code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?php
/*
* This file is part of the symfony package.
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Finds deprecated helpers usage.
*
* @package symfony
* @subpackage task
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfAssetsUpgrade.class.php 24395 2009-11-25 19:02:18Z Kris.Wallsmith $
*/
class sfDeprecatedHelpersValidation extends sfValidation
{
public function getHeader()
{
return 'Checking usage of deprecated helpers';
}
public function getExplanation()
{
return array(
'',
' The files above use deprecated helpers',
' that have been removed in symfony 1.4.',
'',
' You can find a list of all deprecated helpers under the',
' "Helpers" section of the DEPRECATED tutorial:',
'',
' http://www.symfony-project.org/tutorial/1_4/en/deprecated',
'',
);
}
public function validate()
{
$helpers = array(
'select_day_tag', 'select_month_tag', 'select_year_tag', 'select_date_tag', 'select_second_tag',
'select_minute_tag', 'select_hour_tag', 'select_ampm_tag', 'select_time_tag', 'select_datetime_tag',
'select_number_tag', 'select_timezone_tag', 'options_for_select', 'select_tag', 'select_country_tag',
'select_language_tag', 'select_currency_tag', 'input_tag', 'input_hidden_tag', 'input_file_tag',
'input_password_tag', 'textarea_tag', 'checkbox_tag', 'radiobutton_tag', 'input_date_range_tag',
'input_date_tag', 'submit_tag', 'reset_tag', 'submit_image_tag', 'label_for',
'object_admin_input_file_tag', 'object_admin_double_list', 'object_admin_select_list',
'object_admin_check_list', 'object_input_date_tag', 'object_textarea_tag', 'objects_for_select',
'object_select_tag', 'object_select_country_tag', 'object_select_language_tag', 'object_input_hidden_tag',
'object_input_tag', 'object_checkbox_tag', 'form_has_error', 'form_error', 'get_callbacks',
'get_ajax_options', 'button_to_remote', 'link_to_remote', 'periodically_call_remote', 'form_remote_tag',
'submit_to_remote', 'submit_image_to_remote', 'update_element_function', 'evaluate_remote_response',
'remote_function', 'observe_field', 'observe_form', 'visual_effect', 'sortable_element',
'draggable_element', 'drop_receiving_element', 'input_auto_complete_tag', 'input_in_place_editor_tag',
);
$found = array();
$files = sfFinder::type('file')->name('*.php')->prune('vendor')->in(array(
sfConfig::get('sf_apps_dir'),
sfConfig::get('sf_lib_dir'),
sfConfig::get('sf_test_dir'),
sfConfig::get('sf_plugins_dir'),
));
foreach ($files as $file)
{
$content = sfToolkit::stripComments(file_get_contents($file));
$matches = array();
foreach ($helpers as $helper)
{
if (preg_match('#\b'.preg_quote($helper, '#').'\b#', $content))
{
$matches[] = $helper;
}
}
if ($matches)
{
$found[$file] = implode(', ', $matches);
}
}
return $found;
}
}
| wboray/symfony | lib/symfony/task/project/validation/sfDeprecatedHelpersValidation.class.php | PHP | mit | 3,276 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LetsCreateAListOfDucks
{
enum KindOfDuck
{
Mallard,
Muscovy,
Decoy,
}
}
| head-first-csharp/third-edition | VS2013/Chapter_8/LetsCreateAListOfDucks/LetsCreateAListOfDucks/KindOfDuck.cs | C# | mit | 253 |
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/// <reference path="../../../_references.ts"/>
module powerbi.visuals.samples {
import ClassAndSelector = jsCommon.CssConstants.ClassAndSelector;
import CreateClassAndSelector = jsCommon.CssConstants.createClassAndSelector;
import PixelConverter = jsCommon.PixelConverter;
export interface RadarChartConstructorOptions {
animator?: IGenericAnimator;
svg?: D3.Selection;
margin?: IMargin;
}
export interface RadarChartDatapoint extends SelectableDataPoint {
x: number;
y: number;
y0?: number;
color?: string;
value?: number;
tooltipInfo?: TooltipDataItem[];
labelFormatString?: string;
labelFontSize?: string;
}
export interface RadarChartData {
legendData: LegendData;
series: RadarChartSeries[];
settings: RadarChartSettings;
dataLabelsSettings: PointDataLabelsSettings;
}
export interface RadarChartSeries {
fill: string;
name: string;
data: RadarChartDatapoint[];
identity: SelectionId;
}
export interface RadarChartSettings {
showLegend?: boolean;
}
export interface RadarChartBehaviorOptions {
selection: D3.Selection;
clearCatcher: D3.Selection;
}
/**
* RadarChartBehavior
*/
export class RadarChartWebBehavior implements IInteractiveBehavior {
private selection: D3.Selection;
public bindEvents(options: RadarChartBehaviorOptions, selectionHandler: ISelectionHandler): void {
var selection = this.selection = options.selection;
var clearCatcher = options.clearCatcher;
selection.on('click', function (d: SelectableDataPoint) {
selectionHandler.handleSelection(d, d3.event.ctrlKey);
d3.event.stopPropagation();
});
clearCatcher.on('click', function () {
selectionHandler.handleClearSelection();
});
}
public renderSelection(hasSelection: boolean): void {
this.selection.style("opacity", (d: SelectableDataPoint) => (hasSelection && !d.selected) ? RadarChart.DimmedAreaFillOpacity : RadarChart.NodeFillOpacity);
}
}
export class RadarChart implements IVisual {
public static capabilities: VisualCapabilities = {
dataRoles: [
{
displayName: 'Category',
name: 'Category',
kind: powerbi.VisualDataRoleKind.Grouping,
},
{
displayName: 'Y Axis',
name: 'Y',
kind: powerbi.VisualDataRoleKind.Measure,
},
],
dataViewMappings: [{
conditions: [{ 'Category': { min: 1, max: 1 } }],
categorical: {
categories: {
for: { in: 'Category' },
dataReductionAlgorithm: { top: {} }
},
values: {
select: [{ bind: { to: 'Y' } }]
}
}
}],
objects: {
general: {
displayName: data.createDisplayNameGetter('Visual_General'),
properties: {
formatString: {
type: { formatting: { formatString: true } },
},
},
},
legend: {
displayName: data.createDisplayNameGetter('Visual_Legend'),
description: data.createDisplayNameGetter('Visual_LegendDescription'),
properties: {
show: {
displayName: data.createDisplayNameGetter('Visual_Show'),
type: { bool: true }
},
position: {
displayName: data.createDisplayNameGetter('Visual_LegendPosition'),
description: data.createDisplayNameGetter('Visual_LegendPositionDescription'),
type: { enumeration: legendPosition.type }
},
showTitle: {
displayName: data.createDisplayNameGetter('Visual_LegendShowTitle'),
description: data.createDisplayNameGetter('Visual_LegendShowTitleDescription'),
type: { bool: true }
},
titleText: {
displayName: data.createDisplayNameGetter('Visual_LegendName'),
description: data.createDisplayNameGetter('Visual_LegendNameDescription'),
type: { text: true },
suppressFormatPainterCopy: true
},
labelColor: {
displayName: data.createDisplayNameGetter('Visual_LegendTitleColor'),
type: { fill: { solid: { color: true } } }
},
fontSize: {
displayName: data.createDisplayNameGetter('Visual_TextSize'),
type: { formatting: { fontSize: true } }
}
}
},
dataPoint: {
displayName: data.createDisplayNameGetter('Visual_DataPoint'),
description: data.createDisplayNameGetter('Visual_DataPointDescription'),
properties: {
fill: {
displayName: data.createDisplayNameGetter('Visual_Fill'),
type: { fill: { solid: { color: true } } }
}
}
},
labels: {
displayName: data.createDisplayNameGetter('Visual_DataPointsLabels'),
description: data.createDisplayNameGetter('Visual_DataPointsLabelsDescription'),
properties: {
show: {
displayName: data.createDisplayNameGetter('Visual_Show'),
type: { bool: true }
},
color: {
displayName: data.createDisplayNameGetter('Visual_LabelsFill'),
description: data.createDisplayNameGetter('Visual_LabelsFillDescription'),
type: { fill: { solid: { color: true } } }
},
labelDisplayUnits: {
displayName: data.createDisplayNameGetter('Visual_DisplayUnits'),
description: data.createDisplayNameGetter('Visual_DisplayUnitsDescription'),
type: { formatting: { labelDisplayUnits: true } },
suppressFormatPainterCopy: true,
},
labelPrecision: {
displayName: data.createDisplayNameGetter('Visual_Precision'),
description: data.createDisplayNameGetter('Visual_PrecisionDescription'),
placeHolderText: data.createDisplayNameGetter('Visual_Precision_Auto'),
type: { numeric: true },
suppressFormatPainterCopy: true,
},
fontSize: {
displayName: data.createDisplayNameGetter('Visual_TextSize'),
type: { formatting: { fontSize: true } }
},
}
}
}
};
/** Note: Public for testability */
public static formatStringProp: DataViewObjectPropertyIdentifier = {
objectName: 'general',
propertyName: 'formatString',
};
private static Properties: any = {
legend: {
show: <DataViewObjectPropertyIdentifier>{ objectName: 'legend', propertyName: 'show' }
},
dataPoint: {
fill: <DataViewObjectPropertyIdentifier>{ objectName: 'dataPoint', propertyName: 'fill' }
},
labels: {
show: <DataViewObjectPropertyIdentifier>{ objectName: 'labels', propertyName: 'show' },
color: <DataViewObjectPropertyIdentifier>{ objectName: 'labels', propertyName: 'color' },
displayUnits: <DataViewObjectPropertyIdentifier>{ objectName: 'labels', propertyName: 'labelDisplayUnits' },
precision: <DataViewObjectPropertyIdentifier>{ objectName: 'labels', propertyName: 'labelPrecision' },
fontSize: <DataViewObjectPropertyIdentifier>{ objectName: 'labels', propertyName: 'fontSize' },
}
};
private static VisualClassName = 'radarChart';
private static Segments: ClassAndSelector = CreateClassAndSelector('segments');
private static SegmentNode: ClassAndSelector = CreateClassAndSelector('segmentNode');
private static ZeroSegment: ClassAndSelector = CreateClassAndSelector('zeroSegment');
private static ZeroSegmentNode: ClassAndSelector = CreateClassAndSelector('zeroSegmentNode');
private static ZeroLabel: ClassAndSelector = CreateClassAndSelector('zeroLabel');
private static Axis: ClassAndSelector = CreateClassAndSelector('axis');
private static AxisNode: ClassAndSelector = CreateClassAndSelector('axisNode');
private static AxisLabel: ClassAndSelector = CreateClassAndSelector('axisLabel');
private static Chart: ClassAndSelector = CreateClassAndSelector('chart');
private static ChartNode: ClassAndSelector = CreateClassAndSelector('chartNode');
private static ChartArea: ClassAndSelector = CreateClassAndSelector('chartArea');
private static ChartPolygon: ClassAndSelector = CreateClassAndSelector('chartPolygon');
private static ChartDot: ClassAndSelector = CreateClassAndSelector('chartDot');
private static MaxPrecision: number = 17;
private static MinPrecision: number = 0;
private svg: D3.Selection;
private segments: D3.Selection;
private zeroSegment: D3.Selection;
private axis: D3.Selection;
private chart: D3.Selection;
private mainGroupElement: D3.Selection;
private colors: IDataColorPalette;
private viewport: IViewport;
private interactivityService: IInteractivityService;
private animator: IGenericAnimator;
private margin: IMargin;
private legend: ILegend;
private legendObjectProperties: DataViewObject;
private radarChartData: RadarChartData;
private isInteractiveChart: boolean;
private zeroPointRadius: number;
private static DefaultMargin: IMargin = {
top: 50,
bottom: 50,
right: 100,
left: 100
};
private static SegmentLevels: number = 6;
private static SegmentFactor: number = 1;
private static Radians: number = 2 * Math.PI;
private static Scale: number = 1;
public static NodeFillOpacity = 1;
public static AreaFillOpacity = 0.6;
public static DimmedAreaFillOpacity = 0.4;
private angle: number;
private radius: number;
public static AxesLabelsFontFamily: string = "sans-serif";
public static AxesLabelsfontSize: string = "11px";
public static AxesLabelsMaxWidth: number = 200;
public static converter(dataView: DataView, colors: IDataColorPalette): RadarChartData {
if (!dataView ||
!dataView.categorical ||
!dataView.categorical.categories ||
!(dataView.categorical.categories.length > 0) ||
!dataView.categorical.categories[0] ||
!dataView.categorical.values ||
!(dataView.categorical.values.length > 0) ||
!colors) {
return {
legendData: {
dataPoints: []
},
settings: {
showLegend: true
},
series: [],
dataLabelsSettings: dataLabelUtils.getDefaultPointLabelSettings(),
};
}
var catDv: DataViewCategorical = dataView.categorical,
values: DataViewValueColumns = catDv.values,
grouped: DataViewValueColumnGroup[] = catDv && catDv.values ? catDv.values.grouped() : null,
series: RadarChartSeries[] = [],
colorHelper = new ColorHelper(colors, RadarChart.Properties.dataPoint.fill);
var legendData: LegendData = {
fontSize: 8.25,
dataPoints: [],
title: ""
};
//Parse legend settings
var legendSettings: RadarChartSettings = RadarChart.parseSettings(dataView);
var dataLabelsSettings: PointDataLabelsSettings = RadarChart.parseLabelSettings(dataView);
for (var i = 0, iLen = values.length; i < iLen; i++) {
var color = colors.getColorByIndex(i).value,
serieIdentity: SelectionId,
queryName: string,
displayName: string,
dataPoints: RadarChartDatapoint[] = [];
var columnGroup: DataViewValueColumnGroup = grouped
&& grouped.length > i && grouped[i].values? grouped[i] : null;
if (values[i].source) {
var source = values[i].source;
if (source.queryName) {
queryName = source.queryName;
serieIdentity = SelectionId.createWithMeasure(queryName);
}
if (source.displayName)
displayName = source.displayName;
if (source.objects) {
var objects: any = source.objects;
color = colorHelper.getColorForMeasure(objects, queryName);
}
}
legendData.dataPoints.push({
label: displayName,
color: color,
icon: LegendIcon.Box,
selected: false,
identity: serieIdentity
});
for (var k = 0, kLen = values[i].values.length; k < kLen; k++) {
var dataPointIdentity: SelectionId = SelectionIdBuilder
.builder()
.withMeasure(queryName)
.withCategory(catDv.categories[0], k)
.withSeries(dataView.categorical.values, columnGroup)
.createSelectionId();
var tooltipInfo: TooltipDataItem[] = TooltipBuilder.createTooltipInfo(RadarChart.formatStringProp,
catDv,
catDv.categories[0].values[k],
values[i].values[k],
null,
null,
i);
var labelFormatString = valueFormatter.getFormatString(catDv.values[i].source, RadarChart.formatStringProp);
var fontSizeInPx = jsCommon.PixelConverter.fromPoint(dataLabelsSettings.fontSize);
dataPoints.push({
x: k,
y: <number>values[i].values[k],
color: color,
identity: dataPointIdentity,
selected: false,
tooltipInfo: tooltipInfo,
value: <number>values[i].values[k],
labelFormatString: labelFormatString,
labelFontSize: fontSizeInPx,
});
}
if (dataPoints.length > 0)
series.push({
fill: color,
name: displayName,
data: dataPoints,
identity: serieIdentity,
});
}
return {
legendData: legendData,
settings: legendSettings,
series: series,
dataLabelsSettings: dataLabelsSettings,
};
}
public constructor(options?: RadarChartConstructorOptions) {
if (options) {
if (options.svg)
this.svg = options.svg;
if (options.animator)
this.animator = options.animator;
if (options.margin)
this.margin = options.margin;
}
}
public init(options: VisualInitOptions): void {
var element = options.element;
if (!this.svg) {
this.svg = d3.select(element.get(0)).append('svg');
this.svg.style('position', 'absolute');
}
if (!this.margin)
this.margin = RadarChart.DefaultMargin;
this.svg.classed(RadarChart.VisualClassName, true);
this.interactivityService = visuals.createInteractivityService(options.host);
this.isInteractiveChart = options.interactivity && options.interactivity.isInteractiveLegend;
this.legend = createLegend(element,
this.isInteractiveChart,
this.interactivityService,
true,
LegendPosition.Top);
this.colors = options.style.colorPalette.dataColors;
this.mainGroupElement = this.svg.append('g');
this.segments = this.mainGroupElement
.append('g')
.classed(RadarChart.Segments.class, true);
this.zeroSegment = this.mainGroupElement
.append('g')
.classed(RadarChart.ZeroSegment.class, true);
this.axis = this.mainGroupElement
.append('g')
.classed(RadarChart.Axis.class, true);
this.chart = this.mainGroupElement
.append('g')
.classed(RadarChart.Chart.class, true);
}
public update(options: VisualUpdateOptions): void {
if (!options.dataViews || !options.dataViews[0])
return;
var dataView = options.dataViews[0];
this.radarChartData = RadarChart.converter(dataView, this.colors);
var categories: any[] = [],
series = this.radarChartData.series,
dataViewMetadataColumn: DataViewMetadataColumn,
duration = AnimatorCommon.GetAnimationDuration(this.animator, options.suppressAnimations);
if (dataView.categorical &&
dataView.categorical.categories &&
dataView.categorical.categories[0] &&
dataView.categorical.categories[0].values)
categories = dataView.categorical.categories[0].values;
if (dataView.metadata && dataView.metadata.columns && dataView.metadata.columns.length > 0)
dataViewMetadataColumn = dataView.metadata.columns[0];
this.viewport = {
height: options.viewport.height > 0 ? options.viewport.height : 0,
width: options.viewport.width > 0 ? options.viewport.width : 0
};
this.parseLegendProperties(dataView);
this.renderLegend(this.radarChartData);
this.updateViewport();
this.svg
.attr({
'height': this.viewport.height,
'width': this.viewport.width
});
var mainGroup = this.mainGroupElement;
mainGroup.attr('transform', SVGUtil.translate(this.viewport.width / 2, this.viewport.height / 2));
var width: number = this.viewport.width - this.margin.left - this.margin.right;
var height: number = this.viewport.height - this.margin.top - this.margin.bottom;
this.angle = RadarChart.Radians / categories.length;
this.radius = RadarChart.SegmentFactor * RadarChart.Scale * Math.min(width, height) / 2;
this.drawCircularSegments(categories);
this.drawAxes(categories);
this.drawAxesLabels(categories, dataViewMetadataColumn);
this.drawChart(series, duration);
this.drawDataLabels(series);
this.drawZeroCircularSegment(categories);
if (this.zeroPointRadius !== 0)
this.drawZeroLabel();
else
this.mainGroupElement.selectAll(RadarChart.ZeroLabel.selector).remove();
}
private getRadarChartLabelLayout(labelSettings: PointDataLabelsSettings, allDataPoints: RadarChartDatapoint[]): ILabelLayout {
var formattersCache = dataLabelUtils.createColumnFormatterCacheManager();
var angle: number = this.angle;
var viewport = this.viewport;
var halfHeight = this.viewport.height / 2;
var halfWidth = this.viewport.width / 2;
var y: any = this.calculateChartDomain(this.radarChartData.series);
return {
labelText: (d: RadarChartDatapoint) => {
var formmater = formattersCache.getOrCreate(d.labelFormatString, labelSettings);
if (labelSettings.displayUnits === 0) {
var maxDataPoint: RadarChartDatapoint = _.max(allDataPoints, d => d.value);
var maxValue = maxDataPoint.value > 0 ? maxDataPoint.value : 0;
formmater = formattersCache.getOrCreate(d.labelFormatString, labelSettings, maxValue);
}
return dataLabelUtils.getLabelFormattedText({ label: formmater.format(d.value), maxWidth: viewport.width, fontSize: labelSettings.fontSize });
},
labelLayout: {
x: (d: RadarChartDatapoint) => -1 * y(d.y) * Math.sin(d.x * angle) + halfWidth,
y: (d: RadarChartDatapoint) => -1 * y(d.y) * Math.cos(d.x * angle) + halfHeight - 7,
},
filter: (d: RadarChartDatapoint) => {
return (d != null && d.value != null);
},
style: {
'fill': labelSettings.labelColor,
'font-size': (d: RadarChartDatapoint) => PixelConverter.fromPoint(labelSettings.fontSize),
},
};
}
private drawCircularSegments(values: string[]): void {
var data = [];
var angle: number = this.angle,
factor: number = RadarChart.SegmentFactor,
levels: number = RadarChart.SegmentLevels,
radius: number = this.radius;
for (var level = 0; level < levels - 1; level++) {
var levelFactor: number = radius * ((level + 1) / levels);
var transform: number = -1 * levelFactor;
for (var i = 0; i < values.length; i++)
data.push({
x1: levelFactor * (1 - factor * Math.sin(i * angle)),
y1: levelFactor * (1 - factor * Math.cos(i * angle)),
x2: levelFactor * (1 - factor * Math.sin((i + 1) * angle)),
y2: levelFactor * (1 - factor * Math.cos((i + 1) * angle)),
translate: SVGUtil.translate(transform, transform)
});
}
var selection = this.mainGroupElement
.select(RadarChart.Segments.selector)
.selectAll(RadarChart.SegmentNode.selector)
.data(data);
selection
.enter()
.append('svg:line')
.classed(RadarChart.SegmentNode.class, true);
selection
.attr({
'x1': item => item.x1,
'y1': item => item.y1,
'x2': item => item.x2,
'y2': item => item.y2,
'transform': item => item.translate
});
selection.exit().remove();
}
private drawDataLabels(series: RadarChartSeries[]): void {
var allDataPoints: RadarChartDatapoint[] = this.getAllDataPointsList(series);
if (this.radarChartData.dataLabelsSettings.show) {
var layout = this.getRadarChartLabelLayout(this.radarChartData.dataLabelsSettings, allDataPoints);
var viewport = this.viewport;
var labels = dataLabelUtils.drawDefaultLabelsForDataPointChart(allDataPoints, this.mainGroupElement, layout, viewport);
labels.attr('transform', SVGUtil.translate(-(viewport.width / 2), -(viewport.height / 2)));
}
else
dataLabelUtils.cleanDataLabels(this.mainGroupElement);
}
private drawAxes(values: string[]): void {
var angle: number = this.angle,
radius: number = -1 * this.radius;
var selection: D3.Selection = this.mainGroupElement
.select(RadarChart.Axis.selector)
.selectAll(RadarChart.AxisNode.selector);
var axis = selection.data(values);
axis
.enter()
.append('svg:line');
axis
.attr({
'x1': 0,
'y1': 0,
'x2': (name, i) => radius * Math.sin(i * angle),
'y2': (name, i) => radius * Math.cos(i * angle)
})
.classed(RadarChart.AxisNode.class, true);
axis.exit().remove();
}
private drawAxesLabels(values: string[], dataViewMetadataColumn?: DataViewMetadataColumn): void {
var angle: number = this.angle,
radius: number = -1 * this.radius,
length: number = values.length;
var formatter = valueFormatter.create({
format: valueFormatter.getFormatString(dataViewMetadataColumn, RadarChart.formatStringProp, true),
value: values[0],
value2: values[length - 1],
});
var selection: D3.Selection = this.mainGroupElement
.select(RadarChart.Axis.selector)
.selectAll(RadarChart.AxisLabel.selector);
var labels = selection.data(values);
labels
.enter()
.append('svg:text');
labels
.attr({
'text-anchor': 'middle',
'dy': '1.5em',
'transform': SVGUtil.translate(0, -10),
'x': (name, i) => { return (radius - 30) * Math.sin(i * angle); },
'y': (name, i) => { return (radius - 20) * Math.cos(i * angle); }
})
.text(item => {
var properties: TextProperties = {
fontFamily: RadarChart.AxesLabelsFontFamily,
fontSize: RadarChart.AxesLabelsfontSize,
text: formatter.format(item)
};
return TextMeasurementService.getTailoredTextOrDefault(properties, Math.min(RadarChart.AxesLabelsMaxWidth, this.viewport.width));
})
.classed(RadarChart.AxisLabel.class, true);
labels.exit().remove();
}
private drawChart(series: RadarChartSeries[], duration: number): void {
var angle: number = this.angle,
dotRadius: number = 5,
dataPoints: RadarChartDatapoint[][] = this.getDataPoints(series);
var stack = d3.layout.stack();
var layers = stack(dataPoints);
var y: any = this.calculateChartDomain(series);
var calculatePoints = (points) => {
return points.map((value) => {
var x1 = -1 * y(value.y) * Math.sin(value.x * angle);
var y1 = -1 * y(value.y) * Math.cos(value.x * angle);
return `${x1},${y1}`;
}).join(' ');
};
var areas = this.chart.selectAll(RadarChart.ChartArea.selector).data(layers);
areas
.enter()
.append('g')
.classed(RadarChart.ChartArea.class, true);
var polygon = areas.selectAll(RadarChart.ChartPolygon.selector).data(d => {
if (d && d.length > 0) {
return [d];
}
return [];
});
polygon
.enter()
.append('polygon')
.classed(RadarChart.ChartPolygon.class, true);
polygon
.style('fill', d => d[0].color)
.style('opacity', RadarChart.DimmedAreaFillOpacity)
.on('mouseover', function (d) {
d3.select(this).transition()
.duration(duration)
.style('opacity', RadarChart.AreaFillOpacity);
})
.on('mouseout', function (d) {
d3.select(this).transition()
.duration(duration)
.style('opacity', RadarChart.DimmedAreaFillOpacity);
})
.attr('points', calculatePoints);
polygon.exit().remove();
areas.exit().remove();
var selection = this.chart.selectAll(RadarChart.ChartNode.selector).data(layers);
selection
.enter()
.append('g')
.classed(RadarChart.ChartNode.class, true);
var dots = selection.selectAll(RadarChart.ChartDot.selector)
.data((d: RadarChartDatapoint[]) => { return d.filter(d => d.y != null); });
dots.enter()
.append('svg:circle')
.classed(RadarChart.ChartDot.class, true);
dots.attr('r', dotRadius)
.attr({
'cx': (value) => -1 * y(value.y) * Math.sin(value.x * angle),
'cy': (value) => -1 * y(value.y) * Math.cos(value.x * angle)
})
.style('fill', d => d.color);
dots.exit().remove();
TooltipManager.addTooltip(dots, (tooltipEvent: TooltipEvent) => tooltipEvent.data.tooltipInfo, true);
selection.exit().remove();
var behaviorOptions: RadarChartBehaviorOptions = undefined;
if (this.interactivityService) {
// Register interactivity
var dataPointsToBind = this.getAllDataPointsList(series);
behaviorOptions = { selection: dots, clearCatcher: this.svg };
this.interactivityService.bind(dataPointsToBind, new RadarChartWebBehavior(), behaviorOptions);
}
}
private calculateChartDomain(series: RadarChartSeries[]): any {
var radius: number = this.radius,
dataPointsList: RadarChartDatapoint[] = this.getAllDataPointsList(series);
var minValue: number = d3.min(dataPointsList, (d) => { return d.y; });
var maxValue: number = d3.max(dataPointsList, (d) => { return d.y; });
if (this.isPercentChart(dataPointsList)) {
minValue = minValue >= 0 ? 0 : -1;
maxValue = maxValue <= 0 ? 0 : 1;
}
var y = d3.scale.linear()
.domain([minValue, maxValue]).range([0, radius]);
// Calculate zero ring radius
this.zeroPointRadius = ((minValue < 0) && (maxValue > 0)) ? y(0) : 0;
return y;
}
private renderLegend(radarChartData: RadarChartData): void {
if (!radarChartData.legendData)
return;
var legendData: LegendData = radarChartData.legendData;
if (this.legendObjectProperties) {
LegendData.update(legendData, this.legendObjectProperties);
var position = <string>this.legendObjectProperties[legendProps.position];
if (position)
this.legend.changeOrientation(LegendPosition[position]);
}
else
this.legend.changeOrientation(LegendPosition.Top);
var viewport = this.viewport;
this.legend.drawLegend(legendData, { height: viewport.height, width: viewport.width });
Legend.positionChartArea(this.svg, this.legend);
}
private drawZeroCircularSegment(values: string[]): void {
var data = [];
var angle: number = this.angle,
factor: number = RadarChart.SegmentFactor,
radius: number = this.zeroPointRadius,
transform: number = -1 * radius;
for (var i = 0; i < values.length; i++)
data.push({
x1: radius * (1 - factor * Math.sin(i * angle)),
y1: radius * (1 - factor * Math.cos(i * angle)),
x2: radius * (1 - factor * Math.sin((i + 1) * angle)),
y2: radius * (1 - factor * Math.cos((i + 1) * angle)),
translate: SVGUtil.translate(transform, transform)
});
var selection = this.mainGroupElement
.select(RadarChart.ZeroSegment.selector)
.selectAll(RadarChart.ZeroSegmentNode.selector)
.data(data);
selection
.enter()
.append('svg:line')
.classed(RadarChart.ZeroSegmentNode.class, true);
selection
.attr({
'x1': item => item.x1,
'y1': item => item.y1,
'x2': item => item.x2,
'y2': item => item.y2,
'transform': item => item.translate
});
selection.exit().remove();
}
private drawZeroLabel() {
var data = [];
data.push({
'x': this.zeroPointRadius * (1 - RadarChart.SegmentFactor) + 5,
'y': -1 * this.zeroPointRadius
});
var zeroLabel = this.mainGroupElement
.select(RadarChart.ZeroSegment.selector)
.selectAll(RadarChart.ZeroLabel.selector).data(data);
zeroLabel
.enter()
.append('text')
.classed(RadarChart.ZeroLabel.class, true).text("0");
zeroLabel
.attr({
'x': item => item.x,
'y': item => item.y
});
}
private getDataPoints(series: RadarChartSeries[]): RadarChartDatapoint[][] {
var dataPoints: RadarChartDatapoint[][] = [];
for (var i: number = 0; i < series.length; i++) {
dataPoints.push(series[i].data);
}
return dataPoints;
}
private getAllDataPointsList(series: RadarChartSeries[]): RadarChartDatapoint[] {
var dataPoints: RadarChartDatapoint[] = [];
for (var i: number = 0; i < series.length; i++) {
dataPoints = dataPoints.concat(series[i].data);
}
return dataPoints;
}
private isPercentChart(dataPointsList: RadarChartDatapoint[]): boolean {
for (var i: number = 0; i < dataPointsList.length; i++) {
if (dataPointsList[i].labelFormatString.indexOf("%") === -1) {
return false;
}
}
return true;
}
private parseLegendProperties(dataView: DataView): void {
if (!dataView || !dataView.metadata) {
this.legendObjectProperties = {};
return;
}
this.legendObjectProperties = DataViewObjects.getObject(dataView.metadata.objects, "legend", {});
}
private static parseSettings(dataView: DataView): RadarChartSettings {
var objects: DataViewObjects;
if (!dataView || !dataView.metadata || !dataView.metadata.columns || !dataView.metadata.objects)
objects = null;
else
objects = dataView.metadata.objects;
return {
showLegend: DataViewObjects.getValue(objects, RadarChart.Properties.legend.show, true)
};
}
private static getPrecision(value: number): number {
return Math.max(RadarChart.MinPrecision, Math.min(RadarChart.MaxPrecision, value));
}
private static parseLabelSettings(dataView: DataView): PointDataLabelsSettings {
var objects: DataViewObjects;
if (!dataView || !dataView.metadata || !dataView.metadata.objects)
objects = null;
else
objects = dataView.metadata.objects;
var dataLabelsSettings: PointDataLabelsSettings = dataLabelUtils.getDefaultPointLabelSettings();
var labelsObj: PointDataLabelsSettings = {
show: DataViewObjects.getValue(objects, RadarChart.Properties.labels.show, dataLabelsSettings.show),
labelColor: DataViewObjects.getFillColor(objects, RadarChart.Properties.labels.color, dataLabelsSettings.labelColor),
displayUnits: DataViewObjects.getValue(objects, RadarChart.Properties.labels.displayUnits, dataLabelsSettings.displayUnits),
precision: RadarChart.getPrecision(DataViewObjects.getValue(objects, RadarChart.Properties.labels.precision, dataLabelsSettings.precision)),
fontSize: DataViewObjects.getValue(objects, RadarChart.Properties.labels.fontSize, dataLabelsSettings.fontSize),
position: dataLabelsSettings.position
};
return labelsObj;
}
// This function returns the values to be displayed in the property pane for each object.
// Usually it is a bind pass of what the property pane gave you, but sometimes you may want to do
// validation and return other values/defaults
public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstanceEnumeration {
var enumeration = new ObjectEnumerationBuilder();
var settings: RadarChartSettings;
if (!this.radarChartData || !this.radarChartData.settings)
return [];
settings = this.radarChartData.settings;
switch (options.objectName) {
case "legend":
enumeration.pushInstance(this.enumerateLegend(settings));
break;
case "dataPoint":
this.enumerateDataPoint(enumeration);
break;
case 'labels':
this.enumerateDataLabels(enumeration);
break;
}
return enumeration.complete();
}
private getLabelSettingsOptions(enumeration: ObjectEnumerationBuilder, labelSettings: PointDataLabelsSettings): VisualDataLabelsSettingsOptions {
return {
enumeration: enumeration,
dataLabelsSettings: labelSettings,
show: true,
displayUnits: true,
precision: true,
fontSize: true,
};
}
private enumerateDataLabels(enumeration: ObjectEnumerationBuilder): void {
var labelSettings = this.radarChartData.dataLabelsSettings;
//Draw default settings
dataLabelUtils.enumerateDataLabels(this.getLabelSettingsOptions(enumeration, labelSettings));
}
private enumerateLegend(settings: RadarChartSettings): VisualObjectInstance {
var showTitle: boolean = true,
titleText: string = "",
legend: VisualObjectInstance,
labelColor: DataColorPalette,
fontSize: number = 8;
showTitle = DataViewObject.getValue(this.legendObjectProperties, legendProps.showTitle, showTitle);
titleText = DataViewObject.getValue(this.legendObjectProperties, legendProps.titleText, titleText);
labelColor = DataViewObject.getValue(this.legendObjectProperties, legendProps.labelColor, labelColor);
fontSize = DataViewObject.getValue(this.legendObjectProperties, legendProps.fontSize, fontSize);
legend = {
objectName: "legend",
displayName: "legend",
selector: null,
properties: {
show: settings.showLegend,
position: LegendPosition[this.legend.getOrientation()],
showTitle: showTitle,
titleText: titleText,
labelColor: labelColor,
fontSize: fontSize,
}
};
return legend;
}
private enumerateDataPoint(enumeration: ObjectEnumerationBuilder): void {
if (!this.radarChartData || !this.radarChartData.series)
return;
var series: RadarChartSeries[] = this.radarChartData.series;
for (var i: number = 0; i < series.length; i++) {
var serie = series[i];
enumeration.pushInstance({
objectName: "dataPoint",
displayName: serie.name,
selector: ColorHelper.normalizeSelector(serie.identity.getSelector(), false),
properties: {
fill: { solid: { color: serie.fill } }
}
});
}
}
private updateViewport(): void {
var legendMargins: IViewport = this.legend.getMargins(),
legendPosition: LegendPosition;
legendPosition = LegendPosition[<string>this.legendObjectProperties[legendProps.position]];
switch (legendPosition) {
case LegendPosition.Top:
case LegendPosition.TopCenter:
case LegendPosition.Bottom:
case LegendPosition.BottomCenter:
this.viewport.height -= legendMargins.height;
break;
case LegendPosition.Left:
case LegendPosition.LeftCenter:
case LegendPosition.Right:
case LegendPosition.RightCenter:
this.viewport.width -= legendMargins.width;
break;
}
}
}
} | kiewic/PowerBI-visuals | src/Clients/CustomVisuals/visuals/radarChart/visual/radarChart.ts | TypeScript | mit | 44,628 |
/*******************************************************************************
* Copyright (c) 2013-2016 LAAS-CNRS (www.laas.fr)
* 7 Colonel Roche 31077 Toulouse - France
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* Thierry Monteil : Project manager, technical co-manager
* Mahdi Ben Alaya : Technical co-manager
* Samir Medjiah : Technical co-manager
* Khalil Drira : Strategy expert
* Guillaume Garzone : Developer
* François Aïssaoui : Developer
*
* New contributors :
*******************************************************************************/
package org.eclipse.om2m.commons.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;
import org.eclipse.om2m.commons.constants.DBEntities;
import org.eclipse.om2m.commons.resource.LocationRegion;
/**
* Access Control Context JPA Entity
*
*/
@Entity(name=DBEntities.ACCESSCONTROLCONTEXT_ENTITY)
public class AccessControlContextEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private String accessControlContextId;
protected List<String> accessControlWindow;
protected List<String> ipv4Addresses;
protected List<String> ipv6Addresses;
//TODO to store as an external entity to avoid duplication of data
@Transient
protected LocationRegion accessControlLocationRegion;
/**
* @return the accessControlWindow
*/
public List<String> getAccessControlWindow() {
if (accessControlWindow == null){
accessControlWindow = new ArrayList<>();
}
return accessControlWindow;
}
/**
* @param accessControlWindow the accessControlWindow to set
*/
public void setAccessControlWindow(List<String> accessControlWindow) {
this.accessControlWindow = accessControlWindow;
}
/**
* @return the ipv4Addresses
*/
public List<String> getIpv4Addresses() {
if (ipv4Addresses == null){
ipv4Addresses = new ArrayList<>();
}
return ipv4Addresses;
}
/**
* @param ipv4Addresses the ipv4Addresses to set
*/
public void setIpv4Addresses(List<String> ipv4Addresses) {
this.ipv4Addresses = ipv4Addresses;
}
/**
* @return the ipv6Addresses
*/
public List<String> getIpv6Addresses() {
if (ipv6Addresses == null){
ipv6Addresses = new ArrayList<>();
}
return ipv6Addresses;
}
/**
* @param ipv6Addresses the ipv6Addresses to set
*/
public void setIpv6Addresses(List<String> ipv6Addresses) {
this.ipv6Addresses = ipv6Addresses;
}
/**
* @return the accessControlLocationRegion
*/
public LocationRegion getAccessControlLocationRegion() {
return accessControlLocationRegion;
}
/**
* @param accessControlLocationRegion the accessControlLocationRegion to set
*/
public void setAccessControlLocationRegion(
LocationRegion accessControlLocationRegion) {
this.accessControlLocationRegion = accessControlLocationRegion;
}
}
| huanpc/IoT-1 | docker/oneM2M/CSE_IPE/org.eclipse.om2m/org.eclipse.om2m.commons/src/main/java/org/eclipse/om2m/commons/entities/AccessControlContextEntity.java | Java | mit | 3,224 |
/*!
* Copyright 2016 E.J.I.E., S.A.
*
* Licencia con arreglo a la EUPL, Versión 1.1 exclusivamente (la «Licencia»);
* Solo podrá usarse esta obra si se respeta la Licencia.
* Puede obtenerse una copia de la Licencia en
*
* http://ec.europa.eu/idabc/eupl.html
*
* Salvo cuando lo exija la legislación aplicable o se acuerde por escrito,
* el programa distribuido con arreglo a la Licencia se distribuye «TAL CUAL»,
* SIN GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.
* Véase la Licencia en el idioma concreto que rige los permisos y limitaciones
* que establece la Licencia.
*/
/* eslint-env jquery,amd */
/* eslint-disable no-console */
import underscore from 'underscore';
import 'jquery';
import 'rup.base';
import 'popper.js';
import './external/bootstrap-calendar';
/**
* Componente de calendario para la visualización de eventos sobre una interfaz dinámica y personalizable.
*
* @summary Componente RUP Calendar.
* @module rup_calendar
* @example
* var properties = {
* day: 'now',
* classes: {
* months: {
* inmonth: 'cal-day-inmonth',
* outmonth: 'cal-day-outmonth',
* saturday: 'cal-day-weekend',
* sunday: 'cal-day-weekend',
* holidays: 'cal-day-holiday',
* today: 'cal-day-today'
* },
* week: {
* workday: 'cal-day-workday',
* saturday: 'cal-day-weekend',
* sunday: 'cal-day-weekend',
* holidays: 'cal-day-holiday',
* today: 'cal-day-today'
* }
* },
* weekbox: true
* };
*
* $('#calendar').rup_calendar(properties);
*/
//****************************************************************************************************************
// DEFINICIÓN BASE DEL PATRÓN (definición de la variable privada que contendrá los métodos y la función de jQuery)
//****************************************************************************************************************
var rup_calendar = {};
var calObj = {};
var errorstr = (str) => {
let estr = 'Cannot call methods on rup_calendar before init. tried to call method ' + str;
throw ReferenceError(estr);
};
var self;
////El componente subyacente requiere underscore en el scope de window
window._ = underscore;
//Se configura el arranque de UDA para que alberge el nuevo patrón
$.extend($.rup.iniRup, $.rup.rupSelectorObjectConstructor('rup_calendar', rup_calendar));
//*******************************
// DEFINICIÓN DE MÉTODOS PÚBLICOS
//*******************************
$.fn.rup_calendar('extend', {
/**
* Navega en el calendario al punto especificado
* Si el parámetro es un string las únicas opciones son:
* - next
* - prev
* - today
*
* @name navigate
* @param {(string|Date)} navigation Hacia dónde navegar
* @function
* @example
* $("#calendar").rup_calendar('navigate','next');
*/
navigate: function (navigation) {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('navigate');
}
// Si el valor es un objeto Date en función navegamos hasta la posición indicada
if( navigation instanceof Date ) {
if($(ctx).data('cal').options.date_range_start !== undefined ) {
if (navigation.getTime() < $(ctx).data('cal').options.date_range_start.getTime()) {
console.warn('Can´t navigate to an out of range time.');
return;
}
}
if($(ctx).data('cal').options.date_range_end !== undefined ) {
if (navigation.getTime() > $(ctx).data('cal').options.date_range_end.getTime()) {
console.warn('Can´t navigate to an out of range time.');
return;
}
}
let pos = $.extend({}, $(ctx).data('cal').options.position);
pos.start.setTime(navigation.getTime());
$(ctx).data('cal').options.day = pos.start.getFullYear() + '-' +
pos.start.getMonthFormatted() + '-' +
pos.start.getDateFormatted();
$(ctx).data('cal').view();
return;
}
// Si no hay valor se considera que por defecto es "today"
navigation = navigation ? navigation : 'today';
if ($.inArray(navigation, ['next', 'prev', 'today']) < 0) {
throw Error('Parámetro inválido');
}
$(ctx).data('cal').navigate(navigation);
},
/**
* Confirma si en la vista está el día actual.
* @name isToday
* @returns {boolean} true si el dia actual está en la vista. false en caso contrario
* @function
* @example
* $("#calendar").rup_calendar('isToday');
*/
isToday: function() {
var ctx = this;
if (!$(ctx).data('cal').options) {
errorstr('isToday');
}
return $(ctx).data('cal').isToday();
},
/**
* Devuelve la instancia del subyacente bootstrap-calendar
*
* @name instance
* @returns {object} instancia del calendar subyacente
* @function
* @example
* $("#calendar").rup_calendar('instance');
*/
instance: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('instance');
}
return $(ctx).data('cal');
},
/**
* Oculta el menú contextual.
*
* @name setView
* @param {string} viewmode El modo de visualizacion a establecer
* @function
* @example
* $("#calendar").rup_calendar('setView','day');
*/
setView: function (viewmode) {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('setView');
}
// El valor por defecto es month.
viewmode = viewmode ? viewmode : 'month';
if ($.inArray(viewmode, ['year', 'month', 'week', 'day']) < 0) {
throw Error('Parámetro inválido');
}
$(ctx).data('cal').view(viewmode);
},
/**
* Obtiene el modo de visualización actual.
*
* @name getView
* @returns {string} modo de visualización
* @function
* @example
* $('#calendar').rup_calendar('getView');
*/
getView: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getView');
}
return $(ctx).data('cal').options.view;
},
/**
* Obtiene el año del calendario
* @name getYear
* @returns {number} el año del calendario
* @example
* $('#calendar').rup_calendar('getYear');
*/
getYear: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getYear');
}
return $(ctx).data('cal').getYear();
},
/**
* Obtiene el mes del calendario (Enero, Febrero, ..., Diciembre)
* @name getMonth
* @returns {string} el mes del calendario
* @example
* $('#calendar').rup_calendar('getMonth');
*/
getMonth: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getMonth');
}
return $(ctx).data('cal').getMonth();
},
/**
* Obtiene la semana del calendario
* @name getWeek
* @returns {number} la semana del calendario
* @example
* $('#calendar').rup_calendar('getWeek');
*/
getWeek: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getWeek');
}
let date = new Date($(ctx).data('cal').getStartDate());
return date.getWeek();
},
/**
* Obtiene el día de la semana (Lunes - Domingo)
* @name getDay
* @returns {string} el día de la semana
* @example
* $('#calendar').rup_calendar('getDay');
*/
getDay: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getDay');
}
return $(ctx).data('cal').getDay();
},
/**
* Obtiene el título de la vista de calendario.
*
* @name getTitle
* @function
* @returns {string} título de la vista
* @example
* $("#calendar").rup_calendar("getTitle");
*/
'getTitle': function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getTitle');
}
return $(ctx).data('cal').getTitle();
},
/**
* Obtiene la fecha desde la que se muestra el calendario
* @name getStartDate
* @function
* @returns {Date} fecha
* @example
* $("#calendar").rup_calendar("getStartDate");
*/
getStartDate:function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getStartDate');
}
return $(ctx).data('cal').getStartDate();
},
/**
* Obtiene la fecha hasta la que se muestra el calendario
* @name getEndDate
* @function
* @returns {Date} fecha
* @example
* $("#calendar").rup_calendar("getEndDate");
*/
getEndDate:function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getEndDate');
}
return $(ctx).data('cal').getEndDate();
},
/**
* Método que establece y recarga las opciones
*
* @name option
* @function
* @param {string|object} opción Opcion a consultar/establecer u objeto para establecer las propiedades
* @param {any} value Si el primer parametro asigna este valor a la opción especificada
* @example
* $('#calendar').rup_calendar('weekbox', true);
* $('#calendar').rup_calendar({weekbox:true, view:'month'});
*/
option: function(opt, val) {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('option');
}
if(typeof opt === 'object'){
let optNames = Object.keys(opt);
$.each(optNames, (i,e) => {
$(ctx).data('cal').options[e] = opt[e];
$(ctx).data('cal')._render();
});
return;
}
if(val === undefined) {
return $(ctx).data('cal').options[opt];
}
else {
$(ctx).data('cal').options[opt] = val;
$(ctx).data('cal')._render();
}
},
/**
* Devuelve un listado de eventos entre las dos fechas introducidas
*
* @name getEventsBetween
* @function
* @param {Date} fechaDesde
* @param {Date} fechaHasta
* @returns {Array} listado de Eventos entre las fechas
*/
getEventsBetween: function(desde, hasta) {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getEventsBetween');
}
return $(ctx).data('cal').getEventsBetween(desde,hasta);
},
/**
* Muestra los eventos de la casilla con la fecha especificada.
* @name showCell
* @function
* @param {Date} fecha fecha a consultar
* @returns {boolean} true si había eventos. false en caso contrario.
* @example
* $('#calendar').rup_calendar('showCell', new Date('2000-01-01'));
*/
showCell : function(date) {
var ctx = this;
if (!$(ctx).data('cal').options) {
errorstr('showCell');
}
if (!(date instanceof Date)) {
throw TypeError('Se requiere un Date como parámetro');
}
var getCell = (date) => {
let ts = date.getTime();
let col = $('.events-list');
let sel = col.filter( (i, e) => {
return $(e).attr('data-cal-start') <= ts && $(e).attr('data-cal-end') > ts;
});
if(sel.length === 0) {
return false;
}
return $(sel).parent();
};
let cell = getCell(date);
if( cell ) {
if ($('#cal-slide-box').css('display') === undefined ||
$('#cal-slide-box').css('display') === 'none' ){
$(ctx).trigger('beforeShowCell');
cell.mouseover();
cell.click();
}
}
else {
return false;
}
},
/**
* Oculta el div con los eventos si está desplegado
* @name hideCells
* @function
* @example
* $('#calendar').rup_calendar('hideCells');
*/
hideCells: function() {
var ctx = this;
if (!$(ctx).data('cal').options) {
errorstr('showCell');
}
$(ctx).trigger('beforeHideCell');
$('#cal-slide-box').css('display','none');
$(ctx).trigger('afterHideCell');
},
/**
* Recarga los eventos y aplica las opciones cambiadas
*
* @name refresh
* @function
* @example
* $('#calendar').rup_calendar('refresh');
*/
refresh: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('refresh');
}
//Primero actualizamos las opciones (Por si se cambia events_source)
$(ctx).data('cal')._render();
//Actualizamos los eventos
$(ctx).data('cal')._loadEvents();
$(ctx).data('cal')._render();
setTimeout(function () {
$(ctx).trigger('afterRefresh');
}, 400);
},
/**
* Elimina el calendario y retorna a la estructura HTML anterior a la creación del calendario.
*
* @name destroy
* @function
* @example
* $("#contextMenu").rup_calendar("destroy");
*/
destroy: function () {
var ctx = this;
if($(ctx).data('cal') === undefined) {
errorstr('destroy');
}
if( !$(ctx).data('cal').options) {
errorstr('destroy');
}
$(ctx).data('cal').options.selector = undefined;
$(ctx).removeClass('cal-context');
$(ctx).removeData();
$(ctx).children().remove();
$(ctx).trigger('afterDestroy');
}
});
//*******************************
// DEFINICIÓN DE MÉTODOS PRIVADOS
//*******************************
$.fn.rup_calendar('extend', {
_callIfFunction: function (...args) {
if (args.length === 0) return false;
if (args.length > 1) {
let fnc = args[0];
let params = args.slice(1);
if (fnc !== undefined && typeof fnc === 'function') {
return fnc.apply(this, params);
} else {
return false;
}
} else {
if (args !== undefined && typeof (args) === 'function') {
return args.call(this);
}
}
},
/**
* Método de inicialización del componente.
*
* @name _init
* @function
* @private
* @param {object} args - Parámetros de inicialización del componente.
*/
_init: function (args) {
if (args.length > 1) {
$.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_global.initError') + $(this).attr('id'));
} else {
//Se recogen y cruzan las paremetrizaciones del objeto
self = this;
var customSettings = args[0];
var settings = $.extend({}, $.fn.rup_calendar.defaults, customSettings);
self._ADAPTER = $.rup.adapter[settings.adapter];
settings.onAfterEventsLoad = function (...args) {
self._callIfFunction.call(this, $.fn.rup_calendar.defaults.onAfterEventsLoad, args);
self._callIfFunction.call(this, customSettings.rupAfterEventsLoad, args);
$(self).trigger('afterEventsLoad');
};
settings.onAfterViewLoad = function (...args) {
self._callIfFunction.call(this, $.fn.rup_calendar.defaults.onAfterViewLoad, args);
self._callIfFunction.call(this, customSettings.rupAfterViewLoad, args);
$(self).trigger('afterViewLoad');
};
// if ($.rup_utils.aplicatioInPortal()) {
// settings.appendTo = '.r01gContainer';
// }
//El componente subyacente requiere i18n en una variable del scope de window
if (!window.calendar_languages) {
window.calendar_languages = {};
}
window.calendar_languages[settings.language] = $.rup.i18n.base.rup_calendar;
//Lanzar el plugin subyaciente
calObj = new $(self).calendar(settings);
this.data('cal',calObj);
this.trigger('afterInitCalendar');
// Se audita el componente
$.rup.auditComponent('rup_calendar', 'init');
}
}
});
//******************************************************
// DEFINICIÓN DE LA CONFIGURACION POR DEFECTO DEL PATRON
//******************************************************
/**
* @description Propiedades de configuración del componente. Todas son opcionales. Se puede crear un calendario con la funcionalidad básica sin especificar ninguna de estas opciones.
*
* @name defaults
* @property {string} tooltip_container - Container al que se le añade el tooltip.
* @property {(string|function|object)} events_source - Origen de los eventos a añadir en el calendario.
* @property {string} width - Ancho que ocupara el calendario.
* @property {string} view - vista que se mostrara por defecto (year/month/week/day).
* @property {string} day - Punto de inicio del calendario. puede ser 'now' o una fecha en formato (yyyy-mm-dd).
* @property {string} time_start - La hora a la que empieza la vista de día.
* @property {string} time_end - La hora a la que acaba la vista de day.
* @property {string} time_split - Cada cuantos minutos se muestra un separador en la vista de día.
* @property {boolean} format12 - Especifica si se usa o no el formato de 12H en lugar del de 24H.
* @property {string} am_suffix - En el formato de 12H especifica el sufijo para la mañana (default: AM).
* @property {string} pm_suffix - En el formato de 12H especifica el sufijo para la tarde (default: PM).
* @property {string} tmpl_path - Path a la ubicación de las tempaltes de calendar (Debe terminar en '/').
* @property {boolean} tmpl_cache - Indica si cachea o no las templates (default: true).
* @property {object} classes - Establece las clases para cada celda en funcion de la vista.
* @property {(string|null)} modal - ID de la ventana modal. Si se establece las url en los eventos se abrirán en la modal.
* @property {string} modal_type - Modo en el que aparece el modal (iframe/ajax/template).
* @property {function} modal_title - Función para establecer el título del modal. Recibe el evento como parámetro.
* @property {object} views - configuración de las vistas.
* @property {boolean} merge_holidays - Añade al calendario algunas festividades como año nuevo o el día de la independencia americana.
* @property {boolean} display_week_numbers - Determina si se muestra el número de la semana.
* @property {boolean} weekbox - Determina si se muestra o no un div con el número de la semana en la vista de mes.
* @property {object} headers - Cabeceras para las llamadas ajax realizadas desde el calendario.
* @property {boolean} cell_navigation - Determina si se cambia la vista al día o mes haciendo doble click en la celda o click en el número de dia o nombre de mes.
* @property {number} date_range_start - Indica la fecha mínima del rango de operación permitido del calendario. Para retirar esta opcion mediante el método 'options' hay que pasar el valor null.
* @property {number} date_range_end - Indica la fecha máxima del rango de operación permitido del calendario. Para retirar esta opcion mediante el método 'options' hay que padar el valor null.
* @property {function} onAfterEventsLoad - Callback que se ejecuta tras cargar los eventos (Recibe los eventos como parámetros).
* @property {function} onBeforeEventsLoad - Callback que se ejecuta antes de cargar los eventos.
* @property {function} onAfterViewLoad - Callback que se ejecuta tras cargar una nueva vista (Recibe la vista como parámetro).
* @property {function} onAfterModalShow - Callback que se ejecuta tras mostrar el modal (Recibe los eventos como parámetros).
* @property {function} onAfterModalHidden - Callback que se ejecuta tras esconder el modal.(Recibe los eventos como parámetros).
*/
/**
* @description Propiedades del objeto 'classes'
*
* @name classes
*
* @property {object} classes.month - Establece las clases en la vista de mes.
* @property {string} classes.month.inmonth - Establece las clases para las celdas que representan días del mes actual.
* @property {string} classes.month.outmonth - Establece las clases para las celdas que representan días ajenos al mes actual.
* @property {string} classes.month.saturday - Establece las clases para las celdas que representan los sábados.
* @property {string} classes.month.sunday - Establece las clases para las celdas que representan los domingos.
* @property {string} classes.month.holidays - Establece las clases para las celdas que representan los festivos.
* @property {string} classes.month.today - Establece las clases para la celda que representan el día actual.
* @property {object} classes.week - Establece las clases en la vista de semana.
* @property {string} classes.week.workday - Establece las clases para las celdas que representan días entre semana.
* @property {string} classes.week.saturday - Establece las clases para las celdas que representan los sábados.
* @property {string} classes.week.sunday - Establece las clases para las celdas que representan los domingos.
* @property {string} classes.week.holidays - Establece las clases para las celdas que representan los festivos.
* @property {string} classes.week.today - Establece las clases para la celda que representan el día actual.
*/
/**
* @description Propiedades del objeto 'views'
*
* @name views
*
* @property {object} views.year - Establece las opciones para la vista anual.
* @property {integer} views.year.slide_events - Si el valor es 1 permite desplegar los eventos desde las celdas.
* @property {integer} views.year.enable - Si el valor es 1 habilita la vista.
* @property {object} views.month - Establece las opciones para la vista mensual.
* @property {integer} views.month.slide_events - Si el valor es 1 permite desplegar los eventos desde las celdas.
* @property {integer} views.month.enable - Si el valor es 1 habilita la vista.
* @property {object} views.week - Establece las opciones para la vista semanal.
* @property {integer} views.week.enable - Si el valor es 1 habilita la vista.
* @property {object} views.day - Establece las opciones para la vista diaria.
* @property {integer} views.day.enable - Si el valor es 1 habilita la vista.
*/
/**
* @description Ya sea desde local o remoto el JSON con los eventos es un array de objetos en el que
* cada objeto tiene las siguientes propiedades:
*
* @name Eventos
*
* @property {string} id identificador único del evento.
* @property {string} title texto o html que aparecerá al desplegar la celda con el evento.
* @property {string} start la fecha en la que inicia el evento (En milisegundos).
* @property {string} class clase a añadir al evento (Sirve para la visualización del evento).
* @property {string} end la fecha en la que finaliza el evento.
* @property {string} url ruta a la que llevar cuando se haga click sobre el evento.
*
*/
$.fn.rup_calendar.defaults = {
events_source: () => {
return [];
},
language: $.rup.lang,
view: 'month',
tmpl_path: global.STATICS + '/rup/html/templates/rup_calendar/',
tmpl_cache: false,
day: 'now',
weekbox: false,
classes: {
months: {
general: 'label'
}
},
onAfterEventsLoad: () => {},
onAfterViewLoad: () => {},
adapter: 'calendar_bootstrap'
};
| UDA-EJIE/uda-rup | src/rup.calendar.js | JavaScript | mit | 24,871 |
using System.Collections.Generic;
using FoxTool.Fox.Types.Structs;
using FoxTool.Fox.Types.Values;
namespace FoxTool.Tpp.Classes
{
public class TppStrykerDefaultParameter2
{
// Static properties
public FoxEntityHandle Owner { get; set; }
public FoxString ParamName { get; set; }
public FoxFloat GearRatioFactor { get; set; }
public FoxFloat EngineBreakFactor { get; set; }
public FoxFloat SteeringRotFactor { get; set; }
public FoxFloat SteeringRotSpeedFactor { get; set; }
public FoxFloat SteeringRestSpeedFactor { get; set; }
public FoxFloat MaxSpeed { get; set; }
public FoxFloat DifferentialFactor { get; set; }
public FoxBool EnableStabilizer { get; set; }
public FoxFloat StabilizePower { get; set; }
public FoxFloat StabilizeStart { get; set; }
public FoxFloat StabilizeLimit { get; set; }
public FoxFloat EngineRpmLimit { get; set; }
public FoxFloat EngineRpmToShiftUp { get; set; }
public FoxFloat EngineRpmToShiftDown { get; set; }
public FoxFloat FinalGearRatio { get; set; }
public List<FoxFloat> TransmissionGearRatios { get; set; }
public FoxFloat YAxisRotationReductionRate { get; set; }
public FoxFloat XAxisSlipReductionRate { get; set; }
public FoxFloat YAxisRotationReduceThreshold { get; set; }
public FoxFloat XAxisSlipReductionThreshold { get; set; }
public FoxBool EnableXAxisStabilizer { get; set; }
public FoxFloat XAxisStabilizePower { get; set; }
public FoxFloat XAxisStabilizeStart { get; set; }
public FoxFloat XAxisStabilizeLimit { get; set; }
public FoxBool EnableXAxisxAxisAngularVelocityDamp { get; set; }
public FoxBool EnableZAxisxAxisAngularVelocityDamp { get; set; }
public FoxFloat XAxisAngularVelocityDampPower { get; set; }
public FoxFloat ZAxisAngularVelocityDampPower { get; set; }
public FoxBool EnableSteeringWeightBySpeed { get; set; }
public FoxFloat SteeringWeightLowLimitSpeed { get; set; }
public FoxFloat SteeringRotSpeedFactorByMinSpeed { get; set; }
public FoxFloat SteeringWeightHighLimitSpeed { get; set; }
public FoxFloat SteeringRotSpeedFactorByMaxSpeed { get; set; }
public FoxBool EnableSteeringRangeBySpeed { get; set; }
public FoxFloat SteeringRangeLowLimitSpeed { get; set; }
public FoxFloat SteeringRotFactorByMinSpeed { get; set; }
public FoxFloat SteeringRangeHighLimitSpeed { get; set; }
public FoxFloat SteeringRotFactorByMaxSpeed { get; set; }
public FoxBool EnableESC { get; set; }
public FoxFloat EscBrakeMaxAt60 { get; set; }
public FoxFloat EscBrakeRateAt60 { get; set; }
public FoxFloat MaxSpeedReverse { get; set; }
public FoxInt32 MaxBodyLifeValue { get; set; }
public FoxInt32 MaxWheelLifeValue { get; set; }
public FoxFloat MinFallDamageRate { get; set; }
public FoxFloat MaxFallDamageRate { get; set; }
public FoxFloat MinCrashDamageRate { get; set; }
public FoxFloat MaxCrashDamageRate { get; set; }
public FoxFloat HeadLightRange { get; set; }
public FoxFloat HeadLightAngle { get; set; }
public FoxFloat BlastReactionFactor { get; set; }
public List<FoxString> AttachPointNamesAround { get; set; }
public FoxVector3 BasePosOffsetAround { get; set; }
public FoxString AttachPointNamesAroundSub { get; set; }
public FoxVector3 BasePosOffsetAroundSub { get; set; }
public FoxString AttachPointNamesTps { get; set; }
public FoxVector3 BasePosOffsetTps { get; set; }
public FoxString AttachPointNamesTpsSub { get; set; }
public FoxVector3 BasePosOffsetTpsSub { get; set; }
public FoxString AttachPointNamesSubjective { get; set; }
public FoxVector3 BasePosOffsetSubjective { get; set; }
public FoxString AttachPointNamesSubjectiveSub { get; set; }
public FoxVector3 BasePosOffsetSubjectiveSub { get; set; }
public Dictionary<string, FoxInt32> LifeValues { get; set; }
public FoxString FultonConnectPointNames { get; set; }
public FoxFloat TurretRotSpeedFactor { get; set; }
public FoxFloat TurretRotLimitX { get; set; }
public FoxFloat TurretRotMinLimitX { get; set; }
public FoxFloat TurretRotLimitY { get; set; }
public FoxFloat BodyAttackSpeed { get; set; }
public FoxFloat CannonFireInterval { get; set; }
public FoxFloat CannonFireForce { get; set; }
public FoxInt32 TurretLifeMax { get; set; }
public FoxFloat TurretRotSpeedFactorForSubjectiveCamera { get; set; }
}
}
| kkkkyue/FoxTool | FoxTool/Tpp/Classes/TppStrykerDefaultParameter2.cs | C# | mit | 4,865 |
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
// WindowsWeb.h
// Generated from winmd2objc
#pragma once
#include "interopBase.h"
@class WWWebError;
@protocol WWIUriToStreamResolver
, WWIWebErrorStatics;
// Windows.Web.WebErrorStatus
enum _WWWebErrorStatus {
WWWebErrorStatusUnknown = 0,
WWWebErrorStatusCertificateCommonNameIsIncorrect = 1,
WWWebErrorStatusCertificateExpired = 2,
WWWebErrorStatusCertificateContainsErrors = 3,
WWWebErrorStatusCertificateRevoked = 4,
WWWebErrorStatusCertificateIsInvalid = 5,
WWWebErrorStatusServerUnreachable = 6,
WWWebErrorStatusTimeout = 7,
WWWebErrorStatusErrorHttpInvalidServerResponse = 8,
WWWebErrorStatusConnectionAborted = 9,
WWWebErrorStatusConnectionReset = 10,
WWWebErrorStatusDisconnected = 11,
WWWebErrorStatusHttpToHttpsOnRedirection = 12,
WWWebErrorStatusHttpsToHttpOnRedirection = 13,
WWWebErrorStatusCannotConnect = 14,
WWWebErrorStatusHostNameNotResolved = 15,
WWWebErrorStatusOperationCanceled = 16,
WWWebErrorStatusRedirectFailed = 17,
WWWebErrorStatusUnexpectedStatusCode = 18,
WWWebErrorStatusUnexpectedRedirection = 19,
WWWebErrorStatusUnexpectedClientError = 20,
WWWebErrorStatusUnexpectedServerError = 21,
WWWebErrorStatusMultipleChoices = 300,
WWWebErrorStatusMovedPermanently = 301,
WWWebErrorStatusFound = 302,
WWWebErrorStatusSeeOther = 303,
WWWebErrorStatusNotModified = 304,
WWWebErrorStatusUseProxy = 305,
WWWebErrorStatusTemporaryRedirect = 307,
WWWebErrorStatusBadRequest = 400,
WWWebErrorStatusUnauthorized = 401,
WWWebErrorStatusPaymentRequired = 402,
WWWebErrorStatusForbidden = 403,
WWWebErrorStatusNotFound = 404,
WWWebErrorStatusMethodNotAllowed = 405,
WWWebErrorStatusNotAcceptable = 406,
WWWebErrorStatusProxyAuthenticationRequired = 407,
WWWebErrorStatusRequestTimeout = 408,
WWWebErrorStatusConflict = 409,
WWWebErrorStatusGone = 410,
WWWebErrorStatusLengthRequired = 411,
WWWebErrorStatusPreconditionFailed = 412,
WWWebErrorStatusRequestEntityTooLarge = 413,
WWWebErrorStatusRequestUriTooLong = 414,
WWWebErrorStatusUnsupportedMediaType = 415,
WWWebErrorStatusRequestedRangeNotSatisfiable = 416,
WWWebErrorStatusExpectationFailed = 417,
WWWebErrorStatusInternalServerError = 500,
WWWebErrorStatusNotImplemented = 501,
WWWebErrorStatusBadGateway = 502,
WWWebErrorStatusServiceUnavailable = 503,
WWWebErrorStatusGatewayTimeout = 504,
WWWebErrorStatusHttpVersionNotSupported = 505,
};
typedef unsigned WWWebErrorStatus;
#include "WindowsStorageStreams.h"
#include "WindowsFoundation.h"
// Windows.Web.IUriToStreamResolver
#ifndef __WWIUriToStreamResolver_DEFINED__
#define __WWIUriToStreamResolver_DEFINED__
@protocol WWIUriToStreamResolver
- (void)uriToStreamAsync:(WFUri*)uri success:(void (^)(RTObject<WSSIInputStream>*))success failure:(void (^)(NSError*))failure;
@end
#endif // __WWIUriToStreamResolver_DEFINED__
// Windows.Web.WebError
#ifndef __WWWebError_DEFINED__
#define __WWWebError_DEFINED__
WINRT_EXPORT
@interface WWWebError : RTObject
+ (WWWebErrorStatus)getStatus:(int)hresult;
@end
#endif // __WWWebError_DEFINED__
| wanderwaltz/WinObjC | include/Platform/Windows Phone 8.1/UWP/WindowsWeb.h | C | mit | 3,963 |
require 'http/security/parsers/cache_control'
require 'http/security/parsers/content_security_policy'
require 'http/security/parsers/content_security_policy_report_only'
require 'http/security/parsers/expires'
require 'http/security/parsers/pragma'
require 'http/security/parsers/public_key_pins'
require 'http/security/parsers/public_key_pins_report_only'
require 'http/security/parsers/strict_transport_security'
require 'http/security/parsers/set_cookie'
require 'http/security/parsers/public_key_pins'
require 'http/security/parsers/x_content_type_options'
require 'http/security/parsers/x_frame_options'
require 'http/security/parsers/x_permitted_cross_domain_policies'
require 'http/security/parsers/x_xss_protection'
| firebitsbr/http-security | lib/http/security/parsers.rb | Ruby | mit | 724 |
class AddOmniauthToUsers < ActiveRecord::Migration
def change
add_column :users, :provider, :string
execute "UPDATE users SET provider='twitter' WHERE true"
end
end
| pxiventures/vpeeker-channels | db/migrate/20130221113455_add_omniauth_to_users.rb | Ruby | mit | 177 |
/*
License
Copyright (c) 2015 Nathan Cahill
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
(function() {
var global = this
, addEventListener = 'addEventListener'
, removeEventListener = 'removeEventListener'
, getBoundingClientRect = 'getBoundingClientRect'
, isIE8 = global.attachEvent && !global[addEventListener]
, document = global.document
, calc = (function () {
var el
, prefixes = ["", "-webkit-", "-moz-", "-o-"]
for (var i = 0; i < prefixes.length; i++) {
el = document.createElement('div')
el.style.cssText = "width:" + prefixes[i] + "calc(9px)"
if (el.style.length) {
return prefixes[i] + "calc"
}
}
})()
, elementOrSelector = function (el) {
if (typeof el === 'string' || el instanceof String) {
return document.querySelector(el)
} else {
return el
}
}
, Split = function (ids, options) {
var dimension
, i
, clientDimension
, clientAxis
, position
, gutterClass
, paddingA
, paddingB
, pairs = []
// Set defaults
options = typeof options !== 'undefined' ? options : {}
if (!options.gutterSize) options.gutterSize = 10
if (!options.minSize) options.minSize = 100
if (!options.snapOffset) options.snapOffset = 30
if (!options.direction) options.direction = 'horizontal'
if (options.direction == 'horizontal') {
dimension = 'width'
clientDimension = 'clientWidth'
clientAxis = 'clientX'
position = 'left'
gutterClass = 'gutter gutter-horizontal'
paddingA = 'paddingLeft'
paddingB = 'paddingRight'
if (!options.cursor) options.cursor = 'ew-resize'
} else if (options.direction == 'vertical') {
dimension = 'height'
clientDimension = 'clientHeight'
clientAxis = 'clientY'
position = 'top'
gutterClass = 'gutter gutter-vertical'
paddingA = 'paddingTop'
paddingB = 'paddingBottom'
if (!options.cursor) options.cursor = 'ns-resize'
}
// Event listeners for drag events, bound to a pair object.
// Calculate the pair's position and size when dragging starts.
// Prevent selection on start and re-enable it when done.
var startDragging = function (e) {
var self = this
, a = self.a
, b = self.b
if (!self.dragging && options.onDragStart) {
options.onDragStart()
}
e.preventDefault()
self.dragging = true
self.move = drag.bind(self)
self.stop = stopDragging.bind(self)
global[addEventListener]('mouseup', self.stop)
global[addEventListener]('touchend', self.stop)
global[addEventListener]('touchcancel', self.stop)
self.parent[addEventListener]('mousemove', self.move)
self.parent[addEventListener]('touchmove', self.move)
a[addEventListener]('selectstart', preventSelection)
a[addEventListener]('dragstart', preventSelection)
b[addEventListener]('selectstart', preventSelection)
b[addEventListener]('dragstart', preventSelection)
a.style.userSelect = 'none'
a.style.webkitUserSelect = 'none'
a.style.MozUserSelect = 'none'
a.style.pointerEvents = 'none'
b.style.userSelect = 'none'
b.style.webkitUserSelect = 'none'
b.style.MozUserSelect = 'none'
b.style.pointerEvents = 'none'
self.gutter.style.cursor = options.cursor
self.parent.style.cursor = options.cursor
calculateSizes.call(self)
}
, stopDragging = function () {
var self = this
, a = self.a
, b = self.b
if (self.dragging && options.onDragEnd) {
options.onDragEnd()
}
self.dragging = false
global[removeEventListener]('mouseup', self.stop)
global[removeEventListener]('touchend', self.stop)
global[removeEventListener]('touchcancel', self.stop)
self.parent[removeEventListener]('mousemove', self.move)
self.parent[removeEventListener]('touchmove', self.move)
delete self.stop
delete self.move
a[removeEventListener]('selectstart', preventSelection)
a[removeEventListener]('dragstart', preventSelection)
b[removeEventListener]('selectstart', preventSelection)
b[removeEventListener]('dragstart', preventSelection)
a.style.userSelect = ''
a.style.webkitUserSelect = ''
a.style.MozUserSelect = ''
a.style.pointerEvents = ''
b.style.userSelect = ''
b.style.webkitUserSelect = ''
b.style.MozUserSelect = ''
b.style.pointerEvents = ''
self.gutter.style.cursor = ''
self.parent.style.cursor = ''
}
, drag = function (e) {
var offset
if (!this.dragging) return
// Get the relative position of the event from the first side of the
// pair.
if ('touches' in e) {
offset = e.touches[0][clientAxis] - this.start
} else {
offset = e[clientAxis] - this.start
}
// If within snapOffset of min or max, set offset to min or max
if (offset <= this.aMin + options.snapOffset) {
offset = this.aMin
} else if (offset >= this.size - this.bMin - options.snapOffset) {
offset = this.size - this.bMin
}
adjust.call(this, offset)
if (options.onDrag) {
options.onDrag()
}
}
, calculateSizes = function () {
// Calculate the pairs size, and percentage of the parent size
var computedStyle = global.getComputedStyle(this.parent)
, parentSize = this.parent[clientDimension] - parseFloat(computedStyle[paddingA]) - parseFloat(computedStyle[paddingB])
this.size = this.a[getBoundingClientRect]()[dimension] + this.b[getBoundingClientRect]()[dimension] + this.aGutterSize + this.bGutterSize
this.percentage = Math.min(this.size / parentSize * 100, 100)
this.start = this.a[getBoundingClientRect]()[position]
}
, adjust = function (offset) {
// A size is the same as offset. B size is total size - A size.
// Both sizes are calculated from the initial parent percentage.
this.a.style[dimension] = calc + '(' + (offset / this.size * this.percentage) + '% - ' + this.aGutterSize + 'px)'
this.b.style[dimension] = calc + '(' + (this.percentage - (offset / this.size * this.percentage)) + '% - ' + this.bGutterSize + 'px)'
}
, fitMin = function () {
var self = this
, a = self.a
, b = self.b
if (a[getBoundingClientRect]()[dimension] < self.aMin) {
a.style[dimension] = (self.aMin - self.aGutterSize) + 'px'
b.style[dimension] = (self.size - self.aMin - self.aGutterSize) + 'px'
} else if (b[getBoundingClientRect]()[dimension] < self.bMin) {
a.style[dimension] = (self.size - self.bMin - self.bGutterSize) + 'px'
b.style[dimension] = (self.bMin - self.bGutterSize) + 'px'
}
}
, fitMinReverse = function () {
var self = this
, a = self.a
, b = self.b
if (b[getBoundingClientRect]()[dimension] < self.bMin) {
a.style[dimension] = (self.size - self.bMin - self.bGutterSize) + 'px'
b.style[dimension] = (self.bMin - self.bGutterSize) + 'px'
} else if (a[getBoundingClientRect]()[dimension] < self.aMin) {
a.style[dimension] = (self.aMin - self.aGutterSize) + 'px'
b.style[dimension] = (self.size - self.aMin - self.aGutterSize) + 'px'
}
}
, balancePairs = function (pairs) {
for (var i = 0; i < pairs.length; i++) {
calculateSizes.call(pairs[i])
fitMin.call(pairs[i])
}
for (i = pairs.length - 1; i >= 0; i--) {
calculateSizes.call(pairs[i])
fitMinReverse.call(pairs[i])
}
}
, preventSelection = function () { return false }
, parent = elementOrSelector(ids[0]).parentNode
if (!options.sizes) {
var percent = 100 / ids.length
options.sizes = []
for (i = 0; i < ids.length; i++) {
options.sizes.push(percent)
}
}
if (!Array.isArray(options.minSize)) {
var minSizes = []
for (i = 0; i < ids.length; i++) {
minSizes.push(options.minSize)
}
options.minSize = minSizes
}
for (i = 0; i < ids.length; i++) {
var el = elementOrSelector(ids[i])
, isFirst = (i == 1)
, isLast = (i == ids.length - 1)
, size
, gutterSize = options.gutterSize
, pair
if (i > 0) {
pair = {
a: elementOrSelector(ids[i - 1]),
b: el,
aMin: options.minSize[i - 1],
bMin: options.minSize[i],
dragging: false,
parent: parent,
isFirst: isFirst,
isLast: isLast,
direction: options.direction
}
// For first and last pairs, first and last gutter width is half.
pair.aGutterSize = options.gutterSize
pair.bGutterSize = options.gutterSize
if (isFirst) {
pair.aGutterSize = options.gutterSize / 2
}
if (isLast) {
pair.bGutterSize = options.gutterSize / 2
}
}
// IE9 and above
if (!isIE8) {
if (i > 0) {
var gutter = document.createElement('div')
gutter.className = gutterClass
gutter.style[dimension] = options.gutterSize + 'px'
gutter[addEventListener]('mousedown', startDragging.bind(pair))
gutter[addEventListener]('touchstart', startDragging.bind(pair))
parent.insertBefore(gutter, el)
pair.gutter = gutter
}
if (i === 0 || i == ids.length - 1) {
gutterSize = options.gutterSize / 2
}
if (typeof options.sizes[i] === 'string' || options.sizes[i] instanceof String) {
size = options.sizes[i]
} else {
size = calc + '(' + options.sizes[i] + '% - ' + gutterSize + 'px)'
}
// IE8 and below
} else {
if (typeof options.sizes[i] === 'string' || options.sizes[i] instanceof String) {
size = options.sizes[i]
} else {
size = options.sizes[i] + '%'
}
}
el.style[dimension] = size
if (i > 0) {
pairs.push(pair)
}
}
balancePairs(pairs)
}
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = Split
}
exports.Split = Split
} else {
global.Split = Split
}
}).call(window)
| simonmysun/praxis | web.playground/assets/split.js | JavaScript | mit | 12,670 |
import * as React from 'react'
import { ValueLine } from '@framework/Lines'
import { TypeContext } from '@framework/TypeContext'
import { ScheduleRuleMinutelyEntity } from '../Signum.Entities.Scheduler'
export default function ScheduleRuleMinutely(p : { ctx: TypeContext<ScheduleRuleMinutelyEntity> }){
const ctx4 = p.ctx.subCtx({ labelColumns: { sm: 2 } });
return (
<div>
<ValueLine ctx={ctx4.subCtx(f => f.startingOn)} />
<ValueLine ctx={ctx4.subCtx(f => f.eachMinutes)} />
</div>
);
}
| MehdyKarimpour/extensions | Signum.React.Extensions/Scheduler/Templates/ScheduleRuleMinutely.tsx | TypeScript | mit | 534 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JF\GeneratorBundle\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use JF\GeneratorBundle\Command\Helper\DialogHelper;
use JF\GeneratorBundle\Generator\DoctrineCrudGenerator;
use JF\GeneratorBundle\Generator\DoctrineFormGenerator;
use JF\GeneratorBundle\Manipulator\RoutingManipulator;
/**
* Generates a CRUD for a Doctrine entity.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class GenerateDoctrineCrudCommand extends GenerateDoctrineCommand
{
private $formGenerator;
/**
* @see Command
*/
protected function configure()
{
$this
->setDefinition(array(
new InputOption('entity', '', InputOption::VALUE_REQUIRED, 'The entity class name to initialize (shortcut notation)'),
new InputOption('route-prefix', '', InputOption::VALUE_REQUIRED, 'The route prefix'),
new InputOption('with-write', '', InputOption::VALUE_NONE, 'Whether or not to generate create, new and delete actions'),
new InputOption('with-show', '', InputOption::VALUE_NONE, 'Whether or not to generate show actions'),
new InputOption('with-delete', '', InputOption::VALUE_NONE, 'Whether or not to generate delete actions'),
new InputOption('format', '', InputOption::VALUE_REQUIRED, 'Use the format for configuration files (php, xml, yml, or annotation)', 'annotation'),
new InputOption('overwrite', '', InputOption::VALUE_NONE, 'Do not stop the generation if crud controller already exist, thus overwriting all generated files'),
))
->setDescription('Generates a CRUD based on a Doctrine entity')
->setHelp(<<<EOT
The <info>doctrine:generate:crud</info> command generates a CRUD based on a Doctrine entity.
The default command only generates the list and show actions.
<info>php app/console doctrine:generate:crud --entity=AcmeBlogBundle:Post --route-prefix=post_admin</info>
Using the --with-write option allows to generate the new, edit and delete actions.
<info>php app/console doctrine:generate:crud --entity=AcmeBlogBundle:Post --route-prefix=post_admin --with-write</info>
Every generated file is based on a template. There are default templates but they can be overriden by placing custom templates in one of the following locations, by order of priority:
<info>BUNDLE_PATH/Resources/JFGeneratorBundle/skeleton/crud
APP_PATH/Resources/JFGeneratorBundle/skeleton/crud</info>
And
<info>__bundle_path__/Resources/JFGeneratorBundle/skeleton/form
__project_root__/app/Resources/JFGeneratorBundle/skeleton/form</info>
EOT
)
->setName('jf:generate:crud')
->setAliases(array('jf:doctrine:crud'))
;
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$dialog = $this->getDialogHelper();
if ($input->isInteractive()) {
if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you confirm generation', 'yes', '?'), true)) {
$output->writeln('<error>Command aborted</error>');
return 1;
}
}
$entity = Validators::validateEntityName($input->getOption('entity'));
list($bundle, $entity) = $this->parseShortcutNotation($entity);
$format = Validators::validateFormat($input->getOption('format'));
$prefix = $this->getRoutePrefix($input, $entity);
$withWrite = $input->getOption('with-write');
$withShow = $input->getOption('with-show');
$withDelete = $input->getOption('with-delete');
$forceOverwrite = $input->getOption('overwrite');
$dialog->writeSection($output, 'CRUD generation');
$entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle).'\\'.$entity;
$metadata = $this->getEntityMetadata($entityClass);
$bundle = $this->getContainer()->get('kernel')->getBundle($bundle);
$generator = $this->getGenerator($bundle);
$generator->generate($bundle, $entity, $metadata[0], $format, $prefix, $withWrite, $withShow, $withDelete, $forceOverwrite);
$output->writeln('Generating the CRUD code: <info>OK</info>');
$errors = array();
$runner = $dialog->getRunner($output, $errors);
// form
if ($withWrite) {
$this->generateForm($bundle, $entity, $metadata);
$output->writeln('Generating the Form code: <info>OK</info>');
}
// routing
if ('annotation' != $format) {
$runner($this->updateRouting($dialog, $input, $output, $bundle, $format, $entity, $prefix));
}
$dialog->writeGeneratorSummary($output, $errors);
}
protected function interact(InputInterface $input, OutputInterface $output)
{
$dialog = $this->getDialogHelper();
$dialog->writeSection($output, 'Welcome to the Doctrine2 CRUD generator');
// namespace
$output->writeln(array(
'',
'This command helps you generate CRUD controllers and templates.',
'',
'First, you need to give the entity for which you want to generate a CRUD.',
'You can give an entity that does not exist yet and the wizard will help',
'you defining it.',
'',
'You must use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>.',
'',
));
$entity = $dialog->askAndValidate($output, $dialog->getQuestion('The Entity shortcut name', $input->getOption('entity')), array('JF\GeneratorBundle\Command\Validators', 'validateEntityName'), false, $input->getOption('entity'));
$input->setOption('entity', $entity);
list($bundle, $entity) = $this->parseShortcutNotation($entity);
// write?
$withWrite = $input->getOption('with-write') ?: false;
$output->writeln(array(
'',
'By default, the generator creates two actions: list and show.',
'You can also ask it to generate "write" actions: new and update.',
'',
));
$withWrite = $dialog->askConfirmation($output, $dialog->getQuestion('Do you want to generate the "write" actions', $withWrite ? 'yes' : 'no', '?'), $withWrite);
$input->setOption('with-write', $withWrite);
// show?
$withShow = $input->getOption('with-show') ?: false;
$output->writeln(array(
'',
'By default, the generator creates two actions: list and show.',
'You can also ask it to generate "show" actions: show.',
'',
));
$withShow = $dialog->askConfirmation($output, $dialog->getQuestion('Do you want to generate the "show" actions', $withShow ? 'yes' : 'no', '?'), $withShow);
$input->setOption('with-show', $withShow);
// delete?
$withDelete = $input->getOption('with-delete') ?: false;
$output->writeln(array(
'',
'By default, the generator creates two actions: list and show.',
'You can also ask it to generate "delete" actions: delete.',
'',
));
$withDelete = $dialog->askConfirmation($output, $dialog->getQuestion('Do you want to generate the "delete" actions', $withDelete ? 'yes' : 'no', '?'), $withDelete);
$input->setOption('with-delete', $withDelete);
// format
$format = $input->getOption('format');
$output->writeln(array(
'',
'Determine the format to use for the generated CRUD.',
'',
));
$format = $dialog->askAndValidate($output, $dialog->getQuestion('Configuration format (yml, xml, php, or annotation)', $format), array('JF\GeneratorBundle\Command\Validators', 'validateFormat'), false, $format);
$input->setOption('format', $format);
// route prefix
$prefix = $this->getRoutePrefix($input, $entity);
$output->writeln(array(
'',
'Determine the routes prefix (all the routes will be "mounted" under this',
'prefix: /prefix/, /prefix/new, ...).',
'',
));
$prefix = $dialog->ask($output, $dialog->getQuestion('Routes prefix', '/'.$prefix), '/'.$prefix);
$input->setOption('route-prefix', $prefix);
// summary
$output->writeln(array(
'',
$this->getHelper('formatter')->formatBlock('Summary before generation', 'bg=blue;fg=white', true),
'',
sprintf("You are going to generate a CRUD controller for \"<info>%s:%s</info>\"", $bundle, $entity),
sprintf("using the \"<info>%s</info>\" format.", $format),
'',
));
}
/**
* Tries to generate forms if they don't exist yet and if we need write operations on entities.
*/
protected function generateForm($bundle, $entity, $metadata)
{
try {
$this->getFormGenerator($bundle)->generate($bundle, $entity, $metadata[0]);
} catch (\RuntimeException $e ) {
// form already exists
}
}
protected function updateRouting(DialogHelper $dialog, InputInterface $input, OutputInterface $output, BundleInterface $bundle, $format, $entity, $prefix)
{
$auto = true;
if ($input->isInteractive()) {
$auto = $dialog->askConfirmation($output, $dialog->getQuestion('Confirm automatic update of the Routing', 'yes', '?'), true);
}
$output->write('Importing the CRUD routes: ');
$this->getContainer()->get('filesystem')->mkdir($bundle->getPath().'/Resources/config/');
$routing = new RoutingManipulator($bundle->getPath().'/Resources/config/routing.yml');
try {
$ret = $auto ? $routing->addResource($bundle->getName(), $format, '/'.$prefix, 'routing/'.strtolower(str_replace('\\', '_', $entity))) : false;
} catch (\RuntimeException $exc) {
$ret = false;
}
if (!$ret) {
$help = sprintf(" <comment>resource: \"@%s/Resources/config/routing/%s.%s\"</comment>\n", $bundle->getName(), strtolower(str_replace('\\', '_', $entity)), $format);
$help .= sprintf(" <comment>prefix: /%s</comment>\n", $prefix);
return array(
'- Import the bundle\'s routing resource in the bundle routing file',
sprintf(' (%s).', $bundle->getPath().'/Resources/config/routing.yml'),
'',
sprintf(' <comment>%s:</comment>', $bundle->getName().('' !== $prefix ? '_'.str_replace('/', '_', $prefix) : '')),
$help,
'',
);
}
}
protected function getRoutePrefix(InputInterface $input, $entity)
{
$prefix = $input->getOption('route-prefix') ?: strtolower(str_replace(array('\\', '/'), '_', $entity));
if ($prefix && '/' === $prefix[0]) {
$prefix = substr($prefix, 1);
}
return $prefix;
}
protected function createGenerator($bundle = null)
{
return new DoctrineCrudGenerator($this->getContainer()->get('filesystem'));
}
protected function getFormGenerator($bundle = null)
{
if (null === $this->formGenerator) {
$this->formGenerator = new DoctrineFormGenerator($this->getContainer()->get('filesystem'));
$this->formGenerator->setSkeletonDirs($this->getSkeletonDirs($bundle));
}
return $this->formGenerator;
}
public function setFormGenerator(DoctrineFormGenerator $formGenerator)
{
$this->formGenerator = $formGenerator;
}
}
| jf-sysyem/wsp-sf2 | src/JF/GeneratorBundle/Command/GenerateDoctrineCrudCommand.php | PHP | mit | 12,226 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ASPNET_Core_1_0.Models.AccountViewModels
{
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}
| huang6349/inspinia | ASPNET_Core_1_0_Seed_Project/ASPNET_Core_1_0/Models/AccountViewModels/RegisterViewModel.cs | C# | mit | 869 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template weighted_pot_quantile_prob</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.pot_quantile_hpp" title="Header <boost/accumulators/statistics/pot_quantile.hpp>">
<link rel="prev" href="weighted_pot_quantile.html" title="Struct template weighted_pot_quantile">
<link rel="next" href="../as_feature_tag_po_id567301.html" title="Struct template as_feature<tag::pot_quantile< LeftRight >(with_threshold_value)>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="weighted_pot_quantile.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.pot_quantile_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../as_feature_tag_po_id567301.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.accumulators.tag.weighted_pot_quantile_prob"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template weighted_pot_quantile_prob</span></h2>
<p>boost::accumulators::tag::weighted_pot_quantile_prob</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.pot_quantile_hpp" title="Header <boost/accumulators/statistics/pot_quantile.hpp>">boost/accumulators/statistics/pot_quantile.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> LeftRight<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="weighted_pot_quantile_prob.html" title="Struct template weighted_pot_quantile_prob">weighted_pot_quantile_prob</a> <span class="special">:</span> <span class="keyword">public</span> boost::accumulators::depends_on< weighted_peaks_over_threshold_prob< LeftRight > >
<span class="special">{</span>
<span class="special">}</span><span class="special">;</span></pre></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005, 2006 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="weighted_pot_quantile.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.pot_quantile_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../as_feature_tag_po_id567301.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| djsedulous/namecoind | libs/boost_1_50_0/doc/html/boost/accumulators/tag/weighted_pot_quantile_prob.html | HTML | mit | 4,511 |
nested/ | Flet/acetate | test/pretty-urls/expected/nested/index.html | HTML | mit | 7 |
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\File\Test\Unit\Transfer\Adapter;
use \Magento\Framework\File\Transfer\Adapter\Http;
class HttpTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Framework\HTTP\PhpEnvironment\Response|\PHPUnit_Framework_MockObject_MockObject
*/
private $response;
/**
* @var Http|\PHPUnit_Framework_MockObject_MockObject
*/
private $object;
/**
* @var \Magento\Framework\File\Mime|\PHPUnit_Framework_MockObject_MockObject
*/
private $mime;
protected function setUp()
{
$this->response = $this->getMock(
'\Magento\Framework\HTTP\PhpEnvironment\Response',
['setHeader', 'sendHeaders'],
[],
'',
false
);
$this->mime = $this->getMock('Magento\Framework\File\Mime');
$this->object = new Http($this->response, $this->mime);
}
public function testSend()
{
$file = __DIR__ . '/../../_files/javascript.js';
$contentType = 'content/type';
$this->response->expects($this->at(0))
->method('setHeader')
->with('Content-length', filesize($file));
$this->response->expects($this->at(1))
->method('setHeader')
->with('Content-Type', $contentType);
$this->response->expects($this->once())
->method('sendHeaders');
$this->mime->expects($this->once())
->method('getMimeType')
->with($file)
->will($this->returnValue($contentType));
$this->expectOutputString(file_get_contents($file));
$this->object->send($file);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Filename is not set
*/
public function testSendNoFileSpecifiedException()
{
$this->object->send([]);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage File 'nonexistent.file' does not exists
*/
public function testSendNoFileExistException()
{
$this->object->send('nonexistent.file');
}
}
| j-froehlich/magento2_wk | vendor/magento/framework/File/Test/Unit/Transfer/Adapter/HttpTest.php | PHP | mit | 2,250 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>CivilOctave: amarjeet@lab.gdy.club/latex/views_8py_source.tex File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CivilOctave
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Packages</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_5df9b5f8191c445162897bbb77f834f4.html">amarjeet@lab.gdy.club</a></li><li class="navelem"><a class="el" href="dir_e3923da6aed9fa80cf949700f8d38e48.html">latex</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">views_8py_source.tex File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><a href="amarjeet_0Dlab_8gdy_8club_2latex_2views__8py__source_8tex_source.html">Go to the source code of this file.</a></p>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Dec 18 2015 16:53:12 for CivilOctave by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| GreatDevelopers/CivilOctave | Documentation/html/amarjeet_0Dlab_8gdy_8club_2latex_2views__8py__source_8tex.html | HTML | mit | 2,530 |
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* @category Phoenix
* @package Phoenix_Moneybookers
* @copyright Copyright (c) 2016 Phoenix Medien GmbH & Co. KG (http://www.phoenix-medien.de)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
Event.observe(window, 'load', function() {
initMoneybookers();
});
Moneybookers = Class.create();
Moneybookers.prototype = {
initialize: function(bannerUrl, activateemailUrl, checksecretUrl, checkemailUrl){
this.bannerUrl = bannerUrl;
this.activateemailUrl = activateemailUrl;
this.checksecretUrl = checksecretUrl;
this.checkemailUrl = checkemailUrl;
this.txtBtnStatus0 = this.translate('Validate Email');
this.txtBtnStatus1 = this.translate('Activate Moneybookers Quick Checkout');
this.txtBtnStatus2 = this.translate('Validate Secret Word');
this.txtErrStatus0 = this.translate('This email address is not registered.');
this.txtErrStatus2 = this.translate('This Secret Word is incorrect. After activation Moneybookers will give you access to a new section in your Moneybookers account called "Merchant tools". Please choose a secret word (do not use your password for this) and provide it in your Moneybookers admin area and above.');
this.txtInfStatus0 = this.translate('<strong><a href="http://www.moneybookers.com/" target="_blank">Moneybookers</a></strong> is an all in one payments solution that enables a merchant to accept debit and credit card payments, bank transfers and the largest range of local payments directly on your website.<ul style="list-style-position: inside;list-style-type: disc;"><li>Widest network of international and local payment options in the world.</li><li>One interface including payments, banking and marketing.</li><li>Direct payments without the need for direct registration.</li><li>Moneybookers stands for a highly converting payment gateway that turns payment processing into a simple, fast and customer friendly operation.</li><li>Highly competitive rates. Please <a href="http://www.moneybookers.com/app/help.pl?s=m_fees" target="_blank">click here</a> for more detailed information.</li></ul>') + '<img src="' + this.bannerUrl + '" alt="" />';
this.txtInfStatus1 = this.translate('<strong>Moneybookers Quick Checkout</strong> enables you to take <strong>direct</strong> payments from credit cards, debit cards and over 50 other local payment options in over 200 countries for customers without an existing Moneybookers eWallet.');
this.txtNotSavechanges = this.translate('Please save the configuration before continuing.');
this.txtNotStatus0 = this.translate('Email was validated by Moneybookers.');
this.txtNotStatus1 = this.translate('Activation email was sent to Moneybookers. Please be aware that the verification process to use Moneybookers Quick Checkout takes some time. You will be contacted by Moneybookers when the verification process has been completed.');
this.txtNotStatus2 = this.translate('Secret Word was validated by Moneybookers. Your installation is completed and you are ready to receive international and local payments.');
$("moneybookers_settings_moneybookers_email").setAttribute("onchange", "moneybookers.setStatus(0); moneybookers.changeUi(); document.getElementById('moneybookers_settings_customer_id').value = ''; document.getElementById('moneybookers_settings_customer_id_hidden').value = '';");
$("moneybookers_settings_customer_id").disabled = true;
$("moneybookers_settings_customer_id_hidden").name = document.getElementById("moneybookers_settings_customer_id").name;
$("moneybookers_settings_customer_id_hidden").value = document.getElementById("moneybookers_settings_customer_id").value;
$("moneybookers_settings_secret_key").setAttribute("onchange", "moneybookers.setStatus(2); moneybookers.changeUi();");
if (this.isStoreView()) {
this.infoOrig = {
email: $("moneybookers_settings_moneybookers_email").value,
customerId: $("moneybookers_settings_customer_id").value,
key: $("moneybookers_settings_secret_key").value,
status: this.getStatus(),
useDefult: $("moneybookers_settings_moneybookers_email_inherit").checked
};
var defaults = $$("#row_moneybookers_settings_customer_id .use-default, #row_moneybookers_settings_secret_key .use-default, #row_moneybookers_settings_activationstatus .use-default");
if (Object.isArray(defaults)) {
for (var i=0; i<defaults.length; i++) {
defaults[i].hide();
}
}
$("moneybookers_settings_moneybookers_email_inherit").setAttribute("onchange", "moneybookers.changeStore();");
}
this.changeUi();
},
translate: function(text) {
try {
if(Translator){
return Translator.translate(text);
}
}
catch(e){}
return text;
},
button: function () {
var status, response, result;
status = this.getStatus();
if (status < 1) {
response = this.getHttp(this.checkemailUrl + "?email=" + $("moneybookers_settings_moneybookers_email").value);
result = response.split(',');
if (result[0] == "OK") {
$("moneybookers_settings_customer_id").value = result[1];
$("moneybookers_settings_customer_id_hidden").value = result[1];
this.setStatus(1);
status = 1;
alert(this.txtNotStatus0);
}
else {
$("moneybookers_settings_customer_id").value = "";
alert(this.txtErrStatus0 + "\n("+response+")");
}
}
if (status == 1) {
this.getHttp(this.activateemailUrl);
this.setStatus(2);
alert(this.txtNotStatus1);
this.alertSaveChanges();
}
if (status == 2) {
response = this.getHttp(this.checksecretUrl + "?email=" + $("moneybookers_settings_moneybookers_email").value
+ "&secret=" + $("moneybookers_settings_secret_key").value
+ "&cust_id=" + $("moneybookers_settings_customer_id").value);
if (response == "OK") {
this.setStatus(3);
alert(this.txtNotStatus2);
this.alertSaveChanges();
}
else {
alert(this.txtErrStatus2 + "\n("+response+")");
}
}
},
alertSaveChanges: function () {
$("moneybookers_multifuncbutton").style.display = "none";
alert(this.txtNotSavechanges);
},
getHttp: function (url) {
var response;
new Ajax.Request(
url,
{
method: "get",
onComplete: function(transport) {response = transport.responseText;},
asynchronous: false
});
return response;
},
getInteger: function (number) {
number = parseInt(number);
if (isNaN(number)) return 0;
return number;
},
getStatus: function () {
var status = this.getInteger($("moneybookers_settings_activationstatus").value);
if (status == 1 && $("moneybookers_settings_customer_id").value != '' && $("moneybookers_settings_secret_key").value == '') {
status = 2;
this.setStatus(status);
}
return status;
},
setStatus: function (number) {
number = this.getInteger(number);
if (number < 0) number = 0;
else if (number > 3) number = 3;
$("moneybookers_settings_activationstatus").value = number;
},
changeUi: function () {
var status = this.getStatus();
if (status < 1) {
$("moneybookers_inf_div").update(this.txtInfStatus0);
$("moneybookers_multifuncbutton_label").update(this.txtBtnStatus0);
}
if (status == 1) {
$("moneybookers_inf_div").update(this.txtInfStatus1);
$("moneybookers_multifuncbutton_label").update(this.txtBtnStatus1);
}
if (status < 2) {
$("moneybookers_inf_div").style.display = "block";
$("moneybookers_settings_secret_key").disabled = true;
}
if (status == 2) {
$("moneybookers_multifuncbutton_label").update(this.txtBtnStatus2);
if (this.isStoreView()) {
$("moneybookers_settings_secret_key").enable();
$("moneybookers_settings_secret_key_inherit").removeAttribute('checked');
}
}
if (status > 2) {
$("moneybookers_multifuncbutton").style.display = "none";
} else {
$("moneybookers_multifuncbutton").style.display = "block";
}
},
changeStore: function () {
if (!$("moneybookers_settings_moneybookers_email_inherit").checked) {
if (this.infoOrig.useDefult) {
$("moneybookers_settings_customer_id_inherit").click();
$("moneybookers_settings_customer_id").clear();
$("moneybookers_settings_secret_key_inherit").click();
$("moneybookers_settings_secret_key").clear();
$("moneybookers_settings_activationstatus_inherit").click();
this.setStatus(0);
}
}
else {
if (this.infoOrig.useDefult) {
$("moneybookers_settings_customer_id").setValue(this.infoOrig.customerId);
$("moneybookers_settings_customer_id_inherit").click();
$("moneybookers_settings_secret_key").setValue(this.infoOrig.key);
$("moneybookers_settings_secret_key_inherit").click();
$("moneybookers_settings_activationstatus_inherit").click();
this.setStatus(this.infoOrig.status);
}
}
this.changeUi();
},
isStoreView: function() {
return $("moneybookers_settings_moneybookers_email_inherit") != undefined;
}
};
| JaroslawZielinski/magento-backendo | js/mage/adminhtml/moneybookers.js | JavaScript | mit | 10,668 |
require File.expand_path('../spec_helper', __FILE__)
class FakeCore < Consular::Core
def self.valid_system?
true
end
def process!; puts('process'); end
def setup!; puts('setup'); end
end
describe Consular::CLI do
before do
@template = File.read File.expand_path('../../lib/templates/example.yml.tt', __FILE__)
FakeFS.activate!
FileUtils.mkdir_p Consular.global_path
end
after do
FakeFS.deactivate!
Consular.instance_variable_set(:@global_path, nil)
end
it "displays help" do
output = capture_io { Consular::CLI.start ['-h'] }.join('')
assert_match /start \[PROJECT\]/, output
assert_match /init/, output
assert_match /edit \[PROJECT\]/, output
end
it "lists out all global scripts" do
File.open(Consular.global_path('foo.yml'), "w") { |f| f.puts @template }
File.open(Consular.global_path('bar.term'), "w") { |f| f.puts @template }
File.open(Consular.global_path('bar.term~'), "w") { |f| f.puts @template }
output = capture_io { Consular::CLI.start ['list'] }.join('')
assert_match /foo\.yml - COMMENT OF SCRIPT HERE/, output
assert_match /bar - COMMENT OF SCRIPT HERE/, output
refute_match /bar\.term - COMMENT OF SCRIPT HERE/, output
refute_match /bar\.term~/, output
end
describe "start command" do
before do
FileUtils.mkdir_p '/tmp'
FileUtils.touch '/tmp/Termfile'
FileUtils.touch Consular.global_path('foo.term')
FileUtils.touch Consular.global_path('foo.yml')
Consular.instance_variable_set(:@cores,[])
Consular.add_core FakeCore
end
after do
Consular.instance_variable_set(:@cores,[])
end
it "should start a Termfile" do
output = capture_io { Consular::CLI.start ['start', '-r=/tmp'] }.join('')
assert_match /process/, output
end
it "should start a global term script" do
output = capture_io { Consular::CLI.start ['start', 'foo'] }.join('')
assert_match /process/, output
end
it "should start a global yaml script" do
output = capture_io { Consular::CLI.start ['start', 'foo.yml'] }.join('')
assert_match /process/, output
end
it "should return an error message if it doesn't exist" do
output = capture_io { Consular::CLI.start ['start', 'barr'] }.join('')
assert_match /does not exist/, output
end
it "should SystemExit if no core can be found" do
Consular.instance_variable_set(:@cores,[])
assert_raises SystemExit do
capture_io { Consular::CLI.start ['start', 'foo'] }.join('')
end
end
it "should bring up a core selection if more than one matching core" do
Consular::CLI.any_instance.expects(:core_selection).with(anything).returns(FakeCore)
Consular.add_core FakeCore
Consular.add_core FakeCore
assert capture_io { Consular::CLI.start ['start', 'foo'] }.join('')
end
end
describe "setup command" do
before do
FileUtils.mkdir_p '/tmp'
FileUtils.touch '/tmp/Termfile'
FileUtils.touch Consular.global_path('foo.term')
FileUtils.touch Consular.global_path('foo.yml')
Consular.instance_variable_set(:@cores,[])
Consular.add_core FakeCore
end
after do
Consular.instance_variable_set(:@cores,[])
end
it "should setup a Termfile" do
output = capture_io { Consular::CLI.start ['setup', '-r=/tmp'] }.join('')
assert_match /setup/, output
end
it "should setup a global term script" do
output = capture_io { Consular::CLI.start ['setup', 'foo'] }.join('')
assert_match /setup/, output
end
it "should setup a global yaml script" do
output = capture_io { Consular::CLI.start ['setup', 'foo.yml'] }.join('')
assert_match /setup/, output
end
it "should return an error message if it doesn't exist" do
output = capture_io { Consular::CLI.start ['setup', 'barr'] }.join('')
assert_match /does not exist/, output
end
it "should SystemExit if no core can be found" do
Consular.instance_variable_set(:@cores,[])
assert_raises SystemExit do
capture_io { Consular::CLI.start ['setup', 'foo'] }.join('')
end
end
it "should bring up a core selection if more than one matching core" do
Consular::CLI.any_instance.expects(:core_selection).with(anything).returns(FakeCore)
Consular.add_core FakeCore
Consular.add_core FakeCore
assert capture_io { Consular::CLI.start ['setup', 'foo'] }.join('')
end
end
it "init creates a new global script directory and consularc" do
FileUtils.rm_rf Consular.global_path
capture_io { Consular::CLI.start ['init'] }.join('')
assert File.exists?(Consular.global_path), "global script directory exists"
end
describe "delete command" do
it "removes Termfile" do
FileUtils.mkdir_p '/tmp/sample_project'
FileUtils.touch "/tmp/sample_project/Termfile"
capture_io { Consular::CLI.start ['delete',"-r=/tmp/sample_project"] }
refute File.exists?("/tmp/sample_project/Termfile"), 'deletes Termfile'
end
it "removes .yml files" do
FileUtils.touch Consular.global_path('foo.yml')
capture_io { Consular::CLI.start ['delete','foo.yml'] }
refute File.exists?(Consular.global_path('foo.yml')), 'deletes .yml files'
end
it "removes .term file" do
FileUtils.touch Consular.global_path('delete_this.term')
capture_io { Consular::CLI.start ['delete','delete_this'] }
refute File.exists?(Consular.global_path('delete_this.term')), 'deletes .term file'
end
it "removes .term file" do
output = capture_io { Consular::CLI.start ['delete','barr'] }.join('')
assert_match /does not exist/, output
end
end
describe "edit command" do
before do
FakeFS.deactivate!
@path = File.join ENV['HOME'], '.config', 'consular'
@yaml = File.join @path, 'foobar.yml'
@term = File.join @path, 'foobar.term'
`rm -f #{@yaml}`
`rm -f #{@term}`
`rm -f /tmp/Termfile`
end
after do
`rm -f #{@yaml}`
`rm -f #{@term}`
`rm -f /tmp/Termfile`
end
it "edits yaml files" do
FakeFS.deactivate!
Consular::CLI.any_instance.expects(:open_in_editor).with(@yaml, nil).returns(true)
output = capture_io { Consular::CLI.start ['edit', 'foobar.yml'] }.join('')
assert_match /create/, output
assert_match /foobar\.yml/, output
assert_match /- tab1/, File.read(@yaml)
end
it "edits .term file" do
FakeFS.deactivate!
Consular::CLI.any_instance.expects(:open_in_editor).with(@term, nil).returns(true)
output = capture_io { Consular::CLI.start ['edit', 'foobar'] }.join('')
assert_match /create/, output
assert_match /foobar\.term/, output
assert_match /setup/, File.read(@term)
end
it "edits a Termfile" do
FakeFS.deactivate!
Consular::CLI.any_instance.expects(:open_in_editor).with('/tmp/Termfile', nil).returns(true)
output = capture_io { Consular::CLI.start ['edit', '-r=/tmp'] }.join('')
assert_match /create/, output
assert_match /Termfile/, output
assert_match /setup/, File.read('/tmp/Termfile')
end
it "alias create" do
FakeFS.deactivate!
Consular::CLI.any_instance.expects(:open_in_editor).with('/tmp/Termfile', nil).returns(true)
output = capture_io { Consular::CLI.start ['create', '-r=/tmp'] }.join('')
assert_match /create/, output
assert_match /Termfile/, output
assert_match /setup/, File.read('/tmp/Termfile')
end
end
end
| achiu/terminitor | spec/cli_spec.rb | Ruby | mit | 7,729 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumDEG.Models {
public class Option {
public string OptionText { get; set; }
public bool IsSelected { get; set; }
}
}
| MarianaPicolo/2017.1-Forum-Coordenadores-DEG | ForumDEG/ForumDEG/Models/Option.cs | C# | mit | 274 |
<!DOCTYPE html> <html> <head> <title>demo for colorpick</title> <meta charset="utf-8" /> </head> <body> <script src="./pp_colorpick.js?ef6dab06b2171af0d3aca52ebb21ece3" type="text/javascript"></script> </body> </html> | genify/toolkit | test/ui/pub/colorpick.html | HTML | mit | 217 |
#include <math.h>
double mysqrt(double x) {
#if defined (HAVE_LOG) && defined (HAVE_EXP)
return exp(log(x)*.5);
#else //Define the sqrt function another way
return sqrt(x);
#endif
}
| zwimer/IntroToOpenSourceLabs | Lab5/Steps/Step5/MathFunctions/mysqrt.cpp | C++ | mit | 186 |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M20 4H4v13.17L5.17 16H20V4zm-6 10H6v-2h8v2zm4-3H6V9h12v2zm0-3H6V6h12v2z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M20 18c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14zm-16-.83V4h16v12H5.17L4 17.17zM6 12h8v2H6zm0-3h12v2H6zm0-3h12v2H6z"
}, "1")], 'ChatTwoTone'); | oliviertassinari/material-ui | packages/mui-icons-material/lib/esm/ChatTwoTone.js | JavaScript | mit | 464 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace BrowseDotNet.Web.Models
{
public class LoginViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
} | chsakell/browsedotnet | BrowseDotNet.Web/Models/AccountViewModels.cs | C# | mit | 1,182 |
package com.acework.js.components.bootstrap
import com.acework.js.components.bootstrap.Utils._
import com.acework.js.utils.{Mappable, Mergeable}
import japgolly.scalajs.react.Addons.ReactCloneWithProps
import japgolly.scalajs.react.Ref
import scala.scalajs.js
/**
* Created by weiyin on 11/03/15.
*/
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import scala.scalajs.js.{UndefOr, undefined}
object DropdownButton extends BootstrapComponent {
override type P = DropdownButton
override type S = DropdownState
override type B = Backend
override type N = TopNode
override def defaultProps: P = DropdownButton()
case class DropdownButton(
/*== start react bootstraps ==*/
id: UndefOr[String] = undefined,
pullRight: UndefOr[Boolean] = undefined,
dropup: UndefOr[Boolean] = undefined,
title: UndefOr[ReactNode] = undefined,
href: UndefOr[String] = undefined,
eventKey: UndefOr[String] = undefined,
navItem: UndefOr[Boolean] = undefined,
noCaret: UndefOr[Boolean] = undefined,
onClick: () => Unit = () => (),
onSelect: UndefOr[(String) => Unit] = undefined,
/*== end react bootstraps ==*/
bsClass: UndefOr[Classes.Value] = Classes.btn,
bsStyle: UndefOr[Styles.Value] = Styles.default,
bsSize: UndefOr[Sizes.Value] = undefined,
addClasses: String = "")
extends BsProps with MergeableProps[DropdownButton] {
def merge(t: Map[String, Any]): DropdownButton = implicitly[Mergeable[DropdownButton]].merge(this, t)
def asMap: Map[String, Any] = implicitly[Mappable[DropdownButton]].toMap(this)
def apply(children: ReactNode*) = component(this, children)
def apply() = component(this)
}
class Backend(val scope: BackendScope[DropdownButton, DropdownState]) extends DropdownStateMixin[DropdownButton] {
def handleOptionSelect(key: String): Unit = {
if (scope.props.onSelect.isDefined)
scope.props.onSelect.get(key)
}
def handleDropdownClick(e: ReactEvent) = {
e.preventDefault()
setDropdownState(!scope.state.open)
}
}
override val component = ReactComponentB[DropdownButton]("DropdownButton")
.initialState(DropdownState(open = false))
.backend(new Backend(_))
.render((P, C, S, B) => {
def renderButtonGroup(children: ReactNode*) = {
var addClasses = "dropdown"
if (S.open)
addClasses += " open"
ButtonGroup(ButtonGroup.ButtonGroup(addClasses = addClasses), children)
}
def renderNavItem(children: ReactNode*) = {
<.li(^.classSet1("dropdown", "open" -> S.open, "dropup" -> P.dropup.getOrElse(false)))(children)
}
def renderMenuItem(child: ReactNode, index: Int) = {
// Only handle the option selection if an onSelect prop has been set on the
// component or it's child, this allows a user not to pass an onSelect
// handler and have the browser preform the default action.
val handleOptionSelect: js.Any = if (P.onSelect.isDefined) // FIXME || child.props.onSelect)
B.handleOptionSelect _
else () => ()
val keyAndRef = getChildKeyAndRef(child, index)
ReactCloneWithProps(child, keyAndRef ++
Map[String, js.Any](
"onSelect" -> handleOptionSelect) // FIXME createChainedFunction0(childProps.onSelect, handleOptionSelect)
)
}
val buttonRef = Ref("dropdownButton")
val buttonProps = Button.Button(
addClasses = "dropdown-toggle",
onClick = (e: ReactEvent) => B.handleDropdownClick(e),
navDropdown = P.navItem.getOrElse(false),
bsStyle = P.bsStyle,
bsSize = P.bsSize,
bsClass = P.bsClass
)
val menuRef = Ref("menu")
val dropdownMenu = DropdownMenu.withKey(1).withRef("menu")(DropdownMenu.DropdownMenu(ariaLabelledBy = P.id,
pullRight = P.pullRight),
ValidComponentChildren.map(C, renderMenuItem)
)
val button = if (P.noCaret.getOrElse(false))
Button.withKey(0).withRef("dropdownButton")(buttonProps, P.title.get)
else
Button.withKey(0).withRef("dropdownButton")(buttonProps, P.title.get, " ", <.span(^.className := "caret"))
if (P.navItem.getOrElse(false))
renderNavItem(button, dropdownMenu)
else
renderButtonGroup(button, dropdownMenu)
})
.componentWillUnmount(_.backend.onComponentWillUnmount())
.build
} | lvitaly/scalajs-react-bootstrap | core/src/main/scala/com/acework/js/components/bootstrap/DropdownButton.scala | Scala | mit | 4,616 |
/*
Pyramid DX8 System - Bitmap Code (source file)
(c) 2001, Robert Jan Bruinier
*/
#include "Unicorn.h"
#ifdef UNI_BITMAP_SUPPORT
BitmapContainer * bitmapList = NULL;
#define FOREACHBITMAP(ptc) for (BitmapContainer * ptc = bitmapList; NULL != ptc; ptc = ptc->next)
void uniBitmapCreate(char * name, unsigned int * source, dword width, dword height, dword flags) {
#ifdef UNI_LOGHTML
uniLog(" Uploading bitmap %s to memory (%ix%ix%i)\n", name, width, height, uniSystem->usedTextureBpp);
#endif
BitmapContainer * actBitmap = new BitmapContainer();
lstrcpy(actBitmap->name, name);
if (bitmapList)
bitmapList->prev = actBitmap;
actBitmap->prev = NULL;
actBitmap->next = bitmapList;
bitmapList = actBitmap;
actBitmap->width = width;
actBitmap->height = height;
actBitmap->d3d8Surface = NULL;
if (D3D_OK != uniSystem->d3d8Device->CreateImageSurface(width, height,
uniSystem->d3d8PP.BackBufferFormat,
&actBitmap->d3d8Surface))
uniQuit("Failed to create image surface");
D3DLOCKED_RECT d3dlr;
if (D3D_OK != actBitmap->d3d8Surface->LockRect(&d3dlr, NULL, D3DLOCK_NOSYSLOCK))
uniQuit("Failed to lock surface");
uniTextureUploadData(d3dlr.pBits, source, width * height, uniSystem->d3d8PP.BackBufferFormat);
if (D3D_OK != actBitmap->d3d8Surface->UnlockRect())
uniQuit("Failed to unlock surface");
}
void uniBitmapDraw(char * name) {
if (name == NULL)
return;
BitmapContainer * bitmap = NULL;
FOREACHBITMAP (ptcBitmap) {
if (lstrcmpi(name, ptcBitmap->name ) == 0) {
bitmap = ptcBitmap;
break;
}
}
if (bitmap != NULL) {
if (D3D_OK != uniSystem->d3d8Device->CopyRects(bitmap->d3d8Surface, NULL, 0,
uniSystem->surfaceBackBuffer,
NULL))
uniQuit("Failed to render bitmap");
}
}
void uniBitmapDestroy(char * name) {
if (bitmapList) {
FOREACHBITMAP (ptcBitmap) {
if (lstrcmpi(name, ptcBitmap->name ) == 0) {
if (ptcBitmap->prev)
ptcBitmap->prev->next = ptcBitmap->next;
else
bitmapList = ptcBitmap->next;
if (ptcBitmap->next)
ptcBitmap->next->prev = ptcBitmap->prev;
if (ptcBitmap->d3d8Surface != NULL)
ptcBitmap->d3d8Surface->Release();
delete ptcBitmap;
return;
}
}
}
}
void uniBitmapDestroyAll() {
if (bitmapList != NULL) {
FOREACHBITMAP (ptcBitmap) {
if (ptcBitmap->d3d8Surface != NULL)
ptcBitmap->d3d8Surface->Release();
}
do {
BitmapContainer * next_ptr = bitmapList->next;
delete bitmapList;
bitmapList = next_ptr;
} while (bitmapList != NULL);
}
}
#endif
| CrossProd/Aardbei_EastsideWorks | Unicorn System/Bitmap.cpp | C++ | mit | 2,732 |
using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
namespace PingYourPackage.API.Model.Validation {
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class MaximumAttribute : ValidationAttribute {
private readonly int _maximumValue;
public MaximumAttribute(int maximum) :
base(errorMessage: "The {0} field value must be maximum {1}.") {
_maximumValue = maximum;
}
public override string FormatErrorMessage(string name) {
return string.Format(
CultureInfo.CurrentCulture,
base.ErrorMessageString,
name,
_maximumValue);
}
public override bool IsValid(object value) {
int intValue;
if (value != null && int.TryParse(value.ToString(), out intValue)) {
return (intValue <= _maximumValue);
}
return false;
}
}
} | niknhattan/PingYourPackage | PingYourPackage.API.Model/Validation/MaximumAttribute.cs | C# | mit | 1,016 |
function Test-DbaAgentJobOwner {
<#
.SYNOPSIS
Checks SQL Agent Job owners against a login to validate which jobs do not match that owner.
.DESCRIPTION
This function checks all SQL Agent Jobs on an instance against a SQL login to validate if that login owns those SQL Agent Jobs or not. By default, the function checks against 'sa' for ownership, but the user can pass a specific login if they use something else.
Only SQL Agent Jobs that do not match this ownership will be displayed.
Best practice reference: http://sqlmag.com/blog/sql-server-tip-assign-ownership-jobs-sysadmin-account
.PARAMETER SqlInstance
The target SQL Server instance or instances.
.PARAMETER SqlCredential
Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).
Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.
For MFA support, please use Connect-DbaInstance.
.PARAMETER Job
Specifies the job(s) to process. Options for this list are auto-populated from the server. If unspecified, all jobs will be processed.
.PARAMETER ExcludeJob
Specifies the job(s) to exclude from processing. Options for this list are auto-populated from the server.
.PARAMETER Login
Specifies the login that you wish check for ownership. This defaults to 'sa' or the sysadmin name if sa was renamed. This must be a valid security principal which exists on the target server.
.PARAMETER EnableException
By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
.NOTES
Tags: Agent, Job, Owner
Author: Michael Fal (@Mike_Fal), http://mikefal.net
Website: https://dbatools.io
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.LINK
https://dbatools.io/Test-DbaAgentJobOwner
.EXAMPLE
PS C:\> Test-DbaAgentJobOwner -SqlInstance localhost
Returns all SQL Agent Jobs where the owner does not match 'sa'.
.EXAMPLE
PS C:\> Test-DbaAgentJobOwner -SqlInstance localhost -ExcludeJob 'syspolicy_purge_history'
Returns SQL Agent Jobs except for the syspolicy_purge_history job
.EXAMPLE
PS C:\> Test-DbaAgentJobOwner -SqlInstance localhost -Login DOMAIN\account
Returns all SQL Agent Jobs where the owner does not match DOMAIN\account. Note
that Login must be a valid security principal that exists on the target server.
#>
[CmdletBinding()]
[OutputType('System.Object[]')]
param (
[parameter(Mandatory, ValueFromPipeline)]
[DbaInstanceParameter[]]$SqlInstance,
[PSCredential]$SqlCredential,
[Alias("Jobs")]
[object[]]$Job,
[object[]]$ExcludeJob,
[Alias("TargetLogin")]
[string]$Login,
[switch]$EnableException
)
begin {
#connect to the instance and set return array empty
$return = @()
}
process {
foreach ($instance in $SqlInstance) {
#connect to the instance
$server = Connect-SqlInstance $instance -SqlCredential $SqlCredential
#Validate login
if ($Login -and ($server.Logins.Name) -notcontains $Login) {
if ($SqlInstance.count -eq 1) {
Stop-Function -Message "Invalid login: $Login."
return
} else {
Write-Message -Level Warning -Message "$Login is not a valid login on $instance. Moving on."
continue
}
}
if ($Login -and $server.Logins[$Login].LoginType -eq 'WindowsGroup') {
Stop-Function -Message "$Login is a Windows Group and can not be a job owner."
return
}
#Sets the Default Login to sa if the Login Paramater is not set.
if (!($PSBoundParameters.ContainsKey('Login'))) {
$Login = "sa"
}
#sql2000 id property is empty -force target login to 'sa' login
if ($Login -and ( ($server.VersionMajor -lt 9) -and ([string]::IsNullOrEmpty($Login)) )) {
$Login = "sa"
}
# dynamic sa name for orgs who have changed their sa name
if ($Login -eq "sa") {
$Login = ($server.Logins | Where-Object { $_.id -eq 1 }).Name
}
#Get database list. If value for -Job is passed, massage to make it a string array.
#Otherwise, use all jobs on the instance where owner not equal to -TargetLogin
Write-Message -Level Verbose -Message "Gathering jobs to check."
if ($Job) {
$jobCollection = $server.JobServer.Jobs | Where-Object { $Job -contains $_.Name }
} elseif ($ExcludeJob) {
$jobCollection = $server.JobServer.Jobs | Where-Object { $ExcludeJob -notcontains $_.Name }
} else {
$jobCollection = $server.JobServer.Jobs
}
#for each database, create custom object for return set.
foreach ($j in $jobCollection) {
Write-Message -Level Verbose -Message "Checking $j"
$row = [ordered]@{
Server = $server.Name
Job = $j.Name
JobType = if ($j.CategoryID -eq 1) { "Remote" } else { $j.JobType }
CurrentOwner = $j.OwnerLoginName
TargetOwner = $Login
OwnerMatch = if ($j.CategoryID -eq 1) { $true } else { $j.OwnerLoginName -eq $Login }
}
#add each custom object to the return array
$return += New-Object PSObject -Property $row
}
if ($Job) {
$results = $return
} else {
$results = $return | Where-Object { $_.OwnerMatch -eq $False }
}
}
}
end {
#return results
Select-DefaultView -InputObject $results -Property Server, Job, JobType, CurrentOwner, TargetOwner, OwnerMatch
}
} | Splaxi/dbatools | functions/Test-DbaAgentJobOwner.ps1 | PowerShell | mit | 6,595 |
#### Integrations
##### EWS v2
- Improved error messages.
| demisto/content | Packs/EWS/ReleaseNotes/1_7_6.md | Markdown | mit | 59 |
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Profile;
use Predis\ClientException;
/**
* Factory class for creating profile instances from strings.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
final class Factory
{
private static $profiles = array(
'2.0' => 'Predis\Profile\RedisVersion200',
'2.2' => 'Predis\Profile\RedisVersion220',
'2.4' => 'Predis\Profile\RedisVersion240',
'2.6' => 'Predis\Profile\RedisVersion260',
'2.8' => 'Predis\Profile\RedisVersion280',
'3.0' => 'Predis\Profile\RedisVersion300',
'3.2' => 'Predis\Profile\RedisVersion320',
'dev' => 'Predis\Profile\RedisUnstable',
'default' => 'Predis\Profile\RedisVersion300',
);
/**
*
*/
private function __construct()
{
// NOOP
}
/**
* Returns the default server profile.
*
* @return ProfileInterface
*/
public static function getDefault()
{
return self::get('default');
}
/**
* Returns the development server profile.
*
* @return ProfileInterface
*/
public static function getDevelopment()
{
return self::get('dev');
}
/**
* Registers a new server profile.
*
* @param string $alias Profile version or alias.
* @param string $class FQN of a class implementing Predis\Profile\ProfileInterface.
*
* @throws \InvalidArgumentException
*/
public static function define($alias, $class)
{
$reflection = new \ReflectionClass($class);
if (!$reflection->isSubclassOf('Predis\Profile\ProfileInterface')) {
throw new \InvalidArgumentException("The class '$class' is not a valid profile class.");
}
self::$profiles[$alias] = $class;
}
/**
* Returns the specified server profile.
*
* @param string $version Profile version or alias.
*
* @throws ClientException
*
* @return ProfileInterface
*/
public static function get($version)
{
if (!isset(self::$profiles[$version])) {
throw new ClientException("Unknown server profile: '$version'.");
}
$profile = self::$profiles[$version];
return new $profile();
}
}
| gencer/predis | src/Profile/Factory.php | PHP | mit | 2,491 |
<?php
/**
* Created by PhpStorm.
* User: aethr
* Date: 25/04/17
* Time: 5:56 PM
*/
namespace App\Models\Api;
use Neomerx\JsonApi\Schema\SchemaProvider;
class QueueSchema extends SchemaProvider
{
protected $resourceType = 'item';
public function getId($queueItem)
{
/** @var Item $item */
return $queueItem->id;
}
public function getAttributes($queueItem)
{
/** @var Item $item */
return [
'item_type' => $queueItem->item->type,
'item' => $queueItem->item,
];
}
public function getRelationships($queueItem, $isPrimary, array $includeList)
{
/** @var Item $item */
return [
// 'item' => [
// self::DATA => $queueItem->item->id
// ],
];
}
}
| MonkiiBuilt/neocortex | app/Models/Api/QueueSchema.php | PHP | mit | 814 |
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Webapi\Model;
use Magento\Webapi\Model\Config\Converter;
use Magento\Webapi\Model\Cache\Type\Webapi as WebApiCache;
/**
* Service Metadata Model
*/
class ServiceMetadata
{
/**#@+
* Keys that a used for service config internal representation.
*/
const KEY_CLASS = 'class';
const KEY_IS_SECURE = 'isSecure';
const KEY_SERVICE_METHODS = 'methods';
const KEY_METHOD = 'method';
const KEY_IS_REQUIRED = 'inputRequired';
const KEY_ACL_RESOURCES = 'resources';
const KEY_ROUTES = 'routes';
const KEY_ROUTE_METHOD = 'method';
const KEY_ROUTE_PARAMS = 'parameters';
const SERVICES_CONFIG_CACHE_ID = 'services-services-config';
const ROUTES_CONFIG_CACHE_ID = 'routes-services-config';
const REFLECTED_TYPES_CACHE_ID = 'soap-reflected-types';
/**#@-*/
/**
* API services
*
* @var array
*/
protected $services;
/**
* List of services with route data
*
* @var array
*/
protected $routes;
/**
* @var WebApiCache
*/
protected $cache;
/** @var \Magento\Webapi\Model\Config */
protected $config;
/**
* @var \Magento\Webapi\Model\Config\ClassReflector
*/
protected $classReflector;
/**
* @var \Magento\Framework\Reflection\TypeProcessor
*/
protected $typeProcessor;
/**
* Initialize dependencies.
*
* @param \Magento\Webapi\Model\Config $config
* @param WebApiCache $cache
* @param \Magento\Webapi\Model\Config\ClassReflector $classReflector
* @param \Magento\Framework\Reflection\TypeProcessor $typeProcessor
*/
public function __construct(
\Magento\Webapi\Model\Config $config,
WebApiCache $cache,
\Magento\Webapi\Model\Config\ClassReflector $classReflector,
\Magento\Framework\Reflection\TypeProcessor $typeProcessor
) {
$this->config = $config;
$this->cache = $cache;
$this->classReflector = $classReflector;
$this->typeProcessor = $typeProcessor;
}
/**
* Collect the list of services metadata
*
* @return array
*/
protected function initServicesMetadata()
{
$services = [];
foreach ($this->config->getServices()[Converter::KEY_SERVICES] as $serviceClass => $serviceVersionData) {
foreach ($serviceVersionData as $version => $serviceData) {
$serviceName = $this->getServiceName($serviceClass, $version);
foreach ($serviceData[Converter::KEY_METHODS] as $methodName => $methodMetadata) {
$services[$serviceName][self::KEY_SERVICE_METHODS][$methodName] = [
self::KEY_METHOD => $methodName,
self::KEY_IS_REQUIRED => (bool)$methodMetadata[Converter::KEY_SECURE],
self::KEY_IS_SECURE => $methodMetadata[Converter::KEY_SECURE],
self::KEY_ACL_RESOURCES => $methodMetadata[Converter::KEY_ACL_RESOURCES],
];
$services[$serviceName][self::KEY_CLASS] = $serviceClass;
}
$reflectedMethodsMetadata = $this->classReflector->reflectClassMethods(
$serviceClass,
$services[$serviceName][self::KEY_SERVICE_METHODS]
);
$services[$serviceName][self::KEY_SERVICE_METHODS] = array_merge_recursive(
$services[$serviceName][self::KEY_SERVICE_METHODS],
$reflectedMethodsMetadata
);
$services[$serviceName][Converter::KEY_DESCRIPTION] = $this->classReflector->extractClassDescription(
$serviceClass
);
}
}
return $services;
}
/**
* Return services loaded from cache if enabled or from files merged previously
*
* @return array
*/
public function getServicesConfig()
{
if (null === $this->services) {
$servicesConfig = $this->cache->load(self::SERVICES_CONFIG_CACHE_ID);
$typesData = $this->cache->load(self::REFLECTED_TYPES_CACHE_ID);
if ($servicesConfig && is_string($servicesConfig) && $typesData && is_string($typesData)) {
$this->services = unserialize($servicesConfig);
$this->typeProcessor->setTypesData(unserialize($typesData));
} else {
$this->services = $this->initServicesMetadata();
$this->cache->save(serialize($this->services), self::SERVICES_CONFIG_CACHE_ID);
$this->cache->save(serialize($this->typeProcessor->getTypesData()), self::REFLECTED_TYPES_CACHE_ID);
}
}
return $this->services;
}
/**
* Retrieve specific service interface data.
*
* @param string $serviceName
* @return array
* @throws \RuntimeException
*/
public function getServiceMetadata($serviceName)
{
$servicesConfig = $this->getServicesConfig();
if (!isset($servicesConfig[$serviceName]) || !is_array($servicesConfig[$serviceName])) {
throw new \RuntimeException(__('Requested service is not available: "%1"', $serviceName));
}
return $servicesConfig[$serviceName];
}
/**
* Translate service interface name into service name.
*
* Example:
* <pre>
* - 'Magento\Customer\Api\CustomerAccountInterface', 'V1', false => customerCustomerAccount
* - 'Magento\Customer\Api\CustomerAddressInterface', 'V1', true => customerCustomerAddressV1
* </pre>
*
* @param string $interfaceName
* @param string $version
* @param bool $preserveVersion Should version be preserved during interface name conversion into service name
* @return string
* @throws \InvalidArgumentException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function getServiceName($interfaceName, $version, $preserveVersion = true)
{
if (!preg_match(\Magento\Webapi\Model\Config::SERVICE_CLASS_PATTERN, $interfaceName, $matches)) {
$apiClassPattern = "#^(.+?)\\\\(.+?)\\\\Api\\\\(.+?)(Interface)?$#";
preg_match($apiClassPattern, $interfaceName, $matches);
}
if (!empty($matches)) {
$moduleNamespace = $matches[1];
$moduleName = $matches[2];
$moduleNamespace = ($moduleNamespace == 'Magento') ? '' : $moduleNamespace;
if ($matches[4] === 'Interface') {
$matches[4] = $matches[3];
}
$serviceNameParts = explode('\\', trim($matches[4], '\\'));
if ($moduleName == $serviceNameParts[0]) {
/** Avoid duplication of words in service name */
$moduleName = '';
}
$parentServiceName = $moduleNamespace . $moduleName . array_shift($serviceNameParts);
array_unshift($serviceNameParts, $parentServiceName);
if ($preserveVersion) {
$serviceNameParts[] = $version;
}
} elseif (preg_match(\Magento\Webapi\Model\Config::API_PATTERN, $interfaceName, $matches)) {
$moduleNamespace = $matches[1];
$moduleName = $matches[2];
$moduleNamespace = ($moduleNamespace == 'Magento') ? '' : $moduleNamespace;
$serviceNameParts = explode('\\', trim($matches[3], '\\'));
if ($moduleName == $serviceNameParts[0]) {
/** Avoid duplication of words in service name */
$moduleName = '';
}
$parentServiceName = $moduleNamespace . $moduleName . array_shift($serviceNameParts);
array_unshift($serviceNameParts, $parentServiceName);
if ($preserveVersion) {
$serviceNameParts[] = $version;
}
} else {
throw new \InvalidArgumentException(sprintf('The service interface name "%s" is invalid.', $interfaceName));
}
return lcfirst(implode('', $serviceNameParts));
}
/**
* Retrieve specific service interface data with route.
*
* @param string $serviceName
* @return array
* @throws \RuntimeException
*/
public function getRouteMetadata($serviceName)
{
$routesConfig = $this->getRoutesConfig();
if (!isset($routesConfig[$serviceName]) || !is_array($routesConfig[$serviceName])) {
throw new \RuntimeException(__('Requested service is not available: "%1"', $serviceName));
}
return $routesConfig[$serviceName];
}
/**
* Return routes loaded from cache if enabled or from files merged previously
*
* @return array
*/
public function getRoutesConfig()
{
if (null === $this->routes) {
$routesConfig = $this->cache->load(self::ROUTES_CONFIG_CACHE_ID);
$typesData = $this->cache->load(self::REFLECTED_TYPES_CACHE_ID);
if ($routesConfig && is_string($routesConfig) && $typesData && is_string($typesData)) {
$this->routes = unserialize($routesConfig);
$this->typeProcessor->setTypesData(unserialize($typesData));
} else {
$this->routes = $this->initRoutesMetadata();
$this->cache->save(serialize($this->routes), self::ROUTES_CONFIG_CACHE_ID);
$this->cache->save(serialize($this->typeProcessor->getTypesData()), self::REFLECTED_TYPES_CACHE_ID);
}
}
return $this->routes;
}
/**
* Collect the list of services with routes and request types for use in REST.
*
* @return array
*/
protected function initRoutesMetadata()
{
$routes = $this->getServicesConfig();
foreach ($this->config->getServices()[Converter::KEY_ROUTES] as $url => $routeData) {
foreach ($routeData as $method => $data) {
$serviceClass = $data[Converter::KEY_SERVICE][Converter::KEY_SERVICE_CLASS];
$version = explode('/', ltrim($url, '/'))[0];
$serviceName = $this->getServiceName($serviceClass, $version);
$methodName = $data[Converter::KEY_SERVICE][Converter::KEY_METHOD];
$routes[$serviceName][self::KEY_ROUTES][$url][$method][self::KEY_ROUTE_METHOD] = $methodName;
$routes[$serviceName][self::KEY_ROUTES][$url][$method][self::KEY_ROUTE_PARAMS]
= $data[Converter::KEY_DATA_PARAMETERS];
}
}
return $routes;
}
}
| j-froehlich/magento2_wk | vendor/magento/module-webapi/Model/ServiceMetadata.php | PHP | mit | 10,731 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Tools.YamlSplitter
{
using Microsoft.DocAsCode.Build.OverwriteDocuments;
using Microsoft.DocAsCode.MarkdigEngine;
using Microsoft.DocAsCode.Plugins;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public static class FragmentModelHelper
{
public static MarkdigMarkdownService MDService = new MarkdigMarkdownService(
new MarkdownServiceParameters
{
BasePath = ".",
Extensions = new Dictionary<string, object>
{
{ "EnableSourceInfo", false }
}
});
public static Dictionary<string, MarkdownFragment> LoadMarkdownFragment(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return null;
}
if (!File.Exists(fileName))
{
return new Dictionary<string, MarkdownFragment>();
}
var markdown = File.ReadAllText(fileName);
var ast = MDService.Parse(markdown, Path.GetFileName(fileName));
var models = new MarkdownFragmentsCreater().Create(ast).ToList();
return models.ToDictionary(m => m.Uid, m => m.ToMarkdownFragment(markdown));
}
}
}
| dotnet/docfx | tools/YamlSplitter/FragmentModelHelper.cs | C# | mit | 1,492 |
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import startApp from '../../helpers/start-app';
var App;
moduleForComponent('zip-code-input', 'zip-code-input component', {
setup: function() {
App = startApp();
},
teardown: function() {
Ember.run(App, 'destroy');
},
unit: true
});
test('values are correct', function(assert) {
assert.expect(2);
var component = this.subject();
// append the component to the DOM
this.render();
// testing filled in value
fillIn('input', '12345');
triggerEvent('input', 'blur');
andThen(function() { // wait for async helpers to complete
assert.equal(find('input').val(), '12345');
assert.equal(component.get('unmaskedValue'), 12345);
});
});
test('full code works', function(assert) {
assert.expect(2);
var component = this.subject();
// append the component to the DOM
this.render();
Ember.run(function(){
component.set('fullCode', true);
});
// testing filled in value
fillIn('input', '123451234');
triggerEvent('input', 'blur');
andThen(function() { // wait for async helpers to complete
assert.equal(find('input').val(), '12345-1234');
assert.equal(component.get('unmaskedValue'), 123451234);
});
});
| ronco/ember-inputmask | tests/unit/components/zip-code-input-test.js | JavaScript | mit | 1,261 |
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "paymentserver.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "base58.h"
#include "ui_interface.h"
#include "wallet.h"
#include <cstdlib>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <QApplication>
#include <QByteArray>
#include <QDataStream>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileOpenEvent>
#include <QHash>
#include <QList>
#include <QLocalServer>
#include <QLocalSocket>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslCertificate>
#include <QSslError>
#include <QSslSocket>
#include <QStringList>
#include <QTextDocument>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
using namespace boost;
const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds
const QString BITCOIN_IPC_PREFIX("freshcoin:");
const char* BITCOIN_REQUEST_MIMETYPE = "application/bitcoin-paymentrequest";
const char* BITCOIN_PAYMENTACK_MIMETYPE = "application/bitcoin-paymentack";
const char* BITCOIN_PAYMENTACK_CONTENTTYPE = "application/bitcoin-payment";
X509_STORE* PaymentServer::certStore = NULL;
void PaymentServer::freeCertStore()
{
if (PaymentServer::certStore != NULL)
{
X509_STORE_free(PaymentServer::certStore);
PaymentServer::certStore = NULL;
}
}
//
// Create a name that is unique for:
// testnet / non-testnet
// data directory
//
static QString ipcServerName()
{
QString name("FreshcoinQt");
// Append a simple hash of the datadir
// Note that GetDataDir(true) returns a different path
// for -testnet versus main net
QString ddir(QString::fromStdString(GetDataDir(true).string()));
name.append(QString::number(qHash(ddir)));
return name;
}
//
// We store payment URIs and requests received before
// the main GUI window is up and ready to ask the user
// to send payment.
static QList<QString> savedPaymentRequests;
static void ReportInvalidCertificate(const QSslCertificate& cert)
{
qDebug() << "ReportInvalidCertificate : Payment server found an invalid certificate: " << cert.subjectInfo(QSslCertificate::CommonName);
}
//
// Load OpenSSL's list of root certificate authorities
//
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
if (PaymentServer::certStore == NULL)
atexit(PaymentServer::freeCertStore);
else
freeCertStore();
// Unit tests mostly use this, to pass in fake root CAs:
if (_store)
{
PaymentServer::certStore = _store;
return;
}
// Normal execution, use either -rootcertificates or system certs:
PaymentServer::certStore = X509_STORE_new();
// Note: use "-system-" default here so that users can pass -rootcertificates=""
// and get 'I don't like X.509 certificates, don't trust anybody' behavior:
QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-"));
if (certFile.isEmpty())
return; // Empty store
QList<QSslCertificate> certList;
if (certFile != "-system-")
{
certList = QSslCertificate::fromPath(certFile);
// Use those certificates when fetching payment requests, too:
QSslSocket::setDefaultCaCertificates(certList);
}
else
certList = QSslSocket::systemCaCertificates ();
int nRootCerts = 0;
const QDateTime currentTime = QDateTime::currentDateTime();
foreach (const QSslCertificate& cert, certList)
{
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
ReportInvalidCertificate(cert);
continue;
}
#if QT_VERSION >= 0x050000
if (cert.isBlacklisted()) {
ReportInvalidCertificate(cert);
continue;
}
#endif
QByteArray certData = cert.toDer();
const unsigned char *data = (const unsigned char *)certData.data();
X509* x509 = d2i_X509(0, &data, certData.size());
if (x509 && X509_STORE_add_cert(PaymentServer::certStore, x509))
{
// Note: X509_STORE_free will free the X509* objects when
// the PaymentServer is destroyed
++nRootCerts;
}
else
{
ReportInvalidCertificate(cert);
continue;
}
}
qDebug() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates";
// Project for another day:
// Fetch certificate revocation lists, and add them to certStore.
// Issues to consider:
// performance (start a thread to fetch in background?)
// privacy (fetch through tor/proxy so IP address isn't revealed)
// would it be easier to just use a compiled-in blacklist?
// or use Qt's blacklist?
// "certificate stapling" with server-side caching is more efficient
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcParseCommandLine(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
QString arg(argv[i]);
if (arg.startsWith("-"))
continue;
if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // freshcoin: URI
{
savedPaymentRequests.append(arg);
SendCoinsRecipient r;
if (GUIUtil::parseBitcoinURI(arg, &r))
{
CBitcoinAddress address(r.address.toStdString());
SelectParams(CChainParams::MAIN);
if (!address.IsValid())
{
SelectParams(CChainParams::TESTNET);
}
}
}
else if (QFile::exists(arg)) // Filename
{
savedPaymentRequests.append(arg);
PaymentRequestPlus request;
if (readPaymentRequest(arg, request))
{
if (request.getDetails().network() == "main")
SelectParams(CChainParams::MAIN);
else
SelectParams(CChainParams::TESTNET);
}
}
else
{
// Printing to debug.log is about the best we can do here, the
// GUI hasn't started yet so we can't pop up a message box.
qDebug() << "PaymentServer::ipcSendCommandLine : Payment request file does not exist: " << arg;
}
}
return true;
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
foreach (const QString& r, savedPaymentRequests)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
{
delete socket;
return false;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << r;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
socket->disconnectFromServer();
delete socket;
fResult = true;
}
return fResult;
}
PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) :
QObject(parent),
saveURIs(true),
uriServer(0),
netManager(0),
optionsModel(0)
{
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
// Install global event filter to catch QFileOpenEvents
// on Mac: sent when you click freshcoin: links
// other OSes: helpful when dealing with payment request files (in the future)
if (parent)
parent->installEventFilter(this);
QString name = ipcServerName();
// Clean up old socket leftover from a crash:
QLocalServer::removeServer(name);
if (startLocalServer)
{
uriServer = new QLocalServer(this);
if (!uriServer->listen(name)) {
// constructor is called early in init, so don't use "emit message()" here
QMessageBox::critical(0, tr("Payment request error"),
tr("Cannot start freshcoin: click-to-pay handler"));
}
else {
connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));
connect(this, SIGNAL(receivedPaymentACK(QString)), this, SLOT(handlePaymentACK(QString)));
}
}
}
PaymentServer::~PaymentServer()
{
google::protobuf::ShutdownProtobufLibrary();
}
//
// OSX-specific way of handling freshcoin: URIs and
// PaymentRequest mime types
//
bool PaymentServer::eventFilter(QObject *object, QEvent *event)
{
// clicking on freshcoin: URIs creates FileOpen events on the Mac
if (event->type() == QEvent::FileOpen)
{
QFileOpenEvent *fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->file().isEmpty())
handleURIOrFile(fileEvent->file());
else if (!fileEvent->url().isEmpty())
handleURIOrFile(fileEvent->url().toString());
return true;
}
return QObject::eventFilter(object, event);
}
void PaymentServer::initNetManager()
{
if (!optionsModel)
return;
if (netManager != NULL)
delete netManager;
// netManager is used to fetch paymentrequests given in freshcoin: URIs
netManager = new QNetworkAccessManager(this);
QNetworkProxy proxy;
// Query active proxy (fails if no SOCKS5 proxy)
if (optionsModel->getProxySettings(proxy)) {
if (proxy.type() == QNetworkProxy::Socks5Proxy) {
netManager->setProxy(proxy);
qDebug() << "PaymentServer::initNetManager : Using SOCKS5 proxy" << proxy.hostName() << ":" << proxy.port();
}
else
qDebug() << "PaymentServer::initNetManager : No active proxy server found.";
}
else
emit message(tr("Net manager warning"),
tr("Your active proxy doesn't support SOCKS5, which is required for payment requests via proxy."),
CClientUIInterface::MSG_WARNING);
connect(netManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(netRequestFinished(QNetworkReply*)));
connect(netManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> &)),
this, SLOT(reportSslErrors(QNetworkReply*, const QList<QSslError> &)));
}
void PaymentServer::uiReady()
{
initNetManager();
saveURIs = false;
foreach (const QString& s, savedPaymentRequests)
{
handleURIOrFile(s);
}
savedPaymentRequests.clear();
}
void PaymentServer::handleURIOrFile(const QString& s)
{
if (saveURIs)
{
savedPaymentRequests.append(s);
return;
}
if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // freshcoin: URI
{
#if QT_VERSION < 0x050000
QUrl uri(s);
#else
QUrlQuery uri((QUrl(s)));
#endif
if (uri.hasQueryItem("r")) // payment request URI
{
QByteArray temp;
temp.append(uri.queryItemValue("r"));
QString decoded = QUrl::fromPercentEncoding(temp);
QUrl fetchUrl(decoded, QUrl::StrictMode);
if (fetchUrl.isValid())
{
qDebug() << "PaymentServer::handleURIOrFile : fetchRequest(" << fetchUrl << ")";
fetchRequest(fetchUrl);
}
else
{
qDebug() << "PaymentServer::handleURIOrFile : Invalid URL: " << fetchUrl;
emit message(tr("URI handling"),
tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()),
CClientUIInterface::ICON_WARNING);
}
return;
}
else // normal URI
{
SendCoinsRecipient recipient;
if (GUIUtil::parseBitcoinURI(s, &recipient))
emit receivedPaymentRequest(recipient);
else
emit message(tr("URI handling"),
tr("URI can not be parsed! This can be caused by an invalid Freshcoin address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
return;
}
}
if (QFile::exists(s)) // payment request file
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (readPaymentRequest(s, request) && processPaymentRequest(request, recipient))
emit receivedPaymentRequest(recipient);
else
emit message(tr("Payment request file handling"),
tr("Payment request file can not be read or processed! This can be caused by an invalid payment request file."),
CClientUIInterface::ICON_WARNING);
return;
}
}
void PaymentServer::handleURIConnection()
{
QLocalSocket *clientConnection = uriServer->nextPendingConnection();
while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
clientConnection->waitForReadyRead();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_0);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
QString msg;
in >> msg;
handleURIOrFile(msg);
}
bool PaymentServer::readPaymentRequest(const QString& filename, PaymentRequestPlus& request)
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly))
{
qDebug() << "PaymentServer::readPaymentRequest : Failed to open " << filename;
return false;
}
if (f.size() > MAX_PAYMENT_REQUEST_SIZE)
{
qDebug() << "PaymentServer::readPaymentRequest : " << filename << " too large";
return false;
}
QByteArray data = f.readAll();
return request.parse(data);
}
bool PaymentServer::processPaymentRequest(PaymentRequestPlus& request, SendCoinsRecipient& recipient)
{
if (!optionsModel)
return false;
recipient.paymentRequest = request;
recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo());
request.getMerchant(PaymentServer::certStore, recipient.authenticatedMerchant);
QList<std::pair<CScript, qint64> > sendingTos = request.getPayTo();
QStringList addresses;
foreach(const PAIRTYPE(CScript, qint64)& sendingTo, sendingTos) {
// Extract and check destination addresses
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest)) {
// Append destination address
addresses.append(QString::fromStdString(CBitcoinAddress(dest).ToString()));
}
else if (!recipient.authenticatedMerchant.isEmpty()){
// Insecure payments to custom bitcoin addresses are not supported
// (there is no good way to tell the user where they are paying in a way
// they'd have a chance of understanding).
emit message(tr("Payment request error"),
tr("Unverified payment requests to custom payment scripts are unsupported."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Extract and check amounts
CTxOut txOut(sendingTo.second, sendingTo.first);
if (txOut.IsDust(CTransaction::nMinRelayTxFee)) {
QString msg = tr("Requested payment amount of %1 is too small (considered dust).")
.arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second));
qDebug() << "PaymentServer::processPaymentRequest : " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
return false;
}
recipient.amount += sendingTo.second;
}
// Store addresses and format them to fit nicely into the GUI
recipient.address = addresses.join("<br />");
if (!recipient.authenticatedMerchant.isEmpty()) {
qDebug() << "PaymentServer::processPaymentRequest : Secure payment request from " << recipient.authenticatedMerchant;
}
else {
qDebug() << "PaymentServer::processPaymentRequest : Insecure payment request to " << addresses.join(", ");
}
return true;
}
void PaymentServer::fetchRequest(const QUrl& url)
{
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, "PaymentRequest");
netRequest.setUrl(url);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BITCOIN_REQUEST_MIMETYPE);
netManager->get(netRequest);
}
void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction)
{
const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();
if (!details.has_payment_url())
return;
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, "PaymentACK");
netRequest.setUrl(QString::fromStdString(details.payment_url()));
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, BITCOIN_PAYMENTACK_CONTENTTYPE);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BITCOIN_PAYMENTACK_MIMETYPE);
payments::Payment payment;
payment.set_merchant_data(details.merchant_data());
payment.add_transactions(transaction.data(), transaction.size());
// Create a new refund address, or re-use:
QString account = tr("Refund from %1").arg(recipient.authenticatedMerchant);
std::string strAccount = account.toStdString();
set<CTxDestination> refundAddresses = wallet->GetAccountAddresses(strAccount);
if (!refundAddresses.empty()) {
CScript s; s.SetDestination(*refundAddresses.begin());
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
}
else {
CPubKey newKey;
if (wallet->GetKeyFromPool(newKey)) {
LOCK(wallet->cs_wallet); // SetAddressBook
CKeyID keyID = newKey.GetID();
wallet->SetAddressBook(keyID, strAccount, "refund");
CScript s; s.SetDestination(keyID);
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
}
else {
// This should never happen, because sending coins should have just unlocked the wallet
// and refilled the keypool
qDebug() << "PaymentServer::fetchPaymentACK : Error getting refund key, refund_to not set";
}
}
int length = payment.ByteSize();
netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length);
QByteArray serData(length, '\0');
if (payment.SerializeToArray(serData.data(), length)) {
netManager->post(netRequest, serData);
}
else {
// This should never happen, either:
qDebug() << "PaymentServer::fetchPaymentACK : Error serializing payment message";
}
}
void PaymentServer::netRequestFinished(QNetworkReply* reply)
{
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError)
{
QString msg = tr("Error communicating with %1: %2")
.arg(reply->request().url().toString())
.arg(reply->errorString());
qDebug() << "PaymentServer::netRequestFinished : " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
return;
}
QByteArray data = reply->readAll();
QString requestType = reply->request().attribute(QNetworkRequest::User).toString();
if (requestType == "PaymentRequest")
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (request.parse(data) && processPaymentRequest(request, recipient))
{
emit receivedPaymentRequest(recipient);
}
else
{
qDebug() << "PaymentServer::netRequestFinished : Error processing payment request";
emit message(tr("Payment request error"),
tr("Payment request can not be parsed or processed!"),
CClientUIInterface::MSG_ERROR);
}
return;
}
else if (requestType == "PaymentACK")
{
payments::PaymentACK paymentACK;
if (!paymentACK.ParseFromArray(data.data(), data.size()))
{
QString msg = tr("Bad response from server %1")
.arg(reply->request().url().toString());
qDebug() << "PaymentServer::netRequestFinished : " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
}
else
{
emit receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo()));
}
}
}
void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError> &errs)
{
Q_UNUSED(reply);
QString errString;
foreach (const QSslError& err, errs) {
qDebug() << "PaymentServer::reportSslErrors : " << err;
errString += err.errorString() + "\n";
}
emit message(tr("Network request error"), errString, CClientUIInterface::MSG_ERROR);
}
void PaymentServer::setOptionsModel(OptionsModel *optionsModel)
{
this->optionsModel = optionsModel;
}
void PaymentServer::handlePaymentACK(const QString& paymentACKMsg)
{
// currently we don't futher process or store the paymentACK message
emit message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);
}
| mrflow27/freshcoin | src/qt/paymentserver.cpp | C++ | mit | 22,139 |
var grow = grow || {};
window.grow = grow;
(function(grow){
var toolConfig = {};
grow.ui = grow.ui || {};
grow.ui.showNotice = function(text) {
var notice = document.createElement('div');
notice.classList.add('grow_tool__notice');
if (text) {
notice.appendChild(document.createTextNode(text));
}
document.body.appendChild(notice);
return notice;
};
grow.ui.toolConfig = function(tool, options) {
toolConfig[tool] = options;
};
grow.ui.tools = grow.ui.tools || [];
grow.ui.main = function(settings) {
var el = document.createElement('div');
var buttonsEl = document.createElement('div');
buttonsEl.setAttribute('class', 'grow__buttons');
buttonsEl.appendChild(createButton_('primary', null, null, {
'click': function() {
buttonsEl.classList.toggle('grow__expand');
}
}));
buttonsEl.appendChild(createButton_('close', null, null, {
'click': function() {
el.parentNode.removeChild(el);
}
}));
if (settings.injectEditUrl) {
buttonsEl.appendChild(
createButton_('edit', 'Edit', settings.injectEditUrl));
}
if (settings.injectTranslateUrl) {
buttonsEl.appendChild(createButton_(
'translate', 'Translate', settings.injectTranslateUrl));
}
for(i in grow.ui.tools) {
tool = grow.ui.tools[i];
if (tool['init']) {
tool['init'](toolConfig[tool['kind']] || {});
}
if (tool['button']) {
buttonsEl.appendChild(createButton_(
tool['kind'], tool['name'], tool['button']['link'] || null,
tool['button']['events'] || {}));
}
}
// If there is nothing to do, do not show the menu at all.
if (buttonsEl.children.length <= 2) {
return;
}
el.setAttribute('id', 'grow-utils');
el.appendChild(buttonsEl);
document.body.appendChild(el);
};
var createButton_ = function(kind, label, url, events) {
var containerEl = document.createElement('div');
containerEl.classList.add('grow__button');
var buttonEl = document.createElement('a');
buttonEl.classList.add('grow__icon');
buttonEl.classList.add('grow__icon_' + kind);
if (url) {
buttonEl.setAttribute('href', url);
buttonEl.setAttribute('target', '_blank');
} else {
buttonEl.setAttribute('href', 'javascript:void(0)');
}
if (events) {
for (var prop in events) {
buttonEl.addEventListener(prop, events[prop]);
}
}
containerEl.appendChild(buttonEl);
if (label) {
var labelEl = document.createElement('p');
labelEl.appendChild(document.createTextNode(label));
labelEl.classList.add('grow__label');
containerEl.appendChild(labelEl);
}
return containerEl;
};
})(grow);
| grow/pygrow | grow/ui/js/composite/ui.js | JavaScript | mit | 2,800 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Qt 4.8: bearermonitor.h Example File (network/bearermonitor/bearermonitor.h)</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style/superfish.css" />
<link rel="stylesheet" type="text/css" href="style/narrow.css" />
<!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->
<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>
</head>
<body class="" onload="CheckEmptyAndLoadList();">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="narrowsearch"></div>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
<li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul>
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul>
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="supported-platforms.html">Supported Platforms</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul>
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search" id="sidebarsearch">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
<div id="resultdialog">
<a href="#" id="resultclose">Close</a>
<p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p>
<p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p>
<ul id="resultlist" class="all">
</ul>
</div>
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content mainContent">
<h1 class="title">bearermonitor.h Example File</h1>
<span class="small-subtitle">network/bearermonitor/bearermonitor.h</span>
<!-- $$$network/bearermonitor/bearermonitor.h-description -->
<div class="descr"> <a name="details"></a>
<pre class="cpp"> <span class="comment">/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/</span>
<span class="preprocessor">#ifndef BEARERMONITOR_H</span>
<span class="preprocessor">#define BEARERMONITOR_H</span>
<span class="preprocessor">#include <qnetworkconfigmanager.h></span>
<span class="preprocessor">#include <qnetworksession.h></span>
<span class="preprocessor">#if defined (Q_OS_SYMBIAN) || defined(Q_OS_WINCE) || defined(Q_WS_SIMULATOR)</span>
<span class="preprocessor">#include "ui_bearermonitor_240_320.h"</span>
<span class="preprocessor">#elif defined(MAEMO_UI)</span>
<span class="preprocessor">#include "ui_bearermonitor_maemo.h"</span>
<span class="preprocessor">#else</span>
<span class="preprocessor">#include "ui_bearermonitor_640_480.h"</span>
<span class="preprocessor">#endif</span>
QT_USE_NAMESPACE
<span class="keyword">class</span> SessionWidget;
<span class="keyword">class</span> BearerMonitor : <span class="keyword">public</span> <span class="type"><a href="qwidget.html">QWidget</a></span><span class="operator">,</span> <span class="keyword">public</span> Ui_BearerMonitor
{
Q_OBJECT
<span class="keyword">public</span>:
BearerMonitor(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent <span class="operator">=</span> <span class="number">0</span>);
<span class="operator">~</span>BearerMonitor();
<span class="keyword">private</span> <span class="keyword">slots</span>:
<span class="type">void</span> configurationAdded(<span class="keyword">const</span> <span class="type"><a href="qnetworkconfiguration.html">QNetworkConfiguration</a></span> <span class="operator">&</span>config<span class="operator">,</span> <span class="type"><a href="qtreewidgetitem.html">QTreeWidgetItem</a></span> <span class="operator">*</span>parent <span class="operator">=</span> <span class="number">0</span>);
<span class="type">void</span> configurationRemoved(<span class="keyword">const</span> <span class="type"><a href="qnetworkconfiguration.html">QNetworkConfiguration</a></span> <span class="operator">&</span>config);
<span class="type">void</span> configurationChanged(<span class="keyword">const</span> <span class="type"><a href="qnetworkconfiguration.html">QNetworkConfiguration</a></span> <span class="operator">&</span>config);
<span class="type">void</span> updateSnapConfiguration(<span class="type"><a href="qtreewidgetitem.html">QTreeWidgetItem</a></span> <span class="operator">*</span>parent<span class="operator">,</span> <span class="keyword">const</span> <span class="type"><a href="qnetworkconfiguration.html">QNetworkConfiguration</a></span> <span class="operator">&</span>snap);
<span class="type">void</span> updateConfigurations();
<span class="type">void</span> onlineStateChanged(<span class="type">bool</span> isOnline);
<span class="preprocessor">#if defined(Q_OS_WIN) || defined(Q_WS_SIMULATOR)</span>
<span class="type">void</span> registerNetwork();
<span class="type">void</span> unregisterNetwork();
<span class="preprocessor">#endif</span>
<span class="type">void</span> showConfigurationFor(<span class="type"><a href="qtreewidgetitem.html">QTreeWidgetItem</a></span> <span class="operator">*</span>item);
<span class="type">void</span> createSessionFor(<span class="type"><a href="qtreewidgetitem.html">QTreeWidgetItem</a></span> <span class="operator">*</span>item);
<span class="type">void</span> createNewSession();
<span class="preprocessor">#ifndef MAEMO_UI</span>
<span class="type">void</span> deleteSession();
<span class="preprocessor">#endif</span>
<span class="type">void</span> performScan();
<span class="keyword">private</span>:
<span class="type"><a href="qnetworkconfigurationmanager.html">QNetworkConfigurationManager</a></span> manager;
<span class="type"><a href="qlist.html">QList</a></span><span class="operator"><</span>SessionWidget <span class="operator">*</span><span class="operator">></span> sessionWidgets;
};
<span class="preprocessor">#endif //BEARERMONITOR_H</span></pre>
</div>
<!-- @@@network/bearermonitor/bearermonitor.h -->
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Digia, Qt and their respective logos are trademarks of Digia Plc
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
<script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>
| stephaneAG/PengPod700 | QtEsrc/qt-everywhere-opensource-src-4.8.5/doc/html/network-bearermonitor-bearermonitor-h.html | HTML | mit | 15,474 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.PetstoreV2NoSync
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// This is a sample server Petstore server. You can find out more about
/// Swagger at <a
/// href="http://swagger.io">http://swagger.io</a> or on
/// irc.freenode.net, #swagger. For this sample, you can use the api key
/// "special-key" to test the authorization filters
/// </summary>
public partial class SwaggerPetstoreV2 : ServiceClient<SwaggerPetstoreV2>, ISwaggerPetstoreV2
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreV2 class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerPetstoreV2(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreV2 class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerPetstoreV2(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreV2 class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreV2(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreV2 class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreV2(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("http://petstore.swagger.io/v2");
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Pet>> AddPetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
if (body != null)
{
body.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "AddPet", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 405 && (int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Pet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Pet>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
if (body != null)
{
body.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UpdatePet", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 405)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(IList<string> status, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (status == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "status");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("status", status);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "FindPetsByStatus", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/findByStatus").ToString();
List<string> _queryParameters = new List<string>();
if (status != null)
{
_queryParameters.Add(string.Format("status={0}", System.Uri.EscapeDataString(string.Join(",", status))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IList<Pet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<Pet>>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(IList<string> tags, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (tags == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "tags");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("tags", tags);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "FindPetsByTags", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/findByTags").ToString();
List<string> _queryParameters = new List<string>();
if (tags != null)
{
_queryParameters.Add(string.Format("tags={0}", System.Uri.EscapeDataString(string.Join(",", tags))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IList<Pet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<Pet>>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("petId", petId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPetById", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/{petId}").ToString();
_url = _url.Replace("{petId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(petId, SerializationSettings).Trim('"')));
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 404)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Pet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Pet>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(long petId, Stream fileContent, string fileName = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (fileContent == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fileContent");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("petId", petId);
tracingParameters.Add("fileContent", fileContent);
tracingParameters.Add("fileName", fileName);
tracingParameters.Add("status", status);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UpdatePetWithForm", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/{petId}").ToString();
_url = _url.Replace("{petId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(petId, SerializationSettings).Trim('"')));
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent();
if (fileContent != null)
{
System.Net.Http.StreamContent _fileContent = new System.Net.Http.StreamContent(fileContent);
_fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
FileStream _fileContentAsFileStream = fileContent as FileStream;
if (_fileContentAsFileStream != null)
{
System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
_contentDispositionHeaderValue.Name = "fileContent";
_contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name;
_fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue;
}
_multiPartContent.Add(_fileContent, "fileContent");
}
if (fileName != null)
{
System.Net.Http.StringContent _fileName = new System.Net.Http.StringContent(fileName, System.Text.Encoding.UTF8);
_multiPartContent.Add(_fileName, "fileName");
}
if (status != null)
{
System.Net.Http.StringContent _status = new System.Net.Http.StringContent(status, System.Text.Encoding.UTF8);
_multiPartContent.Add(_status, "status");
}
_httpRequest.Content = _multiPartContent;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 405)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiKey", apiKey);
tracingParameters.Add("petId", petId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeletePet", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/{petId}").ToString();
_url = _url.Replace("{petId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(petId, SerializationSettings).Trim('"')));
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (apiKey != null)
{
if (_httpRequest.Headers.Contains("api_key"))
{
_httpRequest.Headers.Remove("api_key");
}
_httpRequest.Headers.TryAddWithoutValidation("api_key", apiKey);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 400)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInventory", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/inventory").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IDictionary<string, int?>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, int?>>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PlaceOrder", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/order").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Order>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Order>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (orderId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "orderId");
}
if (orderId != null)
{
if (orderId.Length > 5)
{
throw new ValidationException(ValidationRules.MaxLength, "orderId", 5);
}
if (orderId.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "orderId", 1);
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("orderId", orderId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetOrderById", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/order/{orderId}").ToString();
_url = _url.Replace("{orderId}", System.Uri.EscapeDataString(orderId));
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 404)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Order>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Order>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (orderId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "orderId");
}
if (orderId != null)
{
if (orderId.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "orderId", 1);
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("orderId", orderId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeleteOrder", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/order/{orderId}").ToString();
_url = _url.Replace("{orderId}", System.Uri.EscapeDataString(orderId));
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 400 && (int)_statusCode != 404)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateUser", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateUsersWithArrayInput", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/createWithArray").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateUsersWithListInput", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/createWithList").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<string,LoginUserHeaders>> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (username == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "username");
}
if (password == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "password");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("username", username);
tracingParameters.Add("password", password);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "LoginUser", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/login").ToString();
List<string> _queryParameters = new List<string>();
if (username != null)
{
_queryParameters.Add(string.Format("username={0}", System.Uri.EscapeDataString(username)));
}
if (password != null)
{
_queryParameters.Add(string.Format("password={0}", System.Uri.EscapeDataString(password)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<string,LoginUserHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<string>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LoginUserHeaders>(Newtonsoft.Json.JsonSerializer.Create(DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> LogoutUserWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "LogoutUser", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/logout").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (username == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "username");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("username", username);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUserByName", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/{username}").ToString();
_url = _url.Replace("{username}", System.Uri.EscapeDataString(username));
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 404)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<User>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<User>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (username == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "username");
}
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("username", username);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UpdateUser", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/{username}").ToString();
_url = _url.Replace("{username}", System.Uri.EscapeDataString(username));
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 400 && (int)_statusCode != 404)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (username == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "username");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("username", username);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeleteUser", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/{username}").ToString();
_url = _url.Replace("{username}", System.Uri.EscapeDataString(username));
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 400 && (int)_statusCode != 404)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| yugangw-msft/autorest | src/generator/AutoRest.CSharp.Tests/Expected/PetstoreV2NoSync/SwaggerPetstoreV2.cs | C# | mit | 118,406 |
package org.kumoricon.service;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class FieldCleanerTest {
@Test
public void testCleanNameTrimsWhitespace() {
assertEquals("Test", FieldCleaner.cleanName(" Test \n"));
}
@Test
public void testCleanNameHandlesNull() {
assertEquals(null, FieldCleaner.cleanName(null));
}
@Test
public void testCleanNameCapitalizesFirstLetter() {
assertEquals("John Smith", FieldCleaner.cleanName("john smith"));
}
@Test
public void testCleanNameDoesNotChangeOtherLetters() {
// Don't try to fix capital inside words - MacDonald and Macdonald are both correct
assertEquals("Old McDonald", FieldCleaner.cleanName("old mcDonald"));
assertEquals("Old Mcdonald", FieldCleaner.cleanName("old mcdonald"));
}
@Test
public void testCleanPhoneNumberTrimsSpaces() {
String testNumber = " 123 ";
assertEquals("123", FieldCleaner.cleanPhoneNumber(testNumber));
}
@Test
public void testCleanPhoneNumberRemovesCharacters() {
String testNumber = "(123) 456-2712 And stuff";
assertEquals("(123) 456-2712", FieldCleaner.cleanPhoneNumber(testNumber));
}
@Test
public void testCleanPhoneNumberHandlesNull() {
String testNumber = null;
assertEquals(null, FieldCleaner.cleanPhoneNumber(testNumber));
}
@Test
public void testCleanPhoneNumberAddsParens() {
String testNumber = "1234567890";
assertEquals("(123) 456-7890", FieldCleaner.cleanPhoneNumber(testNumber));
}
@Test
public void testCleanPhoneNumberHandlesLongNumbers() {
// For long (non-American) phone numbers, just leave the numbers and spaces as is.
String testNumber = "+1 04 12 123-12341234";
assertEquals(testNumber, FieldCleaner.cleanPhoneNumber(testNumber));
}
@Test
public void testCleanPhoneNumberHandlesShortNumbers() {
// Leave short numbers as is - though hopefully people will remember to enter
// the area code, that shouldn't be enforced in this function.
String testNumber = "867-5309";
assertEquals(testNumber, FieldCleaner.cleanPhoneNumber(testNumber));
}
@Test
public void testCleanPhoneNumberLeavesXcharacter() {
String testNumber = "867-5309 x1234";
assertEquals(testNumber, FieldCleaner.cleanPhoneNumber(testNumber));
}
@Test
public void testCleanPhoneNumberStartsWithPlus() {
String testNumber = "+64 6-759 9128";
assertEquals(testNumber, FieldCleaner.cleanPhoneNumber(testNumber));
}
@Test
public void testCleanPhoneNumberRemovesLettersFromLongNumber() {
String testNumber = "+1 04 12 123-12341234 asdfasdf x12321";
assertEquals("+1 04 12 123-12341234 x12321", FieldCleaner.cleanPhoneNumber(testNumber));
}
} | jashort/kumoreg | src/test/java/org/kumoricon/service/FieldCleanerTest.java | Java | mit | 2,914 |
namespace Nancy.Bootstrapper
{
using System;
public sealed class ModuleRegistration
{
/// <summary>
/// Represents a module type for registration into a container
/// </summary>
/// <param name="moduleType">Type of the module</param>
/// <param name="moduleKey">Key that can be used to retrieve the specific module via <see cref="INancyModuleCatalog.GetModuleByKey"/></param>
public ModuleRegistration(Type moduleType, string moduleKey)
{
ModuleType = moduleType;
ModuleKey = moduleKey;
}
public string ModuleKey { get; private set; }
public Type ModuleType { get; private set; }
}
} | paulcbetts/Nancy | src/Nancy/Bootstrapper/ModuleRegistrationType.cs | C# | mit | 727 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace System.Devices.Gpio
{
public class GpioController : IDisposable
{
private IDictionary<int, GpioPin> _pins;
public GpioController(PinNumberingScheme numbering = PinNumberingScheme.Gpio)
{
GpioDriver driver;
bool isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
if (isLinux)
{
driver = new UnixDriver();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
driver = new Windows10Driver();
}
else
{
throw new NotSupportedException($"Platform '{RuntimeInformation.OSDescription}' not supported");
}
Initialize(driver, numbering);
}
public GpioController(GpioDriver driver, PinNumberingScheme numbering = PinNumberingScheme.Gpio)
{
Initialize(driver, numbering);
}
private void Initialize(GpioDriver driver, PinNumberingScheme numbering)
{
Driver = driver;
Numbering = numbering;
_pins = new Dictionary<int, GpioPin>();
driver.ValueChanged += OnPinValueChanged;
}
public void Dispose()
{
while (_pins.Count > 0)
{
GpioPin pin = _pins.Values.First();
pin.Dispose();
}
Driver.Dispose();
}
internal GpioDriver Driver { get; private set; }
public PinNumberingScheme Numbering { get; set; }
public int PinCount => Driver.PinCount;
public IEnumerable<GpioPin> OpenPins => _pins.Values;
public bool IsPinOpen(int pinNumber)
{
int gpioNumber = Driver.ConvertPinNumber(pinNumber, Numbering, PinNumberingScheme.Gpio);
return _pins.ContainsKey(gpioNumber);
}
public GpioPin this[int pinNumber]
{
get
{
int gpioNumber = Driver.ConvertPinNumber(pinNumber, Numbering, PinNumberingScheme.Gpio);
bool isOpen = _pins.TryGetValue(gpioNumber, out GpioPin pin);
if (!isOpen)
{
throw new GpioException("The pin must be already open");
}
return pin;
}
}
public GpioPin OpenPin(int pinNumber)
{
int gpioNumber = Driver.ConvertPinNumber(pinNumber, Numbering, PinNumberingScheme.Gpio);
bool isOpen = _pins.TryGetValue(gpioNumber, out GpioPin pin);
if (isOpen)
{
throw new GpioException("Pin already open");
}
Driver.OpenPin(gpioNumber);
pin = new GpioPin(this, gpioNumber);
_pins[gpioNumber] = pin;
return pin;
}
public void ClosePin(int pinNumber)
{
int gpioNumber = Driver.ConvertPinNumber(pinNumber, Numbering, PinNumberingScheme.Gpio);
bool isOpen = _pins.TryGetValue(gpioNumber, out GpioPin pin);
if (isOpen)
{
InternalClosePin(pin);
}
}
public void ClosePin(GpioPin pin)
{
if (pin == null)
{
throw new ArgumentNullException(nameof(pin));
}
if (pin.Controller != this)
{
throw new ArgumentException("The given pin does not belong to this controller");
}
InternalClosePin(pin);
}
private void InternalClosePin(GpioPin pin)
{
int gpioNumber = pin.GpioNumber;
_pins.Remove(gpioNumber);
Driver.ClosePin(gpioNumber);
}
private void OnPinValueChanged(object sender, PinValueChangedEventArgs e)
{
GpioPin pin = _pins[e.GpioPinNumber];
pin?.OnValueChanged(e);
}
}
}
| stephentoub/corefxlab | src/System.Devices.Gpio/GpioController.cs | C# | mit | 4,293 |
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Flash;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class HasVideo extends AbstractTag
{
protected $Id = 'hasVideo';
protected $Name = 'HasVideo';
protected $FullName = 'Flash::Meta';
protected $GroupName = 'Flash';
protected $g0 = 'Flash';
protected $g1 = 'Flash';
protected $g2 = 'Video';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Has Video';
}
| bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/Flash/HasVideo.php | PHP | mit | 775 |
<div class="modal-body">
<div id="product-pop-up" style="width: 700px;">
<div class="product-page product-pop-up">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-3">
<div class="product-main-image">
<img ng-src="images/model7.jpg" alt="Cool green dress with red bell" class="img-responsive">
</div>
<!--<div class="product-other-images">-->
<!--<a href="#" class="active"><img alt="Berry Lace Dress" src="images/model3.jpg"></a>-->
<!--<a href="#"><img alt="Berry Lace Dress" src="images/model4.jpg"></a>-->
<!--<a href="#"><img alt="Berry Lace Dress" src="images/model5.jpg"></a>-->
<!--</div>-->
</div>
<div class="col-md-6 col-sm-6 col-xs-9">
<h1>Cool green dress with red bell</h1>
<div class="price-availability-block clearfix">
<div class="price">
<strong><span>$</span>47.00</strong>
<em>$<span>62.00</span></em>
</div>
<div class="availability">
Availability: <strong>In Stock</strong>
</div>
</div>
<div class="description">
<p>Lorem ipsum dolor ut sit ame dolore adipiscing elit, sed nonumy nibh sed euismod laoreet dolore magna aliquarm erat volutpat
Nostrud duis molestie at dolore.</p>
</div>
<br>
<div class="product-page-options">
<div class="col-md-4" style="padding-left: 0px;">
<div class="pull-left">
<label class="control-label">Size:</label>
<select class="form-control input-sm">
<option>L</option>
<option>M</option>
<option>XL</option>
</select>
</div>
</div>
<div class="col-md-4" style="padding-left: 0px;">
<div class="pull-left">
<label class="control-label">Color:</label>
<select class="form-control input-sm">
<option>Red</option>
<option>Blue</option>
<option>Black</option>
</select>
</div>
</div>
</div>
<!--<div class="product-page-cart">-->
<!--<div class="product-quantity">-->
<!--<input id="product-quantity3" type="text" value="1" readonly class="form-control input-sm">-->
<!--</div>-->
<!--<button class="btn btn-primary" type="submit">Add to cart</button>-->
<!--<button class="btn btn-default" type="submit">More details</button>-->
<!--</div>-->
</div>
<div class="sticker sticker-sale"></div>
</div>
</div>
</div>
</div> | OrcMan1020/UncleBu | app/template/product_detail.html | HTML | mit | 3,555 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("StripedTowel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StripedTowel")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("decfa348-c6b2-4e67-8efd-049b86dd2301")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| bozhidar-slavov/01.CSharp-Fundamentals | Exam-Preparation/4th-Problems/StripedTowel/Properties/AssemblyInfo.cs | C# | mit | 1,400 |
"""
run quality assurance measures on functional data
"""
import sys,glob
sys.path.append('/corral-repl/utexas/poldracklab/software_lonestar/quality-assessment-protocol')
import os
import numpy
from run_shell_cmd import run_shell_cmd
from compute_fd import compute_fd
from qap import load_func,load_image, load_mask, summary_mask, cnr,efc,fber,fwhm,artifacts,ghost_all,calc_mean_func,calc_dvars,mean_outlier_timepoints,mean_quality_timepoints
basedir='/corral-repl/utexas/poldracklab/data/selftracking/shared_dataset'
funcfiles=glob.glob(os.path.join(basedir,'sub*/BOLD/resting_run001/bold.nii.gz'))
funcdata={'subcode':[],'func_efc':[],'func_fber':[],'func_fwhm':[],'func_gsr':[],'func_dvars':[],'func_outlier':[],'func_quality':[],'func_mean_fd':[],'func_num_fd':[],'func_perc_fd':[]}
#for funcfile in funcfiles:
func_file=funcfiles[0]
if 1:
subcode=func_file.split('/')[7]
print 'processing',subcode
funcdata['subcode'].append(subcode)
mask_file=func_file.replace('.nii.gz','_brain_mask.nii.gz')
if not os.path.exists(mask_file):
cmd='bet %s %s -m -F'%(func_file,func_file.replace('.nii.gz','_brain'))
print cmd
run_shell_cmd(cmd)
func_data = load_func(func_file,mask_file)
mean_func_data = calc_mean_func(func_file)
func_mask = load_mask(mask_file)
func_efc = efc(func_data)
#func_fber = fber(func_data, func_mask)
#func_fwhm = fwhm(func_file, mask_file, out_vox=False)
print 'running ghost_all'
_,func_gsr,_=ghost_all(mean_func_data,func_mask)
print 'running calc_dvars'
func_dvars = calc_dvars(func_data, output_all=False)
print 'running mean_outlier_timepoints'
func_outlier = mean_outlier_timepoints(func_file, mask_file, out_fraction=True)
print 'running compute_fd'
motpars=numpy.loadtxt(func_file.replace('.nii.gz','_mcf.par'))
fd=compute_fd(motpars)
sdf
funcdata['mean_gm'].append(mean_gm)
funcdata['mean_wm'].append(mean_wm)
funcdata['std_bg'].append(std_bg)
funcdata['anat_efc'].append(anat_efc)
funcdata['anat_fber'].append(anat_fber)
funcdata['anat_fwhm'].append(anat_fwhm)
funcdata['anat_qi1'].append(anat_qi1)
| vsoch/myconnectome | myconnectome/qa/run_qap_func.py | Python | mit | 2,129 |
<?php
namespace N98\Util;
class DateTime
{
/**
* Returns a readable string with time difference
*
* @param \DateTime $time1
* @param \DateTime $time2
* @return string
*/
public function getDifferenceAsString(\DateTime $time1, \DateTime $time2)
{
if ($time1 == $time2) {
return '0';
}
$interval = $time1->diff($time2);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d');
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
$seconds = $interval->format('%s');
$differenceString = (($years) ? $years . 'Y ' : '')
. (($months) ? $months. 'M ' : '')
. (($days) ? $days. 'd ' : '')
. (($hours) ? $hours. 'h ' : '')
. (($minutes) ? $minutes . 'm ' : '')
. (($seconds) ? $seconds . 's' : '')
;
return trim($differenceString);
}
} | iMi-digital/n98-magerun | src/N98/Util/DateTime.php | PHP | mit | 1,002 |
#include "tester.hpp"
#include "../sago/platform_folders.h"
int main() {
run_test(sago::getMusicFolder());
sago::PlatformFolders p;
run_test(p.getMusicFolder());
return 0;
}
| sago007/PlatformFolders | test/getMusicFolder.cpp | C++ | mit | 179 |
var RELANG = {};
RELANG['sq'] = {
html: 'HTML',
video: 'Video',
image: 'Fotografi',
table: 'Tabelë',
link: 'Link',
link_insert: 'Lidh linq ...',
unlink: 'Hiq linkun',
formatting: 'Stilet',
paragraph: 'Paragraf',
quote: 'Kuotë',
code: 'Kod',
header1: 'Header 1',
header2: 'Header 2',
header3: 'Header 3',
header4: 'Header 4',
bold: 'Te trasha / Bold',
italic: 'Kursive / Italic',
fontcolor: 'Ngjyra e shkronjave',
backcolor: 'Ngjyra e mbrapavisë së shkronjave',
unorderedlist: 'Liste pa renditje',
orderedlist: 'Liste me renditje',
outdent: 'Outdent',
indent: 'Indent',
redo: 'Ribëj',
undo: 'Zhbëj',
cut: 'Cut',
cancel: 'Anulo',
insert: 'Insert',
save: 'Ruaje',
_delete: 'Fshije',
insert_table: 'Shto tabelë',
insert_row_above: 'Shto rresht sipër',
insert_row_below: 'Shto rresht përfundi',
insert_column_left: 'Shto kolonë majtas',
insert_column_right: 'Shto kolonë djathtas',
delete_column: 'Fshije kolonën',
delete_row: 'Fshije rreshtin',
delete_table: 'Fshije tabelën',
rows: 'Rreshta',
columns: 'Kolona',
add_head: 'Shto titujt e tabelës',
delete_head: 'Fshije titujt e tabelës',
title: 'Titulli',
image_position: 'Pozita',
none: 'Normale',
left: 'Majtas',
right: 'Djathtas',
image_web_link: 'Linku i fotografisë në internet',
text: 'Teksti',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video embed code',
file: 'Fajll',
upload: 'Ngarko',
download: 'Shkarko',
choose: 'Zgjedh',
or_choose: 'Ose zgjedh',
drop_file_here: 'Gjuaje fajllin këtu',
align_left: 'Rreshtoje majtas',
align_center: 'Rreshtoje në mes',
align_right: 'Rreshtoje djathtas',
align_justify: 'Rreshtoje të gjithin njejt',
horizontalrule: 'Vizë horizontale',
fullscreen: 'Pamje e plotë',
deleted: 'E fshirë',
anchor: 'Anchor',
link_new_tab: 'Open link in new tab'
};
| cremol/symphony-demo | extensions/richtext_redactor/lib/lang/sq.js | JavaScript | mit | 1,958 |
<div controller="components.tester.StateManager">
<style>
[tag='state-manager-container'] {
display: none;
}
.all-states {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
.inactive-state {
display: none;
}
</style>
<div tag="state-manager-container">
<embed select="[name]" />
</div>
</div> | jaredjbarnes/WoodlandCreatures | packages/WebLib.2.0.0.724/content/lib/weblib/components/tester/StateManager.html | HTML | mit | 469 |
package Nov2020_FBPrep;
public class _046RegularExpressionMatching {
public static void main(String[] args) {
System.out.println(isMatch("aa", "a"));
System.out.println(isMatch("aa", "a*"));
System.out.println(isMatch("ab", ".*"));
System.out.println(isMatch("aab", "c*a*b"));
System.out.println(isMatch("mississippi", "mis*is*p*."));
}
public static boolean isMatch(String s, String p) {
if (s.equals(p))
return true;
boolean[][] dp = new boolean[s.length() + 1][p.length() + 1];
dp[0][0] = true;
// populate first Row;
for (int j = 1; j < dp[0].length; j++) {
if (p.charAt(j - 1) == '*') {
dp[0][j] = dp[0][j - 2];
}
}
// populate first Row;
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
if (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.') {
dp[i][j] = dp[i - 1][j - 1];
} else if (p.charAt(j - 1) == '*') {
dp[i][j] = dp[i][j - 2];
if (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))
dp[i][j] = dp[i][j] || dp[i - 1][j];
} else {
dp[i][j] = false;
}
}
}
return dp[dp.length - 1][dp[0].length - 1];
}
}
| darshanhs90/Java-InterviewPrep | src/Nov2020_FBPrep/_046RegularExpressionMatching.java | Java | mit | 1,166 |
__version__ = "master"
| jvandijk/pla | pla/version.py | Python | mit | 23 |
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Repository;
use Composer\Package\PackageInterface;
/**
* Composite repository.
*
* @author Beau Simensen <beau@dflydev.com>
*/
class CompositeRepository implements RepositoryInterface
{
/**
* List of repositories
* @var array
*/
private $repositories;
/**
* Constructor
* @param array $repositories
*/
public function __construct(array $repositories)
{
$this->repositories = array();
foreach ($repositories as $repo) {
$this->addRepository($repo);
}
}
/**
* Returns all the wrapped repositories
*
* @return array
*/
public function getRepositories()
{
return $this->repositories;
}
/**
* {@inheritdoc}
*/
public function hasPackage(PackageInterface $package)
{
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
if ($repository->hasPackage($package)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function findPackage($name, $version)
{
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$package = $repository->findPackage($name, $version);
if (null !== $package) {
return $package;
}
}
return null;
}
/**
* {@inheritdoc}
*/
public function findPackages($name, $version = null)
{
$packages = array();
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$packages[] = $repository->findPackages($name, $version);
}
return call_user_func_array('array_merge', $packages);
}
/**
* {@inheritDoc}
*/
public function filterPackages($callback, $class = 'Composer\Package\Package')
{
foreach ($this->repositories as $repository) {
if (false === $repository->filterPackages($callback, $class)) {
return false;
}
}
return true;
}
/**
* {@inheritdoc}
*/
public function getPackages()
{
$packages = array();
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$packages[] = $repository->getPackages();
}
return call_user_func_array('array_merge', $packages);
}
/**
* {@inheritdoc}
*/
public function removePackage(PackageInterface $package)
{
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$repository->removePackage($package);
}
}
/**
* {@inheritdoc}
*/
public function count()
{
$total = 0;
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$total += $repository->count();
}
return $total;
}
/**
* Add a repository.
* @param RepositoryInterface $repository
*/
public function addRepository(RepositoryInterface $repository)
{
if ($repository instanceof self) {
foreach ($repository->getRepositories() as $repo) {
$this->addRepository($repo);
}
} else {
$this->repositories[] = $repository;
}
}
}
| bamarni/composer | src/Composer/Repository/CompositeRepository.php | PHP | mit | 3,809 |
'use strict';
const chalk = require('chalk');
const Task = require('../models/task');
const Watcher = require('../models/watcher');
const Builder = require('../models/builder');
const pDefer = require('p-defer');
class BuildWatchTask extends Task {
constructor(options) {
super(options);
this._builder = null;
this._runDeferred = null;
}
async run(options) {
let { ui } = this;
ui.startProgress(chalk.green('Building'), chalk.green('.'));
this._runDeferred = pDefer();
let builder = (this._builder =
options._builder ||
new Builder({
ui,
outputPath: options.outputPath,
environment: options.environment,
project: this.project,
}));
ui.writeLine(`Environment: ${options.environment}`);
let watcher =
options._watcher ||
new Watcher({
ui,
builder,
analytics: this.analytics,
options,
});
await watcher;
// Run until failure or signal to exit
return this._runDeferred.promise;
}
/**
* Exit silently
*
* @private
* @method onInterrupt
*/
async onInterrupt() {
await this._builder.cleanup();
this._runDeferred.resolve();
}
}
module.exports = BuildWatchTask;
| HeroicEric/ember-cli | lib/tasks/build-watch.js | JavaScript | mit | 1,250 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.gallery;
import org.joda.time.Period;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* A rule condition based on a metric crossing a threshold.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "odata.type")
@JsonTypeName("Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition")
public class ThresholdRuleCondition extends RuleCondition {
/**
* the resource from which the rule collects its data. For this type
* dataSource will always be of type RuleMetricDataSource.
*/
@JsonProperty(value = "dataSource")
private RuleDataSource dataSource;
/**
* the operator used to compare the data and the threshold. Possible values
* include: 'GreaterThan', 'GreaterThanOrEqual', 'LessThan',
* 'LessThanOrEqual'.
*/
@JsonProperty(value = "operator", required = true)
private ConditionOperator operator;
/**
* the threshold value that activates the alert.
*/
@JsonProperty(value = "threshold", required = true)
private double threshold;
/**
* the period of time (in ISO 8601 duration format) that is used to monitor
* alert activity based on the threshold. If specified then it must be
* between 5 minutes and 1 day.
*/
@JsonProperty(value = "windowSize")
private Period windowSize;
/**
* the time aggregation operator. How the data that are collected should be
* combined over time. The default value is the PrimaryAggregationType of
* the Metric. Possible values include: 'Average', 'Minimum', 'Maximum',
* 'Total', 'Last'.
*/
@JsonProperty(value = "timeAggregation")
private TimeAggregationOperator timeAggregation;
/**
* Get the dataSource value.
*
* @return the dataSource value
*/
public RuleDataSource dataSource() {
return this.dataSource;
}
/**
* Set the dataSource value.
*
* @param dataSource the dataSource value to set
* @return the ThresholdRuleCondition object itself.
*/
public ThresholdRuleCondition withDataSource(RuleDataSource dataSource) {
this.dataSource = dataSource;
return this;
}
/**
* Get the operator value.
*
* @return the operator value
*/
public ConditionOperator operator() {
return this.operator;
}
/**
* Set the operator value.
*
* @param operator the operator value to set
* @return the ThresholdRuleCondition object itself.
*/
public ThresholdRuleCondition withOperator(ConditionOperator operator) {
this.operator = operator;
return this;
}
/**
* Get the threshold value.
*
* @return the threshold value
*/
public double threshold() {
return this.threshold;
}
/**
* Set the threshold value.
*
* @param threshold the threshold value to set
* @return the ThresholdRuleCondition object itself.
*/
public ThresholdRuleCondition withThreshold(double threshold) {
this.threshold = threshold;
return this;
}
/**
* Get the windowSize value.
*
* @return the windowSize value
*/
public Period windowSize() {
return this.windowSize;
}
/**
* Set the windowSize value.
*
* @param windowSize the windowSize value to set
* @return the ThresholdRuleCondition object itself.
*/
public ThresholdRuleCondition withWindowSize(Period windowSize) {
this.windowSize = windowSize;
return this;
}
/**
* Get the timeAggregation value.
*
* @return the timeAggregation value
*/
public TimeAggregationOperator timeAggregation() {
return this.timeAggregation;
}
/**
* Set the timeAggregation value.
*
* @param timeAggregation the timeAggregation value to set
* @return the ThresholdRuleCondition object itself.
*/
public ThresholdRuleCondition withTimeAggregation(TimeAggregationOperator timeAggregation) {
this.timeAggregation = timeAggregation;
return this;
}
}
| martinsawicki/azure-sdk-for-java | azure-mgmt-insights/src/main/java/com/microsoft/azure/management/gallery/ThresholdRuleCondition.java | Java | mit | 4,537 |
#!/usr/bin/python
'''
Created on May 14, 2012
@author: Charlie
'''
import ConfigParser
import boto
import cgitb
cgitb.enable()
class MyClass(object):
def __init__(self, domain):
config = ConfigParser.RawConfigParser()
config.read('.boto')
key = config.get('Credentials', 'aws_access_key_id')
secretKey = config.get('Credentials', 'aws_secret_access_key')
self.conn = boto.connect_sdb(key, secretKey)
self.domain = domain
def showDomains(self):
domains = self.conn.get_all_domains()
print domains
def createDomain(self):
self.conn.create_domain(self.domain)
def addData(self, itemName, itemAttrs):
dom = self.conn.get_domain(self.domain)
item_name = itemName
dom.put_attributes(item_name, itemAttrs)
def startXml(self):
xml = "Content-Type: text/xml\n\n"
xml += "<?xml version='1.0'?>\n"
xml += '<test01 count="5">\n'
return xml
def showQuery(self, query):
dom = self.conn.get_domain(self.domain)
result = dom.select(query)
xml = self.startXml()
for item in result:
xml += "\t<line>\n"
keys = item.keys()
keys.sort()
for x in keys:
xml += '\t\t<' + x + '>' + item[x] + '</' + x + '>\n'
xml += "\t</line>\n"
xml += '</test01>'
return xml
my_class = MyClass("Test01")
# my_class.addData('Line01', {'Field01': 'one', 'Field02': 'two'})
# my_class.showDomains()
print my_class.showQuery('select * from Test01')
| donlee888/JsObjects | Python/Prog282SimpleDb/scripts/simpledb.py | Python | mit | 1,593 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class FlattenedProduct(Resource):
"""FlattenedProduct
:param id: Resource Id
:type id: str
:param type: Resource Type
:type type: str
:param tags:
:type tags: dict
:param location: Resource Location
:type location: str
:param name: Resource Name
:type name: str
:param pname:
:type pname: str
:param flattened_product_type:
:type flattened_product_type: str
:param provisioning_state_values: Possible values include: 'Succeeded',
'Failed', 'canceled', 'Accepted', 'Creating', 'Created', 'Updating',
'Updated', 'Deleting', 'Deleted', 'OK'
:type provisioning_state_values: str
:param provisioning_state:
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'location': {'key': 'location', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'pname': {'key': 'properties.pname', 'type': 'str'},
'flattened_product_type': {'key': 'properties.type', 'type': 'str'},
'provisioning_state_values': {'key': 'properties.provisioningStateValues', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, flattened_product_type=None, provisioning_state_values=None, provisioning_state=None, **kwargs):
super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name, **kwargs)
self.pname = pname
self.flattened_product_type = flattened_product_type
self.provisioning_state_values = provisioning_state_values
self.provisioning_state = provisioning_state
| jkonecki/autorest | AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py | Python | mit | 2,348 |
/*
Copyright (c) 2012 <a href="http://www.gutgames.com">James Craig</a>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#region Usings
using Utilities.Random.BaseClasses;
using Utilities.Random.Interfaces;
#endregion
namespace Utilities.Random.NameGenerators
{
/// <summary>
/// Female name generator
/// </summary>
public class FemaleNameGenerator : GeneratorAttributeBase, IGenerator<string>
{
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="Prefix">Should a prefix be generated</param>
/// <param name="MiddleName">Should a middle name be generated</param>
/// <param name="LastName">Should a last name be generated</param>
/// <param name="Suffix">Should a suffix be generated</param>
public FemaleNameGenerator(bool Prefix = false, bool MiddleName = false, bool LastName = true, bool Suffix = false)
: base("", "")
{
this.Prefix = Prefix;
this.MiddleName = MiddleName;
this.Suffix = Suffix;
this.LastName = LastName;
}
#endregion
#region Properties
/// <summary>
/// Should a prefix be generated?
/// </summary>
public virtual bool Prefix { get; protected set; }
/// <summary>
/// Should a middle name be generated?
/// </summary>
public virtual bool MiddleName { get; protected set; }
/// <summary>
/// Should a suffix be generated?
/// </summary>
public virtual bool Suffix { get; protected set; }
/// <summary>
/// Should a last name be generated?
/// </summary>
public virtual bool LastName { get; protected set; }
#endregion
#region Functions
/// <summary>
/// Generates a random value of the specified type
/// </summary>
/// <param name="Rand">Random number generator that it can use</param>
/// <returns>A randomly generated object of the specified type</returns>
public virtual string Next(System.Random Rand)
{
return (Prefix ? new FemaleNamePrefixGenerator().Next(Rand) + " " : "")
+ new FemaleFirstNameGenerator().Next(Rand)
+ (MiddleName ? " " + new FemaleFirstNameGenerator().Next(Rand) : "")
+ (LastName ? " " + new LastNameGenerator().Next(Rand) : "")
+ (Suffix ? " " + new NameSuffixGenerator().Next(Rand) : "");
}
/// <summary>
/// Generates a random value of the specified type
/// </summary>
/// <param name="Rand">Random number generator that it can use</param>
/// <param name="Min">Minimum value (inclusive)</param>
/// <param name="Max">Maximum value (inclusive)</param>
/// <returns>A randomly generated object of the specified type</returns>
public virtual string Next(System.Random Rand, string Min, string Max)
{
return Next(Rand);
}
/// <summary>
/// Generates next object
/// </summary>
/// <param name="Rand">Random number generator</param>
/// <returns>The next object</returns>
public override object NextObj(System.Random Rand)
{
return Next(Rand);
}
#endregion
}
} | khellang/Craig-s-Utility-Library | Utilities/Random/NameGenerators/FemaleNameGenerator.cs | C# | mit | 4,499 |
<?php
/**
* elFinder driver for Volume Group.
*
* @author Naoki Sawada
**/
class elFinderVolumeGroup extends elFinderVolumeDriver
{
/**
* Driver id
* Must be started from letter and contains [a-z0-9]
* Used as part of volume id.
*
* @var string
**/
protected $driverId = 'g';
/**
* Constructor
* Extend options with required fields.
*/
public function __construct()
{
$this->options['type'] = 'group';
$this->options['path'] = '/';
$this->options['dirUrlOwn'] = true;
$this->options['syncMinMs'] = 0;
$this->options['tmbPath'] = '';
$this->options['disabled'] = [
'archive',
'cut',
'duplicate',
'edit',
'extract',
'getfile',
'mkdir',
'mkfile',
'paste',
'rename',
'resize',
'rm',
'upload',
];
}
/*********************************************************************/
/* FS API */
/*********************************************************************/
/*********************** paths/urls *************************/
/**
* {@inheritdoc}
**/
protected function _dirname($path)
{
return '/';
}
/**
* {@inheritdoc}
**/
protected function _basename($path)
{
return '';
}
/**
* {@inheritdoc}
**/
protected function _joinPath($dir, $name)
{
return '/'.$name;
}
/**
* {@inheritdoc}
**/
protected function _normpath($path)
{
return '/';
}
/**
* {@inheritdoc}
**/
protected function _relpath($path)
{
return '/';
}
/**
* {@inheritdoc}
**/
protected function _abspath($path)
{
return '/';
}
/**
* {@inheritdoc}
**/
protected function _path($path)
{
return '/';
}
/**
* {@inheritdoc}
**/
protected function _inpath($path, $parent)
{
return false;
}
/***************** file stat ********************/
/**
* {@inheritdoc}
**/
protected function _stat($path)
{
if ($path === '/') {
return [
'size' => 0,
'ts' => 0,
'mime' => 'directory',
'read' => true,
'write' => false,
'locked' => true,
'hidden' => false,
'dirs' => 0,
];
}
return false;
}
/**
* {@inheritdoc}
**/
protected function _subdirs($path)
{
$dirs = false;
if ($path === '/') {
return true;
}
return $dirs;
}
/**
* {@inheritdoc}
**/
protected function _dimensions($path, $mime)
{
return false;
}
/******************** file/dir content *********************/
/**
* {@inheritdoc}
**/
protected function readlink($path)
{
}
/**
* {@inheritdoc}
**/
protected function _scandir($path)
{
return [];
}
/**
* {@inheritdoc}
**/
protected function _fopen($path, $mode = 'rb')
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _fclose($fp, $path = '')
{
return true;
}
/******************** file/dir manipulations *************************/
/**
* {@inheritdoc}
**/
protected function _mkdir($path, $name)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _mkfile($path, $name)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _symlink($source, $targetDir, $name)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _copy($source, $targetDir, $name)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _move($source, $targetDir, $name)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _unlink($path)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _rmdir($path)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _save($fp, $dir, $name, $stat)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _getContents($path)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _filePutContents($path, $content)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _checkArchivers()
{
}
/**
* {@inheritdoc}
**/
protected function _chmod($path, $mode)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _findSymlinks($path)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _extract($path, $arc)
{
return false;
}
/**
* {@inheritdoc}
**/
protected function _archive($dir, $files, $name, $arc)
{
return false;
}
}
| recca0120/elfinder | lib/elFinderVolumeGroup.class.php | PHP | mit | 5,389 |
<?php
class Example {
/** @return array */
public function read($token)
{
if (!$token || !file_exists($file = 'somefile.txt')) {
return [];
}
// Should infer the type of $file as string because the above condition would set $file if it did not return.
return $file;
}
}
| etsy/phan | tests/files/src/0717_variable_assign_in_complex_condition.php | PHP | mit | 330 |
module.exports={A:{A:{"1":"E A B","2":"H C G EB"},B:{"1":"D p x J L N I"},C:{"1":"0 1 2 3 4 5 6 8 9 R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y","2":"YB BB","132":"F K H C G E A B D p x J L N I O P Q WB QB"},D:{"1":"0 1 2 3 4 5 6 8 9 F K H C G E A B D p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y KB aB FB a GB HB IB"},E:{"1":"F K H C G E A B LB MB NB OB PB z RB","2":"JB CB"},F:{"1":"0 J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w","2":"7 E B D SB TB UB VB z AB XB"},G:{"1":"G ZB DB bB cB dB eB fB gB hB iB jB kB","2":"CB"},H:{"2":"lB"},I:{"1":"BB F a oB pB DB qB rB","2":"mB nB"},J:{"1":"C A"},K:{"1":"7 B D M z AB","2":"A"},L:{"1":"a"},M:{"1":"y"},N:{"1":"A B"},O:{"1":"sB"},P:{"1":"F K tB"},Q:{"1":"uB"},R:{"1":"vB"}},B:6,C:"MP3 audio format"};
| AngeliaGong/AngeliaGong.github.io | node_modules/caniuse-lite/data/features/mp3.js | JavaScript | mit | 837 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Template\TagLib;
use Think\Template\TagLib;
defined('THINK_PATH') or exit();
/**
* Html标签库驱动
*/
class Html extends TagLib{
// 标签定义
protected $tags = array(
// 标签定义: attr 属性列表 close 是否闭合(0 或者1 默认1) alias 标签别名 level 嵌套层次
'editor' => array('attr'=>'id,name,style,width,height,type','close'=>1),
'select' => array('attr'=>'name,options,values,output,multiple,id,size,first,change,selected,dblclick','close'=>0),
'grid' => array('attr'=>'id,pk,style,action,actionlist,show,datasource','close'=>0),
'list' => array('attr'=>'id,pk,style,action,actionlist,show,datasource,checkbox','close'=>0),
'imagebtn' => array('attr'=>'id,name,value,type,style,click','close'=>0),
'checkbox' => array('attr'=>'name,checkboxes,checked,separator','close'=>0),
'radio' => array('attr'=>'name,radios,checked,separator','close'=>0)
);
/**
* editor标签解析 插入可视化编辑器
* 格式: <html:editor id="editor" name="remark" type="FCKeditor" style="" >{$vo.remark}</html:editor>
* @access public
* @param array $tag 标签属性
* @return string|void
*/
public function _editor($tag,$content) {
$id = !empty($tag['id'])?$tag['id']: '_editor';
$name = $tag['name'];
$style = !empty($tag['style'])?$tag['style']:'';
$width = !empty($tag['width'])?$tag['width']: '100%';
$height = !empty($tag['height'])?$tag['height'] :'320px';
// $content = $tag['content'];
$type = $tag['type'] ;
switch(strtoupper($type)) {
case 'FCKEDITOR':
$parseStr = '<!-- 编辑器调用开始 --><script type="text/javascript" src="__ROOT__/Public/Js/FCKeditor/fckeditor.js"></script><textarea id="'.$id.'" name="'.$name.'">'.$content.'</textarea><script type="text/javascript"> var oFCKeditor = new FCKeditor( "'.$id.'","'.$width.'","'.$height.'" ) ; oFCKeditor.BasePath = "__ROOT__/Public/Js/FCKeditor/" ; oFCKeditor.ReplaceTextarea() ;function resetEditor(){setContents("'.$id.'",document.getElementById("'.$id.'").value)}; function saveEditor(){document.getElementById("'.$id.'").value = getContents("'.$id.'");} function InsertHTML(html){ var oEditor = FCKeditorAPI.GetInstance("'.$id.'") ;if (oEditor.EditMode == FCK_EDITMODE_WYSIWYG ){oEditor.InsertHtml(html) ;}else alert( "FCK必须处于WYSIWYG模式!" ) ;}</script> <!-- 编辑器调用结束 -->';
break;
case 'FCKMINI':
$parseStr = '<!-- 编辑器调用开始 --><script type="text/javascript" src="__ROOT__/Public/Js/FCKMini/fckeditor.js"></script><textarea id="'.$id.'" name="'.$name.'">'.$content.'</textarea><script type="text/javascript"> var oFCKeditor = new FCKeditor( "'.$id.'","'.$width.'","'.$height.'" ) ; oFCKeditor.BasePath = "__ROOT__/Public/Js/FCKMini/" ; oFCKeditor.ReplaceTextarea() ;function resetEditor(){setContents("'.$id.'",document.getElementById("'.$id.'").value)}; function saveEditor(){document.getElementById("'.$id.'").value = getContents("'.$id.'");} function InsertHTML(html){ var oEditor = FCKeditorAPI.GetInstance("'.$id.'") ;if (oEditor.EditMode == FCK_EDITMODE_WYSIWYG ){oEditor.InsertHtml(html) ;}else alert( "FCK必须处于WYSIWYG模式!" ) ;}</script> <!-- 编辑器调用结束 -->';
break;
case 'EWEBEDITOR':
$parseStr = "<!-- 编辑器调用开始 --><script type='text/javascript' src='__ROOT__/Public/Js/eWebEditor/js/edit.js'></script><input type='hidden' id='{$id}' name='{$name}' value='{$conent}'><iframe src='__ROOT__/Public/Js/eWebEditor/ewebeditor.htm?id={$name}' frameborder=0 scrolling=no width='{$width}' height='{$height}'></iframe><script type='text/javascript'>function saveEditor(){document.getElementById('{$id}').value = getHTML();} </script><!-- 编辑器调用结束 -->";
break;
case 'NETEASE':
$parseStr = '<!-- 编辑器调用开始 --><textarea id="'.$id.'" name="'.$name.'" style="display:none">'.$content.'</textarea><iframe ID="Editor" name="Editor" src="__ROOT__/Public/Js/HtmlEditor/index.html?ID='.$name.'" frameBorder="0" marginHeight="0" marginWidth="0" scrolling="No" style="height:'.$height.';width:'.$width.'"></iframe><!-- 编辑器调用结束 -->';
break;
case 'UBB':
$parseStr = '<script type="text/javascript" src="__ROOT__/Public/Js/UbbEditor.js"></script><div style="padding:1px;width:'.$width.';border:1px solid silver;float:left;"><script LANGUAGE="JavaScript"> showTool(); </script></div><div><TEXTAREA id="UBBEditor" name="'.$name.'" style="clear:both;float:none;width:'.$width.';height:'.$height.'" >'.$content.'</TEXTAREA></div><div style="padding:1px;width:'.$width.';border:1px solid silver;float:left;"><script LANGUAGE="JavaScript">showEmot(); </script></div>';
break;
case 'KINDEDITOR':
$parseStr = '<script type="text/javascript" src="__ROOT__/Public/Js/KindEditor/kindeditor.js"></script><script type="text/javascript"> KE.show({ id : \''.$id.'\' ,urlType : "absolute"});</script><textarea id="'.$id.'" style="'.$style.'" name="'.$name.'" >'.$content.'</textarea>';
break;
default :
$parseStr = '<textarea id="'.$id.'" style="'.$style.'" name="'.$name.'" >'.$content.'</textarea>';
}
return $parseStr;
}
/**
* imageBtn标签解析
* 格式: <html:imageBtn type="" value="" />
* @access public
* @param array $tag 标签属性
* @return string|void
*/
public function _imageBtn($tag) {
$name = $tag['name']; //名称
$value = $tag['value']; //文字
$id = isset($tag['id'])?$tag['id']:''; //ID
$style = isset($tag['style'])?$tag['style']:''; //样式名
$click = isset($tag['click'])?$tag['click']:''; //点击
$type = empty($tag['type'])?'button':$tag['type']; //按钮类型
if(!empty($name)) {
$parseStr = '<div class="'.$style.'" ><input type="'.$type.'" id="'.$id.'" name="'.$name.'" value="'.$value.'" onclick="'.$click.'" class="'.$name.' imgButton"></div>';
}else {
$parseStr = '<div class="'.$style.'" ><input type="'.$type.'" id="'.$id.'" name="'.$name.'" value="'.$value.'" onclick="'.$click.'" class="button"></div>';
}
return $parseStr;
}
/**
* imageLink标签解析
* 格式: <html:imageLink type="" value="" />
* @access public
* @param array $tag 标签属性
* @return string|void
*/
public function _imgLink($tag) {
$name = $tag['name']; //名称
$alt = $tag['alt']; //文字
$id = $tag['id']; //ID
$style = $tag['style']; //样式名
$click = $tag['click']; //点击
$type = $tag['type']; //点击
if(empty($type)) {
$type = 'button';
}
$parseStr = '<span class="'.$style.'" ><input title="'.$alt.'" type="'.$type.'" id="'.$id.'" name="'.$name.'" onmouseover="this.style.filter=\'alpha(opacity=100)\'" onmouseout="this.style.filter=\'alpha(opacity=80)\'" onclick="'.$click.'" align="absmiddle" class="'.$name.' imgLink"></span>';
return $parseStr;
}
/**
* select标签解析
* 格式: <html:select options="name" selected="value" />
* @access public
* @param array $tag 标签属性
* @return string|void
*/
public function _select($tag) {
$name = $tag['name'];
$options = $tag['options'];
$values = $tag['values'];
$output = $tag['output'];
$multiple = $tag['multiple'];
$id = $tag['id'];
$size = $tag['size'];
$first = $tag['first'];
$selected = $tag['selected'];
$style = $tag['style'];
$ondblclick = $tag['dblclick'];
$onchange = $tag['change'];
if(!empty($multiple)) {
$parseStr = '<select id="'.$id.'" name="'.$name.'" ondblclick="'.$ondblclick.'" onchange="'.$onchange.'" multiple="multiple" class="'.$style.'" size="'.$size.'" >';
}else {
$parseStr = '<select id="'.$id.'" name="'.$name.'" onchange="'.$onchange.'" ondblclick="'.$ondblclick.'" class="'.$style.'" >';
}
if(!empty($first)) {
$parseStr .= '<option value="" >'.$first.'</option>';
}
if(!empty($options)) {
$parseStr .= '<?php foreach($'.$options.' as $key=>$val) { ?>';
if(!empty($selected)) {
$parseStr .= '<?php if(!empty($'.$selected.') && ($'.$selected.' == $key || in_array($key,$'.$selected.'))) { ?>';
$parseStr .= '<option selected="selected" value="<?php echo $key ?>"><?php echo $val ?></option>';
$parseStr .= '<?php }else { ?><option value="<?php echo $key ?>"><?php echo $val ?></option>';
$parseStr .= '<?php } ?>';
}else {
$parseStr .= '<option value="<?php echo $key ?>"><?php echo $val ?></option>';
}
$parseStr .= '<?php } ?>';
}else if(!empty($values)) {
$parseStr .= '<?php for($i=0;$i<count($'.$values.');$i++) { ?>';
if(!empty($selected)) {
$parseStr .= '<?php if(isset($'.$selected.') && ((is_string($'.$selected.') && $'.$selected.' == $'.$values.'[$i]) || (is_array($'.$selected.') && in_array($'.$values.'[$i],$'.$selected.')))) { ?>';
$parseStr .= '<option selected="selected" value="<?php echo $'.$values.'[$i] ?>"><?php echo $'.$output.'[$i] ?></option>';
$parseStr .= '<?php }else { ?><option value="<?php echo $'.$values.'[$i] ?>"><?php echo $'.$output.'[$i] ?></option>';
$parseStr .= '<?php } ?>';
}else {
$parseStr .= '<option value="<?php echo $'.$values.'[$i] ?>"><?php echo $'.$output.'[$i] ?></option>';
}
$parseStr .= '<?php } ?>';
}
$parseStr .= '</select>';
return $parseStr;
}
/**
* checkbox标签解析
* 格式: <html:checkbox checkboxes="" checked="" />
* @access public
* @param array $tag 标签属性
* @return string|void
*/
public function _checkbox($tag) {
$name = $tag['name'];
$checkboxes = $tag['checkboxes'];
$checked = $tag['checked'];
$separator = $tag['separator'];
$checkboxes = $this->tpl->get($checkboxes);
$checked = $this->tpl->get($checked)?$this->tpl->get($checked):$checked;
$parseStr = '';
foreach($checkboxes as $key=>$val) {
if($checked == $key || in_array($key,$checked) ) {
$parseStr .= '<input type="checkbox" checked="checked" name="'.$name.'[]" value="'.$key.'">'.$val.$separator;
}else {
$parseStr .= '<input type="checkbox" name="'.$name.'[]" value="'.$key.'">'.$val.$separator;
}
}
return $parseStr;
}
/**
* radio标签解析
* 格式: <html:radio radios="name" checked="value" />
* @access public
* @param array $tag 标签属性
* @return string|void
*/
public function _radio($tag) {
$name = $tag['name'];
$radios = $tag['radios'];
$checked = $tag['checked'];
$separator = $tag['separator'];
$radios = $this->tpl->get($radios);
$checked = $this->tpl->get($checked)?$this->tpl->get($checked):$checked;
$parseStr = '';
foreach($radios as $key=>$val) {
if($checked == $key ) {
$parseStr .= '<input type="radio" checked="checked" name="'.$name.'[]" value="'.$key.'">'.$val.$separator;
}else {
$parseStr .= '<input type="radio" name="'.$name.'[]" value="'.$key.'">'.$val.$separator;
}
}
return $parseStr;
}
/**
* list标签解析
* 格式: <html:grid datasource="" show="vo" />
* @access public
* @param array $tag 标签属性
* @return string
*/
public function _grid($tag) {
$id = $tag['id']; //表格ID
$datasource = $tag['datasource']; //列表显示的数据源VoList名称
$pk = empty($tag['pk'])?'id':$tag['pk'];//主键名,默认为id
$style = $tag['style']; //样式名
$name = !empty($tag['name'])?$tag['name']:'vo'; //Vo对象名
$action = !empty($tag['action'])?$tag['action']:false; //是否显示功能操作
$key = !empty($tag['key'])?true:false;
if(isset($tag['actionlist'])) {
$actionlist = explode(',',trim($tag['actionlist'])); //指定功能列表
}
if(substr($tag['show'],0,1)=='$') {
$show = $this->tpl->get(substr($tag['show'],1));
}else {
$show = $tag['show'];
}
$show = explode(',',$show); //列表显示字段列表
//计算表格的列数
$colNum = count($show);
if(!empty($action)) $colNum++;
if(!empty($key)) $colNum++;
//显示开始
$parseStr = "<!-- Think 系统列表组件开始 -->\n";
$parseStr .= '<table id="'.$id.'" class="'.$style.'" cellpadding=0 cellspacing=0 >';
$parseStr .= '<tr><td height="5" colspan="'.$colNum.'" class="topTd" ></td></tr>';
$parseStr .= '<tr class="row" >';
//列表需要显示的字段
$fields = array();
foreach($show as $val) {
$fields[] = explode(':',$val);
}
if(!empty($key)) {
$parseStr .= '<th width="12">No</th>';
}
foreach($fields as $field) {//显示指定的字段
$property = explode('|',$field[0]);
$showname = explode('|',$field[1]);
if(isset($showname[1])) {
$parseStr .= '<th width="'.$showname[1].'">';
}else {
$parseStr .= '<th>';
}
$parseStr .= $showname[0].'</th>';
}
if(!empty($action)) {//如果指定显示操作功能列
$parseStr .= '<th >操作</th>';
}
$parseStr .= '</tr>';
$parseStr .= '<volist name="'.$datasource.'" id="'.$name.'" ><tr class="row" >'; //支持鼠标移动单元行颜色变化 具体方法在js中定义
if(!empty($key)) {
$parseStr .= '<td>{$i}</td>';
}
foreach($fields as $field) {
//显示定义的列表字段
$parseStr .= '<td>';
if(!empty($field[2])) {
// 支持列表字段链接功能 具体方法由JS函数实现
$href = explode('|',$field[2]);
if(count($href)>1) {
//指定链接传的字段值
// 支持多个字段传递
$array = explode('^',$href[1]);
if(count($array)>1) {
foreach ($array as $a){
$temp[] = '\'{$'.$name.'.'.$a.'|addslashes}\'';
}
$parseStr .= '<a href="javascript:'.$href[0].'('.implode(',',$temp).')">';
}else{
$parseStr .= '<a href="javascript:'.$href[0].'(\'{$'.$name.'.'.$href[1].'|addslashes}\')">';
}
}else {
//如果没有指定默认传编号值
$parseStr .= '<a href="javascript:'.$field[2].'(\'{$'.$name.'.'.$pk.'|addslashes}\')">';
}
}
if(strpos($field[0],'^')) {
$property = explode('^',$field[0]);
foreach ($property as $p){
$unit = explode('|',$p);
if(count($unit)>1) {
$parseStr .= '{$'.$name.'.'.$unit[0].'|'.$unit[1].'} ';
}else {
$parseStr .= '{$'.$name.'.'.$p.'} ';
}
}
}else{
$property = explode('|',$field[0]);
if(count($property)>1) {
$parseStr .= '{$'.$name.'.'.$property[0].'|'.$property[1].'}';
}else {
$parseStr .= '{$'.$name.'.'.$field[0].'}';
}
}
if(!empty($field[2])) {
$parseStr .= '</a>';
}
$parseStr .= '</td>';
}
if(!empty($action)) {//显示功能操作
if(!empty($actionlist[0])) {//显示指定的功能项
$parseStr .= '<td>';
foreach($actionlist as $val) {
if(strpos($val,':')) {
$a = explode(':',$val);
if(count($a)>2) {
$parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$a[2].'}\')">'.$a[1].'</a> ';
}else {
$parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$pk.'}\')">'.$a[1].'</a> ';
}
}else{
$array = explode('|',$val);
if(count($array)>2) {
$parseStr .= ' <a href="javascript:'.$array[1].'(\'{$'.$name.'.'.$array[0].'}\')">'.$array[2].'</a> ';
}else{
$parseStr .= ' {$'.$name.'.'.$val.'} ';
}
}
}
$parseStr .= '</td>';
}
}
$parseStr .= '</tr></volist><tr><td height="5" colspan="'.$colNum.'" class="bottomTd"></td></tr></table>';
$parseStr .= "\n<!-- Think 系统列表组件结束 -->\n";
return $parseStr;
}
/**
* list标签解析
* 格式: <html:list datasource="" show="" />
* @access public
* @param array $tag 标签属性
* @return string
*/
public function _list($tag) {
$id = $tag['id']; //表格ID
$datasource = $tag['datasource']; //列表显示的数据源VoList名称
$pk = empty($tag['pk'])?'id':$tag['pk'];//主键名,默认为id
$style = $tag['style']; //样式名
$name = !empty($tag['name'])?$tag['name']:'vo'; //Vo对象名
$action = $tag['action']=='true'?true:false; //是否显示功能操作
$key = !empty($tag['key'])?true:false;
$sort = $tag['sort']=='false'?false:true;
$checkbox = $tag['checkbox']; //是否显示Checkbox
if(isset($tag['actionlist'])) {
if(substr($tag['actionlist'],0,1)=='$') {
$actionlist = $this->tpl->get(substr($tag['actionlist'],1));
}else {
$actionlist = $tag['actionlist'];
}
$actionlist = explode(',',trim($actionlist)); //指定功能列表
}
if(substr($tag['show'],0,1)=='$') {
$show = $this->tpl->get(substr($tag['show'],1));
}else {
$show = $tag['show'];
}
$show = explode(',',$show); //列表显示字段列表
//计算表格的列数
$colNum = count($show);
if(!empty($checkbox)) $colNum++;
if(!empty($action)) $colNum++;
if(!empty($key)) $colNum++;
//显示开始
$parseStr = "<!-- Think 系统列表组件开始 -->\n";
$parseStr .= '<table id="'.$id.'" class="'.$style.'" cellpadding=0 cellspacing=0 >';
$parseStr .= '<tr><td height="5" colspan="'.$colNum.'" class="topTd" ></td></tr>';
$parseStr .= '<tr class="row" >';
//列表需要显示的字段
$fields = array();
foreach($show as $val) {
$fields[] = explode(':',$val);
}
if(!empty($checkbox) && 'true'==strtolower($checkbox)) {//如果指定需要显示checkbox列
$parseStr .='<th width="8"><input type="checkbox" id="check" onclick="CheckAll(\''.$id.'\')"></th>';
}
if(!empty($key)) {
$parseStr .= '<th width="12">No</th>';
}
foreach($fields as $field) {//显示指定的字段
$property = explode('|',$field[0]);
$showname = explode('|',$field[1]);
if(isset($showname[1])) {
$parseStr .= '<th width="'.$showname[1].'">';
}else {
$parseStr .= '<th>';
}
$showname[2] = isset($showname[2])?$showname[2]:$showname[0];
if($sort) {
$parseStr .= '<a href="javascript:sortBy(\''.$property[0].'\',\'{$sort}\',\''.ACTION_NAME.'\')" title="按照'.$showname[2].'{$sortType} ">'.$showname[0].'<eq name="order" value="'.$property[0].'" ><img src="__PUBLIC__/images/{$sortImg}.gif" width="12" height="17" border="0" align="absmiddle"></eq></a></th>';
}else{
$parseStr .= $showname[0].'</th>';
}
}
if(!empty($action)) {//如果指定显示操作功能列
$parseStr .= '<th >操作</th>';
}
$parseStr .= '</tr>';
$parseStr .= '<volist name="'.$datasource.'" id="'.$name.'" ><tr class="row" '; //支持鼠标移动单元行颜色变化 具体方法在js中定义
if(!empty($checkbox)) {
// $parseStr .= 'onmouseover="over(event)" onmouseout="out(event)" onclick="change(event)" ';
}
$parseStr .= '>';
if(!empty($checkbox)) {//如果需要显示checkbox 则在每行开头显示checkbox
$parseStr .= '<td><input type="checkbox" name="key" value="{$'.$name.'.'.$pk.'}"></td>';
}
if(!empty($key)) {
$parseStr .= '<td>{$i}</td>';
}
foreach($fields as $field) {
//显示定义的列表字段
$parseStr .= '<td>';
if(!empty($field[2])) {
// 支持列表字段链接功能 具体方法由JS函数实现
$href = explode('|',$field[2]);
if(count($href)>1) {
//指定链接传的字段值
// 支持多个字段传递
$array = explode('^',$href[1]);
if(count($array)>1) {
foreach ($array as $a){
$temp[] = '\'{$'.$name.'.'.$a.'|addslashes}\'';
}
$parseStr .= '<a href="javascript:'.$href[0].'('.implode(',',$temp).')">';
}else{
$parseStr .= '<a href="javascript:'.$href[0].'(\'{$'.$name.'.'.$href[1].'|addslashes}\')">';
}
}else {
//如果没有指定默认传编号值
$parseStr .= '<a href="javascript:'.$field[2].'(\'{$'.$name.'.'.$pk.'|addslashes}\')">';
}
}
if(strpos($field[0],'^')) {
$property = explode('^',$field[0]);
foreach ($property as $p){
$unit = explode('|',$p);
if(count($unit)>1) {
$parseStr .= '{$'.$name.'.'.$unit[0].'|'.$unit[1].'} ';
}else {
$parseStr .= '{$'.$name.'.'.$p.'} ';
}
}
}else{
$property = explode('|',$field[0]);
if(count($property)>1) {
$parseStr .= '{$'.$name.'.'.$property[0].'|'.$property[1].'}';
}else {
$parseStr .= '{$'.$name.'.'.$field[0].'}';
}
}
if(!empty($field[2])) {
$parseStr .= '</a>';
}
$parseStr .= '</td>';
}
if(!empty($action)) {//显示功能操作
if(!empty($actionlist[0])) {//显示指定的功能项
$parseStr .= '<td>';
foreach($actionlist as $val) {
if(strpos($val,':')) {
$a = explode(':',$val);
if(count($a)>2) {
$parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$a[2].'}\')">'.$a[1].'</a> ';
}else {
$parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$pk.'}\')">'.$a[1].'</a> ';
}
}else{
$array = explode('|',$val);
if(count($array)>2) {
$parseStr .= ' <a href="javascript:'.$array[1].'(\'{$'.$name.'.'.$array[0].'}\')">'.$array[2].'</a> ';
}else{
$parseStr .= ' {$'.$name.'.'.$val.'} ';
}
}
}
$parseStr .= '</td>';
}
}
$parseStr .= '</tr></volist><tr><td height="5" colspan="'.$colNum.'" class="bottomTd"></td></tr></table>';
$parseStr .= "\n<!-- Think 系统列表组件结束 -->\n";
return $parseStr;
}
} | furongsoft/weiphp2.0.1202 | Sources/weiphp2.0.1202/ThinkPHP/Library/Think/Template/TagLib/Html.class.php | PHP | mit | 25,987 |
module Rugged
module Redis
VERSION = "0.1.1"
end
end
| JoeStanton/rugged-redis | lib/rugged/redis/version.rb | Ruby | mit | 61 |
<?php
/**
* Actually performs an XML_RPC request.
*
* PHP versions 4 and 5
*
* @category Web Services
* @package XML_RPC
* @author Daniel Convissor <danielc@php.net>
* @copyright 2005-2010 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License
* @version SVN: $Id: test_Dump.php 300962 2010-07-03 02:24:24Z danielc $
* @link http://pear.php.net/package/XML_RPC
*/
/*
* If the package version number is found in the left hand
* portion of the if() expression below, that means this file has
* come from the PEAR installer. Therefore, let's test the
* installed version of XML_RPC which should be in the include path.
*
* If the version has not been substituted in the if() expression,
* this file has likely come from a SVN checkout or a .tar file.
* Therefore, we'll assume the tests should use the version of
* XML_RPC that has come from there as well.
*/
if ('1.5.5' == '@'.'package_version'.'@') {
ini_set('include_path', '../'
. PATH_SEPARATOR . '.' . PATH_SEPARATOR
. ini_get('include_path')
);
}
require_once 'XML/RPC/Dump.php';
$val = new XML_RPC_Value(array(
'title' =>new XML_RPC_Value('das ist der Titel', 'string'),
'startDate'=>new XML_RPC_Value(mktime(0,0,0,13,11,2004), 'dateTime.iso8601'),
'endDate' =>new XML_RPC_Value(mktime(0,0,0,15,11,2004), 'dateTime.iso8601'),
'arkey' => new XML_RPC_Value( array(
new XML_RPC_Value('simple string'),
new XML_RPC_Value(12345, 'int')
), 'array')
)
,'struct');
XML_RPC_Dump($val);
echo '==============' . "\r\n";
$val2 = new XML_RPC_Value(44353, 'int');
XML_RPC_Dump($val2);
echo '==============' . "\r\n";
$val3 = new XML_RPC_Value('this should be a string', 'string');
XML_RPC_Dump($val3);
echo '==============' . "\r\n";
$val4 = new XML_RPC_Value(true, 'boolean');
XML_RPC_Dump($val4);
echo '==============' . "\r\n";
echo 'Next we will test the error handling...' . "\r\n";
$val5 = new XML_RPC_Value(array(
'foo' => 'bar'
), 'struct');
XML_RPC_Dump($val5);
echo '==============' . "\r\n";
echo 'DONE' . "\r\n";
| timcrider/IPLocker | vendor/PEAR/test/XML_RPC/tests/test_Dump.php | PHP | mit | 2,136 |
// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Tony Curtis <http://github.com/daltin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="angular.d.ts" />
declare module "angular-mocks/ngMock" {
var _:string;
export = _;
}
declare module "angular-mocks/ngMockE2E" {
var _:string;
export = _;
}
declare module "angular-mocks/ngAnimateMock" {
var _:string;
export = _;
}
///////////////////////////////////////////////////////////////////////////////
// ngMock module (angular-mocks.js)
///////////////////////////////////////////////////////////////////////////////
declare namespace angular {
///////////////////////////////////////////////////////////////////////////
// AngularStatic
// We reopen it to add the MockStatic definition
///////////////////////////////////////////////////////////////////////////
interface IAngularStatic {
mock: IMockStatic;
}
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
interface IInjectStatic {
(...fns:Function[]): any;
(...inlineAnnotatedConstructor:any[]): any; // this overload is undocumented, but works
strictDi(val?:boolean): void;
}
interface IMockStatic {
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump
dump(obj:any): string;
inject: IInjectStatic
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
module: {
(...modules:any[]): any;
sharedInjector(): void;
}
// see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate
TzDate(offset:number, timestamp:number): Date;
TzDate(offset:number, timestamp:string): Date;
}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
// see https://docs.angularjs.org/api/ngMock/service/$exceptionHandler
// see https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider
///////////////////////////////////////////////////////////////////////////
interface IExceptionHandlerProvider extends IServiceProvider {
mode(mode:string): void;
}
///////////////////////////////////////////////////////////////////////////
// TimeoutService
// see https://docs.angularjs.org/api/ngMock/service/$timeout
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
flush(delay?:number): void;
flushNext(expectedDelay?:number): void;
verifyNoPendingTasks(): void;
}
///////////////////////////////////////////////////////////////////////////
// IntervalService
// see https://docs.angularjs.org/api/ngMock/service/$interval
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
flush(millis?:number): number;
}
///////////////////////////////////////////////////////////////////////////
// LogService
// see https://docs.angularjs.org/api/ngMock/service/$log
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ILogService {
assertEmpty(): void;
reset(): void;
}
interface ILogCall {
logs: string[];
}
///////////////////////////////////////////////////////////////////////////
// ControllerService mock
// see https://docs.angularjs.org/api/ngMock/service/$controller
// This interface extends http://docs.angularjs.org/api/ng.$controller
///////////////////////////////////////////////////////////////////////////
interface IControllerService {
// Although the documentation doesn't state this, locals are optional
<T>(controllerConstructor:new (...args:any[]) => T, locals?:any, bindings?:any): T;
<T>(controllerConstructor:Function, locals?:any, bindings?:any): T;
<T>(controllerName:string, locals?:any, bindings?:any): T;
}
///////////////////////////////////////////////////////////////////////////
// ComponentControllerService
// see https://docs.angularjs.org/api/ngMock/service/$componentController
///////////////////////////////////////////////////////////////////////////
interface IComponentControllerService {
// TBinding is an interface exposed by a component as per John Papa's style guide
// https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#accessible-members-up-top
<T, TBinding>(componentName:string, locals:{ $scope: IScope, [key: string]: any }, bindings?:TBinding, ident?:string): T;
}
///////////////////////////////////////////////////////////////////////////
// HttpBackendService
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
/**
* Flushes all pending requests using the trained responses.
* @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed.
*/
flush(count?:number): void;
/**
* Resets all request expectations, but preserves all backend definitions.
*/
resetExpectations(): void;
/**
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
*/
verifyNoOutstandingExpectation(): void;
/**
* Verifies that there are no outstanding requests that need to be flushed.
*/
verifyNoOutstandingRequest(): void;
/**
* Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expect(method:string, url:string | RegExp | ((url:string) => boolean), data?:string | RegExp | Object | ((data:string) => boolean), headers?:Object | ((object:Object) => boolean)) :mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectDELETE(url:string | RegExp | ((url:string) => boolean), headers?:Object): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectGET(url:string | RegExp | ((url:string) => boolean), headers?:Object): mock.IRequestHandler;
/**
* Creates a new request expectation for HEAD requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectHEAD(url:string | RegExp | ((url:string) => boolean), headers?:Object): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
*/
expectJSONP(url:string | RegExp | ((url:string) => boolean)): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPATCH(url:string | RegExp | ((url:string) => boolean), data?:string | RegExp | Object | ((data:string) => boolean), headers?:Object): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPOST(url:string | RegExp | ((url:string) => boolean), data?:string | RegExp | Object | ((data:string) => boolean), headers?:Object): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPUT(url:string | RegExp | ((url:string) => boolean), data?:string | RegExp | Object | ((data:string) => boolean), headers?:Object): mock.IRequestHandler;
/**
* Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
when(method:string, url:string | RegExp | ((url:string) => boolean), data?:string | RegExp | Object | ((data:string) => boolean), headers?:Object | ((object:Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenDELETE(url:string | RegExp | ((url:string) => boolean), headers?:Object | ((object:Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenGET(url:string | RegExp | ((url:string) => boolean), headers?:Object | ((object:Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenHEAD(url:string | RegExp | ((url:string) => boolean), headers?:Object | ((object:Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenJSONP(url:string | RegExp | ((url:string) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPATCH(url:string | RegExp | ((url:string) => boolean), data?:string | RegExp | Object | ((data:string) => boolean), headers?:Object | ((object:Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPOST(url:string | RegExp | ((url:string) => boolean), data?:string | RegExp | Object | ((data:string) => boolean), headers?:Object | ((object:Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPUT(url:string | RegExp | ((url:string) => boolean), data?:string | RegExp | Object | ((data:string) => boolean), headers?:Object | ((object:Object) => boolean)): mock.IRequestHandler;
}
export module mock {
// returned interface by the the mocked HttpBackendService expect/when methods
interface IRequestHandler {
/**
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text.
*/
respond(func:((method:string, url:string, data:string | Object, headers:Object) => [number, string | Object, Object, string])): IRequestHandler;
/**
* Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(status:number, data:string | Object, headers?:Object, responseText?:string): IRequestHandler;
/**
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(data:string | Object, headers?:Object, responseText?:string): IRequestHandler;
// Available when ngMockE2E is loaded
/**
* Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)
*/
passThrough(): IRequestHandler;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// functions attached to global object (window)
///////////////////////////////////////////////////////////////////////////////
//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
//declare var module: (...modules: any[]) => any;
declare var inject:angular.IInjectStatic;
| uwe0711/snes-konvolut-db | frontend/typings/angularjs/angular-mocks.d.ts | TypeScript | mit | 21,073 |
module DataMapper
# = Properties
# Properties for a model are not derived from a database structure, but
# instead explicitly declared inside your model class definitions. These
# properties then map (or, if using automigrate, generate) fields in your
# repository/database.
#
# If you are coming to DataMapper from another ORM framework, such as
# ActiveRecord, this may be a fundamental difference in thinking to you.
# However, there are several advantages to defining your properties in your
# models:
#
# * information about your model is centralized in one place: rather than
# having to dig out migrations, xml or other configuration files.
# * use of mixins can be applied to model properties: better code reuse
# * having information centralized in your models, encourages you and the
# developers on your team to take a model-centric view of development.
# * it provides the ability to use Ruby's access control functions.
# * and, because DataMapper only cares about properties explicitly defined
# in your models, DataMapper plays well with legacy databases, and shares
# databases easily with other applications.
#
# == Declaring Properties
# Inside your class, you call the property method for each property you want
# to add. The only two required arguments are the name and type, everything
# else is optional.
#
# class Post
# include DataMapper::Resource
#
# property :title, String, :required => true # Cannot be null
# property :publish, Boolean, :default => false # Default value for new records is false
# end
#
# By default, DataMapper supports the following primitive (Ruby) types
# also called core properties:
#
# * Boolean
# * Class (datastore primitive is the same as String. Used for Inheritance)
# * Date
# * DateTime
# * Decimal
# * Float
# * Integer
# * Object (marshalled out during serialization)
# * String (default length is 50)
# * Text (limit of 65k characters by default)
# * Time
#
# == Limiting Access
# Property access control is uses the same terminology Ruby does. Properties
# are public by default, but can also be declared private or protected as
# needed (via the :accessor option).
#
# class Post
# include DataMapper::Resource
#
# property :title, String, :accessor => :private # Both reader and writer are private
# property :body, Text, :accessor => :protected # Both reader and writer are protected
# end
#
# Access control is also analogous to Ruby attribute readers and writers, and can
# be declared using :reader and :writer, in addition to :accessor.
#
# class Post
# include DataMapper::Resource
#
# property :title, String, :writer => :private # Only writer is private
# property :tags, String, :reader => :protected # Only reader is protected
# end
#
# == Overriding Accessors
# The reader/writer for any property can be overridden in the same manner that Ruby
# attr readers/writers can be. After the property is defined, just add your custom
# reader or writer:
#
# class Post
# include DataMapper::Resource
#
# property :title, String
#
# def title=(new_title)
# raise ArgumentError if new_title != 'Lee is l337'
# super(new_title)
# end
# end
#
# Calling super ensures that any validators defined for the property are kept active.
#
# == Lazy Loading
# By default, some properties are not loaded when an object is fetched in
# DataMapper. These lazily loaded properties are fetched on demand when their
# accessor is called for the first time (as it is often unnecessary to
# instantiate -every- property -every- time an object is loaded). For
# instance, DataMapper::Property::Text fields are lazy loading by default,
# although you can over-ride this behavior if you wish:
#
# Example:
#
# class Post
# include DataMapper::Resource
#
# property :title, String # Loads normally
# property :body, Text # Is lazily loaded by default
# end
#
# If you want to over-ride the lazy loading on any field you can set it to a
# context or false to disable it with the :lazy option. Contexts allow
# multiple lazy properties to be loaded at one time. If you set :lazy to
# true, it is placed in the :default context
#
# class Post
# include DataMapper::Resource
#
# property :title, String # Loads normally
# property :body, Text, :lazy => false # The default is now over-ridden
# property :comment, String, :lazy => [ :detailed ] # Loads in the :detailed context
# property :author, String, :lazy => [ :summary, :detailed ] # Loads in :summary & :detailed context
# end
#
# Delaying the request for lazy-loaded attributes even applies to objects
# accessed through associations. In a sense, DataMapper anticipates that
# you will likely be iterating over objects in associations and rolls all
# of the load commands for lazy-loaded properties into one request from
# the database.
#
# Example:
#
# Widget.get(1).components
# # loads when the post object is pulled from database, by default
#
# Widget.get(1).components.first.body
# # loads the values for the body property on all objects in the
# # association, rather than just this one.
#
# Widget.get(1).components.first.comment
# # loads both comment and author for all objects in the association
# # since they are both in the :detailed context
#
# == Keys
# Properties can be declared as primary or natural keys on a table.
# You should a property as the primary key of the table:
#
# Examples:
#
# property :id, Serial # auto-incrementing key
# property :legacy_pk, String, :key => true # 'natural' key
#
# This is roughly equivalent to ActiveRecord's <tt>set_primary_key</tt>,
# though non-integer data types may be used, thus DataMapper supports natural
# keys. When a property is declared as a natural key, accessing the object
# using the indexer syntax <tt>Class[key]</tt> remains valid.
#
# User.get(1)
# # when :id is the primary key on the users table
# User.get('bill')
# # when :name is the primary (natural) key on the users table
#
# == Indices
# You can add indices for your properties by using the <tt>:index</tt>
# option. If you use <tt>true</tt> as the option value, the index will be
# automatically named. If you want to name the index yourself, use a symbol
# as the value.
#
# property :last_name, String, :index => true
# property :first_name, String, :index => :name
#
# You can create multi-column composite indices by using the same symbol in
# all the columns belonging to the index. The columns will appear in the
# index in the order they are declared.
#
# property :last_name, String, :index => :name
# property :first_name, String, :index => :name
# # => index on (last_name, first_name)
#
# If you want to make the indices unique, use <tt>:unique_index</tt> instead
# of <tt>:index</tt>
#
# == Inferred Validations
# If you require the dm-validations plugin, auto-validations will
# automatically be mixed-in in to your model classes: validation rules that
# are inferred when properties are declared with specific column restrictions.
#
# class Post
# include DataMapper::Resource
#
# property :title, String, :length => 250, :min => 0, :max => 250
# # => infers 'validates_length :title'
#
# property :title, String, :required => true
# # => infers 'validates_present :title'
#
# property :email, String, :format => :email_address
# # => infers 'validates_format :email, :with => :email_address'
#
# property :title, String, :length => 255, :required => true
# # => infers both 'validates_length' as well as 'validates_present'
# # better: property :title, String, :length => 1..255
# end
#
# This functionality is available with the dm-validations gem. For more information
# about validations, check the documentation for dm-validations.
#
# == Default Values
# To set a default for a property, use the <tt>:default</tt> key. The
# property will be set to the value associated with that key the first time
# it is accessed, or when the resource is saved if it hasn't been set with
# another value already. This value can be a static value, such as 'hello'
# but it can also be a proc that will be evaluated when the property is read
# before its value has been set. The property is set to the return of the
# proc. The proc is passed two values, the resource the property is being set
# for and the property itself.
#
# property :display_name, String, :default => lambda { |resource, property| resource.login }
#
# Word of warning. Don't try to read the value of the property you're setting
# the default for in the proc. An infinite loop will ensue.
#
# == Embedded Values (not implemented yet)
# As an alternative to extraneous has_one relationships, consider using an
# EmbeddedValue.
#
# == Property options reference
#
# :accessor if false, neither reader nor writer methods are
# created for this property
#
# :reader if false, reader method is not created for this property
#
# :writer if false, writer method is not created for this property
#
# :lazy if true, property value is only loaded when on first read
# if false, property value is always loaded
# if a symbol, property value is loaded with other properties
# in the same group
#
# :default default value of this property
#
# :allow_nil if true, property may have a nil value on save
#
# :key name of the key associated with this property.
#
# :field field in the data-store which the property corresponds to
#
# :length string field length
#
# :format format for autovalidation. Use with dm-validations plugin.
#
# :index if true, index is created for the property. If a Symbol, index
# is named after Symbol value instead of being based on property name.
#
# :unique_index true specifies that index on this property should be unique
#
# :auto_validation if true, automatic validation is performed on the property
#
# :validates validation context. Use together with dm-validations.
#
# :unique if true, property column is unique. Properties of type Serial
# are unique by default.
#
# :precision Indicates the number of significant digits. Usually only makes sense
# for float type properties. Must be >= scale option value. Default is 10.
#
# :scale The number of significant digits to the right of the decimal point.
# Only makes sense for float type properties. Must be > 0.
# Default is nil for Float type and 10 for BigDecimal
#
# == Overriding default Property options
#
# There is the ability to reconfigure a Property and it's subclasses by explicitly
# setting a value in the Property, eg:
#
# # set all String properties to have a default length of 255
# DataMapper::Property::String.length(255)
#
# # set all Boolean properties to not allow nil (force true or false)
# DataMapper::Property::Boolean.allow_nil(false)
#
# # set all properties to be required by default
# DataMapper::Property.required(true)
#
# # turn off auto-validation for all properties by default
# DataMapper::Property.auto_validation(false)
#
# # set all mutator methods to be private by default
# DataMapper::Property.writer(:private)
#
# Please note that this has no effect when a subclass has explicitly
# defined it's own option. For example, setting the String length to
# 255 will not affect the Text property even though it inherits from
# String, because it sets it's own default length to 65535.
#
# == Misc. Notes
# * Properties declared as strings will default to a length of 50, rather than
# 255 (typical max varchar column size). To overload the default, pass
# <tt>:length => 255</tt> or <tt>:length => 0..255</tt>. Since DataMapper
# does not introspect for properties, this means that legacy database tables
# may need their <tt>String</tt> columns defined with a <tt>:length</tt> so
# that DM does not apply an un-needed length validation, or allow overflow.
# * You may declare a Property with the data-type of <tt>Class</tt>.
# see SingleTableInheritance for more on how to use <tt>Class</tt> columns.
class Property
include DataMapper::Assertions
include Subject
extend Equalizer
equalize :model, :name, :options
PRIMITIVES = [
TrueClass,
::String,
::Float,
::Integer,
::BigDecimal,
::DateTime,
::Date,
::Time,
::Class
].to_set.freeze
OPTIONS = [
:load_as, :dump_as, :coercion_method,
:accessor, :reader, :writer,
:lazy, :default, :key, :field,
:index, :unique_index,
:unique, :allow_nil, :allow_blank, :required
]
# Possible :visibility option values
VISIBILITY_OPTIONS = [ :public, :protected, :private ].to_set.freeze
# Invalid property names
INVALID_NAMES = (Resource.instance_methods +
Resource.private_instance_methods +
Query::OPTIONS.to_a
).map { |name| name.to_s }
attr_reader :load_as, :dump_as, :coercion_method,
:model, :name, :instance_variable_name,
:reader_visibility, :writer_visibility, :options,
:default, :repository_name, :allow_nil, :allow_blank, :required
alias_method :load_class, :load_as
alias_method :dump_class, :dump_as
class << self
extend Deprecate
deprecate :all_descendants, :descendants
# @api semipublic
def determine_class(type)
return type if type < DataMapper::Property::Object
find_class(DataMapper::Inflector.demodulize(type.name))
end
# @api private
def demodulized_names
@demodulized_names ||= {}
end
# @api semipublic
def find_class(name)
klass = demodulized_names[name]
klass ||= const_get(name) if const_defined?(name)
klass
end
# @api public
def descendants
@descendants ||= DescendantSet.new
end
# @api private
def inherited(descendant)
# Descendants is a tree rooted in DataMapper::Property that tracks
# inheritance. We pre-calculate each comparison value (demodulized
# class name) to achieve a Hash[]-time lookup, rather than walk the
# entire descendant tree and calculate names on-demand (expensive,
# redundant).
#
# Since the algorithm relegates property class name lookups to a flat
# namespace, we need to ensure properties defined outside of DM don't
# override built-ins (Serial, String, etc) by merely defining a property
# of a same name. We avoid this by only ever adding to the lookup
# table. Given that DM loads its own property classes first, we can
# assume that their names are "reserved" when added to the table.
#
# External property authors who want to provide "replacements" for
# builtins (e.g. in a non-DM-supported adapter) should follow the
# convention of wrapping those properties in a module, and include'ing
# the module on the model class directly. This bypasses the DM-hooked
# const_missing lookup that would normally check this table.
descendants << descendant
Property.demodulized_names[DataMapper::Inflector.demodulize(descendant.name)] ||= descendant
# inherit accepted options
descendant.accepted_options.concat(accepted_options)
# inherit the option values
options.each { |key, value| descendant.send(key, value) }
super
end
# @api public
def accepted_options
@accepted_options ||= []
end
# @api public
def accept_options(*args)
accepted_options.concat(args)
# create methods for each new option
args.each do |property_option|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{property_option}(value = Undefined) # def self.unique(value = Undefined)
return @#{property_option} if value.equal?(Undefined) # return @unique if value.equal?(Undefined)
descendants.each do |descendant| # descendants.each do |descendant|
unless descendant.instance_variable_defined?(:@#{property_option}) # unless descendant.instance_variable_defined?(:@unique)
descendant.#{property_option}(value) # descendant.unique(value)
end # end
end # end
@#{property_option} = value # @unique = value
end # end
RUBY
end
descendants.each { |descendant| descendant.accepted_options.concat(args) }
end
# @api private
def nullable(*args)
# :required is preferable to :allow_nil, but :nullable maps precisely to :allow_nil
raise "#nullable is deprecated, use #required instead (#{caller.first})"
end
# Gives all the options set on this property
#
# @return [Hash] with all options and their values set on this property
#
# @api public
def options
options = {}
accepted_options.each do |name|
options[name] = send(name) if instance_variable_defined?("@#{name}")
end
options
end
# @api deprecated
def primitive(*args)
warn "DataMapper::Property.primitive is deprecated, use .load_as instead (#{caller.first})"
load_as(*args)
end
end
accept_options *Property::OPTIONS
# A hook to allow properties to extend or modify the model it's bound to.
# Implementations are not supposed to modify the state of the property
# class, and should produce no side-effects on the property instance.
def bind
# no op
end
# Supplies the field in the data-store which the property corresponds to
#
# @return [String] name of field in data-store
#
# @api semipublic
def field(repository_name = nil)
if repository_name
raise "Passing in +repository_name+ to #{self.class}#field is deprecated (#{caller.first})"
end
# defer setting the field with the adapter specific naming
# conventions until after the adapter has been setup
@field ||= model.field_naming_convention(self.repository_name).call(self).freeze
end
# Returns true if property is unique. Serial properties and keys
# are unique by default.
#
# @return [Boolean]
# true if property has uniq index defined, false otherwise
#
# @api public
def unique?
!!@unique
end
# Returns index name if property has index.
#
# @return [Boolean, Symbol, Array]
# returns true if property is indexed by itself
# returns a Symbol if the property is indexed with other properties
# returns an Array if the property belongs to multiple indexes
# returns false if the property does not belong to any indexes
#
# @api public
attr_reader :index
# Returns true if property has unique index. Serial properties and
# keys are unique by default.
#
# @return [Boolean, Symbol, Array]
# returns true if property is indexed by itself
# returns a Symbol if the property is indexed with other properties
# returns an Array if the property belongs to multiple indexes
# returns false if the property does not belong to any indexes
#
# @api public
attr_reader :unique_index
# Returns whether or not the property is to be lazy-loaded
#
# @return [Boolean]
# true if the property is to be lazy-loaded
#
# @api public
def lazy?
@lazy
end
# Returns whether or not the property is a key or a part of a key
#
# @return [Boolean]
# true if the property is a key or a part of a key
#
# @api public
def key?
@key
end
# Returns whether or not the property is "serial" (auto-incrementing)
#
# @return [Boolean]
# whether or not the property is "serial"
#
# @api public
def serial?
@serial
end
# Returns whether or not the property must be non-nil and non-blank
#
# @return [Boolean]
# whether or not the property is required
#
# @api public
def required?
@required
end
# Returns whether or not the property can accept 'nil' as it's value
#
# @return [Boolean]
# whether or not the property can accept 'nil'
#
# @api public
def allow_nil?
@allow_nil
end
# Returns whether or not the property can be a blank value
#
# @return [Boolean]
# whether or not the property can be blank
#
# @api public
def allow_blank?
@allow_blank
end
# Standardized reader method for the property
#
# @param [Resource] resource
# model instance for which this property is to be loaded
#
# @return [Object]
# the value of this property for the provided instance
#
# @raise [ArgumentError] "+resource+ should be a Resource, but was ...."
#
# @api private
def get(resource)
get!(resource)
end
# Fetch the ivar value in the resource
#
# @param [Resource] resource
# model instance for which this property is to be unsafely loaded
#
# @return [Object]
# current @ivar value of this property in +resource+
#
# @api private
def get!(resource)
resource.instance_variable_get(instance_variable_name)
end
# Provides a standardized setter method for the property
#
# @param [Resource] resource
# the resource to get the value from
# @param [Object] value
# the value to set in the resource
#
# @return [Object]
# +value+ after being typecasted according to this property's primitive
#
# @raise [ArgumentError] "+resource+ should be a Resource, but was ...."
#
# @api private
def set(resource, value)
set!(resource, typecast(value))
end
# Set the ivar value in the resource
#
# @param [Resource] resource
# the resource to set
# @param [Object] value
# the value to set in the resource
#
# @return [Object]
# the value set in the resource
#
# @api private
def set!(resource, value)
resource.instance_variable_set(instance_variable_name, value)
end
# Check if the attribute corresponding to the property is loaded
#
# @param [Resource] resource
# model instance for which the attribute is to be tested
#
# @return [Boolean]
# true if the attribute is loaded in the resource
#
# @api private
def loaded?(resource)
resource.instance_variable_defined?(instance_variable_name)
end
# Loads lazy columns when get or set is called.
#
# @param [Resource] resource
# model instance for which lazy loaded attribute are loaded
#
# @api private
def lazy_load(resource)
return if loaded?(resource)
resource.__send__(:lazy_load, lazy_load_properties)
end
# @api private
def lazy_load_properties
@lazy_load_properties ||=
begin
properties = self.properties
properties.in_context(lazy? ? [ self ] : properties.defaults)
end
end
# @api private
def properties
@properties ||= model.properties(repository_name)
end
# @api semipublic
def typecast(value)
Virtus::Coercion[value.class].send(coercion_method, value)
end
# Test the value to see if it is a valid value for this Property
#
# @param [Object] loaded_value
# the value to be tested
#
# @return [Boolean]
# true if the value is valid
#
# @api semipulic
def valid?(value, negated = false)
dumped_value = dump(value)
if required? && dumped_value.nil?
negated || false
else
value_dumped?(dumped_value) || (dumped_value.nil? && (allow_nil? || negated))
end
end
# Asserts value is valid
#
# @param [Object] loaded_value
# the value to be tested
#
# @return [Boolean]
# true if the value is valid
#
# @raise [Property::InvalidValueError]
# if value is not valid
def assert_valid_value(value)
unless valid?(value)
raise Property::InvalidValueError.new(self,value)
end
true
end
# Returns a concise string representation of the property instance.
#
# @return [String]
# Concise string representation of the property instance.
#
# @api public
def inspect
"#<#{self.class.name} @model=#{model.inspect} @name=#{name.inspect}>"
end
# Test a value to see if it matches the primitive type
#
# @param [Object] value
# value to test
#
# @return [Boolean]
# true if the value is the correct type
#
# @api semipublic
def primitive?(value)
warn "#primitive? is deprecated, use #value_dumped? instead (#{caller.first})"
value_dumped?(value)
end
def primitive
warn "#primitive is deprecated, use #dump_as instead (#{caller.first})"
dump_as
end
# @api semipublic
def value_dumped?(value)
value.kind_of?(dump_as)
end
# @api semipublic
def value_loaded?(value)
value.kind_of?(load_as)
end
protected
# @api semipublic
def initialize(model, name, options = {})
options = options.to_hash.dup
if INVALID_NAMES.include?(name.to_s) || (kind_of?(Boolean) && INVALID_NAMES.include?("#{name}?"))
raise ArgumentError,
"+name+ was #{name.inspect}, which cannot be used as a property name since it collides with an existing method or a query option"
end
assert_valid_options(options)
predefined_options = self.class.options
@repository_name = model.repository_name
@model = model
@name = name.to_s.chomp('?').to_sym
@options = predefined_options.merge(options).freeze
@instance_variable_name = "@#{@name}".freeze
@coercion_method = @options.fetch(:coercion_method)
@load_as = self.class.load_as
@dump_as = self.class.dump_as
@field = @options[:field].freeze unless @options[:field].nil?
@default = @options[:default]
@serial = @options.fetch(:serial, false)
@key = @options.fetch(:key, @serial)
@unique = @options.fetch(:unique, @key ? :key : false)
@required = @options.fetch(:required, @key)
@allow_nil = @options.fetch(:allow_nil, !@required)
@allow_blank = @options.fetch(:allow_blank, !@required)
@index = @options.fetch(:index, false)
@unique_index = @options.fetch(:unique_index, @unique)
@lazy = @options.fetch(:lazy, false) && !@key
determine_visibility
bind
end
# @api private
def assert_valid_options(options)
keys = options.keys
if (unknown_keys = keys - self.class.accepted_options).any?
raise ArgumentError, "options #{unknown_keys.map { |key| key.inspect }.join(' and ')} are unknown"
end
options.each do |key, value|
boolean_value = value == true || value == false
case key
when :field
assert_kind_of "options[:#{key}]", value, ::String
when :default
if value.nil?
raise ArgumentError, "options[:#{key}] must not be nil"
end
when :serial, :key, :allow_nil, :allow_blank, :required, :auto_validation
unless boolean_value
raise ArgumentError, "options[:#{key}] must be either true or false"
end
if key == :required && (keys.include?(:allow_nil) || keys.include?(:allow_blank))
raise ArgumentError, 'options[:required] cannot be mixed with :allow_nil or :allow_blank'
end
when :index, :unique_index, :unique, :lazy
unless boolean_value || value.kind_of?(Symbol) || (value.kind_of?(Array) && value.any? && value.all? { |val| val.kind_of?(Symbol) })
raise ArgumentError, "options[:#{key}] must be either true, false, a Symbol or an Array of Symbols"
end
when :length
assert_kind_of "options[:#{key}]", value, Range, ::Integer
when :size, :precision, :scale
assert_kind_of "options[:#{key}]", value, ::Integer
when :reader, :writer, :accessor
assert_kind_of "options[:#{key}]", value, Symbol
unless VISIBILITY_OPTIONS.include?(value)
raise ArgumentError, "options[:#{key}] must be #{VISIBILITY_OPTIONS.join(' or ')}"
end
end
end
end
# Assert given visibility value is supported.
#
# Will raise ArgumentError if this Property's reader and writer
# visibilities are not included in VISIBILITY_OPTIONS.
#
# @return [undefined]
#
# @raise [ArgumentError] "property visibility must be :public, :protected, or :private"
#
# @api private
def determine_visibility
default_accessor = @options.fetch(:accessor, :public)
@reader_visibility = @options.fetch(:reader, default_accessor)
@writer_visibility = @options.fetch(:writer, default_accessor)
end
end # class Property
end
| framgia/dm-core | lib/dm-core/property.rb | Ruby | mit | 30,745 |
/*
* compound.h
*
* Created on: Jan 14, 2015
* Author: radoslav
*/
#ifndef COMPOUND_H_
#define COMPOUND_H_
#include "statement.h"
#include <vector>
class CallStackFrame {};
class CompoundStatement : public Statement
{
friend class CallStackFrame;
std::vector<Statement> body;
public:
CompoundStatement() {}
CompoundStatement(const char*);
std::vector<Statement>::const_iterator getIterator() const { return body.begin(); }
};
#endif /* COMPOUND_H_ */
| rgeorgiev583/LambdaRadoInterpreter | tmp/compound.h | C | mit | 478 |
/**
* Imports
*/
import React from 'react';
import {FormattedMessage} from 'react-intl';
// Flux
import IntlStore from '../../../stores/Application/IntlStore';
// Required components
import Button from '../buttons/Button';
import Text from '../typography/Text';
// Translation data for this component
import intlData from './AddressPreview.intl';
/**
* Component
*/
class AddressPreview extends React.Component {
static contextTypes = {
getStore: React.PropTypes.func.isRequired
};
//*** Component Lifecycle ***//
componentDidMount() {
// Component styles
require('./AddressPreview.scss');
}
//*** Template ***//
render() {
let intlStore = this.context.getStore(IntlStore);
return (
<div className="address-preview">
<div className="address-preview__name">
<Text weight="bold">{this.props.address.name}</Text>
</div>
{this.props.address.phone ?
<div className="address-preview__phone">
<Text size="small">{this.props.address.phone}</Text>
</div>
:
null
}
{this.props.address.vatin ?
<div className="address-preview__vatin">
<Text>
<FormattedMessage
message={intlStore.getMessage(intlData, 'vatLabel')}
locales={intlStore.getCurrentLocale()} />: {this.props.address.vatin}
</Text>
</div>
:
null
}
<div className="address-preview__address-line-1">
<Text>{this.props.address.addressLine1}</Text>
</div>
{this.props.address.addressLine2 ?
<div className="address-preview__address-line-2">
<Text>{this.props.address.addressLine2}</Text>
</div>
:
null
}
<div className="address-preview__postal-code">
<Text>{this.props.address.postalCode}</Text>
</div>
<div className="address-preview__city">
<Text>{this.props.address.city}</Text>
</div>
{this.props.address.state ?
<div className="address-preview__state">
<Text>{this.props.address.state}</Text>
</div>
:
null
}
<div className="address-preview__country">
<Text>{this.props.address.country}</Text>
</div>
<div className="address-preview__actions">
{this.props.onEditClick ?
<div className="address-preview__edit" onClick={this.props.onEditClick}>
<Text weight="bold">
<FormattedMessage
message={intlStore.getMessage(intlData, 'edit')}
locales={intlStore.getCurrentLocale()} />
</Text>
</div>
:
null
}
{this.props.onDeleteClick ?
<div className="address-preview__delete" onClick={this.props.onDeleteClick}>
<Text>
<FormattedMessage
message={intlStore.getMessage(intlData, 'delete')}
locales={intlStore.getCurrentLocale()} />
</Text>
</div>
:
null
}
</div>
</div>
);
}
}
/**
* Exports
*/
export default AddressPreview;
| ESTEBANMURUZABAL/bananaStore | src/components/common/forms/AddressPreview.js | JavaScript | mit | 4,127 |
<?php
/** Greek localization file for KCFinder
* author: Spiros Kabasakalis
*/
$lang = array(
'_locale' => "el_GR.UTF-8", // UNIX localization code
'_charset' => "utf-8", // Browser charset
// Date time formats. See http://www.php.net/manual/en/function.strftime.php
'_dateTimeFull' => "%A, %e %B, %Y %H:%M",
'_dateTimeMid' => "%a %e %b %Y %H:%M",
'_dateTimeSmall' => "%d.%m.%Y %H:%M",
"You don't have permissions to upload files." =>
"Δεν έχετε δικαίωμα να ανεβάσετε αρχεία.",
"You don't have permissions to browse server." =>
"Δεν έχετε δικαίωμα να δείτε τα αρχεία στο διακομιστή.",
"Cannot move uploaded file to target folder." =>
"Το αρχείο δε μπορεί να μεταφερθεί στο φάκελο προορισμού.",
"Unknown error." =>
"'Αγνωστο σφάλμα.",
"The uploaded file exceeds {size} bytes." =>
"Το αρχείο υπερβαίνει το μέγεθος των {size} bytes.",
"The uploaded file was only partially uploaded." =>
"Ένα μόνο μέρος του αρχείου ανέβηκε.",
"No file was uploaded." =>
"Κανένα αρχείο δεν ανέβηκε.",
"Missing a temporary folder." =>
"Λείπει ο φάκελος των προσωρινών αρχείων.",
"Failed to write file." =>
"Σφάλμα στη τροποποίηση του αρχείου.",
"Denied file extension." =>
"Δεν επιτρέπονται αυτού του είδους αρχεία.",
"Unknown image format/encoding." =>
"Αγνωστη κωδικοποίηση εικόνας.",
"The image is too big and/or cannot be resized." =>
"Η εικόνα είναι πάρα πολύ μεγάλη και/η δεν μπορεί να αλλάξει μέγεθος.",
"Cannot create {dir} folder." =>
"Αδύνατον να δημιουργηθεί ο φάκελος {dir}.",
"Cannot write to upload folder." =>
"Αδύνατη η εγγραφή στο φάκελο προορισμού.",
"Cannot read .htaccess" =>
"Αδύνατη η ανάγνωση του .htaccess",
"Incorrect .htaccess file. Cannot rewrite it!" =>
"Εσφαλμένο αρχείο .htaccess.Αδύνατη η τροποποίησή του!",
"Cannot read upload folder." =>
"Μη αναγνώσιμος φάκελος προορισμού.",
"Cannot access or create thumbnails folder." =>
"Αδύνατη η πρόσβαση και ανάγνωση του φακέλου με τις μικρογραφίες εικόνων.",
"Cannot access or write to upload folder." =>
"Αδύνατη η πρόσβαση και τροποποίηση του φακέλου προορισμού.",
"Please enter new folder name." =>
"Παρακαλούμε εισάγετε ένα νέο όνομα φακέλου. ",
"Unallowable characters in folder name." =>
"Μη επιτρεπτοί χαρακτήρες στο όνομα φακέλου.",
"Folder name shouldn't begins with '.'" =>
"Το όνομα του φακέλου δε πρέπει να αρχίζει με '.'",
"Please enter new file name." =>
"Παρακαλούμε εισάγετε ένα νέο όνομα αρχείου.",
"Unallowable characters in file name." =>
"Μη επιτρεπτοί χαρακτήρες στο όνομα αρχείου.",
"File name shouldn't begins with '.'" =>
"Το όνομα του αρχείου δε πρέπει να αρχίζει με '.'",
"Are you sure you want to delete this file?" =>
"Σίγουρα θέλετε να διαγράψετε αυτό το αρχείο?",
"Are you sure you want to delete this folder and all its content?" =>
"Σίγουρα θέλετε να διαγράψετε αυτό το φάκελο μαζί με όλα τα περιεχόμενα?",
"Non-existing directory type." =>
"Ανύπαρκτος τύπος φακέλου.",
"Undefined MIME types." =>
"Απροσδιόριστοι τύποι MIME.",
"Fileinfo PECL extension is missing." =>
"Η πληροφορία αρχείου επέκταση PECL δεν υπάρχει.",
"Opening fileinfo database failed." =>
"Η πρόσβαση στις πληροφορίες του αρχείου απέτυχε.",
"You can't upload such files." =>
"Δε μπορείτε να ανεβάσετε τέτοια αρχεία.",
"The file '{file}' does not exist." =>
"Το αρχείο '{file}' δεν υπάρχει.",
"Cannot read '{file}'." =>
"Αρχείο '{file}' μη αναγνώσιμο.",
"Cannot copy '{file}'." =>
"Αδύνατη η αντιγραφή του '{file}'.",
"Cannot move '{file}'." =>
"Αδύνατη η μετακίνηση του '{file}'.",
"Cannot delete '{file}'." =>
"Αδύνατη η διαγραφή του '{file}'.",
"Click to remove from the Clipboard" =>
"Πατήστε για διαγραφή από το Clipboard.",
"This file is already added to the Clipboard." =>
"Αυτό το αρχείο βρίσκεται ήδη στο Clipboard.",
"Copy files here" =>
"Αντιγράψτε αρχεία εδώ.",
"Move files here" =>
"Μετακινήστε αρχεία εδώ.",
"Delete files" =>
"Διαγραφή αρχείων",
"Clear the Clipboard" =>
"Καθαρισμός Clipboard",
"Are you sure you want to delete all files in the Clipboard?" =>
"Σίγουρα θέλετε να διαγράψετε όλα τα αρχεία στο Clipboard?",
"Copy {count} files" =>
"Αντιγραφή {count} αρχείων.",
"Move {count} files" =>
"Μετακίνηση {count} αρχείων.",
"Add to Clipboard" =>
"Προσθήκη στο Clipboard",
"New folder name:" => "Νέο όνομα φακέλου:",
"New file name:" => "Νέο όνομα αρχείου:",
"Upload" => "Ανέβασμα",
"Refresh" => "Ανανέωση",
"Settings" => "Ρυθμίσεις",
"Maximize" => "Μεγιστοποίηση",
"About" => "Σχετικά",
"files" => "αρχεία",
"View:" => "Προβολή:",
"Show:" => "Εμφάνιση:",
"Order by:" => "Ταξινόμηση κατά:",
"Thumbnails" => "Μικρογραφίες",
"List" => "Λίστα",
"Name" => "Όνομα",
"Size" => "Μέγεθος",
"Date" => "Ημερομηνία",
"Descending" => "Φθίνουσα",
"Uploading file..." => "Το αρχείο ανεβαίνει...",
"Loading image..." => "Η εικόνα φορτώνει...",
"Loading folders..." => "Οι φάκελοι φορτώνουν...",
"Loading files..." => "Τα αρχεία φορτώνουν...",
"New Subfolder..." => "Νέος υποφάκελος...",
"Rename..." => "Μετονομασία...",
"Delete" => "Διαγραφή",
"OK" => "OK",
"Cancel" => "Ακύρωση",
"Select" => "Επιλογή",
"Select Thumbnail" => "Επιλογή Μικρογραφίας",
"View" => "Προβολή",
"Download" => "Κατέβασμα",
'Clipboard' => "Clipboard",
// VERSION 2 NEW LABELS
"Cannot rename the folder." =>
"Αδύνατη η μετονομασία του φακέλου.",
"Cannot delete the folder." =>
"Αδύνατη η διαγραφή του φακέλου.",
"The files in the Clipboard are not readable." =>
"Τα αρχεία στο Clipboard είναι μη αναγνώσιμα.",
"{count} files in the Clipboard are not readable. Do you want to copy the rest?" =>
"{count} αρχεία στο Clipboard είναι μη αναγώσιμα.Θέλετε να αντιγράψετε τα υπόλοιπα?",
"The files in the Clipboard are not movable." =>
"Τα αρχεία στο Clipboard είναι αδύνατο να μετακινηθούν.",
"{count} files in the Clipboard are not movable. Do you want to move the rest?" =>
"{count} αρχεία στο Clipboard δεν είναι δυνατό να μετακινηθούν.Θέλετε να μετακινήσετε τα υπόλοιπα?",
"The files in the Clipboard are not removable." =>
"Τα αρχεία στο Clipboard είναι αδύνατο να αφαιρεθούν.",
"{count} files in the Clipboard are not removable. Do you want to delete the rest?" =>
"{count} αρχεία στο Clipboard δεν είναι δυνατό να αφαιρεθούν.Θέλετε να αφαιρέσετε τα υπόλοιπα?",
"The selected files are not removable." =>
"Τα επιλεγμένα αρχεία δε μπορούν να αφαιρεθούν.",
"{count} selected files are not removable. Do you want to delete the rest?" =>
"{count} επιλεγμένα αρχεία δεν είναι δυνατό να αφαιρεθούν.Θέλετε να διαγράψετε τα υπόλοιπα?",
"Are you sure you want to delete all selected files?" =>
"Σίγουρα θέλετε να διαγράψετε όλα τα επιλεγμένα αρχεία?",
"Failed to delete {count} files/folders." =>
"Η διαγραφή {count} αρχείων/φακέλων απέτυχε.",
"A file or folder with that name already exists." =>
"Ένα αρχείο ή φάκελος με αυτό το όνομα υπάρχει ήδη.",
"Inexistant or inaccessible folder." =>
"Ανύπαρκτος η μη προσβάσιμος φάκελος.",
"selected files" => "επιλεγμένα αρχεία",
"Type" => "Τύπος",
"Select Thumbnails" => "Επιλέξτε Μικρογραφίες",
"Download files" => "Κατέβασμα Αρχείων",
// SINCE 2.4
"Checking for new version..." => "Ελεγχος για νέα έκδοση...",
"Unable to connect!" => "Αδύνατη η σύνδεση!",
"Download version {version} now!" => "Κατεβάστε την έκδοση {version} τώρα!",
"KCFinder is up to date!" => "Το KCFinder είναι ενημερωμένο με τη πιο πρόσφατη έκδοση!",
"Licenses:" => "Άδειες:",
"Attention" => "Προσοχή",
"Question" => "Ερώτηση",
"Yes" => "Ναι",
"No" => "Όχι",
);
?>
| RevolvingMindMedia/holdennewhomes | couch/includes/kcfinder/lang/el.php | PHP | mit | 10,585 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>PublicationStore Class Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset='utf-8'>
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Class/PublicationStore" class="dashAnchor"></a>
<a title="PublicationStore Class Reference"></a>
<header>
<div class="content-wrapper">
<p><a href="../index.html">Matchmore Docs</a> (47% documented)</p>
</div>
</header>
<div class="content-wrapper">
<p id="breadcrumbs">
<a href="../index.html">Matchmore Reference</a>
<img id="carat" src="../img/carat.png" />
PublicationStore Class Reference
</p>
</div>
<div class="content-wrapper">
<nav class="sidebar">
<ul class="nav-groups">
<li class="nav-group-name">
<a href="../Classes.html">Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Classes.html#/s:9Matchmore7APIBaseC">APIBase</a>
</li>
<li class="nav-group-task">
<a href="../Classes/APIError.html">APIError</a>
</li>
<li class="nav-group-task">
<a href="../Classes/AlamofireRequestBuilder.html">AlamofireRequestBuilder</a>
</li>
<li class="nav-group-task">
<a href="../Classes/AlpsAPI.html">AlpsAPI</a>
</li>
<li class="nav-group-task">
<a href="../Classes/AlpsManager.html">AlpsManager</a>
</li>
<li class="nav-group-task">
<a href="../Classes/BeaconTripleStore.html">BeaconTripleStore</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Configuration.html">Configuration</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Device.html">Device</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DeviceAPI.html">DeviceAPI</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DeviceUpdate.html">DeviceUpdate</a>
</li>
<li class="nav-group-task">
<a href="../Classes/EncodableDevice.html">EncodableDevice</a>
</li>
<li class="nav-group-task">
<a href="../Classes/EncodableIBeaconDevice.html">EncodableIBeaconDevice</a>
</li>
<li class="nav-group-task">
<a href="../Classes/EncodableIBeaconTriple.html">EncodableIBeaconTriple</a>
</li>
<li class="nav-group-task">
<a href="../Classes/EncodableLocation.html">EncodableLocation</a>
</li>
<li class="nav-group-task">
<a href="../Classes/EncodableMatch.html">EncodableMatch</a>
</li>
<li class="nav-group-task">
<a href="../Classes/EncodableMobileDevice.html">EncodableMobileDevice</a>
</li>
<li class="nav-group-task">
<a href="../Classes/EncodablePinDevice.html">EncodablePinDevice</a>
</li>
<li class="nav-group-task">
<a href="../Classes/EncodablePublication.html">EncodablePublication</a>
</li>
<li class="nav-group-task">
<a href="../Classes/EncodableSubscription.html">EncodableSubscription</a>
</li>
<li class="nav-group-task">
<a href="../Classes/IBeaconDevice.html">IBeaconDevice</a>
</li>
<li class="nav-group-task">
<a href="../Classes/IBeaconTriple.html">IBeaconTriple</a>
</li>
<li class="nav-group-task">
<a href="../Classes/KeychainHelper.html">KeychainHelper</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Location.html">Location</a>
</li>
<li class="nav-group-task">
<a href="../Classes/LocationAPI.html">LocationAPI</a>
</li>
<li class="nav-group-task">
<a href="../Classes.html#/s:9Matchmore21LocationUpdateManagerC">LocationUpdateManager</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Match.html">Match</a>
</li>
<li class="nav-group-task">
<a href="../Classes.html#/s:9Matchmore12MatchMonitorC">MatchMonitor</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MatchMore.html">MatchMore</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MatchesAPI.html">MatchesAPI</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MobileDevice.html">MobileDevice</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MobileDeviceStore.html">MobileDeviceStore</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MulticastDelegate.html">MulticastDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PinDevice.html">PinDevice</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PinDeviceStore.html">PinDeviceStore</a>
</li>
<li class="nav-group-task">
<a href="../Classes/ProximityEvent.html">ProximityEvent</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Publication.html">Publication</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PublicationAPI.html">PublicationAPI</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PublicationStore.html">PublicationStore</a>
</li>
<li class="nav-group-task">
<a href="../Classes.html#/s:9Matchmore25RemoteNotificationManagerC">RemoteNotificationManager</a>
</li>
<li class="nav-group-task">
<a href="../Classes/RequestBuilder.html">RequestBuilder</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Response.html">Response</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Subscription.html">Subscription</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SubscriptionAPI.html">SubscriptionAPI</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SubscriptionStore.html">SubscriptionStore</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Enums.html">Enumerations</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Enums/DeviceType.html">DeviceType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/ErrorResponse.html">ErrorResponse</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Result.html">Result</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Extensions/Sequence.html">Sequence</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Functions.html">Functions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Functions.html#/s:9Matchmore2peoiyAA17MulticastDelegateCyxG_xtlF">+=(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:9Matchmore2seoiyAA17MulticastDelegateCyxG_xtlF">-=(_:_:)</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Protocols/MatchDelegate.html">MatchDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/RequestBuilderFactory.html">RequestBuilderFactory</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Structs.html">Structures</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Structs/MatchMoreConfig.html">MatchMoreConfig</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Typealiases.html">Type Aliases</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Typealiases.html#/s:9Matchmore7Devicesa">Devices</a>
</li>
<li class="nav-group-task">
<a href="../Typealiases.html#/s:9Matchmore14IBeaconTriplesa">IBeaconTriples</a>
</li>
<li class="nav-group-task">
<a href="../Typealiases.html#/s:9Matchmore7Matchesa">Matches</a>
</li>
<li class="nav-group-task">
<a href="../Typealiases.html#/s:9Matchmore14OnMatchClosurea">OnMatchClosure</a>
</li>
<li class="nav-group-task">
<a href="../Typealiases.html#/s:9Matchmore12Publicationsa">Publications</a>
</li>
<li class="nav-group-task">
<a href="../Typealiases.html#/s:9Matchmore13Subscriptionsa">Subscriptions</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section>
<section class="section">
<h1>PublicationStore</h1>
<div class="declaration">
<div class="language">
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">final</span> <span class="kd">class</span> <span class="kt">PublicationStore</span><span class="p">:</span> <span class="kt">CRD</span></code></pre>
</div>
</div>
<p>Undocumented</p>
</section>
<section class="section task-group-section">
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:9Matchmore16PublicationStoreC6createyAA0B0C4item_yAA6ResultOyAFGc10completiontF"></a>
<a name="//apple_ref/swift/Method/create(item:completion:)" class="dashAnchor"></a>
<a class="token" href="#/s:9Matchmore16PublicationStoreC6createyAA0B0C4item_yAA6ResultOyAFGc10completiontF">create(item:completion:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">create</span><span class="p">(</span><span class="nv">item</span><span class="p">:</span> <span class="kt"><a href="../Classes/Publication.html">Publication</a></span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt"><a href="../Enums/Result.html">Result</a></span><span class="o"><</span><span class="kt"><a href="../Classes/Publication.html">Publication</a></span><span class="o">></span><span class="p">)</span> <span class="o">-></span> <span class="kt">Void</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:9Matchmore16PublicationStoreC4findySS4byId_yAA0B0CSgc10completiontF"></a>
<a name="//apple_ref/swift/Method/find(byId:completion:)" class="dashAnchor"></a>
<a class="token" href="#/s:9Matchmore16PublicationStoreC4findySS4byId_yAA0B0CSgc10completiontF">find(byId:completion:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">find</span><span class="p">(</span><span class="nv">byId</span><span class="p">:</span> <span class="kt">String</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt"><a href="../Classes/Publication.html">Publication</a></span><span class="p">?)</span> <span class="o">-></span> <span class="kt">Void</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:9Matchmore16PublicationStoreC7findAllyySayAA0B0CGc10completion_tF"></a>
<a name="//apple_ref/swift/Method/findAll(completion:)" class="dashAnchor"></a>
<a class="token" href="#/s:9Matchmore16PublicationStoreC7findAllyySayAA0B0CGc10completion_tF">findAll(completion:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">findAll</span><span class="p">(</span><span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">([</span><span class="kt"><a href="../Classes/Publication.html">Publication</a></span><span class="p">])</span> <span class="o">-></span> <span class="kt">Void</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:9Matchmore16PublicationStoreC6deleteyAA0B0C4item_yAA13ErrorResponseOSgc10completiontF"></a>
<a name="//apple_ref/swift/Method/delete(item:completion:)" class="dashAnchor"></a>
<a class="token" href="#/s:9Matchmore16PublicationStoreC6deleteyAA0B0C4item_yAA13ErrorResponseOSgc10completiontF">delete(item:completion:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">delete</span><span class="p">(</span><span class="nv">item</span><span class="p">:</span> <span class="kt"><a href="../Classes/Publication.html">Publication</a></span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt"><a href="../Enums/ErrorResponse.html">ErrorResponse</a></span><span class="p">?)</span> <span class="o">-></span> <span class="kt">Void</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:9Matchmore16PublicationStoreC9deleteAllyyAA13ErrorResponseOSgc10completion_tF"></a>
<a name="//apple_ref/swift/Method/deleteAll(completion:)" class="dashAnchor"></a>
<a class="token" href="#/s:9Matchmore16PublicationStoreC9deleteAllyyAA13ErrorResponseOSgc10completion_tF">deleteAll(completion:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">deleteAll</span><span class="p">(</span><span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt"><a href="../Enums/ErrorResponse.html">ErrorResponse</a></span><span class="p">?)</span> <span class="o">-></span> <span class="kt">Void</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
</ul>
</div>
</section>
</section>
<section id="footer">
<p>© 2018 <a class="link" href="https://matchmore.io" target="_blank" rel="external">Matchmore SDK Team</a>. All rights reserved. (Last updated: 2018-04-05)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.9.1</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</article>
</div>
</body>
</div>
</html>
| matchmore/alps-ios-sdk | docs/docsets/Matchmore.docset/Contents/Resources/Documents/Classes/PublicationStore.html | HTML | mit | 20,594 |
@echo off
set PP=%~dp0
%PP%as %*
| goriy/sif | misc/x86_64-w64-mingw32-as.bat | Batchfile | mit | 33 |
'use strict';
var constants = require('../../lifx').constants;
var Packet = {
size: 21
};
/**
* Converts packet specific data from a buffer to an object
* @param {Buffer} buf Buffer containing only packet specific data no header
* @return {Object} Information contained in packet
*/
Packet.toObject = function(buf) {
var obj = {};
var offset = 0;
if (buf.length !== this.size) {
throw new Error('Invalid length given for setWaveform LIFX packet');
}
obj.stream = buf.readUInt8(offset);
offset += 1;
obj.isTransient = buf.readUInt8(offset);
offset += 1;
obj.color = {};
obj.color.hue = buf.readUInt16LE(offset);
offset += 2;
obj.color.saturation = buf.readUInt16LE(offset);
offset += 2;
obj.color.brightness = buf.readUInt16LE(offset);
offset += 2;
obj.color.kelvin = buf.readUInt16LE(offset);
offset += 2;
obj.period = buf.readUInt32LE(offset);
offset += 4;
obj.cycles = buf.readFloatLE(offset);
offset += 4;
obj.skewRatio = buf.readUInt16LE(offset);
offset += 2;
obj.waveform = buf.readUInt8(offset);
offset += 1;
return obj;
};
/**
* Converts the given packet specific object into a packet
* @param {Object} obj object with configuration data
* @param {Boolean} obj.isTransient restore color used before effect
* @param {Object} obj.color an objects with colors to set
* @param {Number} obj.color.hue between 0 and 65535
* @param {Number} obj.color.saturation between 0 and 65535
* @param {Number} obj.color.brightness between 0 and 65535
* @param {Number} [obj.color.kelvin=3500] between 2500 and 9000
* @param {Number} obj.period length of one cycle in milliseconds
* @param {Number} obj.cycles how often to repeat through effect
* @param {Number} obj.skewRatio distribution between time on original and new color , positive is for more new color, negative for original color
* @param {Number} obj.waveform between 0 and 4 for form of effect
* @return {Buffer} packet
*/
Packet.toBuffer = function(obj) {
var buf = new Buffer(this.size);
buf.fill(0);
var offset = 0;
// obj.stream field has unknown function so leave it as 0
offset += 1;
if (obj.isTransient === undefined) {
throw new TypeError('obj.isTransient value must be given for setWaveform LIFX packet');
}
if (typeof obj.isTransient !== 'boolean') {
throw new TypeError('Invalid isTransient value given for setWaveform LIFX packet, must be boolean');
}
buf.writeUInt8(obj.isTransient, offset);
offset += 1;
if (typeof obj.color !== 'object') {
throw new TypeError('Invalid object for color given for setWaveform LIFX packet');
}
if (typeof obj.color.hue !== 'number' && obj.color.hue < 0 || obj.color.hue > 65535) {
throw new RangeError('Invalid color hue given for setWaveform LIFX packet, must be a number between 0 and 65535');
}
buf.writeUInt16LE(obj.color.hue, offset);
offset += 2;
if (typeof obj.color.saturation !== 'number' && obj.color.saturation < 0 || obj.color.saturation > 65535) {
throw new RangeError('Invalid color saturation given for setWaveform LIFX packet, must be a number between 0 and 65535');
}
buf.writeUInt16LE(obj.color.saturation, offset);
offset += 2;
if (typeof obj.color.brightness !== 'number' && obj.color.brightness < 0 || obj.color.brightness > 65535) {
throw new RangeError('Invalid color brightness given for setWaveform LIFX packet, must be a number between 0 and 65535');
}
buf.writeUInt16LE(obj.color.brightness, offset);
offset += 2;
if (obj.color.kelvin === undefined) {
obj.color.kelvin = constants.HSBK_DEFAULT_KELVIN;
}
if (typeof obj.color.kelvin !== 'number' && obj.color.kelvin < 2500 || obj.color.kelvin > 9000) {
throw new RangeError('Invalid color kelvin given for setWaveform LIFX packet, must be a number between 2500 and 9000');
}
buf.writeUInt16LE(obj.color.kelvin, offset);
offset += 2;
if (obj.period === undefined) {
throw new TypeError('obj.period value must be given for setWaveform LIFX packet');
}
if (typeof obj.period !== 'number') {
throw new TypeError('Invalid period type given for setWaveform LIFX packet, must be a number');
}
buf.writeUInt32LE(obj.period, offset);
offset += 4;
if (obj.cycles === undefined) {
throw new TypeError('obj.cycles value must be given for setWaveform LIFX packet');
}
if (typeof obj.cycles !== 'number') {
throw new TypeError('Invalid cycles type given for setWaveform LIFX packet, must be a number');
}
buf.writeFloatLE(obj.cycles, offset);
offset += 4;
if (obj.skewRatio === undefined) {
throw new TypeError('obj.skewRatio value must be given for setWaveform LIFX packet');
}
if (typeof obj.skewRatio !== 'number') {
throw new TypeError('Invalid skewRatio type given for setWaveform LIFX packet, must be a number');
}
buf.writeInt16LE(obj.skewRatio, offset);
offset += 2;
if (obj.waveform === undefined) {
throw new TypeError('obj.waveform value must be given for setWaveform LIFX packet');
}
if (typeof obj.waveform !== 'number' && obj.waveform < 0 || obj.waveform > (constants.LIGHT_WAVEFORMS.length - 1)) {
throw new RangeError('Invalid waveform value given for setWaveform LIFX packet, must be a number between 0 and ' + (constants.LIGHT_WAVEFORMS.length - 1));
}
buf.writeUInt8(obj.waveform, offset);
offset += 1;
return buf;
};
module.exports = Packet;
| 3sigma/NodejsLIFXSerial_nwjs_shell_builder | node_modules/node-lifx/lib/lifx/packets/setWaveform.js | JavaScript | mit | 5,427 |
/*
Baseline - a designer framework
Copyright (C) 2009 Stephane Curzi, ProjetUrbain.com
Creative Commons Attribution-Share Alike 3.0 License
*/
/* Baseline Grid */
.layout-grid { background-image: url(images/baseline.png); background-repeat: repeat; background-position: 0 1px; }
| lifelink1987/old.life-link.org | tpl.main/css/static/baseline.0.5.3/css/background-grid/grid.baseline.css | CSS | mit | 281 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* ApplyRecoveryPoint input specific to A2A provider.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType")
@JsonTypeName("A2A")
public class A2AApplyRecoveryPointInput extends ApplyRecoveryPointProviderSpecificInput {
}
| selvasingh/azure-sdk-for-java | sdk/recoveryservices.siterecovery/mgmt-v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AApplyRecoveryPointInput.java | Java | mit | 704 |
import { createReducer } from 'redux-act';
import { fetchSystemStatus } from 'actions';
import { loadState, loadStart, loadError, loadComplete } from 'reducers/util';
const initialState = loadState();
export default createReducer({
[fetchSystemStatus.START]: state => loadStart(state),
[fetchSystemStatus.ERROR]: (state, { error }) => loadError(state, error),
[fetchSystemStatus.COMPLETE]: (state, { status }) => loadComplete(status),
}, initialState);
| pudo/aleph | ui/src/reducers/systemStatus.js | JavaScript | mit | 462 |
// Utility code
#include <cstdlib>
#include "global.h"
#include "jitpch.h"
#include "cor.h" // CorSigUncompressData
#include "utility.h"
#include "llvm/Support/ConvertUTF.h"
using std::string;
using std::unique_ptr;
int MethodID::parseArgs(const string &S, size_t &I) {
size_t Start = ++I; // skip '('
I = S.find_first_of(")", I);
if (I == string::npos)
return MethodIDState::ANYARGS;
string num = string(S, Start, I - Start);
int NArgs = atoi(num.c_str());
++I; // skip )
return NArgs;
}
unique_ptr<MethodID> MethodID::parse(const string &S, size_t &I) {
MethodID MID;
size_t SLen = S.length();
string token = MID.scan(S, I);
if (token == "") // off the end of S
return nullptr;
if (token == "*") {
MID.ClassName = llvm::make_unique<string>(token);
MID.MethodName = nullptr;
if (I >= SLen || S[I] == ' ') {
MID.NumArgs = MethodIDState::ANYARGS;
}
return llvm::make_unique<MethodID>(MID);
return nullptr;
}
if (S[I] == ':') { // C:M | C:M(A)
MID.ClassName = llvm::make_unique<string>(token);
token = MID.scan(S, ++I); // M | M(A)
}
MID.MethodName = llvm::make_unique<string>(token);
if (I >= SLen || S[I] == ' ') {
MID.NumArgs = MethodIDState::ANYARGS;
return llvm::make_unique<MethodID>(MID);
return nullptr;
}
if (S[I] != '(') // illegal
return nullptr;
MID.NumArgs = MID.parseArgs(S, I);
return llvm::make_unique<MethodID>(MID);
return nullptr;
}
string MethodID::scan(const string &S, size_t &I) {
const size_t SLen = S.length();
if (I >= SLen) // already 'off the end'
return string{""};
size_t Start = I = S.find_first_not_of(" \t", I); // skip whitespace
I = S.find_first_of(" :()", I);
if (I == string::npos) // eg: S = "*"
I = SLen;
return string(S, Start, I - Start);
}
void MethodSet::init(unique_ptr<string> ConfigValue) {
if (this->isInitialized()) {
return;
}
insert(std::move(ConfigValue));
}
void MethodSet::insert(unique_ptr<string> Ups) {
size_t I = 0;
std::list<MethodID> *MIDL = new std::list<MethodID>();
string S = *Ups;
auto MID = MethodID::parse(S, I);
while (MID) {
MIDL->push_back(*MID);
MID = MethodID::parse(S, I);
}
// This write should be atomic, delete if we're not the first.
llvm::sys::cas_flag F = llvm::sys::CompareAndSwap(
(llvm::sys::cas_flag *)&(this->Initialized), 0x1, 0x0);
if (F != 0x0) {
delete MIDL;
} else {
this->MethodIDList = MIDL;
}
}
bool MethodSet::contains(const char *MethodName, const char *ClassName,
PCCOR_SIGNATURE PCSig) {
assert(this->isInitialized());
int NumArgs = MethodIDState::ANYARGS; // assume no signature supplied
if (PCSig) {
PCSig++; // skip calling convention
NumArgs = CorSigUncompressData(PCSig);
}
string StrClassName = ClassName ? ClassName : "";
string StrMethodName = MethodName ? MethodName : "";
auto begin = this->MethodIDList->begin();
auto end = this->MethodIDList->end();
for (auto p = begin; p != end; ++p) { // p => "pattern"
// Check for "*", the common case, first
if (p->ClassName && *p->ClassName == "*")
return true;
// Check for mis-match on NumArgs
if (p->NumArgs != MethodIDState::ANYARGS && p->NumArgs != NumArgs)
continue;
// Check for mis-match on MethodName
if (p->MethodName && (*p->MethodName != StrMethodName))
continue;
// Check for match on ClassName (we already match NumArgs and MethodName)
if (!p->ClassName) // no ClassName
return true;
if (*p->ClassName == StrClassName)
return true;
}
return false;
}
unique_ptr<std::string> Convert::utf16ToUtf8(const char16_t *WideStr) {
// Get the length of the input
size_t SrcLen = 0;
for (; WideStr[SrcLen] != (char16_t)0; SrcLen++)
;
llvm::ArrayRef<char> SrcBytes((const char *)WideStr, 2 * SrcLen);
unique_ptr<std::string> OutString(new std::string);
convertUTF16ToUTF8String(SrcBytes, *OutString);
return OutString;
}
| richardlford/llilc | lib/Jit/utility.cpp | C++ | mit | 4,029 |
package net.mostlyoriginal.game.system.flow;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.artemis.utils.EntityBuilder;
import net.mostlyoriginal.api.component.script.Schedule;
import net.mostlyoriginal.api.manager.AbstractAssetSystem;
import net.mostlyoriginal.game.GdxArtemisGame;
import net.mostlyoriginal.game.component.RetryLevel;
import net.mostlyoriginal.game.component.logic.Transition;
/**
* @author Daan van Yperen
*/
@Wire
public class RetryLevelSystem extends EntityProcessingSystem {
protected ComponentMapper<RetryLevel> mRetryLevelSystem;
private AbstractAssetSystem gameScreenAssetSystem;
public RetryLevelSystem() {
super(Aspect.all(RetryLevel.class));
}
/** Transition to screen after delay in seconds. */
public void transition(float delay) {
new EntityBuilder(world).with(new Schedule().wait(delay).add(new RetryLevel()));
gameScreenAssetSystem.playSfx("loss");
}
@Override
protected void process(Entity e) {
try {
GdxArtemisGame.getInstance().retryLevel();
} catch (Exception ex ) {
throw new RuntimeException(ex);
}
}
}
| thecocce/odb-minion-factorium | core/src/net/mostlyoriginal/game/system/flow/RetryLevelSystem.java | Java | mit | 1,221 |
body {
font-family: Helvetica, sans-serif;
padding: 0;
margin: 0;
background-color: #ffffff;
}
h2, h3 {
margin-top:100px;
}
form {
margin-top: 15px;
margin-left: 550px;
}
form > input {
margin-right: 15px;
}
/*#my_camera{
float:auto;
margin:10px;
padding:10px;
border:1px solid;
}*/
#results {
float:left;
margin:20px;
padding:20px;
border:1px solid;
color: #000000;
background:#ffffff;
z-index: 2;
position: absolute;
top:550px;
}
#block{
position: absolute;
top: 57px;
left: 150px;
width: 1200px;
height: 28px;
display: inline;
background: rgb(202, 60, 60);
color: #ffffff;
line-height: 28px;
padding-left: 5px;
}
/*#form{
color: #000000;
margin-top: 30px;
line-height: 25px;
}*/
.word{
color:#000000;
}
#btn{
margin-top: 60px;
}
| Oryano/Social_Clinic | css/styles.css | CSS | mit | 997 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery微博信息渐显循环显示效果</title>
<script type="text/jscript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/jscript">
$(document).ready(function(e) {
var in_out_time = 800 //渐显时间
var scroll_Interval_time = 2000 //滚动间隔时间
var scroll_time = 1000 //滚动动画时间
addli()
function addli(){
$("#scroll_List").css("top",0);
$("#scroll_List li:last").clone().prependTo("#scroll_List");
$("#scroll_List li:first").css("opacity",0);
$("#scroll_List li:first").animate({opacity:1},in_out_time);
setTimeout(delLi_last,scroll_Interval_time)
}
function delLi_last(){
$("#scroll_List li:last").detach();
$("#scroll_List").animate({top:100},scroll_time,addli)
}
});
</script>
<style>
* {
margin: 0px;
padding: 0px;
list-style: none;
}
.centerBox {
left: 50%;
width: 212px;
margin-left: -151px;
top: 50%;
height: 312px;
margin-top: -156px;
position: absolute;
}
.main {
width: 210px;
height: 310px;
float: left;
border: 1px solid #ccc;
}
.main strong {
width: 200px;
height: 300px;
float: left;
overflow: hidden;
margin: 5px;
display: inline;
position: relative;
}
.main strong ul {
width: 200px;
position: absolute;
}
.main strong ul li {
width: 200px;
height: 100px;
line-height: 100px;
text-align: center;
color: #FFF;
font-family: "simhei";
font-size: 20px;
}
.main strong ul .li_1 {
background: #900;
}
.main strong ul .li_2 {
background: #9C0;
}
.main strong ul .li_3 {
background: #036;
}
.main strong ul .li_4 {
background: #C60;
}
.main strong ul .li_5 {
background: #636;
}
.main strong ul .li_6 {
background: #999;
}
</style>
</head>
<body>
<div class="centerBox">
<div class="main">
<strong>
<ul id="scroll_List">
<li class="li_1">
文本1111dddddddddddddddddd
</li>
<li class="li_2">
文本2ssssssssssssssssssss
</li>
<li class="li_3">
文本3cccccccccccccccccccccc
</li>
<li class="li_4">
文本4cccccccc3333333333333
</li>
</ul> </strong>
</div>
</div>
</body>
</html> | hehongwei44/Project-FE | examples/example.html | HTML | mit | 3,516 |
package org.brunosimoes.programs.paintbrush;
import java.applet.Applet;
import java.awt.Color;
/**
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.<br><br>
*
* 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.<br><br>
*
* 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.,
* 675 Mass Ave, Cambridge, MA 02139, USA.<br><br>
*
* @version 1.0.0.1 (20040301)
* @author <a href="mailto:brunogsimoes@gmail.com">Bruno Simões</a>
*
* Copyright (c) 2004 Bruno Simões. All Rights Reserved.
*/
public class PaintBrushApplet extends Applet {
private static final long serialVersionUID = 873317986287453309L;
public void init(){
setBackground(new Color(170,170,170));
new PaintBrush();
}
}
| behnaaz/jPaintbrush | src/org/brunosimoes/programs/paintbrush/PaintBrushApplet.java | Java | mit | 1,233 |
<?php
/**
* PHP 7 SDK for the KATANA(tm) Framework (http://katana.kusanagi.io)
* Copyright (c) 2016-2018 KUSANAGI S.L. All rights reserved.
*
* Distributed under the MIT license
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code
*
* @link https://github.com/kusanagi/katana-sdk-php7
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @copyright Copyright (c) 2016-2018 KUSANAGI S.L. (http://kusanagi.io)
*/
namespace Katana\Sdk\Tests\Mapper;
use Katana\Sdk\Api\Value\ActionTarget;
use Katana\Sdk\Api\Value\VersionString;
use Katana\Sdk\File;
use Katana\Sdk\Mapper\CompactRuntimeCallMapper;
use Katana\Sdk\Mapper\RuntimeCallWriterInterface;
use Katana\Sdk\Mapper\TransportWriterInterface;
use Katana\Sdk\Param;
use Katana\Sdk\Api\Transport;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
abstract class AbstractRuntimeCallMapperTest extends TestCase
{
abstract function getSystemUnderTest(TransportWriterInterface $transpotMapper): RuntimeCallWriterInterface;
abstract protected function getExpectedOutput(): array;
public function testMapping()
{
$transportMapper = $this->prophesize(TransportWriterInterface::class);
$transportMapper->writeTransport(Argument::any())->willReturn([]);
$transport = $this->prophesize(Transport::class);
$target = new ActionTarget(
'target_service',
new VersionString('1.0.1'),
'target_action'
);
$param = $this->prophesize(Param::class);
$param->getName()->willReturn('param');
$param->getValue()->willReturn('value');
$param->getType()->willReturn('string');
$file = $this->prophesize(File::class);
$file->getName()->willReturn('file_name');
$file->getPath()->willReturn('http://12.34.56.78:1234/files/ac3bd4b8-7da3-4c40-8661-746adfa55e0d');
$file->getToken()->willReturn('fb9an6c46be74s425010896fcbd99e2a');
$file->getFilename()->willReturn('smiley.jpg');
$file->getSize()->willReturn(1234567890);
$file->getMime()->willReturn('image/jpeg');
$mapper = $this->getSystemUnderTest($transportMapper->reveal());
$output = $mapper->writeRuntimeCall(
'action',
$transport->reveal(),
$target,
[$param->reveal()],
[$file->reveal()]);
$this->assertEquals($this->getExpectedOutput(), $output);
}
}
| fcastilloes/katana-sdk-php7 | tests/Mapper/AbstractRuntimeCallMapperTest.php | PHP | mit | 2,527 |
<?php
class Order extends \Eloquent {
protected $fillable = ['table_id', 'completed'];
} | slawisha/RestaurantManager | app/models/Order.php | PHP | mit | 90 |
# React
En este ejemplo añadiremos soporte para [React](https://facebook.github.io/react/).
Empezaremos desde el ejemplo
[00 Intro / 03 Ouput](https://github.com/Lemoncode/webpack-1.x-by-sample/tree/master/00%20Intro/03%20Output)
, instalaremos React de forma local, actualizaremos el archivo *students.js* para usar la sintaxis **_jsx_**, instalaremos el plugin
[*babel-preset-react*](https://github.com/babel/babel/tree/master/packages/babel-preset-react)
y lo configuraremos en *webpack.config.js*.
Resumen de los pasos:
- Instalar React como dependencia local.
- Añadir un punto de entrada para nuestra aplicacion React en *index.html*.
- Actualizar *students.js* a *students.__jsx__* y su contenido.
- Instalar [*babel-preset-react*](https://github.com/babel/babel/tree/master/packages/babel-preset-react)
asi *babel* podrá resolver los archivos *jsx*.
- Añadir la configuracion adecuada y necesaria en *webpack.config.js*.
# Pasos para construir
## Prerrequisitos
Necesitarás tener instalado [Node.js](https://nodejs.org) en tu ordenador. Si quieres
seguir esta guía necesitarás tomar como punto de inicio el ejemplo
[00 Intro / 03 Ouput](https://github.com/Lemoncode/webpack-1.x-by-sample/tree/master/00%20Intro/03%20Output).
## pasos
- React es una librería de código abierto para crear *interfaces* (demasiado popular hoy en día), empezaremos instalando la librería (*react* y *react-dom*).
```
npm install react --save
npm install react-dom --save
```
- En el archivo *index.html* vamos a añadir `<div>` que será nuestro punto de inicio para nuestra app React.
```html
<body>
Hello webpack !
<div id="root">
</div>
</body>
```
- Vamos a renombrarlo *students.js* a *students.__jsx__* y actualizamos el código para usar React.
```javascript
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {getAvg} from './averageService';
const AverageUi = React.createClass({
getInitialState: function () {
return { scores: [90, 75, 60, 99, 94, 30], average: 0 };
},
componentDidMount: function () {
this.setState({ average: getAvg(this.state.scores) });
},
render: function () {
return (
<div>
<span>Students average: {this.state.average}</span>
</div>
);
}
});
ReactDOM.render(
<div>
Hello from react dom
<AverageUi/>
</div>
, document.getElementById('root'));
```
- Para que *babel* parsee los archivos React *jsx* , necesitamos instalar
[*babel-preset-react*](https://github.com/babel/babel/tree/master/packages/babel-preset-react).
```
npm install babel-preset-react --save-dev
```
- Ahora actualizamos *webpack.config.js*, empezaremos añadiendo la extension *jsx* y actualizando el punto de entrada, *students.jsx*.
```
module.exports = {
entry: ['./students.jsx'],
```
- En las secciones *loaders* necesitamos indicar a *babel-loader* que deberá coger no solo los archivos *js* sino _**jsx**_, y que tiene que tener en cuenta React como *presets*.
```
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
```
- Finalmente si arrancamos la aplicacion, veremos en acción la correcta funcionalidad basada en React.

| Lemoncode/webpack-1.x-by-sample | 02 Fx/01 React/README_es.md | Markdown | mit | 3,401 |
default: clean dist run
dist:
mkdir bin/
gcc -std=c99 -I src src/stateMachine.c examples/stateMachineExample.c -o bin/example
run:
./bin/example
clean:
rm -rf bin | adfjhg/stateMachine | Makefile | Makefile | mit | 172 |
A NautilusExtendCommentSwitch is raised when the button to maximize the class comment is switched | vineetreddyrajula/pharo | src/NautilusCommon.package/NautilusExtendCommentSwitch.class/README.md | Markdown | mit | 97 |
require_relative 'random_name_generator'
require_relative 'cumulative_probability_table'
# Class to test the random name generator from the command line interface.
# Will spit out a long list of random names.
class RandomNameGeneratorTest
generator = RandomNameGenerator.new('media/male_sample')
puts 'Generating 40 male names'
40.times { puts generator.generate }
end | gilles-leblanc/gameproject | RandomNameGeneration/random_name_generator_test.rb | Ruby | mit | 376 |
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Filesystem\Filesystem;
/**
* @method static \Illuminate\Contracts\Filesystem\Filesystem assertExists(string|array $path)
* @method static \Illuminate\Contracts\Filesystem\Filesystem assertMissing(string|array $path)
* @method static \Illuminate\Contracts\Filesystem\Filesystem cloud()
* @method static \Illuminate\Contracts\Filesystem\Filesystem build(string|array $root)
* @method static \Illuminate\Contracts\Filesystem\Filesystem disk(string|null $name = null)
* @method static \Illuminate\Filesystem\FilesystemManager extend(string $driver, \Closure $callback)
* @method static \Symfony\Component\HttpFoundation\StreamedResponse download(string $path, string|null $name = null, array|null $headers = [])
* @method static \Symfony\Component\HttpFoundation\StreamedResponse response(string $path, string|null $name = null, array|null $headers = [], string|null $disposition = 'inline')
* @method static array allDirectories(string|null $directory = null)
* @method static array allFiles(string|null $directory = null)
* @method static array directories(string|null $directory = null, bool $recursive = false)
* @method static array files(string|null $directory = null, bool $recursive = false)
* @method static bool append(string $path, string $data)
* @method static bool copy(string $from, string $to)
* @method static bool delete(string|array $paths)
* @method static bool deleteDirectory(string $directory)
* @method static bool exists(string $path)
* @method static bool makeDirectory(string $path)
* @method static bool missing(string $path)
* @method static bool move(string $from, string $to)
* @method static bool prepend(string $path, string $data)
* @method static bool put(string $path, \Psr\Http\Message\StreamInterface|\Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|resource $contents, mixed $options = [])
* @method static bool setVisibility(string $path, string $visibility)
* @method static bool writeStream(string $path, resource $resource, array $options = [])
* @method static int lastModified(string $path)
* @method static int size(string $path)
* @method static resource|null readStream(string $path)
* @method static string get(string $path)
* @method static string getVisibility(string $path)
* @method static string path(string $path)
* @method static string temporaryUrl(string $path, \DateTimeInterface $expiration, array $options = [])
* @method static string url(string $path)
* @method static string|false mimeType(string $path)
* @method static string|false putFile(string $path, \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $file, mixed $options = [])
* @method static string|false putFileAs(string $path, \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $file, string $name, mixed $options = [])
*
* @see \Illuminate\Filesystem\FilesystemManager
*/
class Storage extends Facade
{
/**
* Replace the given disk with a local testing disk.
*
* @param string|null $disk
* @param array $config
* @return \Illuminate\Contracts\Filesystem\Filesystem
*/
public static function fake($disk = null, array $config = [])
{
$disk = $disk ?: static::$app['config']->get('filesystems.default');
$root = storage_path('framework/testing/disks/'.$disk);
if ($token = ParallelTesting::token()) {
$root = "{$root}_test_{$token}";
}
(new Filesystem)->cleanDirectory($root);
static::set($disk, $fake = static::createLocalDriver(array_merge($config, [
'root' => $root,
])));
return $fake;
}
/**
* Replace the given disk with a persistent local testing disk.
*
* @param string|null $disk
* @param array $config
* @return \Illuminate\Contracts\Filesystem\Filesystem
*/
public static function persistentFake($disk = null, array $config = [])
{
$disk = $disk ?: static::$app['config']->get('filesystems.default');
static::set($disk, $fake = static::createLocalDriver(array_merge($config, [
'root' => storage_path('framework/testing/disks/'.$disk),
])));
return $fake;
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'filesystem';
}
}
| mul14/laravel-framework | src/Illuminate/Support/Facades/Storage.php | PHP | mit | 4,441 |
/*
* Sleuth Kit Data Model
*
* Copyright 2014 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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 org.sleuthkit.datamodel;
/**
* Used to pass info about a hash so that it can be added into the TSK-db from Autopsy.
* HashHitInfo is for the reverse direction.
*/
public class HashEntry {
private String fileName;
private String md5Hash;
private String sha1Hash;
private String sha256Hash;
private String comment;
public HashEntry(String fileName, String md5Hash, String sha1Hash, String sha256Hash, String comment) {
this.fileName = fileName;
this.md5Hash = md5Hash;
this.sha1Hash = sha1Hash;
this.sha256Hash = sha256Hash;
this.comment = comment;
}
public String getFileName() {
return fileName;
}
public String getMd5Hash() {
return md5Hash;
}
public String getSha1Hash() {
return sha1Hash;
}
public String getSha256Hash() {
return sha256Hash;
}
public String getComment() {
return comment;
}
}
| ForensicTools/Hotaru-475_2141-Edwards | sleuthkit-develop/bindings/java/src/org/sleuthkit/datamodel/HashEntry.java | Java | mit | 1,535 |
<!DOCTYPE html>
<html>
<head>
<!-- BEGIN META SECTION -->
<meta charset="utf-8">
<title>Themes Lab - Creative Laborator</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="" name="description" />
<meta content="themes-lab" name="author" />
<link rel="shortcut icon" href="../assets/global/images/favicon.png">
<!-- END META SECTION -->
<!-- BEGIN MANDATORY STYLE -->
<link href="../assets/global/css/style.css" rel="stylesheet">
<link href="../assets/global/css/ui.css" rel="stylesheet">
<!-- END MANDATORY STYLE -->
</head>
<body class="sidebar-light coming-soon coming-map">
<div class="map-container">
<div id="map"></div>
</div>
<div class="coming-container">
<!-- BEGIN LOGIN BOX -->
<!-- Social Links -->
<nav class="social-nav">
<ul>
<li><a href="#"><img src="../assets/global/images/social/icon-facebook.png" alt="facebook"/></a></li>
<li><a href="#"><img src="../assets/global/images/social/icon-twitter.png" alt="twitter"/></a></li>
<li><a href="#"><img src="../assets/global/images/social/icon-google.png" alt="google"/></a></li>
<li><a href="#"><img src="../assets/global/images/social/icon-dribbble.png" alt="dribbble"/></a></li>
<li><a href="#"><img src="../assets/global/images/social/icon-linkedin.png" alt="facebook"/></a></li>
<li><a href="#"><img src="../assets/global/images/social/icon-pinterest.png" alt="linkedin" /></a></li>
</ul>
</nav>
<!-- Site Logo -->
<div id="logo"><img src="../assets/global/images/logo/logo-white.png" alt="logo"></div>
<!-- Main Navigation -->
<nav class="main-nav">
<ul>
<li><a href="#home" class="active">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<!-- Home Page -->
<div class="row">
<div class="col-md-6">
<section class="content show" id="home">
<h1>Welcome</h1>
<h5>Our new site is coming soon!</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras vulputate arcu sit amet sem venenatis dictum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse eu massa sed orci interdum lobortis. Vivamus rutrum.</p>
<p><a href="#about">More info »</a></p>
</section>
<!-- About Page -->
<section class="content hide" id="about">
<h1>About</h1>
<h5>Here's a little about what we're up to.</h5>
<p>Nullam quis arcu a elit feugiat congue nec non orci. Pellentesque feugiat bibendum placerat. Nullam eu massa in ipsum varius laoreet. Ut tristique pretium egestas. Sed sed velit dolor. Nam rhoncus euismod lorem, id placerat ipsum placerat nec. Mauris ut eros a ligula tristique lacinia non blandit metus. Sed vitae velit lorem, et scelerisque diam.</p>
<p><a href="#">Follow our updates on Twitter</a></p>
</section>
<!-- Contact Page -->
<section class="content hide" id="contact">
<h1>Contact</h1>
<h5>Get in touch.</h5>
<p>Email: <a href="#">info@avenir.com</a><br />
Phone: 123.456.7890<br />
</p>
<p>123 East Main<br />
New York, NY 12345
</p>
</section>
</div>
<div class="col-md-6">
<div id="countdown">00 weeks 00 days <br> 00:00:00</div>
</div>
</div>
</div>
<div class="loader-overlay">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
<!-- BEGIN MANDATORY SCRIPTS -->
<script src="../assets/global/plugins/jquery/jquery-1.11.1.min.js"></script>
<script src="../assets/global/plugins/jquery/jquery-migrate-1.2.1.min.js"></script>
<script src="../assets/global/plugins/gsap/main-gsap.min.js"></script>
<script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js"></script>
<script src="../assets/global/plugins/countdown/jquery.countdown.min.js"></script>
<script src="//maps.google.com/maps/api/js?sensor=true"></script> <!-- Google Maps -->
<script src="https://google-maps-utility-library-v3.googlecode.com/svn-history/r391/trunk/markerwithlabel/src/markerwithlabel.js"></script>
<script src="../assets/global/plugins/google-maps/gmaps.min.js"></script> <!-- Google Maps Easy -->
<script src="../assets/global/plugins/backstretch/backstretch.min.js"></script>
<script src="../assets/global/js/pages/coming_soon.js"></script>
<script src="../assets/admin/layout3/js/layout.js"></script>
</body>
</html> | newset/theme | backend/normal/ThemeLab/layout3/page-coming-soon.html | HTML | mit | 5,564 |
<?php
namespace Oro\Bundle\ApiBundle\Processor\Subresource\DeleteRelationship;
use Oro\Bundle\ApiBundle\Config\Extra\EntityDefinitionConfigExtra;
use Oro\Bundle\ApiBundle\Config\Extra\FilterIdentifierFieldsConfigExtra;
use Oro\Bundle\ApiBundle\Processor\Subresource\SubresourceContext;
use Oro\Component\ChainProcessor\ContextInterface;
use Oro\Component\ChainProcessor\ProcessorInterface;
/**
* Sets an initial list of requests for configuration data.
* It is supposed that the list was initialized if
* the EntityDefinitionConfigExtra is already exist in the context.
*/
class InitializeConfigExtras implements ProcessorInterface
{
/**
* {@inheritdoc}
*/
public function process(ContextInterface $context)
{
/** @var SubresourceContext $context */
if ($context->hasConfigExtra(EntityDefinitionConfigExtra::NAME)) {
// config extras are already initialized
return;
}
$context->addConfigExtra(
new EntityDefinitionConfigExtra(
$context->getAction(),
$context->isCollection(),
$context->getParentClassName(),
$context->getAssociationName()
)
);
$context->addConfigExtra(new FilterIdentifierFieldsConfigExtra());
}
}
| orocrm/platform | src/Oro/Bundle/ApiBundle/Processor/Subresource/DeleteRelationship/InitializeConfigExtras.php | PHP | mit | 1,310 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .deployed_service_replica_info import DeployedServiceReplicaInfo
class DeployedStatefulServiceReplicaInfo(DeployedServiceReplicaInfo):
"""Information about a stateful service replica deployed on a node.
:param service_name: Full hierarchical name of the service in URI format
starting with `fabric:`.
:type service_name: str
:param service_type_name: Name of the service type as specified in the
service manifest.
:type service_type_name: str
:param service_manifest_name: The name of the service manifest in which
this service type is defined.
:type service_manifest_name: str
:param code_package_name: The name of the code package that hosts this
replica.
:type code_package_name: str
:param partition_id:
:type partition_id: str
:param replica_status: Possible values include: 'Invalid', 'InBuild',
'Standby', 'Ready', 'Down', 'Dropped'
:type replica_status: str
:param address: The last address returned by the replica in Open or
ChangeRole.
:type address: str
:param service_package_activation_id:
:type service_package_activation_id: str
:param ServiceKind: Polymorphic Discriminator
:type ServiceKind: str
:param replica_id: Id of the stateful service replica.
:type replica_id: str
:param replica_role: Possible values include: 'Unknown', 'None',
'Primary', 'IdleSecondary', 'ActiveSecondary'
:type replica_role: str
"""
_validation = {
'ServiceKind': {'required': True},
}
_attribute_map = {
'service_name': {'key': 'ServiceName', 'type': 'str'},
'service_type_name': {'key': 'ServiceTypeName', 'type': 'str'},
'service_manifest_name': {'key': 'ServiceManifestName', 'type': 'str'},
'code_package_name': {'key': 'CodePackageName', 'type': 'str'},
'partition_id': {'key': 'PartitionID', 'type': 'str'},
'replica_status': {'key': 'ReplicaStatus', 'type': 'str'},
'address': {'key': 'Address', 'type': 'str'},
'service_package_activation_id': {'key': 'ServicePackageActivationId', 'type': 'str'},
'ServiceKind': {'key': 'ServiceKind', 'type': 'str'},
'replica_id': {'key': 'ReplicaId', 'type': 'str'},
'replica_role': {'key': 'ReplicaRole', 'type': 'str'},
}
def __init__(self, service_name=None, service_type_name=None, service_manifest_name=None, code_package_name=None, partition_id=None, replica_status=None, address=None, service_package_activation_id=None, replica_id=None, replica_role=None):
super(DeployedStatefulServiceReplicaInfo, self).__init__(service_name=service_name, service_type_name=service_type_name, service_manifest_name=service_manifest_name, code_package_name=code_package_name, partition_id=partition_id, replica_status=replica_status, address=address, service_package_activation_id=service_package_activation_id)
self.replica_id = replica_id
self.replica_role = replica_role
self.ServiceKind = 'Stateful'
| v-iam/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/deployed_stateful_service_replica_info.py | Python | mit | 3,502 |
define(['durandal/app','lib/pagelayout', 'lib/prettify'], function (app, pagelayout, prettify) {
var activePage = ko.observable(),
hash = "",
oc;
return {
compositionComplete : function() {
var that = this;
oc = Stashy.OffCanvas("#sticky", { enableTouch : true });
pagelayout.offcanvasLayout(oc);
prettyPrint();
Stashy.Utils.ScrollTo('#' + that.hash);
},
activePage : activePage,
activate: function (page) {
var that = this;
if (page != undefined) {
that.hash = page;
Stashy.Utils.ScrollTo('#sticky #' + that.hash);
}
ga('send', 'pageview');
}
};
}); | yagopv/Stashy | docs/public/App/viewmodels/sticky/sticky.js | JavaScript | mit | 860 |
<?php
namespace DEPI\ProductosAcademicosBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use DEPI\ProductosAcademicosBundle\Entity\ProductosAcademicos;
class ProductosAcademicosFixtures extends AbstractFixture implements OrderedFixtureInterface
{
public function load(ObjectManager $manager)
{
$productosacademicos = array(
array('meta' => 'Integración de alumnos de licenciatura al proyecto'),
array('meta' => 'Participación de alumnos residentes'),
array('meta' => 'Artículos científicos en revista arbitrada'),
array('meta' => 'Artículos de divulgación'),
array('meta' => 'Memorias en extenso en congresos nacionales'),
array('meta' => 'Memorias en extenso en congresos internacionales'),
array('meta' => 'Tesis de licenciatura a desarrollar'),
array('meta' => 'Tesis de maestría a desarrollar'),
array('meta' => 'Tesis de doctorado a desarrollar'),
array('meta' => 'Libros'),
array('meta' => 'Capítulos de libros'),
array('meta' => 'Patentes'),
array('meta' => 'Prototipos'),
array('meta' => 'Paquetes tecnológicos'),
array('meta' => 'Informes técnicos a empresas o instituciones'),
array('meta' => 'Otros')
);
foreach ($productosacademicos as $productoacademico) {
$entidad = new ProductosAcademicos();
$entidad->setMeta($productoacademico['meta']);
$manager->persist($entidad);
}
$manager->flush();
}
public function getOrder()
{
return 2; // the order in which fixtures will be loaded
}
} | fralan123/DEPISite | src/DEPI/ProductosAcademicosBundle/DataFixtures/ORM/ProductosAcademicosFixtures.php | PHP | mit | 1,851 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("20. Variations of set")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("20. Variations of set")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8e7d171c-a383-4f23-a45f-2f6b098db1c1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| KaloyanchoSt/Telerik-Academy | 1. Programming C#/2. CSharp-Part-2/01. Arrays/20. VariationsOfSet/Properties/AssemblyInfo.cs | C# | mit | 1,436 |
body {
font-family: 'LucidaGrande', sans-serif;
background-color: rgb(72, 72, 72);
color: #fff;
}
a {
text-decoration: none;
color: rgba(255,255,255,0.35);
}
a:hover {
color: rgba(255,255,255,0.75);
}
p, li {
font-size: 10px;
}
ul li {
list-style-type: none;
}
h2 {
-webkit-margin-before: 30px;
-webkit-margin-after: 0px;
margin-left: -20px;
font-size: 14px;
}
h2.dontmove {
margin-left: 0px;
}
h3, h4 {
-webkit-margin-before: 20px;
margin-left: -20px;
-webkit-margin-after: 0px;
font-size: 12px;
}
div#column {
position: absolute;
left: 300px;
top: 0px;
width: 400px;
}
div#column img.logo {
width: 14px;
margin-left: -28px;
padding-right: 14px;
}
div#column img.screenshot {
width: 100%;
}
div#quickies {
position: fixed;
left: 40px;
top: 0px;
width: 200px;
}
div.sample {
position: relative;
display: inline-block;
height: 150px;
width: 300px;
border: 1px solid black;
margin: 20px;
padding: 20px;
background-color: #fff;
color: #000;
}
div.sample img {
position: absolute;
left: 20px;
right: 20px;
bottom: 20px;
}
div.sample button {
position: absolute;
right: 20px;
top: 20px;
border: none;
background-color: rgba( 72, 72, 72, 0.247059);
} | alex-r-bigelow/hanpuku | examples/style.css | CSS | mit | 1,334 |
# == Schema Information
#
# Table name: email_templates
#
# id :integer not null, primary key
# content :text
# hide_recipients :boolean
# status :integer
# subject :string
#
class EmailTemplate < ActiveRecord::Base
enum status: { default: 0, acceptance: 1, rejection: 2 }
validates_inclusion_of :status, in: statuses.keys
validates_inclusion_of :hide_recipients, in: [true, false]
validates_presence_of :subject, :content
scope :with_status, ->(status) { where(status: statuses[status]).to_a }
end
| hpi-swt2/workshop-portal | app/models/email_template.rb | Ruby | mit | 564 |
<?php
namespace Xiaoler\Blade\Concerns;
use Countable;
use Xiaoler\Blade\Support\Arr;
trait ManagesLoops
{
/**
* The stack of in-progress loops.
*
* @var array
*/
protected $loopsStack = [];
/**
* Add new loop to the stack.
*
* @param \Countable|array $data
* @return void
*/
public function addLoop($data)
{
$length = is_array($data) || $data instanceof Countable ? count($data) : null;
$parent = Arr::last($this->loopsStack);
$this->loopsStack[] = [
'iteration' => 0,
'index' => 0,
'remaining' => isset($length) ? $length : null,
'count' => $length,
'first' => true,
'last' => isset($length) ? $length == 1 : null,
'depth' => count($this->loopsStack) + 1,
'parent' => $parent ? (object) $parent : null,
];
}
/**
* Increment the top loop's indices.
*
* @return void
*/
public function incrementLoopIndices()
{
$loop = $this->loopsStack[$index = count($this->loopsStack) - 1];
$this->loopsStack[$index] = array_merge($this->loopsStack[$index], [
'iteration' => $loop['iteration'] + 1,
'index' => $loop['iteration'],
'first' => $loop['iteration'] == 0,
'remaining' => isset($loop['count']) ? $loop['remaining'] - 1 : null,
'last' => isset($loop['count']) ? $loop['iteration'] == $loop['count'] - 1 : null,
]);
}
/**
* Pop a loop from the top of the loop stack.
*
* @return void
*/
public function popLoop()
{
array_pop($this->loopsStack);
}
/**
* Get an instance of the last loop in the stack.
*
* @return \stdClass|null
*/
public function getLastLoop()
{
if ($last = Arr::last($this->loopsStack)) {
return (object) $last;
}
}
/**
* Get the entire loop stack.
*
* @return array
*/
public function getLoopStack()
{
return $this->loopsStack;
}
}
| XiaoLer/blade | src/Concerns/ManagesLoops.php | PHP | mit | 2,125 |
/*
to package
"eslint": "^1.7.3",
"eslint-config-rackt": "^1.1.0",
"eslint-plugin-react": "^3.6.3",
*/
require('es6-promise').polyfill(); // old node 0.10
var path = require('path');
var webpack = require('webpack');
module.exports = {
externals: {
jquery: "jQuery",
autobahn: "autobahn"
},
plugins: [
// new webpack.optimize.UglifyJsPlugin({minimize: true}),
new webpack.optimize.CommonsChunkPlugin(
/* chunkName= */'vendor',
/* filename= */'vendor.js'
),
/* new webpack.ProvidePlugin({ // If you use "_", underscore is automatically required
"$": "jquery",
"_": "underscore",
}) */
],
resolve: {
alias: {
"lodash": path.resolve("./node_modules/lodash"),
"react": path.resolve("./node_modules/react/react.js"),
"react-dom": path.resolve("./node_modules/react/lib/ReactDOM.js"),
"react-router": path.resolve("./node_modules/react-router"),
"reflux": path.resolve("./node_modules/reflux/src/index.js"),
"object-assign":path.resolve("./node_modules/object-assign/index.js"),
}
},
entry: {
// demoshop: [
// './demoshop/app.js'
// ],
// employee: [
// 'employee/views/contact.js'
// ],
navbar: [
'./navbar/app.js'
],
vendor: [
'lodash',
'react',
'react-dom',
'reflux',
'object-assign'
]
},
output: {
path: 'www/app',
filename: '[name].js',
publicPath: '/app/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-0', 'react']
}
},
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.jpg$/, loader: "file-loader" },
{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }
]
},
// devtool: 'source-map',
devtool: 'inline-source-map',
// scripts: {
// watch: "webpack --watch -d --display-error-details"
// }
};
| kalmyk/gyper-app | webpack.config.js | JavaScript | mit | 2,035 |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "core/strings/stringFunctions.h"
#include "console/console.h"
#include "console/simBase.h"
#include "console/engineAPI.h"
#include "platform/platformRedBook.h"
//------------------------------------------------------------------------------
// Class: RedBookDevice
//------------------------------------------------------------------------------
RedBookDevice::RedBookDevice()
{
mAcquired = false;
mDeviceName = 0;
}
RedBookDevice::~RedBookDevice()
{
delete [] mDeviceName;
}
//------------------------------------------------------------------------------
// Class: RedBook
//------------------------------------------------------------------------------
Vector<RedBookDevice *> RedBook::smDeviceList(__FILE__, __LINE__);
RedBookDevice * RedBook::smCurrentDevice;
char RedBook::smLastError[1024];
//------------------------------------------------------------------------------
void RedBook::init()
{
}
void RedBook::destroy()
{
close();
for( Vector<RedBookDevice*>::iterator i = smDeviceList.begin( ); i != smDeviceList.end( ); i++ ) {
delete *i;
}
smDeviceList.clear( );
}
//------------------------------------------------------------------------------
void RedBook::installDevice(RedBookDevice * device)
{
smDeviceList.push_back(device);
}
RedBookDevice * RedBook::getCurrentDevice()
{
return(smCurrentDevice);
}
U32 RedBook::getDeviceCount()
{
return(smDeviceList.size());
}
const char * RedBook::getDeviceName(U32 idx)
{
if(idx >= getDeviceCount())
{
setLastError("Invalid device index");
return("");
}
return(smDeviceList[idx]->mDeviceName);
}
void RedBook::setLastError(const char * error)
{
if(!error || dStrlen(error) >= sizeof(smLastError))
setLastError("Invalid error string passed");
else
dStrcpy(smLastError, error, 1024);
}
const char * RedBook::getLastError()
{
return(smLastError);
}
void RedBook::handleCallback(U32 type)
{
switch(type)
{
case PlayFinished:
Con::executef("RedBookCallback", "PlayFinished");
break;
}
}
//------------------------------------------------------------------------------
bool RedBook::open(const char * deviceName)
{
if(!deviceName)
{
setLastError("Invalid device name");
return(false);
}
for(U32 i = 0; i < smDeviceList.size(); i++)
if(!dStricmp(deviceName, smDeviceList[i]->mDeviceName))
return(open(smDeviceList[i]));
setLastError("Failed to find device");
return(false);
}
bool RedBook::open(RedBookDevice * device)
{
if(!device)
{
setLastError("Invalid device passed");
return(false);
}
close();
smCurrentDevice = device;
return(smCurrentDevice->open());
}
bool RedBook::close()
{
if(smCurrentDevice)
{
bool ret = smCurrentDevice->close();
smCurrentDevice = 0;
return(ret);
}
setLastError("No device is currently open");
return(false);
}
bool RedBook::play(U32 track)
{
if(!smCurrentDevice)
{
setLastError("No device is currently open");
return(false);
}
return(smCurrentDevice->play(track));
}
bool RedBook::stop()
{
if(!smCurrentDevice)
{
setLastError("No device is currently open");
return(false);
}
return(smCurrentDevice->stop());
}
bool RedBook::getTrackCount(U32 * trackCount)
{
if(!smCurrentDevice)
{
setLastError("No device is currently open");
return(false);
}
return(smCurrentDevice->getTrackCount(trackCount));
}
bool RedBook::getVolume(F32 * volume)
{
if(!smCurrentDevice)
{
setLastError("No device is currently open");
return(false);
}
return(smCurrentDevice->getVolume(volume));
}
bool RedBook::setVolume(F32 volume)
{
if(!smCurrentDevice)
{
setLastError("No device is currently open");
return(false);
}
return(smCurrentDevice->setVolume(volume));
}
//------------------------------------------------------------------------------
// console methods
//------------------------------------------------------------------------------
ConsoleFunctionGroupBegin( Redbook, "Control functions for Redbook audio (ie, CD audio).");
DefineEngineFunction( redbookOpen, bool, (const char * device), (""), "(string device=NULL)"
"@brief Deprecated\n\n"
"@internal")
{
if(String::compare(device,"")==0)
return(RedBook::open(RedBook::getDeviceName(0)));
else
return(RedBook::open(device));
}
DefineEngineFunction( redbookClose, bool, (), , "Close the current Redbook device."
"@brief Deprecated\n\n"
"@internal")
{
return(RedBook::close());
}
DefineEngineFunction( redbookPlay, bool, (S32 track), , "(int track) Play the selected track."
"@brief Deprecated\n\n"
"@internal")
{
return(RedBook::play(track));
}
DefineEngineFunction( redbookStop, bool, (), , "Stop playing."
"@brief Deprecated\n\n"
"@internal")
{
return(RedBook::stop());
}
DefineEngineFunction( redbookGetTrackCount, S32, (), , "Return the number of tracks."
"@brief Deprecated\n\n"
"@internal")
{
U32 trackCount;
if(!RedBook::getTrackCount(&trackCount))
return(0);
return(trackCount);
}
DefineEngineFunction( redbookGetVolume, F32, (), , "Get the volume."
"@brief Deprecated\n\n"
"@internal")
{
F32 vol;
if(!RedBook::getVolume(&vol))
return(0.f);
else
return(vol);
}
DefineEngineFunction( redbookSetVolume, bool, (F32 volume), , "(float volume) Set playback volume."
"@brief Deprecated\n\n"
"@internal")
{
return(RedBook::setVolume(volume));
}
DefineEngineFunction( redbookGetDeviceCount, S32, (), , "get the number of redbook devices."
"@brief Deprecated\n\n"
"@internal")
{
return(RedBook::getDeviceCount());
}
DefineEngineFunction( redbookGetDeviceName, const char *, (S32 index), , "(int index) Get name of specified Redbook device."
"@brief Deprecated\n\n"
"@internal")
{
return(RedBook::getDeviceName(index));
}
DefineEngineFunction( redbookGetLastError, const char *, (), , "Get a string explaining the last redbook error."
"@brief Deprecated\n\n"
"@internal")
{
return(RedBook::getLastError());
}
ConsoleFunctionGroupEnd( Redbook );
| Bloodknight/Torque3D | Engine/source/platform/platformRedBook.cpp | C++ | mit | 7,514 |
require('uppercase-core');
require('./DIST/NODE.js');
| Hanul/UPPERCASE | OLD/node_modules/uppercase-room/index.js | JavaScript | mit | 54 |
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <assert.h>
#include <direct.h>
#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "uv.h"
#include "internal.h"
#include "tlhelp32.h"
#include "psapi.h"
#include "iphlpapi.h"
/*
* Max title length; the only thing MSDN tells us about the maximum length
* of the console title is that it is smaller than 64K. However in practice
* it is much smaller, and there is no way to figure out what the exact length
* of the title is or can be, at least not on XP. To make it even more
* annoying, GetConsoleTitle failes when the buffer to be read into is bigger
* than the actual maximum length. So we make a conservative guess here;
* just don't put the novel you're writing in the title, unless the plot
* survives truncation.
*/
#define MAX_TITLE_LENGTH 8192
static char *process_title;
static uv_once_t uv_process_title_init_guard_ = UV_ONCE_INIT;
static CRITICAL_SECTION process_title_lock;
int uv_utf16_to_utf8(const wchar_t* utf16Buffer, size_t utf16Size,
char* utf8Buffer, size_t utf8Size) {
return WideCharToMultiByte(CP_UTF8,
0,
utf16Buffer,
utf16Size,
utf8Buffer,
utf8Size,
NULL,
NULL);
}
int uv_utf8_to_utf16(const char* utf8Buffer, wchar_t* utf16Buffer,
size_t utf16Size) {
return MultiByteToWideChar(CP_UTF8,
0,
utf8Buffer,
-1,
utf16Buffer,
utf16Size);
}
int uv_exepath(char* buffer, size_t* size) {
int retVal;
size_t utf16Size;
wchar_t* utf16Buffer;
if (!buffer || !size) {
return -1;
}
utf16Buffer = (wchar_t*)malloc(sizeof(wchar_t) * *size);
if (!utf16Buffer) {
retVal = -1;
goto done;
}
/* Get the path as UTF-16 */
utf16Size = GetModuleFileNameW(NULL, utf16Buffer, *size - 1);
if (utf16Size <= 0) {
/* uv__set_sys_error(loop, GetLastError()); */
retVal = -1;
goto done;
}
utf16Buffer[utf16Size] = L'\0';
/* Convert to UTF-8 */
*size = uv_utf16_to_utf8(utf16Buffer, utf16Size, buffer, *size);
if (!*size) {
/* uv__set_sys_error(loop, GetLastError()); */
retVal = -1;
goto done;
}
buffer[*size] = '\0';
retVal = 0;
done:
if (utf16Buffer) {
free(utf16Buffer);
}
return retVal;
}
uv_err_t uv_cwd(char* buffer, size_t size) {
uv_err_t err;
size_t utf8Size;
wchar_t* utf16Buffer = NULL;
if (!buffer || !size) {
err.code = UV_EINVAL;
goto done;
}
utf16Buffer = (wchar_t*)malloc(sizeof(wchar_t) * size);
if (!utf16Buffer) {
err.code = UV_ENOMEM;
goto done;
}
if (!_wgetcwd(utf16Buffer, size - 1)) {
err = uv__new_sys_error(_doserrno);
goto done;
}
utf16Buffer[size - 1] = L'\0';
/* Convert to UTF-8 */
utf8Size = uv_utf16_to_utf8(utf16Buffer, -1, buffer, size);
if (utf8Size == 0) {
err = uv__new_sys_error(GetLastError());
goto done;
}
buffer[utf8Size] = '\0';
err = uv_ok_;
done:
if (utf16Buffer) {
free(utf16Buffer);
}
return err;
}
uv_err_t uv_chdir(const char* dir) {
uv_err_t err;
wchar_t* utf16Buffer = NULL;
size_t utf16Size;
if (!dir) {
err.code = UV_EINVAL;
goto done;
}
utf16Size = uv_utf8_to_utf16(dir, NULL, 0);
if (!utf16Size) {
err = uv__new_sys_error(GetLastError());
goto done;
}
utf16Buffer = (wchar_t*)malloc(sizeof(wchar_t) * utf16Size);
if (!utf16Buffer) {
err.code = UV_ENOMEM;
goto done;
}
if (!uv_utf8_to_utf16(dir, utf16Buffer, utf16Size)) {
err = uv__new_sys_error(GetLastError());
goto done;
}
if (_wchdir(utf16Buffer) == -1) {
err = uv__new_sys_error(_doserrno);
goto done;
}
err = uv_ok_;
done:
if (utf16Buffer) {
free(utf16Buffer);
}
return err;
}
void uv_loadavg(double avg[3]) {
/* Can't be implemented */
avg[0] = avg[1] = avg[2] = 0;
}
uint64_t uv_get_free_memory(void) {
MEMORYSTATUSEX memory_status;
memory_status.dwLength = sizeof(memory_status);
if(!GlobalMemoryStatusEx(&memory_status))
{
return -1;
}
return (uint64_t)memory_status.ullAvailPhys;
}
uint64_t uv_get_total_memory(void) {
MEMORYSTATUSEX memory_status;
memory_status.dwLength = sizeof(memory_status);
if(!GlobalMemoryStatusEx(&memory_status))
{
return -1;
}
return (uint64_t)memory_status.ullTotalPhys;
}
int uv_parent_pid() {
int parent_pid = -1;
HANDLE handle;
PROCESSENTRY32 pe;
int current_pid = GetCurrentProcessId();
pe.dwSize = sizeof(PROCESSENTRY32);
handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (Process32First(handle, &pe)) {
do {
if (pe.th32ProcessID == current_pid) {
parent_pid = pe.th32ParentProcessID;
break;
}
} while( Process32Next(handle, &pe));
}
CloseHandle(handle);
return parent_pid;
}
char** uv_setup_args(int argc, char** argv) {
return argv;
}
static void uv_process_title_init(void) {
InitializeCriticalSection(&process_title_lock);
}
uv_err_t uv_set_process_title(const char* title) {
uv_err_t err;
int length;
wchar_t* title_w = NULL;
uv_once(&uv_process_title_init_guard_, uv_process_title_init);
/* Find out how big the buffer for the wide-char title must be */
length = uv_utf8_to_utf16(title, NULL, 0);
if (!length) {
err = uv__new_sys_error(GetLastError());
goto done;
}
/* Convert to wide-char string */
title_w = (wchar_t*)malloc(sizeof(wchar_t) * length);
if (!title_w) {
uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
}
length = uv_utf8_to_utf16(title, title_w, length);
if (!length) {
err = uv__new_sys_error(GetLastError());
goto done;
};
/* If the title must be truncated insert a \0 terminator there */
if (length > MAX_TITLE_LENGTH) {
title_w[MAX_TITLE_LENGTH - 1] = L'\0';
}
if (!SetConsoleTitleW(title_w)) {
err = uv__new_sys_error(GetLastError());
goto done;
}
EnterCriticalSection(&process_title_lock);
free(process_title);
process_title = strdup(title);
LeaveCriticalSection(&process_title_lock);
err = uv_ok_;
done:
free(title_w);
return err;
}
static int uv__get_process_title() {
wchar_t title_w[MAX_TITLE_LENGTH];
int length;
if (!GetConsoleTitleW(title_w, sizeof(title_w) / sizeof(WCHAR))) {
return -1;
}
/* Find out what the size of the buffer is that we need */
length = uv_utf16_to_utf8(title_w, -1, NULL, 0);
if (!length) {
return -1;
}
assert(!process_title);
process_title = (char*)malloc(length);
if (!process_title) {
uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
}
/* Do utf16 -> utf8 conversion here */
if (!uv_utf16_to_utf8(title_w, -1, process_title, length)) {
free(process_title);
return -1;
}
return 0;
}
uv_err_t uv_get_process_title(char* buffer, size_t size) {
uv_once(&uv_process_title_init_guard_, uv_process_title_init);
EnterCriticalSection(&process_title_lock);
/*
* If the process_title was never read before nor explicitly set,
* we must query it with getConsoleTitleW
*/
if (!process_title && uv__get_process_title() == -1) {
return uv__new_sys_error(GetLastError());
}
assert(process_title);
strncpy(buffer, process_title, size);
LeaveCriticalSection(&process_title_lock);
return uv_ok_;
}
uv_err_t uv_resident_set_memory(size_t* rss) {
HANDLE current_process;
PROCESS_MEMORY_COUNTERS pmc;
current_process = GetCurrentProcess();
if (!GetProcessMemoryInfo(current_process, &pmc, sizeof(pmc))) {
return uv__new_sys_error(GetLastError());
}
*rss = pmc.WorkingSetSize;
return uv_ok_;
}
uv_err_t uv_uptime(double* uptime) {
*uptime = (double)GetTickCount()/1000.0;
return uv_ok_;
}
uv_err_t uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
uv_err_t err;
char key[128];
HKEY processor_key = NULL;
DWORD cpu_speed = 0;
DWORD cpu_speed_length = sizeof(cpu_speed);
char cpu_brand[256];
DWORD cpu_brand_length = sizeof(cpu_brand);
SYSTEM_INFO system_info;
uv_cpu_info_t* cpu_info;
unsigned int i;
GetSystemInfo(&system_info);
*cpu_infos = (uv_cpu_info_t*)malloc(system_info.dwNumberOfProcessors *
sizeof(uv_cpu_info_t));
if (!(*cpu_infos)) {
uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
}
*count = 0;
for (i = 0; i < system_info.dwNumberOfProcessors; i++) {
_snprintf(key, sizeof(key), "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d", i);
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE,
&processor_key) != ERROR_SUCCESS) {
if (i == 0) {
err = uv__new_sys_error(GetLastError());
goto done;
}
continue;
}
if (RegQueryValueEx(processor_key, "~MHz", NULL, NULL,
(LPBYTE)&cpu_speed, &cpu_speed_length)
!= ERROR_SUCCESS) {
err = uv__new_sys_error(GetLastError());
goto done;
}
if (RegQueryValueEx(processor_key, "ProcessorNameString", NULL, NULL,
(LPBYTE)&cpu_brand, &cpu_brand_length)
!= ERROR_SUCCESS) {
err = uv__new_sys_error(GetLastError());
goto done;
}
RegCloseKey(processor_key);
processor_key = NULL;
cpu_info = &(*cpu_infos)[i];
/* $TODO: find times on windows */
cpu_info->cpu_times.user = 0;
cpu_info->cpu_times.nice = 0;
cpu_info->cpu_times.sys = 0;
cpu_info->cpu_times.idle = 0;
cpu_info->cpu_times.irq = 0;
cpu_info->model = strdup(cpu_brand);
cpu_info->speed = cpu_speed;
(*count)++;
}
err = uv_ok_;
done:
if (processor_key) {
RegCloseKey(processor_key);
}
if (err.code != UV_OK) {
free(*cpu_infos);
*cpu_infos = NULL;
*count = 0;
}
return err;
}
void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
int i;
for (i = 0; i < count; i++) {
free(cpu_infos[i].model);
}
free(cpu_infos);
}
uv_err_t uv_interface_addresses(uv_interface_address_t** addresses,
int* count) {
unsigned long size = 0;
IP_ADAPTER_ADDRESSES* adapter_addresses;
IP_ADAPTER_ADDRESSES* adapter_address;
uv_interface_address_t* address;
struct sockaddr* sock_addr;
int length;
char* name;
/* Use IP_ADAPTER_UNICAST_ADDRESS_XP to retain backwards compatibility */
/* with Windows XP */
IP_ADAPTER_UNICAST_ADDRESS_XP* unicast_address;
if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size)
!= ERROR_BUFFER_OVERFLOW) {
return uv__new_sys_error(GetLastError());
}
adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(size);
if (!adapter_addresses) {
uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
}
if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, adapter_addresses, &size)
!= ERROR_SUCCESS) {
return uv__new_sys_error(GetLastError());
}
/* Count the number of interfaces */
*count = 0;
for (adapter_address = adapter_addresses;
adapter_address != NULL;
adapter_address = adapter_address->Next) {
unicast_address = (IP_ADAPTER_UNICAST_ADDRESS_XP*)
adapter_address->FirstUnicastAddress;
while (unicast_address) {
(*count)++;
unicast_address = unicast_address->Next;
}
}
*addresses = (uv_interface_address_t*)
malloc(*count * sizeof(uv_interface_address_t));
if (!(*addresses)) {
uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
}
address = *addresses;
for (adapter_address = adapter_addresses;
adapter_address != NULL;
adapter_address = adapter_address->Next) {
name = NULL;
unicast_address = (IP_ADAPTER_UNICAST_ADDRESS_XP*)
adapter_address->FirstUnicastAddress;
while (unicast_address) {
sock_addr = unicast_address->Address.lpSockaddr;
if (sock_addr->sa_family == AF_INET6) {
address->address.address6 = *((struct sockaddr_in6 *)sock_addr);
} else {
address->address.address4 = *((struct sockaddr_in *)sock_addr);
}
address->is_internal =
adapter_address->IfType == IF_TYPE_SOFTWARE_LOOPBACK ? 1 : 0;
if (!name) {
/* Convert FriendlyName to utf8 */
length = uv_utf16_to_utf8(adapter_address->FriendlyName, -1, NULL, 0);
if (length) {
name = (char*)malloc(length);
if (!name) {
uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
}
if (!uv_utf16_to_utf8(adapter_address->FriendlyName, -1, name,
length)) {
free(name);
name = NULL;
}
}
}
assert(name);
address->name = name;
unicast_address = unicast_address->Next;
address++;
}
}
free(adapter_addresses);
return uv_ok_;
}
void uv_free_interface_addresses(uv_interface_address_t* addresses,
int count) {
int i;
char* freed_name = NULL;
for (i = 0; i < count; i++) {
if (freed_name != addresses[i].name) {
freed_name = addresses[i].name;
free(freed_name);
}
}
free(addresses);
}
void uv_filetime_to_time_t(FILETIME* file_time, time_t* stat_time) {
FILETIME local_time;
SYSTEMTIME system_time;
struct tm time;
if ((file_time->dwLowDateTime || file_time->dwHighDateTime) &&
FileTimeToLocalFileTime(file_time, &local_time) &&
FileTimeToSystemTime(&local_time, &system_time)) {
time.tm_year = system_time.wYear - 1900;
time.tm_mon = system_time.wMonth - 1;
time.tm_mday = system_time.wDay;
time.tm_hour = system_time.wHour;
time.tm_min = system_time.wMinute;
time.tm_sec = system_time.wSecond;
time.tm_isdst = -1;
*stat_time = mktime(&time);
} else {
*stat_time = 0;
}
}
| a-bx/brayatan | libuv/src/win/util.c | C | mit | 14,991 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.