code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package com.cadasta.murad.fragments;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.cadasta.murad.R;
import com.cadasta.murad.backend.clients.RestClient;
import com.cadasta.murad.models.project.Extent;
import com.cadasta.murad.models.project.Project;
import com.cadasta.murad.models.project.Projects;
import org.osmdroid.bonuspack.clustering.RadiusMarkerClusterer;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.Polygon;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* A simple {@link BaseFragment} subclass.
*/
public class HomeFragment extends BaseFragment {
public static final String TAG = HomeFragment.class.getSimpleName();
@BindView(R.id.map_view) MapView mapView;
private Context context;
private ItemizedOverlay<OverlayItem> locationOverlay;
private ArrayList<OverlayItem> overlayItems;
private Call<Projects> projectsDownloader;
private RadiusMarkerClusterer radiusMarkerClusterer;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
context = getActivity().getApplicationContext();
initMapView();
return view;
}
private void initMapView() {
Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));
// To change imagery type change this.
mapView.setTileSource(TileSourceFactory.MAPNIK);
// MapView basic.
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
GeoPoint center = new GeoPoint(35.118073, 21.253954);
mapView.getController().setCenter(center);
mapView.getController().setZoom(3);
mapView.setMaxZoomLevel(20);
mapView.setMinZoomLevel(3);
// Clustering stuff
radiusMarkerClusterer = new RadiusMarkerClusterer(getActivity().getApplicationContext());
Drawable clusterIconDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_cluster, null);
Bitmap clusterIcon = ((BitmapDrawable) clusterIconDrawable).getBitmap();
radiusMarkerClusterer.setIcon(clusterIcon);
radiusMarkerClusterer.getTextPaint().setTextSize(12 * getResources().getDisplayMetrics().density);
radiusMarkerClusterer.mAnchorV = Marker.ANCHOR_BOTTOM;
radiusMarkerClusterer.mTextAnchorU = 0.70f;
radiusMarkerClusterer.mTextAnchorV = 0.27f;
radiusMarkerClusterer.setRadius(200);
}
@Override
protected int getLayoutResource() {
return R.layout.fragment_home;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
populateMap();
}
private void populateMap() {
// TODO: For cluster see https://github.com/MKergall/osmbonuspack/wiki/Tutorial_3
projectsDownloader = new RestClient().getProjectService().getProjects();
projectsDownloader.enqueue(new Callback<Projects>() {
@Override
public void onResponse(Call<Projects> call, Response<Projects> response) {
List<Project> projects;
List<Polygon> polygons = new ArrayList<>();
if (response.body() != null) {
if (response.code() == 200) {
projects = response.body().getProjects();
for (int i=0;i<projects.size();i++) {
Project project = projects.get(i);
String projectName = project.getName();
String projectCountry = project.getCountry();
Extent projectExtent = project.getExtent();
List<List<List<Double>>> projectCoordinates;
if (projectExtent != null) {
projectCoordinates = projectExtent.getCoordinates();
} else {
continue;
}
List<GeoPoint> geoPoints = new ArrayList<>();
Polygon polygon = new Polygon();
Marker marker = new Marker(mapView);
for (int j=0;j<projectCoordinates.get(0).size();j++) {
Double lon = projectCoordinates.get(0).get(j).get(1);
Double lat = projectCoordinates.get(0).get(j).get(0);
GeoPoint markerPosition = new GeoPoint(lon, lat);
if (j==0) {
marker.setPosition(markerPosition);
}
GeoPoint geoPoint = new GeoPoint(lon, lat);
geoPoints.add(geoPoint);
}
polygon.setPoints(geoPoints);
polygon.setStrokeColor(Color.TRANSPARENT);
polygon.setFillColor(Color.argb(50, 0, 0, 200));
polygon.setStrokeWidth(3f);
marker.setAnchor(Marker.ANCHOR_TOP, Marker.ANCHOR_BOTTOM);
marker.setIcon(getResources().getDrawable(R.drawable.location_marker_icon));
marker.setTitle(projectName);
marker.setSubDescription(projectCountry);
polygons.add(polygon);
radiusMarkerClusterer.add(marker);
}
} else {
//Show the not-received error.
}
}
mapView.getOverlays().addAll(polygons);
mapView.getOverlays().add(radiusMarkerClusterer);
mapView.invalidate();
}
@Override
public void onFailure(Call<Projects> call, Throwable t) {
}
});
// unComment this to bound the map.
// BoundingBox boundingBox = new BoundingBox(90.000, 180, -90.000, -180);
// mapView.setScrollableAreaLimitDouble(boundingBox);
// locationOverlay = new ItemizedIconOverlay<>(context, overlayItems,
// new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
// @Override
// public boolean onItemSingleTapUp(int index, OverlayItem item) {
// // TODO: Add action for single click.
// return false;
// }
//
// @Override
// public boolean onItemLongPress(int index, OverlayItem item) {
// // TODO: Add action for long press.
// return false;
// }
// });
//
// mapView.getOverlays().add(locationOverlay);
//for bounded areas see https://stackoverflow.com/questions/20656199/osmdroid-add-an-area-to-the-map
// also see this for polygon https://stackoverflow.com/questions/34907526/draw-grid-over-polygon-in-osmdroid-bonus-pack
}
@Override
public void onDestroyView() {
super.onDestroyView();
projectsDownloader.cancel();
}
}
| m-murad/cadasta-android-client | app/src/main/java/com/cadasta/murad/fragments/HomeFragment.java | Java | apache-2.0 | 8,167 |
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dfp.axis.v201411.reportservice;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.dfp.axis.factory.DfpServices;
import com.google.api.ads.dfp.axis.utils.v201411.DateTimes;
import com.google.api.ads.dfp.axis.utils.v201411.ReportDownloader;
import com.google.api.ads.dfp.axis.utils.v201411.StatementBuilder;
import com.google.api.ads.dfp.axis.v201411.Column;
import com.google.api.ads.dfp.axis.v201411.DateRangeType;
import com.google.api.ads.dfp.axis.v201411.Dimension;
import com.google.api.ads.dfp.axis.v201411.DimensionAttribute;
import com.google.api.ads.dfp.axis.v201411.ExportFormat;
import com.google.api.ads.dfp.axis.v201411.ReportJob;
import com.google.api.ads.dfp.axis.v201411.ReportQuery;
import com.google.api.ads.dfp.axis.v201411.ReportServiceInterface;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.api.client.auth.oauth2.Credential;
import java.io.File;
/**
* This example runs a typical delivery report for a single order.
*
* Credentials and properties in {@code fromFile()} are pulled from the
* "ads.properties" file. See README for more info.
*
* Tags: ReportService.runReportJob
*
* @author Adam Rogal
* @author Paul Rashidi
*/
public class RunDeliveryReportForOrder {
// Set the ID of the order to run the report for.
private static final String ORDER_ID = "INSERT_ORDER_ID_HERE";
public static void runExample(DfpServices dfpServices, DfpSession session, long orderId)
throws Exception {
// Get the ReportService.
ReportServiceInterface reportService = dfpServices.get(session, ReportServiceInterface.class);
// Create report query.
ReportQuery reportQuery = new ReportQuery();
reportQuery.setDimensions(new Dimension[] {Dimension.DATE, Dimension.ORDER_ID});
reportQuery.setColumns(new Column[] {Column.AD_SERVER_IMPRESSIONS,
Column.AD_SERVER_CLICKS, Column.AD_SERVER_CTR,
Column.AD_SERVER_CPM_AND_CPC_REVENUE});
reportQuery.setDimensionAttributes(new DimensionAttribute[] {
DimensionAttribute.ORDER_TRAFFICKER, DimensionAttribute.ORDER_START_DATE_TIME,
DimensionAttribute.ORDER_END_DATE_TIME});
// Create statement to filter for an order.
StatementBuilder statementBuilder = new StatementBuilder()
.where("ORDER_ID = :orderId")
.withBindVariableValue("orderId", orderId);
// Set the filter statement.
reportQuery.setStatement(statementBuilder.toStatement());
// Set the start and end dates or choose a dynamic date range type.
reportQuery.setDateRangeType(DateRangeType.CUSTOM_DATE);
reportQuery.setStartDate(
DateTimes.toDateTime("2013-05-01T00:00:00", "America/New_York").getDate());
reportQuery.setEndDate(
DateTimes.toDateTime("2013-05-31T00:00:00", "America/New_York").getDate());
// Create report job.
ReportJob reportJob = new ReportJob();
reportJob.setReportQuery(reportQuery);
// Run report job.
reportJob = reportService.runReportJob(reportJob);
// Create report downloader.
ReportDownloader reportDownloader = new ReportDownloader(reportService, reportJob.getId());
// Wait for the report to be ready.
reportDownloader.waitForReportReady();
// Change to your file location.
String filePath = File.createTempFile("delivery-report-", ".csv.gz").toString();
System.out.printf("Downloading report to %s ...", filePath);
// Download the report.
reportDownloader.downloadReport(ExportFormat.CSV_DUMP, filePath);
System.out.println("done.");
}
public static void main(String[] args) throws Exception {
// Generate a refreshable OAuth2 credential similar to a ClientLogin token
// and can be used in place of a service account.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.DFP)
.fromFile()
.build()
.generateCredential();
// Construct a DfpSession.
DfpSession session = new DfpSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
DfpServices dfpServices = new DfpServices();
runExample(dfpServices, session, Long.parseLong(ORDER_ID));
}
}
| nafae/developer | examples/dfp_axis/src/main/java/dfp/axis/v201411/reportservice/RunDeliveryReportForOrder.java | Java | apache-2.0 | 4,886 |
// expect-runtime-error Fatal injection error: the type int was provided more than once, with different bindings.
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fruit/fruit.h>
#include "test_macros.h"
using fruit::Component;
using fruit::Injector;
using fruit::createComponent;
Component<int> getComponentForInstance(int& p) {
Component<> m = createComponent()
.bindInstance(p);
return createComponent()
.registerConstructor<int()>()
.install(m);
}
int main() {
int p = 5;
Injector<int> injector(getComponentForInstance(p));
if (injector.get<int*>() != &p)
abort();
return 0;
}
| d/fruit | tests/register_instance_error3.cpp | C++ | apache-2.0 | 1,191 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: frontEndGRPC.proto
package com.intel.analytics.zoo.serving.grpc.service.generated;
public interface MetricsReplyOrBuilder extends
// @@protoc_insertion_point(interface_extends:grpc.MetricsReply)
com.google.protobuf.MessageOrBuilder {
/**
* <code>repeated .grpc.MetricsReply.Metric metrics = 1;</code>
*/
java.util.List<MetricsReply.Metric>
getMetricsList();
/**
* <code>repeated .grpc.MetricsReply.Metric metrics = 1;</code>
*/
MetricsReply.Metric getMetrics(int index);
/**
* <code>repeated .grpc.MetricsReply.Metric metrics = 1;</code>
*/
int getMetricsCount();
/**
* <code>repeated .grpc.MetricsReply.Metric metrics = 1;</code>
*/
java.util.List<? extends MetricsReply.MetricOrBuilder>
getMetricsOrBuilderList();
/**
* <code>repeated .grpc.MetricsReply.Metric metrics = 1;</code>
*/
MetricsReply.MetricOrBuilder getMetricsOrBuilder(
int index);
}
| intel-analytics/analytics-zoo | zoo/src/main/java/com/intel/analytics/zoo/serving/grpc/service/generated/MetricsReplyOrBuilder.java | Java | apache-2.0 | 1,004 |
<?php
/**
* Unit Test File
*
* @license Artistic License 2.0
*
* This file is part of Round Eights.
*
* Round Eights is free software: you can redistribute it and/or modify
* it under the terms of the Artistic License as published by
* the Open Source Initiative, either version 2.0 of the License, or
* (at your option) any later version.
*
* Round Eights 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
* Artistic License for more details.
*
* You should have received a copy of the Artistic License
* along with Round Eights. If not, see <http://www.RoundEights.com/license.php>
* or <http://www.opensource.org/licenses/artistic-license-2.0.php>.
*
* @author James Frasca <James@RoundEights.com>
* @copyright Copyright 2009, James Frasca, All Rights Reserved
* @package UnitTests
*/
require_once rtrim( __DIR__, "/" ) ."/../general.php";
/**
* unit tests
*/
class classes_xmlbuilder extends PHPUnit_Framework_TestCase
{
public function testImportNode_import ()
{
$doc = new DOMDocument;
$node = new DOMElement("tag");
$newNode = \r8\XMLBuilder::importNode( $doc, $node );
$this->assertNotSame( $newNode, $node );
$this->assertSame( $doc, $newNode->ownerDocument );
$this->assertSame( "tag", $newNode->tagName );
}
public function testImportNode_unchanged ()
{
$doc = new DOMDocument;
$node = $doc->createElement("tag");
$newNode = \r8\XMLBuilder::importNode( $doc, $node );
$this->assertSame( $newNode, $node );
}
public function testBuildNode_standard ()
{
$doc = new \DOMDocument;
$node = $doc->createElement("tag");
$builder = $this->getMock("r8\iface\XMLBuilder", array("buildNode"));
$builder->expects( $this->once() )
->method("buildNode")
->with( $this->isInstanceOf("DOMDocument") )
->will( $this->returnValue($node) );
$built = \r8\XMLBuilder::buildNode( $builder, $doc );
$this->assertSame( $node, $built );
}
public function testBuildNode_import ()
{
$doc = new \DOMDocument;
$node = new \DOMElement("tag");
$builder = $this->getMock("r8\iface\XMLBuilder", array("buildNode"));
$builder->expects( $this->once() )
->method("buildNode")
->with( $this->isInstanceOf("DOMDocument") )
->will( $this->returnValue($node) );
$built = \r8\XMLBuilder::buildNode( $builder, $doc );
$this->assertNotSame( $node, $built );
$this->assertThat( $built, $this->isInstanceOf("DOMElement") );
$this->assertSame( "tag", $node->tagName );
}
public function testBuildNode_error ()
{
$doc = new \DOMDocument;
$builder = $this->getMock("r8\iface\XMLBuilder", array("buildNode"));
$builder->expects( $this->once() )
->method("buildNode")
->with( $this->isInstanceOf("DOMDocument") )
->will( $this->returnValue("invalid result") );
try {
\r8\XMLBuilder::buildNode( $builder, $doc );
$this->fail("An expected exception was not thrown");
}
catch ( \r8\Exception\Interaction $err ) {
$this->assertSame(
"XMLBuilder did not return a DOMNode object",
$err->getMessage()
);
}
}
public function testBuildDoc ()
{
$doc = new \DOMDocument;
$node = $doc->createElement("tag");
$subBuilder = $this->getMock("r8\iface\XMLBuilder", array("buildNode"));
$subBuilder->expects( $this->once() )
->method("buildNode")
->with( $this->isInstanceOf("DOMDocument") )
->will( $this->returnValue($node) );
$builder = new \r8\XMLBuilder($doc, $subBuilder);
$this->assertSame( $doc, $builder->buildDoc() );
$this->assertSame( $node, $doc->firstChild );
$this->assertSame( $doc->firstChild, $doc->lastChild );
}
}
| Nycto/Round-Eights | tests/classes/XMLBuilder.php | PHP | artistic-2.0 | 4,183 |
// IDuckProxy.cs
//
// Copyright (C) 2007 David Meyer
// All Rights Reserved
//
// Website: http://www.deftflux.net/
// E-mail: deftflux@deftflux.net
//
// This source is licensed to the public via Artistic License 2.0 which should be found in a file
// named license.txt included with the package. It is also available online at:
// http://www.perlfoundation.org/artistic_license_2_0
using System;
using System.Collections.Generic;
using System.Text;
namespace DeftTech.DuckTyping
{
/// <summary>
/// All duck proxy types implement this interface. This interface should normally not be used by code
/// outside the duck typing library.
/// </summary>
public interface IDuckProxy
{
/// <summary>
/// Returns the duck object that the proxy is forwarding calls to.
/// </summary>
/// <returns>The duck object that the proxy is forwarding calls to.</returns>
object UnwrapDuck();
}
}
| deftflux/DuckTyping | DeftTech.DuckTyping/IDuckProxy.cs | C# | artistic-2.0 | 986 |
// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include "CLDefaultStyles.h"
#define USE_LAYOUT 1
#define USE_RENDER 1
// render includes
#include <sbml/packages/render/sbml/GlobalRenderInformation.h>
// xml includes
//
#include <sbml/xml/XMLInputStream.h>
#include <sbml/xml/XMLNode.h>
/**
* A pointer to the list of default styles.
*/
CDataVector<CLGlobalRenderInformation>* DEFAULT_STYLES = NULL;
const char* DEFAULT_STYLES_STRING = \
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<listOfGlobalRenderInformation xmlns=\"http://projects.eml.org/bcb/sbml/render/version1_0_0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"
"<renderInformation id='simple_default' name='Copasi simple style' backgroundColor='#FFFFFFFF'>\n"
" <listOfColorDefinitions>\n"
" <colorDefinition id='black' value='#000000' />\n"
" <colorDefinition id='white' value='#ffffff' />\n"
" <colorDefinition id='transparent' value='#ffffff00' />\n"
" <colorDefinition id='EmptySetOutline' value='#808080' />\n"
" <colorDefinition id='EmptySetGradientStart' value='#ffffff' />\n"
" <colorDefinition id='EmptySetGradientEnd' value='#d3d3d3' />\n"
" <colorDefinition id='CompartmentBorder' value='#e69600b0' />\n"
" <colorDefinition id='CloneMarkerColor' value='#ffa500' />\n"
" <colorDefinition id='CurveColor' value='#000000a0' />\n"
" <colorDefinition id='ModulationCurveColor' value='#0000a0a0' />\n"
" </listOfColorDefinitions>\n"
" <listOfGradientDefinitions>\n"
" <linearGradient x1='50%' y1='0%' z1='0%' x2='50%' y2='100%' z2='100%' id='cloneMarker' spreadMethod='pad'>\n"
" <stop offset='0.0' stop-color='transparent' />\n"
" <stop offset='0.75' stop-color='transparent' />\n"
" <stop offset='0.76' stop-color='CloneMarkerColor' />\n"
" <stop offset='1.0' stop-color='CloneMarkerColor' />\n"
" </linearGradient>\n"
" <linearGradient x1='0%' y1='0%' z1='0%' x2='100%' y2='100%' z2='100%' id='EmptySetGradient' spreadMethod='pad'>\n"
" <stop offset='0%' stop-color='EmptySetGradientStart' />\n"
" <stop offset='100%' stop-color='EmptySetGradientEnd' />\n"
" </linearGradient>\n"
" </listOfGradientDefinitions>\n"
" <listOfLineEndings>\n"
" <lineEnding id='ActivationHead' enableRotationalMapping='true'>\n"
" <boundingBox>\n"
" <position x='-12' y='-6' />\n"
" <dimensions width='12' height='12' />\n"
" </boundingBox>\n"
" <g stroke='CurveColor' stroke-width='1' fill='white'>\n"
" <ellipse stroke='black' stroke-width='1.0' cx='50%' cy='50%' cz='0.0' rx='50%' ry='50%' />\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id='TransitionHead' enableRotationalMapping='true'>\n"
" <boundingBox>\n"
" <position x='-8' y='-6' />\n"
" <dimensions width='12' height='12' />\n"
" </boundingBox>\n"
" <g stroke='CurveColor' stroke-width='0.001' fill='CurveColor'>\n"
" <polygon fill='CurveColor'>\n"
" <listOfCurveSegments>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='0%' y='0%' />\n"
" <end x='100%' y='50%' />\n"
" </curveSegment>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='100%' y='50%' />\n"
" <end x='0%' y='100%' />\n"
" </curveSegment>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='0%' y='100%' />\n"
" <end x='33%' y='50%' />\n"
" </curveSegment>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='33%' y='50%' />\n"
" <end x='0%' y='0%' />\n"
" </curveSegment>\n"
" </listOfCurveSegments>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id='ModulationHead' enableRotationalMapping='true'>\n"
" <boundingBox>\n"
" <position x='-5' y='-5' />\n"
" <dimensions width='10' height='10' />\n"
" </boundingBox>\n"
" <g stroke='ModulationCurveColor' stroke-width='1' fill='ModulationCurveColor'>\n"
" <ellipse cx='50%' cy='50%' rx='45%'/>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id='InhibitionHead' enableRotationalMapping='true'>\n"
" <boundingBox>\n"
" <position x='-0.5' y='-4' />\n"
" <dimensions width='0.6' height='8' />\n"
" </boundingBox>\n"
" <g stroke='black' stroke-width='2' fill='black'>\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type='RenderPoint' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' x='0.0' y='0.0'/>\n"
" <element xsi:type='RenderPoint' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' x='0.3' y='0.0'/>\n"
" <element xsi:type='RenderPoint' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' x='0.3' y='8.0'/>\n"
" <element xsi:type='RenderPoint' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' x='0.0' y='8.0'/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
"</listOfLineEndings>\n"
" <listOfStyles>\n"
" <style roleList='invisible'>\n"
" <g stroke='#ffffff00' fill='#ffffff00'></g>\n"
" </style>\n"
" <style roleList='defaultText' typeList='TEXTGLYPH'>\n"
" <g stroke='black' stroke-width='1' font-family='Verdana' font-size='12' font-weight='normal' font-style='normal' vtext-anchor='middle' text-anchor='middle'></g>\n"
" </style>\n"
" <style roleList='substrate sidesubstrate' typeList='REACTIONGLYPH'>\n"
" <g stroke='CurveColor' stroke-width='3.0' />\n"
" </style>\n"
" <style roleList='inhibitor inhibition SBO-0000169'>\n"
" <g stroke='CurveColor' stroke-width='3.0' endHead='InhibitionHead' />\n"
" </style>\n"
" <style roleList='modifier SBO-0000168'>\n"
" <g stroke='ModulationCurveColor' stroke-width='3.0' fill='white' endHead='ModulationHead' />\n"
" </style>\n"
" <style roleList='catalysis activator SBO-0000172'>\n"
" <g stroke='CurveColor' stroke-width='3.0' fill='white' endHead='ActivationHead' />\n"
" </style>\n"
" <style roleList='product sideproduct' typeList='product sideproduct'>\n"
" <g stroke='CurveColor' stroke-width='3.0' endHead='TransitionHead' />\n"
" </style>\n"
" \n"
" <style roleList='SBO-0000285 NO-SBO' typeList='SPECIESGLYPH'>\n"
" <!-- Unspecified Entity -->\n"
" <g fill='#a0e0a030'>\n"
" <rectangle x='0' y='0' width='100%' height='100%' />\n"
" </g>\n"
" </style>\n"
" <style roleList='SBO-0000289' typeList='COMPARTMENTGLYPH'>\n"
" <!-- Compartment -->\n"
" <g stroke='CompartmentBorder' stroke-width='7' >\n"
" <rectangle x='0' y='0' width='100%' height='100%' rx='20' ry='20' />\n"
" </g>\n"
" </style>\n"
" <style roleList='' typeList='ANY'>\n"
" <!-- Unspecified Entity -->\n"
" <g stroke='black' fill='#f0707070'>\n"
" <rectangle x='0' y='0' width='100%' height='100%' />\n"
" </g>\n"
" </style>\n"
" </listOfStyles>\n"
"</renderInformation>\n"
"<renderInformation id='SBGN_default' name='SBGN Default style' backgroundColor='#FFFFFFFF'>\n"
" <listOfColorDefinitions>\n"
" <colorDefinition id='black' value='#000000' />\n"
" <colorDefinition id='white' value='#ffffff' />\n"
" <colorDefinition id='transparent' value='#ffffff00' />\n"
" <colorDefinition id='EmptySetOutline' value='#808080' />\n"
" <colorDefinition id='EmptySetGradientStart' value='#ffffff' />\n"
" <colorDefinition id='EmptySetGradientEnd' value='#d3d3d3' />\n"
" <colorDefinition id='CompartmentBorder' value='#666666' />\n"
" <colorDefinition id='CompartmentGradientStart' value='#CCCCCC' />\n"
" <colorDefinition id='CompartmentGradientEnd' value='#CCCCFF' />\n"
" <colorDefinition id='CloneMarkerColor' value='#ffa500' />\n"
" <colorDefinition id='EPNGradientStart' value='#ffffff' />\n"
" <colorDefinition id='EPNGradientEnd' value='#c0c0c0' />\n"
" </listOfColorDefinitions>\n"
" <listOfGradientDefinitions>\n"
" <linearGradient x1='0%' y1='0%' z1='0%' x2='100%' y2='100%' z2='100%' id='EPNBackgroundGradient' spreadMethod='pad'>\n"
" <stop offset='0%' stop-color='EPNGradientStart' />\n"
" <stop offset='100%' stop-color='EPNGradientEnd' />\n"
" </linearGradient>\n"
" <linearGradient x1='50%' y1='0%' z1='0%' x2='50%' y2='100%' z2='100%' id='cloneMarker' spreadMethod='pad'>\n"
" <stop offset='0.0' stop-color='transparent' />\n"
" <stop offset='0.75' stop-color='transparent' />\n"
" <stop offset='0.76' stop-color='CloneMarkerColor' />\n"
" <stop offset='1.0' stop-color='CloneMarkerColor' />\n"
" </linearGradient>\n"
" <linearGradient x1='0%' y1='0%' z1='0%' x2='100%' y2='100%' z2='100%' id='EmptySetGradient' spreadMethod='pad'>\n"
" <stop offset='0%' stop-color='EmptySetGradientStart' />\n"
" <stop offset='100%' stop-color='EmptySetGradientEnd' />\n"
" </linearGradient>\n"
" <linearGradient x1='0%' y1='0%' z1='0%' x2='100%' y2='100%' z2='100%' id='CompartmentGradient' spreadMethod='pad'>\n"
" <!--<stop offset='0%' stop-color='#ffdead' />\n"
" <stop offset='100%' stop-color='#ffebcd' />-->\n"
" <stop offset='0%' stop-color='CompartmentGradientStart' />\n"
" <stop offset='100%' stop-color='CompartmentGradientEnd' />\n"
" </linearGradient>\n"
" </listOfGradientDefinitions>\n"
" <listOfLineEndings>\n"
" <lineEnding id='ActivationHead' enableRotationalMapping='true'>\n"
" <boundingBox>\n"
" <position x='-12' y='-6' />\n"
" <dimensions width='12' height='12' />\n"
" </boundingBox>\n"
" <g stroke='black' stroke-width='1' fill='white'>\n"
" <ellipse stroke='black' stroke-width='1.0' cx='50%' cy='50%' cz='0.0' rx='50%' ry='50%' />\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id='TransitionHead' enableRotationalMapping='true'>\n"
" <boundingBox>\n"
" <position x='-12' y='-6' />\n"
" <dimensions width='12' height='12' />\n"
" </boundingBox>\n"
" <g stroke='black' stroke-width='0.001' fill='black'>\n"
" <polygon fill='black'>\n"
" <listOfCurveSegments>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='0%' y='0%' />\n"
" <end x='100%' y='50%' />\n"
" </curveSegment>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='100%' y='50%' />\n"
" <end x='0%' y='100%' />\n"
" </curveSegment>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='0%' y='100%' />\n"
" <end x='33%' y='50%' />\n"
" </curveSegment>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='33%' y='50%' />\n"
" <end x='0%' y='0%' />\n"
" </curveSegment>\n"
" </listOfCurveSegments>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id='ModulationHead' enableRotationalMapping='true'>\n"
" <boundingBox>\n"
" <position x='0' y='-5' />\n"
" <dimensions width='10' height='10' />\n"
" </boundingBox>\n"
" <g stroke='black' stroke-width='1' fill='white'>\n"
" <polygon>\n"
" <listOfCurveSegments>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='0' y='5' />\n"
" <end x='5' y='10' />\n"
" </curveSegment>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='5' y='10' />\n"
" <end x='10' y='5' />\n"
" </curveSegment>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='10' y='5' />\n"
" <end x='5' y='0' />\n"
" </curveSegment>\n"
" <curveSegment xsi:type='LineSegment' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
" <start x='5' y='0' />\n"
" <end x='0' y='5' />\n"
" </curveSegment>\n"
" </listOfCurveSegments>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id='InhibitionHead' enableRotationalMapping='true'>\n"
" <boundingBox>\n"
" <position x='-0.5' y='-4' />\n"
" <dimensions width='0.6' height='8' />\n"
" </boundingBox>\n"
" <g stroke='black' stroke-width='2' fill='black'>\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type='RenderPoint' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' x='0.0' y='0.0'/>\n"
" <element xsi:type='RenderPoint' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' x='0.3' y='0.0'/>\n"
" <element xsi:type='RenderPoint' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' x='0.3' y='8.0'/>\n"
" <element xsi:type='RenderPoint' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' x='0.0' y='8.0'/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
"</listOfLineEndings>\n"
" <listOfStyles>\n"
" <style roleList='invisible'>\n"
" <g stroke='#ffffff00' fill='#ffffff00'></g>\n"
" </style>\n"
" <style roleList='defaultText' typeList='TEXTGLYPH'>\n"
" <g stroke='black' stroke-width='1' font-family='Verdana' font-size='10' font-weight='normal' font-style='normal' text-anchor='middle' vtext-anchor='middle'></g>\n"
" </style>\n"
" <style roleList='substrate sidesubstrate' typeList='REACTIONGLYPH'>\n"
" <g stroke='black' stroke-width='2.0' />\n"
" </style>\n"
" <style roleList='inhibitor inhibition SBO-0000169'>\n"
" <g stroke='black' stroke-width='2.0' endHead='InhibitionHead' />\n"
" </style>\n"
" <style roleList='modifier SBO-0000168'>\n"
" <g stroke='black' stroke-width='2.0' fill='white' endHead='ModulationHead' />\n"
" </style>\n"
" <style roleList='catalysis activator SBO-0000172'>\n"
" <g stroke='black' stroke-width='2.0' fill='white' endHead='ActivationHead' />\n"
" </style>\n"
" <style roleList='product sideproduct' typeList='product sideproduct'>\n"
" <g stroke='black' stroke-width='2.0' endHead='TransitionHead' />\n"
" </style>\n"
" \n"
" <style roleList='SBO-0000285 NO-SBO' typeList='SPECIESGLYPH ANY'>\n"
" <!-- Unspecified Entity -->\n"
" <g stroke='black' stroke-width='2' fill='EPNBackgroundGradient'>\n"
" <ellipse cx='50%' cy='50%' cz='0.0' rx='50%' ry='50%' />\n"
" </g>\n"
" </style>\n"
" <style roleList='SBO-0000289' typeList='COMPARTMENTGLYPH'>\n"
" <!-- Compartment -->\n"
" <g stroke='CompartmentBorder' stroke-width='7' fill='CompartmentGradient'>\n"
" <rectangle x='0' y='0' width='100%' height='100%' rx='10%' ry='10%' />\n"
" </g>\n"
" </style>\n"
" </listOfStyles>\n"
"</renderInformation>\n"
" <renderInformation id=\"default\" name=\"Blue Gradient Species\" backgroundColor=\"#FFFFFFFF\">\n"
" <listOfColorDefinitions>\n"
" <colorDefinition id=\"speciesColor\" value=\"#D2D2E6\"/>\n"
" <colorDefinition id=\"compartmentColor\" value=\"#BCCABA\"/>\n"
" <colorDefinition id=\"white\" value=\"#FFFFFF\"/>\n"
" <colorDefinition id=\"textColor\" value=\"#000000\"/>\n"
" <colorDefinition id=\"speciesReferenceColor\" value=\"#4E4E4E\"/>\n"
" <colorDefinition id=\"frameColor\" value=\"#1A1A1A\"/>\n"
" </listOfColorDefinitions>\n"
" <listOfGradientDefinitions>\n"
" <linearGradient id=\"speciesGlyphGradient\" x1=\"0%\" y1=\"0%\" x2=\"0%\" y2=\"100%\">\n"
" <stop offset=\"0%\" stop-color=\"white\"/>\n"
" <stop offset=\"50%\" stop-color=\"speciesColor\"/>\n"
" <stop offset=\"100%\" stop-color=\"white\"/>\n"
" </linearGradient>\n"
" <linearGradient id=\"compartmentGlyphGradient\" x1=\"0%\" y1=\"0%\" x2=\"0%\" y2=\"100%\">\n"
" <stop offset=\"0%\" stop-color=\"white\"/>\n"
" <stop offset=\"50%\" stop-color=\"compartmentColor\"/>\n"
" <stop offset=\"100%\" stop-color=\"white\"/>\n"
" </linearGradient>\n"
" </listOfGradientDefinitions>\n"
" <listOfLineEndings>\n"
" <lineEnding id=\"ActivationHead\" enableRotationalMapping=\"true\">\n"
" <boundingBox>\n"
" <position x=\"-2.0\" y=\"-2.0\"/>\n"
" <dimensions width=\"5.0\" height=\"4.0\"/>\n"
" </boundingBox>\n"
" <g stroke=\"speciesReferenceColor\" stroke-width=\"2.0\" fill=\"none\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"5.0\" y=\"2.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"4.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"2.0\" y=\"2.0\"/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id=\"TransitionHead\" enableRotationalMapping=\"true\">\n"
" <boundingBox>\n"
" <position x=\"-2.0\" y=\"-2.0\"/>\n"
" <dimensions width=\"5.0\" height=\"4.0\"/>\n"
" </boundingBox>\n"
" <g stroke=\"speciesReferenceColor\" stroke-width=\"1.0\" fill=\"speciesReferenceColor\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"5.0\" y=\"2.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"4.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"2.0\" y=\"2.0\"/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id=\"InhibitionHead\" enableRotationalMapping=\"true\">\n"
" <boundingBox>\n"
" <position x=\"-0.5\" y=\"-3.0\"/>\n"
" <dimensions width=\"1.0\" height=\"6.0\"/>\n"
" </boundingBox>\n"
" <g stroke=\"speciesReferenceColor\" stroke-width=\"1.0\" fill=\"speciesReferenceColor\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"1.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"1.0\" y=\"6.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"6.0\"/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id=\"ModulationHead\" enableRotationalMapping=\"true\">\n"
" <boundingBox>\n"
" <position x=\"0.0\" y=\"-2.0\"/>\n"
" <dimensions width=\"6.0\" height=\"4.0\"/>\n"
" </boundingBox>\n"
" <g stroke=\"speciesReferenceColor\" stroke-width=\"1.0\" fill=\"none\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"2.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"3.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"6.0\" y=\"2.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"3.0\" y=\"4.0\"/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" </listOfLineEndings>\n"
" <listOfStyles>\n"
" <style roleList='invisible'>\n"
" <g stroke='#ffffff00' fill='#ffffff00'></g>\n"
" </style>\n"
" <style id=\"compartmentGlyphStyle\" typeList=\"COMPARTMENTGLYPH\">\n"
" <g stroke=\"frameColor\" stroke-width=\"1.0\">\n"
" <rectangle x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"10%\" ry=\"10%\" fill=\"compartmentGlyphGradient\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"speciesGlyphStyle\" typeList=\"SPECIESGLYPH ANY\">\n"
" <g stroke=\"frameColor\" stroke-width=\"1.0\">\n"
" <rectangle x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"10%\" ry=\"10%\" fill=\"speciesGlyphGradient\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"textGlyphStyle\" typeList=\"TEXTGLYPH\">\n"
" <g stroke=\"textColor\" stroke-width=\"1.0\" font-size=\"16\" text-anchor=\"middle\" vtext-anchor='middle' font-family=\"sans\"/>\n"
" </style>\n"
" <style id=\"productStyle\" roleList=\"product sideproduct\">\n"
" <g stroke=\"speciesReferenceColor\" stroke-width=\"2.0\" endHead=\"TransitionHead\"/>\n"
" </style>\n"
" <style id=\"substrateStyle\" roleList=\"substrate sidesubstrate\" typeList=\"REACTIONGLYPH SPECIESREFERENCEGLYPH\">\n"
" <g stroke=\"speciesReferenceColor\" stroke-width=\"2.0\" endHead=\"none\"/>\n"
" </style>\n"
" <style id=\"activatorStyle\" roleList=\"activator\">\n"
" <g stroke=\"speciesReferenceColor\" stroke-width=\"2.0\" endHead=\"ActivationHead\"/>\n"
" </style>\n"
" <style id=\"inhibitorStyle\" roleList=\"inhibitor\">\n"
" <g stroke=\"speciesReferenceColor\" stroke-width=\"2.0\" endHead=\"InhibitionHead\"/>\n"
" </style>\n"
" <style id=\"modifierStyle\" roleList=\"modifier\">\n"
" <g stroke=\"speciesReferenceColor\" stroke-width=\"2.0\" endHead=\"ModulationHead\"/>\n"
" </style>\n"
" </listOfStyles>\n"
" </renderInformation>\n"
" <renderInformation id=\"lightBlue\" name=\"blue Species; colored modifiers\" backgroundColor=\"#FFFFFFFF\">\n"
" <listOfColorDefinitions>\n"
" <colorDefinition id=\"lightBlue\" value=\"#ADD8E6\"/>\n"
" <colorDefinition id=\"white\" value=\"#FFFFFF\"/>\n"
" <colorDefinition id=\"black\" value=\"#000000\"/>\n"
" <colorDefinition id=\"red\" value=\"#FF0000\"/>\n"
" <colorDefinition id=\"green\" value=\"#00FF00\"/>\n"
" <colorDefinition id=\"blue\" value=\"#0000FF\"/>\n"
" <colorDefinition id=\"lightYellow\" value=\"#FFFFD1\"/>\n"
" <colorDefinition id=\"darkGreen\" value=\"#002000\"/>\n"
" </listOfColorDefinitions>\n"
" <listOfGradientDefinitions>\n"
" <radialGradient id=\"speciesGlyphGradient\">\n"
" <stop offset=\"0%\" stop-color=\"white\"/>\n"
" <stop offset=\"100%\" stop-color=\"lightBlue\"/>\n"
" </radialGradient>\n"
" </listOfGradientDefinitions>\n"
" <listOfLineEndings>\n"
" <lineEnding id=\"simpleHead_black\">\n"
" <boundingBox>\n"
" <position x=\"-8\" y=\"-3\"/>\n"
" <dimensions width=\"10\" height=\"6\"/>\n"
" </boundingBox>\n"
" <g stroke=\"black\" stroke-width=\"1.0\" fill=\"black\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"10.0\" y=\"3.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"6.0\" />\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id=\"simpleHead_red\">\n"
" <boundingBox>\n"
" <position x=\"-8\" y=\"-3\"/>\n"
" <dimensions width=\"10\" height=\"6\"/>\n"
" </boundingBox>\n"
" <g stroke=\"red\" stroke-width=\"1.0\" fill=\"red\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"10.0\" y=\"3.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"6.0\" />\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id=\"simpleHead_green\">\n"
" <boundingBox>\n"
" <position x=\"-8\" y=\"-3\"/>\n"
" <dimensions width=\"10\" height=\"6\"/>\n"
" </boundingBox>\n"
" <g stroke=\"green\" stroke-width=\"1.0\" fill=\"green\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"10.0\" y=\"3.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"6.0\" />\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id=\"simpleHead_blue\">\n"
" <boundingBox>\n"
" <position x=\"-8\" y=\"-3\"/>\n"
" <dimensions width=\"10\" height=\"6\"/>\n"
" </boundingBox>\n"
" <g stroke=\"blue\" stroke-width=\"1.0\" fill=\"blue\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"10.0\" y=\"3.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"6.0\" />\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" </listOfLineEndings>\n"
" <listOfStyles>\n"
" <style roleList='invisible'>\n"
" <g stroke='#ffffff00' fill='#ffffff00'></g>\n"
" </style>\n"
" <style id=\"compartmentGlyphStyle\" typeList=\"COMPARTMENTGLYPH\">\n"
" <g stroke=\"darkGreen\" stroke-width=\"1.0\">\n"
" <rectangle x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"10%\" ry=\"10%\" fill=\"lightYellow\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"speciesGlyphStyle\" typeList=\"SPECIESGLYPH ANY\">\n"
" <g stroke=\"black\" stroke-width=\"1.0\">\n"
" <rectangle x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"5\" ry=\"50%\" fill=\"speciesGlyphGradient\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"reactionGlyphStyle\" typeList=\"REACTIONGLYPH TEXTGLYPH SPECIESREFERENCEGLYPH\">\n"
" <g stroke=\"black\" stroke-width=\"1.0\" font-size=\"12\" text-anchor=\"middle\" vtext-anchor='middle' font-family=\"sans\"/>\n"
" </style>\n"
" <style id=\"reactantSpeciesReferenceGlyphStyle\" roleList=\"substrate sidesubstrate product sideproduct\">\n"
" <g stroke=\"black\" stroke-width=\"1.0\" endHead=\"simpleHead_black\"/>\n"
" </style>\n"
" <style id=\"activatorSpeciesReferenceGlyphStyle\" roleList=\"activator\">\n"
" <g stroke=\"green\" stroke-width=\"1.0\" endHead=\"simpleHead_green\"/>\n"
" </style>\n"
" <style id=\"modifierSpeciesReferenceGlyphStyle\" roleList=\"modifier\">\n"
" <g stroke=\"blue\" stroke-width=\"1.0\" endHead=\"simpleHead_blue\"/>\n"
" </style>\n"
" <style id=\"inhibitorSpeciesReferenceGlyphStyle\" roleList=\"inhibitor\">\n"
" <g stroke=\"red\" stroke-width=\"1.0\" endHead=\"simpleHead_red\"/>\n"
" </style>\n"
" </listOfStyles>\n"
" </renderInformation>\n"
" <renderInformation id=\"gray_green\" name=\"Gray-Green Style\" backgroundColor=\"#FFFFFFFF\">\n"
" <listOfColorDefinitions>\n"
" <colorDefinition id=\"SpeciesColorLight\" value=\"#D2D2E6FF\"/>\n"
" <colorDefinition id=\"CompartmentColorLight\" value=\"#E1F2DFFF\"/>\n"
" <colorDefinition id=\"SpeciesColorDark\" value=\"#A8A8B8FF\"/>\n"
" <colorDefinition id=\"CompartmentColorDark\" value=\"#B2BfB0FF\"/>\n"
" <colorDefinition id=\"ShadowColor\" value=\"#33333399\"/>\n"
" <colorDefinition id=\"SpeciesReferenceColor\" value=\"#4C4C4CFF\"/>\n"
" <colorDefinition id=\"FrameColor\" value=\"#191919FF\"/>\n"
" <colorDefinition id=\"TextColor\" value=\"#000000FF\"/>\n"
" </listOfColorDefinitions>\n"
" <listOfGradientDefinitions>\n"
" <linearGradient id=\"SpeciesGlyphGradient\" x1=\"50%\" y1=\"0%\" x2=\"50%\" y2=\"100%\">\n"
" <stop offset=\"0%\" stop-color=\"SpeciesColorLight\"/>\n"
" <stop offset=\"50%\" stop-color=\"SpeciesColorDark\"/>\n"
" <stop offset=\"100%\" stop-color=\"SpeciesColorLight\"/>\n"
" </linearGradient>\n"
" <linearGradient id=\"CompartmentGlyphGradient\" x1=\"50%\" y1=\"0%\" x2=\"50%\" y2=\"100%\">\n"
" <stop offset=\"0%\" stop-color=\"CompartmentColorLight\"/>\n"
" <stop offset=\"50%\" stop-color=\"CompartmentColorDark\"/>\n"
" <stop offset=\"100%\" stop-color=\"CompartmentColorLight\"/>\n"
" </linearGradient>\n"
" </listOfGradientDefinitions>\n"
" <listOfLineEndings>\n"
" <lineEnding id=\"ActivationHead\" enableRotationalMapping=\"true\">\n"
" <boundingBox>\n"
" <position x=\"-2.0\" y=\"-2.0\"/>\n"
" <dimensions width=\"5.0\" height=\"4.0\"/>\n"
" </boundingBox>\n"
" <g stroke=\"SpeciesReferenceColor\" stroke-width=\"2.0\" fill=\"none\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"5.0\" y=\"2.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"4.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"2.0\" y=\"2.0\"/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id=\"TransitionHead\" enableRotationalMapping=\"true\">\n"
" <boundingBox>\n"
" <position x=\"-2.0\" y=\"-2.0\"/>\n"
" <dimensions width=\"5.0\" height=\"4.0\"/>\n"
" </boundingBox>\n"
" <g stroke=\"SpeciesReferenceColor\" stroke-width=\"1.0\" fill=\"SpeciesReferenceColor\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"5.0\" y=\"2.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"4.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"2.0\" y=\"2.0\"/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id=\"InhibitionHead\" enableRotationalMapping=\"true\">\n"
" <boundingBox>\n"
" <position x=\"-0.5\" y=\"-3.0\"/>\n"
" <dimensions width=\"1.0\" height=\"6.0\"/>\n"
" </boundingBox>\n"
" <g stroke=\"SpeciesReferenceColor\" stroke-width=\"1.0\" fill=\"SpeciesReferenceColor\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"1.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"1.0\" y=\"6.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"6.0\"/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" <lineEnding id=\"ModulationHead\" enableRotationalMapping=\"true\">\n"
" <boundingBox>\n"
" <position x=\"0.0\" y=\"-2.0\"/>\n"
" <dimensions width=\"6.0\" height=\"4.0\"/>\n"
" </boundingBox>\n"
" <g stroke=\"SpeciesReferenceColor\" stroke-width=\"1.0\" fill=\"none\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"2.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"3.0\" y=\"0.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"6.0\" y=\"2.0\"/>\n"
" <element xsi:type=\"RenderPoint\" x=\"3.0\" y=\"4.0\"/>\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" </listOfLineEndings>\n"
" <listOfStyles>\n"
" <style roleList='invisible'>\n"
" <g stroke='#ffffff00' fill='#ffffff00'></g>\n"
" </style>\n"
" <style id=\"compartmentGlyphStyle\" typeList=\"COMPARTMENTGLYPH\">\n"
" <g>\n"
" <rectangle stroke=\"FrameColor\" stroke-width=\"1.0\" fill=\"CompartmentGlyphGradient\" x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"10\" ry=\"10\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"speciesGlyphStyle\" typeList=\"SPECIESGLYPH ANY\">\n"
" <g>\n"
" <rectangle stroke=\"FrameColor\" stroke-width=\"1.0\" fill=\"SpeciesGlyphGradient\" x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"10\" ry=\"10\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"textGlyphStyle\" typeList=\"TEXTGLYPH\">\n"
" <g stroke=\"TextColor\" font-family=\"sans-serif\" font-size=\"70%\" text-anchor=\"middle\" vtext-anchor=\"middle\"/>\n"
" </style>\n"
" <style id=\"productStyle\" roleList=\"product sideproduct\">\n"
" <g stroke=\"SpeciesReferenceColor\" stroke-width=\"2.0\" endHead=\"TransitionHead\"/>\n"
" </style>\n"
" <style id=\"substrateStyle\" roleList=\"substrate sidesubstrate\" typeList=\"REACTIONGLYPH SPECIESREFERENCEGLYPH\">\n"
" <g stroke=\"SpeciesReferenceColor\" stroke-width=\"2.0\" endHead=\"none\"/>\n"
" </style>\n"
" <style id=\"activatorStyle\" roleList=\"activator\">\n"
" <g stroke=\"SpeciesReferenceColor\" stroke-width=\"2.0\" endHead=\"ActivationHead\"/>\n"
" </style>\n"
" <style id=\"inhibitorStyle\" roleList=\"inhibitor\">\n"
" <g stroke=\"SpeciesReferenceColor\" stroke-width=\"2.0\" endHead=\"InhibitionHead\"/>\n"
" </style>\n"
" <style id=\"modifierStyle\" roleList=\"modifier\">\n"
" <g stroke=\"SpeciesReferenceColor\" stroke-width=\"2.0\" endHead=\"ModulationHead\"/>\n"
" </style>\n"
" </listOfStyles>\n"
" </renderInformation>\n"
" <renderInformation id=\"grayStyle\" name=\"Gray Scale\" backgroundColor=\"#FFFFFFFF\">\n"
" <listOfColorDefinitions>\n"
" <colorDefinition id=\"lightGray\" value=\"#CECECE\"/>\n"
" <colorDefinition id=\"white\" value=\"#FFFFFF\"/>\n"
" <colorDefinition id=\"black\" value=\"#000000\"/>\n"
" <colorDefinition id=\"lightGray2\" value=\"#F0F0F0\"/>\n"
" <colorDefinition id=\"gray\" value=\"#0B0B0B\"/>\n"
" </listOfColorDefinitions>\n"
" <listOfGradientDefinitions>\n"
" <radialGradient id=\"speciesGlyphGradient\">\n"
" <stop offset=\"0%\" stop-color=\"white\"/>\n"
" <stop offset=\"100%\" stop-color=\"lightGray\"/>\n"
" </radialGradient>\n"
" </listOfGradientDefinitions>\n"
" <listOfLineEndings>\n"
" <lineEnding id=\"simpleHead_black\">\n"
" <boundingBox>\n"
" <position x=\"-8\" y=\"-3\"/>\n"
" <dimensions width=\"10\" height=\"6\"/>\n"
" </boundingBox>\n"
" <g stroke=\"black\" stroke-width=\"1.0\" fill=\"black\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"10.0\" y=\"3.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"6.0\" />\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" </listOfLineEndings>\n"
" <listOfStyles>\n"
" <style roleList='invisible'>\n"
" <g stroke='#ffffff00' fill='#ffffff00'></g>\n"
" </style>\n"
" <style id=\"compartmentGlyphStyle\" typeList=\"COMPARTMENTGLYPH\">\n"
" <g stroke=\"gray\" stroke-width=\"1.0\">\n"
" <rectangle x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"5%\" fill=\"lightGray2\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"speciesGlyphStyle\" typeList=\"SPECIESGLYPH ANY\">\n"
" <g stroke=\"black\" stroke-width=\"1.0\">\n"
" <rectangle x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"5%\" fill=\"speciesGlyphGradient\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"reactionGlyphStyle\" typeList=\"REACTIONGLYPH TEXTGLYPH\">\n"
" <g stroke=\"black\" stroke-width=\"1.0\" font-size=\"12\" text-anchor=\"middle\" vtext-anchor='middle' font-family=\"sans\"/>\n"
" </style>\n"
" <style id=\"speciesReferenceGlyphStyle\" typeList=\"SPECIESREFERENCEGLYPH\">\n"
" <g stroke=\"black\" stroke-width=\"1.0\" endHead=\"simpleHead_black\" />\n"
" </style>\n"
" </listOfStyles>\n"
" </renderInformation>\n"
" <renderInformation id=\"invertGrayStyle\" name=\"Dark Gray Scale\" backgroundColor=\"#404040FF\">\n"
" <listOfColorDefinitions>\n"
" <colorDefinition id=\"lightGray\" value=\"#CECECE\"/>\n"
" <colorDefinition id=\"white\" value=\"#FFFFFF\"/>\n"
" <colorDefinition id=\"black\" value=\"#000000\"/>\n"
" <colorDefinition id=\"lightGray2\" value=\"#F0F0F0\"/>\n"
" <colorDefinition id=\"gray\" value=\"#0B0B0B\"/>\n"
" </listOfColorDefinitions>\n"
" <listOfGradientDefinitions>\n"
" <linearGradient id=\"speciesGlyphGradient\">\n"
" <stop offset=\"0%\" stop-color=\"black\"/>\n"
" <stop offset=\"5%\" stop-color=\"lightGray\"/>\n"
" <stop offset=\"50%\" stop-color=\"lightGray2\"/>\n"
" <stop offset=\"95%\" stop-color=\"lightGray\"/>\n"
" <stop offset=\"100%\" stop-color=\"black\"/>\n"
" </linearGradient>\n"
" </listOfGradientDefinitions>\n"
" <listOfLineEndings>\n"
" <lineEnding id=\"simpleHead_white\">\n"
" <boundingBox>\n"
" <position x=\"-8\" y=\"-3\"/>\n"
" <dimensions width=\"10\" height=\"6\"/>\n"
" </boundingBox>\n"
" <g stroke=\"black\" stroke-width=\"1.0\" fill=\"white\">\n"
" <polygon>\n"
" <listOfElements>\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"0.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"10.0\" y=\"3.0\" />\n"
" <element xsi:type=\"RenderPoint\" x=\"0.0\" y=\"6.0\" />\n"
" </listOfElements>\n"
" </polygon>\n"
" </g>\n"
" </lineEnding>\n"
" </listOfLineEndings>\n"
" <listOfStyles>\n"
" <style roleList='invisible'>\n"
" <g stroke='#ffffff00' fill='#ffffff00'></g>\n"
" </style>\n"
" <style id=\"compartmentGlyphStyle\" typeList=\"COMPARTMENTGLYPH\">\n"
" <g stroke=\"white\" stroke-width=\"1.0\">\n"
" <rectangle x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"5%\" fill=\"black\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"speciesGlyphStyle\" typeList=\"SPECIESGLYPH ANY\">\n"
" <g stroke=\"white\" stroke-width=\"1.0\">\n"
" <rectangle x=\"0%\" y=\"0%\" width=\"100%\" height=\"100%\" rx=\"5%\" fill=\"speciesGlyphGradient\"/>\n"
" </g>\n"
" </style>\n"
" <style id=\"reactionGlyphStyle\" typeList=\"REACTIONGLYPH\">\n"
" <g stroke=\"white\" stroke-width=\"1.0\" />\n"
" </style>\n"
" <style id=\"textGlyphStyle\" typeList=\"TEXTGLYPH\">\n"
" <g stroke=\"black\" stroke-width=\"1.0\" font-size=\"12\" text-anchor=\"middle\" vtext-anchor='middle' font-family=\"sans\"/>\n"
" </style>\n"
" <style id=\"speciesReferenceGlyphStyle\" typeList=\"SPECIESREFERENCEGLYPH\">\n"
" <g stroke=\"white\" stroke-width=\"1.0\" endHead=\"simpleHead_white\"/>\n"
" </style>\n"
" </listOfStyles>\n"
" </renderInformation>\n"
"</listOfGlobalRenderInformation>\n"
;
/**
* This method returns a global render information list that contains the default styles
* which are built into the renderer.
*/
CDataVector<CLGlobalRenderInformation>* getDefaultStyles()
{
if (!DEFAULT_STYLES)
{
DEFAULT_STYLES = loadDefaultStyles();
}
return DEFAULT_STYLES;
}
/**
* This method returns the number of global styles.
*/
size_t getNumDefaultStyles()
{
size_t result = 0;
if (!DEFAULT_STYLES)
{
DEFAULT_STYLES = loadDefaultStyles();
}
if (DEFAULT_STYLES != NULL)
{
result = DEFAULT_STYLES->size();
}
return result;
}
/**
* This method returns the default render information object with
* the requested index. If the index isinvalid, NULL is returned.
*/
CLGlobalRenderInformation* getDefaultStyle(size_t index)
{
if (!DEFAULT_STYLES)
{
DEFAULT_STYLES = loadDefaultStyles();
}
CLGlobalRenderInformation* pResult = NULL;
if (DEFAULT_STYLES != NULL && index < DEFAULT_STYLES->size())
{
pResult = static_cast<CLGlobalRenderInformation*>(&DEFAULT_STYLES->operator[](index));
}
return pResult;
}
CDataVector<CLGlobalRenderInformation>* loadDefaultStyles()
{
// try to initialize the default styles
if (DEFAULT_STYLES != NULL)
{
delete DEFAULT_STYLES;
}
XMLInputStream stream(DEFAULT_STYLES_STRING, false);
ListOfGlobalRenderInformation* pRI = new ListOfGlobalRenderInformation();
pRI->parseXML(XMLNode(stream));
// convert the SBML objects to COPASI objects
size_t i, iMax = pRI->size();
CDataVector<CLGlobalRenderInformation>* pResult = new CDataVector<CLGlobalRenderInformation>;
for (i = 0; i < iMax; ++i)
{
pResult->add(new CLGlobalRenderInformation(*static_cast<const GlobalRenderInformation*>(pRI->get((unsigned int) i))), true);
}
delete pRI;
return pResult;
}
| jonasfoe/COPASI | copasi/layout/CLDefaultStyles.cpp | C++ | artistic-2.0 | 68,933 |
package com.sdw.soft.demo.netty.version4;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
/**
* Created by shangyindong on 2018/1/5.
*/
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
System.out.println("Server received:" + in.toString(CharsetUtil.UTF_8));
ctx.write(in);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
| sdw2330976/wekeeper | wekeeper-prototype/src/test/java/com/sdw/soft/demo/netty/version4/EchoServerHandler.java | Java | artistic-2.0 | 1,087 |
/*
* header.hpp
*
* Created on: Aug 18, 2015
* Author: zmij
*/
#ifndef PUSHKIN_HTTP_COMMON_HEADER_HPP_
#define PUSHKIN_HTTP_COMMON_HEADER_HPP_
#include <boost/variant.hpp>
#include <map>
#include <set>
#include <vector>
#include <pushkin/http/common/header_names.hpp>
namespace psst {
namespace http {
using header_name = boost::variant< known_header_name, std::string >;
using header = std::pair<header_name, std::string>;
using headers = std::multimap<header_name, std::string>;
using content_size = ::std::int64_t;
std::ostream&
operator << (std::ostream&, header const&);
std::ostream&
operator << (std::ostream&, headers const&);
content_size
content_length(headers const& hdrs);
bool
chunked_transfer_encoding(headers const& hdrs);
using accept_language = std::pair< std::string, float >;
struct accept_language_qvalue_sort {
bool
operator()(accept_language const& lhs, accept_language const& rhs) const
{
return lhs.second > rhs.second;
}
};
using accept_languages = std::multiset< accept_language, accept_language_qvalue_sort >;
} // namespace http
} // namespace tip
#endif /* PUSHKIN_HTTP_COMMON_HEADER_HPP_ */
| zmij/tip-http | include/pushkin/http/common/header.hpp | C++ | artistic-2.0 | 1,153 |
/**
* 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.
*/
package org.apache.spark.streaming.aliyun.logservice.utils;
import java.io.InputStream;
import java.util.Properties;
public class VersionInfoUtils {
private static final String VERSION_INFO_FILE = "emr-versioninfo.properties";
private static final String USER_AGENT_PREFIX = "aliyun-emapreduce-sdk";
private static String version = null;
private static String defaultUserAgent = null;
public static String getVersion() {
if (version == null) {
initializeVersion();
}
return version;
}
public static String getDefaultUserAgent() {
if (defaultUserAgent == null) {
defaultUserAgent = USER_AGENT_PREFIX + "-" + getVersion()+"/" + System.getProperty("java.version");
}
return defaultUserAgent;
}
private static void initializeVersion() {
InputStream inputStream = VersionInfoUtils.class.getClassLoader().getResourceAsStream(VERSION_INFO_FILE);
Properties versionInfoProperties = new Properties();
try {
if (inputStream == null) {
throw new IllegalArgumentException(VERSION_INFO_FILE + " not found on classpath");
}
versionInfoProperties.load(inputStream);
version = versionInfoProperties.getProperty("version");
} catch (Exception e) {
version = "unknown-version";
}
}
}
| aliyun/aliyun-emapreduce-sdk | emr-logservice/src/main/java/org/apache/spark/streaming/aliyun/logservice/utils/VersionInfoUtils.java | Java | artistic-2.0 | 2,204 |
// Copyright (C) 2019 - 2021 by Pedro Mendes, Rector and Visitors of the
// University of Virginia, University of Heidelberg, and University
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
#include "CQGlobalQuantitiesWidget.h"
#include <QHeaderView>
#include <QClipboard>
#include <QKeyEvent>
#include "copasi/copasi.h"
#include "qtUtilities.h"
#include "CQMessageBox.h"
#include "copasi/model/CModel.h"
#include "copasi/CopasiDataModel/CDataModel.h"
#include "copasi/core/CRootContainer.h"
#include <copasi/commandline/CConfigurationFile.h>
#include "copasiui3window.h"
/*
* Constructs a CQGlobalQuantitiesWidget which is a child of 'parent', with the
* name 'name'.'
*/
CQGlobalQuantitiesWidget::CQGlobalQuantitiesWidget(QWidget *parent, const char *name)
: CopasiWidget(parent, name)
{
setupUi(this);
//Create Source Data Model.
mpGlobalQuantityDM = new CQGlobalQuantityDM(this);
//Create the Proxy Model for sorting/filtering and set its properties.
mpProxyModel = new CQSortFilterProxyModel();
mpProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
mpProxyModel->setFilterKeyColumn(-1);
//Setting values for Types comboBox
mpTypeDelegate = new CQComboDelegate(this, mpGlobalQuantityDM->getTypes());
mpTblGlobalQuantities->setItemDelegateForColumn(COL_TYPE_GQ, mpTypeDelegate);
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
mpTblGlobalQuantities->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
#endif
if (CRootContainer::getConfiguration()->resizeToContents())
{
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
mpTblGlobalQuantities->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
mpTblGlobalQuantities->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
#endif
}
mpTblGlobalQuantities->verticalHeader()->hide();
mpTblGlobalQuantities->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder);
// Connect the table widget
connect(mpGlobalQuantityDM, SIGNAL(signalNotifyChanges(const CUndoData::CChangeSet &)),
this, SLOT(slotNotifyChanges(const CUndoData::CChangeSet &)));
connect(mpGlobalQuantityDM, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(dataChanged(const QModelIndex &, const QModelIndex &)));
connect(this, SIGNAL(initFilter()), this, SLOT(slotFilterChanged()));
connect(mpLEFilter, SIGNAL(textChanged(const QString &)),
this, SLOT(slotFilterChanged()));
connect(mpTblGlobalQuantities, SIGNAL(clicked(const QModelIndex &)), this, SLOT(slotSelectionChanged()));
}
/*
* Destroys the object and frees any allocated resources
*/
CQGlobalQuantitiesWidget::~CQGlobalQuantitiesWidget()
{
pdelete(mpTypeDelegate);
pdelete(mpProxyModel);
pdelete(mpGlobalQuantityDM);
// no need to delete child widgets, Qt does it all for us
}
void CQGlobalQuantitiesWidget::slotBtnNewClicked()
{
mpGlobalQuantityDM->insertRow(mpGlobalQuantityDM->rowCount() - 1, QModelIndex());
updateDeleteBtns();
}
void CQGlobalQuantitiesWidget::slotBtnDeleteClicked()
{
if (mpTblGlobalQuantities->hasFocus())
{deleteSelectedGlobalQuantities();}
updateDeleteBtns();
}
void CQGlobalQuantitiesWidget::deleteSelectedGlobalQuantities()
{
const QItemSelectionModel *pSelectionModel = mpTblGlobalQuantities->selectionModel();
QModelIndexList mappedSelRows;
size_t i, imax = mpGlobalQuantityDM->rowCount();
for (i = 0; i < imax; i++)
{
if (pSelectionModel->isRowSelected((int) i, QModelIndex()))
{
mappedSelRows.append(mpProxyModel->mapToSource(mpProxyModel->index((int) i, 0)));
}
}
if (mappedSelRows.empty())
{return;}
mpGlobalQuantityDM->removeRows(mappedSelRows);
}
void CQGlobalQuantitiesWidget::slotBtnClearClicked()
{
int ret = CQMessageBox::question(this, tr("Confirm Delete"), "Delete all Quantities?",
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (ret == QMessageBox::Yes)
{
mpGlobalQuantityDM->clear();
}
updateDeleteBtns();
}
bool CQGlobalQuantitiesWidget::updateProtected(ListViews::ObjectType objectType, ListViews::Action action, const CCommonName & cn)
{
if (mIgnoreUpdates || !isVisible())
{
return true;
}
if (objectType == ListViews::ObjectType::MODEL ||
objectType == ListViews::ObjectType::STATE ||
objectType == ListViews::ObjectType::MODELVALUE)
{
enterProtected();
}
return true;
}
bool CQGlobalQuantitiesWidget::leaveProtected()
{
return true;
}
CQBaseDataModel * CQGlobalQuantitiesWidget::getCqDataModel()
{
return mpGlobalQuantityDM;
}
bool CQGlobalQuantitiesWidget::enterProtected()
{
QByteArray State = mpTblGlobalQuantities->horizontalHeader()->saveState();
blockSignals(true);
mpGlobalQuantityDM->setDataModel(mpDataModel);
mpProxyModel->setSourceModel(mpGlobalQuantityDM);
//Set Model for the TableView
mpTblGlobalQuantities->setModel(NULL);
mpTblGlobalQuantities->setModel(mpProxyModel);
updateDeleteBtns();
mpTblGlobalQuantities->horizontalHeader()->restoreState(State);
blockSignals(false);
if (CRootContainer::getConfiguration()->resizeToContents())
{
mpTblGlobalQuantities->resizeColumnsToContents();
}
emit initFilter();
return true;
}
void CQGlobalQuantitiesWidget::updateDeleteBtns()
{
bool selected = false;
QModelIndexList selRows = mpTblGlobalQuantities->selectionModel()->selectedRows();
if (selRows.size() == 0)
selected = false;
else
{
if (selRows.size() == 1)
{
if (mpGlobalQuantityDM->isDefaultRow(mpProxyModel->mapToSource(selRows[0])))
selected = false;
else
selected = true;
}
else
selected = true;
}
mpBtnDelete->setEnabled(selected);
if (mpProxyModel->rowCount() - 1)
mpBtnClear->setEnabled(true);
else
mpBtnClear->setEnabled(false);
}
void CQGlobalQuantitiesWidget::slotSelectionChanged()
{
updateDeleteBtns();
}
void CQGlobalQuantitiesWidget::dataChanged(const QModelIndex &C_UNUSED(topLeft),
const QModelIndex &C_UNUSED(bottomRight))
{
if (CRootContainer::getConfiguration()->resizeToContents())
{
mpTblGlobalQuantities->resizeColumnsToContents();
}
updateDeleteBtns();
}
void CQGlobalQuantitiesWidget::slotDoubleClicked(const QModelIndex proxyIndex)
{
QModelIndex index = mpProxyModel->mapToSource(proxyIndex);
if (index.row() < 0)
return;
if (mpGlobalQuantityDM->isDefaultRow(index))
{
slotBtnNewClicked();
}
CDataVector < CModelValue > * pVector = dynamic_cast< CDataVector < CModelValue > * >(mpObject);
if (pVector != NULL &&
index.row() < pVector->size())
{
mpListView->switchToOtherWidget(ListViews::WidgetType::GlobalQuantityDetail, pVector->operator [](index.row()).getCN());
}
}
void CQGlobalQuantitiesWidget::keyPressEvent(QKeyEvent *ev)
{
if (ev->key() == Qt::Key_Delete)
slotBtnDeleteClicked();
else if (ev->key() == Qt::Key_C && (ev->modifiers() & Qt::ControlModifier))
{
QModelIndexList selRows = mpTblGlobalQuantities->selectionModel()->selectedRows(0);
if (selRows.empty())
{return;}
QString str;
QModelIndexList::const_iterator i;
for (i = selRows.begin(); i != selRows.end(); ++i)
{
for (int x = 0; x < mpGlobalQuantityDM->columnCount(); ++x)
{
if (!mpTblGlobalQuantities->isColumnHidden(x))
{
if (!str.isEmpty())
str += "\t";
str += mpGlobalQuantityDM->index(mpProxyModel->mapToSource(*i).row(), x).data().toString();
}
}
str += "\n";
}
QApplication::clipboard()->setText(str);
}
}
void CQGlobalQuantitiesWidget::slotFilterChanged()
{
QString Filter = mpLEFilter->text();
setFilterExpression(mpProxyModel, Filter.isEmpty(), Filter + "|New Quantity");
while (mpProxyModel->canFetchMore(QModelIndex()))
mpProxyModel->fetchMore(QModelIndex());
}
| copasi/COPASI | copasi/UI/CQGlobalQuantitiesWidget.cpp | C++ | artistic-2.0 | 8,662 |
var $ = require('jquery');
var foundation = require('foundation');
var _ = require('lodash');
$(document).foundation();
console.log("Hello Worldz");
| abits/static-boilerplate | src/js/app.js | JavaScript | bsd-2-clause | 176 |
package org.pm4j.common.pageable.querybased.idquery;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utility methods for {@link IdQueryService}.
*
* @author Olaf Boede
*/
public class IdQueryServiceUtil {
/**
* Applies the order of the given id list to the given item list.
*
* @param items The unsorted item list.
* @param ids An ID list that defines the sort order.
* @return The sorted item list.<br>
* The list size is the same as of parameter <code>items</code>.
*/
public static <T_ITEM, T_ID> List<T_ITEM> sortByIdList(IdQueryService<T_ITEM, T_ID> service, List<T_ITEM> items, List<T_ID> ids) {
return sortByIdList(service, items, ids, false);
}
/**
* Applies the order of the given id list to the given item list.
*
* @param items The unsorted item list.
* @param ids An ID list that defines the sort order.
* @return The sorted item list.<br>
* The list size is the same as of parameter <code>ids</code>.
* If there was no item for an ID a list position having a <code>null</code> value will be provided.
*/
public static <T_ITEM, T_ID> List<T_ITEM> sortByIdListWithGaps(IdQueryService<T_ITEM, T_ID> service, List<T_ITEM> items, List<T_ID> ids) {
return sortByIdList(service, items, ids, true);
}
private static <T_ITEM, T_ID> List<T_ITEM> sortByIdList(IdQueryService<T_ITEM, T_ID> service, List<T_ITEM> items, List<T_ID> ids, boolean withGaps) {
Map<T_ID, T_ITEM> map = new HashMap<T_ID, T_ITEM>();
for (T_ITEM item : items) {
if (item != null) {
T_ID id = service.getIdForItem(item);
map.put(id, item);
}
}
List<T_ITEM> sortedResult = new ArrayList<T_ITEM>();
for (T_ID id : ids) {
T_ITEM item = map.get(id);
if (item != null || withGaps) {
sortedResult.add(item);
}
}
return sortedResult;
}
}
| pm4j/org.pm4j | pm4j-common/src/main/java/org/pm4j/common/pageable/querybased/idquery/IdQueryServiceUtil.java | Java | bsd-2-clause | 1,954 |
namespace Patterns.Specifications.Models.Testing.Moq
{
public interface ITestContainerTarget {}
public interface ITestContainerDependency1{}
public interface ITestContainerDependency2{}
public class TestContainerTarget : ITestContainerTarget
{
public ITestContainerDependency1 Dependency1 { get; set; }
public ITestContainerDependency2 Dependency2 { get; set; }
public TestContainerTarget(ITestContainerDependency1 dependency1, ITestContainerDependency2 dependency2)
{
Dependency1 = dependency1;
Dependency2 = dependency2;
}
}
} | patterns-group/code-patterns | src/_specs/Models/Testing/Moq/TestContainerTarget.cs | C# | bsd-2-clause | 556 |
package com.baneizalfe.gocarinthia.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.alihafizji.library.CreditCardEditText;
import com.baneizalfe.gocarinthia.R;
import com.baneizalfe.gocarinthia.activities.RegisterActivity;
import com.baneizalfe.gocarinthia.payment.PaymentRequest;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by baneizalfe on 6/26/16.
*/
public class PaymentFragment extends BaseFragment {
@BindView(R.id.cc_name_input)
EditText cc_name_input;
@BindView(R.id.cc_number_input)
CreditCardEditText cc_number_input;
@BindView(R.id.cc_cvc_input)
EditText cc_cvc_input;
@BindView(R.id.cc_expiration_input)
EditText cc_expiration_input;
public static PaymentFragment newInstance() {
PaymentFragment fragment = new PaymentFragment();
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register, container, false);
ButterKnife.bind(this, view);
return view;
}
@OnClick(R.id.submit_btn)
void addPayment() {
PaymentRequest paymentRequest = new PaymentRequest(
cc_number_input.getCreditCardNumber(),
cc_name_input.getText().toString(),
cc_expiration_input.getText().toString(),
cc_cvc_input.getText().toString()
);
if (getActivity() instanceof RegisterActivity)
((RegisterActivity) getActivity()).submitPayment(paymentRequest);
}
}
| baneizalfe/gocarinthia | app/src/main/java/com/baneizalfe/gocarinthia/fragments/PaymentFragment.java | Java | bsd-2-clause | 1,841 |
cask v1: 'wkhtmltopdf' do
version '0.12.3-dev-79ff51e'
if Hardware::CPU.is_32_bit?
sha256 'a9eb4127243ec15c3c300f5d64c3a7e93e69400beb68419f93f070cc3ec54c11'
# bitbucket.org is the official download host per the vendor homepage
url "https://bitbucket.org/wkhtmltopdf/wkhtmltopdf/downloads/wkhtmltox-#{version}_osx-carbon-i386.pkg"
pkg "wkhtmltox-#{version}_osx-carbon-i386.pkg"
else
sha256 '087d7b81d6e02d6d64605fd0901d538d944b926131bcbe2b87f70bc866473382'
# bitbucket.org is the official download host per the vendor homepage
url "https://bitbucket.org/wkhtmltopdf/wkhtmltopdf/downloads/wkhtmltox-#{version}_osx-cocoa-x86-64.pkg"
pkg "wkhtmltox-#{version}_osx-cocoa-x86-64.pkg"
end
name 'wkhtmltopdf'
homepage 'http://wkhtmltopdf.org/'
license :gpl
depends_on macos: '>= :snow_leopard'
uninstall pkgutil: 'org.wkhtmltopdf.wkhtmltox',
delete: [
'/usr/local/include/wkhtmltox',
'/usr/local/lib/libwkhtmltox.dylib',
"/usr/local/lib/libwkhtmltox.#{version.to_i}.dylib",
"/usr/local/lib/libwkhtmltox.#{version.to_f}.dylib",
"/usr/local/lib/libwkhtmltox.#{version.sub(%r{-.*$},'')}.dylib",
'/usr/local/bin/wkhtmltoimage',
'/usr/local/bin/wkhtmltopdf'
]
caveats do
files_in_usr_local
end
end
| askl56/homebrew-cask | Casks/wkhtmltopdf.rb | Ruby | bsd-2-clause | 1,466 |
package integration.mindbody;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy;
import org.jvnet.jaxb2_commons.lang.HashCode;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy;
import org.jvnet.jaxb2_commons.lang.ToString;
import org.jvnet.jaxb2_commons.lang.ToStringStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;
/**
* <p>Java class for ArrayOfCustomClientField complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ArrayOfCustomClientField">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="CustomClientField" type="{http://clients.mindbodyonline.com/api/0_5}CustomClientField" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfCustomClientField", propOrder = {
"customClientField"
})
@Entity(name = "ArrayOfCustomClientField")
@Table(name = "ARRAY_OF_CUSTOM_CLIENT_FIELD")
@Inheritance(strategy = InheritanceType.JOINED)
public class ArrayOfCustomClientField
implements Serializable, Equals, HashCode, ToString
{
private final static long serialVersionUID = 1L;
@XmlElement(name = "CustomClientField", nillable = true)
protected List<CustomClientField> customClientField;
@XmlAttribute(name = "Hjid")
protected Long hjid;
/**
* Gets the value of the customClientField 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 customClientField property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCustomClientField().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CustomClientField }
*
*
*/
@OneToMany(targetEntity = CustomClientField.class, cascade = {
CascadeType.ALL
}, fetch = FetchType.EAGER)
@JoinColumn(name = "CUSTOM_CLIENT_FIELD_ARRAY_OF_0")
public List<CustomClientField> getCustomClientField() {
if (customClientField == null) {
customClientField = new ArrayList<CustomClientField>();
}
return this.customClientField;
}
/**
*
*
*/
public void setCustomClientField(List<CustomClientField> customClientField) {
this.customClientField = customClientField;
}
public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) {
int currentHashCode = 1;
{
List<CustomClientField> theCustomClientField;
theCustomClientField = (((this.customClientField!= null)&&(!this.customClientField.isEmpty()))?this.getCustomClientField():null);
currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "customClientField", theCustomClientField), currentHashCode, theCustomClientField);
}
return currentHashCode;
}
public int hashCode() {
final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE;
return this.hashCode(null, strategy);
}
public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) {
if (!(object instanceof ArrayOfCustomClientField)) {
return false;
}
if (this == object) {
return true;
}
final ArrayOfCustomClientField that = ((ArrayOfCustomClientField) object);
{
List<CustomClientField> lhsCustomClientField;
lhsCustomClientField = (((this.customClientField!= null)&&(!this.customClientField.isEmpty()))?this.getCustomClientField():null);
List<CustomClientField> rhsCustomClientField;
rhsCustomClientField = (((that.customClientField!= null)&&(!that.customClientField.isEmpty()))?that.getCustomClientField():null);
if (!strategy.equals(LocatorUtils.property(thisLocator, "customClientField", lhsCustomClientField), LocatorUtils.property(thatLocator, "customClientField", rhsCustomClientField), lhsCustomClientField, rhsCustomClientField)) {
return false;
}
}
return true;
}
public boolean equals(Object object) {
final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
return equals(null, null, object, strategy);
}
public String toString() {
final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
final StringBuilder buffer = new StringBuilder();
append(null, buffer, strategy);
return buffer.toString();
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
strategy.appendStart(locator, this, buffer);
appendFields(locator, buffer, strategy);
strategy.appendEnd(locator, this, buffer);
return buffer;
}
public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
{
List<CustomClientField> theCustomClientField;
theCustomClientField = (((this.customClientField!= null)&&(!this.customClientField.isEmpty()))?this.getCustomClientField():null);
strategy.appendField(locator, this, "customClientField", buffer, theCustomClientField);
}
return buffer;
}
/**
* Gets the value of the hjid property.
*
* @return
* possible object is
* {@link Long }
*
*/
@Id
@Column(name = "HJID")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getHjid() {
return hjid;
}
/**
* Sets the value of the hjid property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setHjid(Long value) {
this.hjid = value;
}
}
| highsource/hyperjaxb3-support | m/MindBody/src/main/java/integration/mindbody/ArrayOfCustomClientField.java | Java | bsd-2-clause | 7,285 |
package cz.metacentrum.perun.registrar.impl;
import cz.metacentrum.perun.audit.events.ExpirationNotifScheduler.GroupMembershipExpirationInDays;
import cz.metacentrum.perun.audit.events.ExpirationNotifScheduler.GroupMembershipExpirationInMonthNotification;
import cz.metacentrum.perun.audit.events.ExpirationNotifScheduler.GroupMembershipExpired;
import cz.metacentrum.perun.audit.events.ExpirationNotifScheduler.MembershipExpirationInDays;
import cz.metacentrum.perun.audit.events.ExpirationNotifScheduler.MembershipExpirationInMonthNotification;
import cz.metacentrum.perun.audit.events.ExpirationNotifScheduler.MembershipExpired;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.BeansUtils;
import cz.metacentrum.perun.core.api.ExtSourcesManager;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.MemberGroupStatus;
import cz.metacentrum.perun.core.api.PerunClient;
import cz.metacentrum.perun.core.api.PerunPrincipal;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.Status;
import cz.metacentrum.perun.core.api.Vo;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.ExtendMembershipException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.core.impl.Auditer;
import cz.metacentrum.perun.core.impl.Synchronizer;
import cz.metacentrum.perun.registrar.model.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcPerunTemplate;
import javax.sql.DataSource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Class handling incoming membership expiration notifications for VOs and Groups
* It also switches actual (group)member status VALID<-->EXPIRED based on expiration date.
*
* @author Pavel Zlámal <zlamal@cesnet.cz>
*/
public class ExpirationNotifScheduler {
private final static Logger log = LoggerFactory.getLogger(Synchronizer.class);
private PerunSession sess;
private PerunBl perun;
private JdbcPerunTemplate jdbc;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbc = new JdbcPerunTemplate(dataSource);
this.jdbc.setQueryTimeout(BeansUtils.getCoreConfig().getQueryTimeout());
}
public PerunBl getPerun() {
return perun;
}
@Autowired
public void setPerun(PerunBl perun) {
this.perun = perun;
}
public ExpirationNotifScheduler() {
}
/**
* Constructor for unit tests
*
* @param perun PerunBl bean
* @throws Exception When implementation fails
*/
public ExpirationNotifScheduler(PerunBl perun) throws Exception {
this.perun = perun;
initialize();
}
public void initialize() throws InternalErrorException {
String synchronizerPrincipal = "perunSynchronizer";
this.sess = perun.getPerunSession(
new PerunPrincipal(synchronizerPrincipal, ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL),
new PerunClient());
}
/**
* Functional interface defining audit action when members will expire in given time
*/
@FunctionalInterface
private interface ExpirationAuditAction<TA extends Auditer, TS extends PerunSession, TM extends Member, TV extends Vo> {
void callOn(TA auditer, TS session, TM member, TV vo) throws InternalErrorException;
}
/**
* Functional interface defining audit action when group members will expire in given time
*/
@FunctionalInterface
private interface GroupExpirationAuditAction<TA extends Auditer, TS extends PerunSession, TM extends Member, TV extends Group> {
void callOn(TA auditer, TS session, TM member, TV group) throws InternalErrorException;
}
/**
* Enum defining time before member expiration and action that should be logged in auditer when it happens
*/
private enum ExpirationPeriod {
MONTH(((auditer, sess, member, vo) ->
auditer.log(sess, new MembershipExpirationInMonthNotification(member, vo))
)),
DAYS_14(((auditer, sess, member, vo) ->
auditer.log(sess, new MembershipExpirationInDays(member, 14, vo))
)),
DAYS_7(((auditer, sess, member, vo) ->
auditer.log(sess, new MembershipExpirationInDays(member, 7, vo))
)),
DAYS_1(((auditer, sess, member, vo) ->
auditer.log(sess, new MembershipExpirationInDays(member, 1, vo))
));
private final ExpirationAuditAction<Auditer, PerunSession, Member, Vo> expirationAuditAction;
ExpirationAuditAction<Auditer, PerunSession, Member, Vo> getExpirationAuditAction() {
return this.expirationAuditAction;
}
ExpirationPeriod(ExpirationAuditAction<Auditer, PerunSession, Member, Vo> expirationAuditAction) {
this.expirationAuditAction = expirationAuditAction;
}
}
/**
* Enum defining time before member expiration and action that should be logged in auditer when it happens
*/
private enum GroupExpirationPeriod {
MONTH(((auditer, sess, member, group) ->
auditer.log(sess, new GroupMembershipExpirationInMonthNotification(member, group))
)),
DAYS_14(((auditer, sess, member, group) ->
auditer.log(sess, new GroupMembershipExpirationInDays(member, 14, group))
)),
DAYS_7(((auditer, sess, member, group) ->
auditer.log(sess, new GroupMembershipExpirationInDays(member, 7, group))
)),
DAYS_1(((auditer, sess, member, group) ->
auditer.log(sess, new GroupMembershipExpirationInDays(member, 1, group))
));
private final GroupExpirationAuditAction<Auditer, PerunSession, Member, Group> expirationAuditAction;
GroupExpirationAuditAction<Auditer, PerunSession, Member, Group> getExpirationAuditAction() {
return this.expirationAuditAction;
}
GroupExpirationPeriod(GroupExpirationAuditAction<Auditer, PerunSession, Member, Group> expirationAuditAction) {
this.expirationAuditAction = expirationAuditAction;
}
}
/**
* Finds members who should expire in given time, and if they did not submit an extension
* application, notification is logged in auditer
*
* @param allowedStatuses members that has one of this statuses will be checked
* @param vosMap map containing all Vos from perun
* @param timeBeforeExpiration time used for check
* @param expirationPeriod Expiration period, should correspond with given date
* @throws InternalErrorException internal error
*/
private void auditInfoAboutIncomingMembersExpirationInGivenTime(List<Status> allowedStatuses, Map<Integer, Vo> vosMap, LocalDate timeBeforeExpiration, ExpirationPeriod expirationPeriod) throws InternalErrorException {
List<Member> expireInTime = perun.getSearcherBl().getMembersByExpiration(sess, "=", timeBeforeExpiration);
for (Member m : expireInTime) {
try {
if (allowedStatuses.contains(m.getStatus())) {
perun.getMembersManagerBl().canExtendMembershipWithReason(sess, m);
if (didntSubmitExtensionApplication(m)) {
// still didn't apply for extension
expirationPeriod.getExpirationAuditAction().callOn(getPerun().getAuditer(), sess, m, vosMap.get(m.getVoId()));
} else {
log.debug("{} not notified about expiration, has submitted - pending application.", m);
}
} else {
log.debug("{} not notified about expiration, is not in VALID or SUSPENDED state.", m);
}
} catch (ExtendMembershipException ex) {
if (!Objects.equals(ex.getReason(), ExtendMembershipException.Reason.OUTSIDEEXTENSIONPERIOD)) {
// we don't care about other reasons (LoA), user can update it later
if (didntSubmitExtensionApplication(m)) {
// still didn't apply for extension
expirationPeriod.getExpirationAuditAction().callOn(getPerun().getAuditer(), sess, m, vosMap.get(m.getVoId()));
} else {
log.debug("{} not notified about expiration, has submitted - pending application.", m);
}
}
}
}
}
/**
* Finds members who should expire in a group in given time, and if they did not submit an extension
* application, notification is logged into Auditer log.
*
* @param allowedStatuses Only members within allowed statuses will get notification.
* @param group Group to check expiration in
* @param timeBeforeExpiration time used for check
* @param expirationPeriod Expiration period, should correspond with given date
* @throws InternalErrorException internal error
*/
private void auditInfoAboutIncomingGroupMembersExpirationInGivenTime(List<Status> allowedStatuses, Group group, LocalDate timeBeforeExpiration, GroupExpirationPeriod expirationPeriod) throws InternalErrorException {
List<Member> expireInTime = perun.getSearcherBl().getMembersByGroupExpiration(sess, group, "=", timeBeforeExpiration);
for (Member m : expireInTime) {
try {
// we don't notify disabled or invalid members
if (allowedStatuses.contains(m.getStatus())) {
MemberGroupStatus status = perun.getGroupsManagerBl().getDirectMemberGroupStatus(sess, m, group);
// we don't notify members in indirect only relation
if (status != null) {
perun.getGroupsManagerBl().canExtendMembershipInGroupWithReason(sess, m, group);
if (didntSubmitGroupExtensionApplication(m, group)) {
// still didn't apply for extension
expirationPeriod.getExpirationAuditAction().callOn(getPerun().getAuditer(), sess, m, group);
} else {
log.debug("{} not notified about expiration in {}, has submitted - pending application.", m, group);
}
} else {
log.debug("{} not notified about expiration in {}, isn't DIRECT member but still has expiration set!", m, group);
}
} else {
log.debug("{} not notified about expiration in {}, is not in VALID, EXPIRED or SUSPENDED state.", m, group);
}
} catch (ExtendMembershipException ex) {
if (!Objects.equals(ex.getReason(), ExtendMembershipException.Reason.OUTSIDEEXTENSIONPERIOD)) {
// we don't care about other reasons (LoA), user can update it later
if (didntSubmitGroupExtensionApplication(m, group)) {
// still didn't apply for extension
expirationPeriod.getExpirationAuditAction().callOn(getPerun().getAuditer(), sess, m, group);
} else {
log.debug("{} not notified about expiration in {}, has submitted - pending application.", m, group);
}
}
}
}
}
/**
* Perform check on members status and switch it between VALID and EXPIRED (if necessary).
* Switching is based on current date and their value of membership expiration.
*
* Method also log audit messages, that membership will expired in X days or expired X days ago.
*
* Method is triggered by Spring scheduler (at midnight everyday).
*/
public void checkMembersState() {
if (perun.isPerunReadOnly()) {
log.debug("This instance is just read only so skip checking members states.");
return;
}
List<Vo> vos;
try {
// get all available VOs
vos = perun.getVosManagerBl().getVos(sess);
} catch (InternalErrorException e) {
log.error("Synchronizer: checkMembersState, failed to get all vos exception.", e);
return;
}
log.debug("Processing checkMemberState() on (to be) expired members.");
// check group expiration in vos
try {
checkGroupMembersState(vos);
} catch (InternalErrorException e) {
log.error("checkGroupMembersState failed", e);
}
// check vo membership expiration
try {
checkVoMembersState(vos);
} catch(InternalErrorException e){
log.error("Synchronizer: checkMembersState.", e);
} catch(AttributeNotExistsException e){
log.warn("Synchronizer: checkMembersState, attribute definition for membershipExpiration doesn't exist.", e);
} catch(WrongAttributeAssignmentException e){
log.error("Synchronizer: checkMembersState, attribute name is from wrong namespace.", e);
}
}
/**
* Checks state of members in given vos
*
* @param vos vos
* @throws InternalErrorException internal error
* @throws WrongAttributeAssignmentException error
* @throws AttributeNotExistsException error
*/
private void checkVoMembersState(List<Vo> vos) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException {
// Only members with following statuses will be notified
List<Status> allowedStatuses = new ArrayList<>();
allowedStatuses.add(Status.VALID);
allowedStatuses.add(Status.SUSPENDED);
Map<Integer, Vo> vosMap = new HashMap<>();
for (Vo vo : vos) {
vosMap.put(vo.getId(), vo);
}
auditIncomingExpirations(allowedStatuses, vosMap);
auditOldExpirations(allowedStatuses, vosMap);
LocalDate today = LocalDate.now();
expireMembers(today);
validateMembers(today);
}
/**
* Validates member whose expiration is set after the given date
*
* @param date date
* @throws InternalErrorException internal error
* @throws WrongAttributeAssignmentException error
* @throws AttributeNotExistsException error
*/
private void validateMembers(LocalDate date) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException {
List<Member> shouldntBeExpired = perun.getSearcherBl().getMembersByExpiration(sess, ">", date);
for (Member member : shouldntBeExpired) {
if (member.getStatus().equals(Status.EXPIRED)) {
try {
perun.getMembersManagerBl().validateMember(sess, member);
log.info("Switching {} to VALID state, due to changed expiration {}.", member, perun.getAttributesManagerBl().getAttribute(sess, member, "urn:perun:member:attribute-def:def:membershipExpiration").getValue());
} catch (WrongAttributeValueException | WrongReferenceAttributeValueException e) {
log.error("Error during validating member {}, exception {}", member, e);
}
}
}
}
/**
* Expires members whose expiration is set to given date or before it.
*
* @throws InternalErrorException internal error
* @throws WrongAttributeAssignmentException error
* @throws AttributeNotExistsException error
*/
private void expireMembers(LocalDate date) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException {
List<Member> shouldBeExpired = perun.getSearcherBl().getMembersByExpiration(sess, "<=", date);
for (Member member : shouldBeExpired) {
if (member.getStatus().equals(Status.VALID)) {
try {
perun.getMembersManagerBl().expireMember(sess, member);
log.info("Switching {} to EXPIRE state, due to expiration {}.", member, perun.getAttributesManagerBl().getAttribute(sess, member, "urn:perun:member:attribute-def:def:membershipExpiration").getValue());
} catch (WrongAttributeValueException | WrongReferenceAttributeValueException e) {
log.error("Consistency error while trying to expire member {}, exception {}", member, e);
}
}
}
}
/**
* Logs expirations that happened a week ago
*
* @param allowedStatuses allowed Statuses
* @param vosMap vos
* @throws InternalErrorException internal error
*/
private void auditOldExpirations(List<Status> allowedStatuses, Map<Integer, Vo> vosMap) throws InternalErrorException {
// log message for all members which expired 7 days ago
LocalDate expiredWeekAgo = LocalDate.now().minusDays(7);
List<Member> expired7DaysAgo = perun.getSearcherBl().getMembersByExpiration(sess, "=", expiredWeekAgo);
// include expired in this case
allowedStatuses.add(Status.EXPIRED);
for (Member m : expired7DaysAgo) {
if (allowedStatuses.contains(m.getStatus())) {
if (didntSubmitExtensionApplication(m)) {
// still didn't apply for extension
getPerun().getAuditer().log(sess, new MembershipExpired(m, 7, vosMap.get(m.getVoId())));
} else {
log.debug("{} not notified about expiration, has submitted - pending application.", m);
}
} else {
log.debug("{} not notified about expiration, is not in VALID, SUSPENDED or EXPIRED state.", m);
}
}
}
/**
* Logs expirations that happened a week ago for a group
*
* @param allowedStatuses allowed Statuses
* @param group group
* @throws InternalErrorException internal error
*/
private void auditOldGroupExpirations(List<Status> allowedStatuses, Group group) throws InternalErrorException {
// log message for all members which expired 7 days ago
LocalDate expiredWeekAgo = LocalDate.now().minusDays(7);
List<Member> expired7DaysAgo = perun.getSearcherBl().getMembersByGroupExpiration(sess, group, "=", expiredWeekAgo);
for (Member m : expired7DaysAgo) {
if (allowedStatuses.contains(m.getStatus())) {
MemberGroupStatus status = perun.getGroupsManagerBl().getDirectMemberGroupStatus(sess, m, group);
// we don't notify members in indirect only relation
if (status != null) {
if (didntSubmitGroupExtensionApplication(m, group)) {
// still didn't apply for extension
getPerun().getAuditer().log(sess, new GroupMembershipExpired(m, 7, group));
} else {
log.debug("{} not notified about expiration in {}, has submitted - pending application.", m, group);
}
} else {
log.debug("{} not notified about expiration in {}, isn't DIRECT member but still has expiration set!", m, group);
}
} else {
log.debug("{} not notified about expiration in {}, is not in VALID, SUSPENDED or EXPIRED state.", m, group);
}
}
}
/**
* Logs incoming expirations into auditer
*
* @param allowedStatuses allowed statues
* @param vosMap vos
* @throws InternalErrorException internal error
*/
private void auditIncomingExpirations(List<Status> allowedStatuses, Map<Integer, Vo> vosMap) throws InternalErrorException {
LocalDate nextMonth = LocalDate.now().plusMonths(1);
// log message for all members which will expire in 30 days
auditInfoAboutIncomingMembersExpirationInGivenTime(allowedStatuses, vosMap, nextMonth, ExpirationPeriod.MONTH);
// log message for all members which will expire in 14 days
LocalDate expireInA14Days = LocalDate.now().plusDays(14);
auditInfoAboutIncomingMembersExpirationInGivenTime(allowedStatuses, vosMap, expireInA14Days, ExpirationPeriod.DAYS_14);
// log message for all members which will expire in 7 days
LocalDate expireInA7Days = LocalDate.now().plusDays(7);
auditInfoAboutIncomingMembersExpirationInGivenTime(allowedStatuses, vosMap, expireInA7Days, ExpirationPeriod.DAYS_7);
// log message for all members which will expire tomorrow
LocalDate expireInADay = LocalDate.now().plusDays(1);
auditInfoAboutIncomingMembersExpirationInGivenTime(allowedStatuses, vosMap, expireInADay, ExpirationPeriod.DAYS_1);
}
/**
* Logs incoming expirations into auditer for Group expirations
*
* @param allowedStatuses allowed statues
* @param group group
* @throws InternalErrorException internal error
*/
private void auditIncomingGroupExpirations(List<Status> allowedStatuses, Group group) throws InternalErrorException {
LocalDate nextMonth = LocalDate.now().plusMonths(1);
// log message for all members which will expire in 30 days
auditInfoAboutIncomingGroupMembersExpirationInGivenTime(allowedStatuses, group, nextMonth, GroupExpirationPeriod.MONTH);
// log message for all members which will expire in 14 days
LocalDate expireInA14Days = LocalDate.now().plusDays(14);
auditInfoAboutIncomingGroupMembersExpirationInGivenTime(allowedStatuses, group, expireInA14Days, GroupExpirationPeriod.DAYS_14);
// log message for all members which will expire in 7 days
LocalDate expireInA7Days = LocalDate.now().plusDays(7);
auditInfoAboutIncomingGroupMembersExpirationInGivenTime(allowedStatuses, group, expireInA7Days, GroupExpirationPeriod.DAYS_7);
// log message for all members which will expire tomorrow
LocalDate expireInADay = LocalDate.now().plusDays(1);
auditInfoAboutIncomingGroupMembersExpirationInGivenTime(allowedStatuses, group, expireInADay, GroupExpirationPeriod.DAYS_1);
}
/**
* Finds members in given group and if they expire on given date and they have
* VALID MemberGroupState, switch them to EXPIRED
*
* @param group given date
* @param date current date
* @throws InternalErrorException internal error
*/
private void checkGroupMemberExpiration(Group group, LocalDate date) throws InternalErrorException {
List<Member> shouldBeExpired = perun.getSearcherBl().getMembersByGroupExpiration(sess, group, "<=", date);
shouldBeExpired.stream()
// read member exact group status (not calculated from other group relations),
// since we change status in specified group only for direct members !!
.filter(member -> {
try {
// if member is not direct in group, false is returned
return Objects.equals(MemberGroupStatus.VALID, perun.getGroupsManagerBl().getDirectMemberGroupStatus(sess, member, group));
} catch (InternalErrorException e) {
log.error("Synchronizer: checkGroupMemberExpiration failed to read member's state in group. Member: {}, Group: {}, Exception: {}", member, group, e);
return false;
}
})
.forEach(member -> {
try {
perun.getGroupsManagerBl().expireMemberInGroup(sess, member, group);
log.info("Switching {} in {} to EXPIRED state, due to expiration {}.", member, group, perun.getAttributesManagerBl().getAttribute(sess, member, group, AttributesManager.NS_MEMBER_GROUP_ATTR_DEF + "groupMembershipExpiration").getValue());
} catch (InternalErrorException e) {
log.error("Consistency error while trying to expire member {} in {}, exception {}", member, group, e);
} catch (AttributeNotExistsException e) {
log.warn("Synchronizer: checkGroupMembersState, attribute definition for membershipExpiration in group doesn't exist.", e);
} catch(WrongAttributeAssignmentException e){
log.error("Synchronizer: checkMembersState, attribute name is from wrong namespace.", e);
}
});
}
/**
* Finds members in given group which should be valid and if they are expired,
* switch them to VALID state in given group
*
* @param group group where members are searched
* @param date current date
* @throws InternalErrorException internal error
*/
private void checkGroupMemberValidation(Group group, LocalDate date) throws InternalErrorException {
List<Member> shouldNotBeExpired = perun.getSearcherBl().getMembersByGroupExpiration(sess, group, ">", date);
shouldNotBeExpired.stream()
// read member exact group status (not calculated from other group relations),
// since we change status in specified group only for direct members !!
.filter(member -> {
try {
// if member is not direct in group, false is returned
return Objects.equals(MemberGroupStatus.EXPIRED, perun.getGroupsManagerBl().getDirectMemberGroupStatus(sess, member, group));
} catch (InternalErrorException e) {
log.error("Synchronizer: checkGroupMemberExpiration failed to read member's state in group. Member: {}, Group: {}, Exception: {}", member, group, e);
return false;
}
})
.forEach(member -> {
try {
perun.getGroupsManagerBl().validateMemberInGroup(sess, member, group);
log.info("Switching {} in {} to VALID state, due to changed expiration {}.", member, group, perun.getAttributesManagerBl().getAttribute(sess, member, group, AttributesManager.NS_MEMBER_GROUP_ATTR_DEF + "groupMembershipExpiration").getValue());
} catch (InternalErrorException e) {
log.error("Error during validating member {} in {}, exception {}", member, group, e);
} catch (AttributeNotExistsException e) {
log.warn("Synchronizer: checkGroupMemberValidation, attribute definition for membershipExpiration in group doesn't exist.", e);
} catch(WrongAttributeAssignmentException e){
log.error("Synchronizer: checkGroupMemberValidation, attribute name is from wrong namespace.", e);
}
});
}
/**
* Check members states in groups from given Vos.
*
* @param vos vos
* @throws InternalErrorException internal error
*/
private void checkGroupMembersState(List<Vo> vos) throws InternalErrorException {
// Only members with following statuses will be notified
List<Status> allowedStatuses = new ArrayList<>();
allowedStatuses.add(Status.VALID);
allowedStatuses.add(Status.SUSPENDED);
// in opposite to vo expiration we want to notify about incoming group expirations even when user is expired in VO
allowedStatuses.add(Status.EXPIRED);
List<Group> allGroups = new ArrayList<>();
for (Vo vo : vos) {
allGroups.addAll(perun.getGroupsManagerBl().getGroups(sess, vo));
}
LocalDate today = LocalDate.now();
// remove member groups
allGroups = allGroups.stream()
.filter(group -> !group.getName().equals("members"))
.collect(Collectors.toList());
// for all groups in perun
for (Group group : allGroups) {
auditIncomingGroupExpirations(allowedStatuses, group);
auditOldGroupExpirations(allowedStatuses, group);
// check members which should expire today
checkGroupMemberExpiration(group, today);
// check members which should be validated today
checkGroupMemberValidation(group, today);
}
}
/**
* Check if member didn't submit new extension application - in such case, do not send expiration notifications
*
* @param member Member to check applications for
* @return TRUE = didn't submit application / FALSE = otherwise
*/
private boolean didntSubmitExtensionApplication(Member member) {
try {
Application application = jdbc.queryForObject(RegistrarManagerImpl.APP_SELECT + " where a.id=(select max(id) from application where vo_id=? and apptype=? and user_id=? )", RegistrarManagerImpl.APP_MAPPER, member.getVoId(), String.valueOf(Application.AppType.EXTENSION), member.getUserId());
return !Arrays.asList(Application.AppState.NEW, Application.AppState.VERIFIED).contains(application.getState());
} catch (EmptyResultDataAccessException ex) {
// has no application submitted
return true;
} catch (Exception ex) {
log.error("Unable to check if {} has submitted pending application: {}.", member, ex);
return true;
}
}
/**
* Check if member didn't submit new extension application for a group - in such case, do not send expiration notifications
*
* @param member Member to check applications for
* @param group Group to check applications for
* @return TRUE = didn't submit application / FALSE = otherwise
*/
private boolean didntSubmitGroupExtensionApplication(Member member, Group group) {
try {
Application application = jdbc.queryForObject(RegistrarManagerImpl.APP_SELECT + " where a.id=(select max(id) from application where vo_id=? and group_id=? and apptype=? and user_id=? )", RegistrarManagerImpl.APP_MAPPER, member.getVoId(), group.getId(), String.valueOf(Application.AppType.EXTENSION), member.getUserId());
return !Arrays.asList(Application.AppState.NEW, Application.AppState.VERIFIED).contains(application.getState());
} catch (EmptyResultDataAccessException ex) {
// has no application submitted
return true;
} catch (Exception ex) {
log.error("Unable to check if {} has submitted pending application: {}.", member, ex);
return true;
}
}
}
| stavamichal/perun | perun-registrar-lib/src/main/java/cz/metacentrum/perun/registrar/impl/ExpirationNotifScheduler.java | Java | bsd-2-clause | 27,577 |
// Copyright 2015 Bulat Ziganshin
// Released to public domain
#include <amp.h>
#include <stdio.h>
#include "timer.h"
int main()
{
static const unsigned DATASIZE = 1<<25;
static const unsigned BINS = 1<<4; // count low 4-bit freqs for every byte
static const unsigned CHUNK_CNT= 1<<8; // split data into 256 blocks and calculate histogram for each one separately
static const unsigned CHUNK = DATASIZE/CHUNK_CNT; // 128k
static const unsigned ITER = CHUNK/sizeof(unsigned); // 32k
static const unsigned STRIDE = 128; // how many dwords to process by the single thread
static const unsigned TILE = 256, TILE1 = 128, TILE0 = TILE/TILE1; // single tile includes TILE0 blocks * TILE1 independent parts in the every block
std::vector<unsigned> inbuf(CHUNK_CNT*ITER);
std::vector<unsigned> outbuf(CHUNK_CNT*BINS);
concurrency::array_view<unsigned, 2> srcdata(CHUNK_CNT, ITER, inbuf);
concurrency::array_view<unsigned, 2> histogram(CHUNK_CNT, BINS, outbuf);
srcdata.discard_data();
histogram.discard_data();
// Fill with pseudo-random data
concurrency::parallel_for_each (srcdata.extent, [=](concurrency::index<2> idx) restrict(amp)
{
srcdata[idx] = (srcdata.extent[1]*idx[0]+idx[1]) * 1234567891;
});
srcdata.synchronize();
const uint64_t DATASET = uint64_t(10)<<30;
printf("Histogram%d of %d GiB random data", BINS, int(DATASET>>30));
Timer t; t.Start();
for (int i=0; i<DATASET/DATASIZE; i++)
{
concurrency::extent<2> data_extent (srcdata.extent[0], srcdata.extent[1]/STRIDE);
concurrency::parallel_for_each (data_extent.tile<TILE0,TILE1>(), [=](concurrency::tiled_index<TILE0,TILE1> idx) restrict(amp)
{
tile_static unsigned freq[BINS][TILE];
unsigned loc_idx = idx.local[0]*TILE1+idx.local[1];
// init bins that will be used by this thread
for (int bin=0; bin<BINS; bin++)
freq[bin][loc_idx] = 0;
//idx.barrier.wait_with_tile_static_memory_fence(); // may improve performance
for (int i=0; i<STRIDE; i++)
{
#define count(bin) (freq[bin][loc_idx]++)
unsigned x = srcdata (idx.global[0], i*(ITER/STRIDE)+idx.global[1]);
count( x % BINS);
count((x>> 8) % BINS);
count((x>>16) % BINS);
count((x>>24) % BINS);
#undef count
}
idx.barrier.wait_with_tile_static_memory_fence();
// We update only one histogram[] entry per thread, that's correct only if TILE1 >= BINS
const unsigned STRIDE1 = TILE1/BINS;
unsigned bin = idx.local[1] / STRIDE1;
unsigned sum = 0;
for (int i=0; i<BINS; i++)
sum += freq [bin] [idx.local[0]*TILE1 + i*STRIDE1 + idx.local[1]%STRIDE1]; // distribute memory accesses from the single warp accross STRIDE1 banks
concurrency::atomic_fetch_add (&histogram(idx.global[0],bin), sum);
});
}
histogram.synchronize();
t.Stop(); auto speed = DATASET/(t.Elapsed()/1000);
printf(": %.3lf milliseconds = %.3lf GB/s = %.3lf GiB/s\n", t.Elapsed(), speed/1e9, speed/(1<<30));
return 0;
}
| Bulat-Ziganshin/GPU-Compression | histogram16.cpp | C++ | bsd-2-clause | 3,321 |
from copy import deepcopy
from geom import geom
import numpy as np
import pandas as pd
class geom_jitter(geom):
VALID_AES = ['jitter']
def __radd__(self, gg):
gg = deepcopy(gg)
xcol = gg.aesthetics.get("x")
ycol = gg.aesthetics.get("y")
x = gg.data[xcol]
y = gg.data[ycol]
x = x * np.random.uniform(.9, 1.1, len(x))
y = y * np.random.uniform(.9, 1.1, len(y))
gg.data[xcol] = x
gg.data[ycol] = y
return gg
def plot_layer(self, layer):
pass
| hadley/ggplot | ggplot/geoms/geom_jitter.py | Python | bsd-2-clause | 542 |
class ConstraintFailureException(Exception):
pass
| tmaiwald/OSIM | OSIM/Optimizations/ConstraintFailureException.py | Python | bsd-2-clause | 55 |
using LcaDataModel;
using Repository.Pattern.Repositories;
using Service.Pattern;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalRecycleLCA.Services
{
public interface IImpactCategoryService : IService<ImpactCategory>
{
}
public class ImpactCategoryService : Service<ImpactCategory>, IImpactCategoryService
{
public ImpactCategoryService(IRepositoryAsync<ImpactCategory> repository)
: base(repository)
{
}
}
}
| uo-lca/CalRecycleLCA | LCIAToolAPI/CalRecycleLCA.Services/ImpactCategoryService.cs | C# | bsd-2-clause | 558 |
package com.marcosdiez.maps_parser;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | marcosdiez/android_maps_parser | AndroidApp/app/src/androidTest/java/com/marcosdiez/maps_parser/ApplicationTest.java | Java | bsd-2-clause | 357 |
/**
* pims-web org.pimslims.presentation.sample HolderContentsTest.java
*
* @author cm65
* @date 28 Jun 2010
*
* Protein Information Management System
* @version: 3.2
*
* Copyright (c) 2010 cm65 The copyright holder has licenced the STFC to redistribute this software
*/
package org.pimslims.presentation.sample;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.pimslims.access.Access;
import org.pimslims.dao.AbstractModel;
import org.pimslims.dao.ModelImpl;
import org.pimslims.dao.WritableVersion;
import org.pimslims.exception.ConstraintException;
import org.pimslims.model.holder.Holder;
import org.pimslims.model.reference.HolderType;
import org.pimslims.model.sample.Sample;
import org.pimslims.presentation.ModelObjectBean;
/**
* HolderContentsTest
*
*/
public class HolderContentsTest extends TestCase {
private static final String UNIQUE = "hc" + System.currentTimeMillis();
private final AbstractModel model;
/**
* Constructor for SampleBeanTest
*
* @param name
*/
public HolderContentsTest(final String name) {
super(name);
this.model = ModelImpl.getModel();
}
public void testNoType() throws ConstraintException {
final WritableVersion version = this.model.getTestVersion();
try {
final Holder holder = new Holder(version, HolderContentsTest.UNIQUE, null);
HolderContents.getHolderContents(holder);
Assert.fail("no type");
} catch (final IllegalStateException ex) {
// that's fine
} finally {
version.abort();
}
}
public void test2x3x5empty() throws ConstraintException {
final WritableVersion version = this.model.getTestVersion();
try {
final HolderType type = new HolderType(version, HolderContentsTest.UNIQUE);
type.setMaxRow(2);
type.setMaxColumn(3);
type.setMaxSubPosition(5);
final Holder holder = new Holder(version, HolderContentsTest.UNIQUE, type);
final List<List<List<ModelObjectBean>>> contents = HolderContents.getHolderContents(holder);
Assert.assertEquals(2, contents.size());
final List<List<ModelObjectBean>> row1 = contents.iterator().next();
Assert.assertEquals(3, row1.size());
final List subs = row1.iterator().next();
Assert.assertEquals(5, subs.size());
} finally {
version.abort();
}
}
public void testOneSample() throws ConstraintException {
final WritableVersion version = this.model.getTestVersion();
try {
final HolderType type = new HolderType(version, HolderContentsTest.UNIQUE);
type.setMaxRow(2);
type.setMaxColumn(1);
type.setMaxSubPosition(1);
final Holder holder = new Holder(version, HolderContentsTest.UNIQUE, type);
final Sample sample = new Sample(version, HolderContentsTest.UNIQUE);
sample.setHolder(holder);
sample.setRowPosition(1);
sample.setColPosition(1);
sample.setSubPosition(1);
final List<List<List<ModelObjectBean>>> contents = HolderContents.getHolderContents(holder);
Assert.assertEquals(2, contents.size());
final List<List<ModelObjectBean>> row1 = contents.iterator().next();
Assert.assertEquals(1, row1.size());
final List subs = row1.iterator().next();
Assert.assertEquals(1, subs.size());
final SampleBean bean = (SampleBean) subs.iterator().next();
Assert.assertNotNull(bean);
Assert.assertEquals(sample.get_Hook(), bean.getHook());
} finally {
version.abort();
}
}
public void testOneHolder() throws ConstraintException {
final WritableVersion version = this.model.getTestVersion();
try {
final HolderType type = new HolderType(version, HolderContentsTest.UNIQUE);
type.setMaxRow(2);
type.setMaxColumn(1);
type.setMaxSubPosition(1);
final Holder holder = new Holder(version, HolderContentsTest.UNIQUE, type);
final Holder contained =
new Holder(version, HolderContentsTest.UNIQUE + "inner", new HolderType(version,
HolderContentsTest.UNIQUE + "inner"));
contained.setParentHolder(holder);
contained.setRowPosition(1);
contained.setColPosition(1);
contained.setSubPosition(1);
final List<List<List<ModelObjectBean>>> contents = HolderContents.getHolderContents(holder);
Assert.assertEquals(2, contents.size());
final List<List<ModelObjectBean>> row1 = contents.iterator().next();
Assert.assertEquals(1, row1.size());
final List subs = row1.iterator().next();
Assert.assertEquals(1, subs.size());
final ModelObjectBean bean = (ModelObjectBean) subs.iterator().next();
Assert.assertNotNull(bean);
Assert.assertEquals(contained.get_Hook(), bean.getHook());
} finally {
version.abort();
}
}
public void test1D() throws ConstraintException {
final WritableVersion version = this.model.getTestVersion();
try {
final HolderType type = new HolderType(version, HolderContentsTest.UNIQUE);
type.setMaxRow(2);
type.setMaxColumn(1);
type.setMaxSubPosition(1);
final Holder holder = new Holder(version, HolderContentsTest.UNIQUE, type);
Assert.assertEquals(1, HolderContents.getDimensions(holder));
} finally {
version.abort();
}
}
public void test3D() throws ConstraintException {
final WritableVersion version = this.model.getTestVersion();
try {
final HolderType type = new HolderType(version, HolderContentsTest.UNIQUE);
type.setMaxRow(4);
type.setMaxColumn(7);
type.setMaxSubPosition(4);
final Holder holder = new Holder(version, HolderContentsTest.UNIQUE, type);
Assert.assertEquals(3, HolderContents.getDimensions(holder));
} finally {
version.abort();
}
}
}
| homiak/pims-lims | TestSource/org/pimslims/presentation/sample/HolderContentsTest.java | Java | bsd-2-clause | 6,582 |
/*
Copyright (c) 2011-2013, Sergey Usilin. All rights reserved.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of copyright holders.
*/
#include <QSharedPointer>
#include <objedutils/objedconsole.h>
#include <objedutils/objedconfig.h>
#include <objedutils/objedopenmp.h>
#include <objedutils/objedimage.h>
#include <objedutils/objedexp.h>
#include <objedutils/objedsys.h>
#include "objedtrainutils.h"
#include "datasetproc.h"
static QStringList makeImagePathList(const QVariantList &datasetList)
{
QStringList imagePathList;
for (int i = 0; i < datasetList.count(); i++)
{
QDir datasetDir(datasetList[i].toString());
QStringList imageFilterList = ObjedSys::imageFilters();
QStringList imageNameList = datasetDir.entryList(imageFilterList);
for (int j = 0; j < imageNameList.count(); j++)
imagePathList.append(datasetDir.absoluteFilePath(imageNameList[j]));
}
return imagePathList;
}
DatasetProcessor::DatasetProcessor(ObjedConfig *config) :
classifierWidth(0), classifierHeight(0), minScale(1.0),
maxScale(1.0), stpScale(0.1), negativeCount(0)
{
classifierWidth = config->value("ClassifierWidth").toInt();
classifierHeight = config->value("ClassifierHeight").toInt();
minScale = config->value("MinimumScale").toDouble();
maxScale = config->value("MaximumScale").toDouble();
stpScale = config->value("StepScale").toDouble();
if (minScale > maxScale || stpScale <= 1.0)
throw ObjedException("Invalid Scale values");
negativeCount = config->value("NegativeCount").toInt();
if (negativeCount <= 0)
throw ObjedException("Invalid NegativeCount value");
positiveImagePathList = makeImagePathList(config->listValue("PositiveDatasetList"));
if (positiveImagePathList.isEmpty() == true) throw ObjedException("There are no positive images");
negativeImagePathList = makeImagePathList(config->listValue("NegativeDatasetList"));
if (negativeImagePathList.isEmpty() == true) throw ObjedException("There are no negative images");
}
DatasetProcessor::~DatasetProcessor()
{
return;
}
SampleList DatasetProcessor::preparePositiveSamples(objed::Classifier *classifier)
{
if (classifier == 0)
throw ObjedException("Invalid passed classifier");
if (classifier->width() != classifierWidth || classifier->height() != classifierHeight)
throw ObjedException("Invalid classifier size");
SampleList positiveSamples;
ObjedOpenMP::ClassifierList clasifierList = ObjedOpenMP::multiplyClassifier(classifier);
QVector<SampleList> positiveSamplesList(ObjedOpenMP::maxThreadCount());
int loadedSampleCount = 0;
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < positiveImagePathList.count(); i++)
{
QString imagePath = positiveImagePathList[i];
QString imageName = QFileInfo(imagePath).fileName();
int progress = 100 * loadedSampleCount / positiveImagePathList.count();
ObjedConsole::printProgress(QString("Processing positive image %0").arg(imageName), progress);
#pragma omp atomic
loadedSampleCount++;
objed::Classifier *classifier = clasifierList[ObjedOpenMP::threadId()].data();
SampleList &positiveSamples = positiveSamplesList[ObjedOpenMP::threadId()];
QSharedPointer<ObjedImage> image = ObjedImage::create(imagePath);
image->resize(QSize(classifierWidth, classifierHeight));
QSharedPointer<Sample> sample(new Sample(image.data(), imagePath));
float result = objed::epsilon;
classifier->prepare(sample->imagePool);
classifier->evaluate(&result, classifierWidth / 2, classifierHeight / 2);
if (result <= 0.0)
continue;
positiveSamples.append(sample);
}
for (int i = 0; i < positiveSamplesList.count(); i++)
positiveSamples.append(positiveSamplesList[i]);
ObjedConsole::printProgress(QString("%0 positive sample were generated").arg(positiveSamples.count()), 100);
return positiveSamples;
}
SampleList DatasetProcessor::prepareNegativeSamples(objed::Classifier *classifier)
{
if (classifier == 0)
throw ObjedException("Invalid passed classifier");
if (classifier->width() != classifierWidth || classifier->height() != classifierHeight)
throw ObjedException("Invalid classifier size");
ObjedOpenMP::ClassifierList clasifierList = ObjedOpenMP::multiplyClassifier(classifier);
QVector<QSharedPointer<objed::ImagePool> > imagePoolList(ObjedOpenMP::maxThreadCount());
for (int i = 0; i < ObjedOpenMP::maxThreadCount(); i++)
{
imagePoolList[i].reset(objed::ImagePool::create(), objed::ImagePool::destroy);
clasifierList[i]->prepare(imagePoolList[i].data());
}
SampleList negativeSamples;
for (int i = 0; i < negativeImagePathList.count() && negativeSamples.count() < negativeCount; i++)
{
QString imagePath = negativeImagePathList[i];
QString imageName = QFileInfo(imagePath).fileName();
int progress = 100 * i / negativeImagePathList.count();
ObjedConsole::printProgress(QString("Processing negative image %0").arg(imageName), progress);
QList<QSharedPointer<ObjedImage> > imagePyramid = prepareImagePyramid(imagePath);
qint64 period = computePeriod(imagePyramid);
for (qint64 shift = 0; shift < period && negativeSamples.count() < negativeCount; shift++)
{
QVector<SampleList> negativeSamplesList(ObjedOpenMP::maxThreadCount());
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < imagePyramid.size(); i++)
{
objed::Classifier *classifier = clasifierList[ObjedOpenMP::threadId()].data();
objed::ImagePool *imagePool = imagePoolList[ObjedOpenMP::threadId()].data();
SampleList &negativeSamples = negativeSamplesList[ObjedOpenMP::threadId()];
QSharedPointer<ObjedImage> image = imagePyramid[i];
imagePool->update(image->image());
qint64 subwindowNumber = 0;
for (int y = classifierHeight / 2; y < image->height() - classifierHeight / 2; y++)
{
for (int x = classifierWidth / 2; x < image->width() - classifierWidth / 2; x++, subwindowNumber++)
{
float result = objed::epsilon;
classifier->evaluate(&result, x, y);
if ((result > 0) && ((subwindowNumber % period) == shift))
{
QSharedPointer<ObjedImage> imageRegion = ObjedImage::create(image.data(),
QRect(x - classifierWidth / 2, y - classifierHeight / 2, classifierWidth, classifierHeight));
QSharedPointer<Sample> sample(new Sample(imageRegion.data(), imagePath));
negativeSamples.append(sample);
}
}
}
}
for (int i = 0; i < negativeSamplesList.count(); i++)
negativeSamples.append(negativeSamplesList[i]);
}
}
ObjedConsole::printProgress(QString("%0 negative sample were generated").arg(negativeSamples.count()), 100);
return negativeSamples;
}
QList<QSharedPointer<ObjedImage> > DatasetProcessor::prepareImagePyramid(const QString &imagePath)
{
QList<QSharedPointer<ObjedImage> > imagePyramid;
for (double scale = minScale; scale <= maxScale; scale *= stpScale)
{
QSharedPointer<ObjedImage> image = ObjedImage::create(imagePath);
if (image->isEmpty() == true)
continue;
int wd = std::max(1, static_cast<int>(image->width() / scale + 0.5));
int ht = std::max(1, static_cast<int>(image->height() / scale + 0.5));
image->resize(QSize(wd, ht));
imagePyramid.append(image);
}
return imagePyramid;
}
qint64 DatasetProcessor::computePeriod(const QList<QSharedPointer<ObjedImage> > &imagePyramid)
{
qint64 subwindowCount = 0;
foreach (const QSharedPointer<ObjedImage> image, imagePyramid)
{
if (image->isEmpty() == true)
continue;
subwindowCount += std::max(0, image->width() - classifierWidth) *
std::max(0, image->height() - classifierHeight);
}
return qMax<qint64>(1, subwindowCount / negativeCount);
}
| usilinsergey/objed | prj.objed/objedtraincli/src/datasetproc.cpp | C++ | bsd-2-clause | 9,290 |
#!/usr/bin/env python
# this only exists because sympy crashes IDAPython
# for general use sympy is much more complete
import traceback
import types
import copy
import operator
import random
import string
from memoize import Memoize
import numpy
import util
def collect(exp, fn):
rv = set()
def _collect(exp):
if fn(exp):
rv.add(exp)
return exp
exp.walk(_collect)
return rv
def _replace_one(expr, match, repl):
vals = WildResults()
if expr.match(match, vals):
expr = repl.substitute({wilds(w): vals[w] for w in vals})
if len(expr) > 1:
return expr[0](*[_replace_one(x, match, repl) for x in expr.args])
else:
return expr
def replace(expr, d, repeat=True):
while True:
old_expr = expr
for k in d:
expr = _replace_one(expr, k, d[k])
if old_expr == expr or not repeat:
return expr
class _Symbolic(tuple):
def match(self, other, valuestore=None):
'''
matches against a pattern, use wilds() to generate wilds
Example:
a,b = wilds('a b')
val = WildsResults()
if exp.match(a(b + 4), val):
print val.a
print val.b
'''
import match
return match.match(self, other, valuestore)
def __hash__(self):
return hash(self.name)
def simplify(self):
import simplify
return simplify.simplify(self)
def walk(self, *fns):
if len(fns) > 1:
def _(exp):
for f in fns:
exp = f(exp)
return exp
return self.walk(_)
exp = self
fn = fns[0]
if len(exp) == 1:
oldexp = exp
exp = fn(exp)
while exp != oldexp:
oldexp = exp
exp = fn(exp)
else:
args = list(map(lambda x: x.walk(fn), exp.args))
oldexp = self
exp = fn(fn(exp[0])(*args))
#while exp != oldexp:
# print '%s => %s' % (oldexp, exp)
# oldexp = exp
# exp = exp.walk(fn)
if util.DEBUG and exp != self:
#print '%s => %s (%s)' % (self, exp, fn)
pass
return exp
def _dump(self):
return {
'name': self.name,
'id': id(self)
}
def __contains__(self, exp):
rv = {}
rv['val'] = False
def _(_exp):
if _exp.match(exp):
rv['val'] = True
return _exp
self.walk(_)
return rv['val']
def substitute(self, subs):
'''
takes a dictionary of substitutions
returns itself with substitutions made
'''
if self in subs:
self = subs[self]
return self
def compile(self, *arguments):
'''compiles a symbolic expression with arguments to a python function'''
def _compiled_func(*args):
assert len(args) == len(arguments)
argdic = {}
for i in range(len(args)):
argdic[arguments[i]] = args[i]
rv = self.substitute(argdic).simplify()
return desymbolic(rv)
return _compiled_func
def __eq__(self, other):
#return type(self) == type(other) and self.name == other.name
return id(self) == id(other)
def __ne__(self, other):
return not self.__eq__(other)
def __getitem__(self, num):
if num == 0:
return self
raise BaseException("Invalid index")
def __len__(self):
return 1
# comparison operations notice we don't override __eq__
def __gt__(self, obj):
return Fn.GreaterThan(self, obj)
def __ge__(self, obj):
return Fn.GreaterThanEq(self, obj)
def __lt__(self, obj):
return Fn.LessThan(self, obj)
def __le__(self, obj):
return Fn.LessThanEq(self, obj)
# arithmetic overrides
def __mul__(self, other):
return Fn.Mul(self, other)
def __pow__(self, other):
return Fn.Pow(self, other)
def __rpow__(self, other):
return Fn.Pow(other, self)
def __div__(self, other):
return Fn.Div(self, other)
def __add__(self, other):
return Fn.Add(self, other)
def __sub__(self, other):
return Fn.Sub(self, other)
def __or__(self, other):
return Fn.BitOr(self, other)
def __and__(self, other):
return Fn.BitAnd(self, other)
def __xor__(self, other):
return Fn.BitXor(self, other)
def __rmul__(self, other):
return Fn.Mul(other, self)
def __rdiv__(self, other):
return Fn.Div(other, self)
def __radd__(self, other):
return Fn.Add(other, self)
def __rsub__(self, other):
return Fn.Sub(other, self)
def __ror__(self, other):
return Fn.BitOr(other, self)
def __rand__(self, other):
return Fn.BitAnd(other, self)
def __rxor__(self, other):
return Fn.BitXor(other, self)
def __rshift__(self, other):
return Fn.RShift(self, other)
def __lshift__(self, other):
return Fn.LShift(self, other)
def __rrshift__(self, other):
return Fn.RShift(other, self)
def __rlshift__(self, other):
return Fn.LShift(other, self)
def __neg__(self):
return self * -1
class _KnownValue(_Symbolic):
def value(self):
raise BaseException('not implemented')
class Boolean(_KnownValue):
@Memoize
def __new__(typ, b):
self = _KnownValue.__new__(typ)
self.name = str(b)
self.boolean = b
return self
def value(self):
return bool(self.boolean)
def __str__(self):
return str(self.boolean)
def __repr__(self):
return str(self)
def __eq__(self, other):
if isinstance(other, Boolean):
return bool(self.boolean) == bool(other.boolean)
elif isinstance(other, _Symbolic):
return other.__eq__(self)
else:
return bool(self.boolean) == other
class Number(_KnownValue):
IFORMAT = str
FFORMAT = str
@Memoize
def __new__(typ, n):
n = float(n)
self = _KnownValue.__new__(typ)
self.name = str(n)
self.n = n
return self
@property
def is_integer(self):
return self.n.is_integer()
def value(self):
return self.n
def __eq__(self, other):
if isinstance(other, Number):
return self.n == other.n
elif isinstance(other, _Symbolic):
return other.__eq__(self)
else:
return self.n == other
def __ne__(self, other):
if isinstance(other, _Symbolic):
return super(Number, self).__ne__(other)
else:
return self.n != other
def __str__(self):
if self.n.is_integer():
return Number.IFORMAT(int(self.n))
else:
return Number.FFORMAT(self.n)
def __repr__(self):
return str(self)
class WildResults(object):
def __init__(self):
self._hash = {}
def clear(self):
self._hash.clear()
def __setitem__(self, idx, val):
self._hash.__setitem__(idx, val)
def __contains__(self, idx):
return idx in self._hash
def __getitem__(self, idx):
return self._hash[idx]
def __getattr__(self, idx):
return self[idx]
def __iter__(self):
return self._hash.__iter__()
def __str__(self):
return str(self._hash)
def __repr__(self):
return str(self)
def __len__(self):
return len(self._hash)
class Wild(_Symbolic):
'''
wilds will be equal to anything, and are used for pattern matching
'''
@Memoize
def __new__(typ, name, **kargs):
self = _Symbolic.__new__(typ)
self.name = name
self.kargs = kargs
return self
def __str__(self):
return self.name
def __repr__(self):
return str(self)
def __call__(self, *args):
return Fn(self, *args)
def _dump(self):
return {
'type': type(self),
'name': self.name,
'kargs': self.kargs,
'id': id(self)
}
class Symbol(_Symbolic):
'''
symbols with the same name and kargs will be equal
(and in fact are guaranteed to be the same instance)
'''
@Memoize
def __new__(typ, name, **kargs):
self = Wild.__new__(typ, name)
self.name = name
self.kargs = kargs
self.is_integer = False # set to true to force domain to integers
self.is_bitvector = 0 # set to the size of the bitvector if it is a bitvector
self.is_bool = False # set to true if the symbol represents a boolean value
return self
def __str__(self):
return self.name
def __repr__(self):
return str(self)
def __call__(self, *args):
return Fn(self, *args)
def _dump(self):
return {
'type': type(self),
'name': self.name,
'kargs': self.kargs,
'id': id(self)
}
class Fn(_Symbolic):
@Memoize
def __new__(typ, fn, *args):
'''
arguments: Function, *arguments, **kargs
valid keyword args:
commutative (default False) - order of operands is unimportant
'''
if None in args:
raise BaseException('NONE IN ARGS %s %s' % (fn, args))
if not isinstance(fn, _Symbolic):
fn = symbolic(fn)
return Fn.__new__(typ, fn, *args)
for i in args:
if not isinstance(i, _Symbolic):
args = list(map(symbolic, args))
return Fn.__new__(typ, fn, *args)
self = _Symbolic.__new__(typ)
kargs = fn.kargs
self.kargs = fn.kargs
self.name = fn.name
self.fn = fn
self.args = args
#import simplify
#rv = simplify.simplify(self)
return self
def _dump(self):
return {
'id': id(self),
'name': self.name,
'fn': self.fn._dump(),
'kargs': self.kargs,
'args': list(map(lambda x: x._dump(), self.args)),
'orig kargs': self.orig_kargs,
'orig args': list(map(lambda x: x._dump(), self.orig_args))
}
def __call__(self, *args):
return Fn(self, *args)
def substitute(self, subs):
args = list(map(lambda x: x.substitute(subs), self.args))
newfn = self.fn.substitute(subs)
self = Fn(newfn, *args)
if self in subs:
self = subs[self]
return self
def recursive_substitute(self, subs):
y = self
while True:
x = y.substitute(subs)
if x == y:
return x
y = x
def __getitem__(self, n):
if n == 0:
return self.fn
return self.args[n - 1]
def __len__(self):
return len(self.args) + 1
def _get_assoc_arguments(self):
import simplify
rv = []
args = list(self.args)
def _(a, b):
if (isinstance(a, Fn) and a.fn == self.fn) and not (isinstance(b, Fn) and b.fn == self.fn):
return -1
if (isinstance(b, Fn) and b.fn == self.fn) and not (isinstance(a, Fn) and a.fn == self.fn):
return 1
return simplify._order(a, b)
args.sort(_)
for i in args:
if isinstance(i, Fn) and i.fn == self.fn:
for j in i._get_assoc_arguments():
rv.append(j)
else:
rv.append(i)
return rv
@staticmethod
def LessThan(lhs, rhs):
return Fn(stdops.LessThan, lhs, rhs)
@staticmethod
def GreaterThan(lhs, rhs):
return Fn(stdops.GreaterThan, lhs, rhs)
@staticmethod
def LessThanEq(lhs, rhs):
return Fn(stdops.LessThanEq, lhs, rhs)
@staticmethod
def GreaterThanEq(lhs, rhs):
return Fn(stdops.GreaterThanEq, lhs, rhs)
@staticmethod
def Add(lhs, rhs):
return Fn(stdops.Add, lhs, rhs)
@staticmethod
def Sub(lhs, rhs):
return Fn(stdops.Sub, lhs, rhs)
@staticmethod
def Div(lhs, rhs):
return Fn(stdops.Div, lhs, rhs)
@staticmethod
def Mul(lhs, rhs):
return Fn(stdops.Mul, lhs, rhs)
@staticmethod
def Pow(lhs, rhs):
return Fn(stdops.Pow, lhs, rhs)
@staticmethod
def RShift(lhs, rhs):
return Fn(stdops.RShift, lhs, rhs)
@staticmethod
def LShift(lhs, rhs):
return Fn(stdops.LShift, lhs, rhs)
@staticmethod
def BitAnd(lhs, rhs):
return Fn(stdops.BitAnd, lhs, rhs)
@staticmethod
def BitOr(lhs, rhs):
return Fn(stdops.BitOr, lhs, rhs)
@staticmethod
def BitXor(lhs, rhs):
return Fn(stdops.BitXor, lhs, rhs)
def __str__(self):
if isinstance(self.fn, Symbol) and not self.name[0].isalnum() and len(self.args) == 2:
return '(%s %s %s)' % (self.args[0], self.name, self.args[1])
return '%s(%s)' % (self.fn, ','.join(map(str, self.args)))
def __repr__(self):
return str(self)
def symbols(symstr=None, **kargs):
'''
takes a string of symbols seperated by whitespace
returns a tuple of symbols
'''
if symstr == None:
syms = [''.join(random.choice(string.ascii_lowercase) for x in range(12))]
else:
syms = symstr.split(' ')
if len(syms) == 1:
return Symbol(syms[0], **kargs)
rv = []
for i in syms:
rv.append(Symbol(i, **kargs))
return tuple(rv)
def wilds(symstr, **kargs):
'''
wilds should match anything
'''
syms = symstr.split(' ')
if len(syms) == 1:
return Wild(syms[0], **kargs)
rv = []
for i in syms:
rv.append(Wild(i, **kargs))
return tuple(rv)
def wild(name=None, **kargs):
if name == None:
name = ''.join(random.choice(string.ascii_lowercase) for x in range(12))
return Wild(name, **kargs)
def symbolic(obj, **kargs):
'''
makes the symbolic version of an object
'''
if type(obj) in [type(0), type(0.0), type(0L), numpy.int32]:
return Number(obj, **kargs)
elif type(obj) == type('str'):
return Symbol(obj, **kargs)
elif type(obj) == type(True):
return Boolean(obj, **kargs)
elif isinstance(obj, _Symbolic):
return obj
else:
msg = "Unknown type (%s) %s passed to symbolic" % (type(obj), obj)
raise BaseException(msg)
def desymbolic(s):
'''
returns a numeric version of s
'''
if type(s) in (int,long,float):
return s
s = s.simplify()
if not isinstance(s, Number):
raise BaseException("Only numbers can be passed to desymbolic")
return s.value()
import stdops
| bniemczyk/symbolic | symath/core.py | Python | bsd-2-clause | 14,038 |
/*
* Copyright (c) 2017. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.vcf.eval;
import com.reeltwo.jumble.annotations.TestClass;
import com.rtg.util.BasicLinkedListNode;
/**
* Prefer paths that maximise total number of included variants (baseline + called).
* Includes some other tie-breaking heuristics that prefer more aesthetically pleasing matches.
*/
@TestClass("com.rtg.vcf.eval.PathTest")
final class MaxSumBoth implements PathPreference {
@Override
public Path better(Path first, Path second) {
// Prefer paths that maximise total number of included variants (baseline + called)
BasicLinkedListNode<OrientedVariant> firstIncluded = first.mCalledPath.getIncluded();
BasicLinkedListNode<OrientedVariant> secondIncluded = second.mCalledPath.getIncluded();
int firstSize = firstIncluded == null ? 0 : firstIncluded.size();
int secondSize = secondIncluded == null ? 0 : secondIncluded.size();
firstIncluded = first.mBaselinePath.getIncluded();
secondIncluded = second.mBaselinePath.getIncluded();
firstSize += firstIncluded == null ? 0 : firstIncluded.size();
secondSize += secondIncluded == null ? 0 : secondIncluded.size();
if (firstSize == secondSize) {
// Tie break equivalently scoring paths for greater aesthetics
if (firstIncluded != null && secondIncluded != null) {
// Prefer solutions that minimize discrepencies between baseline and call counts since last sync point
final int fDelta = Math.abs(first.mBSinceSync - first.mCSinceSync);
final int sDelta = Math.abs(second.mBSinceSync - second.mCSinceSync);
if (fDelta != sDelta) {
return fDelta < sDelta ? first : second;
}
// Prefer solutions that sync more regularly (more likely to be "simpler")
final int syncDelta = (first.mSyncPointList == null ? 0 : first.mSyncPointList.getValue()) - (second.mSyncPointList == null ? 0 : second.mSyncPointList.getValue());
if (syncDelta != 0) {
return syncDelta > 0 ? first : second;
}
/*
Diagnostic.developerLog("Sum: Remaining break at: " + first.mBaselinePath.getPosition() + " sum = " + firstSize
+ " first = (" + first.mBSinceSync + "," + first.mCSinceSync + ")"
+ " second = (" + second.mBSinceSync + "," + second.mCSinceSync + ")"
+ " " + first.inSync() + "," + second.inSync() + " syncdelta=" + syncDelta
);
*/
// At this point break ties arbitrarily based on allele ordering
return (firstIncluded.getValue().alleleId() < secondIncluded.getValue().alleleId()) ? first : second;
}
}
return firstSize > secondSize ? first : second;
}
}
| RealTimeGenomics/rtg-tools | src/com/rtg/vcf/eval/MaxSumBoth.java | Java | bsd-2-clause | 4,037 |
#include <mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_AceEnumerator.h>
#include <mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_GenericAce.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/mscorlib_System_String.h>
namespace mscorlib
{
namespace System
{
namespace Security
{
namespace AccessControl
{
//Public Methods
mscorlib::System::Boolean AceEnumerator::MoveNext()
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "AceEnumerator", 0, NULL, "MoveNext", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
void AceEnumerator::Reset()
{
Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "AceEnumerator", 0, NULL, "Reset", __native_object__, 0, NULL, NULL, NULL);
}
//Get Set Properties Methods
// Get:Current
mscorlib::System::Security::AccessControl::GenericAce AceEnumerator::get_Current() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "AceEnumerator", 0, NULL, "get_Current", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::Security::AccessControl::GenericAce(__result__);
}
}
}
}
}
| brunolauze/MonoNative | MonoNative/mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_AceEnumerator.cpp | C++ | bsd-2-clause | 1,376 |
<?php
namespace AppZap\PHPFramework\Persistence;
use AppZap\PHPFramework\Configuration\Configuration;
/**
* Database wrapper class
*/
class DatabaseConnection {
const QUERY_MODE_LIKE = 1;
const QUERY_MODE_NOT = 2;
const QUERY_MODE_REGULAR = 3;
const QUERY_MODE_LESS = 4;
const QUERY_MODE_GREATER = 5;
const QUERY_MODE_LESS_OR_EQUAL = 6;
const QUERY_MODE_GREATER_OR_EQUAL = 7;
/**
* @var \PDO
*/
protected $connection = NULL;
/**
* Connects to the MySQL server, sets the charset for the connection and
* selects the database
*/
public function connect() {
if (!($this->connection instanceof \PDO)) {
$dbConfiguration = Configuration::getSection('phpframework', 'db');
$dsn = 'mysql:host=' . $dbConfiguration['mysql.host'] . ';dbname=' . $dbConfiguration['mysql.database'];
$this->connection = new \PDO($dsn, $dbConfiguration['mysql.user'], $dbConfiguration['mysql.password']);
if (isset($dbConfiguration['charset'])) {
$this->setCharset($dbConfiguration['charset']);
}
}
}
/**
* Checks whether the connection to the database is established
*
* @return bool
*/
public function isConnected() {
return (bool) $this->connection;
}
/**
* Sets the charset for transfer encoding
*
* @param string $charset Connection transfer charset
*/
protected function setCharset($charset) {
$sql = 'SET NAMES ' . $charset;
$this->execute($sql);
}
/**
* Executes the passed SQL statement
*
* @param string $sql Finally escaped SQL statement
* @return array Result data of the query
*/
public function query($sql) {
$result = $this->execute($sql);
$rows = [];
foreach ($result as $row) {
$rows[] = $row;
}
return $rows;
}
/**
* Executes the passed SQL statement
*
* @param string $sql Finally escaped SQL statement
* @param array $parameters
* @return resource Result data of the query
* @throws DatabaseQueryException
*/
public function execute($sql, $parameters = []) {
$this->connect();
// execute the query
$statement = $this->connection->prepare($sql);
try {
$success = $statement->execute($parameters);
} catch(\PDOException $e) {
// under HHVM we get a \PDOException instead of FALSE if the query fails
$success = FALSE;
}
if ($success === FALSE) {
throw new DatabaseQueryException('Database query failed. Error: "' . print_r($statement->errorInfo(), 1) . '". Query was: "' . $statement->queryString . '". Parameters: ' . print_r($parameters, 1), 1415219261);
}
return $statement->fetchAll();
}
/**
* Returns the auto increment ID of the last query
*
* @return int
*/
public function lastId() {
$this->connect();
return $this->connection->lastInsertId();
}
/**
* Lists the fields of a table
*
* @param string $table Name of the table
* @return array with field names
*/
public function fields($table) {
$sql = 'SHOW COLUMNS FROM ' . $table;
$result = $this->query($sql);
$fields = [];
foreach ($result as $row) {
$fields[] = $row['Field'];
}
return $fields;
}
/**
* Inserts dataset into the table and returns the auto increment key for it
*
* @param string $table Name of the table
* @param array $input Dataset to insert into the table
* @param boolean $ignore Use "INSERT IGNORE" for the query
* @return int
*/
public function insert($table, $input = [], $ignore = FALSE) {
$ignore = $ignore ? ' IGNORE' : '';
if (count($input)) {
$values = ' SET ' . $this->values($input);
} else {
$values = '(id) VALUES (NULL)';
}
$this->execute('INSERT' . $ignore . ' INTO ' . $table . $values);
return $this->lastId();
}
/**
* Replaces dataset in the table
*
* @param string $table Name of the table
* @param array $input Dataset to replace in the table
* @return resource
*/
public function replace($table, $input) {
return $this->execute('REPLACE INTO ' . $table . ' SET ' . $this->values($input));
}
/**
* Updates datasets in the table
*
* @param string $table Name of the table
* @param array $input Dataset to write over the old one into the table
* @param array $where Selector for the datasets to overwrite
* @return resource
*/
public function update($table, $input, $where) {
$sql = sprintf(
'UPDATE %s SET %s%s',
$table,
$this->values($input),
$this->where($where)
);
return $this->execute($sql);
}
/**
* Deletes datasets from table
*
* @param string $table Name of the table
* @param array $where Selector for the datasets to delete
*/
public function delete($table, $where = NULL) {
$sql = sprintf(
'DELETE FROM %s%s',
$table,
$this->where($where)
);
$this->execute($sql);
}
/**
* Truncates a table (empties it and resets autoincrements)
*
* @param string $table
*/
public function truncate($table) {
$sql = sprintf('TRUNCATE %s', $table);
$this->execute($sql);
}
/**
* Selects datasets from table
*
* @param string $table Name of the table
* @param string $select Fields to retrieve from table
* @param array $where Selector for the datasets to select
* @param string $order Already escaped content of order clause
* @param int $offset First index of dataset to retrieve
* @param int $limit Number of entries to retrieve
* @return array
*/
public function select($table, $select = '*', $where = NULL, $order = '', $offset = 0, $limit = NULL) {
$sql = sprintf(
'SELECT %s FROM %s%s%s%s',
$select,
$table,
$this->where($where),
$this->order($order),
$this->limit($limit),
$this->offset($offset)
);
return $this->query($sql);
}
/**
* Select one row from table or FALSE if there is no row
*
* @param string $table Name of the table
* @param string $select Fields to retrieve from table
* @param array $where Selector for the datasets to select
* @param string $order Already escaped content of order clause
* @return array|boolean
*/
public function row($table, $select = '*', $where = NULL, $order = NULL) {
$result = $this->select($table, $select, $where, $order, 0, 1);
return (count($result) > 0) ? $result[0] : FALSE;
}
/**
* Select one field from table
*
* @param string $table Name of the table
* @param string $field Name of the field to return
* @param array $where Selector for the datasets to select
* @param string $order Already escaped content of order clause
* @return mixed
*/
public function field($table, $field, $where = NULL, $order = NULL) {
$result = $this->row($table, $field, $where, $order);
return $result[$field];
}
/**
* Counts the rows matching the where clause in table
*
* @param string $table Name of the table
* @param array $where Selector for the datasets to select
* @return int
*/
public function count($table, $where = NULL) {
$result = $this->row($table, 'count(1)', $where);
return ($result) ? (int) $result['count(1)'] : 0;
}
/**
* Selects the minimum of a column or FALSE if there is no data
*
* @param string $table Name of the table
* @param string $column Name of column to retrieve
* @param array $where Selector for the datasets to select
* @return int|boolean
*/
public function min($table, $column, $where = NULL) {
$result = $this->row($table, 'MIN(`' . $column . '`) as min', $where);
return ($result) ? $result['min'] : FALSE;
}
/**
* Selects the maximum of a column or FALSE if there is no data
*
* @param string $table Name of the table
* @param string $column Name of column to retrieve
* @param string|array $where Selector for the datasets to select
* @return int|boolean
*/
public function max($table, $column, $where = NULL) {
$result = $this->row($table, 'MAX(`' . $column . '`) as max', $where);
return ($result) ? $result['max'] : FALSE;
}
/**
* Selects the sum of a column
*
* @param string $table Name of the table
* @param string $column Name of column to retrieve
* @param string|array $where Selector for the datasets to select
* @return int
*/
public function sum($table, $column, $where = NULL) {
$result = $this->row($table, 'SUM(`' . $column . '`) as sum', $where);
return ($result) ? $result['sum'] : 0;
}
/**
* @param array $input
* @return string
*/
protected function values($input) {
$retval = [];
foreach ($input as $key => $value) {
if ($value === NULL) {
$retval[] = '`' . $key . '`' . ' = NULL';
} else {
$retval[] = '`' . $key . '`' . ' = ' . $this->escape($value);
}
}
return implode(', ', $retval);
}
/**
* Escape values
*
* @param mixed $value
* @return string
*/
public function escape($value) {
if ($value === NULL) {
return $value;
}
$this->connect();
return $this->connection->quote((string)$value);
}
/**
* @param string $order
* @return string
*/
protected function order($order = '') {
if ($order) {
$order = sprintf(
' ORDER BY %s',
$order
);
}
return $order;
}
/**
* @param int $limit
* @return string
*/
protected function limit($limit = 0) {
if ($limit > 0) {
return sprintf(
' LIMIT %d',
$limit
);
} else {
return '';
}
}
/**
* @param int $offset
* @return string
*/
protected function offset($offset = 0) {
if ($offset > 0) {
return sprintf(
' OFFSET %d',
$offset
);
} else {
return '';
}
}
/**
* @param array $where
* @param string $method
* @return string
* @throws \InvalidArgumentException
*/
protected function where($where, $method = 'AND') {
if ($where === NULL) {
return '';
}
if (!is_array($where)) {
throw new \InvalidArgumentException('where clause has to be an associative array', 1409767864);
}
if (!count($where)) {
return '';
}
$constraints = [];
foreach ($where AS $field => $value) {
switch(substr($field, -2)) {
case '<=':
$queryMode = self::QUERY_MODE_LESS_OR_EQUAL;
$field = substr($field, 0, -2);
break;
case '>=':
$queryMode = self::QUERY_MODE_GREATER_OR_EQUAL;
$field = substr($field, 0, -2);
break;
default:
switch(substr($field, -1)) {
case '!':
$queryMode = self::QUERY_MODE_NOT;
$field = substr($field, 0, -1);
break;
case '?':
$queryMode = self::QUERY_MODE_LIKE;
$field = substr($field, 0, -1);
break;
case '<':
$queryMode = self::QUERY_MODE_LESS;
$field = substr($field, 0, -1);
break;
case '>':
$queryMode = self::QUERY_MODE_GREATER;
$field = substr($field, 0, -1);
break;
default:
$queryMode = self::QUERY_MODE_REGULAR;
}
}
if ($queryMode >= self::QUERY_MODE_LESS && $queryMode <= self::QUERY_MODE_GREATER_OR_EQUAL) {
if (is_array($value)) {
$value = array_map('floatval', $value);
} else {
$value = (float) $value;
}
} else {
if (is_array($value)) {
$value = array_map([$this, 'escape'], $value);
} else {
$value = $this->escape($value);
}
}
if ($queryMode === self::QUERY_MODE_LIKE && is_array($value)) {
// LIKE and multiple values needs a special syntax in SQL
$constraints[] = '(`' . $field . '` LIKE ' . implode(' OR `' . $field . '` LIKE ', $value) . ')';
} elseif ($queryMode >= self::QUERY_MODE_LESS && $queryMode <= self::QUERY_MODE_GREATER_OR_EQUAL && is_array($value)) {
$constraints[] = $this->whereMultipleInequationValues($value, $queryMode, $field);
} else {
if (is_array($value)) {
$constraints[] = $this->whereMultipleValues($value, $queryMode, $field);
} elseif($value === NULL) {
$constraints[] = $this->whereNullValue($queryMode, $field);
} else {
$constraints[] = $this->whereSingleValue($value, $queryMode, $field);
}
}
}
return sprintf(
' WHERE %s',
implode(' ' . $method . ' ', $constraints)
);
}
/**
* @param array $values
* @param int $queryMode
* @param string $field
* @return string
*/
protected function whereMultipleValues($values, $queryMode, $field) {
$value = implode(', ', $values);
if ($queryMode === self::QUERY_MODE_NOT) {
$operand = 'NOT IN';
} else {
$operand = 'IN';
}
return sprintf('`%s` %s (%s)', $field, $operand, $value);
}
/**
* @param string $value
* @param int $queryMode
* @param string $field
* @return string
*/
protected function whereSingleValue($value, $queryMode, $field) {
switch ($queryMode) {
case self::QUERY_MODE_LIKE:
$operand = 'LIKE';
break;
case self::QUERY_MODE_NOT:
$operand = '!=';
break;
case self::QUERY_MODE_LESS:
$operand = '<';
break;
case self::QUERY_MODE_LESS_OR_EQUAL:
$operand = '<=';
break;
case self::QUERY_MODE_GREATER:
$operand = '>';
break;
case self::QUERY_MODE_GREATER_OR_EQUAL:
$operand = '>=';
break;
default:
$operand = '=';
}
return sprintf('`%s` %s %s', $field, $operand, $value);
}
/**
* @param int $queryMode
* @param string $field
* @return string
*/
protected function whereNullValue($queryMode, $field) {
switch ($queryMode) {
case self::QUERY_MODE_NOT:
$operand = 'IS NOT';
break;
case self::QUERY_MODE_LIKE:
default:
$operand = 'IS';
}
return sprintf('`%s` %s %s', $field, $operand, 'NULL');
}
/**
* @param string $value
* @param int $queryMode
* @param string $field
* @return string
* @throws \InvalidArgumentException
*/
protected function whereMultipleInequationValues($value, $queryMode, $field) {
switch ($queryMode) {
case self::QUERY_MODE_LESS:
$operand = '<';
break;
case self::QUERY_MODE_LESS_OR_EQUAL:
$operand = '<=';
break;
case self::QUERY_MODE_GREATER:
$operand = '>';
break;
case self::QUERY_MODE_GREATER_OR_EQUAL:
$operand = '>=';
break;
default:
throw new \InvalidArgumentException('whereMultipleInequationValues must be called with an inequation $queryMode', 1421419086);
}
return '(`' . $field . '` ' . $operand . ' ' . implode(' AND `' . $field . '` ' . $operand . ' ', $value) . ')';
}
}
| app-zap/PHPFramework | classes/Persistence/DatabaseConnection.php | PHP | bsd-2-clause | 15,168 |
/*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.scene.plugins.blender.file;
import com.jme3.scene.plugins.blender.BlenderContext;
import com.jme3.scene.plugins.blender.exceptions.BlenderFileException;
import java.util.HashMap;
import java.util.Map;
/**
* The data block containing the description of the file.
* @author Marcin Roguski (Kaelthas)
*/
public class DnaBlockData {
private static final int SDNA_ID = 'S' << 24 | 'D' << 16 | 'N' << 8 | 'A'; // SDNA
private static final int NAME_ID = 'N' << 24 | 'A' << 16 | 'M' << 8 | 'E'; // NAME
private static final int TYPE_ID = 'T' << 24 | 'Y' << 16 | 'P' << 8 | 'E'; // TYPE
private static final int TLEN_ID = 'T' << 24 | 'L' << 16 | 'E' << 8 | 'N'; // TLEN
private static final int STRC_ID = 'S' << 24 | 'T' << 16 | 'R' << 8 | 'C'; // STRC
/** Structures available inside the file. */
private final Structure[] structures;
/** A map that helps finding a structure by type. */
private final Map<String, Structure> structuresMap;
/**
* Constructor. Loads the block from the given stream during instance creation.
* @param inputStream
* the stream we read the block from
* @param blenderContext
* the blender context
* @throws BlenderFileException
* this exception is throw if the blend file is invalid or somehow corrupted
*/
public DnaBlockData(BlenderInputStream inputStream, BlenderContext blenderContext) throws BlenderFileException {
int identifier;
// reading 'SDNA' identifier
identifier = inputStream.readByte() << 24 | inputStream.readByte() << 16 | inputStream.readByte() << 8 | inputStream.readByte();
if (identifier != SDNA_ID) {
throw new BlenderFileException("Invalid identifier! '" + this.toString(SDNA_ID) + "' expected and found: " + this.toString(identifier));
}
// reading names
identifier = inputStream.readByte() << 24 | inputStream.readByte() << 16 | inputStream.readByte() << 8 | inputStream.readByte();
if (identifier != NAME_ID) {
throw new BlenderFileException("Invalid identifier! '" + this.toString(NAME_ID) + "' expected and found: " + this.toString(identifier));
}
int amount = inputStream.readInt();
if (amount <= 0) {
throw new BlenderFileException("The names amount number should be positive!");
}
String[] names = new String[amount];
for (int i = 0; i < amount; ++i) {
names[i] = inputStream.readString();
}
// reding types
inputStream.alignPosition(4);
identifier = inputStream.readByte() << 24 | inputStream.readByte() << 16 | inputStream.readByte() << 8 | inputStream.readByte();
if (identifier != TYPE_ID) {
throw new BlenderFileException("Invalid identifier! '" + this.toString(TYPE_ID) + "' expected and found: " + this.toString(identifier));
}
amount = inputStream.readInt();
if (amount <= 0) {
throw new BlenderFileException("The types amount number should be positive!");
}
String[] types = new String[amount];
for (int i = 0; i < amount; ++i) {
types[i] = inputStream.readString();
}
// reading lengths
inputStream.alignPosition(4);
identifier = inputStream.readByte() << 24 | inputStream.readByte() << 16 | inputStream.readByte() << 8 | inputStream.readByte();
if (identifier != TLEN_ID) {
throw new BlenderFileException("Invalid identifier! '" + this.toString(TLEN_ID) + "' expected and found: " + this.toString(identifier));
}
int[] lengths = new int[amount];// theamount is the same as int types
for (int i = 0; i < amount; ++i) {
lengths[i] = inputStream.readShort();
}
// reading structures
inputStream.alignPosition(4);
identifier = inputStream.readByte() << 24 | inputStream.readByte() << 16 | inputStream.readByte() << 8 | inputStream.readByte();
if (identifier != STRC_ID) {
throw new BlenderFileException("Invalid identifier! '" + this.toString(STRC_ID) + "' expected and found: " + this.toString(identifier));
}
amount = inputStream.readInt();
if (amount <= 0) {
throw new BlenderFileException("The structures amount number should be positive!");
}
structures = new Structure[amount];
structuresMap = new HashMap<String, Structure>(amount);
for (int i = 0; i < amount; ++i) {
structures[i] = new Structure(inputStream, names, types, blenderContext);
if (structuresMap.containsKey(structures[i].getType())) {
throw new BlenderFileException("Blend file seems to be corrupted! The type " + structures[i].getType() + " is defined twice!");
}
structuresMap.put(structures[i].getType(), structures[i]);
}
}
/**
* This method returns the amount of the structures.
* @return the amount of the structures
*/
public int getStructuresCount() {
return structures.length;
}
/**
* This method returns the structure of the given index.
* @param index
* the index of the structure
* @return the structure of the given index
*/
public Structure getStructure(int index) {
try {
return (Structure) structures[index].clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Structure should be clonable!!!", e);
}
}
/**
* This method returns a structure of the given name. If the name does not exists then null is returned.
* @param name
* the name of the structure
* @return the required structure or null if the given name is inapropriate
*/
public Structure getStructure(String name) {
try {
return (Structure) structuresMap.get(name).clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
/**
* This method indicates if the structure of the given name exists.
* @param name
* the name of the structure
* @return true if the structure exists and false otherwise
*/
public boolean hasStructure(String name) {
return structuresMap.containsKey(name);
}
/**
* This method converts the given identifier code to string.
* @param code
* the code taht is to be converted
* @return the string value of the identifier
*/
private String toString(int code) {
char c1 = (char) ((code & 0xFF000000) >> 24);
char c2 = (char) ((code & 0xFF0000) >> 16);
char c3 = (char) ((code & 0xFF00) >> 8);
char c4 = (char) (code & 0xFF);
return String.valueOf(c1) + c2 + c3 + c4;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("=============== ").append(SDNA_ID).append('\n');
for (Structure structure : structures) {
stringBuilder.append(structure.toString()).append('\n');
}
return stringBuilder.append("===============").toString();
}
}
| chototsu/MikuMikuStudio | engine/src/blender/com/jme3/scene/plugins/blender/file/DnaBlockData.java | Java | bsd-2-clause | 9,171 |
from ...utils.bitfun import encode_imm32, align, wrap_negative
from ..encoding import Relocation
from .isa import ArmToken, arm_isa
@arm_isa.register_relocation
class Rel8Relocation(Relocation):
name = "rel8"
token = ArmToken
field = "imm8"
def calc(self, sym_value, reloc_value):
assert sym_value % 2 == 0
offset = sym_value - (align(reloc_value, 2) + 4)
assert offset in range(-256, 254, 2), str(offset)
return wrap_negative(offset >> 1, 8)
@arm_isa.register_relocation
class Imm24Relocation(Relocation):
name = "imm24"
token = ArmToken
field = "imm24"
def calc(self, sym_value, reloc_value):
assert sym_value % 4 == 0
assert reloc_value % 4 == 0
offset = sym_value - (reloc_value + 8)
return wrap_negative(offset >> 2, 24)
@arm_isa.register_relocation
class LdrImm12Relocation(Relocation):
name = "ldr_imm12"
token = ArmToken
def apply(self, sym_value, data, reloc_value):
assert sym_value % 4 == 0
assert reloc_value % 4 == 0
offset = sym_value - (reloc_value + 8)
U = 1
if offset < 0:
offset = -offset
U = 0
assert offset < 4096, "{} < 4096 {} {}".format(offset, sym_value, data)
data[2] |= U << 7
data[1] |= (offset >> 8) & 0xF
data[0] = offset & 0xFF
return data
@arm_isa.register_relocation
class AdrImm12Relocation(Relocation):
name = "adr_imm12"
token = ArmToken
def apply(self, sym_value, data, reloc_value):
assert sym_value % 4 == 0
assert reloc_value % 4 == 0
offset = sym_value - (reloc_value + 8)
U = 2
if offset < 0:
offset = -offset
U = 1
assert offset < 4096
offset = encode_imm32(offset)
data[2] |= U << 6
data[1] |= (offset >> 8) & 0xF
data[0] = offset & 0xFF
return data
| windelbouwman/ppci-mirror | ppci/arch/arm/arm_relocations.py | Python | bsd-2-clause | 1,941 |
/**
* Copyright (c) 2014 Samsung Electronics, Inc.,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.samsung.sec.dexter.executor.cli;
import com.samsung.sec.dexter.core.checker.Checker;
import java.io.File;
import java.util.List;
public interface IDexterCLIOption {
public enum CommandMode {
NONE, CREATE_ACCOUNT, STATIC_ANALYSIS
};
/**
* @param args
* it should be parameters from main method.
*/
void createCliOptionFromArguments(final String[] args);
/**
* @return full file path of dexter_cfg.json file, which has configurations
* to run Dexter CLI such as project name, source folder path, etc.
*/
String getConfigFilePath();
boolean isStandAloneMode();
boolean isAsynchronousMode();
boolean isSpecifiedCheckerEnabledMode();
boolean isTargetFilesOptionEnabled();
List<String> getTargetFileFullPathList();
String getUserId();
String getUserPassword();
boolean checkCheckerEnablenessByCliOption(final String toolName, final String language, Checker checker);
boolean isXml2File();
boolean isXmlFile();
boolean isJsonFile();
File getXml2ResultFile();
File getXmlResultFile();
File getJsonResultFile();
CommandMode getCommandMode();
int getServerPort();
String getServerHostIp();
void setDexterServerIP(final String dexterServerIp);
void setDexterServerPort(final int dexterServerPort);
}
| marchpig/Dexter | project/dexter-executor/src/java/com/samsung/sec/dexter/executor/cli/IDexterCLIOption.java | Java | bsd-2-clause | 2,743 |
using UnityEngine;
using System.Collections;
namespace EA4S.MixedLetters
{
public class RotateButtonController : MonoBehaviour
{
public BoxCollider boxCollider;
public DropZoneController dropZone;
// Use this for initialization
void Start()
{
IInputManager inputManager = MixedLettersConfiguration.Instance.Context.GetInputManager();
inputManager.onPointerDown += OnPointerDown;
}
private void OnPointerDown()
{
Ray ray = Camera.main.ScreenPointToRay(MixedLettersConfiguration.Instance.Context.GetInputManager().LastPointerPosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity) && hit.collider == boxCollider)
{
dropZone.OnRotateLetter();
}
}
// Update is called once per frame
void Update()
{
}
public void SetDropZone(DropZoneController dropZone)
{
this.dropZone = dropZone;
}
public void SetPosition(Vector3 position)
{
transform.position = position;
}
public void Enable()
{
gameObject.SetActive(true);
}
public void Disable()
{
gameObject.SetActive(false);
}
}
} | Norad-Eduapp4syria/Norad-Eduapp4syria | finalApprovedVersion/Antura/EA4S_Antura_U3D/Assets/_games/MixedLetters/_scripts/RotateButtonController.cs | C# | bsd-2-clause | 1,362 |
<?hh
/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/bsd-license.php
* @link http://titon.io
*/
/**
* --------------------------------------------------------------
* Type Aliases
* --------------------------------------------------------------
*
* Defines type aliases that are used by the cache package.
*/
namespace Titon\Cache {
type CacheCallback = (function(): mixed);
type ItemList = Vector<Item>;
type ItemMap = Map<string, Item>;
type StatsMap = Map<string, mixed>;
type StorageMap = Map<string, Storage>;
}
| titon/framework | src/Titon/Cache/bootstrap.hh | C++ | bsd-2-clause | 603 |
// Copyright (c) 2010, Adam Petersen <adam@adampetersen.se>. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY Adam Petersen ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Adam Petersen OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "tinch_pp/erl_string.h"
#include "tinch_pp/erl_any.h"
#include "string_matcher.h"
#include "ext_term_grammar.h"
#include "term_conversions.h"
#include <boost/bind.hpp>
#include <list>
#include <algorithm>
#include <cassert>
using namespace tinch_pp;
using namespace tinch_pp::erl;
using namespace boost;
using namespace std;
namespace {
typedef tinch_pp::detail::string_matcher matcher_s;
erl::int_ create_int(char val)
{
const uint32_t int_val = val;
return erl::int_(int_val);
}
bool match_string_value(msg_seq_iter& f, const msg_seq_iter& l, const string& val)
{
// We're reusing the list implementation:
std::list<int_> as_ints;
std::transform(val.begin(), val.end(), back_inserter(as_ints), create_int);
return matcher_s::match(as_ints, f, l);
}
char shrink_int(const erl::int_& val)
{
return static_cast<char>(val.value());
}
bool assign_matched_string(msg_seq_iter& f, const msg_seq_iter& l, string* to_assign)
{
assert(to_assign != 0);
std::list<int_> as_ints;
const bool res = matcher_s::assign_match(&as_ints, f, l);
for_each(as_ints.begin(), as_ints.end(), bind(&string::push_back, to_assign,
bind(shrink_int, ::_1)));
return res;
}
bool match_any_string(msg_seq_iter& f, const msg_seq_iter& l, const any& match_any)
{
std::string ignore;
msg_seq_iter start = f;
return assign_matched_string(f, l, &ignore) ? match_any.save_matched_bytes(msg_seq(start, f)) : false;
}
}
e_string::e_string(const std::string& a_val)
: val(a_val),
to_assign(0),
match_fn(bind(match_string_value, ::_1, ::_2, cref(val))) {}
e_string::e_string(std::string* a_to_assign)
: to_assign(a_to_assign),
match_fn(bind(assign_matched_string, ::_1, ::_2, to_assign)) {}
e_string::e_string(const any& match_any)
: to_assign(0),
match_fn(bind(match_any_string, ::_1, ::_2, cref(match_any))) {}
void e_string::serialize(msg_seq_out_iter& out) const
{
const serializable_string s(val);
term_to_binary<string_ext_g>(out, s);
}
bool e_string::match(msg_seq_iter& f, const msg_seq_iter& l) const
{
return match_fn(f, l);
}
| adamtornhill/tinch_pp | impl/erl_string.cpp | C++ | bsd-2-clause | 3,573 |
#!/usr/bin/env python
import logging
import socket
import struct
import time
import sys
import cb_bin_client
import couchbaseConstants
import pump
import cbsnappy as snappy
try:
import ctypes
except ImportError:
cb_path = '/opt/couchbase/lib/python'
while cb_path in sys.path:
sys.path.remove(cb_path)
try:
import ctypes
except ImportError:
sys.exit('error: could not import ctypes module')
else:
sys.path.insert(0, cb_path)
OP_MAP = {
'get': couchbaseConstants.CMD_GET,
'set': couchbaseConstants.CMD_SET,
'add': couchbaseConstants.CMD_ADD,
'delete': couchbaseConstants.CMD_DELETE,
}
OP_MAP_WITH_META = {
'get': couchbaseConstants.CMD_GET,
'set': couchbaseConstants.CMD_SET_WITH_META,
'add': couchbaseConstants.CMD_ADD_WITH_META,
'delete': couchbaseConstants.CMD_DELETE_WITH_META
}
class MCSink(pump.Sink):
"""Dumb client sink using binary memcached protocol.
Used when moxi or memcached is destination."""
def __init__(self, opts, spec, source_bucket, source_node,
source_map, sink_map, ctl, cur):
super(MCSink, self).__init__(opts, spec, source_bucket, source_node,
source_map, sink_map, ctl, cur)
self.op_map = OP_MAP
if opts.extra.get("try_xwm", 1):
self.op_map = OP_MAP_WITH_META
self.init_worker(MCSink.run)
self.uncompress = opts.extra.get("uncompress", 0)
def close(self):
self.push_next_batch(None, None)
@staticmethod
def check_base(opts, spec):
if getattr(opts, "destination_vbucket_state", "active") != "active":
return ("error: only --destination-vbucket-state=active" +
" is supported by this destination: %s") % (spec)
op = getattr(opts, "destination_operation", None)
if not op in [None, 'set', 'add', 'get']:
return ("error: --destination-operation unsupported value: %s" +
"; use set, add, get") % (op)
# Skip immediate superclass Sink.check_base(),
# since MCSink can handle different destination operations.
return pump.EndPoint.check_base(opts, spec)
@staticmethod
def run(self):
"""Worker thread to asynchronously store batches into sink."""
mconns = {} # State kept across scatter_gather() calls.
backoff_cap = self.opts.extra.get("backoff_cap", 10)
while not self.ctl['stop']:
batch, future = self.pull_next_batch()
if not batch:
self.future_done(future, 0)
self.close_mconns(mconns)
return
backoff = 0.1 # Reset backoff after a good batch.
while batch: # Loop in case retry is required.
rv, batch, need_backoff = self.scatter_gather(mconns, batch)
if rv != 0:
self.future_done(future, rv)
self.close_mconns(mconns)
return
if batch:
self.cur["tot_sink_retry_batch"] = \
self.cur.get("tot_sink_retry_batch", 0) + 1
if need_backoff:
backoff = min(backoff * 2.0, backoff_cap)
logging.warn("backing off, secs: %s" % (backoff))
time.sleep(backoff)
self.future_done(future, 0)
self.close_mconns(mconns)
def close_mconns(self, mconns):
for k, conn in mconns.items():
self.add_stop_event(conn)
conn.close()
def scatter_gather(self, mconns, batch):
conn = mconns.get("conn")
if not conn:
rv, conn = self.connect()
if rv != 0:
return rv, None
mconns["conn"] = conn
# TODO: (1) MCSink - run() handle --data parameter.
# Scatter or send phase.
rv = self.send_msgs(conn, batch.msgs, self.operation())
if rv != 0:
return rv, None, None
# Gather or recv phase.
rv, retry, refresh = self.recv_msgs(conn, batch.msgs)
if refresh:
self.refresh_sink_map()
if retry:
return rv, batch, True
return rv, None, None
def send_msgs(self, conn, msgs, operation, vbucket_id=None):
m = []
msg_format_length = 0
for i, msg in enumerate(msgs):
if not msg_format_length:
msg_format_length = len(msg)
cmd, vbucket_id_msg, key, flg, exp, cas, meta, val = msg[:8]
seqno = dtype = nmeta = conf_res = 0
if msg_format_length > 8:
seqno, dtype, nmeta, conf_res = msg[8:]
if vbucket_id is not None:
vbucket_id_msg = vbucket_id
if self.skip(key, vbucket_id_msg):
continue
rv, cmd = self.translate_cmd(cmd, operation, meta)
if rv != 0:
return rv
if dtype > 2:
if self.uncompress and val:
try:
val = snappy.uncompress(val)
except Exception, err:
pass
if cmd == couchbaseConstants.CMD_GET:
val, flg, exp, cas = '', 0, 0, 0
if cmd == couchbaseConstants.CMD_NOOP:
key, val, flg, exp, cas = '', '', 0, 0, 0
if cmd in (couchbaseConstants.CMD_DELETE, couchbaseConstants.CMD_DELETE_WITH_META):
val = ''
rv, req = self.cmd_request(cmd, vbucket_id_msg, key, val,
ctypes.c_uint32(flg).value,
exp, cas, meta, i, dtype, nmeta,
conf_res)
if rv != 0:
return rv
self.append_req(m, req)
if m:
try:
conn.s.send(''.join(m))
except socket.error, e:
return "error: conn.send() exception: %s" % (e)
return 0
def recv_msgs(self, conn, msgs, vbucket_id=None, verify_opaque=True):
refresh = False
retry = False
for i, msg in enumerate(msgs):
cmd, vbucket_id_msg, key, flg, exp, cas, meta, val = msg[:8]
if vbucket_id is not None:
vbucket_id_msg = vbucket_id
if self.skip(key, vbucket_id_msg):
continue
try:
r_cmd, r_status, r_ext, r_key, r_val, r_cas, r_opaque = \
self.read_conn(conn)
if verify_opaque and i != r_opaque:
return "error: opaque mismatch: %s %s" % (i, r_opaque), None, None
if r_status == couchbaseConstants.ERR_SUCCESS:
continue
elif r_status == couchbaseConstants.ERR_KEY_EEXISTS:
#logging.warn("item exists: %s, key: %s" %
# (self.spec, key))
continue
elif r_status == couchbaseConstants.ERR_KEY_ENOENT:
if (cmd != couchbaseConstants.CMD_TAP_DELETE and
cmd != couchbaseConstants.CMD_GET):
logging.warn("item not found: %s, key: %s" %
(self.spec, key))
continue
elif (r_status == couchbaseConstants.ERR_ETMPFAIL or
r_status == couchbaseConstants.ERR_EBUSY or
r_status == couchbaseConstants.ERR_ENOMEM):
retry = True # Retry the whole batch again next time.
continue # But, finish recv'ing current batch.
elif r_status == couchbaseConstants.ERR_NOT_MY_VBUCKET:
msg = ("received NOT_MY_VBUCKET;"
" perhaps the cluster is/was rebalancing;"
" vbucket_id: %s, key: %s, spec: %s, host:port: %s:%s"
% (vbucket_id_msg, key, self.spec,
conn.host, conn.port))
if self.opts.extra.get("nmv_retry", 1):
logging.warn("warning: " + msg)
refresh = True
retry = True
self.cur["tot_sink_not_my_vbucket"] = \
self.cur.get("tot_sink_not_my_vbucket", 0) + 1
else:
return "error: " + msg, None, None
elif r_status == couchbaseConstants.ERR_UNKNOWN_COMMAND:
if self.op_map == OP_MAP:
if not retry:
return "error: unknown command: %s" % (r_cmd), None, None
else:
if not retry:
logging.warn("destination does not take XXX-WITH-META"
" commands; will use META-less commands")
self.op_map = OP_MAP
retry = True
else:
return "error: MCSink MC error: " + str(r_status), None, None
except Exception, e:
logging.error("MCSink exception: %s", e)
return "error: MCSink exception: " + str(e), None, None
return 0, retry, refresh
def translate_cmd(self, cmd, op, meta):
if len(str(meta)) <= 0:
# The source gave no meta, so use regular commands.
self.op_map = OP_MAP
if cmd in[couchbaseConstants.CMD_TAP_MUTATION, couchbaseConstants.CMD_DCP_MUTATION] :
m = self.op_map.get(op, None)
if m:
return 0, m
return "error: MCSink.translate_cmd, unsupported op: " + op, None
if cmd in [couchbaseConstants.CMD_TAP_DELETE, couchbaseConstants.CMD_DCP_DELETE]:
if op == 'get':
return 0, couchbaseConstants.CMD_NOOP
return 0, self.op_map['delete']
if cmd == couchbaseConstants.CMD_GET:
return 0, cmd
return "error: MCSink - unknown cmd: %s, op: %s" % (cmd, op), None
def append_req(self, m, req):
hdr, ext, key, val, extra_meta = req
m.append(hdr)
if ext:
m.append(ext)
if key:
m.append(str(key))
if val:
m.append(str(val))
if extra_meta:
m.append(extra_meta)
@staticmethod
def can_handle(opts, spec):
return (spec.startswith("memcached://") or
spec.startswith("memcached-binary://"))
@staticmethod
def check(opts, spec, source_map):
host, port, user, pswd, path = \
pump.parse_spec(opts, spec, int(getattr(opts, "port", 11211)))
if opts.ssl:
ports = couchbaseConstants.SSL_PORT
rv, conn = MCSink.connect_mc(host, port, user, pswd)
if rv != 0:
return rv, None
conn.close()
return 0, None
def refresh_sink_map(self):
return 0
@staticmethod
def consume_design(opts, sink_spec, sink_map,
source_bucket, source_map, source_design):
if source_design:
logging.warn("warning: cannot restore bucket design"
" on a memached destination")
return 0
def consume_batch_async(self, batch):
return self.push_next_batch(batch, pump.SinkBatchFuture(self, batch))
def connect(self):
host, port, user, pswd, path = \
pump.parse_spec(self.opts, self.spec,
int(getattr(self.opts, "port", 11211)))
if self.opts.ssl:
port = couchbaseConstants.SSL_PORT
return MCSink.connect_mc(host, port, user, pswd)
@staticmethod
def connect_mc(host, port, user, pswd):
mc = cb_bin_client.MemcachedClient(host, int(port))
if user:
try:
mc.sasl_auth_cram_md5(str(user), str(pswd))
except cb_bin_client.MemcachedError:
try:
mc.sasl_auth_plain(str(user), str(pswd))
except EOFError:
return "error: SASL auth error: %s:%s, user: %s" % \
(host, port, user), None
except cb_bin_client.MemcachedError:
return "error: SASL auth failed: %s:%s, user: %s" % \
(host, port, user), None
except socket.error:
return "error: SASL auth exception: %s:%s, user: %s" % \
(host, port, user), None
except EOFError:
return "error: SASL auth error: %s:%s, user: %s" % \
(host, port, user), None
except socket.error:
return "error: SASL auth exception: %s:%s, user: %s" % \
(host, port, user), None
return 0, mc
def cmd_request(self, cmd, vbucket_id, key, val, flg, exp, cas, meta, opaque, dtype, nmeta, conf_res):
ext_meta = ''
if (cmd == couchbaseConstants.CMD_SET_WITH_META or
cmd == couchbaseConstants.CMD_ADD_WITH_META or
cmd == couchbaseConstants.CMD_DELETE_WITH_META):
if meta:
try:
ext = struct.pack(">IIQQ", flg, exp, int(str(meta)), cas)
except ValueError:
seq_no = str(meta)
if len(seq_no) > 8:
seq_no = seq_no[0:8]
if len(seq_no) < 8:
# The seq_no might be 32-bits from 2.0DP4, so pad with 0x00's.
seq_no = ('\x00\x00\x00\x00\x00\x00\x00\x00' + seq_no)[-8:]
check_seqno, = struct.unpack(">Q", seq_no)
if check_seqno:
ext = (struct.pack(">II", flg, exp) + seq_no +
struct.pack(">Q", cas))
else:
ext = struct.pack(">IIQQ", flg, exp, 1, cas)
else:
ext = struct.pack(">IIQQ", flg, exp, 1, cas)
if conf_res:
extra_meta = struct.pack(">BBHH",
couchbaseConstants.DCP_EXTRA_META_VERSION,
couchbaseConstants.DCP_EXTRA_META_CONFLICT_RESOLUTION,
con_res_len,
conf_res)
ext += struct.pack(">H", len(extra_meta))
elif (cmd == couchbaseConstants.CMD_SET or
cmd == couchbaseConstants.CMD_ADD):
ext = struct.pack(couchbaseConstants.SET_PKT_FMT, flg, exp)
elif (cmd == couchbaseConstants.CMD_DELETE or
cmd == couchbaseConstants.CMD_GET or
cmd == couchbaseConstants.CMD_NOOP):
ext = ''
else:
return "error: MCSink - unknown cmd for request: " + str(cmd), None
hdr = self.cmd_header(cmd, vbucket_id, key, val, ext, 0, opaque, dtype)
return 0, (hdr, ext, key, val, ext_meta)
def cmd_header(self, cmd, vbucket_id, key, val, ext, cas, opaque,
dtype=0,
fmt=couchbaseConstants.REQ_PKT_FMT,
magic=couchbaseConstants.REQ_MAGIC_BYTE):
#MB-11902
dtype = 0
return struct.pack(fmt, magic, cmd,
len(key), len(ext), dtype, vbucket_id,
len(key) + len(ext) + len(val), opaque, cas)
def read_conn(self, conn):
ext = ''
key = ''
val = ''
buf, cmd, errcode, extlen, keylen, data, cas, opaque = \
self.recv_msg(conn.s, getattr(conn, 'buf', ''))
conn.buf = buf
if data:
ext = data[0:extlen]
key = data[extlen:extlen+keylen]
val = data[extlen+keylen:]
return cmd, errcode, ext, key, val, cas, opaque
def recv_msg(self, sock, buf):
pkt, buf = self.recv(sock, couchbaseConstants.MIN_RECV_PACKET, buf)
if not pkt:
raise EOFError()
magic, cmd, keylen, extlen, dtype, errcode, datalen, opaque, cas = \
struct.unpack(couchbaseConstants.RES_PKT_FMT, pkt)
if magic != couchbaseConstants.RES_MAGIC_BYTE:
raise Exception("unexpected recv_msg magic: " + str(magic))
data, buf = self.recv(sock, datalen, buf)
return buf, cmd, errcode, extlen, keylen, data, cas, opaque
def recv(self, skt, nbytes, buf):
while len(buf) < nbytes:
data = None
try:
data = skt.recv(max(nbytes - len(buf), 4096))
except socket.timeout:
logging.error("error: recv socket.timeout")
except Exception, e:
logging.error("error: recv exception: " + str(e))
if not data:
return None, ''
buf += data
return buf[:nbytes], buf[nbytes:]
| TOTVS/mdmpublic | couchbase-cli/lib/python/pump_mc.py | Python | bsd-2-clause | 17,056 |
using System;
using bv.model.BLToolkit;
using eidss.model.Reports.KZ;
using EIDSS.Reports.BaseControls.Filters;
using EIDSS.Reports.BaseControls.Keeper;
using EIDSS.Reports.BaseControls.Report;
namespace EIDSS.Reports.Parameterized.Veterinary.KZ.Keepers
{
public partial class VetProphMeasuresKeeper : BaseIntervalKeeper
{
public string[] m_MeasureType = new string[0];
private long? m_Region;
public VetProphMeasuresKeeper()
{
InitializeComponent();
}
public VetProphMeasuresKeeper(Type reportType)
: base(reportType)
{
InitializeComponent();
if (ReportType == typeof (VetCountryProphilacticMeasures))
{
regionFilter1.Hide();
}
regionFilter1.SetMandatory();
}
protected override BaseReport GenerateReport(DbManagerProxy manager)
{
var model = new SanitaryModel(CurrentCulture.ShortName, StartDateTruncated, EndDateTruncated,
m_Region, m_MeasureType, UseArchive);
dynamic report = CreateReportObject();
report.SetParameters(manager, model);
return report;
}
protected internal override void ApplyResources(DbManagerProxy manager)
{
base.ApplyResources(manager);
regionFilter1.DefineBinding();
measureTypeFilter1.DefineBinding();
}
private void regionFilter1_ValueChanged(object sender, SingleFilterEventArgs e)
{
m_Region = regionFilter1.RegionId > 0 ? (long?) regionFilter1.RegionId : null;
}
private void measureTypeFilter1_ValueChanged(object sender, MultiFilterEventArgs e)
{
m_MeasureType = e.KeyArray;
}
}
} | EIDSS/EIDSS-Legacy | EIDSS v6/vb/EIDSS/EIDSS.Reports/Parameterized/Veterinary/KZ/Keepers/VetProphMeasuresKeeper.cs | C# | bsd-2-clause | 1,874 |
<?php
class tasks_Db extends controller_Tasks
{
public function actionCheck($force = false)
{
}
} | fsw/old_eve | evelibs/core.lib/tasks/Db.php | PHP | bsd-2-clause | 107 |
#pragma once
#include "FAST/Visualization/Window.hpp"
class QPushButton;
class QLineEdit;
class QLabel;
class QElapsedTimer;
class QListWidget;
namespace fast {
class RealSenseStreamer;
class Tracking;
class TrackingGUI : public Window {
FAST_OBJECT(TrackingGUI)
public:
void extractPointCloud();
void restart();
void toggleRecord();
void updateMessages();
void playRecording();
void refreshRecordingsList();
private:
TrackingGUI();
std::shared_ptr<RealSenseStreamer> mStreamer;
std::shared_ptr<Tracking> mTracking;
QPushButton* mRecordButton;
QPushButton* mPlayButton;
QLineEdit* mStorageDir;
QLineEdit* mRecordingNameLineEdit;
QLabel* mRecordingInformation;
QElapsedTimer* mRecordTimer;
QListWidget* mRecordingsList;
bool mRecording = false;
bool mPlaying = false;
std::string mRecordingName;
};
}
| smistad/FAST | source/FAST/Examples/RealSense/TrackingGUI.hpp | C++ | bsd-2-clause | 973 |
import argparse
import os
import json
import sys
from lxml import etree
def process_file(name):
tree = etree.parse(name)
xpath = tree.xpath("//xsl:when/@test",
namespaces={"xsl": "http://www.w3.org/1999/XSL/Transform"})
test_xml = tree.xpath("/xsl:stylesheet/xsl:template/xsl:if[@test='false()']",
namespaces={"xsl": "http://www.w3.org/1999/XSL/Transform"})
if not xpath:
print("couldn't find xpath in %s" % name)
sys.exit(1)
xpath = xpath[0]
if not (len(test_xml[0]) == 1):
print("test didn't have single root element, %s" % name)
print(test_xml)
sys.exit(1)
return xpath, test_xml[0][0]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Convert XPath tests.')
parser.add_argument('in_dir', metavar='IN', help='path to presto-testo XPath tests')
parser.add_argument('out_dir', metavar='OUT', default="new",
help='path to output new XPath tests')
args = parser.parse_args()
tests = etree.fromstring("<tests/>")
d = args.in_dir
files = os.listdir(d)
for f in files:
if f.endswith(".xml") and f != "ref.xml":
xpath, test_xml = process_file(os.path.join(d, f))
test = etree.Element("test")
tests.append(test)
test.append(etree.Element("xpath"))
test.append(etree.Element("tree"))
test[0].text = xpath
test[1].append(test_xml)
with open(os.path.join(args.out_dir, "tests.xml"), "wb") as fp:
wrapped = etree.ElementTree(tests)
wrapped.write(fp, encoding="ascii", pretty_print=True, exclusive=True)
| gsnedders/presto-testo-converters | convert_xpath.py | Python | bsd-2-clause | 1,711 |
class GnomeRecipes < Formula
desc "Formula for GNOME recipes"
homepage "https://wiki.gnome.org/Apps/Recipes"
url "https://download.gnome.org/sources/gnome-recipes/2.0/gnome-recipes-2.0.2.tar.xz"
sha256 "1be9d2fcb7404a97aa029d2409880643f15071c37039247a6a4320e7478cd5fb"
revision 2
bottle do
sha256 "9250ea26b664e3ec8982762710969f15582b7e87e11e989584294a6147c07926" => :high_sierra
sha256 "e44081479d677544aa1c89cf1fcd2aef07f6afd6fa4eb81fe9a0a39677ae0e0c" => :sierra
sha256 "5271c2503df67137bce7a6eb04c581474e23015332ea0aed73870a849053d973" => :el_capitan
end
depends_on "meson" => :build
depends_on "ninja" => :build
depends_on "pkg-config" => :build
depends_on "itstool" => :build
depends_on "python3" => :build
depends_on "gtk+3"
depends_on "adwaita-icon-theme"
depends_on "libcanberra"
depends_on "gnome-autoar"
depends_on "gspell"
depends_on "libsoup"
depends_on "gnu-tar"
# dependencies for goa
depends_on "intltool" => :build
depends_on "json-glib"
depends_on "librest"
resource "goa" do
url "https://download.gnome.org/sources/gnome-online-accounts/3.26/gnome-online-accounts-3.26.1.tar.xz"
sha256 "603c110405cb89a01497a69967f10e3f3f36add3dc175b062ec4c5ed4485621b"
end
def install
resource("goa").stage do
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{libexec}",
"--disable-backend"
system "make", "install"
end
ENV.prepend_path "PKG_CONFIG_PATH", libexec/"lib/pkgconfig"
# BSD tar does not support the required options
inreplace "src/gr-recipe-store.c", "argv[0] = \"tar\";", "argv[0] = \"gtar\";"
# stop meson_post_install.py from doing what needs to be done in the post_install step
ENV["DESTDIR"] = ""
ENV.delete "PYTHONPATH"
mkdir "build" do
system "meson", "--prefix=#{prefix}", ".."
system "ninja"
system "ninja", "install"
end
end
def post_install
system "#{Formula["glib"].opt_bin}/glib-compile-schemas", "#{HOMEBREW_PREFIX}/share/glib-2.0/schemas"
system "#{Formula["gtk+3"].opt_bin}/gtk3-update-icon-cache", "-f", "-t", "#{HOMEBREW_PREFIX}/share/icons/hicolor"
end
test do
system "#{bin}/gnome-recipes", "--help"
end
end
| reelsense/homebrew-core | Formula/gnome-recipes.rb | Ruby | bsd-2-clause | 2,389 |
""" Web runtime based on Selenium.
Selenium is a Python library to automate browsers.
"""
from .common import BaseRuntime
class SeleniumRuntime(BaseRuntime):
""" Runtime based on Selenium (http://www.seleniumhq.org/), a tool
to automate browsers, e.g. for testing. Requires the Python package
"selenium" to be installed.
"""
def _launch(self):
# Get url and browser type
url = self._kwargs['url']
type = self._kwargs.get('type', '')
self._driver = None
# Import here; selenium is an optional dependency
from selenium import webdriver
if type.lower() == 'firefox':
self._driver = webdriver.Firefox()
elif type.lower() == 'chrome':
self._driver = webdriver.Chrome()
elif type.lower() == 'ie':
self._driver = webdriver.Ie()
elif type:
classname = None
type2 = type[0].upper() + type[1:]
if hasattr(webdriver, type):
classname = type
elif hasattr(webdriver, type2):
classname = type2
if classname:
self._driver = getattr(webdriver, classname)()
else:
raise ValueError('Unknown Selenium browser type %r' % type)
else:
raise ValueError('To use selenium runtime specify a browser type".')
# Open page
self._driver.get(url)
def close(self):
if self._driver:
self._driver.close()
self._driver = None
@property
def driver(self):
""" The Selenium webdriver object. Use this to control the browser.
"""
return self._driver
| JohnLunzer/flexx | flexx/webruntime/selenium.py | Python | bsd-2-clause | 1,783 |
using FlubuCore.Context;
using FlubuCore.Tasks.NetCore;
using Moq;
using Xunit;
namespace FlubuCore.Tests.Tasks
{
public class DotnetRestoreUnitTests : TaskUnitTestBase
{
private readonly DotnetRestoreTask _task;
public DotnetRestoreUnitTests()
{
_task = new DotnetRestoreTask();
_task.Executable("dotnet");
Tasks.Setup(x => x.RunProgramTask("dotnet")).Returns(RunProgramTask.Object);
}
[Fact]
public void ConfigurationAndProjectFromFluentInterfaceConfigurationTest()
{
_task.Project("project");
_task.ExecuteVoid(Context.Object);
Assert.Single(_task.GetArguments());
Assert.Equal("project", _task.GetArguments()[0]);
}
[Fact]
public void ConfigurationAndProjectFromFluentInterfaceWithArgumentsTest()
{
_task.WithArguments("project");
_task.ExecuteVoid(Context.Object);
Assert.Equal("project", _task.GetArguments()[0]);
}
[Fact]
public void ConfigurationAndProjectFromBuildPropertiesTest()
{
Properties.Setup(x => x.Get<string>(BuildProps.SolutionFileName, null, It.IsAny<string>())).Returns("project2");
_task.ExecuteVoid(Context.Object);
Assert.Single(_task.GetArguments());
Assert.Equal("project2", _task.GetArguments()[0]);
}
[Fact]
public void ProjectIsFirstArgumentTest()
{
_task.WithArguments("-c", "release", "somearg", "-sf");
_task.Project("project");
_task.ExecuteVoid(Context.Object);
Assert.Equal("project", _task.GetArguments()[0]);
}
}
}
| flubu-core/flubu.core | src/FlubuCore.Tests/Tasks/DotnetRestoreUnitTests.cs | C# | bsd-2-clause | 1,751 |
// Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <w32.gdi/Key.hpp>
namespace w32 { namespace gdi {
const Key Key::shift ()
{
return (VK_SHIFT);
}
const Key Key::lshift ()
{
return (VK_LSHIFT);
}
const Key Key::rshift ()
{
return (VK_RSHIFT);
}
const Key Key::control ()
{
return (VK_CONTROL);
}
const Key Key::lcontrol ()
{
return (VK_LCONTROL);
}
const Key Key::rcontrol ()
{
return (VK_RCONTROL);
}
const Key Key::menu ()
{
return (VK_MENU);
}
const Key Key::lmenu ()
{
return (VK_LMENU);
}
const Key Key::rmenu ()
{
return (VK_RMENU);
}
Key::Key ( int identifier )
: myIdentifier(identifier)
{
}
bool Key::up ( const Key& key )
{
return ((::GetKeyState(key.identifier()) & 0x8000) != 0);
}
bool Key::down ( const Key& key )
{
return ((::GetKeyState(key.identifier()) & 0x8000) == 0);
}
bool Key::toggled ( const Key& key )
{
return ((::GetKeyState(key.identifier()) & 0x0001) == 1);
}
int Key::identifier () const
{
return (myIdentifier);
}
} }
| AndreLouisCaron/w32 | code/w32.gdi/Key.cpp | C++ | bsd-2-clause | 2,607 |
/*
* #%L
* ImageJ2 software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2021 ImageJ2 developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.ops.convert;
import net.imagej.ops.AbstractNamespace;
import net.imagej.ops.Namespace;
import net.imagej.ops.OpMethod;
import net.imagej.ops.Ops;
import net.imglib2.IterableInterval;
import net.imglib2.img.Img;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.ComplexType;
import net.imglib2.type.numeric.IntegerType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.complex.ComplexDoubleType;
import net.imglib2.type.numeric.complex.ComplexFloatType;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.integer.IntType;
import net.imglib2.type.numeric.integer.LongType;
import net.imglib2.type.numeric.integer.ShortType;
import net.imglib2.type.numeric.integer.Unsigned128BitType;
import net.imglib2.type.numeric.integer.Unsigned12BitType;
import net.imglib2.type.numeric.integer.Unsigned2BitType;
import net.imglib2.type.numeric.integer.Unsigned4BitType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedIntType;
import net.imglib2.type.numeric.integer.UnsignedLongType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.type.numeric.real.FloatType;
import org.scijava.plugin.Plugin;
/**
* The convert namespace contains operations for converting between types.
*
* @author Curtis Rueden
*/
@Plugin(type = Namespace.class)
public class ConvertNamespace extends AbstractNamespace {
// -- Convert namespace ops --
@OpMethod(op = net.imagej.ops.convert.clip.ClipRealTypes.class)
public <I extends RealType<I>, O extends RealType<O>> O clip(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result = (O) ops().run(
Ops.Convert.Clip.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.copy.CopyRealTypes.class)
public <I extends RealType<I>, O extends RealType<O>> O copy(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result = (O) ops().run(
Ops.Convert.Copy.class, out, in);
return result;
}
@OpMethod(
op = net.imagej.ops.convert.imageType.ConvertIIs.class)
public <I extends RealType<I>, O extends RealType<O>> IterableInterval<O>
imageType(final IterableInterval<O> out, final IterableInterval<I> in,
final RealTypeConverter<I, O> typeConverter)
{
@SuppressWarnings("unchecked")
final IterableInterval<O> result = (IterableInterval<O>) ops().run(
Ops.Convert.ImageType.class, out, in,
typeConverter);
return result;
}
@OpMethod(
op = net.imagej.ops.convert.normalizeScale.NormalizeScaleRealTypes.class)
public <I extends RealType<I>, O extends RealType<O>> O normalizeScale(
final O out, final I in)
{
@SuppressWarnings("unchecked")
final O result = (O) ops().run(
Ops.Convert.NormalizeScale.class, out,
in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.scale.ScaleRealTypes.class)
public <I extends RealType<I>, O extends RealType<O>> O scale(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result = (O) ops().run(
Ops.Convert.Scale.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Bit.class)
public <C extends ComplexType<C>> Img<BitType> bit(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<BitType> result = (Img<BitType>) ops().run(
Ops.Convert.Bit.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Bit.class)
public <C extends ComplexType<C>> Img<BitType> bit(final Img<BitType> out,
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<BitType> result = (Img<BitType>) ops().run(
Ops.Convert.Bit.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToBit.class)
public <C extends ComplexType<C>> BitType bit(final C in) {
final BitType result = (BitType) ops().run(
Ops.Convert.Bit.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToBit.class)
public <C extends ComplexType<C>> BitType bit(final BitType out, final C in) {
final BitType result = (BitType) ops().run(
Ops.Convert.Bit.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToBit.class)
public <T extends IntegerType<T>> BitType bit(final T in) {
final BitType result = (BitType) ops().run(Ops.Convert.Uint2.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToBit.class)
public <T extends IntegerType<T>> BitType bit(final BitType out, final T in) {
final BitType result = (BitType) ops().run(Ops.Convert.Uint2.class, out,
in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint2.class)
public <C extends ComplexType<C>> Img<Unsigned2BitType> uint2(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<Unsigned2BitType> result = (Img<Unsigned2BitType>) ops().run(
Ops.Convert.Uint2.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint2.class)
public <C extends ComplexType<C>> Img<Unsigned2BitType> uint2(
final Img<Unsigned2BitType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<Unsigned2BitType> result = (Img<Unsigned2BitType>) ops().run(
Ops.Convert.Uint2.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint2.class)
public <C extends ComplexType<C>> Unsigned2BitType uint2(final C in) {
final Unsigned2BitType result = (Unsigned2BitType) ops().run(
Ops.Convert.Uint2.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint2.class)
public <C extends ComplexType<C>> Unsigned2BitType uint2(
final Unsigned2BitType out, final C in)
{
final Unsigned2BitType result = (Unsigned2BitType) ops().run(
Ops.Convert.Uint2.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint2.class)
public <T extends IntegerType<T>> Unsigned2BitType uint2(final T in) {
final Unsigned2BitType result = (Unsigned2BitType) ops().run(
Ops.Convert.Uint2.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint2.class)
public <T extends IntegerType<T>> Unsigned2BitType uint2(
final Unsigned2BitType out, final T in)
{
final Unsigned2BitType result = (Unsigned2BitType) ops().run(
Ops.Convert.Uint2.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint4.class)
public <C extends ComplexType<C>> Img<Unsigned4BitType> uint4(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<Unsigned4BitType> result = (Img<Unsigned4BitType>) ops().run(
Ops.Convert.Uint4.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint4.class)
public <C extends ComplexType<C>> Img<Unsigned4BitType> uint4(
final Img<Unsigned4BitType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<Unsigned4BitType> result = (Img<Unsigned4BitType>) ops().run(
Ops.Convert.Uint4.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint4.class)
public <C extends ComplexType<C>> Unsigned4BitType uint4(final C in) {
final Unsigned4BitType result = (Unsigned4BitType) ops().run(
Ops.Convert.Uint4.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint4.class)
public <C extends ComplexType<C>> Unsigned4BitType uint4(
final Unsigned4BitType out, final C in)
{
final Unsigned4BitType result = (Unsigned4BitType) ops().run(
Ops.Convert.Uint4.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint4.class)
public <T extends IntegerType<T>> Unsigned4BitType uint4(final T in) {
final Unsigned4BitType result = (Unsigned4BitType) ops().run(
Ops.Convert.Uint4.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint4.class)
public <T extends IntegerType<T>> Unsigned4BitType uint4(
final Unsigned4BitType out, final T in)
{
final Unsigned4BitType result = (Unsigned4BitType) ops().run(
Ops.Convert.Uint4.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Int8.class)
public <C extends ComplexType<C>> Img<ByteType> int8(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<ByteType> result = (Img<ByteType>) ops().run(
Ops.Convert.Int8.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Int8.class)
public <C extends ComplexType<C>> Img<ByteType> int8(final Img<ByteType> out,
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<ByteType> result = (Img<ByteType>) ops().run(
Ops.Convert.Int8.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToInt8.class)
public <C extends ComplexType<C>> ByteType int8(final C in) {
final ByteType result = (ByteType) ops().run(
Ops.Convert.Int8.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToInt8.class)
public <C extends ComplexType<C>> ByteType int8(final ByteType out,
final C in)
{
final ByteType result = (ByteType) ops().run(
Ops.Convert.Int8.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToInt8.class)
public <T extends IntegerType<T>> ByteType int8(final T in) {
final ByteType result = (ByteType) ops().run(
Ops.Convert.Int8.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToInt8.class)
public <T extends IntegerType<T>> ByteType int8(final ByteType out,
final T in)
{
final ByteType result = (ByteType) ops().run(
Ops.Convert.Int8.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint8.class)
public <C extends ComplexType<C>> Img<UnsignedByteType> uint8(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<UnsignedByteType> result = (Img<UnsignedByteType>) ops().run(
Ops.Convert.Uint8.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint8.class)
public <C extends ComplexType<C>> Img<UnsignedByteType> uint8(
final Img<UnsignedByteType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<UnsignedByteType> result = (Img<UnsignedByteType>) ops().run(
Ops.Convert.Uint8.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint8.class)
public <C extends ComplexType<C>> UnsignedByteType uint8(final C in) {
final UnsignedByteType result = (UnsignedByteType) ops().run(
Ops.Convert.Uint8.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint8.class)
public <C extends ComplexType<C>> UnsignedByteType uint8(
final UnsignedByteType out, final C in)
{
final UnsignedByteType result = (UnsignedByteType) ops().run(
Ops.Convert.Uint8.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint8.class)
public <T extends IntegerType<T>> UnsignedByteType uint8(final T in) {
final UnsignedByteType result = (UnsignedByteType) ops().run(
Ops.Convert.Uint8.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint8.class)
public <T extends IntegerType<T>> UnsignedByteType uint8(
final UnsignedByteType out, final T in)
{
final UnsignedByteType result = (UnsignedByteType) ops().run(
Ops.Convert.Uint8.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint12.class)
public <C extends ComplexType<C>> Img<Unsigned12BitType> uint12(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<Unsigned12BitType> result = (Img<Unsigned12BitType>) ops().run(
Ops.Convert.Uint12.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint12.class)
public <C extends ComplexType<C>> Img<Unsigned12BitType> uint12(
final Img<Unsigned12BitType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<Unsigned12BitType> result = (Img<Unsigned12BitType>) ops().run(
Ops.Convert.Uint12.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint12.class)
public <C extends ComplexType<C>> Unsigned12BitType uint12(final C in) {
final Unsigned12BitType result = (Unsigned12BitType) ops().run(
Ops.Convert.Uint12.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint12.class)
public <C extends ComplexType<C>> Unsigned12BitType uint12(
final Unsigned12BitType out, final C in)
{
final Unsigned12BitType result = (Unsigned12BitType) ops().run(
Ops.Convert.Uint12.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint12.class)
public <T extends IntegerType<T>> Unsigned12BitType uint12(final T in) {
final Unsigned12BitType result = (Unsigned12BitType) ops().run(
Ops.Convert.Uint12.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint12.class)
public <T extends IntegerType<T>> Unsigned12BitType uint12(
final Unsigned12BitType out, final T in)
{
final Unsigned12BitType result = (Unsigned12BitType) ops().run(
Ops.Convert.Uint12.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Int16.class)
public <C extends ComplexType<C>> Img<ShortType> int16(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<ShortType> result = (Img<ShortType>) ops().run(
Ops.Convert.Int16.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Int16.class)
public <C extends ComplexType<C>> Img<ShortType> int16(
final Img<ShortType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<ShortType> result = (Img<ShortType>) ops().run(
Ops.Convert.Int16.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToInt16.class)
public <C extends ComplexType<C>> ShortType int16(final C in) {
final ShortType result = (ShortType) ops().run(
Ops.Convert.Int16.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToInt16.class)
public <C extends ComplexType<C>> ShortType int16(final ShortType out,
final C in)
{
final ShortType result = (ShortType) ops().run(
Ops.Convert.Int16.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToInt16.class)
public <T extends IntegerType<T>> ShortType int16(final T in) {
final ShortType result = (ShortType) ops().run(
Ops.Convert.Int16.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToInt16.class)
public <T extends IntegerType<T>> ShortType int16(final ShortType out,
final T in)
{
final ShortType result = (ShortType) ops().run(
Ops.Convert.Int16.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint16.class)
public <C extends ComplexType<C>> Img<UnsignedShortType> uint16(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<UnsignedShortType> result = (Img<UnsignedShortType>) ops().run(
Ops.Convert.Uint16.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint16.class)
public <C extends ComplexType<C>> Img<UnsignedShortType> uint16(
final Img<UnsignedShortType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<UnsignedShortType> result = (Img<UnsignedShortType>) ops().run(
Ops.Convert.Uint16.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint16.class)
public <C extends ComplexType<C>> UnsignedShortType uint16(final C in) {
final UnsignedShortType result = (UnsignedShortType) ops().run(
Ops.Convert.Uint16.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint16.class)
public <C extends ComplexType<C>> UnsignedShortType uint16(
final UnsignedShortType out, final C in)
{
final UnsignedShortType result = (UnsignedShortType) ops().run(
Ops.Convert.Uint16.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint16.class)
public <T extends IntegerType<T>> UnsignedShortType uint16(final T in) {
final UnsignedShortType result = (UnsignedShortType) ops().run(
Ops.Convert.Uint16.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint16.class)
public <T extends IntegerType<T>> UnsignedShortType uint16(
final UnsignedShortType out, final T in)
{
final UnsignedShortType result = (UnsignedShortType) ops().run(
Ops.Convert.Uint16.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Int32.class)
public <C extends ComplexType<C>> Img<IntType> int32(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<IntType> result = (Img<IntType>) ops().run(
Ops.Convert.Int32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Int32.class)
public <C extends ComplexType<C>> Img<IntType> int32(final Img<IntType> out,
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<IntType> result = (Img<IntType>) ops().run(
Ops.Convert.Int32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToInt32.class)
public <T extends IntegerType<T>> IntType int32(final T in) {
final IntType result = (IntType) ops().run(
Ops.Convert.Int32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToInt32.class)
public <T extends IntegerType<T>> IntType int32(final IntType out,
final T in)
{
final IntType result = (IntType) ops().run(
Ops.Convert.Int32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToInt32.class)
public <C extends ComplexType<C>> IntType int32(final C in) {
final IntType result = (IntType) ops().run(
Ops.Convert.Int32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToInt32.class)
public <C extends ComplexType<C>> IntType int32(final IntType out,
final C in)
{
final IntType result = (IntType) ops().run(
Ops.Convert.Int32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint32.class)
public <C extends ComplexType<C>> Img<UnsignedIntType> uint32(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<UnsignedIntType> result = (Img<UnsignedIntType>) ops().run(
Ops.Convert.Uint32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint32.class)
public <C extends ComplexType<C>> Img<UnsignedIntType> uint32(
final Img<UnsignedIntType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<UnsignedIntType> result = (Img<UnsignedIntType>) ops().run(
Ops.Convert.Uint32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint32.class)
public <C extends ComplexType<C>> UnsignedIntType uint32(final C in) {
final UnsignedIntType result = (UnsignedIntType) ops().run(
Ops.Convert.Uint32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint32.class)
public <C extends ComplexType<C>> UnsignedIntType uint32(
final UnsignedIntType out, final C in)
{
final UnsignedIntType result = (UnsignedIntType) ops().run(
Ops.Convert.Uint32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint32.class)
public <T extends IntegerType<T>> UnsignedIntType uint32(final T in) {
final UnsignedIntType result = (UnsignedIntType) ops().run(
Ops.Convert.Uint32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint32.class)
public <T extends IntegerType<T>> UnsignedIntType uint32(
final UnsignedIntType out, final T in)
{
final UnsignedIntType result = (UnsignedIntType) ops().run(
Ops.Convert.Uint32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Int64.class)
public <C extends ComplexType<C>> Img<LongType> int64(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<LongType> result = (Img<LongType>) ops().run(
Ops.Convert.Int64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Int64.class)
public <C extends ComplexType<C>> Img<LongType> int64(final Img<LongType> out,
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<LongType> result = (Img<LongType>) ops().run(
Ops.Convert.Int64.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToInt64.class)
public <C extends ComplexType<C>> LongType int64(final C in) {
final LongType result = (LongType) ops().run(
Ops.Convert.Int64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToInt64.class)
public <C extends ComplexType<C>> LongType int64(final LongType out,
final C in)
{
final LongType result = (LongType) ops().run(
Ops.Convert.Int64.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToInt64.class)
public <T extends IntegerType<T>> LongType int64(final T in) {
final LongType result = (LongType) ops().run(
Ops.Convert.Int64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToInt64.class)
public <T extends IntegerType<T>> LongType int64(final LongType out,
final T in)
{
final LongType result = (LongType) ops().run(
Ops.Convert.Int64.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint64.class)
public <C extends ComplexType<C>> Img<UnsignedLongType> uint64(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<UnsignedLongType> result = (Img<UnsignedLongType>) ops().run(
Ops.Convert.Uint64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint64.class)
public <C extends ComplexType<C>> Img<UnsignedLongType> uint64(
final Img<UnsignedLongType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<UnsignedLongType> result = (Img<UnsignedLongType>) ops().run(
Ops.Convert.Uint64.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint64.class)
public <C extends ComplexType<C>> UnsignedLongType uint64(final C in) {
final UnsignedLongType result = (UnsignedLongType) ops().run(
Ops.Convert.Uint64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint64.class)
public <C extends ComplexType<C>> UnsignedLongType uint64(
final UnsignedLongType out, final C in)
{
final UnsignedLongType result = (UnsignedLongType) ops().run(
Ops.Convert.Uint64.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint64.class)
public <T extends IntegerType<T>> UnsignedLongType uint64(final T in) {
final UnsignedLongType result = (UnsignedLongType) ops().run(
Ops.Convert.Uint64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint64.class)
public <T extends IntegerType<T>> UnsignedLongType uint64(
final UnsignedLongType out, final T in)
{
final UnsignedLongType result = (UnsignedLongType) ops().run(
Ops.Convert.Uint64.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint128.class)
public <C extends ComplexType<C>> Img<Unsigned128BitType> uint128(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<Unsigned128BitType> result = (Img<Unsigned128BitType>) ops().run(
Ops.Convert.Uint128.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Uint128.class)
public <C extends ComplexType<C>> Img<Unsigned128BitType> uint128(
final Img<Unsigned128BitType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<Unsigned128BitType> result = (Img<Unsigned128BitType>) ops().run(
Ops.Convert.Uint128.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint128.class)
public <T extends IntegerType<T>> Unsigned128BitType uint128(final T in) {
final Unsigned128BitType result = (Unsigned128BitType) ops().run(
Ops.Convert.Uint128.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.IntegerToUint128.class)
public <T extends IntegerType<T>> Unsigned128BitType uint128(
final Unsigned128BitType out, final T in)
{
final Unsigned128BitType result = (Unsigned128BitType) ops().run(
Ops.Convert.Uint128.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint128.class)
public <C extends ComplexType<C>> Unsigned128BitType uint128(final C in) {
final Unsigned128BitType result = (Unsigned128BitType) ops().run(
Ops.Convert.Uint128.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToUint128.class)
public <C extends ComplexType<C>> Unsigned128BitType uint128(
final Unsigned128BitType out, final C in)
{
final Unsigned128BitType result = (Unsigned128BitType) ops().run(
Ops.Convert.Uint128.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Float32.class)
public <C extends ComplexType<C>> Img<FloatType> float32(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<FloatType> result = (Img<FloatType>) ops().run(
Ops.Convert.Float32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Float32.class)
public <C extends ComplexType<C>> Img<FloatType> float32(
final Img<FloatType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<FloatType> result = (Img<FloatType>) ops().run(
Ops.Convert.Float32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToFloat32.class)
public <C extends ComplexType<C>> FloatType float32(final C in) {
final FloatType result = (FloatType) ops().run(
Ops.Convert.Float32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToFloat32.class)
public <C extends ComplexType<C>> FloatType float32(final FloatType out,
final C in)
{
final FloatType result = (FloatType) ops().run(
Ops.Convert.Float32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Cfloat32.class)
public <C extends ComplexType<C>> Img<ComplexFloatType> cfloat32(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<ComplexFloatType> result = (Img<ComplexFloatType>) ops().run(
Ops.Convert.Cfloat32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Cfloat32.class)
public <C extends ComplexType<C>> Img<ComplexFloatType> cfloat32(
final Img<ComplexFloatType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<ComplexFloatType> result = (Img<ComplexFloatType>) ops().run(
Ops.Convert.Cfloat32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToCfloat32.class)
public <C extends ComplexType<C>> ComplexFloatType cfloat32(final C in) {
final ComplexFloatType result = (ComplexFloatType) ops().run(
Ops.Convert.Cfloat32.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToCfloat32.class)
public <C extends ComplexType<C>> ComplexFloatType cfloat32(
final ComplexFloatType out, final C in)
{
final ComplexFloatType result = (ComplexFloatType) ops().run(
Ops.Convert.Cfloat32.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Float64.class)
public <C extends ComplexType<C>> Img<DoubleType> float64(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<DoubleType> result = (Img<DoubleType>) ops().run(
Ops.Convert.Float64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Float64.class)
public <C extends ComplexType<C>> Img<DoubleType> float64(
final Img<DoubleType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<DoubleType> result = (Img<DoubleType>) ops().run(
Ops.Convert.Float64.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToFloat64.class)
public <C extends ComplexType<C>> DoubleType float64(final C in) {
final DoubleType result = (DoubleType) ops().run(
Ops.Convert.Float64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToFloat64.class)
public <C extends ComplexType<C>> DoubleType float64(final DoubleType out,
final C in)
{
final DoubleType result = (DoubleType) ops().run(
Ops.Convert.Float64.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Cfloat64.class)
public <C extends ComplexType<C>> Img<ComplexDoubleType> cfloat64(
final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<ComplexDoubleType> result = (Img<ComplexDoubleType>) ops().run(
Ops.Convert.Cfloat64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertImages.Cfloat64.class)
public <C extends ComplexType<C>> Img<ComplexDoubleType> cfloat64(
final Img<ComplexDoubleType> out, final IterableInterval<C> in)
{
@SuppressWarnings("unchecked")
final Img<ComplexDoubleType> result = (Img<ComplexDoubleType>) ops().run(
Ops.Convert.Cfloat64.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToCfloat64.class)
public <C extends ComplexType<C>> ComplexDoubleType cfloat64(final C in) {
final ComplexDoubleType result = (ComplexDoubleType) ops().run(
Ops.Convert.Cfloat64.class, in);
return result;
}
@OpMethod(op = net.imagej.ops.convert.ConvertTypes.ComplexToCfloat64.class)
public <C extends ComplexType<C>> ComplexDoubleType cfloat64(
final ComplexDoubleType out, final C in)
{
final ComplexDoubleType result = (ComplexDoubleType) ops().run(
Ops.Convert.Cfloat64.class, out, in);
return result;
}
// -- Named methods --
@Override
public String getName() {
return "convert";
}
}
| imagej/imagej-ops | src/main/java/net/imagej/ops/convert/ConvertNamespace.java | Java | bsd-2-clause | 32,601 |
from Crypto.Cipher import AES
import struct
CHUNK_SIZE = 32768
def encrypt_chunk(f, aes):
chunk = f.read(CHUNK_SIZE)
realn = len(chunk)
if realn == 0:
return ''
if realn % 16 != 0:
padding = 16 - (realn % 16)
chunk += ' ' * padding
head = struct.pack('!H', realn)
return head + aes.encrypt(chunk)
def decrypt_chunk(f, aes):
headn = struct.calcsize('!H')
head = f.read(headn)
if len(head) == 0:
return ''
realn, = struct.unpack('!H', head)
if realn % 16 != 0:
n = realn + (16 - (realn % 16))
else:
n = realn
chunk = f.read(n)
plain = aes.decrypt(chunk)
return plain[:realn]
def transform_file(infname, outfname, key, chunk_func):
inf = open(infname, 'rb')
outf = open(outfname, 'wb')
aes = AES.new(key)
chunk = chunk_func(inf, aes)
while chunk:
outf.write(chunk)
chunk = chunk_func(inf, aes)
inf.close()
outf.close()
def encrypt_file(infname, outfname, key):
transform_file(infname, outfname, key, encrypt_chunk)
def decrypt_file(infname, outfname, key):
transform_file(infname, outfname, key, decrypt_chunk)
| zhemao/bootlegger | bootlegger/cryptfile.py | Python | bsd-2-clause | 1,195 |
using Lombiq.Vsix.Orchard.Models;
using System.Collections.Generic;
using System.Linq;
namespace Lombiq.Vsix.Orchard.Services.DependencyInjector
{
public class SimplifiedFieldNameFromGenericTypeGenerator : FieldNameFromGenericTypeGeneratorBase
{
private static IEnumerable<string> SimplifiedGenericTypes = new[]
{
"UserManager",
"ILogger"
};
public override double Priority => 15;
public override bool CanGenerate(string dependency) =>
base.CanGenerate(dependency) && SimplifiedGenericTypes.Any(type => dependency.StartsWith(type));
public override DependencyInjectionData Generate(string dependency, bool useShortName)
{
// Default implementation to handle dependencies with generic types. It places the generic parameter right
// after the underscore and the generic type to the end.
var segments = GetGenericTypeSegments(dependency);
return new DependencyInjectionData
{
FieldName = useShortName ?
GetShortNameWithUnderscore(segments.CleanedGenericTypeName) :
GetStringWithUnderscore(GetCamelCased(segments.CleanedGenericTypeName)),
FieldType = dependency,
ConstructorParameterName = useShortName ?
GetShortName(GetCamelCased(segments.CleanedGenericTypeName)) :
GetCamelCased(segments.CleanedGenericTypeName),
ConstructorParameterType = dependency
};
}
}
}
| Lombiq/Lombiq-Visual-Studio-Extension | Lombiq.Vsix.Orchard/Services/DependencyInjector/SimplifiedFieldNameFromGenericTypeGenerator.cs | C# | bsd-2-clause | 1,640 |
#!/bin/env ruby
# \[XR[hÌShiftJIS¶ñðGR[h·é
# includeµÄ¢é"*.h"ð"*.hxx"É«·¦é
require "kconv"
while ($<.gets)
line=Kconv::tosjis($_)
if (line=~/^[ ]*#include[ ]"/)!=nil
line.gsub!(/"([^"]*)\.h"/) do "\""+$1+".hxx\"" end
end
kanji1=0
line.each_byte do |c|
if kanji1==0
if (((c^0x20)-0xa1)&0xff)<=0x3b
# SJIS
# 0x00-0x7f ASCII
# 0x80-0x9f,0xe0-0xfc ¢íäéSp1oCgÚ
# 0xa0-0xdf ¢íäé¼pJi
# ¿ÈÝÉ2oCgÚÍ0x40-0xfc
kanji1=c
else
putc c
end
else
# printf "\\x%x\\x%x",kanji1,c
printf "\\%03o\\%03o",kanji1,c
kanji1=0
end
end
end
| kawari/kawari7 | src/sjis2ascii.rb | Ruby | bsd-2-clause | 642 |
import os.path
import subprocess
import sys
import prob_util
CODEBASE_DIR = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).strip('\n')
MALE_NAME_FILE = os.path.join(CODEBASE_DIR, 'data', 'male-first.txt')
FEMALE_NAME_FILE = os.path.join(CODEBASE_DIR, 'data', 'female-first.txt')
LASTNAME_FILE = os.path.join(CODEBASE_DIR, 'data', 'lastnames.txt')
def load_name_data(fpath):
""" Loads name data as list of names paired with frequency """
with open(fpath, 'r') as fp:
data = [x.split(' ') for x in fp.read().split('\n') if len(x) > 0]
stat_data = [(x[0], float(x[1])) for x in data]
total = [freq for _, freq in stat_data]
scale = 100.0 / sum(total)
stat_data = [(name, scale * freq / 100.0) for name, freq in stat_data]
assert abs(1.0 - sum([freq for _,freq in stat_data])) < 1e-6, "Frequencies should sum to 1.0"
return stat_data
def load_all_names():
files = [MALE_NAME_FILE, FEMALE_NAME_FILE, LASTNAME_FILE]
lists = [ ]
for file in files:
lists.append(load_name_data(file))
male_freq_list = prob_util.freq_list_from_tuple_list(lists[0])
female_freq_list = prob_util.freq_list_from_tuple_list(lists[1])
last_freq_list = prob_util.freq_list_from_tuple_list(lists[2])
return male_freq_list, female_freq_list, last_freq_list
"""
if __name__ == "__main__":
infile = sys.argv[1]
outfile = sys.argv[2] if len(sys.argv) > 2 else sys.argv[1]
with open(infile, "r") as inf:
raw = inf.read()
raw = raw.split('\n')
freq_names = []
for line in raw:
if len(line) < 1:
continue
line = [l for l in line.split(' ') if len(l) > 0]
freq_names.append( (line[0], line[1]) )
with open(outfile, "w+") as outf:
for name, freq in freq_names:
outf.write(name + ' ' + freq + '\n')
"""
| iveygman/namegen | util/names.py | Python | bsd-2-clause | 1,858 |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XenAdmin.Controls;
using XenAdmin.Network;
using XenAPI;
using XenAdmin.Actions;
using XenAdmin.Commands;
namespace XenAdmin.Dialogs
{
public partial class MoveVirtualDiskDialog : XenDialogBase
{
private const int BATCH_SIZE = 3;
private readonly List<VDI> _vdisToMove;
private readonly List<VDI> _vdisToMigrate;
/// <summary>
/// Designer support only. Do not use.
/// </summary>
public MoveVirtualDiskDialog()
{
InitializeComponent();
}
public MoveVirtualDiskDialog(IXenConnection connection, List<VDI> vdisToMove, List<VDI> vdisToMigrate)
: base(connection)
{
InitializeComponent();
//set those so we don't have to bother with null checks further down
_vdisToMove = vdisToMove ?? new List<VDI>();
_vdisToMigrate = vdisToMigrate ?? new List<VDI>();
if (_vdisToMove.Count > 0)
{
srPicker1.Usage = SrPicker.SRPickerType.MoveOrCopy;
srPicker1.SetExistingVDIs(_vdisToMove.ToArray());
srPicker1.DiskSize = _vdisToMove.Sum(d => d.physical_utilisation);
}
else if (_vdisToMigrate.Count > 0)
{
srPicker1.Usage = SrPicker.SRPickerType.Migrate;
srPicker1.SetExistingVDIs(_vdisToMigrate.ToArray());
srPicker1.DiskSize = _vdisToMigrate.Sum(d => d.physical_utilisation);
}
srPicker1.SrHint.Visible = false;
srPicker1.Connection = connection;
srPicker1.srListBox.Invalidate();
srPicker1.selectDefaultSROrAny();
}
private SR SelectedSR
{
get { return srPicker1.SR; }
}
private void srPicker1_ItemSelectionNull()
{
updateButtons();
}
private void srPicker1_ItemSelectionNotNull()
{
updateButtons();
}
void SRPicker_DoubleClickOnRow(object sender, EventArgs e)
{
if (buttonMove.Enabled)
buttonMove.PerformClick();
}
private void updateButtons()
{
buttonMove.Enabled = srPicker1.SR != null;
}
private void buttonMove_Click(object sender, EventArgs e)
{
CreateAndRunParallelActions();
Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
Close();
}
private void CreateAndRunParallelActions()
{
if (_vdisToMigrate.Count == 1)
{
new MigrateVirtualDiskAction(connection, _vdisToMigrate[0], SelectedSR).RunAsync();
}
else if (_vdisToMigrate.Count > 1)
{
string title = string.Format(Messages.ACTION_MIGRATING_X_VDIS, _vdisToMigrate.Count, SelectedSR.name_label);
var batch = from VDI vdi in _vdisToMigrate
select (AsyncAction)new MigrateVirtualDiskAction(connection, vdi, SelectedSR);
new ParallelAction(connection, title, Messages.ACTION_MIGRATING_X_VDIS_STARTED,
Messages.ACTION_MIGRATING_X_VDIS_COMPLETED, batch.ToList(), BATCH_SIZE).RunAsync();
}
if (_vdisToMove.Count == 1)
{
new MoveVirtualDiskAction(connection, _vdisToMove[0], SelectedSR).RunAsync();
}
else if (_vdisToMove.Count > 1)
{
string title = string.Format(Messages.ACTION_MOVING_X_VDIS, _vdisToMove.Count, SelectedSR.name_label);
var batch = from VDI vdi in _vdisToMove
select (AsyncAction)new MoveVirtualDiskAction(connection, vdi, SelectedSR);
new ParallelAction(connection, title, Messages.ACTION_MOVING_X_VDIS_STARTED,
Messages.ACTION_MOVING_X_VDIS_COMPLETED, batch.ToList(), BATCH_SIZE).RunAsync();
}
}
internal override string HelpName
{
get { return "VDIMigrateDialog"; }
}
internal static Command MoveMigrateCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection)
{
var cmd = new MigrateVirtualDiskCommand(mainWindow, selection);
if (cmd.CanExecute())
return cmd;
return new MoveVirtualDiskCommand(mainWindow, selection);
}
}
}
| Frezzle/xenadmin | XenAdmin/Dialogs/MoveVirtualDiskDialog.cs | C# | bsd-2-clause | 6,229 |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using BLToolkit.DataAccess;
using BLToolkit.Reflection;
using bv.common.Core;
using bv.common.Enums;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using bv.winclient.BasePanel;
using bv.winclient.Core;
using eidss.model.Enums;
using eidss.model.Schema;
using eidss.winclient.Schema;
using eidss.model.Core;
namespace eidss.winclient.Vet
{
public partial class VetCaseListPanel : BaseListPanel_VetCaseListItem
{
public VetCaseListPanel()
{
InitializeComponent();
SearchPanelLabelWidth = 194;
}
public override void ShowReport()
{
if (FocusedItem != null)
{
var item = ((VetCaseListItem)FocusedItem);
if (item.idfsCaseType == (long)CaseTypeEnum.Avian)
{
EidssSiteContext.ReportFactory.VetAvianInvestigation(item.idfCase, item.idfsDiagnosis ?? 0);
}
else
{
EidssSiteContext.ReportFactory.VetLivestockInvestigation(item.idfCase, item.idfsDiagnosis ?? 0);
}
}
}
public override string GetDetailFormName(IObject o)
{
string name = ((VetCaseListItem) o).idfsCaseType == (long) CaseTypeEnum.Avian
? "VetCaseAvianDetail"
: "VetCaseLiveStockDetail";
return name;
}
public override List<object> GetParamsAction()
{
return FocusedItem == null
? null
: new List<object> { FocusedItem.Key, FocusedItem };
}
public static void Register(Control parentControl)
{
RegisterItem("MenuVetCase", 300, false);
RegisterItem("ToolbarFindVetCase", 190, true);
}
private static void RegisterItem(string resourceKey, int order, bool showInToolbar)
{
//TODO вставить правильные иконки
new MenuAction(ShowMe, MenuActionManager.Instance, MenuActionManager.Instance.Journals,
resourceKey, order, showInToolbar, (int)MenuIconsSmall.SearchVetCase,
(int)MenuIcons.SearchVetCase)
{
SelectPermission = PermissionHelper.SelectPermission(EIDSSPermissionObject.VetCase),
ShowInMenu = !showInToolbar
};
}
private static void ShowMe()
{
BaseFormManager.ShowClient(typeof(VetCaseListPanel), BaseFormManager.MainForm,
VetCaseListItem.CreateInstance());
}
public override void SetCustomActions(List<ActionMetaItem> actions)
{
base.SetCustomActions(actions);
SetActionFunction(actions, "CreateLivestock", CreateLivestock);
SetActionFunction(actions, "CreateAvian", CreateAvian);
}
private static ActResult CreateLivestock(DbManagerProxy manager, IObject bo, List<object> parameters)
{
return Create(parameters, CaseTypeEnum.Livestock);
}
private static ActResult CreateAvian(DbManagerProxy manager, IObject bo, List<object> parameters)
{
return Create(parameters, CaseTypeEnum.Avian);
}
private static bool Create(List<object> parameters, CaseTypeEnum caseType)
{
if (!(parameters[2] is IBaseListPanel))
{
throw new TypeMismatchException("listPanel", typeof (IBaseListPanel));
}
var listPanel = ((IBaseListPanel) parameters[2]);
object key = null;
var vetCase = (VetCaseListItem) TypeAccessor.CreateInstance(typeof (VetCaseListItem));
vetCase.idfsCaseType = (long) caseType;
listPanel.Edit(key, new List<object> {key, vetCase, listPanel}, ActionTypes.Create, false);
return true;
}
private VetCaseListItem m_VetCaseListItem;
protected override void HidePersonalData(List<VetCaseListItem> list)
{
bool hideAddress =
EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details);
bool hideSettlement =
EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement);
if (hideSettlement || hideAddress)
{
if (m_VetCaseListItem == null )
{
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
{
////object creation
IObjectCreator meta = ObjectAccessor.CreatorInterface(typeof(VetCaseListItem));
m_VetCaseListItem = meta.CreateNew(manager, null, null) as VetCaseListItem;
}
}
foreach (var item in list)
{
item.strOwnerFirstName = "*";
item.strOwnerLastName = "*";
item.strOwnerMiddleName = "*";
m_VetCaseListItem.idfsCountry = item.idfsCountry;
m_VetCaseListItem.idfsRegion = item.idfsRegion;
m_VetCaseListItem.idfsRayon = item.idfsRayon;
if (hideSettlement)
item.AddressName = Utils.Join(",",
new[]
{
"*",
m_VetCaseListItem.RayonLookup.Find(
c => c.idfsRayon == item.idfsRayon).strRayonName,
m_VetCaseListItem.RegionLookup.Find(
c => c.idfsRegion == item.idfsRegion).strRegionName
//,
//m_VetCaseListItem.CountryLookup.Find(
// c => c.idfsCountry == item.idfsCountry).
// strCountryName
});
else
item.AddressName = Utils.Join(",",
new[]
{
"*",
m_VetCaseListItem.SettlementLookup.Find(
c => c.idfsSettlement == item.idfsSettlement).
strSettlementName,
m_VetCaseListItem.RayonLookup.Find(
c => c.idfsRayon == item.idfsRayon).strRayonName,
m_VetCaseListItem.RegionLookup.Find(
c => c.idfsRegion == item.idfsRegion).strRegionName//,
//m_VetCaseListItem.CountryLookup.Find(
// c => c.idfsCountry == item.idfsCountry).
// strCountryName
});
}
}
}
/*perm!!
public override void CheckActionPermission(ActionMetaItem action, ref bool showAction)
{
switch (action.Name)
{
case "CreateAvian":
showAction = showAction && EidssUserContext.User.HasPermission(PermissionHelper.InsertPermission(EIDSSPermissionObject.VetCase)) && !ReadOnly;
return;
case "CreateLivestock":
showAction = showAction && EidssUserContext.User.HasPermission(PermissionHelper.InsertPermission(EIDSSPermissionObject.VetCase)) && !ReadOnly;
return;
case "Delete":
showAction = showAction && EidssUserContext.User.HasPermission(PermissionHelper.DeletePermission(EIDSSPermissionObject.VetCase)) && !ReadOnly;
return;
}
}*/
}
}
| EIDSS/EIDSS-Legacy | EIDSS v5/eidss.winclient/Vet/VetCaseListPanel.cs | C# | bsd-2-clause | 9,268 |
cask 'rekordbox' do
version '5.8.5'
sha256 'da2a2e67c6bafa1b96439b8e20c4d1713139802e91c86a2391ac61e7cf32adaa'
url "https://rekordbox.com/_app/files/Install_rekordbox_#{version.dots_to_underscores}.pkg.zip"
appcast 'https://rekordbox.com/en/support/releasenote.php'
name 'rekordbox'
homepage 'https://rekordbox.com/en/'
auto_updates true
depends_on macos: '>= :yosemite'
pkg "Install_rekordbox_#{version.dots_to_underscores}.pkg"
uninstall pkgutil: "com.pioneer.rekordbox.#{version.major}.*",
delete: "/Applications/rekordbox #{version.major}"
zap trash: [
'~/Library/Application Support/Pioneer/rekordbox',
'~/Library/Pioneer/rekordbox',
]
end
| lantrix/homebrew-cask | Casks/rekordbox.rb | Ruby | bsd-2-clause | 727 |
/*!
* OS.js - JavaScript Cloud/Web Desktop Platform
*
* Copyright (c) 2011-2016, Anders Evenrud <andersevenrud@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Anders Evenrud <andersevenrud@gmail.com>
* @licence Simplified BSD License
*/
(function(_osjs, _http, _path, _url, _fs, _qs, _multipart, Cookies) {
'use strict';
var instance, server;
/////////////////////////////////////////////////////////////////////////////
// HELPERS
/////////////////////////////////////////////////////////////////////////////
/**
* Respond to HTTP Call
*/
function respond(data, mime, response, headers, code, pipeFile) {
data = data || '';
headers = headers || [];
mime = mime || 'text/html; charset=utf-8';
code = code || 200;
function _end() {
if ( instance.handler && instance.handler.onRequestEnd ) {
instance.handler.onRequestEnd(null, response);
}
response.end();
}
for ( var i = 0; i < headers.length; i++ ) {
response.writeHead.apply(response, headers[i]);
}
response.writeHead(code, {'Content-Type': mime});
if ( pipeFile ) {
var stream = _fs.createReadStream(pipeFile, {bufferSize: 64 * 1024});
stream.on('end', function() {
_end();
});
stream.pipe(response);
} else {
response.write(data);
_end();
}
}
/**
* Respond with JSON data
*/
function respondJSON(data, response, headers) {
data = JSON.stringify(data);
if ( instance.config.logging ) {
console.log('>>>', 'application/json');
}
respond(data, 'application/json', response, headers);
}
/**
* Respond with a file
*/
function respondFile(path, request, response, jpath) {
var fullPath = jpath ? path : instance.vfs.getRealPath(path, instance.config, request).root;
_fs.exists(fullPath, function(exists) {
if ( exists ) {
var mime = instance.vfs.getMime(fullPath, instance.config);
if ( instance.config.logging ) {
console.log('>>>', mime, path);
}
respond(null, mime, response, null, null, fullPath);
} else {
if ( instance.config.logging ) {
console.log('!!!', '404', fullPath);
}
respond('404 Not Found', null, response, null, 404);
}
});
}
/**
* Handles file requests
*/
function fileGET(path, request, response, arg) {
if ( !arg ) {
if ( instance.config.logging ) {
console.log('===', 'FileGET', path);
}
try {
instance.handler.checkPrivilege(request, response, 'vfs');
} catch ( e ) {
respond(e, 'text/plain', response, null, 500);
}
}
respondFile(unescape(path), request, response, arg);
}
/**
* Handles file uploads
*/
function filePOST(fields, files, request, response) {
try {
instance.handler.checkPrivilege(request, response, 'upload');
} catch ( e ) {
respond(e, 'text/plain', response, null, 500);
}
instance.vfs.upload([
files.upload.path,
files.upload.name,
fields.path,
String(fields.overwrite) === 'true'
], request, function(err, result) {
if ( err ) {
respond(err, 'text/plain', response, null, 500);
} else {
respond(result, 'text/plain', response);
}
}, instance.config);
}
/**
* Handles Core API HTTP Request
*/
function coreAPI(url, path, POST, request, response) {
if ( path.match(/^\/API/) ) {
try {
var data = JSON.parse(POST);
var method = data.method;
var args = data['arguments'] || {};
if ( instance.config.logging ) {
console.log('===', 'CoreAPI', method, args);
}
instance.request(method, args, function(error, result) {
respondJSON({result: result, error: error}, response);
}, request, response);
} catch ( e ) {
console.error('!!! Caught exception', e);
console.warn(e.stack);
respondJSON({result: null, error: '500 Internal Server Error: ' + e}, response);
}
return true;
}
return false;
}
/**
* Handles a HTTP Request
*/
function httpCall(request, response) {
var url = _url.parse(request.url, true),
path = decodeURIComponent(url.pathname),
cookies = new Cookies(request, response);
request.cookies = cookies;
if ( path === '/' ) {
path += 'index.html';
}
if ( instance.config.logging ) {
console.log('<<<', path);
}
if ( instance.handler && instance.handler.onRequestStart ) {
instance.handler.onRequestStart(request, response);
}
if ( request.method === 'POST' ) {
if ( path.match(/^\/FS$/) ) { // File upload
var form = new _multipart.IncomingForm({
uploadDir: instance.config.tmpdir
});
form.parse(request, function(err, fields, files) {
if ( err ) {
if ( instance.config.logging ) {
console.log('>>>', 'ERR', 'Error on form parse', err);
}
} else {
filePOST(fields, files, request, response);
}
});
} else { // API Calls
var body = '';
request.on('data', function(data) {
body += data;
});
request.on('end', function() {
if ( !coreAPI(url, path, body, request, response) ) {
if ( instance.config.logging ) {
console.log('>>>', '404', path);
}
respond('404 Not Found', null, response, [[404, {}]]);
}
});
}
} else { // File reads
if ( path.match(/^\/FS/) ) {
fileGET(path.replace(/^\/FS/, ''), request, response, false);
} else {
fileGET(_path.join(instance.config.distdir, path.replace(/^\//, '')), request, response, true);
}
}
}
/////////////////////////////////////////////////////////////////////////////
// EXPORTS
/////////////////////////////////////////////////////////////////////////////
/**
* Create HTTP server and listen
*
* @param Object setup Configuration (see osjs.js)
*
* @option setup int port Listening port (default=null/auto)
* @option setup String dirname Server running dir (ex: /osjs/src/server/node)
* @option setup String root Installation root directory (ex: /osjs)
* @option setup String dist Build root directory (ex: /osjs/dist)
* @option setup boolean nw NW build (default=false)
* @option setup boolean logging Enable logging (default=true)
*
* @api http.listen
*/
module.exports.listen = function(setup) {
instance = _osjs.init(setup);
server = _http.createServer(httpCall);
if ( setup.logging !== false ) {
console.log(JSON.stringify(instance.config, null, 2));
}
if ( instance.handler && instance.handler.onServerStart ) {
instance.handler.onServerStart(instance.config);
}
server.listen(setup.port || instance.config.port);
};
/**
* Closes the active HTTP server
*
* @param Function cb Callback function
*
* @api http.close
*/
module.exports.close = function(cb) {
cb = cb || function() {};
if ( instance.handler && instance.handler.onServerEnd ) {
instance.handler.onServerEnd(instance.config);
}
if ( server ) {
server.close(cb);
} else {
cb();
}
};
})(
require('osjs'),
require('http'),
require('path'),
require('url'),
require('node-fs-extra'),
require('querystring'),
require('formidable'),
require('cookies')
);
| afang/OS.js-Apps | src/server/node/http.js | JavaScript | bsd-2-clause | 9,042 |
require(['lib/domReady', 'match'], function (domReady, matchClass) {
// Don't let events bubble up
if (Event.halt === undefined) {
// Don't let events bubble up
Event.prototype.halt = function () {
this.stopPropagation();
this.preventDefault();
};
};
// Add toggleClass method similar to jquery
HTMLElement.prototype.toggleClass = function (c1, c2) {
var cl = this.classList;
if (cl.contains(c1)) {
cl.add(c2);
cl.remove(c1);
}
else {
cl.remove(c2);
cl.add(c1);
};
};
domReady(function () {
var inactiveLi = document.querySelectorAll(
'#search > ol > li:not(.active)'
);
var i = 0;
for (i = 0; i < inactiveLi.length; i++) {
inactiveLi[i].addEventListener('click', function (e) {
if (this._match !== undefined) {
if (this._match.open())
e.halt();
}
else {
matchClass.create(this).open();
};
});
};
});
});
| KorAP/Rabbid | dev/js/src/app.js | JavaScript | bsd-2-clause | 946 |
class Swiftformat < Formula
desc "Formatting tool for reformatting Swift code"
homepage "https://github.com/nicklockwood/SwiftFormat"
url "https://github.com/nicklockwood/SwiftFormat/archive/0.33.7.tar.gz"
sha256 "e48534f2d2df4cc02dacdfb1af8653a8e1d1399685f8b38bf3a9ba7990cdf343"
head "https://github.com/nicklockwood/SwiftFormat.git", :shallow => false
bottle do
cellar :any_skip_relocation
sha256 "5f65bd9463728af018dc533a34c0e97a4ba8d558140385039693ce01bc48c6e0" => :high_sierra
sha256 "4b918cf20bffa40345abc9807abf9101c1ac5ca30f0da808fe78e395ad597b0d" => :sierra
end
depends_on :xcode => ["9.0", :build]
def install
xcodebuild "-project",
"SwiftFormat.xcodeproj",
"-scheme", "SwiftFormat (Command Line Tool)",
"CODE_SIGN_IDENTITY=",
"SYMROOT=build", "OBJROOT=build"
bin.install "build/Release/swiftformat"
end
test do
(testpath/"potato.swift").write <<~EOS
struct Potato {
let baked: Bool
}
EOS
system "#{bin}/swiftformat", "#{testpath}/potato.swift"
end
end
| moderndeveloperllc/homebrew-core | Formula/swiftformat.rb | Ruby | bsd-2-clause | 1,076 |
// -*- coding: utf-8 -*-
// Copyright (C) 2006-2012 Rosen Diankov <rosen.diankov@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "plugindefs.h"
#include <openrave/plugin.h>
namespace drchubo_v2_leftarm_ikfast { IkSolverBasePtr CreateIkSolver(EnvironmentBasePtr, std::istream& sinput, const std::vector<dReal>&vfreeinc); }
namespace drchubo_v2_rightarm_ikfast { IkSolverBasePtr CreateIkSolver(EnvironmentBasePtr, std::istream& sinput, const std::vector<dReal>&vfreeinc); }
namespace drchubo_v2_leftleg_ikfast { IkSolverBasePtr CreateIkSolver(EnvironmentBasePtr, std::istream& sinput, const std::vector<dReal>&vfreeinc); }
namespace drchubo_v2_rightleg_ikfast { IkSolverBasePtr CreateIkSolver(EnvironmentBasePtr, std::istream& sinput, const std::vector<dReal>&vfreeinc); }
IkSolverBasePtr CreateIkSolverFromName(const string& _name, const std::vector<dReal>& vfreeinc, EnvironmentBasePtr penv);
ModuleBasePtr CreateIkFastModule(EnvironmentBasePtr penv, std::istream& sinput);
void DestroyIkFastLibraries();
InterfaceBasePtr CreateInterfaceValidated(InterfaceType type, const std::string& interfacename, std::istream& sinput, EnvironmentBasePtr penv)
{
switch(type) {
case PT_IkSolver: {
if( interfacename == "ikfast" ) {
string ikfastname;
sinput >> ikfastname;
if( !!sinput ) {
vector<dReal> vfreeinc((istream_iterator<dReal>(sinput)), istream_iterator<dReal>());
// look at all the ikfast problem solvers
IkSolverBasePtr psolver = CreateIkSolverFromName(ikfastname, vfreeinc, penv);
if( !!psolver ) {
return psolver;
}
}
}
else {
vector<dReal> vfreeinc((istream_iterator<dReal>(sinput)), istream_iterator<dReal>());
if( interfacename == "drchubo_v2_leftarm_ikfast" ) {
return drchubo_v2_leftarm_ikfast::CreateIkSolver(penv, sinput, vfreeinc);
}
else if( interfacename == "drchubo_v2_rightarm_ikfast" ) {
return drchubo_v2_rightarm_ikfast::CreateIkSolver(penv, sinput, vfreeinc);
}
else if( interfacename == "drchubo_v2_leftleg_ikfast" ) {
return drchubo_v2_leftleg_ikfast::CreateIkSolver(penv, sinput, vfreeinc);
}
else if( interfacename == "drchubo_v2_rightleg_ikfast" ) {
return drchubo_v2_rightleg_ikfast::CreateIkSolver(penv, sinput, vfreeinc);
}
}
break;
}
case PT_Module:
if( interfacename == "ikfast") {
return CreateIkFastModule(penv,sinput);
}
break;
default:
break;
}
return InterfaceBasePtr();
}
void GetPluginAttributesValidated(PLUGININFO& info)
{
info.interfacenames[PT_IkSolver].push_back("drchubo_v2_leftarm_ikfast");
info.interfacenames[PT_IkSolver].push_back("drchubo_v2_rightarm_ikfast");
info.interfacenames[PT_IkSolver].push_back("drchubo_v2_leftleg_ikfast");
info.interfacenames[PT_IkSolver].push_back("drchubo_v2_rightleg_ikfast");
}
OPENRAVE_PLUGIN_API void DestroyPlugin()
{
DestroyIkFastLibraries();
}
| benersuay/drchubo_v2_ikfast | src/drchubo_v2_ikfastsolvers.cpp | C++ | bsd-2-clause | 3,827 |
package org.kodejava.example.jdbc;
import java.sql.*;
public class DriverPropertyInfoDemo {
private static final String URL = "jdbc:mysql://localhost/kodejava";
public static void main(String[] args) {
try {
// Gets information about the possible properties for this
// driver.
Driver driver = DriverManager.getDriver(URL);
DriverPropertyInfo[] props = driver.getPropertyInfo(URL, null);
for (DriverPropertyInfo info : props) {
System.out.println("-----------------------------------");
System.out.println("Name : " + info.name);
System.out.println("Description: " + info.description);
System.out.println("Value : " + info.value);
String[] choices = info.choices;
if (choices != null) {
StringBuilder sb = new StringBuilder("Choices : ");
for (String choice : choices) {
sb.append(choice).append(",");
}
System.out.println(sb.toString());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| kodejava/kodejava.project | kodejava-jdbc/src/main/java/org/kodejava/example/jdbc/DriverPropertyInfoDemo.java | Java | bsd-2-clause | 1,254 |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "Paper2DEditorPrivatePCH.h"
#include "STimelineTrack.h"
#include "GenericCommands.h"
#include "FlipbookEditorCommands.h"
#include "SFlipbookTrackHandle.h"
#include "AssetDragDropOp.h"
#include "PropertyCustomizationHelpers.h"
#define LOCTEXT_NAMESPACE "FlipbookEditor"
//////////////////////////////////////////////////////////////////////////
// SFlipbookKeyframeWidget
TSharedRef<SWidget> SFlipbookKeyframeWidget::GenerateContextMenu()
{
const FFlipbookEditorCommands& Commands = FFlipbookEditorCommands::Get();
OnSelectionChanged.ExecuteIfBound(FrameIndex);
FMenuBuilder MenuBuilder(true, CommandList);
{
FNumberFormattingOptions NoCommas;
NoCommas.UseGrouping = false;
const FText KeyframeSectionTitle = FText::Format(LOCTEXT("KeyframeActionsSectionHeader", "Keyframe #{0} Actions"), FText::AsNumber(FrameIndex, &NoCommas));
MenuBuilder.BeginSection("KeyframeActions", KeyframeSectionTitle);
// MenuBuilder.AddMenuEntry(FGenericCommands::Get().Cut);
// MenuBuilder.AddMenuEntry(FGenericCommands::Get().Copy);
// MenuBuilder.AddMenuEntry(FGenericCommands::Get().Paste);
MenuBuilder.AddMenuEntry(FGenericCommands::Get().Duplicate);
MenuBuilder.AddMenuEntry(FGenericCommands::Get().Delete);
MenuBuilder.AddMenuSeparator();
MenuBuilder.AddMenuEntry(Commands.AddNewFrameBefore);
MenuBuilder.AddMenuEntry(Commands.AddNewFrameAfter);
MenuBuilder.EndSection();
}
CommandList->MapAction(Commands.ShowInContentBrowser, FExecuteAction::CreateSP(this, &SFlipbookKeyframeWidget::ShowInContentBrowser));
CommandList->MapAction(Commands.EditSpriteFrame, FExecuteAction::CreateSP(this, &SFlipbookKeyframeWidget::EditKeyFrame));
{
TAttribute<FText> CurrentAssetTitle = TAttribute<FText>::Create(TAttribute<FText>::FGetter::CreateSP(this, &SFlipbookKeyframeWidget::GetKeyframeAssetName));
MenuBuilder.BeginSection("KeyframeAssetActions", CurrentAssetTitle);
MenuBuilder.AddMenuEntry(Commands.ShowInContentBrowser);
MenuBuilder.AddMenuEntry(Commands.EditSpriteFrame);
MenuBuilder.AddSubMenu(
Commands.PickNewSpriteFrame->GetLabel(),
Commands.PickNewSpriteFrame->GetDescription(),
FNewMenuDelegate::CreateSP(this, &SFlipbookKeyframeWidget::OpenSpritePickerMenu));
MenuBuilder.EndSection();
}
return MenuBuilder.MakeWidget();
}
void SFlipbookKeyframeWidget::Construct(const FArguments& InArgs, int32 InFrameIndex, TSharedPtr<FUICommandList> InCommandList)
{
FrameIndex = InFrameIndex;
CommandList = MakeShareable(new FUICommandList);
CommandList->Append(InCommandList.ToSharedRef());
SlateUnitsPerFrame = InArgs._SlateUnitsPerFrame;
FlipbookBeingEdited = InArgs._FlipbookBeingEdited;
OnSelectionChanged = InArgs._OnSelectionChanged;
// Color each region based on whether a sprite has been set or not for it
const auto BorderColorDelegate = [](TAttribute<UPaperFlipbook*> ThisFlipbookPtr, int32 TestIndex) -> FSlateColor
{
UPaperFlipbook* FlipbookPtr = ThisFlipbookPtr.Get();
const bool bFrameValid = (FlipbookPtr != nullptr) && (FlipbookPtr->GetSpriteAtFrame(TestIndex) != nullptr);
return bFrameValid ? FLinearColor::White : FLinearColor::Black;
};
ChildSlot
[
SNew(SOverlay)
+SOverlay::Slot()
[
SNew(SBox)
.Padding(FFlipbookUIConstants::FramePadding)
.WidthOverride(this, &SFlipbookKeyframeWidget::GetFrameWidth)
[
SNew(SBorder)
.BorderImage(FPaperStyle::Get()->GetBrush("FlipbookEditor.RegionBody"))
.BorderBackgroundColor_Static(BorderColorDelegate, FlipbookBeingEdited, FrameIndex)
.OnMouseButtonUp(this, &SFlipbookKeyframeWidget::KeyframeOnMouseButtonUp)
.ToolTipText(this, &SFlipbookKeyframeWidget::GetKeyframeTooltip)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.ColorAndOpacity(FLinearColor::Black)
.Text(this, &SFlipbookKeyframeWidget::GetKeyframeText)
]
]
]
+SOverlay::Slot()
.HAlign(HAlign_Right)
[
SNew(SBox)
.WidthOverride(FFlipbookUIConstants::HandleWidth)
[
SNew(SFlipbookTrackHandle)
.SlateUnitsPerFrame(SlateUnitsPerFrame)
.FlipbookBeingEdited(FlipbookBeingEdited)
.KeyFrameIdx(FrameIndex)
]
]
];
}
FReply SFlipbookKeyframeWidget::OnMouseButtonDown(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent)
{
if (MouseEvent.GetEffectingButton() == EKeys::LeftMouseButton)
{
return FReply::Handled().DetectDrag(SharedThis(this), EKeys::LeftMouseButton);
}
return FReply::Unhandled();
}
FReply SFlipbookKeyframeWidget::OnDragDetected(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent)
{
if (MouseEvent.IsMouseButtonDown(EKeys::LeftMouseButton))
{
UPaperFlipbook* Flipbook = FlipbookBeingEdited.Get();
if ((Flipbook != nullptr) && Flipbook->IsValidKeyFrameIndex(FrameIndex))
{
TSharedRef<FFlipbookKeyFrameDragDropOp> Operation = FFlipbookKeyFrameDragDropOp::New(
GetFrameWidth().Get(), Flipbook, FrameIndex);
return FReply::Handled().BeginDragDrop(Operation);
}
}
return FReply::Unhandled();
}
FReply SFlipbookKeyframeWidget::OnDrop(const FGeometry& MyGeometry, const FDragDropEvent& DragDropEvent)
{
bool bWasDropHandled = false;
UPaperFlipbook* Flipbook = FlipbookBeingEdited.Get();
if ((Flipbook != nullptr) && Flipbook->IsValidKeyFrameIndex(FrameIndex))
{
TSharedPtr<FDragDropOperation> Operation = DragDropEvent.GetOperation();
if (!Operation.IsValid())
{
}
else if (Operation->IsOfType<FAssetDragDropOp>())
{
const auto& AssetDragDropOp = StaticCastSharedPtr<FAssetDragDropOp>(Operation);
//@TODO: Handle asset inserts
// OnAssetsDropped(*AssetDragDropOp);
// bWasDropHandled = true;
}
else if (Operation->IsOfType<FFlipbookKeyFrameDragDropOp>())
{
const auto& FrameDragDropOp = StaticCastSharedPtr<FFlipbookKeyFrameDragDropOp>(Operation);
FrameDragDropOp->InsertInFlipbook(Flipbook, FrameIndex);
bWasDropHandled = true;
}
}
return bWasDropHandled ? FReply::Handled() : FReply::Unhandled();
}
FReply SFlipbookKeyframeWidget::KeyframeOnMouseButtonUp(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent)
{
if (MouseEvent.GetEffectingButton() == EKeys::RightMouseButton)
{
TSharedRef<SWidget> MenuContents = GenerateContextMenu();
FWidgetPath WidgetPath = MouseEvent.GetEventPath() != nullptr ? *MouseEvent.GetEventPath() : FWidgetPath();
FSlateApplication::Get().PushMenu(AsShared(), WidgetPath, MenuContents, MouseEvent.GetScreenSpacePosition(), FPopupTransitionEffect(FPopupTransitionEffect::ContextMenu));
return FReply::Handled();
}
return FReply::Unhandled();
}
// Can return null
const FPaperFlipbookKeyFrame* SFlipbookKeyframeWidget::GetKeyFrameData() const
{
UPaperFlipbook* Flipbook = FlipbookBeingEdited.Get();
if ((Flipbook != nullptr) && Flipbook->IsValidKeyFrameIndex(FrameIndex))
{
return &(Flipbook->GetKeyFrameChecked(FrameIndex));
}
return nullptr;
}
FText SFlipbookKeyframeWidget::GetKeyframeAssetName() const
{
if (const FPaperFlipbookKeyFrame* KeyFrame = GetKeyFrameData())
{
const FText SpriteLine = (KeyFrame->Sprite != nullptr) ? FText::FromString(KeyFrame->Sprite->GetName()) : LOCTEXT("NoSprite", "(none)");
return FText::Format(LOCTEXT("KeyFrameAssetName", "Current Asset: {0}"), SpriteLine);
}
else
{
return LOCTEXT("KeyFrameAssetName_None", "Current Asset: (none)");
}
}
FText SFlipbookKeyframeWidget::GetKeyframeText() const
{
if (const FPaperFlipbookKeyFrame* KeyFrame = GetKeyFrameData())
{
if (KeyFrame->Sprite != nullptr)
{
return FText::AsCultureInvariant(KeyFrame->Sprite->GetName());
}
}
return FText::GetEmpty();
}
FText SFlipbookKeyframeWidget::GetKeyframeTooltip() const
{
if (const FPaperFlipbookKeyFrame* KeyFrame = GetKeyFrameData())
{
const FText SpriteLine = (KeyFrame->Sprite != nullptr) ? FText::FromString(KeyFrame->Sprite->GetName()) : LOCTEXT("NoSprite", "(none)");
const FText FramesText = (KeyFrame->FrameRun == 1) ? LOCTEXT("SingularFrames", "frame") : LOCTEXT("PluralFrames", "frames");
return FText::Format(LOCTEXT("KeyFrameTooltip", "Sprite: {0}\nIndex: {1}\nDuration: {2} {3}"),
SpriteLine,
FText::AsNumber(FrameIndex),
FText::AsNumber(KeyFrame->FrameRun),
FramesText);
}
else
{
return LOCTEXT("KeyFrameTooltip_Invalid", "Invalid key frame index");
}
}
FOptionalSize SFlipbookKeyframeWidget::GetFrameWidth() const
{
if (const FPaperFlipbookKeyFrame* KeyFrame = GetKeyFrameData())
{
return FMath::Max<float>(0, KeyFrame->FrameRun * SlateUnitsPerFrame.Get());
}
else
{
return 1;
}
}
void SFlipbookKeyframeWidget::OpenSpritePickerMenu(FMenuBuilder& MenuBuilder)
{
const bool bAllowClear = true;
TArray<const UClass*> AllowedClasses;
AllowedClasses.Add(UPaperSprite::StaticClass());
FAssetData CurrentAssetData;
if (const FPaperFlipbookKeyFrame* KeyFrame = GetKeyFrameData())
{
CurrentAssetData = FAssetData(KeyFrame->Sprite);
}
TSharedRef<SWidget> AssetPickerWidget = PropertyCustomizationHelpers::MakeAssetPickerWithMenu(CurrentAssetData,
bAllowClear,
AllowedClasses,
PropertyCustomizationHelpers::GetNewAssetFactoriesForClasses(AllowedClasses),
FOnShouldFilterAsset(),
FOnAssetSelected::CreateSP(this, &SFlipbookKeyframeWidget::OnAssetSelected),
FSimpleDelegate::CreateSP(this, &SFlipbookKeyframeWidget::CloseMenu));
MenuBuilder.AddWidget(AssetPickerWidget, FText::GetEmpty(), /*bNoIndent=*/ true);
}
void SFlipbookKeyframeWidget::CloseMenu()
{
FSlateApplication::Get().DismissAllMenus();
}
void SFlipbookKeyframeWidget::OnAssetSelected(const FAssetData& AssetData)
{
if (UPaperFlipbook* Flipbook = FlipbookBeingEdited.Get())
{
FScopedFlipbookMutator EditLock(Flipbook);
if (EditLock.KeyFrames.IsValidIndex(FrameIndex))
{
UPaperSprite* NewSprite = Cast<UPaperSprite>(AssetData.GetAsset());
EditLock.KeyFrames[FrameIndex].Sprite = NewSprite;
}
}
}
void SFlipbookKeyframeWidget::ShowInContentBrowser()
{
if (const FPaperFlipbookKeyFrame* KeyFrame = GetKeyFrameData())
{
if (KeyFrame->Sprite != nullptr)
{
TArray<UObject*> ObjectsToSync;
ObjectsToSync.Add(KeyFrame->Sprite);
GEditor->SyncBrowserToObjects(ObjectsToSync);
}
}
}
void SFlipbookKeyframeWidget::EditKeyFrame()
{
if (const FPaperFlipbookKeyFrame* KeyFrame = GetKeyFrameData())
{
if (KeyFrame->Sprite != nullptr)
{
FAssetEditorManager::Get().OpenEditorForAsset(KeyFrame->Sprite);
}
}
}
//////////////////////////////////////////////////////////////////////////
// FFlipbookKeyFrameDragDropOp
TSharedPtr<SWidget> FFlipbookKeyFrameDragDropOp::GetDefaultDecorator() const
{
const FLinearColor BorderColor = (KeyFrameData.Sprite != nullptr) ? FLinearColor::White : FLinearColor::Black;
return SNew(SBox)
.WidthOverride(WidgetWidth - FFlipbookUIConstants::FramePadding.GetTotalSpaceAlong<Orient_Horizontal>())
.HeightOverride(FFlipbookUIConstants::FrameHeight - FFlipbookUIConstants::FramePadding.GetTotalSpaceAlong<Orient_Vertical>())
[
SNew(SBorder)
.BorderImage(FPaperStyle::Get()->GetBrush("FlipbookEditor.RegionBody"))
.BorderBackgroundColor(BorderColor)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.ColorAndOpacity(FLinearColor::Black)
.Text(BodyText)
]
];
}
void FFlipbookKeyFrameDragDropOp::OnDragged(const class FDragDropEvent& DragDropEvent)
{
if (CursorDecoratorWindow.IsValid())
{
CursorDecoratorWindow->MoveWindowTo(DragDropEvent.GetScreenSpacePosition());
}
}
void FFlipbookKeyFrameDragDropOp::Construct()
{
MouseCursor = EMouseCursor::GrabHandClosed;
if (UPaperFlipbook* Flipbook = SourceFlipbook.Get())
{
if (UPaperSprite* Sprite = Flipbook->GetSpriteAtFrame(SourceFrameIndex))
{
BodyText = FText::AsCultureInvariant(Sprite->GetName());
}
}
FDragDropOperation::Construct();
}
void FFlipbookKeyFrameDragDropOp::OnDrop(bool bDropWasHandled, const FPointerEvent& MouseEvent)
{
if (!bDropWasHandled)
{
// Add us back to our source, the drop fizzled
InsertInFlipbook(SourceFlipbook.Get(), SourceFrameIndex);
Transaction.Cancel();
}
}
void FFlipbookKeyFrameDragDropOp::AppendToFlipbook(UPaperFlipbook* DestinationFlipbook)
{
DestinationFlipbook->Modify();
FScopedFlipbookMutator EditLock(DestinationFlipbook);
EditLock.KeyFrames.Add(KeyFrameData);
}
void FFlipbookKeyFrameDragDropOp::InsertInFlipbook(UPaperFlipbook* DestinationFlipbook, int32 Index)
{
DestinationFlipbook->Modify();
FScopedFlipbookMutator EditLock(DestinationFlipbook);
EditLock.KeyFrames.Insert(KeyFrameData, Index);
}
TSharedRef<FFlipbookKeyFrameDragDropOp> FFlipbookKeyFrameDragDropOp::New(int32 InWidth, UPaperFlipbook* InFlipbook, int32 InFrameIndex)
{
// Create the drag-drop op containing the key
TSharedRef<FFlipbookKeyFrameDragDropOp> Operation = MakeShareable(new FFlipbookKeyFrameDragDropOp);
Operation->KeyFrameData = InFlipbook->GetKeyFrameChecked(InFrameIndex);
Operation->SourceFrameIndex = InFrameIndex;
Operation->SourceFlipbook = InFlipbook;
Operation->WidgetWidth = InWidth;
Operation->Construct();
// Remove the key from the flipbook
{
InFlipbook->Modify();
FScopedFlipbookMutator EditLock(InFlipbook);
EditLock.KeyFrames.RemoveAt(InFrameIndex);
}
return Operation;
}
FFlipbookKeyFrameDragDropOp::FFlipbookKeyFrameDragDropOp()
: Transaction(LOCTEXT("MovedFramesInTimeline", "Reorder key frames"))
{
}
//////////////////////////////////////////////////////////////////////////
// SFlipbookTimelineTrack
void SFlipbookTimelineTrack::Construct(const FArguments& InArgs, TSharedPtr<FUICommandList> InCommandList)
{
CommandList = InCommandList;
SlateUnitsPerFrame = InArgs._SlateUnitsPerFrame;
FlipbookBeingEdited = InArgs._FlipbookBeingEdited;
OnSelectionChanged = InArgs._OnSelectionChanged;
ChildSlot
[
SAssignNew(MainBoxPtr, SHorizontalBox)
];
Rebuild();
}
void SFlipbookTimelineTrack::Rebuild()
{
MainBoxPtr->ClearChildren();
// Create the sections for each keyframe
if (UPaperFlipbook* Flipbook = FlipbookBeingEdited.Get())
{
for (int32 KeyFrameIdx = 0; KeyFrameIdx < Flipbook->GetNumKeyFrames(); ++KeyFrameIdx)
{
MainBoxPtr->AddSlot()
.AutoWidth()
[
SNew(SFlipbookKeyframeWidget, KeyFrameIdx, CommandList)
.SlateUnitsPerFrame(this->SlateUnitsPerFrame)
.FlipbookBeingEdited(this->FlipbookBeingEdited)
.OnSelectionChanged(this->OnSelectionChanged)
];
}
}
}
#undef LOCTEXT_NAMESPACE
| PopCap/GameIdea | Engine/Plugins/2D/Paper2D/Source/Paper2DEditor/Private/FlipbookEditor/STimelineTrack.cpp | C++ | bsd-2-clause | 14,371 |
// Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Runtime.InteropServices.WindowsRuntime
// Name: WindowsRuntimeMarshal
// C++ Typed Name: mscorlib::System::Runtime::InteropServices::WindowsRuntime::WindowsRuntimeMarshal
#include <gtest/gtest.h>
#include <mscorlib/System/Runtime/InteropServices/WindowsRuntime/mscorlib_System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/Runtime/InteropServices/WindowsRuntime/mscorlib_System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken.h>
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace InteropServices
{
namespace WindowsRuntime
{
//Public Methods Tests
//Public Static Methods Tests
// Method AddEventHandler
// Signature: mscorlib::Callback<mscorlib::System::Runtime::InteropServices::WindowsRuntime::EventRegistrationToken (T )> addMethod, mscorlib::Callback<void (mscorlib::System::Runtime::InteropServices::WindowsRuntime::EventRegistrationToken )> removeMethod, T handler
TEST(mscorlib_System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal_Fixture,AddEventHandler_StaticTest)
{
}
// Method FreeHString
// Signature: mscorlib::System::IntPtr ptr
TEST(mscorlib_System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal_Fixture,FreeHString_StaticTest)
{
}
// Method GetActivationFactory
// Signature: mscorlib::System::Type type
TEST(mscorlib_System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal_Fixture,GetActivationFactory_StaticTest)
{
}
// Method PtrToStringHString
// Signature: mscorlib::System::IntPtr ptr
TEST(mscorlib_System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal_Fixture,PtrToStringHString_StaticTest)
{
}
// Method RemoveAllEventHandlers
// Signature: mscorlib::Callback<void (mscorlib::System::Runtime::InteropServices::WindowsRuntime::EventRegistrationToken )> removeMethod
TEST(mscorlib_System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal_Fixture,RemoveAllEventHandlers_StaticTest)
{
}
// Method RemoveEventHandler
// Signature: mscorlib::Callback<void (mscorlib::System::Runtime::InteropServices::WindowsRuntime::EventRegistrationToken )> removeMethod, T handler
TEST(mscorlib_System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal_Fixture,RemoveEventHandler_StaticTest)
{
}
// Method StringToHString
// Signature: mscorlib::System::String s
TEST(mscorlib_System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal_Fixture,StringToHString_StaticTest)
{
}
}
}
}
}
}
| brunolauze/MonoNative | MonoNative.Tests/mscorlib/System/Runtime/InteropServices/WindowsRuntime/mscorlib_System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal_Fixture.cpp | C++ | bsd-2-clause | 3,038 |
# pylint: disable=W0401
from .test_triggers import *
from .test_views import *
from .test_factories import *
from .test_path_filter import *
from .test_topology import *
from .test_path_split import *
from .test_filters import *
from .test_graph import *
from .test_forms import *
from .test_fields import *
from .test_models import *
| camillemonchicourt/Geotrek | geotrek/core/tests/__init__.py | Python | bsd-2-clause | 336 |
package sim.workload.swarm;
import sim.math.Exponential;
import sim.net.overlay.dht.PeerData;
public class KeysTestNormal extends Default {
public KeysTestNormal(String[] arglist) throws Exception {
super(arglist);
int highcap = Integer.parseInt(arglist[0]);
int lowcap = Integer.parseInt(arglist[1]);
int count = highcap + lowcap;
setupPeers(highcap, lowcap, 1.0, 1.0);
// 1 million puts
PeerData.quickHack();
// 10000 gets, exponentially distributed interval with 6 minute mean
generateRandomGets(new Exponential(360000), count * 10);
}
}
| bramp/p2psim | src/sim/workload/swarm/KeysTestNormal.java | Java | bsd-2-clause | 587 |
<table class="host_info">
<tr>
<td>
<b style='font-size:20px;'><a href="."><?php _host(); ?></a></b> <span style="font-size:12px;line-height:20px;">(<a target="blank" href="http://<?php _host('m_host'); ?>"><?php _host('m_host'); ?></a>)</span><br/>
<?php _host('m_desc') ?><br/>
<b>Hardware</b> <?php _e("HW_VER"); ?><br/>
<b>Firmware</b> <?php _e("FW_VER"); ?><br/>
<b>Software</b> <?php _e("SW_VER"); ?><br/>
<b>Serial Number</b> <?php _e("SERIAL_NUM"); ?><br>
<b>Uptime</b> <?php printf("%.1f",__e("UPTIME")/(24*60*60*100)); ?> days<br/>
<br>
<b>WLAN1 SSID</b> <?php _e("WLAN1_SSID"); ?><br>
<b>WLAN1 Band</b> <?php _e("WLAN1_CHAN_BAND"); ?><br>
<b>WLAN1 Frequency</b> <?php _e("WLAN1_CHAN_FREQ"); ?><br>
<b>WLAN1 SUs</b> <?php _e("WLAN1_SU_COUNT"); ?><br>
<br>
<b>WLAN2 SSID</b> <?php _e("WLAN2_SSID"); ?><br>
<b>WLAN2 Band</b> <?php _e("WLAN2_CHAN_BAND"); ?><br>
<b>WLAN2 Frequency</b> <?php _e("WLAN2_CHAN_FREQ"); ?><br>
<b>WLAN2 SUs</b> <?php _e("WLAN2_SU_COUNT"); ?><br>
</td>
<td class="center">
<?php _g("UPTIME"); ?><br/><hr/>
<?php _g("ETH_TRAFFIC_B"); ?><br/><hr/>
<?php _g("NM5_SFP1_TRAF"); ?><br/><hr/>
<?php _g("NM5_WLAN1_TRAF"); ?><br/><hr/>
<?php _g("NM5_WLAN2_TRAF"); ?><br/><hr/>
<?php _g("NM5_SU_COUNT"); ?><br/>
</td>
</tr>
</table>
<hr/>
<table class="subhost_preview">
<tr class="host_preview_header">
<td/>
<td>
Session Uptime
</td>
<td>
RSSI
</td>
<td>
SNR
</td>
<td>
RF Traffic
</td>
</tr>
{content}
</table>
| danpalamo/php-tsunami | templates/mtknm5/host_page.php | PHP | bsd-2-clause | 1,551 |
/* brass_table.cc: Btree implementation
*
* Copyright 1999,2000,2001 BrightStation PLC
* Copyright 2002 Ananova Ltd
* Copyright 2002,2003,2004,2005,2006,2007,2008,2009,2010,2011 Olly Betts
* Copyright 2008 Lemur Consulting Ltd
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include <config.h>
#include "brass_table.h"
#include <xapian/error.h>
#include "safeerrno.h"
#ifdef __WIN32__
# include "msvc_posix_wrapper.h"
#endif
#include "omassert.h"
#include "str.h"
#include "stringutils.h" // For STRINGIZE().
// Define to use "dangerous" mode - in this mode we write modified btree
// blocks back in place. This is somewhat faster (especially once we're
// I/O bound) but the database can't be safely searched during indexing
// and if indexing is terminated uncleanly, the database may be corrupt.
//
// Despite the risks, it's useful for speeding up a full rebuild.
//
// FIXME: make this mode run-time selectable, and record that it is currently
// in use somewhere on disk, so readers can check and refuse to open the
// database.
//
// #define DANGEROUS
#include <sys/types.h>
// Trying to include the correct headers with the correct defines set to
// get pread() and pwrite() prototyped on every platform without breaking any
// other platform is a real can of worms. So instead we probe for what
// prototypes (if any) are required in configure and put them into
// PREAD_PROTOTYPE and PWRITE_PROTOTYPE.
#if defined HAVE_PREAD && defined PREAD_PROTOTYPE
PREAD_PROTOTYPE
#endif
#if defined HAVE_PWRITE && defined PWRITE_PROTOTYPE
PWRITE_PROTOTYPE
#endif
#include <cstdio> /* for rename */
#include <cstring> /* for memmove */
#include <climits> /* for CHAR_BIT */
#include "brass_btreebase.h"
#include "brass_cursor.h"
#include "debuglog.h"
#include "io_utils.h"
#include "omassert.h"
#include "pack.h"
#include "unaligned.h"
#include "utils.h"
#include <algorithm> // for std::min()
#include <string>
using namespace Brass;
using namespace std;
// Only try to compress tags longer than this many bytes.
const size_t COMPRESS_MIN = 4;
//#define BTREE_DEBUG_FULL 1
#undef BTREE_DEBUG_FULL
#ifdef BTREE_DEBUG_FULL
/*------debugging aids from here--------*/
static void print_key(const byte * p, int c, int j);
static void print_tag(const byte * p, int c, int j);
/*
static void report_cursor(int N, Btree * B, Brass::Cursor * C)
{
int i;
printf("%d)\n", N);
for (i = 0; i <= B->level; i++)
printf("p=%d, c=%d, n=[%d], rewrite=%d\n",
C[i].p, C[i].c, C[i].n, C[i].rewrite);
}
*/
/*------to here--------*/
#endif /* BTREE_DEBUG_FULL */
static inline byte *zeroed_new(size_t size)
{
byte *temp = new byte[size];
// No need to check if temp is NULL, new throws std::bad_alloc if
// allocation fails.
Assert(temp);
memset(temp, 0, size);
return temp;
}
/* A B-tree comprises (a) a base file, containing essential information (Block
size, number of the B-tree root block etc), (b) a bitmap, the Nth bit of the
bitmap being set if the Nth block of the B-tree file is in use, and (c) a
file DB containing the B-tree proper. The DB file is divided into a sequence
of equal sized blocks, numbered 0, 1, 2 ... some of which are free, some in
use. Those in use are arranged in a tree.
Each block, b, has a structure like this:
R L M T D o1 o2 o3 ... oN <gap> [item] .. [item] .. [item] ...
<---------- D ----------> <-M->
And then,
R = REVISION(b) is the revision number the B-tree had when the block was
written into the DB file.
L = GET_LEVEL(b) is the level of the block, which is the number of levels
towards the root of the B-tree structure. So leaf blocks
have level 0 and the one root block has the highest level
equal to the number of levels in the B-tree.
M = MAX_FREE(b) is the size of the gap between the end of the directory and
the first item of data. (It is not necessarily the maximum
size among the bits of space that are free, but I can't
think of a better name.)
T = TOTAL_FREE(b)is the total amount of free space left in b.
D = DIR_END(b) gives the offset to the end of the directory.
o1, o2 ... oN are a directory of offsets to the N items held in the block.
The items are key-tag pairs, and as they occur in the directory are ordered
by the keys.
An item has this form:
I K key x C tag
<--K-->
<------I------>
A long tag presented through the API is split up into C tags small enough to
be accommodated in the blocks of the B-tree. The key is extended to include
a counter, x, which runs from 1 to C. The key is preceded by a length, K,
and the whole item with a length, I, as depicted above.
Here are the corresponding definitions:
*/
/** Flip to sequential addition block-splitting after this number of observed
* sequential additions (in negated form). */
#define SEQ_START_POINT (-10)
/* There are two bit maps in bit_map0 and bit_map. The nth bit of bitmap is 0
if the nth block is free, otherwise 1. bit_map0 is the initial state of
bitmap at the start of the current transaction.
Note use of the limits.h values:
UCHAR_MAX = 255, an unsigned with all bits set, and
CHAR_BIT = 8, the number of bits per byte
BYTE_PAIR_RANGE below is the smallest +ve number that can't be held in two
bytes -- 64K effectively.
*/
#define BYTE_PAIR_RANGE (1 << 2 * CHAR_BIT)
/// read_block(n, p) reads block n of the DB file to address p.
void
BrassTable::read_block(uint4 n, byte * p) const
{
// Log the value of p, not the contents of the block it points to...
LOGCALL_VOID(DB, "BrassTable::read_block", n | (void*)p);
/* Use the base bit_map_size not the bitmap's size, because
* the latter is uninitialised in readonly mode.
*/
Assert(n / CHAR_BIT < base.get_bit_map_size());
#ifdef HAVE_PREAD
off_t offset = off_t(block_size) * n;
int m = block_size;
while (true) {
ssize_t bytes_read = pread(handle, reinterpret_cast<char *>(p), m,
offset);
// normal case - read succeeded, so return.
if (bytes_read == m) break;
if (bytes_read == -1) {
if (errno == EINTR) continue;
if (errno == EBADF && handle == -2)
BrassTable::throw_database_closed();
string message = "Error reading block " + str(n) + ": ";
message += strerror(errno);
throw Xapian::DatabaseError(message);
} else if (bytes_read == 0) {
string message = "Error reading block " + str(n) + ": got end of file";
throw Xapian::DatabaseError(message);
} else if (bytes_read < m) {
/* Read part of the block, which is not an error. We should
* continue reading the rest of the block.
*/
m -= int(bytes_read);
p += bytes_read;
offset += bytes_read;
}
}
#else
if (lseek(handle, off_t(block_size) * n, SEEK_SET) == -1) {
if (errno == EBADF && handle == -2)
BrassTable::throw_database_closed();
string message = "Error seeking to block: ";
message += strerror(errno);
throw Xapian::DatabaseError(message);
}
io_read(handle, reinterpret_cast<char *>(p), block_size, block_size);
#endif
int dir_end = DIR_END(p);
if (rare(dir_end < DIR_START || unsigned(dir_end) > block_size)) {
string msg("dir_end invalid in block ");
msg += str(n);
throw Xapian::DatabaseCorruptError(msg);
}
}
/** write_block(n, p) writes block n in the DB file from address p.
* When writing we check to see if the DB file has already been
* modified. If not (so this is the first write) the old base is
* deleted. This prevents the possibility of it being opened
* subsequently as an invalid base.
*/
void
BrassTable::write_block(uint4 n, const byte * p) const
{
LOGCALL_VOID(DB, "BrassTable::write_block", n | p);
Assert(writable);
/* Check that n is in range. */
Assert(n / CHAR_BIT < base.get_bit_map_size());
/* don't write to non-free */;
AssertParanoid(base.block_free_at_start(n));
/* write revision is okay */
AssertEqParanoid(REVISION(p), latest_revision_number + 1);
if (both_bases) {
// Delete the old base before modifying the database.
//
// If the file is on NFS, then io_unlink() may return false even if
// the file was removed, so on balance throwing an exception in this
// case is unhelpful, since we wanted the file gone anyway! The
// likely explanation is that somebody moved, deleted, or changed a
// symlink to the database directory.
(void)io_unlink(name + "base" + other_base_letter());
both_bases = false;
latest_revision_number = revision_number;
}
#ifdef HAVE_PWRITE
off_t offset = off_t(block_size) * n;
int m = block_size;
while (true) {
ssize_t bytes_written = pwrite(handle, p, m, offset);
if (bytes_written == m) {
// normal case - write succeeded, so return.
return;
} else if (bytes_written == -1) {
if (errno == EINTR) continue;
string message = "Error writing block: ";
message += strerror(errno);
throw Xapian::DatabaseError(message);
} else if (bytes_written == 0) {
string message = "Error writing block: wrote no data";
throw Xapian::DatabaseError(message);
} else if (bytes_written < m) {
/* Wrote part of the block, which is not an error. We should
* continue writing the rest of the block.
*/
m -= bytes_written;
p += bytes_written;
offset += bytes_written;
}
}
#else
if (lseek(handle, (off_t)block_size * n, SEEK_SET) == -1) {
string message = "Error seeking to block: ";
message += strerror(errno);
throw Xapian::DatabaseError(message);
}
io_write(handle, reinterpret_cast<const char *>(p), block_size);
#endif
}
/* A note on cursors:
Each B-tree level has a corresponding array element C[j] in a
cursor, C. C[0] is the leaf (or data) level, and C[B->level] is the
root block level. Within a level j,
C[j].p addresses the block
C[j].c is the offset into the directory entry in the block
C[j].n is the number of the block at C[j].p
A look up in the B-tree causes navigation of the blocks starting
from the root. In each block, p, we find an offset, c, to an item
which gives the number, n, of the block for the next level. This
leads to an array of values p,c,n which are held inside the cursor.
Any Btree object B has a built-in cursor, at B->C. But other cursors may
be created. If BC is a created cursor, BC->C is the cursor in the
sense given above, and BC->B is the handle for the B-tree again.
*/
void
BrassTable::set_overwritten() const
{
LOGCALL_VOID(DB, "BrassTable::set_overwritten", NO_ARGS);
// If we're writable, there shouldn't be another writer who could cause
// overwritten to be flagged, so that's a DatabaseCorruptError.
if (writable)
throw Xapian::DatabaseCorruptError("Db block overwritten - are there multiple writers?");
throw Xapian::DatabaseModifiedError("The revision being read has been discarded - you should call Xapian::Database::reopen() and retry the operation");
}
/* block_to_cursor(C, j, n) puts block n into position C[j] of cursor
C, writing the block currently at C[j] back to disk if necessary.
Note that
C[j].rewrite
is true iff C[j].n is different from block n in file DB. If it is
false no rewriting is necessary.
*/
void
BrassTable::block_to_cursor(Brass::Cursor * C_, int j, uint4 n) const
{
LOGCALL_VOID(DB, "BrassTable::block_to_cursor", (void*)C_ | j | n);
if (n == C_[j].n) return;
byte * p = C_[j].p;
Assert(p);
// FIXME: only needs to be done in write mode
if (C_[j].rewrite) {
Assert(writable);
Assert(C == C_);
write_block(C_[j].n, p);
C_[j].rewrite = false;
}
// Check if the block is in the built-in cursor (potentially in
// modified form).
if (n == C[j].n) {
if (p != C[j].p)
memcpy(p, C[j].p, block_size);
} else {
read_block(n, p);
}
C_[j].n = n;
if (j < level) {
/* unsigned comparison */
if (rare(REVISION(p) > REVISION(C_[j + 1].p))) {
set_overwritten();
return;
}
}
if (rare(j != GET_LEVEL(p))) {
string msg = "Expected block ";
msg += str(j);
msg += ", not ";
msg += str(GET_LEVEL(p));
throw Xapian::DatabaseCorruptError(msg);
}
}
/** Btree::alter(); is called when the B-tree is to be altered.
It causes new blocks to be forced for the current set of blocks in
the cursor.
The point is that if a block at level 0 is to be altered it may get
a new number. Then the pointer to this block from level 1 will need
changing. So the block at level 1 needs altering and may get a new
block number. Then the pointer to this block from level 2 will need
changing ... and so on back to the root.
The clever bit here is spotting the cases when we can make an early
exit from this process. If C[j].rewrite is true, C[j+k].rewrite
will be true for k = 1,2 ... We have been through all this before,
and there is no need to do it again. If C[j].n was free at the
start of the transaction, we can copy it back to the same place
without violating the integrity of the B-tree. We don't then need a
new n and can return. The corresponding C[j].rewrite may be true or
false in that case.
*/
void
BrassTable::alter()
{
LOGCALL_VOID(DB, "BrassTable::alter", NO_ARGS);
Assert(writable);
#ifdef DANGEROUS
C[0].rewrite = true;
#else
int j = 0;
byte * p = C[j].p;
while (true) {
if (C[j].rewrite) return; /* all new, so return */
C[j].rewrite = true;
uint4 n = C[j].n;
if (base.block_free_at_start(n)) {
Assert(REVISION(p) == latest_revision_number + 1);
return;
}
Assert(REVISION(p) < latest_revision_number + 1);
base.free_block(n);
n = base.next_free_block();
C[j].n = n;
SET_REVISION(p, latest_revision_number + 1);
if (j == level) return;
j++;
p = C[j].p;
Item_wr(p, C[j].c).set_block_given_by(n);
}
#endif
}
/** find_in_block(p, key, leaf, c) searches for the key in the block at p.
leaf is true for a data block, and false for an index block (when the
first key is dummy and never needs to be tested). What we get is the
directory entry to the last key <= the key being searched for.
The lookup is by binary chop, with i and j set to the left and
right ends of the search area. In sequential addition, c will often
be the answer, so we test the keys round c and move i and j towards
c if possible.
*/
int
BrassTable::find_in_block(const byte * p, Key key, bool leaf, int c)
{
LOGCALL_STATIC(DB, int, "BrassTable::find_in_block", (const void*)p | (const void *)key.get_address() | leaf | c);
int i = DIR_START;
if (leaf) i -= D2;
int j = DIR_END(p);
if (c != -1) {
if (c < j && i < c && Item(p, c).key() <= key)
i = c;
c += D2;
if (c < j && i < c && key < Item(p, c).key())
j = c;
}
while (j - i > D2) {
int k = i + ((j - i)/(D2 * 2))*D2; /* mid way */
if (key < Item(p, k).key()) j = k; else i = k;
}
RETURN(i);
}
/** find(C_) searches for the key of B->kt in the B-tree.
Result is true if found, false otherwise. When false, the B_tree
cursor is positioned at the last key in the B-tree <= the search
key. Goes to first (null) item in B-tree when key length == 0.
*/
bool
BrassTable::find(Brass::Cursor * C_) const
{
LOGCALL(DB, bool, "BrassTable::find", (void*)C_);
// Note: the parameter is needed when we're called by BrassCursor
const byte * p;
int c;
Key key = kt.key();
for (int j = level; j > 0; --j) {
p = C_[j].p;
c = find_in_block(p, key, false, C_[j].c);
#ifdef BTREE_DEBUG_FULL
printf("Block in BrassTable:find - code position 1");
report_block_full(j, C_[j].n, p);
#endif /* BTREE_DEBUG_FULL */
C_[j].c = c;
block_to_cursor(C_, j - 1, Item(p, c).block_given_by());
}
p = C_[0].p;
c = find_in_block(p, key, true, C_[0].c);
#ifdef BTREE_DEBUG_FULL
printf("Block in BrassTable:find - code position 2");
report_block_full(0, C_[0].n, p);
#endif /* BTREE_DEBUG_FULL */
C_[0].c = c;
if (c < DIR_START) RETURN(false);
RETURN(Item(p, c).key() == key);
}
/** compact(p) compact the block at p by shuffling all the items up to the end.
MAX_FREE(p) is then maximized, and is equal to TOTAL_FREE(p).
*/
void
BrassTable::compact(byte * p)
{
LOGCALL_VOID(DB, "BrassTable::compact", (void*)p);
Assert(writable);
int e = block_size;
byte * b = buffer;
int dir_end = DIR_END(p);
for (int c = DIR_START; c < dir_end; c += D2) {
Item item(p, c);
int l = item.size();
e -= l;
memmove(b + e, item.get_address(), l);
setD(p, c, e); /* reform in b */
}
memmove(p + e, b + e, block_size - e); /* copy back */
e -= dir_end;
SET_TOTAL_FREE(p, e);
SET_MAX_FREE(p, e);
}
/** Btree needs to gain a new level to insert more items: so split root block
* and construct a new one.
*/
void
BrassTable::split_root(uint4 split_n)
{
LOGCALL_VOID(DB, "BrassTable::split_root", split_n);
/* gain a level */
++level;
/* check level overflow - this isn't something that should ever happen
* but deserves more than an Assert()... */
if (level == BTREE_CURSOR_LEVELS) {
throw Xapian::DatabaseCorruptError("Btree has grown impossibly large ("STRINGIZE(BTREE_CURSOR_LEVELS)" levels)");
}
byte * q = zeroed_new(block_size);
C[level].p = q;
C[level].c = DIR_START;
C[level].n = base.next_free_block();
C[level].rewrite = true;
SET_REVISION(q, latest_revision_number + 1);
SET_LEVEL(q, level);
SET_DIR_END(q, DIR_START);
compact(q); /* to reset TOTAL_FREE, MAX_FREE */
/* form a null key in b with a pointer to the old root */
byte b[10]; /* 7 is exact */
Item_wr item(b);
item.form_null_key(split_n);
add_item(item, level);
}
/** enter_key(j, prevkey, newkey) is called after a block split.
It enters in the block at level C[j] a separating key for the block
at level C[j - 1]. The key itself is newkey. prevkey is the
preceding key, and at level 1 newkey can be trimmed down to the
first point of difference to prevkey for entry in C[j].
This code looks longer than it really is. If j exceeds the number
of B-tree levels the root block has split and we have to construct
a new one, but this is a rare event.
The key is constructed in b, with block number C[j - 1].n as tag,
and this is added in with add_item. add_item may itself cause a
block split, with a further call to enter_key. Hence the recursion.
*/
void
BrassTable::enter_key(int j, Key prevkey, Key newkey)
{
LOGCALL_VOID(DB, "BrassTable::enter_key", j | Literal("prevkey") | Literal("newkey"));
Assert(writable);
Assert(prevkey < newkey);
AssertRel(j,>=,1);
uint4 blocknumber = C[j - 1].n;
// FIXME update to use Key
// Keys are truncated here: but don't truncate the count at the end away.
const int newkey_len = newkey.length();
AssertRel(newkey_len,>,0);
int i;
if (j == 1) {
// Truncate the key to the minimal key which differs from prevkey,
// the preceding key in the block.
i = 0;
const int min_len = min(newkey_len, prevkey.length());
while (i < min_len && prevkey[i] == newkey[i]) {
i++;
}
// Want one byte of difference.
if (i < newkey_len) i++;
} else {
/* Can't truncate between branch levels, since the separated keys
* are in at the leaf level, and truncating again will change the
* branch point.
*/
i = newkey_len;
}
byte b[UCHAR_MAX + 6];
Item_wr item(b);
Assert(i <= 256 - I2 - C2);
Assert(i <= (int)sizeof(b) - I2 - C2 - 4);
item.set_key_and_block(newkey, i, blocknumber);
// When j > 1 we can make the first key of block p null. This is probably
// worthwhile as it trades a small amount of CPU and RAM use for a small
// saving in disk use. Other redundant keys will still creep in though.
if (j > 1) {
byte * p = C[j - 1].p;
uint4 n = getint4(newkey.get_address(), newkey_len + K1 + C2);
int new_total_free = TOTAL_FREE(p) + newkey_len + C2;
// FIXME: incredibly icky going from key to item like this...
Item_wr(const_cast<byte*>(newkey.get_address()) - I2).form_null_key(n);
SET_TOTAL_FREE(p, new_total_free);
}
C[j].c = find_in_block(C[j].p, item.key(), false, 0) + D2;
C[j].rewrite = true; /* a subtle point: this *is* required. */
add_item(item, j);
}
/** mid_point(p) finds the directory entry in c that determines the
approximate mid point of the data in the block at p.
*/
int
BrassTable::mid_point(byte * p)
{
LOGCALL(DB, int, "BrassTable::mid_point", (void*)p);
int n = 0;
int dir_end = DIR_END(p);
int size = block_size - TOTAL_FREE(p) - dir_end;
for (int c = DIR_START; c < dir_end; c += D2) {
int l = Item(p, c).size();
n += 2 * l;
if (n >= size) {
if (l < n - size) RETURN(c);
RETURN(c + D2);
}
}
/* falling out of mid_point */
Assert(false);
RETURN(0); /* Stop compiler complaining about end of method. */
}
/** add_item_to_block(p, kt_, c) adds item kt_ to the block at p.
c is the offset in the directory that needs to be expanded to accommodate
the new entry for the item. We know before this is called that there is
enough contiguous room for the item in the block, so it's just a matter of
shuffling up any directory entries after where we're inserting and copying
in the item.
*/
void
BrassTable::add_item_to_block(byte * p, Item_wr kt_, int c)
{
LOGCALL_VOID(DB, "BrassTable::add_item_to_block", (void*)p | Literal("kt_") | c);
Assert(writable);
int dir_end = DIR_END(p);
int kt_len = kt_.size();
int needed = kt_len + D2;
int new_total = TOTAL_FREE(p) - needed;
int new_max = MAX_FREE(p) - needed;
Assert(new_total >= 0);
AssertRel(MAX_FREE(p),>=,needed);
Assert(dir_end >= c);
memmove(p + c + D2, p + c, dir_end - c);
dir_end += D2;
SET_DIR_END(p, dir_end);
int o = dir_end + new_max;
setD(p, c, o);
memmove(p + o, kt_.get_address(), kt_len);
SET_MAX_FREE(p, new_max);
SET_TOTAL_FREE(p, new_total);
}
/** BrassTable::add_item(kt_, j) adds item kt_ to the block at cursor level C[j].
*
* If there is not enough room the block splits and the item is then
* added to the appropriate half.
*/
void
BrassTable::add_item(Item_wr kt_, int j)
{
LOGCALL_VOID(DB, "BrassTable::add_item", Literal("kt_") | j);
Assert(writable);
byte * p = C[j].p;
int c = C[j].c;
uint4 n;
int needed = kt_.size() + D2;
if (TOTAL_FREE(p) < needed) {
int m;
// Prepare to split p. After splitting, the block is in two halves, the
// lower half is split_p, the upper half p again. add_to_upper_half
// becomes true when the item gets added to p, false when it gets added
// to split_p.
if (seq_count < 0) {
// If we're not in sequential mode, we split at the mid point
// of the node.
m = mid_point(p);
} else {
// During sequential addition, split at the insert point
m = c;
}
uint4 split_n = C[j].n;
C[j].n = base.next_free_block();
memcpy(split_p, p, block_size); // replicate the whole block in split_p
SET_DIR_END(split_p, m);
compact(split_p); /* to reset TOTAL_FREE, MAX_FREE */
{
int residue = DIR_END(p) - m;
int new_dir_end = DIR_START + residue;
memmove(p + DIR_START, p + m, residue);
SET_DIR_END(p, new_dir_end);
}
compact(p); /* to reset TOTAL_FREE, MAX_FREE */
bool add_to_upper_half;
if (seq_count < 0) {
add_to_upper_half = (c >= m);
} else {
// And add item to lower half if split_p has room, otherwise upper
// half
add_to_upper_half = (TOTAL_FREE(split_p) < needed);
}
if (add_to_upper_half) {
c -= (m - DIR_START);
Assert(seq_count < 0 || c <= DIR_START + D2);
Assert(c >= DIR_START);
Assert(c <= DIR_END(p));
add_item_to_block(p, kt_, c);
n = C[j].n;
} else {
Assert(c >= DIR_START);
Assert(c <= DIR_END(split_p));
add_item_to_block(split_p, kt_, c);
n = split_n;
}
write_block(split_n, split_p);
// Check if we're splitting the root block.
if (j == level) split_root(split_n);
/* Enter a separating key at level j + 1 between */
/* the last key of block split_p, and the first key of block p */
enter_key(j + 1,
Item(split_p, DIR_END(split_p) - D2).key(),
Item(p, DIR_START).key());
} else {
AssertRel(TOTAL_FREE(p),>=,needed);
if (MAX_FREE(p) < needed) {
compact(p);
AssertRel(MAX_FREE(p),>=,needed);
}
add_item_to_block(p, kt_, c);
n = C[j].n;
}
if (j == 0) {
changed_n = n;
changed_c = c;
}
}
/** BrassTable::delete_item(j, repeatedly) is (almost) the converse of add_item.
*
* If repeatedly is true, the process repeats at the next level when a
* block has been completely emptied, freeing the block and taking out
* the pointer to it. Emptied root blocks are also removed, which
* reduces the number of levels in the B-tree.
*/
void
BrassTable::delete_item(int j, bool repeatedly)
{
LOGCALL_VOID(DB, "BrassTable::delete_item", j | repeatedly);
Assert(writable);
byte * p = C[j].p;
int c = C[j].c;
int kt_len = Item(p, c).size(); /* size of the item to be deleted */
int dir_end = DIR_END(p) - D2; /* directory length will go down by 2 bytes */
memmove(p + c, p + c + D2, dir_end - c);
SET_DIR_END(p, dir_end);
SET_MAX_FREE(p, MAX_FREE(p) + D2);
SET_TOTAL_FREE(p, TOTAL_FREE(p) + kt_len + D2);
if (!repeatedly) return;
if (j < level) {
if (dir_end == DIR_START) {
base.free_block(C[j].n);
C[j].rewrite = false;
C[j].n = BLK_UNUSED;
C[j + 1].rewrite = true; /* *is* necessary */
delete_item(j + 1, true);
}
} else {
Assert(j == level);
while (dir_end == DIR_START + D2 && level > 0) {
/* single item in the root block, so lose a level */
uint4 new_root = Item(p, DIR_START).block_given_by();
delete [] p;
C[level].p = 0;
base.free_block(C[level].n);
C[level].rewrite = false;
C[level].n = BLK_UNUSED;
level--;
block_to_cursor(C, level, new_root);
p = C[level].p;
dir_end = DIR_END(p); /* prepare for the loop */
}
}
}
/* debugging aid:
static addcount = 0;
*/
/** add_kt(found) adds the item (key-tag pair) at B->kt into the
B-tree, using cursor C.
found == find() is handed over as a parameter from Btree::add.
Btree::alter() prepares for the alteration to the B-tree. Then
there are a number of cases to consider:
If an item with the same key is in the B-tree (found is true),
the new kt replaces it.
If then kt is smaller, or the same size as, the item it replaces,
kt is put in the same place as the item it replaces, and the
TOTAL_FREE measure is reduced.
If kt is larger than the item it replaces it is put in the
MAX_FREE space if there is room, and the directory entry and
space counts are adjusted accordingly.
- But if there is not room we do it the long way: the old item is
deleted with delete_item and kt is added in with add_item.
If the key of kt is not in the B-tree (found is false), the new
kt is added in with add_item.
*/
int
BrassTable::add_kt(bool found)
{
LOGCALL(DB, int, "BrassTable::add_kt", found);
Assert(writable);
int components = 0;
/*
{
printf("%d) %s ", addcount++, (found ? "replacing" : "adding"));
print_bytes(kt[I2] - K1 - C2, kt + I2 + K1); putchar('\n');
}
*/
alter();
if (found) { /* replacement */
seq_count = SEQ_START_POINT;
sequential = false;
byte * p = C[0].p;
int c = C[0].c;
Item item(p, c);
int kt_size = kt.size();
int needed = kt_size - item.size();
components = item.components_of();
if (needed <= 0) {
/* simple replacement */
memmove(const_cast<byte *>(item.get_address()),
kt.get_address(), kt_size);
SET_TOTAL_FREE(p, TOTAL_FREE(p) - needed);
} else {
/* new item into the block's freespace */
int new_max = MAX_FREE(p) - kt_size;
if (new_max >= 0) {
int o = DIR_END(p) + new_max;
memmove(p + o, kt.get_address(), kt_size);
setD(p, c, o);
SET_MAX_FREE(p, new_max);
SET_TOTAL_FREE(p, TOTAL_FREE(p) - needed);
} else {
/* do it the long way */
delete_item(0, false);
add_item(kt, 0);
}
}
} else {
/* addition */
if (changed_n == C[0].n && changed_c == C[0].c) {
if (seq_count < 0) seq_count++;
} else {
seq_count = SEQ_START_POINT;
sequential = false;
}
C[0].c += D2;
add_item(kt, 0);
}
RETURN(components);
}
/* delete_kt() corresponds to add_kt(found), but there are only
two cases: if the key is not found nothing is done, and if it is
found the corresponding item is deleted with delete_item.
*/
int
BrassTable::delete_kt()
{
LOGCALL(DB, int, "BrassTable::delete_kt", NO_ARGS);
Assert(writable);
bool found = find(C);
int components = 0;
seq_count = SEQ_START_POINT;
sequential = false;
/*
{
printf("%d) %s ", addcount++, (found ? "deleting " : "ignoring "));
print_bytes(B->kt[I2] - K1 - C2, B->kt + I2 + K1); putchar('\n');
}
*/
if (found) {
components = Item(C[0].p, C[0].c).components_of();
alter();
delete_item(0, true);
}
RETURN(components);
}
/* BrassTable::form_key(key) treats address kt as an item holder and fills in
the key part:
(I) K key c (C tag)
The bracketed parts are left blank. The key is filled in with key_len bytes and
K set accordingly. c is set to 1.
*/
void BrassTable::form_key(const string & key) const
{
LOGCALL_VOID(DB, "BrassTable::form_key", key);
kt.form_key(key);
}
/* BrassTable::add(key, tag) adds the key/tag item to the
B-tree, replacing any existing item with the same key.
For a long tag, we end up having to add m components, of the form
key 1 m tag1
key 2 m tag2
...
key m m tagm
and tag1+tag2+...+tagm are equal to tag. These in their turn may be replacing
n components of the form
key 1 n TAG1
key 2 n TAG2
...
key n n TAGn
and n may be greater than, equal to, or less than m. These cases are dealt
with in the code below. If m < n for example, we end up with a series of
deletions.
*/
void
BrassTable::add(const string &key, string tag, bool already_compressed)
{
LOGCALL_VOID(DB, "BrassTable::add", key | tag | already_compressed);
Assert(writable);
if (handle < 0) create_and_open(block_size);
form_key(key);
bool compressed = false;
if (already_compressed) {
compressed = true;
} else if (compress_strategy != DONT_COMPRESS && tag.size() > COMPRESS_MIN) {
CompileTimeAssert(DONT_COMPRESS != Z_DEFAULT_STRATEGY);
CompileTimeAssert(DONT_COMPRESS != Z_FILTERED);
CompileTimeAssert(DONT_COMPRESS != Z_HUFFMAN_ONLY);
#ifdef Z_RLE
CompileTimeAssert(DONT_COMPRESS != Z_RLE);
#endif
lazy_alloc_deflate_zstream();
deflate_zstream->next_in = (Bytef *)const_cast<char *>(tag.data());
deflate_zstream->avail_in = (uInt)tag.size();
// If compressed size is >= tag.size(), we don't want to compress.
unsigned long blk_len = tag.size() - 1;
unsigned char * blk = new unsigned char[blk_len];
deflate_zstream->next_out = blk;
deflate_zstream->avail_out = (uInt)blk_len;
int err = deflate(deflate_zstream, Z_FINISH);
if (err == Z_STREAM_END) {
// If deflate succeeded, then the output was at least one byte
// smaller than the input.
tag.assign(reinterpret_cast<const char *>(blk), deflate_zstream->total_out);
compressed = true;
} else {
// Deflate failed - presumably the data wasn't compressible.
}
delete [] blk;
}
// sort of matching kt.append_chunk(), but setting the chunk
const size_t cd = kt.key().length() + K1 + I2 + C2 + C2; // offset to the tag data
const size_t L = max_item_size - cd; // largest amount of tag data for any chunk
size_t first_L = L; // - amount for tag1
bool found = find(C);
if (!found) {
byte * p = C[0].p;
size_t n = TOTAL_FREE(p) % (max_item_size + D2);
if (n > D2 + cd) {
n -= (D2 + cd);
// if n >= last then fully filling this block won't produce
// an extra item, so we might as well do this even if
// full_compaction isn't active.
//
// In the full_compaction case, it turns out we shouldn't always
// try to fill every last byte. Doing so can actually increase the
// total space required (I believe this effect is due to longer
// dividing keys being required in the index blocks). Empirically,
// n >= key.size() + K appears a good criterion for K ~= 34. This
// seems to save about 0.2% in total database size over always
// splitting the tag. It'll also give be slightly faster retrieval
// as we can avoid reading an extra block occasionally.
size_t last = tag.length() % L;
if (n >= last || (full_compaction && n >= key.size() + 34))
first_L = n;
}
}
// a null tag must be added in of course
int m = tag.empty() ? 1 : (tag.length() - first_L + L - 1) / L + 1;
// there are m items to add
/* FIXME: sort out this error higher up and turn this into
* an assert.
*/
if (m >= BYTE_PAIR_RANGE)
throw Xapian::UnimplementedError("Can't handle insanely large tags");
int n = 0; // initialise to shut off warning
// - and there will be n to delete
int o = 0; // Offset into the tag
size_t residue = tag.length(); // Bytes of the tag remaining to add in
int replacement = false; // Has there been a replacement ?
int i;
kt.set_components_of(m);
for (i = 1; i <= m; i++) {
size_t l = (i == m ? residue : (i == 1 ? first_L : L));
Assert(cd + l <= block_size);
Assert(string::size_type(o + l) <= tag.length());
kt.set_tag(cd, tag.data() + o, l, compressed);
kt.set_component_of(i);
o += l;
residue -= l;
if (i > 1) found = find(C);
n = add_kt(found);
if (n > 0) replacement = true;
}
/* o == tag.length() here, and n may be zero */
for (i = m + 1; i <= n; i++) {
kt.set_component_of(i);
delete_kt();
}
if (!replacement) ++item_count;
Btree_modified = true;
if (cursor_created_since_last_modification) {
cursor_created_since_last_modification = false;
++cursor_version;
}
}
/* BrassTable::del(key) returns false if the key is not in the B-tree,
otherwise deletes it and returns true.
Again, this is parallel to BrassTable::add, but simpler in form.
*/
bool
BrassTable::del(const string &key)
{
LOGCALL(DB, bool, "BrassTable::del", key);
Assert(writable);
if (handle < 0) {
if (handle == -2) {
BrassTable::throw_database_closed();
}
RETURN(false);
}
// We can't delete a key which we is too long for us to store.
if (key.size() > BRASS_BTREE_MAX_KEY_LEN) RETURN(false);
if (key.empty()) RETURN(false);
form_key(key);
int n = delete_kt(); /* there are n items to delete */
if (n <= 0) RETURN(false);
for (int i = 2; i <= n; i++) {
kt.set_component_of(i);
delete_kt();
}
item_count--;
Btree_modified = true;
if (cursor_created_since_last_modification) {
cursor_created_since_last_modification = false;
++cursor_version;
}
RETURN(true);
}
bool
BrassTable::get_exact_entry(const string &key, string & tag) const
{
LOGCALL(DB, bool, "BrassTable::get_exact_entry", key | tag);
Assert(!key.empty());
if (handle < 0) {
if (handle == -2) {
BrassTable::throw_database_closed();
}
RETURN(false);
}
// An oversized key can't exist, so attempting to search for it should fail.
if (key.size() > BRASS_BTREE_MAX_KEY_LEN) RETURN(false);
form_key(key);
if (!find(C)) RETURN(false);
(void)read_tag(C, &tag, false);
RETURN(true);
}
bool
BrassTable::key_exists(const string &key) const
{
LOGCALL(DB, bool, "BrassTable::key_exists", key);
Assert(!key.empty());
// An oversized key can't exist, so attempting to search for it should fail.
if (key.size() > BRASS_BTREE_MAX_KEY_LEN) RETURN(false);
form_key(key);
RETURN(find(C));
}
bool
BrassTable::read_tag(Brass::Cursor * C_, string *tag, bool keep_compressed) const
{
LOGCALL(DB, bool, "BrassTable::read_tag", Literal("C_") | tag | keep_compressed);
Item item(C_[0].p, C_[0].c);
/* n components to join */
int n = item.components_of();
tag->resize(0);
// max_item_size also includes K1 + I2 + C2 + C2 bytes overhead and the key
// (which is at least 1 byte long).
if (n > 1) tag->reserve((max_item_size - (1 + K1 + I2 + C2 + C2)) * n);
item.append_chunk(tag);
bool compressed = item.get_compressed();
for (int i = 2; i <= n; i++) {
if (!next(C_, 0)) {
throw Xapian::DatabaseCorruptError("Unexpected end of table when reading continuation of tag");
}
(void)Item(C_[0].p, C_[0].c).append_chunk(tag);
}
// At this point the cursor is on the last item - calling next will move
// it to the next key (BrassCursor::get_tag() relies on this).
if (!compressed || keep_compressed) RETURN(compressed);
// FIXME: Perhaps we should we decompress each chunk as we read it so we
// don't need both the full compressed and uncompressed tags in memory
// at once.
string utag;
// May not be enough for a compressed tag, but it's a reasonable guess.
utag.reserve(tag->size() + tag->size() / 2);
Bytef buf[8192];
lazy_alloc_inflate_zstream();
inflate_zstream->next_in = (Bytef*)const_cast<char *>(tag->data());
inflate_zstream->avail_in = (uInt)tag->size();
int err = Z_OK;
while (err != Z_STREAM_END) {
inflate_zstream->next_out = buf;
inflate_zstream->avail_out = (uInt)sizeof(buf);
err = inflate(inflate_zstream, Z_SYNC_FLUSH);
if (err == Z_BUF_ERROR && inflate_zstream->avail_in == 0) {
LOGLINE(DB, "Z_BUF_ERROR - faking checksum of " << inflate_zstream->adler);
Bytef header2[4];
setint4(header2, 0, inflate_zstream->adler);
inflate_zstream->next_in = header2;
inflate_zstream->avail_in = 4;
err = inflate(inflate_zstream, Z_SYNC_FLUSH);
if (err == Z_STREAM_END) break;
}
if (err != Z_OK && err != Z_STREAM_END) {
if (err == Z_MEM_ERROR) throw std::bad_alloc();
string msg = "inflate failed";
if (inflate_zstream->msg) {
msg += " (";
msg += inflate_zstream->msg;
msg += ')';
}
throw Xapian::DatabaseError(msg);
}
utag.append(reinterpret_cast<const char *>(buf),
inflate_zstream->next_out - buf);
}
if (utag.size() != inflate_zstream->total_out) {
string msg = "compressed tag didn't expand to the expected size: ";
msg += str(utag.size());
msg += " != ";
// OpenBSD's zlib.h uses off_t instead of uLong for total_out.
msg += str((size_t)inflate_zstream->total_out);
throw Xapian::DatabaseCorruptError(msg);
}
swap(*tag, utag);
RETURN(false);
}
void
BrassTable::set_full_compaction(bool parity)
{
LOGCALL_VOID(DB, "BrassTable::set_full_compaction", parity);
Assert(writable);
if (parity) seq_count = 0;
full_compaction = parity;
}
BrassCursor * BrassTable::cursor_get() const {
LOGCALL(DB, BrassCursor *, "BrassTable::cursor_get", NO_ARGS);
if (handle < 0) {
if (handle == -2) {
BrassTable::throw_database_closed();
}
RETURN(NULL);
}
// FIXME Ick - casting away const is nasty
RETURN(new BrassCursor(const_cast<BrassTable *>(this)));
}
/************ B-tree opening and closing ************/
bool
BrassTable::basic_open(bool revision_supplied, brass_revision_number_t revision_)
{
LOGCALL(DB, bool, "BrassTable::basic_open", revision_supplied | revision_);
int ch = 'X'; /* will be 'A' or 'B' */
{
const size_t BTREE_BASES = 2;
string err_msg;
static const char basenames[BTREE_BASES] = { 'A', 'B' };
BrassTable_base bases[BTREE_BASES];
bool base_ok[BTREE_BASES];
both_bases = true;
bool valid_base = false;
{
for (size_t i = 0; i < BTREE_BASES; ++i) {
bool ok = bases[i].read(name, basenames[i], writable, err_msg);
base_ok[i] = ok;
if (ok) {
valid_base = true;
} else {
both_bases = false;
}
}
}
if (!valid_base) {
if (handle >= 0) {
::close(handle);
handle = -1;
}
string message = "Error opening table `";
message += name;
message += "':\n";
message += err_msg;
throw Xapian::DatabaseOpeningError(message);
}
if (revision_supplied) {
bool found_revision = false;
for (size_t i = 0; i < BTREE_BASES; ++i) {
if (base_ok[i] && bases[i].get_revision() == revision_) {
ch = basenames[i];
found_revision = true;
break;
}
}
if (!found_revision) {
/* Couldn't open the revision that was asked for.
* This shouldn't throw an exception, but should just return
* false to upper levels.
*/
RETURN(false);
}
} else {
brass_revision_number_t highest_revision = 0;
for (size_t i = 0; i < BTREE_BASES; ++i) {
if (base_ok[i] && bases[i].get_revision() >= highest_revision) {
ch = basenames[i];
highest_revision = bases[i].get_revision();
}
}
}
BrassTable_base *basep = 0;
BrassTable_base *other_base = 0;
for (size_t i = 0; i < BTREE_BASES; ++i) {
LOGLINE(DB, "Checking (ch == " << ch << ") against "
"basenames[" << i << "] == " << basenames[i]);
LOGLINE(DB, "bases[" << i << "].get_revision() == " <<
bases[i].get_revision());
LOGLINE(DB, "base_ok[" << i << "] == " << base_ok[i]);
if (ch == basenames[i]) {
basep = &bases[i];
// FIXME: assuming only two bases for other_base
size_t otherbase_num = 1-i;
if (base_ok[otherbase_num]) {
other_base = &bases[otherbase_num];
}
break;
}
}
Assert(basep);
/* basep now points to the most recent base block */
/* Avoid copying the bitmap etc. - swap contents with the base
* object in the vector, since it'll be destroyed anyway soon.
*/
base.swap(*basep);
revision_number = base.get_revision();
block_size = base.get_block_size();
root = base.get_root();
level = base.get_level();
//bit_map_size = basep->get_bit_map_size();
item_count = base.get_item_count();
faked_root_block = base.get_have_fakeroot();
sequential = base.get_sequential();
if (other_base != 0) {
latest_revision_number = other_base->get_revision();
if (revision_number > latest_revision_number)
latest_revision_number = revision_number;
} else {
latest_revision_number = revision_number;
}
}
/* kt holds constructed items as well as keys */
kt = Item_wr(zeroed_new(block_size));
set_max_item_size(BLOCK_CAPACITY);
base_letter = ch;
/* ready to open the main file */
RETURN(true);
}
void
BrassTable::read_root()
{
LOGCALL_VOID(DB, "BrassTable::read_root", NO_ARGS);
if (faked_root_block) {
/* root block for an unmodified database. */
byte * p = C[0].p;
Assert(p);
/* clear block - shouldn't be necessary, but is a bit nicer,
* and means that the same operations should always produce
* the same database. */
memset(p, 0, block_size);
int o = block_size - I2 - K1 - C2 - C2;
Item_wr(p + o).fake_root_item();
setD(p, DIR_START, o); // its directory entry
SET_DIR_END(p, DIR_START + D2);// the directory size
o -= (DIR_START + D2);
SET_MAX_FREE(p, o);
SET_TOTAL_FREE(p, o);
SET_LEVEL(p, 0);
if (!writable) {
/* reading - revision number doesn't matter as long as
* it's not greater than the current one. */
SET_REVISION(p, 0);
C[0].n = 0;
} else {
/* writing - */
SET_REVISION(p, latest_revision_number + 1);
C[0].n = base.next_free_block();
}
} else {
/* using a root block stored on disk */
block_to_cursor(C, level, root);
if (REVISION(C[level].p) > revision_number) set_overwritten();
/* although this is unlikely */
}
}
bool
BrassTable::do_open_to_write(bool revision_supplied,
brass_revision_number_t revision_,
bool create_db)
{
LOGCALL(DB, bool, "BrassTable::do_open_to_write", revision_supplied | revision_ | create_db);
if (handle == -2) {
BrassTable::throw_database_closed();
}
int flags = O_RDWR | O_BINARY;
if (create_db) flags |= O_CREAT | O_TRUNC;
handle = ::open((name + "DB").c_str(), flags, 0666);
if (handle < 0) {
// lazy doesn't make a lot of sense with create_db anyway, but ENOENT
// with O_CREAT means a parent directory doesn't exist.
if (lazy && !create_db && errno == ENOENT) {
revision_number = revision_;
RETURN(true);
}
string message(create_db ? "Couldn't create " : "Couldn't open ");
message += name;
message += "DB read/write: ";
message += strerror(errno);
throw Xapian::DatabaseOpeningError(message);
}
if (!basic_open(revision_supplied, revision_)) {
::close(handle);
handle = -1;
if (!revision_supplied) {
throw Xapian::DatabaseOpeningError("Failed to open for writing");
}
/* When the revision is supplied, it's not an exceptional
* case when open failed, so we just return false here.
*/
RETURN(false);
}
writable = true;
for (int j = 0; j <= level; j++) {
C[j].n = BLK_UNUSED;
C[j].p = new byte[block_size];
if (C[j].p == 0) {
throw std::bad_alloc();
}
}
split_p = new byte[block_size];
if (split_p == 0) {
throw std::bad_alloc();
}
read_root();
buffer = zeroed_new(block_size);
changed_n = 0;
changed_c = DIR_START;
seq_count = SEQ_START_POINT;
RETURN(true);
}
BrassTable::BrassTable(const char * tablename_, const string & path_,
bool readonly_, int compress_strategy_, bool lazy_)
: tablename(tablename_),
revision_number(0),
item_count(0),
block_size(0),
latest_revision_number(0),
both_bases(false),
base_letter('A'),
faked_root_block(true),
sequential(true),
handle(-1),
level(0),
root(0),
kt(0),
buffer(0),
base(),
name(path_),
seq_count(0),
changed_n(0),
changed_c(0),
max_item_size(0),
Btree_modified(false),
full_compaction(false),
writable(!readonly_),
cursor_created_since_last_modification(false),
cursor_version(0),
split_p(0),
compress_strategy(compress_strategy_),
deflate_zstream(NULL),
inflate_zstream(NULL),
lazy(lazy_)
{
LOGCALL_CTOR(DB, "BrassTable", tablename_ | path_ | readonly_ | compress_strategy_ | lazy_);
}
void
BrassTable::lazy_alloc_deflate_zstream() const {
if (usual(deflate_zstream)) {
if (usual(deflateReset(deflate_zstream) == Z_OK)) return;
// Try to recover by deleting the stream and starting from scratch.
delete deflate_zstream;
}
deflate_zstream = new z_stream;
deflate_zstream->zalloc = reinterpret_cast<alloc_func>(0);
deflate_zstream->zfree = reinterpret_cast<free_func>(0);
deflate_zstream->opaque = (voidpf)0;
// -15 means raw deflate with 32K LZ77 window (largest)
// memLevel 9 is the highest (8 is default)
int err;
err = deflateInit2(deflate_zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
-15, 9, compress_strategy);
if (rare(err != Z_OK)) {
if (err == Z_MEM_ERROR) {
delete deflate_zstream;
deflate_zstream = 0;
throw std::bad_alloc();
}
string msg = "deflateInit2 failed (";
if (deflate_zstream->msg) {
msg += deflate_zstream->msg;
} else {
msg += str(err);
}
msg += ')';
delete deflate_zstream;
deflate_zstream = 0;
throw Xapian::DatabaseError(msg);
}
}
void
BrassTable::lazy_alloc_inflate_zstream() const {
if (usual(inflate_zstream)) {
if (usual(inflateReset(inflate_zstream) == Z_OK)) return;
// Try to recover by deleting the stream and starting from scratch.
delete inflate_zstream;
}
inflate_zstream = new z_stream;
inflate_zstream->zalloc = reinterpret_cast<alloc_func>(0);
inflate_zstream->zfree = reinterpret_cast<free_func>(0);
inflate_zstream->next_in = Z_NULL;
inflate_zstream->avail_in = 0;
int err = inflateInit2(inflate_zstream, -15);
if (rare(err != Z_OK)) {
if (err == Z_MEM_ERROR) {
delete inflate_zstream;
inflate_zstream = 0;
throw std::bad_alloc();
}
string msg = "inflateInit2 failed (";
if (inflate_zstream->msg) {
msg += inflate_zstream->msg;
} else {
msg += str(err);
}
msg += ')';
delete inflate_zstream;
inflate_zstream = 0;
throw Xapian::DatabaseError(msg);
}
}
bool
BrassTable::exists() const {
LOGCALL(DB, bool, "BrassTable::exists", NO_ARGS);
return (file_exists(name + "DB") &&
(file_exists(name + "baseA") || file_exists(name + "baseB")));
}
void
BrassTable::erase()
{
LOGCALL_VOID(DB, "BrassTable::erase", NO_ARGS);
close();
(void)io_unlink(name + "baseA");
(void)io_unlink(name + "baseB");
(void)io_unlink(name + "DB");
}
void
BrassTable::set_block_size(unsigned int block_size_)
{
LOGCALL_VOID(DB, "BrassTable::set_block_size", block_size_);
// Block size must in the range 2048..BYTE_PAIR_RANGE, and a power of two.
if (block_size_ < 2048 || block_size_ > BYTE_PAIR_RANGE ||
(block_size_ & (block_size_ - 1)) != 0) {
block_size_ = BRASS_DEFAULT_BLOCK_SIZE;
}
block_size = block_size_;
}
void
BrassTable::create_and_open(unsigned int block_size_)
{
LOGCALL_VOID(DB, "BrassTable::create_and_open", block_size_);
if (handle == -2) {
BrassTable::throw_database_closed();
}
Assert(writable);
close();
set_block_size(block_size_);
// FIXME: it would be good to arrange that this works such that there's
// always a valid table in place if you run create_and_open() on an
// existing table.
/* write initial values to files */
/* create the base file */
BrassTable_base base_;
base_.set_revision(revision_number);
base_.set_block_size(block_size);
base_.set_have_fakeroot(true);
base_.set_sequential(true);
base_.write_to_file(name + "baseA", 'A', string(), -1, NULL);
/* remove the alternative base file, if any */
(void)io_unlink(name + "baseB");
// Any errors are thrown if revision_supplied is false.
(void)do_open_to_write(false, 0, true);
}
BrassTable::~BrassTable() {
LOGCALL_DTOR(DB, "BrassTable");
BrassTable::close();
if (deflate_zstream) {
// Errors which we care about have already been handled, so just ignore
// any which get returned here.
(void) deflateEnd(deflate_zstream);
delete deflate_zstream;
}
if (inflate_zstream) {
// Errors which we care about have already been handled, so just ignore
// any which get returned here.
(void) inflateEnd(inflate_zstream);
delete inflate_zstream;
}
}
void BrassTable::close(bool permanent) {
LOGCALL_VOID(DB, "BrassTable::close", NO_ARGS);
if (handle >= 0) {
// If an error occurs here, we just ignore it, since we're just
// trying to free everything.
(void)::close(handle);
handle = -1;
}
if (permanent) {
handle = -2;
// Don't delete the resources in the table, since they may
// still be used to look up cached content.
return;
}
for (int j = level; j >= 0; j--) {
delete [] C[j].p;
C[j].p = 0;
}
delete [] split_p;
split_p = 0;
delete [] kt.get_address();
kt = 0;
delete [] buffer;
buffer = 0;
}
void
BrassTable::flush_db()
{
LOGCALL_VOID(DB, "BrassTable::flush_db", NO_ARGS);
Assert(writable);
if (handle < 0) {
if (handle == -2) {
BrassTable::throw_database_closed();
}
return;
}
for (int j = level; j >= 0; j--) {
if (C[j].rewrite) {
write_block(C[j].n, C[j].p);
}
}
if (Btree_modified) {
faked_root_block = false;
}
}
void
BrassTable::commit(brass_revision_number_t revision, int changes_fd,
const string * changes_tail)
{
LOGCALL_VOID(DB, "BrassTable::commit", revision | changes_fd | changes_tail);
Assert(writable);
if (revision <= revision_number) {
throw Xapian::DatabaseError("New revision too low");
}
if (handle < 0) {
if (handle == -2) {
BrassTable::throw_database_closed();
}
latest_revision_number = revision_number = revision;
return;
}
try {
if (faked_root_block) {
/* We will use a dummy bitmap. */
base.clear_bit_map();
}
base.set_revision(revision);
base.set_root(C[level].n);
base.set_level(level);
base.set_item_count(item_count);
base.set_have_fakeroot(faked_root_block);
base.set_sequential(sequential);
base_letter = other_base_letter();
both_bases = true;
latest_revision_number = revision_number = revision;
root = C[level].n;
Btree_modified = false;
for (int i = 0; i < BTREE_CURSOR_LEVELS; ++i) {
C[i].n = BLK_UNUSED;
C[i].c = -1;
C[i].rewrite = false;
}
// Save to "<table>.tmp" and then rename to "<table>.base<letter>" so
// that a reader can't try to read a partially written base file.
string tmp = name;
tmp += "tmp";
string basefile = name;
basefile += "base";
basefile += char(base_letter);
base.write_to_file(tmp, base_letter, tablename, changes_fd, changes_tail);
// Do this as late as possible to allow maximum time for writes to
// happen, and so the calls to io_sync() are adjacent which may be
// more efficient, at least with some Linux kernel versions.
if (!io_sync(handle)) {
(void)::close(handle);
handle = -1;
(void)unlink(tmp);
throw Xapian::DatabaseError("Can't commit new revision - failed to flush DB to disk");
}
#if defined __WIN32__
if (msvc_posix_rename(tmp.c_str(), basefile.c_str()) < 0)
#else
if (rename(tmp.c_str(), basefile.c_str()) < 0)
#endif
{
// With NFS, rename() failing may just mean that the server crashed
// after successfully renaming, but before reporting this, and then
// the retried operation fails. So we need to check if the source
// file still exists, which we do by calling unlink(), since we want
// to remove the temporary file anyway.
int saved_errno = errno;
if (unlink(tmp) == 0 || errno != ENOENT) {
string msg("Couldn't update base file ");
msg += basefile;
msg += ": ";
msg += strerror(saved_errno);
throw Xapian::DatabaseError(msg);
}
}
base.commit();
read_root();
changed_n = 0;
changed_c = DIR_START;
seq_count = SEQ_START_POINT;
} catch (...) {
BrassTable::close();
throw;
}
}
void
BrassTable::write_changed_blocks(int changes_fd)
{
LOGCALL_VOID(DB, "BrassTable::write_changed_blocks", changes_fd);
Assert(changes_fd >= 0);
if (handle < 0) return;
if (faked_root_block) return;
string buf;
pack_uint(buf, 2u); // Indicate the item is a list of blocks
pack_string(buf, tablename);
pack_uint(buf, block_size);
io_write(changes_fd, buf.data(), buf.size());
// Compare the old and new bitmaps to find blocks which have changed, and
// write them to the file descriptor.
uint4 n = 0;
byte * p = new byte[block_size];
try {
base.calculate_last_block();
while (base.find_changed_block(&n)) {
buf.resize(0);
pack_uint(buf, n + 1);
io_write(changes_fd, buf.data(), buf.size());
// Read block n.
read_block(n, p);
// Write block n to the file.
io_write(changes_fd, reinterpret_cast<const char *>(p), block_size);
++n;
}
delete[] p;
p = 0;
} catch (...) {
delete[] p;
throw;
}
buf.resize(0);
pack_uint(buf, 0u);
io_write(changes_fd, buf.data(), buf.size());
}
void
BrassTable::cancel()
{
LOGCALL_VOID(DB, "BrassTable::cancel", NO_ARGS);
Assert(writable);
if (handle < 0) {
if (handle == -2) {
BrassTable::throw_database_closed();
}
latest_revision_number = revision_number; // FIXME: we can end up reusing a revision if we opened a btree at an older revision, start to modify it, then cancel...
return;
}
// This causes problems: if (!Btree_modified) return;
string err_msg;
if (!base.read(name, base_letter, writable, err_msg)) {
throw Xapian::DatabaseCorruptError(string("Couldn't reread base ") + base_letter);
}
revision_number = base.get_revision();
block_size = base.get_block_size();
root = base.get_root();
level = base.get_level();
//bit_map_size = basep->get_bit_map_size();
item_count = base.get_item_count();
faked_root_block = base.get_have_fakeroot();
sequential = base.get_sequential();
latest_revision_number = revision_number; // FIXME: we can end up reusing a revision if we opened a btree at an older revision, start to modify it, then cancel...
Btree_modified = false;
for (int j = 0; j <= level; j++) {
C[j].n = BLK_UNUSED;
C[j].rewrite = false;
}
read_root();
changed_n = 0;
changed_c = DIR_START;
seq_count = SEQ_START_POINT;
}
/************ B-tree reading ************/
bool
BrassTable::do_open_to_read(bool revision_supplied, brass_revision_number_t revision_)
{
LOGCALL(DB, bool, "BrassTable::do_open_to_read", revision_supplied | revision_);
if (handle == -2) {
BrassTable::throw_database_closed();
}
handle = ::open((name + "DB").c_str(), O_RDONLY | O_BINARY);
if (handle < 0) {
if (lazy) {
// This table is optional when reading!
revision_number = revision_;
RETURN(true);
}
string message("Couldn't open ");
message += name;
message += "DB to read: ";
message += strerror(errno);
throw Xapian::DatabaseOpeningError(message);
}
if (!basic_open(revision_supplied, revision_)) {
::close(handle);
handle = -1;
if (revision_supplied) {
// The requested revision was not available.
// This could be because the database was modified underneath us, or
// because a base file is missing. Return false, and work out what
// the problem was at a higher level.
RETURN(false);
}
throw Xapian::DatabaseOpeningError("Failed to open table for reading");
}
for (int j = 0; j <= level; j++) {
C[j].n = BLK_UNUSED;
C[j].p = new byte[block_size];
if (C[j].p == 0) {
throw std::bad_alloc();
}
}
read_root();
RETURN(true);
}
void
BrassTable::open()
{
LOGCALL_VOID(DB, "BrassTable::open", NO_ARGS);
LOGLINE(DB, "opening at path " << name);
close();
if (!writable) {
// Any errors are thrown if revision_supplied is false
(void)do_open_to_read(false, 0);
return;
}
// Any errors are thrown if revision_supplied is false.
(void)do_open_to_write(false, 0);
}
bool
BrassTable::open(brass_revision_number_t revision)
{
LOGCALL(DB, bool, "BrassTable::open", revision);
LOGLINE(DB, "opening for particular revision at path " << name);
close();
if (!writable) {
if (do_open_to_read(true, revision)) {
AssertEq(revision_number, revision);
RETURN(true);
} else {
close();
RETURN(false);
}
}
if (!do_open_to_write(true, revision)) {
// Can't open at the requested revision.
close();
RETURN(false);
}
AssertEq(revision_number, revision);
RETURN(true);
}
bool
BrassTable::prev_for_sequential(Brass::Cursor * C_, int /*dummy*/) const
{
LOGCALL(DB, bool, "BrassTable::prev_for_sequential", Literal("C_") | Literal("/*dummy*/"));
int c = C_[0].c;
if (c == DIR_START) {
byte * p = C_[0].p;
Assert(p);
uint4 n = C_[0].n;
while (true) {
if (n == 0) RETURN(false);
n--;
if (writable) {
if (n == C[0].n) {
// Block is a leaf block in the built-in cursor
// (potentially in modified form).
memcpy(p, C[0].p, block_size);
} else {
// Blocks in the built-in cursor may not have been written
// to disk yet, so we have to check that the block number
// isn't in the built-in cursor or we'll read an
// uninitialised block (for which GET_LEVEL(p) will
// probably return 0).
int j;
for (j = 1; j <= level; ++j) {
if (n == C[j].n) break;
}
if (j <= level) continue;
// Block isn't in the built-in cursor, so the form on disk
// is valid, so read it to check if it's the next level 0
// block.
read_block(n, p);
}
} else {
read_block(n, p);
}
if (writable) AssertEq(revision_number, latest_revision_number);
if (REVISION(p) > revision_number + writable) {
set_overwritten();
RETURN(false);
}
if (GET_LEVEL(p) == 0) break;
}
c = DIR_END(p);
C_[0].n = n;
}
c -= D2;
C_[0].c = c;
RETURN(true);
}
bool
BrassTable::next_for_sequential(Brass::Cursor * C_, int /*dummy*/) const
{
LOGCALL(DB, bool, "BrassTable::next_for_sequential", Literal("C_") | Literal("/*dummy*/"));
byte * p = C_[0].p;
Assert(p);
int c = C_[0].c;
c += D2;
Assert((unsigned)c < block_size);
if (c == DIR_END(p)) {
uint4 n = C_[0].n;
while (true) {
n++;
if (n > base.get_last_block()) RETURN(false);
if (writable) {
if (n == C[0].n) {
// Block is a leaf block in the built-in cursor
// (potentially in modified form).
memcpy(p, C[0].p, block_size);
} else {
// Blocks in the built-in cursor may not have been written
// to disk yet, so we have to check that the block number
// isn't in the built-in cursor or we'll read an
// uninitialised block (for which GET_LEVEL(p) will
// probably return 0).
int j;
for (j = 1; j <= level; ++j) {
if (n == C[j].n) break;
}
if (j <= level) continue;
// Block isn't in the built-in cursor, so the form on disk
// is valid, so read it to check if it's the next level 0
// block.
read_block(n, p);
}
} else {
read_block(n, p);
}
if (writable) AssertEq(revision_number, latest_revision_number);
if (REVISION(p) > revision_number + writable) {
set_overwritten();
RETURN(false);
}
if (GET_LEVEL(p) == 0) break;
}
c = DIR_START;
C_[0].n = n;
}
C_[0].c = c;
RETURN(true);
}
bool
BrassTable::prev_default(Brass::Cursor * C_, int j) const
{
LOGCALL(DB, bool, "BrassTable::prev_default", Literal("C_") | j);
byte * p = C_[j].p;
int c = C_[j].c;
Assert(c >= DIR_START);
Assert((unsigned)c < block_size);
Assert(c <= DIR_END(p));
if (c == DIR_START) {
if (j == level) RETURN(false);
if (!prev_default(C_, j + 1)) RETURN(false);
c = DIR_END(p);
}
c -= D2;
C_[j].c = c;
if (j > 0) {
block_to_cursor(C_, j - 1, Item(p, c).block_given_by());
}
RETURN(true);
}
bool
BrassTable::next_default(Brass::Cursor * C_, int j) const
{
LOGCALL(DB, bool, "BrassTable::next_default", Literal("C_") | j);
byte * p = C_[j].p;
int c = C_[j].c;
Assert(c >= DIR_START);
c += D2;
Assert((unsigned)c < block_size);
// Sometimes c can be DIR_END(p) + 2 here it appears...
if (c >= DIR_END(p)) {
if (j == level) RETURN(false);
if (!next_default(C_, j + 1)) RETURN(false);
c = DIR_START;
}
C_[j].c = c;
if (j > 0) {
block_to_cursor(C_, j - 1, Item(p, c).block_given_by());
#ifdef BTREE_DEBUG_FULL
printf("Block in BrassTable:next_default");
report_block_full(j - 1, C_[j - 1].n, C_[j - 1].p);
#endif /* BTREE_DEBUG_FULL */
}
RETURN(true);
}
void
BrassTable::throw_database_closed()
{
throw Xapian::DatabaseError("Database has been closed");
}
/** Compares this key with key2.
The result is true if this key precedes key2. The comparison is for byte
sequence collating order, taking lengths into account. So if the keys are
made up of lower case ASCII letters we get alphabetical ordering.
Now remember that items are added into the B-tree in fastest time
when they are preordered by their keys. This is therefore the piece
of code that needs to be followed to arrange for the preordering.
This is complicated by the fact that keys have two parts - a value
and then a count. We first compare the values, and only if they
are equal do we compare the counts.
*/
bool Key::operator<(Key key2) const
{
LOGCALL(DB, bool, "Key::operator<", static_cast<const void*>(key2.p));
int key1_len = length();
int key2_len = key2.length();
if (key1_len == key2_len) {
// The keys are the same length, so we can compare the counts
// in the same operation since they're stored as 2 byte
// bigendian numbers.
RETURN(memcmp(p + K1, key2.p + K1, key1_len + C2) < 0);
}
int k_smaller = (key2_len < key1_len ? key2_len : key1_len);
// Compare the common part of the keys
int diff = memcmp(p + K1, key2.p + K1, k_smaller);
if (diff != 0) RETURN(diff < 0);
// We dealt with the "same length" case above so we never need to check
// the count here.
RETURN(key1_len < key2_len);
}
bool Key::operator==(Key key2) const
{
LOGCALL(DB, bool, "Key::operator==", static_cast<const void*>(key2.p));
int key1_len = length();
if (key1_len != key2.length()) RETURN(false);
// The keys are the same length, so we can compare the counts
// in the same operation since they're stored as 2 byte
// bigendian numbers.
RETURN(memcmp(p + K1, key2.p + K1, key1_len + C2) == 0);
}
| iveteran/xapian-scws | xapian-core_scws-1.2.18/backends/brass/brass_table.cc | C++ | bsd-2-clause | 65,871 |
<?php
declare(strict_types=1);
namespace Mwop\Art\Storage;
use Aws\S3\S3Client;
use League\Flysystem\AwsS3V3\AwsS3V3Adapter;
use League\Flysystem\AwsS3V3\PortableVisibilityConverter;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemOperator;
use League\Flysystem\Visibility;
use Psr\Container\ContainerInterface;
class ImagesFilesystemFactory
{
public function __invoke(ContainerInterface $container): FilesystemOperator
{
$folder = $container->get('config-art')['storage']['folder'] ?? '';
return new Filesystem(
new AwsS3V3Adapter(
$container->get(S3Client::class),
$container->get('config-file-storage')['bucket'] ?? '',
$folder . '/',
new PortableVisibilityConverter(
Visibility::PRIVATE
),
)
);
}
}
| weierophinney/mwop.net | src/Art/Storage/ImagesFilesystemFactory.php | PHP | bsd-2-clause | 883 |
/*
* Copyright (c) 2019, Adam <Adam@sigterm.info>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.cooking;
import com.google.inject.Guice;
import com.google.inject.testing.fieldbinder.Bind;
import com.google.inject.testing.fieldbinder.BoundFieldModule;
import javax.inject.Inject;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.GraphicID;
import net.runelite.api.Player;
import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GraphicChanged;
import net.runelite.client.game.ItemManager;
import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.ui.overlay.infobox.InfoBoxManager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.ArgumentMatchers.any;
import org.mockito.Mock;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class CookingPluginTest
{
private static final String[] COOKING_MESSAGES = {
"You successfully cook a shark.",
"You successfully cook an anglerfish.",
"You manage to cook a tuna.",
"You cook the karambwan. It looks delicious.",
"You roast a lobster.",
"You cook a bass.",
"You successfully bake a tasty garden pie.",
"You dry a piece of meat and extract the sinew."
};
private static final String incenseBurnerMessage = "You burn some marrentill in the incense burner.";
@Inject
CookingPlugin cookingPlugin;
@Mock
@Bind
Client client;
@Mock
@Bind
InfoBoxManager infoBoxManager;
@Mock
@Bind
ItemManager itemManager;
@Mock
@Bind
CookingConfig config;
@Mock
@Bind
CookingOverlay cookingOverlay;
@Mock
@Bind
OverlayManager overlayManager;
@Before
public void before()
{
Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this);
}
@Test
public void testOnChatMessage()
{
for (String message : COOKING_MESSAGES)
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", message, "", 0);
cookingPlugin.onChatMessage(chatMessage);
}
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", incenseBurnerMessage, "", 0);
cookingPlugin.onChatMessage(chatMessage);
CookingSession cookingSession = cookingPlugin.getSession();
assertNotNull(cookingSession);
assertEquals(COOKING_MESSAGES.length, cookingSession.getCookAmount());
assertEquals(0, cookingSession.getBurnAmount());
}
@Test
public void testOnGraphicChanged()
{
Player player = mock(Player.class);
when(player.getGraphic()).thenReturn(GraphicID.WINE_MAKE);
when(config.fermentTimer()).thenReturn(true);
when(client.getLocalPlayer()).thenReturn(player);
GraphicChanged graphicChanged = new GraphicChanged();
graphicChanged.setActor(player);
cookingPlugin.onGraphicChanged(graphicChanged);
verify(infoBoxManager).addInfoBox(any(FermentTimer.class));
}
} | runelite/runelite | runelite-client/src/test/java/net/runelite/client/plugins/cooking/CookingPluginTest.java | Java | bsd-2-clause | 4,401 |
/*
* RPLIDAR SDK
*
* Copyright (c) 2009 - 2014 RoboPeak Team
* http://www.robopeak.com
* Copyright (c) 2014 - 2018 Shanghai Slamtec Co., Ltd.
* http://www.slamtec.com
*
*/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "sdkcommon.h"
#include <mmsystem.h>
#pragma comment(lib, "Winmm.lib")
namespace rp{ namespace arch{
static LARGE_INTEGER _current_freq;
void HPtimer_reset()
{
BOOL ans=QueryPerformanceFrequency(&_current_freq);
_current_freq.QuadPart/=1000;
}
_u32 getHDTimer()
{
LARGE_INTEGER current;
QueryPerformanceCounter(¤t);
return (_u32)(current.QuadPart/_current_freq.QuadPart);
}
BEGIN_STATIC_CODE(timer_cailb)
{
HPtimer_reset();
}END_STATIC_CODE(timer_cailb)
}}
| robopeak/rplidar_ros | sdk/src/arch/win32/timer.cpp | C++ | bsd-2-clause | 2,003 |
// Copyright (c) 2012, Joshua Burke
// All rights reserved.
//
// See LICENSE for more information.
namespace Frost.Painting
{
public enum LineStyle
{
Solid,
Dash,
Dot
}
public enum LineJoin
{
Round,
Bevel,
Miter
}
public enum LineCap
{
Butt,
Round,
Square
}
public enum Repetition
{
Repeat,
Horizontal,
Vertical,
Clamp
}
} | fealty/Frost | Frost/Painting/Enumerations.cs | C# | bsd-2-clause | 371 |
/*
* Copyright (c) 2015-2019, Statens vegvesen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.vegvesen.nvdbapi.client.clients;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.google.gson.JsonObject;
import no.vegvesen.nvdbapi.client.gson.RouteParser;
import no.vegvesen.nvdbapi.client.model.Coordinates;
import no.vegvesen.nvdbapi.client.model.Geometry;
import no.vegvesen.nvdbapi.client.model.Projection;
import no.vegvesen.nvdbapi.client.model.roadnet.TypeOfRoad;
import no.vegvesen.nvdbapi.client.model.roadnet.route.RouteOnRoadNet;
public class RoadNetRouteClient extends AbstractJerseyClient {
static class RouteRequestField {
static final String START = "start";
static final String END = "slutt";
static final String GEOMETRY = "geometri";
static final String SRID = "srid";
static final String BRIEF_RESPONSE = "kortform";
static final String CONNECTION_LINKS = "konnekteringslenker";
static final String DETAILED_LINKS = "detaljerte_lenker";
static final String DISTANCE = "maks_avstand";
static final String ENVELOPE = "omkrets";
static final String ROAD_SYS_REFS = "vegsystemreferanse";
static final String TYPE_OF_ROAD = "typeveg";
static final String ROAD_USER_GROUP = "trafikantgruppe";
static final String KEEP_ROAD_USER_GROUP = "behold_trafikantgruppe";
static final String POINT_IN_TIME = "tidspunkt";
static final String START_POINT_IN_TIME = "tidspunkt_start";
static final String END_POINT_IN_TIME = "tidspunkt_slutt";
}
RoadNetRouteClient(String baseUrl, Client client, Consumer<AbstractJerseyClient> onClose) {
super(baseUrl, client, onClose);
}
public RouteOnRoadNet getRouteOnRoadnet(RoadNetRouteRequest request) {
WebTarget target = getWebTarget(request);
JsonObject result = JerseyHelper.execute(target).getAsJsonObject();
if (request.isBriefResponse()) {
return RouteParser.parseBrief(result);
} else {
return RouteParser.parseDetailed(result);
}
}
public RouteOnRoadNet postRouteOnRoadnet(RoadNetRouteRequest request) {
WebTarget target = getWebTarget();
Entity<Map<String, String>> entity = Entity.entity(getJsonObject(request), MediaType.APPLICATION_JSON);
JsonObject result = JerseyHelper.execute(target, entity).getAsJsonObject();
if (request.isBriefResponse()) {
return RouteParser.parseBrief(result);
} else {
return RouteParser.parseDetailed(result);
}
}
private Map<String, String> getJsonObject(RoadNetRouteRequest request) {
Map<String, String> jsonMap = new HashMap<>();
if (request.getStartReflinkPosition() != null) jsonMap.put(RouteRequestField.START, String.valueOf(request.getStartReflinkPosition()));
if (request.getEndReflinkPosition() != null) jsonMap.put(RouteRequestField.END, String.valueOf(request.getEndReflinkPosition()));
if (request.getGeometry() != null) jsonMap.put(RouteRequestField.GEOMETRY, request.getGeometry());
jsonMap.put(RouteRequestField.DISTANCE, String.valueOf(request.getDistance()));
jsonMap.put(RouteRequestField.ENVELOPE, String.valueOf(request.getEnvelope()));
jsonMap.put(RouteRequestField.BRIEF_RESPONSE, String.valueOf(request.isBriefResponse()));
jsonMap.put(RouteRequestField.CONNECTION_LINKS, String.valueOf(request.isConnectionLinks()));
jsonMap.put(RouteRequestField.DETAILED_LINKS, String.valueOf(request.isDetailedLinks()));
jsonMap.put(RouteRequestField.KEEP_ROAD_USER_GROUP, String.valueOf(request.isKeepRoadUserGroup()));
request.getRoadRefFilter().ifPresent(s -> jsonMap.put(RouteRequestField.ROAD_SYS_REFS, s));
request.getRoadUserGroup().ifPresent(userGroup -> jsonMap.put(RouteRequestField.ROAD_USER_GROUP, userGroup.getTextValue()));
if (!request.getTypeOfRoad().isEmpty()) jsonMap.put(RouteRequestField.TYPE_OF_ROAD, request.getTypeOfRoad().stream().map(TypeOfRoad::getTypeOfRoadSosi).collect(Collectors.joining(",")));
request.getPointInTime().ifPresent(pit -> jsonMap.put(RouteRequestField.POINT_IN_TIME, pit.toString()));
request.getStartPointInTime().ifPresent(pit -> jsonMap.put(RouteRequestField.START_POINT_IN_TIME, pit.toString()));
request.getEndPointInTime().ifPresent(pit -> jsonMap.put(RouteRequestField.END_POINT_IN_TIME, pit.toString()));
return jsonMap;
}
private WebTarget getWebTarget() {
return getClient().target(endpoint());
}
private WebTarget getWebTarget(RoadNetRouteRequest request) {
Objects.requireNonNull(request, "Missing page info argument.");
UriBuilder path = endpoint();
request.getPointInTime().ifPresent(v -> path.queryParam(RouteRequestField.POINT_IN_TIME, v.toString()));
request.getStartPointInTime().ifPresent(v -> path.queryParam(RouteRequestField.START_POINT_IN_TIME, v.toString()));
request.getEndPointInTime().ifPresent(v -> path.queryParam(RouteRequestField.END_POINT_IN_TIME, v.toString()));
path.queryParam(RouteRequestField.BRIEF_RESPONSE, request.isBriefResponse());
path.queryParam(RouteRequestField.CONNECTION_LINKS, request.isConnectionLinks());
path.queryParam(RouteRequestField.DETAILED_LINKS, request.isDetailedLinks());
request.getRoadRefFilter().ifPresent(v -> path.queryParam(RouteRequestField.ROAD_SYS_REFS, v));
request.getRoadUserGroup().ifPresent(v -> path.queryParam(RouteRequestField.ROAD_USER_GROUP, v.getTextValue()));
path.queryParam(RouteRequestField.KEEP_ROAD_USER_GROUP, request.isKeepRoadUserGroup());
if (!request.getTypeOfRoad().isEmpty()) path.queryParam(RouteRequestField.TYPE_OF_ROAD, request.getTypeOfRoad()
.stream()
.map(TypeOfRoad::getTypeOfRoadSosi)
.collect(Collectors.joining(",")));
if (request.usesGeometry()) {
path.queryParam(RouteRequestField.GEOMETRY, request.getGeometry());
path.queryParam(RouteRequestField.DISTANCE, request.getDistance());
if (request.getProjection() != Projection.UTM33) {
path.queryParam(RouteRequestField.SRID, request.getProjection().getSrid());
}
} else if(request.usesReflinkPosition()) {
path.queryParam(RouteRequestField.START, request.getStartReflinkPosition());
path.queryParam(RouteRequestField.END, request.getEndReflinkPosition());
} else {
Coordinates startCoordinates = request.getStartCoordinates();
path.queryParam(RouteRequestField.START, startCoordinates);
path.queryParam(RouteRequestField.END, request.getEndCoordinates());
path.queryParam(RouteRequestField.DISTANCE, request.getDistance());
path.queryParam(RouteRequestField.ENVELOPE, request.getEnvelope());
if(startCoordinates.getProjection() != Projection.UTM33) {
path.queryParam(RouteRequestField.SRID, startCoordinates.getProjection().getSrid());
}
}
return getClient().target(path);
}
private UriBuilder endpoint() {
return start().path("beta/vegnett/rute");
}
}
| nvdb-vegdata/nvdb-api-client | src/main/java/no/vegvesen/nvdbapi/client/clients/RoadNetRouteClient.java | Java | bsd-2-clause | 8,901 |
package httap
import (
"github.com/stretchr/testify/assert"
"testing"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
)
type requestInfo struct {
*http.Request
consumedBody []byte
}
func TestNewWiretapOptions(t *testing.T) {
tap := NewWiretap(Options{})
assert.NotNil(t, tap)
assert.Equal(t, tap.BufSize, int32(65535))
assert.Equal(t, tap.Timeout, time.Second/100)
assert.NotNil(t, tap.Log)
}
func TestPcapVersion(t *testing.T) {
assert.Contains(t, PcapVersion(), "libpcap version")
}
func TestStartWiretap(t *testing.T) {
orig, copy := performHttpWiretap(Options{}, nil)
assert.Equal(t, copy.URL.String(), orig.URL.String())
assert.Equal(t, copy.Header, orig.Header)
assert.Equal(t, copy.Host, orig.Host)
}
func TestStartWiretapMultipliesRequest(t *testing.T) {
orig, copies := performMultipliedHttpWiretap(Options{Multiply: 2.0}, nil)
assert.Equal(t, copies[0].URL.String(), orig.URL.String())
assert.Equal(t, copies[0].Header, orig.Header)
assert.Equal(t, copies[0].Host, orig.Host)
assert.Equal(t, copies[1].URL.String(), orig.URL.String())
assert.Equal(t, copies[1].Header, orig.Header)
assert.Equal(t, copies[1].Host, orig.Host)
}
func TestStartWiretapReplacesHost(t *testing.T) {
orig, copy := performHttpWiretap(Options{Headers: []string{"Host: example.com"}}, nil)
assert.Equal(t, copy.URL.String(), orig.URL.String())
assert.Equal(t, copy.Header, orig.Header)
assert.Equal(t, copy.Host, "example.com")
}
func TestStartWiretapForwardsBody(t *testing.T) {
orig, copy := performHttpWiretap(Options{}, func(host string) {
http.Post(host, "text/plain", strings.NewReader("FOO BAR BAZ"))
})
assert.Equal(t, copy.URL.String(), orig.URL.String())
assert.Equal(t, copy.Header, orig.Header)
assert.Equal(t, string(copy.consumedBody), "FOO BAR BAZ")
}
/* Note: HTTP client does not support 100 continue/delayed body submission yet. */
func TestStartWiretapForwardsBodyAfterHttpContinue(t *testing.T) {
orig, copy := performHttpWiretap(Options{}, func(host string) {
client := &http.Client{}
req, _ := http.NewRequest("POST", host, strings.NewReader("FOO BAR BAZ"))
req.Header.Set("Expect", "100-continue")
client.Do(req)
})
assert.Equal(t, copy.URL.String(), orig.URL.String())
assert.Equal(t, copy.Header, orig.Header)
assert.Equal(t, string(copy.consumedBody), "FOO BAR BAZ")
}
func TestStartWiretapFiltersHttpVerb(t *testing.T) {
orig, copy := performHttpWiretap(Options{Methods: []string{"GET"}}, func(host string) {
http.Post(host, "text/plain", strings.NewReader(""))
http.Get(host)
})
assert.Equal(t, copy.URL.String(), orig.URL.String())
assert.Equal(t, copy.Host, orig.Host)
assert.Equal(t, copy.Method, "GET")
}
func createHttpChannel(n int) (string, chan requestInfo) {
channel := make(chan requestInfo)
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
panic(err)
}
i := 0
handler := func(writer http.ResponseWriter, req *http.Request) {
body, _ := ioutil.ReadAll(req.Body)
channel <- requestInfo{req, body}
i++
if i == n {
defer listener.Close()
}
}
go http.Serve(listener, http.HandlerFunc(handler))
return listener.Addr().String(), channel
}
func performMultipliedHttpWiretap(opts Options, callback func(string)) (requestInfo, []requestInfo) {
n := int(opts.Multiply)
if n == 0 {
n = 1
}
if callback == nil {
callback = func(host string) {
http.Get(host)
}
}
tstHost, tstReqs := createHttpChannel(n)
prdHost, prdReqs := createHttpChannel(1)
opts.Sources = []string{prdHost}
opts.Destinations = []string{tstHost}
wiretap := NewWiretap(opts)
wiretap.RepeatDelay = 0
go wiretap.Start()
/* Sleep to allow wiretap to start up before issuing request. */
time.Sleep(50 * time.Millisecond)
go callback("http://" + prdHost)
orig := <-prdReqs
copy := make([]requestInfo, n)
for i := 0; i < n; i++ {
copy[i] = <-tstReqs
}
return orig, copy
}
func performHttpWiretap(opts Options, callback func(string)) (requestInfo, requestInfo) {
orig, copy := performMultipliedHttpWiretap(opts, callback)
return orig, copy[0]
}
| rolftimmermans/httap | lib/wiretap_test.go | GO | bsd-2-clause | 4,082 |
/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
*/
#ifndef __SOT_EXCEPTION_FACTORY_H
#define __SOT_EXCEPTION_FACTORY_H
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#include "sot/core/api.hh"
#include <sot/core/exception-abstract.hh>
/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */
namespace dynamicgraph {
namespace sot {
/* \class ExceptionFactory
*/
class SOT_CORE_EXPORT ExceptionFactory : public ExceptionAbstract
{
public:
enum ErrorCodeEnum {
GENERIC = ExceptionAbstract::FACTORY,
UNREFERED_OBJECT,
UNREFERED_SIGNAL,
UNREFERED_FUNCTION,
DYNAMIC_LOADING,
SIGNAL_CONFLICT,
FUNCTION_CONFLICT,
OBJECT_CONFLICT,
SYNTAX_ERROR // j' aime bien FATAL_ERROR aussi faut que je la case qq
// part...
,
READ_FILE
};
static const std::string EXCEPTION_NAME;
virtual const std::string &getExceptionName(void) const {
return ExceptionFactory::EXCEPTION_NAME;
}
ExceptionFactory(const ExceptionFactory::ErrorCodeEnum &errcode,
const std::string &msg = "");
ExceptionFactory(const ExceptionFactory::ErrorCodeEnum &errcode,
const std::string &msg, const char *format, ...);
virtual ~ExceptionFactory(void) throw() {}
};
} /* namespace sot */
} /* namespace dynamicgraph */
#endif /* #ifndef __SOT_EXCEPTION_FACTORY_H */
/*
* Local variables:
* c-basic-offset: 2
* End:
*/
| stack-of-tasks/sot-core | include/sot/core/exception-factory.hh | C++ | bsd-2-clause | 1,792 |
/*
* Source MUD
* Copyright (C) 2000-2005 Sean Middleditch
* See the file COPYING for license details
* http://www.sourcemud.org
*/
#include "common.h"
#include "common/imanager.h"
std::vector<IManager*>* IManager::managers = NULL;
std::vector<IManager*>* IManager::pending = NULL;
// add manager to registry
IManager::IManager()
{
// make managers vector
if (!pending)
pending = new std::vector<IManager*>;
// register
pending->push_back(this);
}
// initialize a manager if not already handled
int IManager::require(IManager& manager)
{
// make managers vector
if (!managers)
managers = new std::vector<IManager*>;
// already initialized?
if (std::find(managers->begin(), managers->end(), &manager) != managers->end())
return 0;
// try initialization
if (manager.initialize())
return 1;
// add to pending list
managers->push_back(&manager);
// all good!
return 0;
}
// load all managers
int IManager::initializeAll()
{
// load manager
for (std::vector<IManager*>::iterator i = pending->begin(); i != pending->end(); ++i)
if (IManager::require(**i))
return -1;
// release pending list
delete pending;
pending = NULL;
return 0;
}
// shutdown all managers
void IManager::shutdownAll()
{
for (std::vector<IManager*>::reverse_iterator i = managers->rbegin(); i != managers->rend(); ++i)
(*i)->shutdown();
}
// save state for all managers
void IManager::saveAll()
{
for (std::vector<IManager*>::reverse_iterator i = managers->rbegin(); i != managers->rend(); ++i)
(*i)->save();
}
| elanthis/sourcemud | src/common/imanager.cc | C++ | bsd-2-clause | 1,535 |
package wkb
import (
"encoding/binary"
"github.com/geodatalake/geom"
"io"
)
func geometryCollectionReader(r io.Reader, byteOrder binary.ByteOrder) (geom.Geom, error) {
var numGeometries uint32
if err := binary.Read(r, byteOrder, &numGeometries); err != nil {
return nil, err
}
geoms := make([]geom.Geom, numGeometries)
for i := uint32(0); i < numGeometries; i++ {
if g, err := Read(r); err == nil {
var ok bool
geoms[i], ok = g.(geom.Geom)
if !ok {
return nil, &UnexpectedGeometryError{g}
}
} else {
return nil, err
}
}
return geom.GeometryCollection(geoms), nil
}
func writeGeometryCollection(w io.Writer, byteOrder binary.ByteOrder, geometryCollection geom.GeometryCollection) error {
if err := binary.Write(w, byteOrder, uint32(len(geometryCollection))); err != nil {
return err
}
for _, geom := range geometryCollection {
if err := Write(w, byteOrder, geom); err != nil {
return err
}
}
return nil
}
| owcm/geom | encoding/wkb/geometrycollection.go | GO | bsd-2-clause | 958 |
// Copyright 2012, 2017 Dmitry Chestnykh. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package wots implements Winternitz-Lamport-Diffie one-time signature scheme.
//
// If the hash function is one-way and of sufficient length, the private key is
// random, not known to the attacker, and used to sign only one message, and
// there are no bugs in this implementation, it is infeasible to forge
// signatures (even on quantum computer, provided that it can't break the
// underlying hash function).
//
// Implementation details
//
// Cost/size trade-off parameter w=8 bits, which means that public key
// generation takes (n+2)*256+1 hash function evaluations, where n is hash
// output size in bytes. Similarly, on average, signing or verifying a single
// message take 1+((n+2)*255)/2 evaluations.
//
// Message hash is calculated with randomization as specified in NIST
// SP-800-106 "Randomized Hashing for Digital Signatures", with length
// of randomization string equal to the length of hash function output.
// The randomization string is prepended to the signature.
package wots
import (
"bytes"
"errors"
"hash"
"io"
)
// Scheme represents one-time signature signing/verification configuration.
type Scheme struct {
blockSize int
hashFunc func() hash.Hash
rand io.Reader
}
// NewScheme returns a new signing/verification scheme from the given function
// returning hash.Hash type and a random byte reader (must be cryptographically
// secure, such as crypto/rand.Reader).
//
// The hash function output size must have minimum 16 and maximum 128 bytes,
// otherwise GenerateKeyPair method will always return error.
func NewScheme(h func() hash.Hash, rand io.Reader) *Scheme {
return &Scheme{
blockSize: h().Size(),
hashFunc: h,
rand: rand,
}
}
// PrivateKeySize returns private key size in bytes.
func (s *Scheme) PrivateKeySize() int { return (s.blockSize + 2) * s.blockSize }
// PublicKeySize returns public key size in bytes.
func (s *Scheme) PublicKeySize() int { return s.blockSize }
// SignatureSize returns signature size in bytes.
func (s *Scheme) SignatureSize() int { return (s.blockSize+2)*s.blockSize + s.blockSize }
// PublicKey represents a public key.
type PublicKey []byte
// PrivateKey represents a private key.
type PrivateKey []byte
// hashBlock returns in hashed the given number of times: H(...H(in)).
// If times is 0, returns a copy of input without hashing it.
func hashBlock(h hash.Hash, in []byte, times int) (out []byte) {
out = append(out, in...)
for i := 0; i < times; i++ {
h.Reset()
h.Write(out)
out = h.Sum(out[:0])
}
return
}
// GenerateKeyPair generates a new private and public key pair.
func (s *Scheme) GenerateKeyPair() (PrivateKey, PublicKey, error) {
if s.blockSize < 16 || s.blockSize > 128 {
return nil, nil, errors.New("wots: wrong hash output size")
}
// Generate random private key.
privateKey := make([]byte, s.PrivateKeySize())
if _, err := io.ReadFull(s.rand, privateKey); err != nil {
return nil, nil, err
}
publicKey, err := s.PublicKeyFromPrivate(privateKey)
if err != nil {
return nil, nil, err
}
return privateKey, publicKey, nil
}
// PublicKeyFromPrivate returns a public key corresponding to the given private key.
func (s *Scheme) PublicKeyFromPrivate(privateKey PrivateKey) (PublicKey, error) {
if len(privateKey) != s.PrivateKeySize() {
return nil, errors.New("wots: private key size doesn't match the scheme")
}
// Create public key from private key.
keyHash := s.hashFunc()
blockHash := s.hashFunc()
for i := 0; i < len(privateKey); i += s.blockSize {
keyHash.Write(hashBlock(blockHash, privateKey[i:i+s.blockSize], 256))
}
return keyHash.Sum(nil), nil
}
// messageDigest returns a randomized digest of message with 2-byte checksum.
func messageDigest(h hash.Hash, r []byte, msg []byte) []byte {
// Randomized hashing (NIST SP-800-106).
//
// Padding: m = msg ‖ 0x80 [0x00...]
// Hashing: H(r ‖ m1 ⊕ r, ..., mL ⊕ r ‖ rv_length_indicator)
// where m1..mL are blocks of size len(r) of padded msg,
// and rv_length_indicator is 16-byte big endian len(r).
//
h.Write(r)
rlen := len(r)
tmp := make([]byte, rlen)
for len(msg) >= rlen {
for i, m := range msg[:rlen] {
tmp[i] = m ^ r[i]
}
h.Write(tmp)
msg = msg[rlen:]
}
for i := range tmp {
tmp[i] = 0
}
copy(tmp, msg)
tmp[len(msg)] = 0x80
for i := range tmp {
tmp[i] ^= r[i]
}
h.Write(tmp)
tmp[0] = uint8(rlen >> 8)
tmp[1] = uint8(rlen)
h.Write(tmp[:2])
d := h.Sum(nil)
// Append checksum of digest bits.
var sum uint16
for _, v := range d {
sum += 256 - uint16(v)
}
return append(d, uint8(sum>>8), uint8(sum))
}
// Sign signs an arbitrary length message using the given private key and
// returns signature.
//
// IMPORTANT: Do not use the same private key to sign more than one message!
// It's a one-time signature.
func (s *Scheme) Sign(privateKey PrivateKey, message []byte) (sig []byte, err error) {
if len(privateKey) != s.PrivateKeySize() {
return nil, errors.New("wots: private key size doesn't match the scheme")
}
blockHash := s.hashFunc()
// Generate message randomization parameter.
r := make([]byte, s.blockSize)
if _, err := io.ReadFull(s.rand, r); err != nil {
return nil, err
}
// Prepend randomization parameter to signature.
sig = append(sig, r...)
for _, v := range messageDigest(s.hashFunc(), r, message) {
sig = append(sig, hashBlock(blockHash, privateKey[:s.blockSize], int(v))...)
privateKey = privateKey[s.blockSize:]
}
return
}
// Verify verifies the signature of message using the public key,
// and returns true iff the signature is valid.
//
// Note: verification time depends on message and signature.
func (s *Scheme) Verify(publicKey PublicKey, message []byte, sig []byte) bool {
if len(publicKey) != s.PublicKeySize() || len(sig) != s.SignatureSize() {
return false
}
d := messageDigest(s.hashFunc(), sig[:s.blockSize], message)
sig = sig[s.blockSize:]
keyHash := s.hashFunc()
blockHash := s.hashFunc()
for _, v := range d {
keyHash.Write(hashBlock(blockHash, sig[:s.blockSize], 256-int(v)))
sig = sig[s.blockSize:]
}
return bytes.Equal(keyHash.Sum(nil), publicKey)
}
| dchest/wots | wots.go | GO | bsd-2-clause | 6,280 |
import traceback
from collections import namedtuple, defaultdict
import itertools
import logging
import textwrap
from shutil import get_terminal_size
from .abstract import Callable, DTypeSpec, Dummy, Literal, Type, weakref
from .common import Opaque
from .misc import unliteral
from numba.core import errors, utils, types, config
from numba.core.typeconv import Conversion
_logger = logging.getLogger(__name__)
# terminal color markup
_termcolor = errors.termcolor()
_FAILURE = namedtuple('_FAILURE', 'template matched error literal')
_termwidth = get_terminal_size().columns
# pull out the lead line as unit tests often use this
_header_lead = "No implementation of function"
_header_template = (_header_lead + " {the_function} found for signature:\n \n "
">>> {fname}({signature})\n \nThere are {ncandidates} "
"candidate implementations:")
_reason_template = """
" - Of which {nmatches} did not match due to:\n
"""
def _wrapper(tmp, indent=0):
return textwrap.indent(tmp, ' ' * indent, lambda line: True)
_overload_template = ("- Of which {nduplicates} did not match due to:\n"
"{kind} {inof} function '{function}': File: {file}: "
"Line {line}.\n With argument(s): '({args})':")
_err_reasons = {'specific_error': "Rejected as the implementation raised a "
"specific error:\n{}"}
def _bt_as_lines(bt):
"""
Converts a backtrace into a list of lines, squashes it a bit on the way.
"""
return [y for y in itertools.chain(*[x.split('\n') for x in bt]) if y]
def argsnkwargs_to_str(args, kwargs):
buf = [str(a) for a in tuple(args)]
buf.extend(["{}={}".format(k, v) for k, v in kwargs.items()])
return ', '.join(buf)
class _ResolutionFailures(object):
"""Collect and format function resolution failures.
"""
def __init__(self, context, function_type, args, kwargs, depth=0):
self._context = context
self._function_type = function_type
self._args = args
self._kwargs = kwargs
self._failures = defaultdict(list)
self._depth = depth
self._max_depth = 5
self._scale = 2
def __len__(self):
return len(self._failures)
def add_error(self, calltemplate, matched, error, literal):
"""
Args
----
calltemplate : CallTemplate
error : Exception or str
Error message
"""
isexc = isinstance(error, Exception)
errclazz = '%s: ' % type(error).__name__ if isexc else ''
key = "{}{}".format(errclazz, str(error))
self._failures[key].append(_FAILURE(calltemplate, matched, error,
literal))
def format(self):
"""Return a formatted error message from all the gathered errors.
"""
indent = ' ' * self._scale
argstr = argsnkwargs_to_str(self._args, self._kwargs)
ncandidates = sum([len(x) for x in self._failures.values()])
# sort out a display name for the function
tykey = self._function_type.typing_key
# most things have __name__
fname = getattr(tykey, '__name__', None)
is_external_fn_ptr = isinstance(self._function_type,
ExternalFunctionPointer)
if fname is None:
if is_external_fn_ptr:
fname = "ExternalFunctionPointer"
else:
fname = "<unknown function>"
msgbuf = [_header_template.format(the_function=self._function_type,
fname=fname,
signature=argstr,
ncandidates=ncandidates)]
nolitargs = tuple([unliteral(a) for a in self._args])
nolitkwargs = {k: unliteral(v) for k, v in self._kwargs.items()}
nolitargstr = argsnkwargs_to_str(nolitargs, nolitkwargs)
# depth could potentially get massive, so limit it.
ldepth = min(max(self._depth, 0), self._max_depth)
def template_info(tp):
src_info = tp.get_template_info()
unknown = "unknown"
source_name = src_info.get('name', unknown)
source_file = src_info.get('filename', unknown)
source_lines = src_info.get('lines', unknown)
source_kind = src_info.get('kind', 'Unknown template')
return source_name, source_file, source_lines, source_kind
for i, (k, err_list) in enumerate(self._failures.items()):
err = err_list[0]
nduplicates = len(err_list)
template, error = err.template, err.error
ifo = template_info(template)
source_name, source_file, source_lines, source_kind = ifo
largstr = argstr if err.literal else nolitargstr
if err.error == "No match.":
err_dict = defaultdict(set)
for errs in err_list:
err_dict[errs.template].add(errs.literal)
# if there's just one template, and it's erroring on
# literal/nonliteral be specific
if len(err_dict) == 1:
template = [_ for _ in err_dict.keys()][0]
source_name, source_file, source_lines, source_kind = \
template_info(template)
source_lines = source_lines[0]
else:
source_file = "<numerous>"
source_lines = "N/A"
msgbuf.append(_termcolor.errmsg(
_wrapper(_overload_template.format(nduplicates=nduplicates,
kind=source_kind.title(),
function=fname,
inof='of',
file=source_file,
line=source_lines,
args=largstr),
ldepth + 1)))
msgbuf.append(_termcolor.highlight(_wrapper(err.error,
ldepth + 2)))
else:
# There was at least one match in this failure class, but it
# failed for a specific reason try and report this.
msgbuf.append(_termcolor.errmsg(
_wrapper(_overload_template.format(nduplicates=nduplicates,
kind=source_kind.title(),
function=source_name,
inof='in',
file=source_file,
line=source_lines[0],
args=largstr),
ldepth + 1)))
if isinstance(error, BaseException):
reason = indent + self.format_error(error)
errstr = _err_reasons['specific_error'].format(reason)
else:
errstr = error
# if you are a developer, show the back traces
if config.DEVELOPER_MODE:
if isinstance(error, BaseException):
# if the error is an actual exception instance, trace it
bt = traceback.format_exception(type(error), error,
error.__traceback__)
else:
bt = [""]
bt_as_lines = _bt_as_lines(bt)
nd2indent = '\n{}'.format(2 * indent)
errstr += _termcolor.reset(nd2indent +
nd2indent.join(bt_as_lines))
msgbuf.append(_termcolor.highlight(_wrapper(errstr,
ldepth + 2)))
loc = self.get_loc(template, error)
if loc:
msgbuf.append('{}raised from {}'.format(indent, loc))
# the commented bit rewraps each block, may not be helpful?!
return _wrapper('\n'.join(msgbuf) + '\n') # , self._scale * ldepth)
def format_error(self, error):
"""Format error message or exception
"""
if isinstance(error, Exception):
return '{}: {}'.format(type(error).__name__, error)
else:
return '{}'.format(error)
def get_loc(self, classtemplate, error):
"""Get source location information from the error message.
"""
if isinstance(error, Exception) and hasattr(error, '__traceback__'):
# traceback is unavailable in py2
frame = traceback.extract_tb(error.__traceback__)[-1]
return "{}:{}".format(frame[0], frame[1])
def raise_error(self):
for faillist in self._failures.values():
for fail in faillist:
if isinstance(fail.error, errors.ForceLiteralArg):
raise fail.error
raise errors.TypingError(self.format())
def _unlit_non_poison(ty):
"""Apply unliteral(ty) and raise a TypingError if type is Poison.
"""
out = unliteral(ty)
if isinstance(out, types.Poison):
m = f"Poison type used in arguments; got {out}"
raise errors.TypingError(m)
return out
class BaseFunction(Callable):
"""
Base type class for some function types.
"""
def __init__(self, template):
if isinstance(template, (list, tuple)):
self.templates = tuple(template)
keys = set(temp.key for temp in self.templates)
if len(keys) != 1:
raise ValueError("incompatible templates: keys = %s"
% (keys,))
self.typing_key, = keys
else:
self.templates = (template,)
self.typing_key = template.key
self._impl_keys = {}
name = "%s(%s)" % (self.__class__.__name__, self.typing_key)
self._depth = 0
super(BaseFunction, self).__init__(name)
@property
def key(self):
return self.typing_key, self.templates
def augment(self, other):
"""
Augment this function type with the other function types' templates,
so as to support more input types.
"""
if type(other) is type(self) and other.typing_key == self.typing_key:
return type(self)(self.templates + other.templates)
def get_impl_key(self, sig):
"""
Get the implementation key (used by the target context) for the
given signature.
"""
return self._impl_keys[sig.args]
def get_call_type(self, context, args, kws):
from numba.core.target_extension import (target_registry,
get_local_target)
prefer_lit = [True, False] # old behavior preferring literal
prefer_not = [False, True] # new behavior preferring non-literal
failures = _ResolutionFailures(context, self, args, kws,
depth=self._depth)
# get the current target target
target_hw = get_local_target(context)
# fish out templates that are specific to the target if a target is
# specified
DEFAULT_TARGET = 'generic'
usable = []
for ix, temp_cls in enumerate(self.templates):
# ? Need to do something about this next line
hw = temp_cls.metadata.get('target', DEFAULT_TARGET)
if hw is not None:
hw_clazz = target_registry[hw]
if target_hw.inherits_from(hw_clazz):
usable.append((temp_cls, hw_clazz, ix))
# sort templates based on target specificity
def key(x):
return target_hw.__mro__.index(x[1])
order = [x[0] for x in sorted(usable, key=key)]
if not order:
msg = (f"Function resolution cannot find any matches for function"
f" '{self.key[0]}' for the current target: '{target_hw}'.")
raise errors.UnsupportedError(msg)
self._depth += 1
for temp_cls in order:
temp = temp_cls(context)
# The template can override the default and prefer literal args
choice = prefer_lit if temp.prefer_literal else prefer_not
for uselit in choice:
try:
if uselit:
sig = temp.apply(args, kws)
else:
nolitargs = tuple([_unlit_non_poison(a) for a in args])
nolitkws = {k: _unlit_non_poison(v)
for k, v in kws.items()}
sig = temp.apply(nolitargs, nolitkws)
except Exception as e:
sig = None
failures.add_error(temp, False, e, uselit)
else:
if sig is not None:
self._impl_keys[sig.args] = temp.get_impl_key(sig)
self._depth -= 1
return sig
else:
registered_sigs = getattr(temp, 'cases', None)
if registered_sigs is not None:
msg = "No match for registered cases:\n%s"
msg = msg % '\n'.join(" * {}".format(x) for x in
registered_sigs)
else:
msg = 'No match.'
failures.add_error(temp, True, msg, uselit)
failures.raise_error()
def get_call_signatures(self):
sigs = []
is_param = False
for temp in self.templates:
sigs += getattr(temp, 'cases', [])
is_param = is_param or hasattr(temp, 'generic')
return sigs, is_param
class Function(BaseFunction, Opaque):
"""
Type class for builtin functions implemented by Numba.
"""
class BoundFunction(Callable, Opaque):
"""
A function with an implicit first argument (denoted as *this* below).
"""
def __init__(self, template, this):
# Create a derived template with an attribute *this*
newcls = type(template.__name__ + '.' + str(this), (template,),
dict(this=this))
self.template = newcls
self.typing_key = self.template.key
self.this = this
name = "%s(%s for %s)" % (self.__class__.__name__,
self.typing_key, self.this)
super(BoundFunction, self).__init__(name)
def unify(self, typingctx, other):
if (isinstance(other, BoundFunction) and
self.typing_key == other.typing_key):
this = typingctx.unify_pairs(self.this, other.this)
if this is not None:
# XXX is it right that both template instances are distinct?
return self.copy(this=this)
def copy(self, this):
return type(self)(self.template, this)
@property
def key(self):
return self.typing_key, self.this
def get_impl_key(self, sig):
"""
Get the implementation key (used by the target context) for the
given signature.
"""
return self.typing_key
def get_call_type(self, context, args, kws):
template = self.template(context)
literal_e = None
nonliteral_e = None
out = None
choice = [True, False] if template.prefer_literal else [False, True]
for uselit in choice:
if uselit:
# Try with Literal
try:
out = template.apply(args, kws)
except Exception as exc:
if isinstance(exc, errors.ForceLiteralArg):
raise exc
literal_e = exc
out = None
else:
break
else:
# if the unliteral_args and unliteral_kws are the same as the
# literal ones, set up to not bother retrying
unliteral_args = tuple([_unlit_non_poison(a) for a in args])
unliteral_kws = {k: _unlit_non_poison(v)
for k, v in kws.items()}
skip = unliteral_args == args and kws == unliteral_kws
# If the above template application failed and the non-literal
# args are different to the literal ones, try again with
# literals rewritten as non-literals
if not skip and out is None:
try:
out = template.apply(unliteral_args, unliteral_kws)
except Exception as exc:
if isinstance(exc, errors.ForceLiteralArg):
if template.prefer_literal:
# For template that prefers literal types,
# reaching here means that the literal types
# have failed typing as well.
raise exc
nonliteral_e = exc
else:
break
if out is None and (nonliteral_e is not None or literal_e is not None):
header = "- Resolution failure for {} arguments:\n{}\n"
tmplt = _termcolor.highlight(header)
if config.DEVELOPER_MODE:
indent = ' ' * 4
def add_bt(error):
if isinstance(error, BaseException):
# if the error is an actual exception instance, trace it
bt = traceback.format_exception(type(error), error,
error.__traceback__)
else:
bt = [""]
nd2indent = '\n{}'.format(2 * indent)
errstr = _termcolor.reset(nd2indent +
nd2indent.join(_bt_as_lines(bt)))
return _termcolor.reset(errstr)
else:
add_bt = lambda X: ''
def nested_msg(literalness, e):
estr = str(e)
estr = estr if estr else (str(repr(e)) + add_bt(e))
new_e = errors.TypingError(textwrap.dedent(estr))
return tmplt.format(literalness, str(new_e))
raise errors.TypingError(nested_msg('literal', literal_e) +
nested_msg('non-literal', nonliteral_e))
return out
def get_call_signatures(self):
sigs = getattr(self.template, 'cases', [])
is_param = hasattr(self.template, 'generic')
return sigs, is_param
class MakeFunctionLiteral(Literal, Opaque):
pass
class _PickleableWeakRef(weakref.ref):
"""
Allow a weakref to be pickled.
Note that if the object referred to is not kept alive elsewhere in the
pickle, the weakref will immediately expire after being constructed.
"""
def __getnewargs__(self):
obj = self()
if obj is None:
raise ReferenceError("underlying object has vanished")
return (obj,)
class WeakType(Type):
"""
Base class for types parametered by a mortal object, to which only
a weak reference is kept.
"""
def _store_object(self, obj):
self._wr = _PickleableWeakRef(obj)
def _get_object(self):
obj = self._wr()
if obj is None:
raise ReferenceError("underlying object has vanished")
return obj
@property
def key(self):
return self._wr
def __eq__(self, other):
if type(self) is type(other):
obj = self._wr()
return obj is not None and obj is other._wr()
return NotImplemented
def __hash__(self):
return Type.__hash__(self)
class Dispatcher(WeakType, Callable, Dummy):
"""
Type class for @jit-compiled functions.
"""
def __init__(self, dispatcher):
self._store_object(dispatcher)
super(Dispatcher, self).__init__("type(%s)" % dispatcher)
def dump(self, tab=''):
print((f'{tab}DUMP {type(self).__name__}[code={self._code}, '
f'name={self.name}]'))
self.dispatcher.dump(tab=tab + ' ')
print(f'{tab}END DUMP')
def get_call_type(self, context, args, kws):
"""
Resolve a call to this dispatcher using the given argument types.
A signature returned and it is ensured that a compiled specialization
is available for it.
"""
template, pysig, args, kws = \
self.dispatcher.get_call_template(args, kws)
sig = template(context).apply(args, kws)
if sig:
sig = sig.replace(pysig=pysig)
return sig
def get_call_signatures(self):
sigs = self.dispatcher.nopython_signatures
return sigs, True
@property
def dispatcher(self):
"""
A strong reference to the underlying numba.dispatcher.Dispatcher
instance.
"""
return self._get_object()
def get_overload(self, sig):
"""
Get the compiled overload for the given signature.
"""
return self.dispatcher.get_overload(sig.args)
def get_impl_key(self, sig):
"""
Get the implementation key for the given signature.
"""
return self.get_overload(sig)
def unify(self, context, other):
return utils.unified_function_type((self, other), require_precise=False)
def can_convert_to(self, typingctx, other):
if isinstance(other, types.FunctionType):
if self.dispatcher.get_compile_result(other.signature):
return Conversion.safe
class ObjModeDispatcher(Dispatcher):
"""Dispatcher subclass that enters objectmode function.
"""
pass
class ExternalFunctionPointer(BaseFunction):
"""
A pointer to a native function (e.g. exported via ctypes or cffi).
*get_pointer* is a Python function taking an object
and returning the raw pointer value as an int.
"""
def __init__(self, sig, get_pointer, cconv=None):
from numba.core.typing.templates import (AbstractTemplate,
make_concrete_template,
signature)
from numba.core.types import ffi_forced_object
if sig.return_type == ffi_forced_object:
raise TypeError("Cannot return a pyobject from a external function")
self.sig = sig
self.requires_gil = any(a == ffi_forced_object for a in self.sig.args)
self.get_pointer = get_pointer
self.cconv = cconv
if self.requires_gil:
class GilRequiringDefn(AbstractTemplate):
key = self.sig
def generic(self, args, kws):
if kws:
raise TypeError("does not support keyword arguments")
# Make ffi_forced_object a bottom type to allow any type to
# be casted to it. This is the only place that support
# ffi_forced_object.
coerced = [actual if formal == ffi_forced_object else formal
for actual, formal
in zip(args, self.key.args)]
return signature(self.key.return_type, *coerced)
template = GilRequiringDefn
else:
template = make_concrete_template("CFuncPtr", sig, [sig])
super(ExternalFunctionPointer, self).__init__(template)
@property
def key(self):
return self.sig, self.cconv, self.get_pointer
class ExternalFunction(Function):
"""
A named native function (resolvable by LLVM) accepting an explicit
signature. For internal use only.
"""
def __init__(self, symbol, sig):
from numba.core import typing
self.symbol = symbol
self.sig = sig
template = typing.make_concrete_template(symbol, symbol, [sig])
super(ExternalFunction, self).__init__(template)
@property
def key(self):
return self.symbol, self.sig
class NamedTupleClass(Callable, Opaque):
"""
Type class for namedtuple classes.
"""
def __init__(self, instance_class):
self.instance_class = instance_class
name = "class(%s)" % (instance_class)
super(NamedTupleClass, self).__init__(name)
def get_call_type(self, context, args, kws):
# Overridden by the __call__ constructor resolution in
# typing.collections
return None
def get_call_signatures(self):
return (), True
@property
def key(self):
return self.instance_class
class NumberClass(Callable, DTypeSpec, Opaque):
"""
Type class for number classes (e.g. "np.float64").
"""
def __init__(self, instance_type):
self.instance_type = instance_type
name = "class(%s)" % (instance_type,)
super(NumberClass, self).__init__(name)
def get_call_type(self, context, args, kws):
# Overridden by the __call__ constructor resolution in typing.builtins
return None
def get_call_signatures(self):
return (), True
@property
def key(self):
return self.instance_type
@property
def dtype(self):
return self.instance_type
class RecursiveCall(Opaque):
"""
Recursive call to a Dispatcher.
"""
_overloads = None
def __init__(self, dispatcher_type):
assert isinstance(dispatcher_type, Dispatcher)
self.dispatcher_type = dispatcher_type
name = "recursive(%s)" % (dispatcher_type,)
super(RecursiveCall, self).__init__(name)
# Initializing for the first time
if self._overloads is None:
self._overloads = {}
@property
def overloads(self):
return self._overloads
@property
def key(self):
return self.dispatcher_type
| stonebig/numba | numba/core/types/functions.py | Python | bsd-2-clause | 26,542 |
cask v1: 'xtorrent' do
version '2.1(v171)'
sha256 '26ea235dcb827c6e58ab3409bec83396e86704d742d517e527016ecd44672379'
# dreamhosters.com is the official download host per the vendor homepage
url "http://acquisition.dreamhosters.com/xtorrent/Xtorrent#{version}.dmg"
name 'Xtorrent'
appcast 'https://xtorrent.s3.amazonaws.com/appcast.xml',
sha256: '21d8752a39782479a9f6f2485b0aba0af3f1f12d17ebc938c7526e5ca1a8b355'
homepage 'http://www.xtorrent.com'
license :freemium
app 'Xtorrent.app'
end
| askl56/homebrew-cask | Casks/xtorrent.rb | Ruby | bsd-2-clause | 518 |
import React from "react"
import { Helmet } from "react-helmet"
import { useParams } from "react-router-dom"
import Box from "@material-ui/core/Box"
import { useStrainQuery } from "dicty-graphql-schema"
import DetailsHeader from "features/Stocks/Details/common/DetailsHeader"
import DetailsLoader from "features/Stocks/Details/common/DetailsLoader"
import StrainDetailsCard from "./StrainDetailsCard"
import GraphQLErrorPage from "features/Errors/GraphQLErrorPage"
import characterConverter from "common/utils/characterConverter"
type Params = {
/** Stock ID from URL */
id: string
}
/**
* StrainDetailsContainer is the main component for an individual strain details page.
* It is responsible for fetching the data and passing it down to more specific components.
*/
const StrainDetailsContainer = () => {
const { id } = useParams<Params>()
const { loading, error, data } = useStrainQuery({
variables: { id },
errorPolicy: "ignore",
fetchPolicy: "cache-and-network",
})
if (loading) return <DetailsLoader />
if (error) return <GraphQLErrorPage error={error} />
const label = characterConverter(data?.strain?.label as string)
let title = `Strain Details for ${label}`
if (data?.strain?.phenotypes && data.strain.phenotypes.length > 0) {
title = `Phenotype and Strain Details for ${label}`
}
return (
<Box textAlign="center">
<Helmet>
<title>{title} - Dicty Stock Center</title>
<meta
name="description"
content={`Dicty Stock Center strain details page for ${label}`}
/>
</Helmet>
{data?.strain && (
<React.Fragment>
<DetailsHeader id={data.strain.id} name={data.strain.label} />
<StrainDetailsCard data={data.strain} />
</React.Fragment>
)}
</Box>
)
}
export { StrainDetailsContainer }
export default StrainDetailsContainer
| dictyBase/Dicty-Stock-Center | src/features/Stocks/Details/Strains/StrainDetailsContainer.tsx | TypeScript | bsd-2-clause | 1,888 |
//=============================================================================
// Copyright © Jason Heddings, All Rights Reserved
// $Id: SimpleTask.cs 83 2013-11-06 23:34:18Z jheddings $
//=============================================================================
using System;
using System.Xml.Serialization;
using Flynn.Utilities;
// a SimpleTask attaches to a trigger and invokes a corresponding action
namespace Flynn.Core.Tasks {
[XmlRoot("SimpleTask", Namespace = "Flynn.Core.Tasks")]
public sealed class SimpleTask : TaskBase, IDisposable {
private static readonly Logger _logger = Logger.Get(typeof(SimpleTask));
///////////////////////////////////////////////////////////////////////
public override bool Enabled { get; set; }
///////////////////////////////////////////////////////////////////////
private ITrigger _trigger;
public ITrigger Trigger {
get { return _trigger; }
set {
// unregister existing events
if (_trigger != null) {
_trigger.Fire -= Trigger_OnFire;
}
// register with the new trigger
if (value != null) {
value.Fire += Trigger_OnFire;
}
_trigger = value;
}
}
///////////////////////////////////////////////////////////////////////
public IAction Action { get; set; }
///////////////////////////////////////////////////////////////////////
public IFilter Filter { get; set; }
///////////////////////////////////////////////////////////////////////
public SimpleTask() {
}
///////////////////////////////////////////////////////////////////////
public SimpleTask(ITrigger trigger, IAction action) {
Action = action;
Trigger = trigger;
}
///////////////////////////////////////////////////////////////////////
public SimpleTask(ITrigger trigger, IAction action, IFilter filter) {
Action = action;
Filter = filter;
Trigger = trigger;
}
///////////////////////////////////////////////////////////////////////
public void Dispose() {
Enabled = false;
Action = null;
Trigger = null;
}
///////////////////////////////////////////////////////////////////////
private void Trigger_OnFire(Object sender, EventArgs args) {
if (! Enabled) { return; }
if ((Filter != null) && (! Filter.Accept())) {
_logger.Debug("trigger rejected by filter");
return;
}
if (Action == null) {
_logger.Debug("trigger fired; no action");
return;
}
_logger.Debug("trigger fired");
try {
Action.Invoke();
} catch (Exception e) {
_logger.Error(e);
}
}
}
}
| jheddings/flynn | source/core/Tasks/SimpleTask.cs | C# | bsd-2-clause | 3,021 |
#region Copyright notice
/**
* Copyright (c) 2018 Samsung Electronics, Inc.,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DexterCRC.Tests
{
[TestClass()]
public class ClassCRCTests
{
ClassCRC classCRC;
void Init()
{
classCRC = new ClassCRC();
}
[TestMethod]
public void CheckEventNamingTest_ReturnsTrue_Invalid_Class_Name()
{
Init();
// Given
string className = @"MyEvent";
string baseName = @"EventArgs";
// When
bool result = classCRC.CheckEventNaming(className, baseName);
// Then
Assert.IsTrue(result);
}
[TestMethod]
public void CheckEventNamingTest_ValidClassName_ReturnsFalse()
{
Init();
// Given
string className = @"MyEventArgs";
string baseName = @"EventArgs";
// When
bool result = classCRC.CheckEventNaming(className, baseName);
// Then
Assert.IsFalse(result);
}
[TestMethod]
public void CheckAttributeNamingTest_InvalidClassName_ReturnsTrue()
{
Init();
// Given
string className = @"User";
string baseName = @"Attribute";
// When
bool result = classCRC.CheckAttributeNaming(className, baseName);
// Then
Assert.IsTrue(result);
}
[TestMethod]
public void CheckAttributeNamingTest_ValidClassName_ReturnsFalse()
{
Init();
// Given
string className = @"HelpAttribute";
string baseName = @"Attribute";
// When
bool result = classCRC.CheckAttributeNaming(className, baseName);
// Then
Assert.IsFalse(result);
}
}
} | Samsung/Dexter | project/dexter-cs/DexterCSTest/Src/Crc/ClassCRCTests.cs | C# | bsd-2-clause | 3,256 |
goog.provide('ol.layer.Group');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.math');
goog.require('goog.object');
goog.require('ol.Collection');
goog.require('ol.CollectionEvent');
goog.require('ol.CollectionEventType');
goog.require('ol.Object');
goog.require('ol.ObjectEventType');
goog.require('ol.layer.Base');
goog.require('ol.source.State');
/**
* @enum {string}
*/
ol.layer.GroupProperty = {
LAYERS: 'layers'
};
/**
* @constructor
* @extends {ol.layer.Base}
* @param {olx.layer.GroupOptions=} opt_options Layer options.
* @todo observable layers {ol.Collection} collection of {@link ol.layer} layers
* that are part of this group
* @todo api
*/
ol.layer.Group = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
var baseOptions = /** @type {olx.layer.GroupOptions} */
(goog.object.clone(options));
delete baseOptions.layers;
var layers = options.layers;
goog.base(this, baseOptions);
/**
* @private
* @type {Object.<string, goog.events.Key>}
*/
this.listenerKeys_ = null;
goog.events.listen(this,
ol.Object.getChangeEventType(ol.layer.GroupProperty.LAYERS),
this.handleLayersChanged_, false, this);
if (goog.isDef(layers)) {
if (goog.isArray(layers)) {
layers = new ol.Collection(goog.array.clone(layers));
} else {
goog.asserts.assertInstanceof(layers, ol.Collection);
layers = layers;
}
} else {
layers = new ol.Collection();
}
this.setLayers(layers);
};
goog.inherits(ol.layer.Group, ol.layer.Base);
/**
* @private
*/
ol.layer.Group.prototype.handleLayerChange_ = function() {
if (this.getVisible()) {
this.dispatchChangeEvent();
}
};
/**
* @param {goog.events.Event} event Event.
* @private
*/
ol.layer.Group.prototype.handleLayersChanged_ = function(event) {
if (!goog.isNull(this.listenerKeys_)) {
goog.array.forEach(
goog.object.getValues(this.listenerKeys_), goog.events.unlistenByKey);
this.listenerKeys_ = null;
}
var layers = this.getLayers();
if (goog.isDefAndNotNull(layers)) {
this.listenerKeys_ = {
'add': goog.events.listen(layers, ol.CollectionEventType.ADD,
this.handleLayersAdd_, false, this),
'remove': goog.events.listen(layers, ol.CollectionEventType.REMOVE,
this.handleLayersRemove_, false, this)
};
var layersArray = layers.getArray();
var i, ii, layer;
for (i = 0, ii = layersArray.length; i < ii; i++) {
layer = layersArray[i];
this.listenerKeys_[goog.getUid(layer).toString()] =
goog.events.listen(layer,
[ol.ObjectEventType.PROPERTYCHANGE, goog.events.EventType.CHANGE],
this.handleLayerChange_, false, this);
}
}
this.dispatchChangeEvent();
};
/**
* @param {ol.CollectionEvent} collectionEvent Collection event.
* @private
*/
ol.layer.Group.prototype.handleLayersAdd_ = function(collectionEvent) {
var layer = /** @type {ol.layer.Base} */ (collectionEvent.element);
this.listenerKeys_[goog.getUid(layer).toString()] = goog.events.listen(
layer, [ol.ObjectEventType.PROPERTYCHANGE, goog.events.EventType.CHANGE],
this.handleLayerChange_, false, this);
this.dispatchChangeEvent();
};
/**
* @param {ol.CollectionEvent} collectionEvent Collection event.
* @private
*/
ol.layer.Group.prototype.handleLayersRemove_ = function(collectionEvent) {
var layer = /** @type {ol.layer.Base} */ (collectionEvent.element);
var key = goog.getUid(layer).toString();
goog.events.unlistenByKey(this.listenerKeys_[key]);
delete this.listenerKeys_[key];
this.dispatchChangeEvent();
};
/**
* @return {ol.Collection|undefined} Collection of layers.
*/
ol.layer.Group.prototype.getLayers = function() {
return /** @type {ol.Collection|undefined} */ (this.get(
ol.layer.GroupProperty.LAYERS));
};
goog.exportProperty(
ol.layer.Group.prototype,
'getLayers',
ol.layer.Group.prototype.getLayers);
/**
* @param {ol.Collection|undefined} layers Collection of layers.
*/
ol.layer.Group.prototype.setLayers = function(layers) {
this.set(ol.layer.GroupProperty.LAYERS, layers);
};
goog.exportProperty(
ol.layer.Group.prototype,
'setLayers',
ol.layer.Group.prototype.setLayers);
/**
* @inheritDoc
*/
ol.layer.Group.prototype.getLayersArray = function(opt_array) {
var array = (goog.isDef(opt_array)) ? opt_array : [];
this.getLayers().forEach(function(layer) {
layer.getLayersArray(array);
});
return array;
};
/**
* @inheritDoc
*/
ol.layer.Group.prototype.getLayerStatesArray = function(opt_states) {
var states = (goog.isDef(opt_states)) ? opt_states : [];
var pos = states.length;
this.getLayers().forEach(function(layer) {
layer.getLayerStatesArray(states);
});
var ownLayerState = this.getLayerState();
var i, ii, layerState;
for (i = pos, ii = states.length; i < ii; i++) {
layerState = states[i];
layerState.brightness = goog.math.clamp(
layerState.brightness + ownLayerState.brightness, -1, 1);
layerState.contrast *= ownLayerState.contrast;
layerState.hue += ownLayerState.hue;
layerState.opacity *= ownLayerState.opacity;
layerState.saturation *= ownLayerState.saturation;
layerState.visible = layerState.visible && ownLayerState.visible;
layerState.maxResolution = Math.min(
layerState.maxResolution, ownLayerState.maxResolution);
layerState.minResolution = Math.max(
layerState.minResolution, ownLayerState.minResolution);
}
return states;
};
/**
* @inheritDoc
*/
ol.layer.Group.prototype.getSourceState = function() {
return ol.source.State.READY;
};
| jeluard/cljs-ol3js | resources/closure-js/libs/ol-v3.0.0-beta.5/ol/layer/layergroup.js | JavaScript | bsd-2-clause | 5,759 |
using UnityEngine;
using System.Collections.Generic;
using Require;
using System;
[Serializable]
public class CircuitDictionaryItem
{
public string transitionName;
public List<CircuitComponent> transition;
}
public class CircuitDictionaryComponent : CircuitComponent
{
public List<CircuitDictionaryItem> transitions;
public void Spark(string transitionName)
{
bool found = false;
foreach (CircuitDictionaryItem item in transitions)
{
if (transitionName == item.transitionName)
{
Spark(item.transition);
found = true;
}
}
if (!found)
{
throw new KeyNotFoundException("trying to spark " + transitionName + " but it doesn't exist");
}
}
public void Chain(string transitionName, CircuitComponent component)
{
if (transitions == null)
{
transitions = new List<CircuitDictionaryItem>();
}
foreach (CircuitDictionaryItem item in transitions)
{
if (item.transitionName == transitionName)
{
if (item.transition == null)
{
item.transition = new List<CircuitComponent>();
}
item.transition.Add(component);
return;
}
}
CircuitDictionaryItem newItem = new CircuitDictionaryItem();
newItem.transitionName = transitionName;
newItem.transition = new List<CircuitComponent>();
newItem.transition.Add(component);
transitions.Add(newItem);
}
}
| invisibledrygoods/Circuitry | Circuitry/Assets/Scripts/CircuitDictionary.cs | C# | bsd-2-clause | 1,648 |
#ifndef AFFICHEUR_HPP
#define AFFICHEUR_HPP
#include "QSFMLCanvas.hpp"
#include <iostream>
//QT
#include <QtGui>
//SFML
#include <SFML/Graphics.hpp>
//perso
#include "Taille_fenetre.hpp"
#include "afficheur_options.hpp"
#include "afficheur_options_perso.hpp"
#include "map_options.hpp"
#include "Editeur_skill.hpp"
#include "Editeur_Quette.h"
#include "Text_Encadre.hpp"
#include "sons_option.hpp"
class AFFICHEUR_GRILLE : public QSFMLCanvas
{
/********************************************
cette classe, est la classe principal par laquelle passe la mojorité
des evenemets.
elle delègue certains calcules à d'autres classe.
Elle gere surtout tout ce qui concerne l'edition de la carte
(positionner les decors, objets, pnj, hero ) et delegue
la modification des caractéristique de ceux ci
Elle gere également les racourcis clavier pour permettre une edition plus rappide des niveaux
*/
Q_OBJECT
public :
AFFICHEUR_GRILLE(QWidget* Parent=0) : QSFMLCanvas(Parent, QPoint(0,0), QSize(taille_objets_pix*taille_carte_case_x,taille_objets_pix*taille_carte_case_y))
{
taille_x=taille_carte_case_x;
taille_y=taille_carte_case_y;
init();
};
void mousePressEvent ( QMouseEvent * event ); //permet de gere les evenement souris lors du click
void mouseReleaseEvent (QMouseEvent *event); //permet de gerer les evenemetn souris lors du relachement
void mouseMoveEvent ( QMouseEvent * event ); //permet de gere les evenement souris lors de son deplacement
void keyPressEvent (QKeyEvent * event); //permet de gere les evenement clavier (raccourcis)
void keyReleaseEvent ( QKeyEvent * event ); //permet de gere les evenement clavier (stop des raccourcis)
void OnInit(); //ce qui est fait au premeier lancement de la class
void OnUpdate(); //se qui est vérifié en permanence et fait à chaque frame
void init(); //se qui est commun aux constructeurs
void Set_sprite_courant(sf::Sprite spr) {sprite_courant=spr;}; //permet de dire quel sprite est actuelement en selection
void add_PNJ(); //permet d'ajouter un PNJ à la carte
void add_OBJ(); //permet d'ajouter un objet à la carte
void Set_sprite_courant_PNJ(sf::Sprite s) {sprite_courant_PNJ=s;}; //permet de dire quel est le sprite de l'objet courant
void Set_sprite_courant_OBJ(sf::Sprite s) {sprite_courant_OBJ=s;}; //idem masi avec les objets
void Set_grille( std::vector<sf::Sprite> g); //permet d'obtenir la grille de base à afficher
void SetAutoImage(sf::Image* img) {AutoImage=img;}; //permet de dire quelle est l'image utilisé pour l'edition des contours automatique
void SetType(_type_objets t); // permet de dir le type d'objet qui est actuelement ajouter
void SetLvl(int l); //permet de modifier le niveau des monstres qui seron ajouter (calcul des stats en fonction du niveau)
void MajAuto(); //permet de mettre à jours les different sprite autours du curseurs dans le cas d'un ajout ou d'une supretion en mode d'edition automatique
void UpLevelPnj(int u);
std::vector<sf::Sprite> grille; //tableau de tous les srite qui sont affiché (grille, ou sripte de la carte)
std::vector<sf::Sprite> grille_collision; //permet de montrer graphiquemet si il y a une collision ou pas à une case donnée
std::vector<sf::Sprite> tab_PNJ; //tableau de tous les PNJ qui sont sur la carte (sprite)
std::vector<_PNJ> tab_PNJ_struct; //tableau de tous les pnj qui sont sur la carte (leur informations)
std::vector<sf::Sprite> tab_OBJ; //tableau de tous les objets qui sont sur la carte (sprites)
std::vector<_OBJ> tab_OBJ_struct; //tableau de tous les objet qui sont sur la cartes (infos)
std::vector<Sons_Spacialise> tab_SONS_struct; //tableau de tous les sons
sf::Image image_grille,image_colision_no,Image_vide,image_mur,Image_TP,image_son; //differentes images qui sont utilisés (grille , si il u a une colision, image transparente, image des mur invisible, image associé à la sortie des teleporteurs)
sf::Sprite sprite_mur,sprite_fond,sprite_son; // sprite associé aux image des mur invisible et à l'image de fond du niveau
sf::Image image_fond; //image de fond du niveau
void Set_PNJ(_PNJ p,sf::Image* i); //permet d'ajouter un PNG avec les infos de base, et l'image qui lui est assicié
void Set_OBJ(_OBJ o,sf::Image* i); //idem masi avec un objet
void Set_Heros_coord(int x,int y); //permet de modifier la position du hero
void Set_Map(options_map ma) {map_option->setMap(ma);modifFond();}; //permet de dire quelle sont des differents options associé à la cartes
void SetAuto(bool a){Auto=a;}; //permet de dir si l'on est en mode auto ou pas (gestion des bordures tou seul)
// void SetDestTP(_OBJ*);//permet de definir la destination du teleporteur actuelement en cour d'edition
options_map getMapOption() {return map_option->getMapOption();}; //permet d'avoir les option de la carte
void setPointOrigineVue(Vector2i i) {point=i;}; //permet d'avoir les coordonnée de l'ange haut gauche pour n'afficher que se qu'il faut à l'écrant (un bout de la carte)
void setClickSouris(Vector2f * cl,Vector2f * rel) {clickPush=cl;clickRelase=rel;} //permet de dir ou la souris à ete enfoncé, et ou elle est relaché (pour permetre de bouger la carte ave l'apuie de la molette)
heros curent_Heros; //caractéristique du hero
TEXT_ENCADRE Aide; //texte d'aide afin de dire se qui est actuelement fait
public slots :
void reset(); //permet d'effacer les info de la cartes acctuelle poour en commencer une nouvelle
void Set_type_edition(int c); //permet de dir se qui est actuelement editer
void modifFond(); //permet de mettre a jour l'image du fond de niveau
void ChangeDestTp() {DestTP=true;}; //permet de dir que l'on veu changer la destination d'un teleporteur
signals:
void Clicked(); //pour dire que la souris à été enfoncée
void Relased(); //pour dire que le souris à etre relachée
private :
Vector2i point; //coordonée de l'angle supérieur gauche
Vector2f *clickPush,*clickRelase; //coordonée des point d'enfoncement et de relachement de la souris
std::vector<sf::Sprite>::iterator grille_iter; //permet le parcour du tableau de sprite
sf::Sprite sprite_courant, //sprite qui est actuelement utilisé
sprite_courant_PNJ, //sprite du PNJ acctuelement en edition
sprite_courant_OBJ, //idemen avec un objet
sprite_all_items; //sprite contenant le skill de tous les objets spéciaux
_PNJ curent_PNJ; //information sur le pnj courant
_OBJ curent_OBJ,*Telep; //information sur l'objet courant, et sur le teleporteur courant
_type_objets currentType,currentTypeReal; //permet de gérer le type des objet avec un raccourcis clavier, et pendant un raccourcis clavier
int curentLvl; //niveau qui doit etre associer au monstre qui sont ajoutes
MAP_OPTION* map_option; //information de la carte
sf::Image hero_img,image_all_items,telepor_vert,etoile_boss_I; //image utilisé pour le hero, les objet spéciaux, et teleporteur
sf::Image* AutoImage; //pointeur sur l'image du skin de niveau en mode automatique
OBJECT *heros_obj; //animation du hero
AFFICHEUR_OPTION_PERSO* option_perso; //fenettre permetant de gere les options du hero
sf::Sprite gr,vide,TP,telepor,etoile_boss_S; //different sprites grille de base, sprite transparent,destination de teleporteur en cour d'edition, et destination des autres teleporteur
Editeur_Skill* Fenettre_skill; //fenettre qui permet de gerer l'edition des skill
Editeur_Quette* Fenettre_quette;//fenettre qui permet d'editer plus facilement toutes les interaction de quette en une seulle fenettre
AFFICHEUR_OPTION* Options; //fenettre qui permets de gere les option des objets ou PNJ
SONS_OPTION * sons_option;
bool show_options,Auto,collision,PressedRight,PressedLeft,DestTP; //different bool pour tester l'etat. savoir si il faut afficher les options du mode d'edition en cour, savoir si le mod auto est activé , savoir si il y a des collision ou pas
//savoir si le boutant droit ou gauche de la souris à ete pressé, et pour savoir si on doit modifier la destination du teleporteur courant
void MajSpriteCourant(int c,bool first=false); // fonction qui permet de mettre à jours la grille en lui specifiant la case (cette fonction est recursive dans la cas du l'edition auto, d'ou le bool )
inline void MajSpriteCourant(int x,int y,bool first=false) {MajSpriteCourant(convertToCase(x,y),first);}; //idem, masi avec les coordonée de la case à la place de l'index
void MajSpriteCourantDel(int c); //permet de supprimer le decort mis ) la case spécifié
inline bool IsImageAuto(int c) {return grille[c].GetImage()==AutoImage;}; // savoir si le sprite à la case spécifié fait partie de l'edition auto
inline bool IsImageAuto(int x,int y) {return IsImageAuto(convertToCase(x,y));}; //idemen, mais avec les coordonée
inline int convertToCase(Vector2i v) {return (v.y*taille_x+v.x);}; //fonction qui permet de convertir une position en index du tableau de la grille
inline Vector2i convertToVector(int c) { Vector2i v;v.x=c%taille_x;v.y=c/taille_x;return v;}; // permet de convertir un idex en coordonées
inline int convertToCase(int x,int y) {return convertToCase(Vector2i(x,y));}; //fonction qui permet de convertir une position en index du tableau de la grille
inline bool testProximite(Vector2i V) { return (grille[convertToCase(V.x,V.y)].GetImage() != &image_grille && grille[convertToCase(V.x,V.y)].GetImage() != &image_mur);}; // permet de savoir si il y a des sprite mis en edition auto autour d'une coordonées
inline bool testProximite(int c) { return testProximite(convertToVector(c));}; //idem, masi avec un l'index du talbeau en parametre
inline bool testProximite(int x,int y){ return testProximite(convertToCase(x,y));}; //idem avec des coordonée en parametre
struct {
unsigned int i; //case du pnj concernéé dans le vector
enum DIR{MIN=0,MAX} dir; //si c'est le minimum ou le max à redéfinir
} ref_pnj; //structure qui sert a savoir quel pnj est utilisé en se moment
int taille_x,taille_y; //taille en nombre de cases
_type_edition type_edition; //type d'édition en cour
};
#endif
| Krozark/Dethroned-God | SFML-1.6/Editeur/afficheur.hpp | C++ | bsd-2-clause | 10,554 |
from django.conf.urls import patterns, url
from packages.simple.views import PackageIndex, PackageDetail
handler404 = "packages.simple.views.not_found"
urlpatterns = patterns("",
url(r"^$", PackageIndex.as_view(), name="simple_package_index"),
url(r"^(?P<slug>[^/]+)/(?:(?P<version>[^/]+)/)?$", PackageDetail.as_view(), name="simple_package_detail"),
)
| crate-archive/crate-site | crateweb/apps/packages/simple/urls.py | Python | bsd-2-clause | 364 |
class ApacheSpark121 < Formula
desc "Engine for large-scale data processing"
homepage "https://spark.apache.org/"
url "https://d3kbcqa49mib13.cloudfront.net/spark-1.2.1-bin-hadoop2.4.tgz"
version "1.2.1"
sha256 "8e618cf67b3090acf87119a96e5e2e20e51f6266c44468844c185122b492b454"
head "https://github.com/apache/spark.git"
bottle :unneeded
conflicts_with "hive", :because => "both install `beeline` binaries"
conflicts_with "apache-spark", :because => "Both install the same binaries"
def install
rm_f Dir["bin/*.cmd"]
libexec.install Dir["*"]
bin.write_exec_script Dir["#{libexec}/bin/*"]
end
test do
pipe_output("#{bin}/spark-shell", "sc.parallelize(1 to 1000).count()")
end
end
| jimhe/homebrew-versions | apache-spark121.rb | Ruby | bsd-2-clause | 725 |
//----------------------------------*-C++-*----------------------------------//
/*!
* \file Alea/mc_solvers/Polynomial.hh
* \author Steven Hamilton
* \brief Polynomial class declaration.
*/
//---------------------------------------------------------------------------//
#ifndef Alea_mc_solvers_Polynomial_hh
#define Alea_mc_solvers_Polynomial_hh
#include "Teuchos_RCP.hpp"
#include "Teuchos_ParameterList.hpp"
#include "AnasaziTypes.hpp"
#include "AleaTypedefs.hh"
#include "PolynomialBasis.hh"
#include "harness/DBC.hh"
namespace alea
{
//---------------------------------------------------------------------------//
/*!
* \class Polynomial
* \brief Base class for polynomial types.
*/
//---------------------------------------------------------------------------//
class Polynomial
{
public:
// Access coefficient values.
virtual Teuchos::ArrayRCP<const SCALAR>
getCoeffs(const PolynomialBasis &target = PolynomialBasis("power")) const;
//! \brief Access PolynomialBasis object used internally.
virtual Teuchos::RCP<const PolynomialBasis> getNativeBasis() const
{
REQUIRE( !b_native_basis.is_null() );
return b_native_basis;
}
virtual ~Polynomial(){};
protected:
// Constructor, protected to avoid direct construction
Polynomial(Teuchos::RCP<const MATRIX> A,
Teuchos::RCP<Teuchos::ParameterList> pl);
enum Verbosity_Level { NONE, LOW, MEDIUM, HIGH };
// Original matrix
Teuchos::RCP<const MATRIX> b_A;
// ParameterLists
Teuchos::RCP<Teuchos::ParameterList> b_pl;
Teuchos::RCP<Teuchos::ParameterList> b_poly_pl;
// Polynomial order
int b_m;
// Polynomial coefficients
Teuchos::ArrayRCP<SCALAR> b_coeffs;
// Polynomial basis
Teuchos::RCP<PolynomialBasis> b_native_basis;
// Output level
Verbosity_Level b_verbosity;
};
}
#endif // Alea_mc_solvers_Polynomial_hh
| ORNL-CEES/Profugus | packages/Alea/mc_solvers/Polynomial.hh | C++ | bsd-2-clause | 1,923 |
/*
* Copyright (c) 2013, Dwijesh Bhageerutty
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package memory.node;
/**
* StateNode class.
*
* @author Dwijesh Bhageerutty, neerav789@gmail.com
* Date created: 1:25:51 PM, Nov 7, 2013
* Description: data structure to represent state node
*/
public class StateNode {
/** id */
private int id;
/** characteristics */
private String characteristics;
/**
* Constructor
* @param n - state number
* @param c - state characteristics
*/
public StateNode(int n, String c) {
this.id = n;
this.characteristics = c;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @return the characteristics
*/
public String getCharacteristics() {
return characteristics;
}
} | dbhage/qasp | src/memory/node/StateNode.java | Java | bsd-2-clause | 2,135 |
// Copyright 2013 The lime Authors.
// Use of this source code is governed by a 2-clause
// BSD-style license that can be found in the LICENSE file.
package main
import (
"fmt"
"image/color"
"runtime"
"strings"
"sync"
"time"
"gopkg.in/fsnotify.v1"
"gopkg.in/qml.v1"
"github.com/limetext/lime-backend/lib"
"github.com/limetext/lime-backend/lib/keys"
"github.com/limetext/lime-backend/lib/log"
"github.com/limetext/lime-backend/lib/render"
"github.com/limetext/sublime"
. "github.com/limetext/text"
"github.com/limetext/util"
)
var (
scheme *sublime.Theme
)
const (
batching_enabled = true
qmlMainFile = "qml/main.qml"
qmlViewFile = "qml/LimeView.qml"
// http://qt-project.org/doc/qt-5.1/qtcore/qt.html#KeyboardModifier-enum
shift_mod = 0x02000000
ctrl_mod = 0x04000000
alt_mod = 0x08000000
meta_mod = 0x10000000
keypad_mod = 0x20000000
)
// keeping track of frontend state
type qmlfrontend struct {
status_message string
lock sync.Mutex
windows map[*backend.Window]*frontendWindow
Console *frontendView
qmlDispatch chan qmlDispatch
}
// Used for batching qml.Changed calls
type qmlDispatch struct{ value, field interface{} }
func (t *qmlfrontend) Window(w *backend.Window) *frontendWindow {
return t.windows[w]
}
func (t *qmlfrontend) Show(v *backend.View, r Region) {
// TODO
}
func (t *qmlfrontend) VisibleRegion(v *backend.View) Region {
// TODO
return Region{0, v.Size()}
}
func (t *qmlfrontend) StatusMessage(msg string) {
t.lock.Lock()
defer t.lock.Unlock()
t.status_message = msg
}
func (t *qmlfrontend) ErrorMessage(msg string) {
log.Error(msg)
var q qmlDialog
q.Show(msg, "StandardIcon.Critical")
}
func (t *qmlfrontend) MessageDialog(msg string) {
var q qmlDialog
q.Show(msg, "StandardIcon.Information")
}
func (t *qmlfrontend) OkCancelDialog(msg, ok string) bool {
var q qmlDialog
return q.Show(msg, "StandardIcon.Question") == 1
}
func (t *qmlfrontend) scroll(b Buffer) {
t.Show(backend.GetEditor().Console(), Region{b.Size(), b.Size()})
}
func (t *qmlfrontend) Erased(changed_buffer Buffer, region_removed Region, data_removed []rune) {
t.scroll(changed_buffer)
}
func (t *qmlfrontend) Inserted(changed_buffer Buffer, region_inserted Region, data_inserted []rune) {
t.scroll(changed_buffer)
}
// Apparently calling qml.Changed also triggers a re-draw, meaning that typed text is at the
// mercy of how quick Qt happens to be rendering.
// Try setting batching_enabled = false to see the effects of non-batching
func (t *qmlfrontend) qmlBatchLoop() {
queue := make(map[qmlDispatch]bool)
t.qmlDispatch = make(chan qmlDispatch, 1000)
for {
if len(queue) > 0 {
select {
case <-time.After(time.Millisecond * 20):
// Nothing happened for 20 milliseconds, so dispatch all queued changes
for k := range queue {
qml.Changed(k.value, k.field)
}
queue = make(map[qmlDispatch]bool)
case d := <-t.qmlDispatch:
queue[d] = true
}
} else {
queue[<-t.qmlDispatch] = true
}
}
}
func (t *qmlfrontend) qmlChanged(value, field interface{}) {
if !batching_enabled {
qml.Changed(value, field)
} else {
t.qmlDispatch <- qmlDispatch{value, field}
}
}
func (t *qmlfrontend) DefaultBg() color.RGBA {
c := scheme.Spice(&render.ViewRegions{})
c.Background.A = 0xff
return color.RGBA(c.Background)
}
func (t *qmlfrontend) DefaultFg() color.RGBA {
c := scheme.Spice(&render.ViewRegions{})
c.Foreground.A = 0xff
return color.RGBA(c.Foreground)
}
// Called when a new view is opened
func (t *qmlfrontend) onNew(v *backend.View) {
fv := &frontendView{bv: v}
v.AddObserver(fv)
v.Settings().AddOnChange("blah", fv.onChange)
fv.Title.Text = v.FileName()
if len(fv.Title.Text) == 0 {
fv.Title.Text = "untitled"
}
w2 := t.windows[v.Window()]
w2.views = append(w2.views, fv)
if w2.window == nil {
return
}
w2.window.Call("addTab", "", fv)
}
// called when a view is closed
func (t *qmlfrontend) onClose(v *backend.View) {
w2 := t.windows[v.Window()]
for i := range w2.views {
if w2.views[i].bv == v {
w2.window.ObjectByName("tabs").Call("removeTab", i)
copy(w2.views[i:], w2.views[i+1:])
w2.views = w2.views[:len(w2.views)-1]
return
}
}
log.Error("Couldn't find closed view...")
}
// called when a view has loaded
func (t *qmlfrontend) onLoad(v *backend.View) {
w2 := t.windows[v.Window()]
i := 0
for i = range w2.views {
if w2.views[i].bv == v {
break
}
}
v2 := w2.views[i]
v2.Title.Text = v.FileName()
tabs := w2.window.ObjectByName("tabs")
tabs.Set("currentIndex", w2.ActiveViewIndex())
tab := tabs.Call("getTab", i).(qml.Object)
tab.Set("title", v2.Title.Text)
}
func (t *qmlfrontend) onSelectionModified(v *backend.View) {
w2 := t.windows[v.Window()]
i := 0
for i = range w2.views {
if w2.views[i].bv == v {
break
}
}
v2 := w2.views[i]
if v2.qv == nil {
return
}
v2.qv.Call("onSelectionModified")
}
// Launches the provided command in a new goroutine
// (to avoid locking up the GUI)
func (t *qmlfrontend) RunCommand(command string) {
t.RunCommandWithArgs(command, make(backend.Args))
}
func (t *qmlfrontend) RunCommandWithArgs(command string, args backend.Args) {
ed := backend.GetEditor()
go ed.RunCommand(command, args)
}
func (t *qmlfrontend) HandleInput(text string, keycode int, modifiers int) bool {
log.Debug("qmlfrontend.HandleInput: text=%v, key=%x, modifiers=%x", text, keycode, modifiers)
shift := false
alt := false
ctrl := false
super := false
if key, ok := lut[keycode]; ok {
ed := backend.GetEditor()
if (modifiers & shift_mod) != 0 {
shift = true
}
if (modifiers & alt_mod) != 0 {
alt = true
}
if (modifiers & ctrl_mod) != 0 {
if runtime.GOOS == "darwin" {
super = true
} else {
ctrl = true
}
}
if (modifiers & meta_mod) != 0 {
if runtime.GOOS == "darwin" {
ctrl = true
} else {
super = true
}
}
ed.HandleInput(keys.KeyPress{Text: text, Key: key, Shift: shift, Alt: alt, Ctrl: ctrl, Super: super})
return true
}
return false
}
// Quit closes all open windows to de-reference all qml objects
func (t *qmlfrontend) Quit() (err error) {
// todo: handle changed files that aren't saved.
for _, v := range t.windows {
if v.window != nil {
v.window.Hide()
v.window.Destroy()
v.window = nil
}
}
return
}
func (t *qmlfrontend) loop() (err error) {
backend.OnNew.Add(t.onNew)
backend.OnClose.Add(t.onClose)
backend.OnLoad.Add(t.onLoad)
backend.OnSelectionModified.Add(t.onSelectionModified)
ed := backend.GetEditor()
ed.SetFrontend(t)
ed.LogInput(false)
ed.LogCommands(false)
c := ed.Console()
t.Console = &frontendView{bv: c}
c.AddObserver(t.Console)
c.AddObserver(t)
var (
engine *qml.Engine
component qml.Object
// WaitGroup keeping track of open windows
wg sync.WaitGroup
)
ed.Init()
// create and setup a new engine, destroying
// the old one if one exists.
//
// This is needed to re-load qml files to get
// the new file contents from disc as otherwise
// the old file would still be what is referenced.
newEngine := func() (err error) {
if engine != nil {
log.Debug("calling destroy")
// TODO(.): calling this appears to make the editor *very* crash-prone, just let it leak for now
// engine.Destroy()
engine = nil
}
log.Debug("calling newEngine")
engine = qml.NewEngine()
engine.On("quit", t.Quit)
log.Debug("setvar frontend")
engine.Context().SetVar("frontend", t)
log.Debug("setvar editor")
engine.Context().SetVar("editor", backend.GetEditor())
log.Debug("loadfile")
component, err = engine.LoadFile(qmlMainFile)
if err != nil {
return err
}
return
}
if err := newEngine(); err != nil {
log.Error(err)
}
backend.OnNewWindow.Add(func(w *backend.Window) {
fw := &frontendWindow{bw: w}
t.windows[w] = fw
if component != nil {
fw.launch(&wg, component)
}
})
// TODO: should be done backend side
if sc, err := sublime.LoadTheme("../packages/TextMate-Themes/Monokai.tmTheme"); err != nil {
log.Error(err)
} else {
scheme = sc
}
w := ed.NewWindow()
w.NewFile()
ed.AddPackagesPath("shipped", "../packages")
ed.AddPackagesPath("default", "../packages/Default")
ed.AddPackagesPath("user", "../packages/User")
// TODO: setting syntax should be done automaticly in backend and after
// implementing this we could run Init in a go routine and remove the
// next two line
_ = ed.ActiveWindow().OpenFile("main.go", 0)
// v.SetSyntaxFile("../packages/go-tmbundle/Syntaxes/Go.tmLanguage")
defer func() {
fmt.Println(util.Prof)
}()
// The rest of code is related to livereloading qml files
// TODO: this doesnt work currently
watch, err := fsnotify.NewWatcher()
if err != nil {
log.Error("Unable to create file watcher: %s", err)
return
}
defer watch.Close()
watch.Add("qml")
defer watch.Remove("qml")
reloadRequested := false
waiting := false
go func() {
// reloadRequested = true
// t.Quit()
for {
time.Sleep(1 * time.Second) // quitting too frequently causes crashes
select {
case ev := <-watch.Events:
if strings.HasSuffix(ev.Name, ".qml") && ev.Op == fsnotify.Write && ev.Op != fsnotify.Chmod && !reloadRequested && waiting {
reloadRequested = true
t.Quit()
}
}
}
}()
for {
// Reset reload status
reloadRequested = false
log.Debug("Waiting for all windows to close")
// wg would be the WaitGroup all windows belong to, so first we wait for
// all windows to close.
waiting = true
wg.Wait()
waiting = false
log.Debug("All windows closed. reloadRequest: %v", reloadRequested)
// then we check if there's a reload request in the pipe
if !reloadRequested || len(t.windows) == 0 {
// This would be a genuine exit; all windows closed by the user
break
}
// *We* closed all windows because we want to reload freshly changed qml
// files.
for {
log.Debug("Calling newEngine")
if err := newEngine(); err != nil {
// Reset reload status
reloadRequested = false
log.Error(err)
for !reloadRequested {
// This loop allows us to re-try reloading
// if there was an error in the file this time,
// we just loop around again when we receive the next
// reload request (ie on the next save of the file).
time.Sleep(time.Second)
}
continue
}
log.Debug("break")
break
}
log.Debug("re-launching all windows")
// Succeeded loading the file, re-launch all windows
for _, v := range t.windows {
v.launch(&wg, component)
for i, bv := range v.Back().Views() {
t.onNew(bv)
t.onLoad(bv)
v.View(i)
}
}
}
return
}
| ricochet1k/lime-qml | main/frontend.go | GO | bsd-2-clause | 10,649 |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using DotLiquid;
using Microsoft.VisualBasic.FileIO;
namespace MarkdownSharp
{
using MarkdownSharp.Preprocessor;
public static class OffensiveWordFilterHelper
{
static readonly HashSet<string> OffensiveWordList = new HashSet<string>();
static readonly Regex WordSplitPattern = new Regex(@"\w+", RegexOptions.Compiled);
private static TransformationData _transformationData;
private static bool _thisIsPreview;
public static void Init(TransformationData transformationData, bool thisIsPreview)
{
var offensiveWordList = new FileInfo(Path.Combine(transformationData.CurrentFolderDetails.AbsoluteMarkdownPath, "Include", "NoRedist","OffensiveWordList", "wordlist.csv"));
if (!offensiveWordList.Exists)
{
return;
}
var parser = new TextFieldParser(offensiveWordList.FullName);
parser.HasFieldsEnclosedInQuotes = true;
parser.Delimiters = new string[] {","};
// for every line in file
while (!parser.EndOfData)
{
var cells = parser.ReadFields();
OffensiveWordList.Add(cells[0].ToLower());
}
_transformationData = transformationData;
_thisIsPreview = thisIsPreview;
}
public static string CheckAndGenerateInfos(string text, PreprocessedTextLocationMap map)
{
if (OffensiveWordList.Count == 0)
{
return text;
}
var changes = new List<PreprocessingTextChange>();
var output = WordSplitPattern.Replace(text, match => Evaluator(match, changes));
map.ApplyChanges(changes);
return output;
}
private static string Evaluator(Match match, List<PreprocessingTextChange> changes)
{
var word = match.Value;
if (OffensiveWordList.Contains(word.ToLower()))
{
var errorId = _transformationData.ErrorList.Count;
_transformationData.ErrorList.Add(Markdown.GenerateError(Language.Message("FoundOffensiveWord", word),
MessageClass.Info, word,
errorId,
_transformationData));
if (_thisIsPreview)
{
var output = Templates.ErrorHighlight.Render(Hash.FromAnonymousObject(
new
{
errorId = errorId,
errorText = word
}));
changes.Add(new PreprocessingTextChange(match.Index, match.Length, output.Length));
return output;
}
}
return word;
}
}
} | PopCap/GameIdea | Engine/Source/Programs/UnrealDocTool/UnrealDocTool/MarkdownSharp/OffensiveWordFilterHelper.cs | C# | bsd-2-clause | 3,212 |
# Copyright 2012-2017 Luc Saffre
# License: BSD (see file COPYING for details)
from __future__ import unicode_literals
from __future__ import print_function
from lino.api import dd, rt, _
# from etgen.html import E
from .mixins import VatDocument
from lino_xl.lib.ledger.ui import PartnerVouchers, ByJournal, PrintableByJournal
from lino_xl.lib.ledger.choicelists import TradeTypes
from lino_xl.lib.ledger.choicelists import VoucherTypes
from lino_xl.lib.ledger.roles import LedgerUser, LedgerStaff
from lino_xl.lib.ledger.mixins import ItemsByVoucher
from lino_xl.lib.ledger.mixins import VouchersByPartnerBase
from .choicelists import VatRegimes
# class VatRules(dd.Table):
# model = 'vat.VatRule'
# required_roles = dd.login_required(LedgerStaff)
# column_names = "seqno vat_area trade_type vat_class vat_regime \
# #start_date #end_date rate can_edit \
# vat_account vat_returnable vat_returnable_account *"
# hide_sums = True
# auto_fit_column_widths = True
# order_by = ['seqno']
class InvoiceDetail(dd.DetailLayout):
main = "general ledger"
totals = """
total_base
total_vat
total_incl
workflow_buttons
"""
general = dd.Panel("""
id entry_date partner user
due_date your_ref vat_regime #item_vat
ItemsByInvoice:60 totals:20
""", label=_("General"))
ledger = dd.Panel("""
journal accounting_period number narration
ledger.MovementsByVoucher
""", label=_("Ledger"))
class Invoices(PartnerVouchers):
required_roles = dd.login_required(LedgerUser)
model = 'vat.VatAccountInvoice'
order_by = ["-id"]
column_names = "entry_date id number_with_year partner total_incl user *"
detail_layout = InvoiceDetail()
insert_layout = """
journal partner
entry_date total_incl
"""
# start_at_bottom = True
class InvoicesByJournal(Invoices, ByJournal):
params_layout = "partner state start_period end_period user"
column_names = "number_with_year voucher_date due_date " \
"partner " \
"total_incl " \
"total_base total_vat user workflow_buttons *"
#~ "ledger_remark:10 " \
insert_layout = """
partner
entry_date total_incl
"""
class PrintableInvoicesByJournal(PrintableByJournal, Invoices):
label = _("Purchase journal")
VoucherTypes.add_item_lazy(InvoicesByJournal)
class ItemsByInvoice(ItemsByVoucher):
model = 'vat.InvoiceItem'
display_mode = 'grid'
column_names = "account title vat_class total_base total_vat total_incl"
class VouchersByPartner(VouchersByPartnerBase):
label = _("VAT vouchers")
column_names = "entry_date voucher total_incl total_base total_vat"
_voucher_base = VatDocument
@dd.virtualfield('vat.VatAccountInvoice.total_incl')
def total_incl(self, row, ar):
return row.total_incl
@dd.virtualfield('vat.VatAccountInvoice.total_base')
def total_base(self, row, ar):
return row.total_base
@dd.virtualfield('vat.VatAccountInvoice.total_vat')
def total_vat(self, row, ar):
return row.total_vat
class IntracomInvoices(PartnerVouchers):
_trade_type = None
editable = False
model = VatDocument
column_names = 'detail_pointer partner partner__vat_id vat_regime total_base total_vat total_incl'
# order_by = ['entry_date', 'partner']
# order_by = ['entry_date', 'id']
# order_by = ['entry_date', 'number']
order_by = ['number']
hidden_elements = frozenset(
"""entry_date journal__trade_type journal number
journal__trade_type state user""".split())
@classmethod
def get_request_queryset(cls, ar, **kwargs):
fkw = dict()
if cls._trade_type is not None:
fkw.update(journal__trade_type=cls._trade_type)
regimes = set([r for r in VatRegimes.get_list_items()
if r.name.startswith('intracom')])
# (VatRegimes.intracom, VatRegimes.intracom_supp)
fkw.update(vat_regime__in=regimes)
qs = super(IntracomInvoices, cls).get_request_queryset(ar, **fkw)
# raise Exception("20170905 {}".format(qs.query))
return qs
dd.update_field(
IntracomInvoices, 'detail_pointer', verbose_name=_("Invoice"))
class IntracomSales(IntracomInvoices):
_trade_type = TradeTypes.sales
label = _("Intra-Community sales")
class IntracomPurchases(IntracomInvoices):
_trade_type = TradeTypes.purchases
label = _("Intra-Community purchases")
| khchine5/xl | lino_xl/lib/vat/desktop.py | Python | bsd-2-clause | 4,520 |
# Copyright 2009-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from distutils.command.build_py import build_py
from distutils.command.build_scripts import build_scripts
from distutils.command.install_scripts import install_scripts
from distutils.command.sdist import sdist
import glob
import os.path
import sys
from setuptools import find_packages, setup
from euca2ools import __version__
REQUIREMENTS = ['lxml',
'PyYAML',
'requestbuilder>=0.4',
'requests',
'six>=1.4']
if sys.version_info < (2, 7):
REQUIREMENTS.append('argparse')
# Cheap hack: install symlinks separately from regular files.
# cmd.copy_tree accepts a preserve_symlinks option, but when we call
# ``setup.py install'' more than once the method fails when it encounters
# symlinks that are already there.
class build_scripts_except_symlinks(build_scripts):
'''Like build_scripts, but ignoring symlinks'''
def copy_scripts(self):
orig_scripts = self.scripts
self.scripts = [script for script in self.scripts
if not os.path.islink(script)]
build_scripts.copy_scripts(self)
self.scripts = orig_scripts
class install_scripts_and_symlinks(install_scripts):
'''Like install_scripts, but also replicating nonexistent symlinks'''
def run(self):
install_scripts.run(self)
# Replicate symlinks if they don't exist
for script in self.distribution.scripts:
if os.path.islink(script):
target = os.readlink(script)
newlink = os.path.join(self.install_dir,
os.path.basename(script))
if not os.path.exists(newlink):
os.symlink(target, newlink)
class build_py_with_git_version(build_py):
'''Like build_py, but also hardcoding the version in __init__.__version__
so it's consistent even outside of the source tree'''
def build_module(self, module, module_file, package):
build_py.build_module(self, module, module_file, package)
print module, module_file, package
if module == '__init__' and '.' not in package:
version_line = "__version__ = '{0}'\n".format(__version__)
old_init_name = self.get_module_outfile(self.build_lib, (package,),
module)
new_init_name = old_init_name + '.new'
with open(new_init_name, 'w') as new_init:
with open(old_init_name) as old_init:
for line in old_init:
if line.startswith('__version__ ='):
new_init.write(version_line)
else:
new_init.write(line)
new_init.flush()
os.rename(new_init_name, old_init_name)
class sdist_with_git_version(sdist):
'''Like sdist, but also hardcoding the version in __init__.__version__ so
it's consistent even outside of the source tree'''
def make_release_tree(self, base_dir, files):
sdist.make_release_tree(self, base_dir, files)
version_line = "__version__ = '{0}'\n".format(__version__)
old_init_name = os.path.join(base_dir, 'euca2ools/__init__.py')
new_init_name = old_init_name + '.new'
with open(new_init_name, 'w') as new_init:
with open(old_init_name) as old_init:
for line in old_init:
if line.startswith('__version__ ='):
new_init.write(version_line)
else:
new_init.write(line)
new_init.flush()
os.rename(new_init_name, old_init_name)
setup(name="euca2ools",
version=__version__,
description="Eucalyptus Command Line Tools",
long_description="Eucalyptus Command Line Tools",
author="Eucalyptus Systems, Inc.",
author_email="support@eucalyptus.com",
url="http://www.eucalyptus.com",
scripts=sum((glob.glob('bin/euare-*'),
glob.glob('bin/euca-*'),
glob.glob('bin/euform-*'),
glob.glob('bin/euimage-*'),
glob.glob('bin/eulb-*'),
glob.glob('bin/euscale-*'),
glob.glob('bin/euwatch-*')),
[]),
data_files=[('share/man/man1', glob.glob('man/*.1')),
('share/man/man5', glob.glob('man/*.5')),
('share/man/man7', glob.glob('man/*.7'))],
packages=find_packages(),
install_requires=REQUIREMENTS,
license='BSD (Simplified)',
platforms='Posix; MacOS X',
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Simplified BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet'],
cmdclass={'build_py': build_py_with_git_version,
'build_scripts': build_scripts_except_symlinks,
'install_scripts': install_scripts_and_symlinks,
'sdist': sdist_with_git_version})
| nagyistoce/euca2ools | setup.py | Python | bsd-2-clause | 6,806 |
package org.newdawn.slick.svg.inkscape;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.newdawn.slick.geom.Polygon;
import org.newdawn.slick.geom.Shape;
import org.newdawn.slick.geom.Transform;
import org.newdawn.slick.svg.Diagram;
import org.newdawn.slick.svg.Figure;
import org.newdawn.slick.svg.Loader;
import org.newdawn.slick.svg.NonGeometricData;
import org.newdawn.slick.svg.ParsingException;
import org.w3c.dom.Element;
/**
* A processor for the <polygon> and <path> elements marked as not an arc.
*
* @author kevin
*/
public class PolygonProcessor implements ElementProcessor {
/**
* Process the points in a polygon definition
*
* @param poly The polygon being built
* @param element The XML element being read
* @param tokens The tokens representing the path
* @return The number of points found
* @throws ParsingException Indicates an invalid token in the path
*/
private static int processPoly(Polygon poly, Element element, StringTokenizer tokens) throws ParsingException {
int count = 0;
ArrayList pts = new ArrayList();
boolean moved = false;
while (tokens.hasMoreTokens()) {
String nextToken = tokens.nextToken();
if (nextToken.equals("L")) {
continue;
}
if (nextToken.equals("z")) {
break;
}
if (nextToken.equals("M")) {
if (!moved) {
moved = true;
continue;
}
return 0;
}
if (nextToken.equals("C")) {
return 0;
}
String tokenX = nextToken;
String tokenY = tokens.nextToken();
try {
float x = Float.parseFloat(tokenX);
float y = Float.parseFloat(tokenY);
poly.addPoint(x,y);
count++;
} catch (NumberFormatException e) {
throw new ParsingException(element.getAttribute("id"), "Invalid token in points list", e);
}
}
return count;
}
/**
* @see org.newdawn.slick.svg.inkscape.ElementProcessor#process(org.newdawn.slick.svg.Loader, org.w3c.dom.Element, org.newdawn.slick.svg.Diagram, org.newdawn.slick.geom.Transform)
*/
public void process(Loader loader, Element element, Diagram diagram, Transform t) throws ParsingException {
Transform transform = Util.getTransform(element);
transform = new Transform(transform, t);
String points = element.getAttribute("points");
if (element.getNodeName().equals("path")) {
points = element.getAttribute("d");
}
StringTokenizer tokens = new StringTokenizer(points, ", ");
Polygon poly = new Polygon();
int count = processPoly(poly, element, tokens);
NonGeometricData data = Util.getNonGeometricData(element);
if (count > 3) {
Shape shape = poly.transform(transform);
diagram.addFigure(new Figure(Figure.POLYGON, shape, data, transform));
}
}
/**
* @see org.newdawn.slick.svg.inkscape.ElementProcessor#handles(org.w3c.dom.Element)
*/
public boolean handles(Element element) {
if (element.getNodeName().equals("polygon")) {
return true;
}
if (element.getNodeName().equals("path")) {
if (!"arc".equals(element.getAttributeNS(Util.SODIPODI, "type"))) {
return true;
}
}
return false;
}
}
| SenshiSentou/SourceFight | slick_dev/tags/Slick0.19/src/org/newdawn/slick/svg/inkscape/PolygonProcessor.java | Java | bsd-2-clause | 3,230 |
/*
Copyright 2005-2012 Intel Corporation. All Rights Reserved.
The source code contained or described herein and all documents related
to the source code ("Material") are owned by Intel Corporation or its
suppliers or licensors. Title to the Material remains with Intel
Corporation or its suppliers and licensors. The Material is protected
by worldwide copyright laws and treaty provisions. No part of the
Material may be used, copied, reproduced, modified, published, uploaded,
posted, transmitted, distributed, or disclosed in any way without
Intel's prior express written permission.
No license under any patent, copyright, trade secret or other
intellectual property right is granted to or conferred upon you by
disclosure or delivery of the Materials, either expressly, by
implication, inducement, estoppel or otherwise. Any license under such
intellectual property rights must be express and approved by Intel in
writing.
*/
#if __TBB_CPF_BUILD
// undefine __TBB_CPF_BUILD to simulate user's setup
#undef __TBB_CPF_BUILD
#define TBB_PREVIEW_TASK_ARENA 1
#include "tbb/task_arena.h"
#include "tbb/task_scheduler_observer.h"
#include "tbb/task_scheduler_init.h"
#include <cstdlib>
#include "harness_assert.h"
#include <cstdio>
#include "harness.h"
#include "harness_barrier.h"
#include "harness_concurrency_tracker.h"
#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"
#include "tbb/enumerable_thread_specific.h"
#if _MSC_VER
// plays around __TBB_NO_IMPLICIT_LINKAGE. __TBB_LIB_NAME should be defined (in makefiles)
#pragma comment(lib, __TBB_STRING(__TBB_LIB_NAME))
#endif
typedef tbb::blocked_range<int> Range;
class ConcurrencyTrackingBody {
public:
void operator() ( const Range& ) const {
Harness::ConcurrencyTracker ct;
for ( volatile int i = 0; i < 1000000; ++i )
;
}
};
Harness::SpinBarrier our_barrier;
static tbb::enumerable_thread_specific<int> local_id, old_id;
void ResetTLS() {
local_id.clear();
old_id.clear();
}
class ArenaObserver : public tbb::task_scheduler_observer {
int myId;
tbb::atomic<int> myTrappedSlot;
/*override*/
void on_scheduler_entry( bool is_worker ) {
REMARK("a %s #%p is entering arena %d from %d\n", is_worker?"worker":"master", &local_id.local(), myId, local_id.local());
ASSERT(!old_id.local(), "double-call to on_scheduler_entry");
old_id.local() = local_id.local();
ASSERT(old_id.local() != myId, "double-entry to the same arena");
local_id.local() = myId;
if(is_worker) ASSERT(tbb::task_arena::current_slot()>0, NULL);
else ASSERT(tbb::task_arena::current_slot()==0, NULL);
}
/*override*/
void on_scheduler_exit( bool is_worker ) {
REMARK("a %s #%p is leaving arena %d to %d\n", is_worker?"worker":"master", &local_id.local(), myId, old_id.local());
//ASSERT(old_id.local(), "call to on_scheduler_exit without prior entry");
ASSERT(local_id.local() == myId, "nesting of arenas is broken");
local_id.local() = old_id.local();
old_id.local() = 0;
}
/*override*/
bool on_scheduler_leaving() {
return tbb::task_arena::current_slot() >= myTrappedSlot;
}
public:
ArenaObserver(tbb::task_arena &a, int id, int trap = 0) : tbb::task_scheduler_observer(a) {
observe(true);
ASSERT(id, NULL);
myId = id;
myTrappedSlot = trap;
}
~ArenaObserver () {
ASSERT(!old_id.local(), "inconsistent observer state");
}
};
struct AsynchronousWork : NoAssign {
Harness::SpinBarrier &my_barrier;
bool my_is_blocking;
AsynchronousWork(Harness::SpinBarrier &a_barrier, bool blocking = true)
: my_barrier(a_barrier), my_is_blocking(blocking) {}
void operator()() const {
ASSERT(local_id.local() != 0, "not in explicit arena");
tbb::parallel_for(Range(0,35), ConcurrencyTrackingBody());
if(my_is_blocking) my_barrier.timed_wait(10); // must be asynchronous to master thread
else my_barrier.signal_nowait();
}
};
void TestConcurrentArenas(int p) {
//Harness::ConcurrencyTracker::Reset();
tbb::task_arena a1(1);
ArenaObserver o1(a1, p*2+1);
tbb::task_arena a2(2);
ArenaObserver o2(a2, p*2+2);
Harness::SpinBarrier barrier(2);
AsynchronousWork work(barrier);
a1.enqueue(work); // put async work
barrier.timed_wait(10);
a2.enqueue(work); // another work
a2.execute(work); // my_barrier.timed_wait(10) inside
a1.wait_until_empty();
a2.wait_until_empty();
}
class MultipleMastersBody : NoAssign {
tbb::task_arena &my_a;
Harness::SpinBarrier &my_b;
public:
MultipleMastersBody(tbb::task_arena &a, Harness::SpinBarrier &b)
: my_a(a), my_b(b) {}
void operator()(int) const {
my_a.execute(AsynchronousWork(my_b, /*blocking=*/false));
my_a.wait_until_empty();
}
};
void TestMultipleMasters(int p) {
REMARK("multiple masters\n");
tbb::task_arena a(1);
ArenaObserver o(a, 1);
Harness::SpinBarrier barrier(p+1);
NativeParallelFor( p, MultipleMastersBody(a, barrier) );
a.wait_until_empty();
barrier.timed_wait(10);
}
int TestMain () {
// TODO: a workaround for temporary p-1 issue in market
tbb::task_scheduler_init init_market_p_plus_one(MaxThread+1);
for( int p=MinThread; p<=MaxThread; ++p ) {
REMARK("testing with %d threads\n", p );
NativeParallelFor( p, &TestConcurrentArenas );
ResetTLS();
TestMultipleMasters( p );
ResetTLS();
}
return Harness::Done;
}
#else // __TBB_CPF_BUILD
#include "harness.h"
int TestMain () {
return Harness::Skipped;
}
#endif
| PopCap/GameIdea | Engine/Source/ThirdParty/IntelTBB/IntelTBB-4.0/src/test/test_task_arena.cpp | C++ | bsd-2-clause | 5,747 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Hutte documentation build configuration file, created by
# sphinx-quickstart on Mon Jul 27 23:08:58 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.todo',
'rubydomain'
]
primary_domain = 'rb'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Hutte'
copyright = '2015, Bastien Léonard'
author = 'Bastien Léonard'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
highlight_language = 'ruby'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'Huttedoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Hutte.tex', 'Hutte Documentation',
'Bastien Léonard', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'hutte', 'Hutte Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Hutte', 'Hutte Documentation',
author, 'Hutte', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The basename for the epub file. It defaults to the project name.
#epub_basename = project
# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
#epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'
# Fix unsupported image types using the Pillow.
#epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'
# If false, no index is generated.
#epub_use_index = True
| bastienleonard/hutte | doc/sphinx/conf.py | Python | bsd-2-clause | 11,279 |
//------------------------------------------------------------------------------
// <copyright file="XmlDocCommentHighPriorityClassifierClassificationDefinition.cs" company="Company">
// Copyright (c) Company. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace XmlDocCommentHighPriorityClassifier
{
/// <summary>
/// Classification type definition export for XmlDocCommentHighPriorityClassifier
/// </summary>
internal static class XmlDocCommentHighPriorityClassifierClassificationDefinition
{
// This disables "The field is never used" compiler's warning. Justification: the field is used by MEF.
#pragma warning disable 169
/// <summary>
/// Defines the "XmlDocCommentHighPriorityClassifier" classification type.
/// </summary>
[Export(typeof(ClassificationTypeDefinition))]
[Name("XmlDocCommentHighPriorityClassifier")]
private static ClassificationTypeDefinition typeDefinition;
#pragma warning restore 169
}
}
| nickhalvorsen/VSXMLDocCommentClassifier | XmlDocCommentHighPriorityClassifier/XmlDocCommentHighPriorityClassifierClassificationDefinition.cs | C# | bsd-2-clause | 1,215 |
package repos
import (
"strings"
"github.com/cbroglie/mustache"
"github.com/khades/servbot/models"
"gopkg.in/mgo.v2/bson"
)
var templateCollection = "templates"
func SetChannelTemplateAlias(user *string, userID *string, channelID *string, commandName *string, aliasTo *string) {
aliasStripped := strings.ToLower(strings.Join(strings.Fields(*aliasTo), ""))
commandNameStripped := strings.ToLower(strings.Join(strings.Fields(*commandName), ""))
result, error := GetChannelTemplate(channelID, &aliasStripped)
aliasTemplate := models.TemplateInfoBody{}
if error == nil {
aliasTemplate = result.TemplateInfoBody
}
putChannelTemplate(user, userID, channelID, &commandNameStripped, &aliasTemplate)
PushCommandsForChannel(channelID)
}
func SetChannelTemplate(user *string, userID *string, channelID *string, commandName *string, template *models.TemplateInfoBody) error {
commandNameStripped := strings.ToLower(strings.Join(strings.Fields(*commandName), ""))
if template.Template == "" {
_, templateError := mustache.ParseString(template.Template)
if templateError != nil {
return templateError
}
}
putChannelTemplate(user, userID, channelID, &commandNameStripped, template)
PushCommandsForChannel(channelID)
return nil
}
func GetChannelTemplate(channelID *string, commandName *string) (models.TemplateInfo, error) {
var result models.TemplateInfo
error := Db.C(templateCollection).Find(models.TemplateSelector{ChannelID: *channelID, CommandName: *commandName}).One(&result)
return result, error
}
// GetChannelTemplateWithHistory gets specific paginated
func GetChannelTemplateWithHistory(channelID *string, commandName *string) (*models.TemplateInfoWithHistory, error) {
var result models.TemplateInfoWithHistory
error := Db.C(templateCollection).Find(models.TemplateSelector{ChannelID: *channelID, CommandName: *commandName}).One(&result)
return &result, error
}
func GetChannelTemplates(channelID *string) (*[]models.TemplateInfo, error) {
var result []models.TemplateInfo
error := Db.C(templateCollection).Find(models.ChannelSelector{ChannelID: *channelID}).All(&result)
return &result, error
}
func GetChannelActiveTemplates(channelID *string) (*[]models.TemplateInfo, error) {
var result []models.TemplateInfo
error := Db.C(templateCollection).Find(bson.M{"channelid": *channelID, "template": bson.M{"$ne": ""}}).All(&result)
return &result, error
}
func GetChannelAliasedTemplates(channelID *string, aliasTo *string) ([]models.TemplateInfo, error) {
var result []models.TemplateInfo
error := Db.C(templateCollection).Find(models.TemplateAliasSelector{ChannelID: *channelID, AliasTo: *aliasTo}).All(&result)
return result, error
}
| khades/servbot | repos/template.go | GO | bsd-2-clause | 2,685 |
from optparse import make_option
import os
import shutil
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import MySQLdb
from blog.models import Blog, Post, Asset
class Command(BaseCommand):
help = 'Import blog posts from Movable Type'
option_list = BaseCommand.option_list + (
make_option('-d',
dest='database',
help='The MT database name'),
make_option('-u',
dest='user',
help='The MT database user'),
make_option('-p',
dest='password',
help='The MT database password'),
make_option('-r',
dest='root',
help='The MT root directory (for copying image files)'),
make_option('-i',
dest='src_blog_id',
help='The MT blog ID to copy'),
make_option('-b',
dest='dst_blog_id',
help='The Django destionation blog id. Should exist.'))
def handle(self, *args, **options):
blog = Blog.objects.get(id=options['dst_blog_id'])
blog.ensure_assets_directory()
db = MySQLdb.Connect(db=options['database'], user=options['user'], passwd=options['password'])
entry_cursor = db.cursor()
entry_cursor.execute('''
select e.entry_id, e.entry_basename, e.entry_modified_on, e.entry_title, e.entry_text,
a.author_basename, a.author_email, a.author_nickname
from mt_entry as e, mt_author as a
where e.entry_blog_id = %s
and e.entry_author_id = a.author_id''' % options['src_blog_id'])
print list(entry_cursor)
for row in list(entry_cursor):
row = dict(zip(['id', 'basename', 'modified_on', 'title', 'body', 'username', 'email', 'first_name'], row))
print "create user %s" % row['username']
# Ensure the user exists.
try:
user = User.objects.get(username=row['username'])
except User.DoesNotExist:
user = User.objects.create_user(row['username'], row['email'])
user.first_name = row['first_name']
user.save()
# Create the blog post.
self.stdout.write('Create "%s"' % row['title'])
try:
post = Post.objects.get(blog=blog, user=user, slug=row['basename'])
except Post.DoesNotExist:
post = Post.objects.create(blog=blog,
user=user,
title=row['title'] or '<No Title>',
slug=row['basename'][:50],
pub_date=row['modified_on'],
body=row['body'])
# Create the files.
asset_cursor = db.cursor()
asset_cursor.execute('''select a.asset_file_path, a.asset_class
from mt_asset as a, mt_objectasset as oa
where oa.objectasset_object_id = %s
and oa.objectasset_blog_id = %s
and a.asset_id = oa.objectasset_asset_id''' % (row['id'], options['src_blog_id']))
for i, asset in enumerate(list(asset_cursor)):
position = i + 1
asset = dict(zip(['file_path', 'asset_class'], asset))
src_file = asset['file_path'].replace(r'%r', options['root'])
print src_file
dst_file = os.path.join(blog.assets_directory, os.path.basename(asset['file_path']))
if os.path.exists(src_file):
print src_file, "->", dst_file
shutil.copyfile(src_file, dst_file)
Asset.objects.create(post=post,
file_name=os.path.basename(dst_file),
type=asset['asset_class'],
description='',
position=position)
| nodebox/workshops | blog/management/commands/import_mt.py | Python | bsd-2-clause | 4,262 |
package org.laladev.moneyjinn.model.capitalsource;
public enum CapitalsourceState {
NON_CACHE,
CACHE;
}
| OlliL/moneyjinn-server | moneyjinn-model/src/main/java/org/laladev/moneyjinn/model/capitalsource/CapitalsourceState.java | Java | bsd-2-clause | 107 |
$:.unshift File.expand_path("../../lib", __FILE__)
require "minitest/autorun"
require "minitest/spec"
require "matchrb/global"
describe "match" do
describe "when the pattern is a class" do
it "matches the kind of the object" do
Foo = Class.new
foo = Foo.new
result = match foo,
Foo => "foo is Foo"
result.must_equal "foo is Foo"
end
end
describe "when the pattern is a Regexp" do
it "matches the regex against the object" do
result = match "this is a string",
/this is not a string/ => false,
/this is a.*/ => true
result.must_equal true
end
end
describe "when no pattern is matched" do
it "returns nil" do
result = match "this is a string",
Integer => false,
Class => true
result.must_equal nil
end
end
describe "when the action is an object" do
it "returns that object" do
someobject = Object.new
result = match 1,
Integer => someobject
result.object_id.must_equal someobject.object_id
end
end
describe "when the action is a :to_proc'able object" do
it "returns the result of calling that object" do
Identity = Class.new do
def initialize(number)
@number = number
end
def to_proc
-> { @number }
end
end
result = match 1,
Integer => Identity.new(10)
result.must_equal 10
end
end
describe "when an `otherwise' pattern is given" do
it "matches that pattern if no other is matched before" do
result = match "this is a string",
666 => true,
/the quick brown fox/ => false,
otherwise => "none matched"
result.must_equal "none matched"
end
it "matches more specific patterns before that" do
result = match "this is a string",
String => true,
Class => false,
otherwise => "none matched"
result.must_equal true
end
end
it "matches any predicate if it returns true for that object" do
Twice = Class.new do
def self.===(object)
object % 2 == 0
end
end
number = 21 * 2
result = match number,
Twice => "it's twice something"
result.must_equal "it's twice something"
end
describe "when passed an 'extractor'" do
it "it calls the action with the extracted value" do
Multiple = Class.new do
def self.of(number)
new(number)
end
def initialize(number)
@number = number
end
def ===(object)
object % @number == 0 ? object/@number : false
end
end
number = 99
result = match number,
Multiple.of(3) => ->(value) { value }
result.must_equal 33
end
end
describe "when used as control flow" do
it "returns from outer context when using `proc'" do
def foobar
match 1,
Integer => proc { return 666 }
10
end
foobar.must_equal 666
end
end
end
| dlisboa/matchrb | spec/match_spec.rb | Ruby | bsd-2-clause | 3,033 |
#include "stdafx.h"
#include "DDE_Stopper.h"
#include "DDE_StopperDlg.h"
#include ".\dde_stopperdlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
UINT CDDE_StopperDlg::WM_TRAYRESTARTNOTIFY = (WM_USER + 1002);
UINT CDDE_StopperDlg::WM_TRAYICONNOTIFY = (WM_USER + 1003);
UINT CDDE_StopperDlg::WM_ADDLOG = (WM_USER + 1004);
CDDE_StopperDlg::CDDE_StopperDlg(CWnd* pParent /*=NULL*/)
: CDialog(CDDE_StopperDlg::IDD, pParent)
{
m_hHook = NULL;
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_hIconAct = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_hIconIna = AfxGetApp()->LoadIcon(IDR_MAINFRAME1);
WM_TRAYRESTARTNOTIFY = RegisterWindowMessage(TEXT("TaskbarCreated"));
WM_TRAYICONNOTIFY = RegisterWindowMessage(TEXT("CloseWndTrayNotify"));
WM_ADDLOG = RegisterWindowMessage(TEXT("DDEStopperAddLog"));
m_hModule = ::LoadLibrary(_T("DDE_StopperDll.dll"));
m_SetHook = (HHOOK (CALLBACK *)(HWND))::GetProcAddress(m_hModule, "SetHook");
m_UnHook = (void (CALLBACK *)())::GetProcAddress(m_hModule, "UnHook");
}
CDDE_StopperDlg::~CDDE_StopperDlg()
{
m_UnHook();
m_hHook = NULL;
FreeLibrary(m_hModule);
}
void CDDE_StopperDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CDDE_StopperDlg, CDialog)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_REGISTERED_MESSAGE(WM_TRAYRESTARTNOTIFY, OnTrayRestartNotify)
ON_REGISTERED_MESSAGE(WM_TRAYICONNOTIFY, OnTrayIconNotify)
ON_REGISTERED_MESSAGE(WM_ADDLOG, OnAddLog)
ON_WM_TIMER()
ON_WM_SIZE()
END_MESSAGE_MAP()
// CDDE_StopperDlg bZ[W nh
BOOL CDDE_StopperDlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
m_hHook = m_SetHook( GetSafeHwnd() );
m_stNotifyIcon.cbSize = sizeof(NOTIFYICONDATA);
m_stNotifyIcon.uID = 0;
m_stNotifyIcon.hWnd = m_hWnd;
m_stNotifyIcon.hIcon = m_hIcon;
m_stNotifyIcon.uCallbackMessage = WM_TRAYICONNOTIFY;
lstrcpy( m_stNotifyIcon.szTip, AfxGetApp()->m_pszAppName );
AddTaskbarIcons();
SetTimer(127, 3000, NULL);
return TRUE;
}
HCURSOR CDDE_StopperDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CDDE_StopperDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this);
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
void CDDE_StopperDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
if (IsWindow(GetSafeHwnd()) &&
IsWindow(GetDlgItem(IDC_EDITLOG)->GetSafeHwnd()))
{
GetDlgItem(IDC_EDITLOG)->MoveWindow(0,0,cx,cy);
}
}
afx_msg LRESULT CDDE_StopperDlg::OnAddLog(WPARAM wParam, LPARAM lParam)
{
CWnd *log = GetDlgItem(IDC_EDITLOG);
log->SendMessage(
EM_SETSEL,
log->SendMessage(WM_GETTEXTLENGTH, 0, 0),
-1);
log->SendMessage(
EM_REPLACESEL,
0,
lParam);
m_stNotifyIcon.uFlags = NIF_ICON;
m_stNotifyIcon.hIcon = m_hIconAct;
::Shell_NotifyIcon( NIM_MODIFY, &m_stNotifyIcon );
ShowWindow(SW_SHOW);
return 0;
}
//^XNgCR[obN
afx_msg LRESULT CDDE_StopperDlg::OnTrayIconNotify(WPARAM wParam, LPARAM lParam)
{
POINT point;
::GetCursorPos(&point);
switch(lParam)
{
case WM_RBUTTONDOWN:
SetForegroundWindow();
m_stNotifyIcon.uFlags = NIF_ICON;
m_stNotifyIcon.hIcon = m_hIconAct;
::Shell_NotifyIcon( NIM_MODIFY, &m_stNotifyIcon );
m_CursorTrayIcon = TRUE;
ShowWindow(SW_SHOW);
PostMessage(WM_NULL);
break;
case WM_LBUTTONDOWN:
SetForegroundWindow();
m_stNotifyIcon.uFlags = NIF_ICON;
m_stNotifyIcon.hIcon = m_hIconAct;
::Shell_NotifyIcon( NIM_MODIFY, &m_stNotifyIcon );
m_CursorTrayIcon = TRUE;
PostMessage(WM_NULL);
break;
}
return 0L;
}
void CDDE_StopperDlg::DelTaskbarIcons()
{
m_stNotifyIcon.uFlags = 0;
::Shell_NotifyIcon(NIM_DELETE, &m_stNotifyIcon);
}
void CDDE_StopperDlg::AddTaskbarIcons()
{
m_stNotifyIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
::Shell_NotifyIcon( NIM_ADD, &m_stNotifyIcon );
}
LRESULT CDDE_StopperDlg::OnTrayRestartNotify(WPARAM wParam, LPARAM lParam)
{
AddTaskbarIcons();
return 0L;
}
//ftHgñ\¦
void CDDE_StopperDlg::OnTimer(UINT nIDEvent)
{
if(nIDEvent == 127)
{
CWnd *log = GetDlgItem(IDC_EDITLOG);
log->SendMessage(
EM_SETSEL,
0,
log->SendMessage(WM_GETTEXTLENGTH, 0, 0));
log->SendMessage(
EM_REPLACESEL,
0,
(LPARAM)_T(""));
m_stNotifyIcon.uFlags = NIF_ICON;
m_stNotifyIcon.hIcon = m_hIconIna;
::Shell_NotifyIcon( NIM_MODIFY, &m_stNotifyIcon );
ShowWindow(SW_HIDE);
}
CDialog::OnTimer(nIDEvent);
}
| katakk/DDE-stopper | src/DDE_StopperDlg.cpp | C++ | bsd-2-clause | 4,997 |
class Webdis < Formula
desc "Redis HTTP interface with JSON output"
homepage "https://webd.is/"
url "https://github.com/nicolasff/webdis/archive/0.1.15.tar.gz"
sha256 "6ef2ce437240b792442594968f149b5ddc6b4a8a0abd58f7b19374387373aed1"
license "BSD-2-Clause"
bottle do
sha256 cellar: :any, arm64_big_sur: "9bad540c5e1122e2b6f94bfc8401cb3e4ec5a87beb7f85b67637d8adf0f876e4"
sha256 cellar: :any, big_sur: "aa7ce60364d343a7c643c2d667ef6a447a0c0d062d30d3ad25b7d4d141f569ff"
sha256 cellar: :any, catalina: "b9b7b70e46c81533e46032a90b8c8f23395ac5a15eb89c3dd8aadbf2b4c266af"
sha256 cellar: :any, mojave: "eae3a12f74750e5b7593e4ef3aa1f7ba3173f4cf31ccc8a4bb865b010de098f0"
sha256 cellar: :any_skip_relocation, x86_64_linux: "0b91fe9573a070bc8620a3b1a19c48d0b3780a1209f3ffc9b282cf6944eaa372"
end
depends_on "libevent"
def install
system "make"
bin.install "webdis"
inreplace "webdis.prod.json" do |s|
s.gsub! "/var/log/webdis.log", "#{var}/log/webdis.log"
s.gsub!(/daemonize":\s*true/, "daemonize\":\tfalse")
end
etc.install "webdis.json", "webdis.prod.json"
end
def post_install
(var/"log").mkpath
end
plist_options manual: "webdis #{HOMEBREW_PREFIX}/etc/webdis.json"
def plist
<<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/webdis</string>
<string>#{etc}/webdis.prod.json</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>WorkingDirectory</key>
<string>#{var}</string>
</dict>
</plist>
EOS
end
test do
port = free_port
cp "#{etc}/webdis.json", "#{testpath}/webdis.json"
inreplace "#{testpath}/webdis.json", "\"http_port\":\t7379,", "\"http_port\":\t#{port},"
server = fork do
exec "#{bin}/webdis", "#{testpath}/webdis.json"
end
sleep 0.5
# Test that the response is from webdis
assert_match(/Server: Webdis/, shell_output("curl --silent -XGET -I http://localhost:#{port}/PING"))
ensure
Process.kill "TERM", server
Process.wait server
end
end
| Linuxbrew/homebrew-core | Formula/webdis.rb | Ruby | bsd-2-clause | 2,593 |
/**
* @module ol/style/RegularShape
*/
import {asString} from '../color.js';
import {asColorLike} from '../colorlike.js';
import {createCanvasContext2D} from '../dom.js';
import {CANVAS_LINE_DASH} from '../has.js';
import ImageState from '../ImageState.js';
import {defaultStrokeStyle, defaultFillStyle, defaultLineCap, defaultLineWidth, defaultLineJoin, defaultMiterLimit} from '../render/canvas.js';
import ImageStyle from './Image.js';
/**
* Specify radius for regular polygons, or radius1 and radius2 for stars.
* @typedef {Object} Options
* @property {import("./Fill.js").default} [fill] Fill style.
* @property {number} points Number of points for stars and regular polygons. In case of a polygon, the number of points
* is the number of sides.
* @property {number} [radius] Radius of a regular polygon.
* @property {number} [radius1] Outer radius of a star.
* @property {number} [radius2] Inner radius of a star.
* @property {number} [angle=0] Shape's angle in radians. A value of 0 will have one of the shape's point facing up.
* @property {import("./Stroke.js").default} [stroke] Stroke style.
* @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).
* @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view.
* @property {import("./AtlasManager.js").default} [atlasManager] The atlas manager to use for this symbol. When
* using WebGL it is recommended to use an atlas manager to avoid texture switching. If an atlas manager is given, the
* symbol is added to an atlas. By default no atlas manager is used.
*/
/**
* @typedef {Object} RenderOptions
* @property {import("../colorlike.js").ColorLike} [strokeStyle]
* @property {number} strokeWidth
* @property {number} size
* @property {string} lineCap
* @property {Array<number>} lineDash
* @property {number} lineDashOffset
* @property {string} lineJoin
* @property {number} miterLimit
*/
/**
* @classdesc
* Set regular shape style for vector features. The resulting shape will be
* a regular polygon when `radius` is provided, or a star when `radius1` and
* `radius2` are provided.
* @api
*/
class RegularShape extends ImageStyle {
/**
* @param {Options} options Options.
*/
constructor(options) {
/**
* @type {boolean}
*/
const rotateWithView = options.rotateWithView !== undefined ?
options.rotateWithView : false;
super({
opacity: 1,
rotateWithView: rotateWithView,
rotation: options.rotation !== undefined ? options.rotation : 0,
scale: 1
});
/**
* @private
* @type {Array<string|number>}
*/
this.checksums_ = null;
/**
* @private
* @type {HTMLCanvasElement}
*/
this.canvas_ = null;
/**
* @private
* @type {HTMLCanvasElement}
*/
this.hitDetectionCanvas_ = null;
/**
* @private
* @type {import("./Fill.js").default}
*/
this.fill_ = options.fill !== undefined ? options.fill : null;
/**
* @private
* @type {Array<number>}
*/
this.origin_ = [0, 0];
/**
* @private
* @type {number}
*/
this.points_ = options.points;
/**
* @protected
* @type {number}
*/
this.radius_ = /** @type {number} */ (options.radius !== undefined ?
options.radius : options.radius1);
/**
* @private
* @type {number|undefined}
*/
this.radius2_ = options.radius2;
/**
* @private
* @type {number}
*/
this.angle_ = options.angle !== undefined ? options.angle : 0;
/**
* @private
* @type {import("./Stroke.js").default}
*/
this.stroke_ = options.stroke !== undefined ? options.stroke : null;
/**
* @private
* @type {Array<number>}
*/
this.anchor_ = null;
/**
* @private
* @type {import("../size.js").Size}
*/
this.size_ = null;
/**
* @private
* @type {import("../size.js").Size}
*/
this.imageSize_ = null;
/**
* @private
* @type {import("../size.js").Size}
*/
this.hitDetectionImageSize_ = null;
/**
* @protected
* @type {import("./AtlasManager.js").default|undefined}
*/
this.atlasManager_ = options.atlasManager;
this.render_(this.atlasManager_);
}
/**
* Clones the style. If an atlasmanager was provided to the original style it will be used in the cloned style, too.
* @return {RegularShape} The cloned style.
* @api
*/
clone() {
const style = new RegularShape({
fill: this.getFill() ? this.getFill().clone() : undefined,
points: this.getPoints(),
radius: this.getRadius(),
radius2: this.getRadius2(),
angle: this.getAngle(),
stroke: this.getStroke() ? this.getStroke().clone() : undefined,
rotation: this.getRotation(),
rotateWithView: this.getRotateWithView(),
atlasManager: this.atlasManager_
});
style.setOpacity(this.getOpacity());
style.setScale(this.getScale());
return style;
}
/**
* @inheritDoc
* @api
*/
getAnchor() {
return this.anchor_;
}
/**
* Get the angle used in generating the shape.
* @return {number} Shape's rotation in radians.
* @api
*/
getAngle() {
return this.angle_;
}
/**
* Get the fill style for the shape.
* @return {import("./Fill.js").default} Fill style.
* @api
*/
getFill() {
return this.fill_;
}
/**
* @inheritDoc
*/
getHitDetectionImage(pixelRatio) {
return this.hitDetectionCanvas_;
}
/**
* @inheritDoc
* @api
*/
getImage(pixelRatio) {
return this.canvas_;
}
/**
* @inheritDoc
*/
getImageSize() {
return this.imageSize_;
}
/**
* @inheritDoc
*/
getHitDetectionImageSize() {
return this.hitDetectionImageSize_;
}
/**
* @inheritDoc
*/
getImageState() {
return ImageState.LOADED;
}
/**
* @inheritDoc
* @api
*/
getOrigin() {
return this.origin_;
}
/**
* Get the number of points for generating the shape.
* @return {number} Number of points for stars and regular polygons.
* @api
*/
getPoints() {
return this.points_;
}
/**
* Get the (primary) radius for the shape.
* @return {number} Radius.
* @api
*/
getRadius() {
return this.radius_;
}
/**
* Get the secondary radius for the shape.
* @return {number|undefined} Radius2.
* @api
*/
getRadius2() {
return this.radius2_;
}
/**
* @inheritDoc
* @api
*/
getSize() {
return this.size_;
}
/**
* Get the stroke style for the shape.
* @return {import("./Stroke.js").default} Stroke style.
* @api
*/
getStroke() {
return this.stroke_;
}
/**
* @inheritDoc
*/
listenImageChange(listener, thisArg) {
return undefined;
}
/**
* @inheritDoc
*/
load() {}
/**
* @inheritDoc
*/
unlistenImageChange(listener, thisArg) {}
/**
* @protected
* @param {import("./AtlasManager.js").default|undefined} atlasManager An atlas manager.
*/
render_(atlasManager) {
let imageSize;
let lineCap = '';
let lineJoin = '';
let miterLimit = 0;
let lineDash = null;
let lineDashOffset = 0;
let strokeStyle;
let strokeWidth = 0;
if (this.stroke_) {
strokeStyle = this.stroke_.getColor();
if (strokeStyle === null) {
strokeStyle = defaultStrokeStyle;
}
strokeStyle = asColorLike(strokeStyle);
strokeWidth = this.stroke_.getWidth();
if (strokeWidth === undefined) {
strokeWidth = defaultLineWidth;
}
lineDash = this.stroke_.getLineDash();
lineDashOffset = this.stroke_.getLineDashOffset();
if (!CANVAS_LINE_DASH) {
lineDash = null;
lineDashOffset = 0;
}
lineJoin = this.stroke_.getLineJoin();
if (lineJoin === undefined) {
lineJoin = defaultLineJoin;
}
lineCap = this.stroke_.getLineCap();
if (lineCap === undefined) {
lineCap = defaultLineCap;
}
miterLimit = this.stroke_.getMiterLimit();
if (miterLimit === undefined) {
miterLimit = defaultMiterLimit;
}
}
let size = 2 * (this.radius_ + strokeWidth) + 1;
/** @type {RenderOptions} */
const renderOptions = {
strokeStyle: strokeStyle,
strokeWidth: strokeWidth,
size: size,
lineCap: lineCap,
lineDash: lineDash,
lineDashOffset: lineDashOffset,
lineJoin: lineJoin,
miterLimit: miterLimit
};
if (atlasManager === undefined) {
// no atlas manager is used, create a new canvas
const context = createCanvasContext2D(size, size);
this.canvas_ = context.canvas;
// canvas.width and height are rounded to the closest integer
size = this.canvas_.width;
imageSize = size;
this.draw_(renderOptions, context, 0, 0);
this.createHitDetectionCanvas_(renderOptions);
} else {
// an atlas manager is used, add the symbol to an atlas
size = Math.round(size);
const hasCustomHitDetectionImage = !this.fill_;
let renderHitDetectionCallback;
if (hasCustomHitDetectionImage) {
// render the hit-detection image into a separate atlas image
renderHitDetectionCallback =
this.drawHitDetectionCanvas_.bind(this, renderOptions);
}
const id = this.getChecksum();
const info = atlasManager.add(
id, size, size, this.draw_.bind(this, renderOptions),
renderHitDetectionCallback);
this.canvas_ = info.image;
this.origin_ = [info.offsetX, info.offsetY];
imageSize = info.image.width;
if (hasCustomHitDetectionImage) {
this.hitDetectionCanvas_ = info.hitImage;
this.hitDetectionImageSize_ =
[info.hitImage.width, info.hitImage.height];
} else {
this.hitDetectionCanvas_ = this.canvas_;
this.hitDetectionImageSize_ = [imageSize, imageSize];
}
}
this.anchor_ = [size / 2, size / 2];
this.size_ = [size, size];
this.imageSize_ = [imageSize, imageSize];
}
/**
* @private
* @param {RenderOptions} renderOptions Render options.
* @param {CanvasRenderingContext2D} context The rendering context.
* @param {number} x The origin for the symbol (x).
* @param {number} y The origin for the symbol (y).
*/
draw_(renderOptions, context, x, y) {
let i, angle0, radiusC;
// reset transform
context.setTransform(1, 0, 0, 1, 0, 0);
// then move to (x, y)
context.translate(x, y);
context.beginPath();
let points = this.points_;
if (points === Infinity) {
context.arc(
renderOptions.size / 2, renderOptions.size / 2,
this.radius_, 0, 2 * Math.PI, true);
} else {
const radius2 = (this.radius2_ !== undefined) ? this.radius2_
: this.radius_;
if (radius2 !== this.radius_) {
points = 2 * points;
}
for (i = 0; i <= points; i++) {
angle0 = i * 2 * Math.PI / points - Math.PI / 2 + this.angle_;
radiusC = i % 2 === 0 ? this.radius_ : radius2;
context.lineTo(renderOptions.size / 2 + radiusC * Math.cos(angle0),
renderOptions.size / 2 + radiusC * Math.sin(angle0));
}
}
if (this.fill_) {
let color = this.fill_.getColor();
if (color === null) {
color = defaultFillStyle;
}
context.fillStyle = asColorLike(color);
context.fill();
}
if (this.stroke_) {
context.strokeStyle = renderOptions.strokeStyle;
context.lineWidth = renderOptions.strokeWidth;
if (renderOptions.lineDash) {
context.setLineDash(renderOptions.lineDash);
context.lineDashOffset = renderOptions.lineDashOffset;
}
context.lineCap = /** @type {CanvasLineCap} */ (renderOptions.lineCap);
context.lineJoin = /** @type {CanvasLineJoin} */ (renderOptions.lineJoin);
context.miterLimit = renderOptions.miterLimit;
context.stroke();
}
context.closePath();
}
/**
* @private
* @param {RenderOptions} renderOptions Render options.
*/
createHitDetectionCanvas_(renderOptions) {
this.hitDetectionImageSize_ = [renderOptions.size, renderOptions.size];
if (this.fill_) {
this.hitDetectionCanvas_ = this.canvas_;
return;
}
// if no fill style is set, create an extra hit-detection image with a
// default fill style
const context = createCanvasContext2D(renderOptions.size, renderOptions.size);
this.hitDetectionCanvas_ = context.canvas;
this.drawHitDetectionCanvas_(renderOptions, context, 0, 0);
}
/**
* @private
* @param {RenderOptions} renderOptions Render options.
* @param {CanvasRenderingContext2D} context The context.
* @param {number} x The origin for the symbol (x).
* @param {number} y The origin for the symbol (y).
*/
drawHitDetectionCanvas_(renderOptions, context, x, y) {
// reset transform
context.setTransform(1, 0, 0, 1, 0, 0);
// then move to (x, y)
context.translate(x, y);
context.beginPath();
let points = this.points_;
if (points === Infinity) {
context.arc(
renderOptions.size / 2, renderOptions.size / 2,
this.radius_, 0, 2 * Math.PI, true);
} else {
const radius2 = (this.radius2_ !== undefined) ? this.radius2_
: this.radius_;
if (radius2 !== this.radius_) {
points = 2 * points;
}
let i, radiusC, angle0;
for (i = 0; i <= points; i++) {
angle0 = i * 2 * Math.PI / points - Math.PI / 2 + this.angle_;
radiusC = i % 2 === 0 ? this.radius_ : radius2;
context.lineTo(renderOptions.size / 2 + radiusC * Math.cos(angle0),
renderOptions.size / 2 + radiusC * Math.sin(angle0));
}
}
context.fillStyle = asString(defaultFillStyle);
context.fill();
if (this.stroke_) {
context.strokeStyle = renderOptions.strokeStyle;
context.lineWidth = renderOptions.strokeWidth;
if (renderOptions.lineDash) {
context.setLineDash(renderOptions.lineDash);
context.lineDashOffset = renderOptions.lineDashOffset;
}
context.stroke();
}
context.closePath();
}
/**
* @return {string} The checksum.
*/
getChecksum() {
const strokeChecksum = this.stroke_ ?
this.stroke_.getChecksum() : '-';
const fillChecksum = this.fill_ ?
this.fill_.getChecksum() : '-';
const recalculate = !this.checksums_ ||
(strokeChecksum != this.checksums_[1] ||
fillChecksum != this.checksums_[2] ||
this.radius_ != this.checksums_[3] ||
this.radius2_ != this.checksums_[4] ||
this.angle_ != this.checksums_[5] ||
this.points_ != this.checksums_[6]);
if (recalculate) {
const checksum = 'r' + strokeChecksum + fillChecksum +
(this.radius_ !== undefined ? this.radius_.toString() : '-') +
(this.radius2_ !== undefined ? this.radius2_.toString() : '-') +
(this.angle_ !== undefined ? this.angle_.toString() : '-') +
(this.points_ !== undefined ? this.points_.toString() : '-');
this.checksums_ = [checksum, strokeChecksum, fillChecksum,
this.radius_, this.radius2_, this.angle_, this.points_];
}
return /** @type {string} */ (this.checksums_[0]);
}
}
export default RegularShape;
| mzur/ol3 | src/ol/style/RegularShape.js | JavaScript | bsd-2-clause | 15,429 |