text
stringlengths 2
99.7k
| meta
dict |
|---|---|
--TEST--
\PHPUnit\Framework\MockObject\Generator::generateClassFromWsdl('3530.wsdl', 'Test')
--SKIPIF--
<?php declare(strict_types=1);
if (!extension_loaded('soap')) echo 'skip: SOAP extension is required';
--FILE--
<?php declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
$generator = new \PHPUnit\Framework\MockObject\Generator;
print $generator->generateClassFromWsdl(
__DIR__ . '/../../../_files/3530.wsdl',
'Test'
);
--EXPECTF--
class Test extends \SoapClient
{
public function __construct($wsdl, array $options)
{
parent::__construct('%s/3530.wsdl', $options);
}
public function Contact_Information($Contact_Id)
{
}
}
|
{
"pile_set_name": "Github"
}
|
<% content_for :title_bar do %>
<span class="navbar-brand"><%= t('.resend_confirmation_instructions') %></span>
<% end %>
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-4 col-md-offset-3 col-lg-offset-4">
<div class="auth-wrapper">
<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post, class: 'form-horizontal' }) do |f| %>
<%= devise_error_messages! %>
<div class="auth-form-group">
<%= f.label :email, class: 'sr-only' %>
<%= f.email_field :email, autofocus: true, value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email), placeholder: true, class: 'form-control auth-form-control' %>
</div>
<div class="actions clearfix">
<%= f.submit t('.resend_confirmation_instructions'), class: 'btn btn-primary btn-block auth-button-submit' %>
</div>
<% end %>
</div>
</div>
<div class="clearfix"></div>
<div class="col-sm-12 col-md-6 col-lg-4 col-md-offset-3 col-lg-offset-4">
<%= render 'devise/shared/links' %>
</div>
</div>
|
{
"pile_set_name": "Github"
}
|
{
"name": "CRBoxInputView",
"version": "0.1.7",
"summary": "You can use this widget for verify code, password input or phone number input.",
"description": "TODO: You can use this widget for verify code, password input or phone number input.",
"homepage": "https://github.com/CRAnimation/CRBoxInputView",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"BearRan": "648070256@qq.com"
},
"source": {
"git": "https://github.com/CRAnimation/CRBoxInputView.git",
"tag": "0.1.7"
},
"platforms": {
"ios": "8.0"
},
"source_files": "PodCode/Classes/**/*",
"dependencies": {
"Masonry": [
]
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Loads a Wavefront .mtl file specifying materials
*
* @author angelxuanchang
*/
THREE.MTLLoader = function( baseUrl, options, crossOrigin ) {
this.baseUrl = baseUrl;
this.options = options;
this.crossOrigin = crossOrigin;
};
THREE.MTLLoader.prototype = {
constructor: THREE.MTLLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new THREE.XHRLoader();
loader.setCrossOrigin( this.crossOrigin );
loader.load( url, function ( text ) {
onLoad( scope.parse( text ) );
}, onProgress, onError );
},
/**
* Parses loaded MTL file
* @param text - Content of MTL file
* @return {THREE.MTLLoader.MaterialCreator}
*/
parse: function ( text ) {
var lines = text.split( "\n" );
var info = {};
var delimiter_pattern = /\s+/;
var materialsInfo = {};
for ( var i = 0; i < lines.length; i ++ ) {
var line = lines[ i ];
line = line.trim();
if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
// Blank line or comment ignore
continue;
}
var pos = line.indexOf( ' ' );
var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
key = key.toLowerCase();
var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : "";
value = value.trim();
if ( key === "newmtl" ) {
// New material
info = { name: value };
materialsInfo[ value ] = info;
} else if ( info ) {
if ( key === "ka" || key === "kd" || key === "ks" ) {
var ss = value.split( delimiter_pattern, 3 );
info[ key ] = [ parseFloat( ss[0] ), parseFloat( ss[1] ), parseFloat( ss[2] ) ];
} else {
info[ key ] = value;
}
}
}
var materialCreator = new THREE.MTLLoader.MaterialCreator( this.baseUrl, this.options );
materialCreator.setMaterials( materialsInfo );
return materialCreator;
}
};
/**
* Create a new THREE-MTLLoader.MaterialCreator
* @param baseUrl - Url relative to which textures are loaded
* @param options - Set of options on how to construct the materials
* side: Which side to apply the material
* THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
* wrap: What type of wrapping to apply for textures
* THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
* normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
* Default: false, assumed to be already normalized
* ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
* Default: false
* invertTransparency: If transparency need to be inverted (inversion is needed if d = 0 is fully opaque)
* Default: false (d = 1 is fully opaque)
* @constructor
*/
THREE.MTLLoader.MaterialCreator = function( baseUrl, options ) {
this.baseUrl = baseUrl;
this.options = options;
this.materialsInfo = {};
this.materials = {};
this.materialsArray = [];
this.nameLookup = {};
this.side = ( this.options && this.options.side )? this.options.side: THREE.FrontSide;
this.wrap = ( this.options && this.options.wrap )? this.options.wrap: THREE.RepeatWrapping;
};
THREE.MTLLoader.MaterialCreator.prototype = {
constructor: THREE.MTLLoader.MaterialCreator,
setMaterials: function( materialsInfo ) {
this.materialsInfo = this.convert( materialsInfo );
this.materials = {};
this.materialsArray = [];
this.nameLookup = {};
},
convert: function( materialsInfo ) {
if ( !this.options ) return materialsInfo;
var converted = {};
for ( var mn in materialsInfo ) {
// Convert materials info into normalized form based on options
var mat = materialsInfo[ mn ];
var covmat = {};
converted[ mn ] = covmat;
for ( var prop in mat ) {
var save = true;
var value = mat[ prop ];
var lprop = prop.toLowerCase();
switch ( lprop ) {
case 'kd':
case 'ka':
case 'ks':
// Diffuse color (color under white light) using RGB values
if ( this.options && this.options.normalizeRGB ) {
value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
}
if ( this.options && this.options.ignoreZeroRGBs ) {
if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 1 ] === 0 ) {
// ignore
save = false;
}
}
break;
case 'd':
// According to MTL format (http://paulbourke.net/dataformats/mtl/):
// d is dissolve for current material
// factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent)
if ( this.options && this.options.invertTransparency ) {
value = 1 - value;
}
break;
default:
break;
}
if ( save ) {
covmat[ lprop ] = value;
}
}
}
return converted;
},
preload: function () {
for ( var mn in this.materialsInfo ) {
this.create( mn );
}
},
getIndex: function( materialName ) {
return this.nameLookup[ materialName ];
},
getAsArray: function() {
var index = 0;
for ( var mn in this.materialsInfo ) {
this.materialsArray[ index ] = this.create( mn );
this.nameLookup[ mn ] = index;
index ++;
}
return this.materialsArray;
},
create: function ( materialName ) {
if ( this.materials[ materialName ] === undefined ) {
this.createMaterial_( materialName );
}
return this.materials[ materialName ];
},
createMaterial_: function ( materialName ) {
// Create material
var mat = this.materialsInfo[ materialName ];
var params = {
name: materialName,
side: this.side
};
for ( var prop in mat ) {
var value = mat[ prop ];
switch ( prop.toLowerCase() ) {
// Ns is material specular exponent
case 'kd':
// Diffuse color (color under white light) using RGB values
params[ 'diffuse' ] = new THREE.Color().fromArray( value );
break;
case 'ka':
// Ambient color (color under shadow) using RGB values
params[ 'ambient' ] = new THREE.Color().fromArray( value );
break;
case 'ks':
// Specular color (color when light is reflected from shiny surface) using RGB values
params[ 'specular' ] = new THREE.Color().fromArray( value );
break;
case 'map_kd':
// Diffuse texture map
params[ 'map' ] = this.loadTexture( this.baseUrl + value );
params[ 'map' ].wrapS = this.wrap;
params[ 'map' ].wrapT = this.wrap;
break;
case 'ns':
// The specular exponent (defines the focus of the specular highlight)
// A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
params['shininess'] = value;
break;
case 'd':
// According to MTL format (http://paulbourke.net/dataformats/mtl/):
// d is dissolve for current material
// factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent)
if ( value < 1 ) {
params['transparent'] = true;
params['opacity'] = value;
}
break;
default:
break;
}
}
if ( params[ 'diffuse' ] ) {
if ( !params[ 'ambient' ]) params[ 'ambient' ] = params[ 'diffuse' ];
params[ 'color' ] = params[ 'diffuse' ];
}
this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
return this.materials[ materialName ];
},
loadTexture: function ( url, mapping, onLoad, onError ) {
var texture;
var loader = THREE.Loader.Handlers.get( url );
if ( loader !== null ) {
texture = loader.load( url, onLoad );
} else {
texture = new THREE.Texture();
loader = new THREE.ImageLoader();
loader.crossOrigin = this.crossOrigin;
loader.load( url, function ( image ) {
texture.image = THREE.MTLLoader.ensurePowerOfTwo_( image );
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
} );
}
texture.mapping = mapping;
return texture;
}
};
THREE.MTLLoader.ensurePowerOfTwo_ = function ( image ) {
if ( ! THREE.Math.isPowerOfTwo( image.width ) || ! THREE.Math.isPowerOfTwo( image.height ) ) {
var canvas = document.createElement( "canvas" );
canvas.width = THREE.MTLLoader.nextHighestPowerOfTwo_( image.width );
canvas.height = THREE.MTLLoader.nextHighestPowerOfTwo_( image.height );
var ctx = canvas.getContext("2d");
ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
return canvas;
}
return image;
};
THREE.MTLLoader.nextHighestPowerOfTwo_ = function( x ) {
--x;
for ( var i = 1; i < 32; i <<= 1 ) {
x = x | x >> i;
}
return x + 1;
};
THREE.EventDispatcher.prototype.apply( THREE.MTLLoader.prototype );
|
{
"pile_set_name": "Github"
}
|
# 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 ._application_gateways_operations import ApplicationGatewaysOperations
from ._application_security_groups_operations import ApplicationSecurityGroupsOperations
from ._network_management_client_operations import NetworkManagementClientOperationsMixin
from ._available_endpoint_services_operations import AvailableEndpointServicesOperations
from ._express_route_circuit_authorizations_operations import ExpressRouteCircuitAuthorizationsOperations
from ._express_route_circuit_peerings_operations import ExpressRouteCircuitPeeringsOperations
from ._express_route_circuits_operations import ExpressRouteCircuitsOperations
from ._express_route_service_providers_operations import ExpressRouteServiceProvidersOperations
from ._load_balancers_operations import LoadBalancersOperations
from ._load_balancer_backend_address_pools_operations import LoadBalancerBackendAddressPoolsOperations
from ._load_balancer_frontend_ip_configurations_operations import LoadBalancerFrontendIPConfigurationsOperations
from ._inbound_nat_rules_operations import InboundNatRulesOperations
from ._load_balancer_load_balancing_rules_operations import LoadBalancerLoadBalancingRulesOperations
from ._load_balancer_network_interfaces_operations import LoadBalancerNetworkInterfacesOperations
from ._load_balancer_probes_operations import LoadBalancerProbesOperations
from ._network_interfaces_operations import NetworkInterfacesOperations
from ._network_interface_ip_configurations_operations import NetworkInterfaceIPConfigurationsOperations
from ._network_interface_load_balancers_operations import NetworkInterfaceLoadBalancersOperations
from ._network_security_groups_operations import NetworkSecurityGroupsOperations
from ._security_rules_operations import SecurityRulesOperations
from ._default_security_rules_operations import DefaultSecurityRulesOperations
from ._network_watchers_operations import NetworkWatchersOperations
from ._packet_captures_operations import PacketCapturesOperations
from ._connection_monitors_operations import ConnectionMonitorsOperations
from ._operations import Operations
from ._public_ip_addresses_operations import PublicIPAddressesOperations
from ._route_filters_operations import RouteFiltersOperations
from ._route_filter_rules_operations import RouteFilterRulesOperations
from ._route_tables_operations import RouteTablesOperations
from ._routes_operations import RoutesOperations
from ._bgp_service_communities_operations import BgpServiceCommunitiesOperations
from ._usages_operations import UsagesOperations
from ._virtual_networks_operations import VirtualNetworksOperations
from ._subnets_operations import SubnetsOperations
from ._virtual_network_peerings_operations import VirtualNetworkPeeringsOperations
from ._virtual_network_gateways_operations import VirtualNetworkGatewaysOperations
from ._virtual_network_gateway_connections_operations import VirtualNetworkGatewayConnectionsOperations
from ._local_network_gateways_operations import LocalNetworkGatewaysOperations
__all__ = [
'ApplicationGatewaysOperations',
'ApplicationSecurityGroupsOperations',
'NetworkManagementClientOperationsMixin',
'AvailableEndpointServicesOperations',
'ExpressRouteCircuitAuthorizationsOperations',
'ExpressRouteCircuitPeeringsOperations',
'ExpressRouteCircuitsOperations',
'ExpressRouteServiceProvidersOperations',
'LoadBalancersOperations',
'LoadBalancerBackendAddressPoolsOperations',
'LoadBalancerFrontendIPConfigurationsOperations',
'InboundNatRulesOperations',
'LoadBalancerLoadBalancingRulesOperations',
'LoadBalancerNetworkInterfacesOperations',
'LoadBalancerProbesOperations',
'NetworkInterfacesOperations',
'NetworkInterfaceIPConfigurationsOperations',
'NetworkInterfaceLoadBalancersOperations',
'NetworkSecurityGroupsOperations',
'SecurityRulesOperations',
'DefaultSecurityRulesOperations',
'NetworkWatchersOperations',
'PacketCapturesOperations',
'ConnectionMonitorsOperations',
'Operations',
'PublicIPAddressesOperations',
'RouteFiltersOperations',
'RouteFilterRulesOperations',
'RouteTablesOperations',
'RoutesOperations',
'BgpServiceCommunitiesOperations',
'UsagesOperations',
'VirtualNetworksOperations',
'SubnetsOperations',
'VirtualNetworkPeeringsOperations',
'VirtualNetworkGatewaysOperations',
'VirtualNetworkGatewayConnectionsOperations',
'LocalNetworkGatewaysOperations',
]
|
{
"pile_set_name": "Github"
}
|
module.exports = {
sourceCode: "echo\"ciao\"'mondo'",
result: {
type: "Script",
commands: [
{
type: "SimpleCommand",
name: {
text: "echociaomondo",
type: "Word"
}
}
]
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2014 The Prometheus Authors
// 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 prometheus_test
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
)
var (
// apiRequestDuration tracks the duration separate for each HTTP status
// class (1xx, 2xx, ...). This creates a fair amount of time series on
// the Prometheus server. Usually, you would track the duration of
// serving HTTP request without partitioning by outcome. Do something
// like this only if needed. Also note how only status classes are
// tracked, not every single status code. The latter would create an
// even larger amount of time series. Request counters partitioned by
// status code are usually OK as each counter only creates one time
// series. Histograms are way more expensive, so partition with care and
// only where you really need separate latency tracking. Partitioning by
// status class is only an example. In concrete cases, other partitions
// might make more sense.
apiRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "api_request_duration_seconds",
Help: "Histogram for the request duration of the public API, partitioned by status class.",
Buckets: prometheus.ExponentialBuckets(0.1, 1.5, 5),
},
[]string{"status_class"},
)
)
func handler(w http.ResponseWriter, r *http.Request) {
status := http.StatusOK
// The ObserverFunc gets called by the deferred ObserveDuration and
// decides wich Histogram's Observe method is called.
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
switch {
case status >= 500: // Server error.
apiRequestDuration.WithLabelValues("5xx").Observe(v)
case status >= 400: // Client error.
apiRequestDuration.WithLabelValues("4xx").Observe(v)
case status >= 300: // Redirection.
apiRequestDuration.WithLabelValues("3xx").Observe(v)
case status >= 200: // Success.
apiRequestDuration.WithLabelValues("2xx").Observe(v)
default: // Informational.
apiRequestDuration.WithLabelValues("1xx").Observe(v)
}
}))
defer timer.ObserveDuration()
// Handle the request. Set status accordingly.
// ...
}
func ExampleTimer_complex() {
http.HandleFunc("/api", handler)
}
|
{
"pile_set_name": "Github"
}
|
// Npgsql.NpgsqlReadyState.cs
//
// Author:
// Dave Joyner <d4ljoyn@yahoo.com>
//
// Copyright (C) 2002 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
using System.Collections.Generic;
using System.IO;
namespace Revenj.DatabasePersistence.Postgres.Npgsql
{
internal sealed class NpgsqlReadyState : NpgsqlState
{
public static readonly NpgsqlReadyState Instance = new NpgsqlReadyState();
// Flush and Sync messages. It doesn't need to be created every time it is called.
private static readonly NpgsqlFlush _flushMessage = new NpgsqlFlush();
private static readonly NpgsqlSync _syncMessage = new NpgsqlSync();
private NpgsqlReadyState() : base() { }
public override IEnumerable<IServerResponseObject> QueryEnum(NpgsqlConnector context, NpgsqlCommand command)
{
// Send the query request to backend.
NpgsqlQuery.Send(command, context.Stream);
context.Stream.Flush();
return ProcessBackendResponsesEnum(context, false);
}
public override void Parse(NpgsqlConnector context, NpgsqlParse parse)
{
Stream stream = context.Stream;
parse.WriteToStream(stream);
//stream.Flush();
}
public override IEnumerable<IServerResponseObject> SyncEnum(NpgsqlConnector context)
{
_syncMessage.WriteToStream(context.Stream);
context.Stream.Flush();
return ProcessBackendResponsesEnum(context, false);
}
public override void Flush(NpgsqlConnector context)
{
_flushMessage.WriteToStream(context.Stream);
context.Stream.Flush();
ProcessBackendResponses(context);
}
public override void Bind(NpgsqlConnector context, NpgsqlBind bind)
{
Stream stream = context.Stream;
bind.WriteToStream(stream);
//stream.Flush();
}
public override void Describe(NpgsqlConnector context, NpgsqlDescribe describe)
{
describe.WriteToStream(context.Stream);
//context.Stream.Flush();
}
public override void Execute(NpgsqlConnector context, NpgsqlExecute execute)
{
Stream stream = context.Stream;
NpgsqlDescribe.Send('P', execute.PortalName, stream);
execute.WriteToStream(stream);
//stream.Flush();
Sync(context);
}
public override IEnumerable<IServerResponseObject> ExecuteEnum(NpgsqlConnector context, NpgsqlExecute execute)
{
Stream stream = context.Stream;
NpgsqlDescribe.Send('P', execute.PortalName, stream);
execute.WriteToStream(stream);
//stream.Flush();
return SyncEnum(context);
}
public override void Close(NpgsqlConnector context)
{
Stream stream = context.Stream;
try
{
stream.WriteByte((byte)FrontEndMessageCode.Termination);
PGUtil.WriteInt32(stream, 4);
stream.Flush();
}
catch
{
//Error writting termination message to stream, nothing we can do.
}
try { stream.Close(); }
catch { }
context.Stream = null;
ChangeState(context, NpgsqlClosedState.Instance);
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="HardcodedText"
>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="@dimen/main_collapsing_toolbar_height"
app:elevation="16dp"
>
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"
app:titleEnabled="false"
>
<FrameLayout
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:layout_collapseMode="parallax"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:includeFontPadding="false"
android:text="Aesthetic + Material Components"
android:textAppearance="?attr/textAppearanceHeadline6"
android:textColor="?android:textColorPrimaryInverse"
/>
</FrameLayout>
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_collapseMode="pin"
/>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<include layout="@layout/main_content"/>
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:elevation="16dp"
app:backgroundTint="@color/text_color_primary"
app:navigationIcon="@drawable/ic_drawer_menu_24px"
tools:ignore="BottomAppBar,UnusedAttribute"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_anchor="@id/bar"
app:srcCompat="@drawable/ic_add_24px"
/>
<FrameLayout
android:id="@+id/bottom_drawer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="16dp"
app:behavior_hideable="true"
app:layout_behavior="@string/bottom_sheet_behavior"
tools:ignore="UnusedAttribute"
>
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/demo_primary"
/>
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
|
{
"pile_set_name": "Github"
}
|
@keyframes flipInX {
from {
transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
animation-timing-function: ease-in;
opacity: 0;
}
40% {
transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
animation-timing-function: ease-in;
}
60% {
transform: perspective(400px) rotate3d(1, 0, 0, 10deg);
opacity: 1;
}
80% {
transform: perspective(400px) rotate3d(1, 0, 0, -5deg);
}
to {
transform: perspective(400px);
}
}
.flipInX {
backface-visibility: visible !important;
animation-name: flipInX;
}
|
{
"pile_set_name": "Github"
}
|
// Package S016 defines an Analyzer that checks for
// Schema including Set without TypeSet
package S016
import (
"go/ast"
"golang.org/x/tools/go/analysis"
"github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema"
"github.com/bflad/tfproviderlint/passes/commentignore"
"github.com/bflad/tfproviderlint/passes/helper/schema/schemainfo"
)
const Doc = `check for Schema including Set without TypeSet
The S016 analyzer reports cases of schema including Set without TypeSet,
which will fail schema validation.`
const analyzerName = "S016"
var Analyzer = &analysis.Analyzer{
Name: analyzerName,
Doc: Doc,
Requires: []*analysis.Analyzer{
schemainfo.Analyzer,
commentignore.Analyzer,
},
Run: run,
}
func run(pass *analysis.Pass) (interface{}, error) {
ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer)
schemaInfos := pass.ResultOf[schemainfo.Analyzer].([]*schema.SchemaInfo)
for _, schemaInfo := range schemaInfos {
if ignorer.ShouldIgnore(analyzerName, schemaInfo.AstCompositeLit) {
continue
}
if !schemaInfo.DeclaresField(schema.SchemaFieldSet) {
continue
}
if schemaInfo.IsType(schema.SchemaValueTypeSet) {
continue
}
switch t := schemaInfo.AstCompositeLit.Type.(type) {
default:
pass.Reportf(schemaInfo.AstCompositeLit.Lbrace, "%s: schema Set should only be included for TypeSet", analyzerName)
case *ast.SelectorExpr:
pass.Reportf(t.Sel.Pos(), "%s: schema Set should only be included for TypeSet", analyzerName)
}
}
return nil, nil
}
|
{
"pile_set_name": "Github"
}
|
// NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef DIFF_TOOL_H
#define DIFF_TOOL_H
#include "i18n.h"
namespace STRING_MANAGER
{
const ucstring nl("\n");
struct TStringInfo
{
std::string Identifier;
ucstring Text;
ucstring Text2;
mutable ucstring Comments;
uint64 HashValue;
};
struct TStringDiffContext
{
typedef std::vector<TStringInfo>::iterator iterator;
const std::vector<TStringInfo> &Addition;
std::vector<TStringInfo> &Reference;
std::vector<TStringInfo> &Diff;
TStringDiffContext(const std::vector<TStringInfo> &addition, std::vector<TStringInfo> &reference, std::vector<TStringInfo> &diff)
: Addition(addition),
Reference(reference),
Diff(diff)
{
}
};
struct TClause
{
std::string Identifier;
ucstring Conditions;
ucstring Text;
ucstring Comments;
uint64 HashValue;
};
struct TPhrase
{
std::string Identifier;
ucstring Parameters;
mutable ucstring Comments;
std::vector<TClause> Clauses;
uint64 HashValue;
};
struct TPhraseDiffContext
{
typedef std::vector<TPhrase>::iterator iterator;
const std::vector<TPhrase> &Addition;
std::vector<TPhrase> &Reference;
std::vector<TPhrase> &Diff;
TPhraseDiffContext(const std::vector<TPhrase> &addition, std::vector<TPhrase> &reference, std::vector<TPhrase> &diff)
: Addition(addition),
Reference(reference),
Diff(diff)
{
}
};
struct TWorksheet
{
typedef std::vector<ucstring> TRow;
typedef std::vector<TRow> TData;
TData Data;
uint ColCount;
TWorksheet()
: ColCount(0)
{
}
std::vector<TRow>::iterator begin()
{
return Data.begin();
}
std::vector<TRow>::iterator end()
{
return Data.end();
}
std::vector<TRow>::const_iterator begin() const
{
return Data.begin();
}
std::vector<TRow>::const_iterator end() const
{
return Data.end();
}
void push_back(const TRow &row)
{
Data.push_back(row);
}
std::vector<TRow>::iterator insert(std::vector<TRow>::iterator pos, const TRow &value)
{
return Data.insert(pos, value);
}
std::vector<TRow>::iterator erase(std::vector<TRow>::iterator it)
{
return Data.erase(it);
}
TRow &back()
{
return Data.back();
}
TRow &operator [] (uint index)
{
return Data[index];
}
const TRow &operator [] (uint index) const
{
return Data[index];
}
uint size() const
{
return (uint)Data.size();
}
void insertColumn(uint colIndex)
{
nlassert(colIndex <= ColCount);
for (uint i=0; i<Data.size(); ++i)
{
// insert a default value.
Data[i].insert(Data[i].begin()+colIndex, ucstring());
}
ColCount++;
}
void copyColumn(uint srcColIndex, uint dstColIndex)
{
nlassert(srcColIndex < ColCount);
nlassert(dstColIndex < ColCount);
for (uint i=0; i<Data.size(); ++i)
{
Data[i][dstColIndex] = Data[i][srcColIndex];
}
}
void eraseColumn(uint colIndex)
{
nlassertex(colIndex < ColCount, ("TWorksheet::eraseColumn : bad column index: colIndex(%u) is not less than ColCount(%u)", colIndex, ColCount));
for (uint i=0; i<Data.size(); ++i)
{
// insert a default value.
Data[i].erase(Data[i].begin()+colIndex);
}
ColCount--;
}
void moveColumn(uint oldColIndex, uint newColIndex)
{
nlassert(oldColIndex < ColCount);
nlassert(newColIndex < ColCount);
if (oldColIndex == newColIndex)
return;
if (newColIndex > oldColIndex)
{
// the dst is after the src, no problem with index
insertColumn(newColIndex);
copyColumn(oldColIndex, newColIndex);
eraseColumn(oldColIndex);
}
else
{
// the dst is before the src, need to take the column insertion into account
insertColumn(newColIndex);
copyColumn(oldColIndex+1, newColIndex);
eraseColumn(oldColIndex+1);
}
}
void setColCount(uint count)
{
if (count != ColCount)
{
for (uint i=0; i<Data.size(); ++i)
Data[i].resize(count);
}
ColCount = count;
}
bool findId(uint& colIndex)
{
if (Data.empty())
return false;
for (TWorksheet::TRow::iterator it=Data[0].begin(); it!=Data[0].end(); ++it)
{
std::string columnTitle = (*it).toString();
if ( ! columnTitle.empty() )
{
// Return the first column for which the title does not begin with '*'
if ( columnTitle[0] != '*' )
{
colIndex = (uint)(it - Data[0].begin());
return true;
}
}
}
return false;
}
bool findCol(const ucstring &colName, uint &colIndex)
{
if (Data.empty())
return false;
TWorksheet::TRow::iterator it = std::find(Data[0].begin(), Data[0].end(), colName);
if (it == Data[0].end())
return false;
colIndex = (uint)(it - Data[0].begin());
return true;
}
void insertRow(uint rowIndex, const TRow &row)
{
nlassertex(rowIndex <= Data.size(), ("TWorksheet::insertRow: bad row index: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size()-1));
nlassertex(row.size() == ColCount, ("TWorksheet::insertRow: bad column count : inserted row size(%u) is invalid (must be %u) at rowIndex(%u)", row.size(), ColCount, rowIndex));
Data.insert(Data.begin()+rowIndex, row);
}
// resize the rows
void resize(uint numRows)
{
uint oldSize= (uint)Data.size();
Data.resize(numRows);
// alloc good Column count for new lines
for(uint i= oldSize;i<Data.size();i++)
Data[i].resize(ColCount);
}
bool findRow(uint colIndex, const ucstring &colValue, uint &rowIndex)
{
nlassertex(colIndex < ColCount, ("TWorksheet::findRow: bad column index: colIndex(%u) is not less than ColCount(%u)", colIndex, ColCount));
TData::iterator first(Data.begin()), last(Data.end());
for (; first != last; ++first)
{
if (first->operator[](colIndex) == colValue)
{
rowIndex = (uint)(first - Data.begin());
return true;
}
}
return false;
}
void setData(uint rowIndex, uint colIndex, const ucstring &value)
{
nlassertex(rowIndex < Data.size(), ("TWorksheet::setData: bad row index: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size()));
nlassertex(colIndex < ColCount, ("TWorksheet::setData: bad column index: colIndex(%u) is not less than ColCount(%u) ar rowIndex(%u)", colIndex, ColCount, rowIndex));
Data[rowIndex][colIndex] = value;
}
const ucstring &getData(uint rowIndex, uint colIndex) const
{
nlassertex(rowIndex < Data.size(), ("TWorksheet::getData: bad row index: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size()));
nlassertex(colIndex < ColCount, ("TWorksheet::getData: bad column index: colIndex(%u) is not less than ColCount(%u) at rowIndex(%u)", colIndex, ColCount, rowIndex));
return Data[rowIndex][colIndex];
}
void setData(uint rowIndex, const ucstring &colName, const ucstring &value)
{
nlassertex(rowIndex > 0, ("TWorksheet::setData: rowIndex(%u) must be greater then 0 !", rowIndex));
nlassertex(rowIndex < Data.size(), ("TWorksheet::setData: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size()));
TWorksheet::TRow::iterator it = std::find(Data[0].begin(), Data[0].end(), ucstring(colName));
nlassertex(it != Data[0].end(), ("TWorksheet::setData: invalid colName: can't find the column named '%s' at row %u", colName.toString().c_str(), rowIndex));
Data[rowIndex][it - Data[0].begin()] = value;
}
const ucstring &getData(uint rowIndex, const ucstring &colName) const
{
nlassertex(rowIndex > 0, ("TWorksheet::getData: bad row index: rowIndex(%u) must be greater then 0 !", rowIndex));
nlassertex(rowIndex < Data.size(), ("TWorksheet::getData: bad row index: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size()));
TWorksheet::TRow::const_iterator it = std::find(Data[0].begin(), Data[0].end(), ucstring(colName));
nlassertex(it != Data[0].end(), ("TWorksheet::getData: invalid colName: can't find the column named '%s' at row %u", colName.toString().c_str(), rowIndex));
return Data[rowIndex][it - Data[0].begin()];
}
};
struct TGetWorksheetIdentifier
{
std::string operator()(const TWorksheet &container, uint index) const
{
return container.getData(index, 1).toString();
}
};
struct TGetWorksheetHashValue
{
uint64 operator()(const TWorksheet &container, uint index) const
{
return NLMISC::CI18N::stringToHash(container.getData(index, ucstring("*HASH_VALUE")).toString());
}
};
struct TTestWorksheetItem : public std::unary_function<TWorksheet::TRow, bool>
{
ucstring Identifier;
TTestWorksheetItem(const std::string &identifier)
: Identifier(identifier)
{}
bool operator () (const TWorksheet::TRow &row) const
{
return row[1] == Identifier;
}
};
struct TWordsDiffContext
{
typedef TWorksheet::TData::iterator iterator;
const TWorksheet &Addition;
TWorksheet &Reference;
TWorksheet &Diff;
TWordsDiffContext(const TWorksheet &addition, TWorksheet &reference, TWorksheet &diff)
: Addition(addition),
Reference(reference),
Diff(diff)
{
}
};
template<class ItemType>
struct TGetIdentifier
{
std::string operator()(const std::vector<ItemType> &container, uint index) const
{
return container[index].Identifier;
}
};
template<class ItemType>
struct TGetHashValue
{
uint64 operator()(const std::vector<ItemType> &container, uint index) const
{
return container[index].HashValue;
}
};
template<class ItemType>
struct TTestItem : public std::unary_function<ItemType, bool>
{
std::string Identifier;
TTestItem(const std::string &identifier)
: Identifier(identifier)
{}
bool operator () (const ItemType &item) const
{
return item.Identifier == Identifier;
}
};
/**
* ItemType must have a property named Identifier that uniquely
* identify each item.
* ItemType must have a property named HashValue that is used
* to determine the change between context.Addition and context.Reference vector.
*/
template <class ItemType, class Context, class GetIdentifier = TGetIdentifier<ItemType>, class GetHashValue = TGetHashValue<ItemType>, class TestItem = TTestItem<ItemType> >
class CMakeDiff
{
public:
struct IDiffCallback
{
virtual void onEquivalent(uint addIndex, uint refIndex, Context &context) = 0;
virtual void onAdd(uint addIndex, uint refIndex, Context &context) = 0;
virtual void onRemove(uint addIndex, uint refIndex, Context &context) = 0;
virtual void onChanged(uint addIndex, uint refIndex, Context &context) = 0;
virtual void onSwap(uint newIndex, uint refIndex, Context &context) = 0;
};
void makeDiff(IDiffCallback *callback, Context &context, bool skipFirstRecord = false)
{
#ifdef NL_DEBUG
// compile time checking
// Context::iterator testIt;
#endif
GetIdentifier getIdentifier;
GetHashValue getHashValue;
// compare the context.Reference an context.Addition file, remove any equivalent strings.
uint addCount, refCount;
if (skipFirstRecord)
{
addCount = 1;
refCount = 1;
}
else
{
addCount = 0;
refCount=0;
}
while (addCount < context.Addition.size() || refCount < context.Reference.size())
{
bool equal = true;
if (addCount != context.Addition.size() && refCount != context.Reference.size())
{
equal = getHashValue(context.Addition, addCount) == getHashValue(context.Reference, refCount);
}
// vector<ItemType>::iterator it;
if (addCount == context.Addition.size()
||
(
!equal
&& find_if(context.Addition.begin(), context.Addition.end(), TestItem(getIdentifier(context.Reference, refCount))) == context.Addition.end()
)
)
{
// this can only be removal
callback->onRemove(addCount, refCount, context);
context.Reference.erase(context.Reference.begin()+refCount);
// ++refCount;
}
else if (refCount == context.Reference.size()
||
(
!equal
&& find_if(context.Reference.begin(), context.Reference.end(), TestItem(getIdentifier(context.Addition, addCount))) == context.Reference.end()
)
)
{
// this can only be context.Addition
callback->onAdd(addCount, refCount, context);
context.Reference.insert(context.Reference.begin()+refCount, context.Addition[addCount]);
++refCount;
++addCount;
}
else if (getIdentifier(context.Addition, addCount) != getIdentifier(context.Reference, refCount))
{
// swap two element.
// Context::iterator it = find_if(context.Reference.begin(), context.Reference.end(), TestItem(getIdentifier(context.Addition, addCount)));
// if (it == context.Reference.end())
if (find_if(
context.Reference.begin(),
context.Reference.end(),
TestItem(getIdentifier(context.Addition, addCount)))
== context.Reference.end())
{
// context.Addition
callback->onAdd(addCount, refCount, context);
context.Reference.insert(context.Reference.begin()+refCount, context.Addition[addCount]);
++refCount;
++addCount;
}
else
{
// nlassert(it != context.Reference.begin()+refCount);
uint index = (uint)(find_if(context.Reference.begin(), context.Reference.end(), TestItem(getIdentifier(context.Addition, addCount))) - context.Reference.begin());
// callback->onSwap(it - context.Reference.begin(), refCount, context);
callback->onSwap(index, refCount, context);
// std::swap(*it, context.Reference[refCount]);
std::swap(context.Reference[index], context.Reference[refCount]);
}
}
else if (getHashValue(context.Addition, addCount) != getHashValue(context.Reference, refCount))
{
// changed element
callback->onChanged(addCount, refCount, context);
++refCount;
++addCount;
}
else
{
// same entry
callback->onEquivalent(addCount, refCount, context);
addCount++;
refCount++;
}
}
}
};
typedef CMakeDiff<TStringInfo, TStringDiffContext> TStringDiff;
typedef CMakeDiff<TPhrase, TPhraseDiffContext> TPhraseDiff;
typedef CMakeDiff<TWorksheet::TRow, TWordsDiffContext, TGetWorksheetIdentifier, TGetWorksheetHashValue, TTestWorksheetItem> TWorkSheetDiff;
uint64 makePhraseHash(const TPhrase &phrase);
bool parseHashFromComment(const ucstring &comments, uint64 &hashValue);
bool loadStringFile(const std::string filename, std::vector<TStringInfo> &stringInfos, bool forceRehash, ucchar openMark = '[', ucchar closeMark = ']', bool specialCase = false);
ucstring prepareStringFile(const std::vector<TStringInfo> &strings, bool removeDiffComments, bool noDiffInfo = false);
bool readPhraseFile(const std::string &filename, std::vector<TPhrase> &phrases, bool forceRehash);
bool readPhraseFileFromString(ucstring const& doc, const std::string &filename, std::vector<TPhrase> &phrases, bool forceRehash);
ucstring tabLines(uint nbTab, const ucstring &str);
ucstring preparePhraseFile(const std::vector<TPhrase> &phrases, bool removeDiffComments);
bool loadExcelSheet(const std::string filename, TWorksheet &worksheet, bool checkUnique = true);
bool readExcelSheet(const ucstring &text, TWorksheet &worksheet, bool checkUnique = true);
void makeHashCode(TWorksheet &sheet, bool forceRehash);
ucstring prepareExcelSheet(const TWorksheet &worksheet);
} // namespace STRING_MANAGER
#endif // DIFF_TOOL_H
|
{
"pile_set_name": "Github"
}
|
# Copyright 1999-2019 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
EAPI=6
inherit autotools
DESCRIPTION="Shell history suggest box"
HOMEPAGE="https://github.com/dvorka/hstr http://www.mindforger.com"
SRC_URI="https://github.com/dvorka/hstr/archive/${PV}.tar.gz -> ${P}.tar.gz"
SLOT="0"
LICENSE="Apache-2.0"
KEYWORDS="amd64 x86"
RDEPEND="
sys-libs/ncurses:0=[unicode]"
DEPEND="
${RDEPEND}
virtual/pkgconfig"
DOCS=( CONFIGURATION.md README.md )
PATCHES=( ${FILESDIR}/${P}-fix-ncurses-configure.patch )
src_prepare() {
default
sed \
-e 's:-O2::g' \
-i src/Makefile.am || die
eautoreconf
}
|
{
"pile_set_name": "Github"
}
|
(set-logic QF_S)
(set-option :strings-exp true)
(set-info :status sat)
(declare-const input_0_1000 String)
(assert (= (str.substr input_0_1000 0 4) "good"))
(assert (= (str.substr input_0_1000 5 1) "I"))
(assert (not (= input_0_1000 "goodAI")))
(check-sat)
|
{
"pile_set_name": "Github"
}
|
# 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 ._configuration import NetworkManagementClientConfiguration
from ._network_management_client import NetworkManagementClient
__all__ = ['NetworkManagementClient', 'NetworkManagementClientConfiguration']
from .version import VERSION
__version__ = VERSION
|
{
"pile_set_name": "Github"
}
|
//
// Typography
// --------------------------------------------------
// Body text
// -------------------------
p {
margin: 0 0 @baseLineHeight / 2;
}
.lead {
margin-bottom: @baseLineHeight;
font-size: @baseFontSize * 1.5;
font-weight: 200;
line-height: @baseLineHeight * 1.5;
}
// Emphasis & misc
// -------------------------
small {
font-size: 85%; // Ex: 14px base font * 85% = about 12px
}
strong {
font-weight: bold;
}
em {
font-style: italic;
}
cite {
font-style: normal;
}
// Utility classes
.muted {
color: @grayLight;
}
.text-warning {
color: @warningText;
}
.text-error {
color: @errorText;
}
.text-info {
color: @infoText;
}
.text-success {
color: @successText;
}
// Headings
// -------------------------
h1, h2, h3, h4, h5, h6 {
margin: (@baseLineHeight / 2) 0;
font-family: @headingsFontFamily;
font-weight: @headingsFontWeight;
line-height: 1;
color: @headingsColor;
text-rendering: optimizelegibility; // Fix the character spacing for headings
small {
font-weight: normal;
line-height: 1;
color: @grayLight;
}
}
h1 { font-size: 36px; line-height: 40px; }
h2 { font-size: 30px; line-height: 40px; }
h3 { font-size: 24px; line-height: 40px; }
h4 { font-size: 18px; line-height: 20px; }
h5 { font-size: 14px; line-height: 20px; }
h6 { font-size: 12px; line-height: 20px; }
h1 small { font-size: 24px; }
h2 small { font-size: 18px; }
h3 small { font-size: 14px; }
h4 small { font-size: 14px; }
// Page header
// -------------------------
.page-header {
padding-bottom: (@baseLineHeight / 2) - 1;
margin: @baseLineHeight 0 (@baseLineHeight * 1.5);
border-bottom: 1px solid @grayLighter;
}
// Lists
// --------------------------------------------------
// Unordered and Ordered lists
ul, ol {
padding: 0;
margin: 0 0 @baseLineHeight / 2 25px;
}
ul ul,
ul ol,
ol ol,
ol ul {
margin-bottom: 0;
}
li {
line-height: @baseLineHeight;
}
ul.unstyled,
ol.unstyled {
margin-left: 0;
list-style: none;
}
// Description Lists
dl {
margin-bottom: @baseLineHeight;
}
dt,
dd {
line-height: @baseLineHeight;
}
dt {
font-weight: bold;
}
dd {
margin-left: @baseLineHeight / 2;
}
// Horizontal layout (like forms)
.dl-horizontal {
.clearfix(); // Ensure dl clears floats if empty dd elements present
dt {
float: left;
width: @horizontalComponentOffset - 20;
clear: left;
text-align: right;
.text-overflow();
}
dd {
margin-left: @horizontalComponentOffset;
}
}
// MISC
// ----
// Horizontal rules
hr {
margin: @baseLineHeight 0;
border: 0;
border-top: 1px solid @hrBorder;
border-bottom: 1px solid @white;
}
// Abbreviations and acronyms
abbr[title] {
cursor: help;
border-bottom: 1px dotted @grayLight;
}
abbr.initialism {
font-size: 90%;
text-transform: uppercase;
}
// Blockquotes
blockquote {
padding: 0 0 0 15px;
margin: 0 0 @baseLineHeight;
border-left: 5px solid @grayLighter;
p {
margin-bottom: 0;
#font > .shorthand(16px,300,@baseLineHeight * 1.25);
}
small {
display: block;
line-height: @baseLineHeight;
color: @grayLight;
&:before {
content: '\2014 \00A0';
}
}
// Float right with text-align: right
&.pull-right {
float: right;
padding-right: 15px;
padding-left: 0;
border-right: 5px solid @grayLighter;
border-left: 0;
p,
small {
text-align: right;
}
small {
&:before {
content: '';
}
&:after {
content: '\00A0 \2014';
}
}
}
}
// Quotes
q:before,
q:after,
blockquote:before,
blockquote:after {
content: "";
}
// Addresses
address {
display: block;
margin-bottom: @baseLineHeight;
font-style: normal;
line-height: @baseLineHeight;
}
|
{
"pile_set_name": "Github"
}
|
/******************************************************************************
* Copyright (c) 2004, 2008 IBM Corporation
* All rights reserved.
* This program and the accompanying materials
* are made available under the terms of the BSD License
* which accompanies this distribution, and is available at
* http://www.opensource.org/licenses/bsd-license.php
*
* Contributors:
* IBM Corporation - initial implementation
*****************************************************************************/
#include <string.h>
char *
strtok(char *src, const char *pattern)
{
static char *nxtTok;
char *retVal = NULL;
if (!src)
src = nxtTok;
while (*src) {
const char *pp = pattern;
while (*pp) {
if (*pp == *src) {
break;
}
pp++;
}
if (!*pp) {
if (!retVal)
retVal = src;
else if (!src[-1])
break;
} else
*src = '\0';
src++;
}
nxtTok = src;
return retVal;
}
|
{
"pile_set_name": "Github"
}
|
// fieldstruct example
addrmap foo_map {
// define simple packed fieldstruct
fieldstruct fs1 {
field { sw=rw; hw=rw; we; } fld1[4] = 4'd0;
field { sw=rw; hw=r; } fld2;
};
// define fieldstruct w/ field gaps
fieldstruct fs2 {
field { sw=rw; hw=rw; we; } fld1[3:0] = 4'd0;
field { sw=rw; hw=r; } fld2[8:8];
};
// define fieldstruct w/ explicit width
fieldstruct fs3 {
fieldstructwidth = 8;
field { sw=rw; hw=rw; we; } fld1[4] = 4'd0;
field { sw=rw; hw=r; } fld2;
};
// define hierarchical fieldstruct
fieldstruct hier_fs {
fs1 fs1;
field { sw=rw; hw=r; } fld1;
fs2 fs2;
};
// reg using these fieldstructs
reg {
hier_fs hier_fs;
fs3 fs3[31:24]; // fieldstruct at a specific bit position
} areg[2];
// reg using replicated fieldstructs
reg {
fs1 fs1[3];
fs3 fs3[2];
} blabla;
} foo;
|
{
"pile_set_name": "Github"
}
|
--q48.sql--
select sum (ss_quantity)
from store_sales, store, customer_demographics, customer_address, date_dim
where s_store_sk = ss_store_sk
and ss_sold_date_sk = d_date_sk and d_year = 2000
and
(
(
cd_demo_sk = ss_cdemo_sk
and
cd_marital_status = 'M'
and
cd_education_status = '4 yr Degree'
and
ss_sales_price between 100.00 and 150.00
)
or
(
cd_demo_sk = ss_cdemo_sk
and
cd_marital_status = 'D'
and
cd_education_status = '2 yr Degree'
and
ss_sales_price between 50.00 and 100.00
)
or
(
cd_demo_sk = ss_cdemo_sk
and
cd_marital_status = 'S'
and
cd_education_status = 'College'
and
ss_sales_price between 150.00 and 200.00
)
)
and
(
(
ss_addr_sk = ca_address_sk
and
ca_country = 'United States'
and
ca_state in ('CO', 'OH', 'TX')
and ss_net_profit between 0 and 2000
)
or
(ss_addr_sk = ca_address_sk
and
ca_country = 'United States'
and
ca_state in ('OR', 'MN', 'KY')
and ss_net_profit between 150 and 3000
)
or
(ss_addr_sk = ca_address_sk
and
ca_country = 'United States'
and
ca_state in ('VA', 'CA', 'MS')
and ss_net_profit between 50 and 25000
)
)
|
{
"pile_set_name": "Github"
}
|
---
-api-id: P:Windows.UI.Xaml.Controls.RichEditBox.IsHandwritingViewEnabledProperty
-api-type: winrt property
---
<!-- Property syntax.
public DependencyProperty IsHandwritingViewEnabledProperty { get; }
-->
# Windows.UI.Xaml.Controls.RichEditBox.IsHandwritingViewEnabledProperty
## -description
Identifies the IsHandwritingViewEnabled dependency property.
## -property-value
The identifier for the IsHandwritingViewEnabled dependency property.
## -remarks
## -see-also
[Text input with the handwriting view](/windows/uwp/design/controls-and-patterns/text-handwriting-view)
## -examples
In this example, we disable the handwriting view by setting the [IsHandwritingViewEnabled](/uwp/api/windows.ui.xaml.controls.textbox.ishandwritingviewenabled) property of the [RichEditBox](/uwp/api/windows.ui.xaml.controls.richeditbox) control to false. All text controls that support the handwriting view support a similar property.
```xaml
<RIchEditBox Name="SampleTextBox"
Height="50" Width="500"
FontSize="36" FontFamily="Segoe UI"
PlaceholderText="Try taping with your pen"
IsHandwritingViewEnabled="False">
</RichEditBox>
```
|
{
"pile_set_name": "Github"
}
|
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for apply().
This converts apply(func, v, k) into (func)(*v, **k)."""
# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Call, Comma, parenthesize
class FixApply(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
power< 'apply'
trailer<
'('
arglist<
(not argument<NAME '=' any>) func=any ','
(not argument<NAME '=' any>) args=any [','
(not argument<NAME '=' any>) kwds=any] [',']
>
')'
>
>
"""
def transform(self, node, results):
syms = self.syms
assert results
func = results["func"]
args = results["args"]
kwds = results.get("kwds")
prefix = node.prefix
func = func.clone()
if (func.type not in (token.NAME, syms.atom) and
(func.type != syms.power or
func.children[-2].type == token.DOUBLESTAR)):
# Need to parenthesize
func = parenthesize(func)
func.prefix = ""
args = args.clone()
args.prefix = ""
if kwds is not None:
kwds = kwds.clone()
kwds.prefix = ""
l_newargs = [pytree.Leaf(token.STAR, "*"), args]
if kwds is not None:
l_newargs.extend([Comma(),
pytree.Leaf(token.DOUBLESTAR, "**"),
kwds])
l_newargs[-2].prefix = " " # that's the ** token
# XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t)
# can be translated into f(x, y, *t) instead of f(*(x, y) + t)
#new = pytree.Node(syms.power, (func, ArgList(l_newargs)))
return Call(func, l_newargs, prefix=prefix)
|
{
"pile_set_name": "Github"
}
|
#-------------------------------------------------
#
# Project created by QtCreator 2015-02-05T09:45:38
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport
TARGET = Demo
TEMPLATE = app
SOURCES += main.cpp\
custommodel.cpp \
tableprinterexample.cpp
HEADERS += \
custommodel.h \
tableprinterexample.h \
tdpreviewdialog.h
FORMS += \
tableprinterexample.ui \
tdpreviewdialog.ui
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/../build-tableprinter-Desktop_Qt_5_3_MSVC2010_OpenGL_32bit-Debug/release/ -ltableprinter
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/../build-tableprinter-Desktop_Qt_5_3_MSVC2010_OpenGL_32bit-Debug/debug/ -ltableprinter
INCLUDEPATH += $$PWD/../build-tableprinter-Desktop_Qt_5_3_MSVC2010_OpenGL_32bit-Debug/debug
DEPENDPATH += $$PWD/../build-tableprinter-Desktop_Qt_5_3_MSVC2010_OpenGL_32bit-Debug/debug
win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/../build-tableprinter-Desktop_Qt_5_3_MSVC2010_OpenGL_32bit-Debug/release/libtableprinter.a
else:win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/../build-tableprinter-Desktop_Qt_5_3_MSVC2010_OpenGL_32bit-Debug/debug/libtableprinter.a
else:win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/../build-tableprinter-Desktop_Qt_5_3_MSVC2010_OpenGL_32bit-Debug/release/tableprinter.lib
else:win32:!win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/../build-tableprinter-Desktop_Qt_5_3_MSVC2010_OpenGL_32bit-Debug/debug/tableprinter.lib
|
{
"pile_set_name": "Github"
}
|
95e54b261530a1bcf6de6fe3b21dc5f6 *tests/data/fate/acodec-pcm-s16le.wav
1058444 tests/data/fate/acodec-pcm-s16le.wav
95e54b261530a1bcf6de6fe3b21dc5f6 *tests/data/fate/acodec-pcm-s16le.out.wav
stddev: 0.00 PSNR:999.99 MAXDIFF: 0 bytes: 1058400/ 1058400
|
{
"pile_set_name": "Github"
}
|
/**
@Title: layui.rate 评分评星
@Author: star1029
@License:MIT
*/
layui.define('jquery',function(exports){
"use strict";
var $ = layui.jquery
//外部接口
,rate = {
config: {}
,index: layui.rate ? (layui.rate.index + 10000) : 0
//设置全局项
,set: function(options){
var that = this;
that.config = $.extend({}, that.config, options);
return that;
}
//事件监听
,on: function(events, callback){
return layui.onevent.call(this, MOD_NAME, events, callback);
}
}
//操作当前实例
,thisRate = function(){
var that = this
,options = that.config;
return {
setvalue: function(value){
that.setvalue.call(that, value);
}
,config: options
}
}
//字符常量
,MOD_NAME = 'rate',ELEM_VIEW = 'layui-rate', ICON_RATE = 'layui-icon-rate', ICON_RATE_SOLID = 'layui-icon-rate-solid', ICON_RATE_HALF = 'layui-icon-rate-half'
,ICON_SOLID_HALF = 'layui-icon-rate-solid layui-icon-rate-half', ICON_SOLID_RATE = 'layui-icon-rate-solid layui-icon-rate', ICON_HALF_RATE = 'layui-icon-rate layui-icon-rate-half'
//构造器
,Class = function(options){
var that = this;
that.index = ++rate.index;
that.config = $.extend({}, that.config, rate.config, options);
that.render();
};
//默认配置
Class.prototype.config = {
length: 5 //初始长度
,text: false //是否显示评分等级
,readonly: false //是否只读
,half: false //是否可以半星
,value: 0 //星星选中个数
,theme: ''
};
//评分渲染
Class.prototype.render = function(){
var that = this
,options = that.config
,style = options.theme ? ('style="color: '+ options.theme + ';"') : '';
options.elem = $(options.elem);
//如果没有选择半星的属性,却给了小数的数值,统一向上或向下取整
if(parseInt(options.value) !== options.value){
if(!options.half){
options.value = (Math.ceil(options.value) - options.value) < 0.5 ? Math.ceil(options.value): Math.floor(options.value)
}
}
//组件模板
var temp = '<ul class="layui-rate" '+ (options.readonly ? 'readonly' : '') +'>';
for(var i = 1;i <= options.length;i++){
var item = '<li class="layui-inline"><i class="layui-icon '
+ (i>Math.floor(options.value)?ICON_RATE:ICON_RATE_SOLID)
+ '" '+ style +'></i></li>';
if(options.half){
if(parseInt(options.value) !== options.value){
if(i == Math.ceil(options.value)){
temp = temp + '<li><i class="layui-icon layui-icon-rate-half" '+ style +'></i></li>';
}else{
temp = temp + item
}
}else{
temp = temp + item
}
}else{
temp = temp +item;
}
}
temp += '</ul>' + (options.text ? ('<span class="layui-inline">'+ options.value + '星') : '') + '</span>';
//开始插入替代元素
var othis = options.elem
,hasRender = othis.next('.' + ELEM_VIEW);
//生成替代元素
hasRender[0] && hasRender.remove(); //如果已经渲染,则Rerender
that.elemTemp = $(temp);
options.span = that.elemTemp.next('span');
options.setText && options.setText(options.value);
othis.html(that.elemTemp);
othis.addClass("layui-inline");
//如果不是只读,那么进行触控事件
if(!options.readonly) that.action();
};
//评分重置
Class.prototype.setvalue = function(value){
var that = this
,options = that.config ;
options.value = value ;
that.render();
};
//li触控事件
Class.prototype.action = function(){
var that = this
,options = that.config
,_ul = that.elemTemp
,wide = _ul.find("i").width();
_ul.children("li").each(function(index){
var ind = index + 1
,othis = $(this);
//点击
othis.on('click', function(e){
//将当前点击li的索引值赋给value
options.value = ind;
if(options.half){
//获取鼠标在li上的位置
var x = e.pageX - $(this).offset().left;
if(x <= wide / 2){
options.value = options.value - 0.5;
}
}
if(options.text) _ul.next("span").text(options.value + "星");
options.choose && options.choose(options.value);
options.setText && options.setText(options.value);
});
//移入
othis.on('mousemove', function(e){
_ul.find("i").each(function(){
$(this).addClass(ICON_RATE).removeClass(ICON_SOLID_HALF)
});
_ul.find("i:lt(" + ind + ")").each(function(){
$(this).addClass(ICON_RATE_SOLID).removeClass(ICON_HALF_RATE)
});
// 如果设置可选半星,那么判断鼠标相对li的位置
if(options.half){
var x = e.pageX - $(this).offset().left;
if(x <= wide / 2){
othis.children("i").addClass(ICON_RATE_HALF).removeClass(ICON_RATE_SOLID)
}
}
})
//移出
othis.on('mouseleave', function(){
_ul.find("i").each(function(){
$(this).addClass(ICON_RATE).removeClass(ICON_SOLID_HALF)
});
_ul.find("i:lt(" + Math.floor(options.value) + ")").each(function(){
$(this).addClass(ICON_RATE_SOLID).removeClass(ICON_HALF_RATE)
});
//如果设置可选半星,根据分数判断是否有半星
if(options.half){
if(parseInt(options.value) !== options.value){
_ul.children("li:eq(" + Math.floor(options.value) + ")").children("i").addClass(ICON_RATE_HALF).removeClass(ICON_SOLID_RATE)
}
}
})
})
};
//事件处理
Class.prototype.events = function(){
var that = this
,options = that.config;
};
//核心入口
rate.render = function(options){
var inst = new Class(options);
return thisRate.call(inst);
};
exports(MOD_NAME, rate);
})
|
{
"pile_set_name": "Github"
}
|
#include "boo.h++"
#include <foo.h>
void t2(int i);
void t1()
{
for (int i = 0; i < 100; ++i)
{
if (98 == i)
{
t2(i);
break;
}
}
}
void t2(int i)
{
if (9 == i)
{
int k = i + 9;
++k;
return;
}
acme::t1();
}
int main()
{
t1();
return 0;
}
|
{
"pile_set_name": "Github"
}
|
import React from 'react'
import cx from 'classnames'
import styles from './logo.css'
import { AnimationComponent, ClassicText } from 'light-ui'
const _LogoText = (props) => {
const {
status,
className
} = props
const textClassName = cx(
className,
styles.logoContainer,
styles[`logoContainer-${status}`]
)
return (
<ClassicText
{...props}
className={textClassName}
text={props.text || 'hacknical'}
/>
)
}
const LogoText = props => (
<AnimationComponent>
<_LogoText {...props} />
</AnimationComponent>
)
export default LogoText
|
{
"pile_set_name": "Github"
}
|
<html>
<head>
<script>
function log(message)
{
document.getElementById("result").innerHTML += message + "<br>";
}
function loadJSFile(){
var s = document.createElement('script')
s.setAttribute("type", "text/javascript")
s.setAttribute("src", "resources/load-deferrer-script-element.js")
document.getElementsByTagName("head")[0].appendChild(s);
}
jsLoaded = false;
runningModal = false;
// This line will load external script into memory.
loadJSFile();
function runModal()
{
jsLoaded = true;
loadJSFile();
runningModal = true;
alert("Scripts should not be running in the background!");
runningModal = false;
}
</script>
</head>
<body>
<p>This tests the bug https://bugs.webkit.org/show_bug.cgi?id=38910.
Click the button, wait 5 seconds and close it.
The test passes if no error messages show up in the page!</p>
<input id="button" type="button" value="click me" onclick="runModal()"/>
<p id="result"></p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
var assert = require('assert');
var wordwrap = require('wordwrap');
var fs = require('fs');
var idleness = fs.readFileSync(__dirname + '/idleness.txt', 'utf8');
exports.stop80 = function () {
var lines = wordwrap(80)(idleness).split(/\n/);
var words = idleness.split(/\s+/);
lines.forEach(function (line) {
assert.ok(line.length <= 80, 'line > 80 columns');
var chunks = line.match(/\S/) ? line.split(/\s+/) : [];
assert.deepEqual(chunks, words.splice(0, chunks.length));
});
};
exports.start20stop60 = function () {
var lines = wordwrap(20, 100)(idleness).split(/\n/);
var words = idleness.split(/\s+/);
lines.forEach(function (line) {
assert.ok(line.length <= 100, 'line > 100 columns');
var chunks = line
.split(/\s+/)
.filter(function (x) { return x.match(/\S/) })
;
assert.deepEqual(chunks, words.splice(0, chunks.length));
assert.deepEqual(line.slice(0, 20), new Array(20 + 1).join(' '));
});
};
|
{
"pile_set_name": "Github"
}
|
var assert = require('assert');
var wordwrap = require('wordwrap');
var fs = require('fs');
var idleness = fs.readFileSync(__dirname + '/idleness.txt', 'utf8');
exports.stop80 = function () {
var lines = wordwrap(80)(idleness).split(/\n/);
var words = idleness.split(/\s+/);
lines.forEach(function (line) {
assert.ok(line.length <= 80, 'line > 80 columns');
var chunks = line.match(/\S/) ? line.split(/\s+/) : [];
assert.deepEqual(chunks, words.splice(0, chunks.length));
});
};
exports.start20stop60 = function () {
var lines = wordwrap(20, 100)(idleness).split(/\n/);
var words = idleness.split(/\s+/);
lines.forEach(function (line) {
assert.ok(line.length <= 100, 'line > 100 columns');
var chunks = line
.split(/\s+/)
.filter(function (x) { return x.match(/\S/) })
;
assert.deepEqual(chunks, words.splice(0, chunks.length));
assert.deepEqual(line.slice(0, 20), new Array(20 + 1).join(' '));
});
};
|
{
"pile_set_name": "Github"
}
|
#version 450
struct AStruct { vec4 foobar; };
void someFunction(out AStruct s) { s.foobar = vec4(1.0); }
highp vec3 global_variable;
void otherFunction() {
global_variable = vec3(1.0);
}
layout(location = 0) out vec3 FragColor;
void main() {
AStruct inputs;
someFunction(inputs);
otherFunction();
FragColor = global_variable;
}
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env roseus
(load "irteus/kalmanlib.l")
(ros::load-ros-manifest "roseus")
(ros::load-ros-manifest "posedetection_msgs")
(ros::roseus "marker-publish")
(ros::roseus-add-msgs "posedetection_msgs")
(setq *map-id* "/map")
(setq *solve-tf* t)
(setq *object-width* (ros::get-param "~object_width" 0))
(setq *object-height* (ros::get-param "~object_height" 0))
(setq *relative-pose-str* (ros::get-param "~relative_pose" "0 0 0 0 0 0 1"))
(setq *detection-topic* (ros::get-param "~detection_topic" "/kinect_head/rgb/ObjectDetection"))
(setq *marker-life* (ros::get-param "~marker_life" 300))
(setq *base-frame-id* (ros::get-param "~base_frame_id" "/base_footprint"))
(setq *calc-kalman* t)
(setq *detect-flag* t)
(setq *tf-force* nil)
(setq *target-obj* (make-cube 60 60 60))
(send *target-obj* :reset-coords)
(setf (get *target-obj* :type) (ros::get-param "~target_type" nil))
(setq *map-frame-objectdetection* (instance posedetection_msgs::ObjectDetection :init))
(send *map-frame-objectdetection* :header :frame_id *map-id*)
(setq *filtered-objectdetection* (instance posedetection_msgs::ObjectDetection :init))
(send *filtered-objectdetection* :header :frame_id *map-id*)
(setq *kfs-lst* nil)
(setq *list-of-target-x-pos* nil)
(setq *threshold-of-target-x-pos-diff* 30) ; mm
(setq *average-of-target-x-pos* 0)
(defclass kalman-filters
:super propertied-object
:slots (kfp kfr)
)
(defmethod kalman-filters
(:init
(&key (pos (float-vector 0 0 0)) (yaw (float-vector 0)))
(setq kfp (instance kalman-filter :init :state-dim 3 :measure-dim 3 :q-variance 1))
(send kfp :x (float-vector (elt pos 0) (elt pos 1) (elt pos 2)))
(setq kfr (instance kalman-filter :init :state-dim 2 :measure-dim 1 :q-variance 0.1))
(send kfr :x (float-vector yaw 0))
;; (send kfp :x pos)
;; (send kfp :A (make-array (list 3 3)))
;; (send kfp :A #2f((1 0 0 1 0 0) (0 1 0 0 1 0) (0 0 1 0 0 1) (0 0 0 1 0 0) (0 0 0 0 1 0) (0 0 0 0 0 1)))
;; (send kfr :A (make-array (list 2 2)))
;; (send kfr :A #2f((1 1) (0 1)))
;; (setq kfr (instance kalman-filter :init :state-dim 1 :measure-dim 1))
;; (send kfr :x (float-vector yaw))
)
(:pos
(p)
(send kfp :x p)
)
(:yaw
(y)
(send kfr :x y)
)
(:proc
(z1 z2)
(let (h1 h2)
(setq h1 (send kfp :proc z1 :adaptive t :m 3))
(setq h2 (send kfr :proc (float-vector z2) :adaptive t :m 30))
(list h1 h2)
))
(:P
()
(send kfp :P)
))
(defmethod coordinates
(:stamp (&optional s) (if s (setf (get self :stamp) s)) (get self :stamp))
(:frame_id (&optional f) (if f (setf (get self :frame_id) f)) (get self :frame_id)))
(defun remap-to-map-frame-and-store-ObjectDetection (target-obj msg)
(let ((obj-lst (send msg :objects))
(frame (send msg :header :frame_id))
(tp (get target-obj :type))
tmp-obj-lst stamp trans)
(ros::ros-debug "object detection callback target ~A(~A), frame ~A, object ~A"
tp (stringp tp) frame target-obj)
(dolist (obj obj-lst)
(when (or (not (stringp tp))
(substringp tp (send obj :type))) ;; found target
(setq stamp (if *tf-force* (ros::time 0) (send msg :header :stamp)))
(cond
(*solve-tf*
(unless (boundp '*tfl*)
(setq *tfl* (instance ros::transform-listener :init)))
(unless (send *tfl* :wait-for-transform *map-id* frame stamp 1)
(ros::ros-error "could not solve ~A to ~A" *map-id* frame))
(setq trans (send *tfl* :lookup-transform *map-id* frame stamp))
(ros::ros-debug "trans ~A" trans))
(t (setq trans (make-coords))))
(when trans
(let ((tmp-obj (instance posedetection_msgs::Object6DPose :init)))
(ros::ros-info "object detected ~A ~A ~20,9f" (send obj :type)
(ros::tf-pose->coords (send obj :pose))
(send (send msg :header :stamp) :to-sec))
(send target-obj :name (send obj :type))
(send target-obj :stamp (send msg :header :stamp))
(send target-obj :frame_id (send msg :header :frame_id))
(send target-obj :reset-coords)
(send target-obj :move-to trans :local)
(send target-obj :move-to (ros::tf-pose->coords (send obj :pose)) :local)
(send tmp-obj :pose (ros::coords->tf-pose target-obj))
(send tmp-obj :type (send obj :type))
(setq tmp-obj-lst (append tmp-obj-lst (list tmp-obj)))
(when (find-method target-obj :update-descendants)
(send target-obj :update-descendants) ;; clean me
)
(unless (boundp '*tfb*)
(setq *tfb* (instance ros::transform-broadcaster :init)))
(send *tfb* :send-transform (ros::tf-pose->coords (send obj :pose)) frame (send target-obj :name))
))))
(send *map-frame-objectdetection* :objects tmp-obj-lst)
(send *map-frame-objectdetection* :header :stamp (send msg :header :stamp))
))
(defun publish-marker (target-obj marker-life &key (publish-name "object_detection_marker_array")
(object-name *map-frame-objectdetection*)
(text-name nil) (text-color nil) (obj-color nil))
(let ((mf-obj-lst (send object-name :objects))
(tmp-tgtobj (make-cube 60 60 60))
(tp (get target-obj :type)))
(when obj-color
(send tmp-tgtobj :set-color obj-color))
(dolist (obj mf-obj-lst)
(when (or (not (stringp tp))
(substringp tp (send obj :type))) ;; found target
(send tmp-tgtobj :move-to (ros::tf-pose->coords (send obj :pose)) :local)
(ros::publish publish-name
(instance visualization_msgs::MarkerArray :init
:markers
(list (text->marker-msg
(cond
(text-name
text-name)
(t
(send obj :type)
))
(send (send (ros::tf-pose->coords (send obj :pose)) :copy-worldcoords) :translate #f(-100 0 100))
(send object-name :header)
:ns (format nil "object_text_~A" (send obj :type))
:color (cond
(text-color
text-color)
(t
#f(1 0 0)))
:scale 100 :lifetime marker-life :id 0)
(coords->marker-msg
(send (ros::tf-pose->coords (send obj :pose)) :copy-worldcoords)
(send object-name :header)
:ns (format nil "object_coords_~A" (send obj :type))
;; :size 200 :width 20
:lifetime marker-life :id 1)
(object->marker-msg
tmp-tgtobj
(send object-name :header)
:ns (format nil "object_body_~A" (send obj :type))
:lifetime marker-life :id 2)
)))))))
(defun catch-outlier (target-obj)
(let ((mf-obj-lst (send *map-frame-objectdetection* :objects))
(tmp-tgtobj (make-cube 60 60 60))
(marker-life 700)
(outlierflag nil)
(tp (get target-obj :type)))
(dolist (obj mf-obj-lst)
(when (or (not (stringp tp))
(substringp tp (send obj :type))) ;; found target
(send tmp-tgtobj :move-to (ros::tf-pose->coords (send obj :pose)) :local)
(cond
((< (length *list-of-target-x-pos*) 20) ;;stock only
(setq *list-of-target-x-pos* (append *list-of-target-x-pos* (list (aref (send tmp-tgtobj :pos) 0))))
)
(t
(setq *average-of-target-x-pos* 0)
(dolist (x *list-of-target-x-pos* nil)
(setq *average-of-target-x-pos* (+ *average-of-target-x-pos* x))
)
(setq *average-of-target-x-pos* (/ *average-of-target-x-pos* 20))
(ros::ros-info "ave:~A x: ~A diff:~A outlierflag:~A" *average-of-target-x-pos*
(aref (send tmp-tgtobj :pos) 0)
(abs (- *average-of-target-x-pos* (aref (send tmp-tgtobj :pos) 0)))
(< *threshold-of-target-x-pos-diff* (abs (- *average-of-target-x-pos* (aref (send tmp-tgtobj :pos) 0))))
)
(cond
((< *threshold-of-target-x-pos-diff* (abs (- *average-of-target-x-pos* (aref (send tmp-tgtobj :pos) 0)))) ;; outsider
(ros::ros-info "publish outlier")
(setq outlierflag t)
(setq *list-of-target-x-pos* (append (cdr *list-of-target-x-pos*) (list (aref (send tmp-tgtobj :pos) 0))))
)
(t ;; inside
;; like queue
(setq *list-of-target-x-pos* (append (cdr *list-of-target-x-pos*) (list (aref (send tmp-tgtobj :pos) 0))))
))))))
(when outlierflag
(publish-marker target-obj *marker-life* :publish-name "outlier"
:object-name *map-frame-objectdetection*
:text-name "outlier" :text-color (float-vector 0 1 0)
:obj-color (float-vector 0.4 1 0.4))
)
(return-from catch-outlier outlierflag)
))
(defparameter *poselist* nil)
(defun add-to-xlist (x)
(setq *poselist* (append *poselist* (list x)))
(cond
((> (length *poselist*) 10)
(setq *poselist* (cdr *poselist*))
)
(t
nil)))
(defun calc-covariance ()
(let ((x-cov 0)
(y-cov 0)
(z-cov 0)
(x-ave 0)
(y-ave 0)
(z-ave 0))
;; (ros::ros-info "poselist:~A" *poselist*)
(dolist (pose *poselist*)
(setq x-ave (+ x-ave (send pose :position :x)))
(setq y-ave (+ y-ave (send pose :position :y)))
(setq z-ave (+ z-ave (send pose :position :z)))
)
(setq x-ave (/ (* 1.0 x-ave) (length *poselist*)))
(setq y-ave (/ (* 1.0 y-ave) (length *poselist*)))
(setq z-ave (/ (* 1.0 z-ave) (length *poselist*)))
;; (ros::ros-info "x-ave:~A" x-ave)
(dolist (pose *poselist*)
(setq x-cov (+ x-cov
(* (- (send pose :position :x) x-ave) (- (send pose :position :x) x-ave))))
(setq y-cov (+ y-cov
(* (- (send pose :position :y) y-ave) (- (send pose :position :y) y-ave))))
(setq z-cov (+ z-cov
(* (- (send pose :position :z) z-ave) (- (send pose :position :z) z-ave))))
)
(setq x-cov (/ (* 1.0 x-cov) (length *poselist*)))
(setq y-cov (/ (* 1.0 y-cov) (length *poselist*)))
(setq z-cov (/ (* 1.0 z-cov) (length *poselist*)))
;; too small
(setq x-cov (* x-cov 100))
(setq y-cov (* y-cov 100))
(setq z-cov (* z-cov 100))
;; (ros::ros-info "x-cov:~A" x-cov)
;; (return-from calc-covariance (list x-cov y-cov z-cov))
(list x-cov y-cov z-cov)
))
(defun simply-calc-covariance-and-pub-PoseStamped-and-PoseWithCovarianceStamped
(target-obj &key (object-name *map-frame-objectdetection*))
(let* ((mf-obj-lst (send object-name :objects))
(tmp-posestamped (instance geometry_msgs::PoseStamped :init))
(tp (get target-obj :type))
(relative-pose-stream (make-string-input-stream *relative-pose-str*))
(tmp-pose (instance geometry_msgs::Pose :init))
covlst
(tmp-posewithcovariancestamped (instance geometry_msgs::PoseWithCovarianceStamped :init))
(tmp-cov (send tmp-posewithcovariancestamped :pose :covariance))
)
;; currently considered only 1 kind of data comes
(dolist (obj mf-obj-lst)
(when (or (not (stringp tp))
(substringp tp (send obj :type))) ;; found target
(add-to-xlist (send obj :pose))
))
(setf covlst (calc-covariance))
(send tmp-pose :position :x (read relative-pose-stream nil))
(send tmp-pose :position :y (read relative-pose-stream nil))
(send tmp-pose :position :z (read relative-pose-stream nil))
(send tmp-pose :orientation :x (read relative-pose-stream nil))
(send tmp-pose :orientation :y (read relative-pose-stream nil))
(send tmp-pose :orientation :z (read relative-pose-stream nil))
(send tmp-pose :orientation :w (read relative-pose-stream nil))
(setq inverse-trans (send (send (ros::tf-pose->coords tmp-pose) :inverse-transformation)
:translate (float-vector (* (/ *object-height* 2.0) 1000) (* (/ *object-width* 2.0) 1000) 0)))
(dolist (obj mf-obj-lst)
(when (or (not (stringp tp))
(substringp tp (send obj :type))) ;; found target
(let ((tmp-coords (send (ros::tf-pose->coords (send obj :pose)) :copy-worldcoords)))
(send tmp-coords :transform inverse-trans)
(send tmp-posestamped :pose (ros::coords->tf-pose tmp-coords))
(send tmp-posestamped :header (send object-name :header))
)))
(setf (elt tmp-cov 0) (car covlst))
(setf (elt tmp-cov 7) (cadr covlst))
(setf (elt tmp-cov 14) (caddr covlst))
(unless (eq (car covlst) 0.0)
(ros::ros-info "simplecov x:~A y:~A z:~A" (car covlst) (cadr covlst) (caddr covlst))
(setf (elt tmp-cov 21) 0.1)
(setf (elt tmp-cov 28) 0.1)
(setf (elt tmp-cov 35) 0.1)
(send tmp-posewithcovariancestamped :header (send object-name :header))
(send tmp-posewithcovariancestamped :pose :pose (send tmp-posestamped :pose))
(send tmp-posewithcovariancestamped :pose :covariance tmp-cov)
(ros::publish "simplecov" tmp-posewithcovariancestamped)
)
))
(defun apply-kalman-filter-to-mapframeobjectdetection ()
(let ((mf-obj-lst (send *map-frame-objectdetection* :objects))
(flag t)
)
(dolist (obj mf-obj-lst)
(dolist (kf *kfs-lst*)
(cond
((equal (get kf :type) (send obj :type))
(let ((ps (send (ros::tf-pose->coords (send obj :pose)) :pos))
(yaw (elt (elt (rpy-angle (send (ros::tf-pose->coords (send obj :pose)) :rot)) 0) 0))
z^
)
(setq flag nil)
(setq z^ (send kf :proc ps yaw))
(dolist (fo (send *filtered-objectdetection* :objects))
(cond
((equal (get kf :type) (send fo :type))
(let ((tmp-coords (make-coords)))
(send tmp-coords :locate (elt z^ 0))
(send tmp-coords :rotate (elt (elt z^ 1) 0) :z)
(send fo :pose (ros::coords->tf-pose tmp-coords))))
(t
nil)))
))
(t
nil)))
(if flag
(progn
(let ((tmp-kfs (instance kalman-filters :init
:pos (send (ros::tf-pose->coords (send obj :pose)) :pos)
:yaw (elt (elt (rpy-angle (send (ros::tf-pose->coords (send obj :pose)) :rot)) 0) 0)))
tmp-fo
)
(setf (get tmp-kfs :type) (send obj :type))
(setq *kfs-lst* (append *kfs-lst* (list tmp-kfs)))
(send *filtered-objectdetection* :objects (append (send *filtered-objectdetection* :objects) (list obj)))
))))
(send *filtered-objectdetection* :header (send *map-frame-objectdetection* :header))
))
(defun pub-PoseStamped-and-PoseWithCovarianceStamped (target-obj &key (object-name *map-frame-objectdetection*))
(let ((mf-obj-lst (send object-name :objects))
(tmp-posestamped (instance geometry_msgs::PoseStamped :init))
(tmp-posewithcovariancestamped (instance geometry_msgs::PoseWithCovarianceStamped :init))
(relative-pose-stream (make-string-input-stream *relative-pose-str*))
(tmp-pose (instance geometry_msgs::Pose :init))
(tp (get target-obj :type)))
(ros::unsubscribe "/openni_c2/rgb/image_rect_color")
(send tmp-pose :position :x (read relative-pose-stream nil))
(send tmp-pose :position :y (read relative-pose-stream nil))
(send tmp-pose :position :z (read relative-pose-stream nil))
(send tmp-pose :orientation :x (read relative-pose-stream nil))
(send tmp-pose :orientation :y (read relative-pose-stream nil))
(send tmp-pose :orientation :z (read relative-pose-stream nil))
(send tmp-pose :orientation :w (read relative-pose-stream nil))
(print-ros-msg tmp-pose)
(setq inverse-trans (send (send (ros::tf-pose->coords tmp-pose) :inverse-transformation)
:translate (float-vector (* (/ *object-height* 2.0) 1000) (* (/ *object-width* 2.0) 1000) 0)))
(dolist (obj mf-obj-lst)
(when (or (not (stringp tp))
(substringp tp (send obj :type))) ;; found target
(let ((tmp-coords (send (ros::tf-pose->coords (send obj :pose)) :copy-worldcoords)))
(send tmp-coords :transform inverse-trans)
(send tmp-posestamped :pose (ros::coords->tf-pose tmp-coords))
(send tmp-posestamped :header (send object-name :header))
)))
(unless (null *kfs-lst*)
(let ((cov (send (car *kfs-lst*) :P))
(tmp-cov (send tmp-posewithcovariancestamped :pose :covariance)))
(setq *pwc* tmp-cov)
(setq *cov* cov)
(setf (elt tmp-cov 0) (/ (elt (matrix-row cov 0) 0) 100.0))
(setf (elt tmp-cov 1) (/ (elt (matrix-row cov 0) 1) 100.0))
(setf (elt tmp-cov 2) (/ (elt (matrix-row cov 0) 2) 100.0))
(setf (elt tmp-cov 6) (/ (elt (matrix-row cov 1) 0) 100.0))
(setf (elt tmp-cov 7) (/ (elt (matrix-row cov 1) 1) 100.0))
(setf (elt tmp-cov 8) (/ (elt (matrix-row cov 1) 2) 100.0))
(setf (elt tmp-cov 12) (/ (elt (matrix-row cov 2) 0) 100.0))
(setf (elt tmp-cov 13) (/ (elt (matrix-row cov 2) 1) 100.0))
(setf (elt tmp-cov 14) (/ (elt (matrix-row cov 2) 2) 100.0))
(setf (elt tmp-cov 21) 0.1)
(setf (elt tmp-cov 28) 0.1)
(setf (elt tmp-cov 35) 0.1)
(ros::ros-info "estimated covariance of adaptive kalmanfilter:~A" cov)
(ros::ros-info "poswithcovariance: ~A" tmp-cov)
(send tmp-posewithcovariancestamped :header (send object-name :header))
(send tmp-posewithcovariancestamped :pose :pose (send tmp-posestamped :pose))
(send tmp-posewithcovariancestamped :pose :covariance tmp-cov)
(ros::publish "posewithcovstamped" tmp-posewithcovariancestamped)
))
(ros::publish "attention_clipper/input/pose" tmp-posestamped)
))
(defun attention-init (msg)
(let ((tmp-pose (instance geometry_msgs::Pose :init))
(tmp-pose-stamped (instance geometry_msgs::PoseStamped :init))
(header (instance std_msgs::header :init))
)
(send tmp-pose :position :x 0)
(send tmp-pose :position :y 0)
(send tmp-pose :position :z 0.2)
(send tmp-pose :orientation :x 0)
(send tmp-pose :orientation :y 0)
(send tmp-pose :orientation :z 0)
(send tmp-pose :orientation :w 1)
(send header :stamp (ros::time 0))
(send header :frame_id "/openni_rgb_optical_frame")
(send tmp-pose-stamped :pose tmp-pose)
(send tmp-pose-stamped :header header)
(ros::publish "attention_clipper/input/pose" tmp-pose-stamped)
))
(defun pub-cb (target-obj msg)
(let ()
;; remap to map-frame and store it to *mapframe-objectdetection*
(remap-to-map-frame-and-store-ObjectDetection target-obj msg)
(when *calc-kalman*
(cond
((send target-obj :stamp);;for avoiding tf error
(publish-marker target-obj *marker-life* :text-name "raw"
:obj-color (float-vector 1 0.4 0.4))
(simply-calc-covariance-and-pub-PoseStamped-and-PoseWithCovarianceStamped target-obj)
(when (null (catch-outlier target-obj)) ;; avoiding divergence by outlier
(apply-kalman-filter-to-mapframeobjectdetection)
(publish-marker target-obj *marker-life* :object-name *filtered-objectdetection*
:publish-name "filtered" :obj-color (float-vector 0.4 0.4 1)
:text-color (float-vector 0 0 1) :text-name "filtered")
(pub-PoseStamped-and-PoseWithCovarianceStamped target-obj)
))
(t
nil)
))))
(defun target-obj-cb (req)
(let ((m (send req :response))
(cds (make-coords))
(tmp-coords (instance posedetection_msgs::Object6DPose :init))
ts)
(send tmp-coords :pose :orientation :w 1)
(send tmp-coords :reliability 0.5)
(unless (boundp '*tfl*)
(setq *tfl* (instance ros::transform-listener :init)))
(unless (send *tfl* :wait-for-transform *base-frame-id* *map-id* (ros::time 0) 1)
(ros::ros-error "could not solve ~A to ~A" *base-frame-id* *map-id*))
(setq ts (send *tfl* :lookup-transform *base-frame-id* *map-id* (ros::time 0)))
(ros::ros-info "ts ~A" ts)
(send cds :reset-coords)
(cond
((and ts (send *map-frame-objectdetection* :objects))
(send cds :move-to ts :local)
(Let ((mf-obj-lst (send *map-frame-objectdetection* :objects))
(tp (send req :type)))
(dolist (obj mf-obj-lst)
(when (or (not (stringp tp))
(substringp tp (send obj :type))) ;; found target
(send cds :move-to (ros::tf-pose->coords (send obj :pose)) :local)
(send tmp-coords :pose (ros::coords->tf-pose (send cds :copy-worldcoords)))
(send tmp-coords :type (send obj :type))
(ros::ros-info "in cb tmp-coords:(~A ~A ~A)"
(send (send (send tmp-coords :pose) :position) :x)
(send (send (send tmp-coords :pose) :position) :y)
(send (send (send tmp-coords :pose) :position) :z))))))
(t
(send tmp-coords :reliability 0)
nil))
(ros::ros-info "cds:~A" (send cds :worldcoords))
(send m :object_pose tmp-coords)
(ros::ros-info "reliability:~A type:~A" (send (send m :object_pose) :reliability) (send (send m :object_pose) :type))
m))
(defun detect-switch-cb (msg)
(ros::ros-debug "detect-switch data:~A" (send msg :data))
(setq *detect-flag* (send msg :data))
(when *detect-flag*
;; reflesh
(setq *map-frame-objectdetection* (instance posedetection_msgs::ObjectDetection :init))
(send *map-frame-objectdetection* :header :frame_id *map-id*) ;; avoiding header error in rviz
))
(ros::advertise "object_detection_marker_array" visualization_msgs::MarkerArray 5)
(ros::advertise "filtered" visualization_msgs::MarkerArray 5)
(ros::advertise "outlier" visualization_msgs::MarkerArray 5)
(ros::advertise "attention_clipper/input/pose" geometry_msgs::PoseStamped 1)
(ros::advertise "posewithcovstamped" geometry_msgs::PoseWithCovarianceStamped 1)
(ros::advertise "simplecov" geometry_msgs::PoseWithCovarianceStamped 1)
(ros::advertise-service "targetobj" posedetection_msgs::TargetObj #'target-obj-cb)
(ros::subscribe "input/image" sensor_msgs::Image #'attention-init)
(ros::subscribe "input/switch" std_msgs::Bool #'detect-switch-cb)
(ros::rate 10)
(while t
(ros::spin-once)
(cond
(*detect-flag*
(ros::subscribe "input/ObjectDetection"
posedetection_msgs::ObjectDetection
#'pub-cb *target-obj*))
(t
(ros::unsubscribe detection-topic)))
(ros::sleep))
|
{
"pile_set_name": "Github"
}
|
---
layout: feature
title: 'Abbr'
shortdef: 'abbreviation'
udver: '2'
---
Boolean feature. Is this an abbreviation?
### <a name="Yes">`Yes`</a>: it is abbreviation
Examples: [sv] _<b>t.ex.</b>, <b>ca</b>_
|
{
"pile_set_name": "Github"
}
|
<HTML><HEAD>
<!-- $Id: package.html,v 1.8 2002/01/30 21:00:44 dbrownell Exp $ -->
</HEAD><BODY>
<p>
This package contains interfaces to SAX2 facilities that
conformant SAX drivers won't necessarily support.
<p>See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
for more information about SAX.</p>
<p> This package is independent of the SAX2 core, though the functionality
exposed generally needs to be implemented within a parser core.
That independence has several consequences:</p>
<ul>
<li>SAX2 drivers are <em>not</em> required to recognize these handlers.
</li>
<li>You cannot assume that the class files will be present in every SAX2
installation.</li>
<li>This package may be updated independently of SAX2 (i.e. new
handlers and classes may be added without updating SAX2 itself).</li>
<li>The new handlers are not implemented by the SAX2
<code>org.xml.sax.helpers.DefaultHandler</code> or
<code>org.xml.sax.helpers.XMLFilterImpl</code> classes.
You can subclass these if you need such behavior, or
use the helper classes found here.</li>
<li>The handlers need to be registered differently than core SAX2
handlers.</li>
</ul>
<p>This package, SAX2-ext, is a standardized extension to SAX2. It is
designed both to allow SAX parsers to pass certain types of information
to applications, and to serve as a simple model for other SAX2 parser
extension packages. Not all such extension packages should need to
be recognized directly by parsers, however.
As an example, most validation systems can be cleanly layered on top
of parsers supporting the standardized SAX2 interfaces. </p>
</BODY></HTML>
|
{
"pile_set_name": "Github"
}
|
from ruamel.yaml.scalarstring import DoubleQuotedScalarString as dss
from ..shared.namer import *
from ..shared.yml_job import YMLJob
from ..shared.constants import NPM_UPMCI_INSTALL_URL,PATH_PACKAGES_temp
class PreviewPublish_PromoteJob():
def __init__(self, agent, package, platforms, target_editor, dry_run=False):
self.job_id = pb_job_id_promote(package["name"])
self.yml = self.get_job_definition(agent, package, platforms, target_editor, dry_run).get_yml()
def get_job_definition(self, agent, package, platforms, target_editor, dry_run):
if package["publish_source"] != True:
raise Exception('Tried to promote package for which "publish_source" set to false.')
# define dependencies
dependencies = [f'{packages_filepath()}#{package_job_id_pack(package["name"])}']
if dry_run:
dependencies.append(f'{packages_filepath()}#{package_job_id_publish_dry(package["name"])}')
else:
dependencies.append(f'{packages_filepath()}#{package_job_id_publish(package["name"])}')
for platform in platforms:
dependencies.append(f'{packages_filepath()}#{package_job_id_test(package["name"], platform["os"], target_editor)}')
# construct job
job = YMLJob()
job.set_name(f'[{package["name"]}] Preview - Production Promote')
job.set_agent(agent)
job.add_var_custom('UPMCI_PROMOTION', 1)
job.add_dependencies(dependencies)
job.add_commands([
f'copy {PATH_PACKAGES_temp}\\{package["name"]}\\upm-ci~\\packages\\packages.json upm-ci~\\packages',
f'npm install upm-ci-utils@stable -g --registry {NPM_UPMCI_INSTALL_URL}',
f'upm-ci {package["type"]} promote --{package["type"]}-path {package["path"]}'])
job.add_artifacts_packages()
return job
|
{
"pile_set_name": "Github"
}
|
diff -ur u-boot-2010.03/drivers/spi/Makefile u-boot-nbg/drivers/spi/Makefile
--- u-boot-2010.03/drivers/spi/Makefile 2010-03-31 23:54:39.000000000 +0200
+++ u-boot-nbg/drivers/spi/Makefile 2010-04-15 19:31:27.000000000 +0200
@@ -25,6 +25,7 @@
LIB := $(obj)libspi.a
+COBJS-$(CONFIG_AR71XX_SPI) += ar71xx_spi.o
COBJS-$(CONFIG_ATMEL_DATAFLASH_SPI) += atmel_dataflash_spi.o
COBJS-$(CONFIG_ATMEL_SPI) += atmel_spi.o
COBJS-$(CONFIG_BFIN_SPI) += bfin_spi.o
|
{
"pile_set_name": "Github"
}
|
from .timex_constants import Constants
class TimexInference:
@staticmethod
def infer(obj):
types = set()
if TimexInference.__is_present(obj):
types.add(Constants.TIMEX_TYPES_PRESENT)
if TimexInference.__is_definite(obj):
types.add(Constants.TIMEX_TYPES_DEFINITE)
if TimexInference.__is_date(obj):
types.add(Constants.TIMEX_TYPES_DATE)
if TimexInference.__is_date_range(obj):
types.add(Constants.TIMEX_TYPES_DATERANGE)
if TimexInference.__is_duration(obj):
types.add(Constants.TIMEX_TYPES_DURATION)
if TimexInference.__is_time(obj):
types.add(Constants.TIMEX_TYPES_TIME)
if TimexInference.__is_time_range(obj):
types.add(Constants.TIMEX_TYPES_TIMERANGE)
if Constants.TIMEX_TYPES_PRESENT in types:
types.add(Constants.TIMEX_TYPES_DATE)
types.add(Constants.TIMEX_TYPES_TIME)
if Constants.TIMEX_TYPES_TIME in types and Constants.TIMEX_TYPES_DURATION in types:
types.add(Constants.TIMEX_TYPES_TIMERANGE)
if Constants.TIMEX_TYPES_DATE in types and Constants.TIMEX_TYPES_TIME in types:
types.add(Constants.TIMEX_TYPES_DATETIME)
if Constants.TIMEX_TYPES_DATE in types and Constants.TIMEX_TYPES_DURATION in types:
types.add(Constants.TIMEX_TYPES_DATERANGE)
if Constants.TIMEX_TYPES_DATETIME in types and Constants.TIMEX_TYPES_DURATION in types:
types.add(Constants.TIMEX_TYPES_DATETIMERANGE)
if Constants.TIMEX_TYPES_DATE in types and Constants.TIMEX_TYPES_TIMERANGE in types:
types.add(Constants.TIMEX_TYPES_DATETIMERANGE)
return types
@staticmethod
def __is_present(obj):
return obj.now is True
@staticmethod
def __is_duration(obj):
return (obj.years or obj.months or obj.weeks or
obj.days or obj.hours or obj.minutes or obj.seconds)
@staticmethod
def __is_time(obj):
return obj.hour is not None and obj.minute is not None and obj.second is not None
@staticmethod
def __is_date(obj):
return (obj.month is not None and obj.day_of_month is not None) or obj.day_of_week
@staticmethod
def __is_time_range(obj):
return obj.part_of_day is not None
@staticmethod
def __is_date_range(obj):
return ((obj.year is not None and obj.day_of_month is None) or
(obj.year is not None and obj.month is not None and obj.day_of_month is None) or
(obj.month is not None and obj.day_of_month is None) or
obj.season or obj.week_of_year or obj.week_of_month)
@staticmethod
def __is_definite(obj):
return obj.year is not None and obj.month is not None and obj.day_of_month is not None
|
{
"pile_set_name": "Github"
}
|
// generated by gengoos.go using 'go generate'
package sys
const GOOS = `windows`
const GoosAndroid = 0
const GoosDarwin = 0
const GoosDragonfly = 0
const GoosFreebsd = 0
const GoosLinux = 0
const GoosNacl = 0
const GoosNetbsd = 0
const GoosOpenbsd = 0
const GoosPlan9 = 0
const GoosSolaris = 0
const GoosWindows = 1
|
{
"pile_set_name": "Github"
}
|
#include <ncurses.h>
#include <stdlib.h>
#include "screen.h"
static window_t **init_windows(size_t term_height) {
// determine number of windows we want to display from terminal height
size_t line_number = term_height - 1;
const size_t height = 1, width = COLS;
window_t **windows = malloc(line_number * sizeof(window_t *));
for (size_t i = 0; i < line_number; i ++) {
windows[i] = malloc(sizeof(window_t));
windows[i]->w = newwin(height, width, i, 0);
windows[i]->r = NULL;
windows[i]->line_number = 0;
}
return windows;
}
static window_t *init_status_window(size_t term_height) {
const size_t height = 1, width = COLS;
window_t *status_window = malloc(sizeof(window_t));
status_window->w = newwin(height, width, term_height - 1, 0);
status_window->r = NULL;
status_window->line_number = 0;
return status_window;
}
static void destroy_window(window_t *w) {
delwin(w->w);
free(w);
}
static void destroy_windows(window_t **windows) {
size_t line_number = LINES - 1;
for (size_t i = 0; i < line_number; i ++) {
destroy_window(windows[i]);
}
free(windows);
}
screen_t *init_screen(size_t term_height) {
screen_t *scr = malloc(sizeof(screen_t));
scr->num_windows = term_height - 1;
scr->windows = init_windows(term_height);
scr->status_window = init_status_window(term_height);
return scr;
}
void destroy_screen(screen_t *scr) {
destroy_windows(scr->windows);
destroy_window(scr->status_window);
free(scr);
}
|
{
"pile_set_name": "Github"
}
|
// SPDX-License-Identifier: GPL-2.0
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "tests.h"
#include "session.h"
#include "debug.h"
#include "demangle-java.h"
int test__demangle_java(struct test *test __maybe_unused, int subtest __maybe_unused)
{
int ret = TEST_OK;
char *buf = NULL;
size_t i;
struct {
const char *mangled, *demangled;
} test_cases[] = {
{ "Ljava/lang/StringLatin1;equals([B[B)Z",
"boolean java.lang.StringLatin1.equals(byte[], byte[])" },
{ "Ljava/util/zip/ZipUtils;CENSIZ([BI)J",
"long java.util.zip.ZipUtils.CENSIZ(byte[], int)" },
{ "Ljava/util/regex/Pattern$BmpCharProperty;match(Ljava/util/regex/Matcher;ILjava/lang/CharSequence;)Z",
"boolean java.util.regex.Pattern$BmpCharProperty.match(java.util.regex.Matcher, int, java.lang.CharSequence)" },
{ "Ljava/lang/AbstractStringBuilder;appendChars(Ljava/lang/String;II)V",
"void java.lang.AbstractStringBuilder.appendChars(java.lang.String, int, int)" },
{ "Ljava/lang/Object;<init>()V",
"void java.lang.Object<init>()" },
};
for (i = 0; i < sizeof(test_cases) / sizeof(test_cases[0]); i++) {
buf = java_demangle_sym(test_cases[i].mangled, 0);
if (strcmp(buf, test_cases[i].demangled)) {
pr_debug("FAILED: %s: %s != %s\n", test_cases[i].mangled,
buf, test_cases[i].demangled);
ret = TEST_FAIL;
}
free(buf);
}
return ret;
}
|
{
"pile_set_name": "Github"
}
|
[
{
"Unit": "CPU-M-CF",
"EventCode": "64",
"EventName": "PRNG_FUNCTIONS",
"BriefDescription": "PRNG Functions",
"PublicDescription": "Total number of the PRNG functions issued by the CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "65",
"EventName": "PRNG_CYCLES",
"BriefDescription": "PRNG Cycles",
"PublicDescription": "Total number of CPU cycles when the DEA/AES coprocessor is busy performing PRNG functions issued by the CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "66",
"EventName": "PRNG_BLOCKED_FUNCTIONS",
"BriefDescription": "PRNG Blocked Functions",
"PublicDescription": "Total number of the PRNG functions that are issued by the CPU and are blocked because the DEA/AES coprocessor is busy performing a function issued by another CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "67",
"EventName": "PRNG_BLOCKED_CYCLES",
"BriefDescription": "PRNG Blocked Cycles",
"PublicDescription": "Total number of CPU cycles blocked for the PRNG functions issued by the CPU because the DEA/AES coprocessor is busy performing a function issued by another CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "68",
"EventName": "SHA_FUNCTIONS",
"BriefDescription": "SHA Functions",
"PublicDescription": "Total number of SHA functions issued by the CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "69",
"EventName": "SHA_CYCLES",
"BriefDescription": "SHA Cycles",
"PublicDescription": "Total number of CPU cycles when the SHA coprocessor is busy performing the SHA functions issued by the CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "70",
"EventName": "SHA_BLOCKED_FUNCTIONS",
"BriefDescription": "SHA Blocked Functions",
"PublicDescription": "Total number of the SHA functions that are issued by the CPU and are blocked because the SHA coprocessor is busy performing a function issued by another CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "71",
"EventName": "SHA_BLOCKED_CYCLES",
"BriefDescription": "SHA Bloced Cycles",
"PublicDescription": "Total number of CPU cycles blocked for the SHA functions issued by the CPU because the SHA coprocessor is busy performing a function issued by another CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "72",
"EventName": "DEA_FUNCTIONS",
"BriefDescription": "DEA Functions",
"PublicDescription": "Total number of the DEA functions issued by the CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "73",
"EventName": "DEA_CYCLES",
"BriefDescription": "DEA Cycles",
"PublicDescription": "Total number of CPU cycles when the DEA/AES coprocessor is busy performing the DEA functions issued by the CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "74",
"EventName": "DEA_BLOCKED_FUNCTIONS",
"BriefDescription": "DEA Blocked Functions",
"PublicDescription": "Total number of the DEA functions that are issued by the CPU and are blocked because the DEA/AES coprocessor is busy performing a function issued by another CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "75",
"EventName": "DEA_BLOCKED_CYCLES",
"BriefDescription": "DEA Blocked Cycles",
"PublicDescription": "Total number of CPU cycles blocked for the DEA functions issued by the CPU because the DEA/AES coprocessor is busy performing a function issued by another CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "76",
"EventName": "AES_FUNCTIONS",
"BriefDescription": "AES Functions",
"PublicDescription": "Total number of AES functions issued by the CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "77",
"EventName": "AES_CYCLES",
"BriefDescription": "AES Cycles",
"PublicDescription": "Total number of CPU cycles when the DEA/AES coprocessor is busy performing the AES functions issued by the CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "78",
"EventName": "AES_BLOCKED_FUNCTIONS",
"BriefDescription": "AES Blocked Functions",
"PublicDescription": "Total number of AES functions that are issued by the CPU and are blocked because the DEA/AES coprocessor is busy performing a function issued by another CPU"
},
{
"Unit": "CPU-M-CF",
"EventCode": "79",
"EventName": "AES_BLOCKED_CYCLES",
"BriefDescription": "AES Blocked Cycles",
"PublicDescription": "Total number of CPU cycles blocked for the AES functions issued by the CPU because the DEA/AES coprocessor is busy performing a function issued by another CPU"
},
]
|
{
"pile_set_name": "Github"
}
|
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28010.2048
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NavigationParticipation", "NavigationParticipation\NavigationParticipation.csproj", "{99C9E82C-C594-446D-AA59-8FFBC43AD226}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModuleA", "ModuleA\ModuleA.csproj", "{AB8B448C-DD74-4D60-A041-3E5D03A32180}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{99C9E82C-C594-446D-AA59-8FFBC43AD226}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{99C9E82C-C594-446D-AA59-8FFBC43AD226}.Debug|Any CPU.Build.0 = Debug|Any CPU
{99C9E82C-C594-446D-AA59-8FFBC43AD226}.Release|Any CPU.ActiveCfg = Release|Any CPU
{99C9E82C-C594-446D-AA59-8FFBC43AD226}.Release|Any CPU.Build.0 = Release|Any CPU
{AB8B448C-DD74-4D60-A041-3E5D03A32180}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB8B448C-DD74-4D60-A041-3E5D03A32180}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB8B448C-DD74-4D60-A041-3E5D03A32180}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AB8B448C-DD74-4D60-A041-3E5D03A32180}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
|
{
"pile_set_name": "Github"
}
|
//! Computations on places -- field projections, going from mir::Place, and writing
//! into a place.
//! All high-level functions to write to memory work on places as destinations.
use std::convert::TryFrom;
use std::hash::Hash;
use rustc_macros::HashStable;
use rustc_middle::mir;
use rustc_middle::ty::layout::{PrimitiveExt, TyAndLayout};
use rustc_middle::ty::{self, Ty};
use rustc_target::abi::{Abi, Align, FieldsShape, TagEncoding};
use rustc_target::abi::{HasDataLayout, LayoutOf, Size, VariantIdx, Variants};
use super::{
mir_assign_valid_types, truncate, AllocId, AllocMap, Allocation, AllocationExtra, ConstAlloc,
ImmTy, Immediate, InterpCx, InterpResult, LocalValue, Machine, MemoryKind, OpTy, Operand,
Pointer, PointerArithmetic, Scalar, ScalarMaybeUninit,
};
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
/// Information required for the sound usage of a `MemPlace`.
pub enum MemPlaceMeta<Tag = ()> {
/// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
Meta(Scalar<Tag>),
/// `Sized` types or unsized `extern type`
None,
/// The address of this place may not be taken. This protects the `MemPlace` from coming from
/// a ZST Operand without a backing allocation and being converted to an integer address. This
/// should be impossible, because you can't take the address of an operand, but this is a second
/// protection layer ensuring that we don't mess up.
Poison,
}
impl<Tag> MemPlaceMeta<Tag> {
pub fn unwrap_meta(self) -> Scalar<Tag> {
match self {
Self::Meta(s) => s,
Self::None | Self::Poison => {
bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
}
}
}
fn has_meta(self) -> bool {
match self {
Self::Meta(_) => true,
Self::None | Self::Poison => false,
}
}
pub fn erase_tag(self) -> MemPlaceMeta<()> {
match self {
Self::Meta(s) => MemPlaceMeta::Meta(s.erase_tag()),
Self::None => MemPlaceMeta::None,
Self::Poison => MemPlaceMeta::Poison,
}
}
}
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
pub struct MemPlace<Tag = ()> {
/// A place may have an integral pointer for ZSTs, and since it might
/// be turned back into a reference before ever being dereferenced.
/// However, it may never be uninit.
pub ptr: Scalar<Tag>,
pub align: Align,
/// Metadata for unsized places. Interpretation is up to the type.
/// Must not be present for sized types, but can be missing for unsized types
/// (e.g., `extern type`).
pub meta: MemPlaceMeta<Tag>,
}
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
pub enum Place<Tag = ()> {
/// A place referring to a value allocated in the `Memory` system.
Ptr(MemPlace<Tag>),
/// To support alloc-free locals, we are able to write directly to a local.
/// (Without that optimization, we'd just always be a `MemPlace`.)
Local { frame: usize, local: mir::Local },
}
#[derive(Copy, Clone, Debug)]
pub struct PlaceTy<'tcx, Tag = ()> {
place: Place<Tag>, // Keep this private; it helps enforce invariants.
pub layout: TyAndLayout<'tcx>,
}
impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
type Target = Place<Tag>;
#[inline(always)]
fn deref(&self) -> &Place<Tag> {
&self.place
}
}
/// A MemPlace with its layout. Constructing it is only possible in this module.
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub struct MPlaceTy<'tcx, Tag = ()> {
mplace: MemPlace<Tag>,
pub layout: TyAndLayout<'tcx>,
}
impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
type Target = MemPlace<Tag>;
#[inline(always)]
fn deref(&self) -> &MemPlace<Tag> {
&self.mplace
}
}
impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
#[inline(always)]
fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
}
}
impl<Tag> MemPlace<Tag> {
/// Replace ptr tag, maintain vtable tag (if any)
#[inline]
pub fn replace_tag(self, new_tag: Tag) -> Self {
MemPlace { ptr: self.ptr.erase_tag().with_tag(new_tag), align: self.align, meta: self.meta }
}
#[inline]
pub fn erase_tag(self) -> MemPlace {
MemPlace { ptr: self.ptr.erase_tag(), align: self.align, meta: self.meta.erase_tag() }
}
#[inline(always)]
fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
MemPlace { ptr, align, meta: MemPlaceMeta::None }
}
#[inline(always)]
pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
Self::from_scalar_ptr(ptr.into(), align)
}
/// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
/// This is the inverse of `ref_to_mplace`.
#[inline(always)]
pub fn to_ref(self) -> Immediate<Tag> {
match self.meta {
MemPlaceMeta::None => Immediate::Scalar(self.ptr.into()),
MemPlaceMeta::Meta(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
MemPlaceMeta::Poison => bug!(
"MPlaceTy::dangling may never be used to produce a \
place that will have the address of its pointee taken"
),
}
}
pub fn offset(
self,
offset: Size,
meta: MemPlaceMeta<Tag>,
cx: &impl HasDataLayout,
) -> InterpResult<'tcx, Self> {
Ok(MemPlace {
ptr: self.ptr.ptr_offset(offset, cx)?,
align: self.align.restrict_for_offset(offset),
meta,
})
}
}
impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
/// Produces a MemPlace that works for ZST but nothing else
#[inline]
pub fn dangling(layout: TyAndLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
let align = layout.align.abi;
let ptr = Scalar::from_machine_usize(align.bytes(), cx);
// `Poison` this to make sure that the pointer value `ptr` is never observable by the program.
MPlaceTy { mplace: MemPlace { ptr, align, meta: MemPlaceMeta::Poison }, layout }
}
/// Replace ptr tag, maintain vtable tag (if any)
#[inline]
pub fn replace_tag(self, new_tag: Tag) -> Self {
MPlaceTy { mplace: self.mplace.replace_tag(new_tag), layout: self.layout }
}
#[inline]
pub fn offset(
self,
offset: Size,
meta: MemPlaceMeta<Tag>,
layout: TyAndLayout<'tcx>,
cx: &impl HasDataLayout,
) -> InterpResult<'tcx, Self> {
Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
}
#[inline]
fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyAndLayout<'tcx>) -> Self {
MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
}
#[inline]
pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
if self.layout.is_unsized() {
// We need to consult `meta` metadata
match self.layout.ty.kind() {
ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx),
_ => bug!("len not supported on unsized type {:?}", self.layout.ty),
}
} else {
// Go through the layout. There are lots of types that support a length,
// e.g., SIMD types.
match self.layout.fields {
FieldsShape::Array { count, .. } => Ok(count),
_ => bug!("len not supported on sized type {:?}", self.layout.ty),
}
}
}
#[inline]
pub(super) fn vtable(self) -> Scalar<Tag> {
match self.layout.ty.kind() {
ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
_ => bug!("vtable not supported on type {:?}", self.layout.ty),
}
}
}
// These are defined here because they produce a place.
impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
#[inline(always)]
/// Note: do not call `as_ref` on the resulting place. This function should only be used to
/// read from the resulting mplace, not to get its address back.
pub fn try_as_mplace(
self,
cx: &impl HasDataLayout,
) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
match *self {
Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
Operand::Immediate(_) if self.layout.is_zst() => {
Ok(MPlaceTy::dangling(self.layout, cx))
}
Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)),
}
}
#[inline(always)]
/// Note: do not call `as_ref` on the resulting place. This function should only be used to
/// read from the resulting mplace, not to get its address back.
pub fn assert_mem_place(self, cx: &impl HasDataLayout) -> MPlaceTy<'tcx, Tag> {
self.try_as_mplace(cx).unwrap()
}
}
impl<Tag: ::std::fmt::Debug> Place<Tag> {
#[inline]
pub fn assert_mem_place(self) -> MemPlace<Tag> {
match self {
Place::Ptr(mplace) => mplace,
_ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
}
}
}
impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
#[inline]
pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
}
}
// separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
impl<'mir, 'tcx: 'mir, Tag, M> InterpCx<'mir, 'tcx, M>
where
// FIXME: Working around https://github.com/rust-lang/rust/issues/54385
Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
M: Machine<'mir, 'tcx, PointerTag = Tag>,
// FIXME: Working around https://github.com/rust-lang/rust/issues/24159
M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKind>, Allocation<Tag, M::AllocExtra>)>,
M::AllocExtra: AllocationExtra<Tag>,
{
/// Take a value, which represents a (thin or wide) reference, and make it a place.
/// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
///
/// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
/// want to ever use the place for memory access!
/// Generally prefer `deref_operand`.
pub fn ref_to_mplace(
&self,
val: ImmTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
let pointee_type =
val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
let layout = self.layout_of(pointee_type)?;
let (ptr, meta) = match *val {
Immediate::Scalar(ptr) => (ptr.check_init()?, MemPlaceMeta::None),
Immediate::ScalarPair(ptr, meta) => {
(ptr.check_init()?, MemPlaceMeta::Meta(meta.check_init()?))
}
};
let mplace = MemPlace {
ptr,
// We could use the run-time alignment here. For now, we do not, because
// the point of tracking the alignment here is to make sure that the *static*
// alignment information emitted with the loads is correct. The run-time
// alignment can only be more restrictive.
align: layout.align.abi,
meta,
};
Ok(MPlaceTy { mplace, layout })
}
/// Take an operand, representing a pointer, and dereference it to a place -- that
/// will always be a MemPlace. Lives in `place.rs` because it creates a place.
pub fn deref_operand(
&self,
src: OpTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
let val = self.read_immediate(src)?;
trace!("deref to {} on {:?}", val.layout.ty, *val);
let place = self.ref_to_mplace(val)?;
self.mplace_access_checked(place, None)
}
/// Check if the given place is good for memory access with the given
/// size, falling back to the layout's size if `None` (in the latter case,
/// this must be a statically sized type).
///
/// On success, returns `None` for zero-sized accesses (where nothing else is
/// left to do) and a `Pointer` to use for the actual access otherwise.
#[inline]
pub(super) fn check_mplace_access(
&self,
place: MPlaceTy<'tcx, M::PointerTag>,
size: Option<Size>,
) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
let size = size.unwrap_or_else(|| {
assert!(!place.layout.is_unsized());
assert!(!place.meta.has_meta());
place.layout.size
});
self.memory.check_ptr_access(place.ptr, size, place.align)
}
/// Return the "access-checked" version of this `MPlace`, where for non-ZST
/// this is definitely a `Pointer`.
///
/// `force_align` must only be used when correct alignment does not matter,
/// like in Stacked Borrows.
pub fn mplace_access_checked(
&self,
mut place: MPlaceTy<'tcx, M::PointerTag>,
force_align: Option<Align>,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
let (size, align) = self
.size_and_align_of_mplace(place)?
.unwrap_or((place.layout.size, place.layout.align.abi));
assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
// Check (stricter) dynamic alignment, unless forced otherwise.
place.mplace.align = force_align.unwrap_or(align);
// When dereferencing a pointer, it must be non-NULL, aligned, and live.
if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
place.mplace.ptr = ptr.into();
}
Ok(place)
}
/// Force `place.ptr` to a `Pointer`.
/// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
pub(super) fn force_mplace_ptr(
&self,
mut place: MPlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
Ok(place)
}
/// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is
/// always possible without allocating, so it can take `&self`. Also return the field's layout.
/// This supports both struct and array fields.
///
/// This also works for arrays, but then the `usize` index type is restricting.
/// For indexing into arrays, use `mplace_index`.
#[inline(always)]
pub fn mplace_field(
&self,
base: MPlaceTy<'tcx, M::PointerTag>,
field: usize,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
let offset = base.layout.fields.offset(field);
let field_layout = base.layout.field(self, field)?;
// Offset may need adjustment for unsized fields.
let (meta, offset) = if field_layout.is_unsized() {
// Re-use parent metadata to determine dynamic field layout.
// With custom DSTS, this *will* execute user-defined code, but the same
// happens at run-time so that's okay.
let align = match self.size_and_align_of(base.meta, field_layout)? {
Some((_, align)) => align,
None if offset == Size::ZERO => {
// An extern type at offset 0, we fall back to its static alignment.
// FIXME: Once we have made decisions for how to handle size and alignment
// of `extern type`, this should be adapted. It is just a temporary hack
// to get some code to work that probably ought to work.
field_layout.align.abi
}
None => span_bug!(
self.cur_span(),
"cannot compute offset for extern type field at non-0 offset"
),
};
(base.meta, offset.align_to(align))
} else {
// base.meta could be present; we might be accessing a sized field of an unsized
// struct.
(MemPlaceMeta::None, offset)
};
// We do not look at `base.layout.align` nor `field_layout.align`, unlike
// codegen -- mostly to see if we can get away with that
base.offset(offset, meta, field_layout, self)
}
/// Index into an array.
#[inline(always)]
pub fn mplace_index(
&self,
base: MPlaceTy<'tcx, M::PointerTag>,
index: u64,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
// Not using the layout method because we want to compute on u64
match base.layout.fields {
FieldsShape::Array { stride, .. } => {
let len = base.len(self)?;
if index >= len {
// This can only be reached in ConstProp and non-rustc-MIR.
throw_ub!(BoundsCheckFailed { len, index });
}
let offset = stride * index; // `Size` multiplication
// All fields have the same layout.
let field_layout = base.layout.field(self, 0)?;
assert!(!field_layout.is_unsized());
base.offset(offset, MemPlaceMeta::None, field_layout, self)
}
_ => span_bug!(
self.cur_span(),
"`mplace_index` called on non-array type {:?}",
base.layout.ty
),
}
}
// Iterates over all fields of an array. Much more efficient than doing the
// same by repeatedly calling `mplace_array`.
pub(super) fn mplace_array_fields(
&self,
base: MPlaceTy<'tcx, Tag>,
) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
{
let len = base.len(self)?; // also asserts that we have a type where this makes sense
let stride = match base.layout.fields {
FieldsShape::Array { stride, .. } => stride,
_ => span_bug!(self.cur_span(), "mplace_array_fields: expected an array layout"),
};
let layout = base.layout.field(self, 0)?;
let dl = &self.tcx.data_layout;
// `Size` multiplication
Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl)))
}
fn mplace_subslice(
&self,
base: MPlaceTy<'tcx, M::PointerTag>,
from: u64,
to: u64,
from_end: bool,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
let len = base.len(self)?; // also asserts that we have a type where this makes sense
let actual_to = if from_end {
if from.checked_add(to).map_or(true, |to| to > len) {
// This can only be reached in ConstProp and non-rustc-MIR.
throw_ub!(BoundsCheckFailed { len: len, index: from.saturating_add(to) });
}
len.checked_sub(to).unwrap()
} else {
to
};
// Not using layout method because that works with usize, and does not work with slices
// (that have count 0 in their layout).
let from_offset = match base.layout.fields {
FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked
_ => {
span_bug!(self.cur_span(), "unexpected layout of index access: {:#?}", base.layout)
}
};
// Compute meta and new layout
let inner_len = actual_to.checked_sub(from).unwrap();
let (meta, ty) = match base.layout.ty.kind() {
// It is not nice to match on the type, but that seems to be the only way to
// implement this.
ty::Array(inner, _) => (MemPlaceMeta::None, self.tcx.mk_array(inner, inner_len)),
ty::Slice(..) => {
let len = Scalar::from_machine_usize(inner_len, self);
(MemPlaceMeta::Meta(len), base.layout.ty)
}
_ => {
span_bug!(self.cur_span(), "cannot subslice non-array type: `{:?}`", base.layout.ty)
}
};
let layout = self.layout_of(ty)?;
base.offset(from_offset, meta, layout, self)
}
pub(super) fn mplace_downcast(
&self,
base: MPlaceTy<'tcx, M::PointerTag>,
variant: VariantIdx,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
// Downcasts only change the layout
assert!(!base.meta.has_meta());
Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
}
/// Project into an mplace
pub(super) fn mplace_projection(
&self,
base: MPlaceTy<'tcx, M::PointerTag>,
proj_elem: mir::PlaceElem<'tcx>,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
use rustc_middle::mir::ProjectionElem::*;
Ok(match proj_elem {
Field(field, _) => self.mplace_field(base, field.index())?,
Downcast(_, variant) => self.mplace_downcast(base, variant)?,
Deref => self.deref_operand(base.into())?,
Index(local) => {
let layout = self.layout_of(self.tcx.types.usize)?;
let n = self.access_local(self.frame(), local, Some(layout))?;
let n = self.read_scalar(n)?;
let n = u64::try_from(
self.force_bits(n.check_init()?, self.tcx.data_layout.pointer_size)?,
)
.unwrap();
self.mplace_index(base, n)?
}
ConstantIndex { offset, min_length, from_end } => {
let n = base.len(self)?;
if n < min_length {
// This can only be reached in ConstProp and non-rustc-MIR.
throw_ub!(BoundsCheckFailed { len: min_length, index: n });
}
let index = if from_end {
assert!(0 < offset && offset <= min_length);
n.checked_sub(offset).unwrap()
} else {
assert!(offset < min_length);
offset
};
self.mplace_index(base, index)?
}
Subslice { from, to, from_end } => self.mplace_subslice(base, from, to, from_end)?,
})
}
/// Gets the place of a field inside the place, and also the field's type.
/// Just a convenience function, but used quite a bit.
/// This is the only projection that might have a side-effect: We cannot project
/// into the field of a local `ScalarPair`, we have to first allocate it.
pub fn place_field(
&mut self,
base: PlaceTy<'tcx, M::PointerTag>,
field: usize,
) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
// FIXME: We could try to be smarter and avoid allocation for fields that span the
// entire place.
let mplace = self.force_allocation(base)?;
Ok(self.mplace_field(mplace, field)?.into())
}
pub fn place_index(
&mut self,
base: PlaceTy<'tcx, M::PointerTag>,
index: u64,
) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
let mplace = self.force_allocation(base)?;
Ok(self.mplace_index(mplace, index)?.into())
}
pub fn place_downcast(
&self,
base: PlaceTy<'tcx, M::PointerTag>,
variant: VariantIdx,
) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
// Downcast just changes the layout
Ok(match base.place {
Place::Ptr(mplace) => {
self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into()
}
Place::Local { .. } => {
let layout = base.layout.for_variant(self, variant);
PlaceTy { layout, ..base }
}
})
}
/// Projects into a place.
pub fn place_projection(
&mut self,
base: PlaceTy<'tcx, M::PointerTag>,
&proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
use rustc_middle::mir::ProjectionElem::*;
Ok(match proj_elem {
Field(field, _) => self.place_field(base, field.index())?,
Downcast(_, variant) => self.place_downcast(base, variant)?,
Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
// For the other variants, we have to force an allocation.
// This matches `operand_projection`.
Subslice { .. } | ConstantIndex { .. } | Index(_) => {
let mplace = self.force_allocation(base)?;
self.mplace_projection(mplace, proj_elem)?.into()
}
})
}
/// Computes a place. You should only use this if you intend to write into this
/// place; for reading, a more efficient alternative is `eval_place_for_read`.
pub fn eval_place(
&mut self,
place: mir::Place<'tcx>,
) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
let mut place_ty = PlaceTy {
// This works even for dead/uninitialized locals; we check further when writing
place: Place::Local { frame: self.frame_idx(), local: place.local },
layout: self.layout_of_local(self.frame(), place.local, None)?,
};
for elem in place.projection.iter() {
place_ty = self.place_projection(place_ty, &elem)?
}
trace!("{:?}", self.dump_place(place_ty.place));
// Sanity-check the type we ended up with.
debug_assert!(mir_assign_valid_types(
*self.tcx,
self.param_env,
self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
place.ty(&self.frame().body.local_decls, *self.tcx).ty
))?,
place_ty.layout,
));
Ok(place_ty)
}
/// Write a scalar to a place
#[inline(always)]
pub fn write_scalar(
&mut self,
val: impl Into<ScalarMaybeUninit<M::PointerTag>>,
dest: PlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
self.write_immediate(Immediate::Scalar(val.into()), dest)
}
/// Write an immediate to a place
#[inline(always)]
pub fn write_immediate(
&mut self,
src: Immediate<M::PointerTag>,
dest: PlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
self.write_immediate_no_validate(src, dest)?;
if M::enforce_validity(self) {
// Data got changed, better make sure it matches the type!
self.validate_operand(self.place_to_op(dest)?)?;
}
Ok(())
}
/// Write an `Immediate` to memory.
#[inline(always)]
pub fn write_immediate_to_mplace(
&mut self,
src: Immediate<M::PointerTag>,
dest: MPlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
self.write_immediate_to_mplace_no_validate(src, dest)?;
if M::enforce_validity(self) {
// Data got changed, better make sure it matches the type!
self.validate_operand(dest.into())?;
}
Ok(())
}
/// Write an immediate to a place.
/// If you use this you are responsible for validating that things got copied at the
/// right type.
fn write_immediate_no_validate(
&mut self,
src: Immediate<M::PointerTag>,
dest: PlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
if cfg!(debug_assertions) {
// This is a very common path, avoid some checks in release mode
assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
match src {
Immediate::Scalar(ScalarMaybeUninit::Scalar(Scalar::Ptr(_))) => assert_eq!(
self.pointer_size(),
dest.layout.size,
"Size mismatch when writing pointer"
),
Immediate::Scalar(ScalarMaybeUninit::Scalar(Scalar::Raw { size, .. })) => {
assert_eq!(
Size::from_bytes(size),
dest.layout.size,
"Size mismatch when writing bits"
)
}
Immediate::Scalar(ScalarMaybeUninit::Uninit) => {} // uninit can have any size
Immediate::ScalarPair(_, _) => {
// FIXME: Can we check anything here?
}
}
}
trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
// See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
// but not factored as a separate function.
let mplace = match dest.place {
Place::Local { frame, local } => {
match M::access_local_mut(self, frame, local)? {
Ok(local) => {
// Local can be updated in-place.
*local = LocalValue::Live(Operand::Immediate(src));
return Ok(());
}
Err(mplace) => {
// The local is in memory, go on below.
mplace
}
}
}
Place::Ptr(mplace) => mplace, // already referring to memory
};
let dest = MPlaceTy { mplace, layout: dest.layout };
// This is already in memory, write there.
self.write_immediate_to_mplace_no_validate(src, dest)
}
/// Write an immediate to memory.
/// If you use this you are responsible for validating that things got copied at the
/// right type.
fn write_immediate_to_mplace_no_validate(
&mut self,
value: Immediate<M::PointerTag>,
dest: MPlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
// Note that it is really important that the type here is the right one, and matches the
// type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
// to handle padding properly, which is only correct if we never look at this data with the
// wrong type.
// Invalid places are a thing: the return place of a diverging function
let ptr = match self.check_mplace_access(dest, None)? {
Some(ptr) => ptr,
None => return Ok(()), // zero-sized access
};
let tcx = *self.tcx;
// FIXME: We should check that there are dest.layout.size many bytes available in
// memory. The code below is not sufficient, with enough padding it might not
// cover all the bytes!
match value {
Immediate::Scalar(scalar) => {
match dest.layout.abi {
Abi::Scalar(_) => {} // fine
_ => span_bug!(
self.cur_span(),
"write_immediate_to_mplace: invalid Scalar layout: {:#?}",
dest.layout
),
}
self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
&tcx,
ptr,
scalar,
dest.layout.size,
)
}
Immediate::ScalarPair(a_val, b_val) => {
// We checked `ptr_align` above, so all fields will have the alignment they need.
// We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
// which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
let (a, b) = match dest.layout.abi {
Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
_ => span_bug!(
self.cur_span(),
"write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
dest.layout
),
};
let (a_size, b_size) = (a.size(self), b.size(self));
let b_offset = a_size.align_to(b.align(self).abi);
let b_ptr = ptr.offset(b_offset, self)?;
// It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
// but that does not work: We could be a newtype around a pair, then the
// fields do not match the `ScalarPair` components.
self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(&tcx, ptr, a_val, a_size)?;
self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(&tcx, b_ptr, b_val, b_size)
}
}
}
/// Copies the data from an operand to a place. This does not support transmuting!
/// Use `copy_op_transmute` if the layouts could disagree.
#[inline(always)]
pub fn copy_op(
&mut self,
src: OpTy<'tcx, M::PointerTag>,
dest: PlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
self.copy_op_no_validate(src, dest)?;
if M::enforce_validity(self) {
// Data got changed, better make sure it matches the type!
self.validate_operand(self.place_to_op(dest)?)?;
}
Ok(())
}
/// Copies the data from an operand to a place. This does not support transmuting!
/// Use `copy_op_transmute` if the layouts could disagree.
/// Also, if you use this you are responsible for validating that things get copied at the
/// right type.
fn copy_op_no_validate(
&mut self,
src: OpTy<'tcx, M::PointerTag>,
dest: PlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
// We do NOT compare the types for equality, because well-typed code can
// actually "transmute" `&mut T` to `&T` in an assignment without a cast.
if !mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) {
span_bug!(
self.cur_span(),
"type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
src.layout.ty,
dest.layout.ty,
);
}
// Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
let src = match self.try_read_immediate(src)? {
Ok(src_val) => {
assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
// Yay, we got a value that we can write directly.
// FIXME: Add a check to make sure that if `src` is indirect,
// it does not overlap with `dest`.
return self.write_immediate_no_validate(*src_val, dest);
}
Err(mplace) => mplace,
};
// Slow path, this does not fit into an immediate. Just memcpy.
trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
// This interprets `src.meta` with the `dest` local's layout, if an unsized local
// is being initialized!
let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
let size = size.unwrap_or_else(|| {
assert!(
!dest.layout.is_unsized(),
"Cannot copy into already initialized unsized place"
);
dest.layout.size
});
assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
let src = self
.check_mplace_access(src, Some(size))
.expect("places should be checked on creation");
let dest = self
.check_mplace_access(dest, Some(size))
.expect("places should be checked on creation");
let (src_ptr, dest_ptr) = match (src, dest) {
(Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
(None, None) => return Ok(()), // zero-sized copy
_ => bug!("The pointers should both be Some or both None"),
};
self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
}
/// Copies the data from an operand to a place. The layouts may disagree, but they must
/// have the same size.
pub fn copy_op_transmute(
&mut self,
src: OpTy<'tcx, M::PointerTag>,
dest: PlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
if mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) {
// Fast path: Just use normal `copy_op`
return self.copy_op(src, dest);
}
// We still require the sizes to match.
if src.layout.size != dest.layout.size {
// FIXME: This should be an assert instead of an error, but if we transmute within an
// array length computation, `typeck` may not have yet been run and errored out. In fact
// most likey we *are* running `typeck` right now. Investigate whether we can bail out
// on `typeck_results().has_errors` at all const eval entry points.
debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
self.tcx.sess.delay_span_bug(
self.cur_span(),
"size-changing transmute, should have been caught by transmute checking",
);
throw_inval!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
}
// Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
// to avoid that here.
assert!(
!src.layout.is_unsized() && !dest.layout.is_unsized(),
"Cannot transmute unsized data"
);
// The hard case is `ScalarPair`. `src` is already read from memory in this case,
// using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
// We have to write them to `dest` at the offsets they were *read at*, which is
// not necessarily the same as the offsets in `dest.layout`!
// Hence we do the copy with the source layout on both sides. We also make sure to write
// into memory, because if `dest` is a local we would not even have a way to write
// at the `src` offsets; the fact that we came from a different layout would
// just be lost.
let dest = self.force_allocation(dest)?;
self.copy_op_no_validate(
src,
PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
)?;
if M::enforce_validity(self) {
// Data got changed, better make sure it matches the type!
self.validate_operand(dest.into())?;
}
Ok(())
}
/// Ensures that a place is in memory, and returns where it is.
/// If the place currently refers to a local that doesn't yet have a matching allocation,
/// create such an allocation.
/// This is essentially `force_to_memplace`.
///
/// This supports unsized types and returns the computed size to avoid some
/// redundant computation when copying; use `force_allocation` for a simpler, sized-only
/// version.
pub fn force_allocation_maybe_sized(
&mut self,
place: PlaceTy<'tcx, M::PointerTag>,
meta: MemPlaceMeta<M::PointerTag>,
) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
let (mplace, size) = match place.place {
Place::Local { frame, local } => {
match M::access_local_mut(self, frame, local)? {
Ok(&mut local_val) => {
// We need to make an allocation.
// We need the layout of the local. We can NOT use the layout we got,
// that might e.g., be an inner field of a struct with `Scalar` layout,
// that has different alignment than the outer field.
let local_layout =
self.layout_of_local(&self.stack()[frame], local, None)?;
// We also need to support unsized types, and hence cannot use `allocate`.
let (size, align) = self
.size_and_align_of(meta, local_layout)?
.expect("Cannot allocate for non-dyn-sized type");
let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
let mplace = MemPlace { ptr: ptr.into(), align, meta };
if let LocalValue::Live(Operand::Immediate(value)) = local_val {
// Preserve old value.
// We don't have to validate as we can assume the local
// was already valid for its type.
let mplace = MPlaceTy { mplace, layout: local_layout };
self.write_immediate_to_mplace_no_validate(value, mplace)?;
}
// Now we can call `access_mut` again, asserting it goes well,
// and actually overwrite things.
*M::access_local_mut(self, frame, local).unwrap().unwrap() =
LocalValue::Live(Operand::Indirect(mplace));
(mplace, Some(size))
}
Err(mplace) => (mplace, None), // this already was an indirect local
}
}
Place::Ptr(mplace) => (mplace, None),
};
// Return with the original layout, so that the caller can go on
Ok((MPlaceTy { mplace, layout: place.layout }, size))
}
#[inline(always)]
pub fn force_allocation(
&mut self,
place: PlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0)
}
pub fn allocate(
&mut self,
layout: TyAndLayout<'tcx>,
kind: MemoryKind<M::MemoryKind>,
) -> MPlaceTy<'tcx, M::PointerTag> {
let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
MPlaceTy::from_aligned_ptr(ptr, layout)
}
/// Returns a wide MPlace.
pub fn allocate_str(
&mut self,
str: &str,
kind: MemoryKind<M::MemoryKind>,
) -> MPlaceTy<'tcx, M::PointerTag> {
let ptr = self.memory.allocate_bytes(str.as_bytes(), kind);
let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
let mplace = MemPlace {
ptr: ptr.into(),
align: Align::from_bytes(1).unwrap(),
meta: MemPlaceMeta::Meta(meta),
};
let layout = self.layout_of(self.tcx.mk_static_str()).unwrap();
MPlaceTy { mplace, layout }
}
/// Writes the discriminant of the given variant.
pub fn write_discriminant(
&mut self,
variant_index: VariantIdx,
dest: PlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
// Layout computation excludes uninhabited variants from consideration
// therefore there's no way to represent those variants in the given layout.
if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
throw_ub!(Unreachable);
}
match dest.layout.variants {
Variants::Single { index } => {
assert_eq!(index, variant_index);
}
Variants::Multiple {
tag_encoding: TagEncoding::Direct,
tag: ref tag_layout,
tag_field,
..
} => {
// No need to validate that the discriminant here because the
// `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
let discr_val =
dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
// raw discriminants for enums are isize or bigger during
// their computation, but the in-memory tag is the smallest possible
// representation
let size = tag_layout.value.size(self);
let tag_val = truncate(discr_val, size);
let tag_dest = self.place_field(dest, tag_field)?;
self.write_scalar(Scalar::from_uint(tag_val, size), tag_dest)?;
}
Variants::Multiple {
tag_encoding:
TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start },
tag: ref tag_layout,
tag_field,
..
} => {
// No need to validate that the discriminant here because the
// `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
if variant_index != dataful_variant {
let variants_start = niche_variants.start().as_u32();
let variant_index_relative = variant_index
.as_u32()
.checked_sub(variants_start)
.expect("overflow computing relative variant idx");
// We need to use machine arithmetic when taking into account `niche_start`:
// tag_val = variant_index_relative + niche_start_val
let tag_layout = self.layout_of(tag_layout.value.to_int_ty(*self.tcx))?;
let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
let variant_index_relative_val =
ImmTy::from_uint(variant_index_relative, tag_layout);
let tag_val = self.binary_op(
mir::BinOp::Add,
variant_index_relative_val,
niche_start_val,
)?;
// Write result.
let niche_dest = self.place_field(dest, tag_field)?;
self.write_immediate(*tag_val, niche_dest)?;
}
}
}
Ok(())
}
pub fn raw_const_to_mplace(
&self,
raw: ConstAlloc<'tcx>,
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
// This must be an allocation in `tcx`
let _ = self.tcx.global_alloc(raw.alloc_id);
let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?;
let layout = self.layout_of(raw.ty)?;
Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
}
/// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
/// Also return some more information so drop doesn't have to run the same code twice.
pub(super) fn unpack_dyn_trait(
&self,
mplace: MPlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
let vtable = mplace.vtable(); // also sanity checks the type
let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
let layout = self.layout_of(ty)?;
// More sanity checks
if cfg!(debug_assertions) {
let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
assert_eq!(size, layout.size);
// only ABI alignment is preserved
assert_eq!(align, layout.align.abi);
}
let mplace = MPlaceTy { mplace: MemPlace { meta: MemPlaceMeta::None, ..*mplace }, layout };
Ok((instance, mplace))
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Use an external test to avoid os/exec -> net/http -> crypto/x509 -> os/exec
// circular dependency on non-cgo darwin.
package exec_test
import (
"bufio"
"bytes"
"context"
"fmt"
"internal/poll"
"internal/testenv"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
"time"
)
func helperCommandContext(t *testing.T, ctx context.Context, s ...string) (cmd *exec.Cmd) {
testenv.MustHaveExec(t)
cs := []string{"-test.run=TestHelperProcess", "--"}
cs = append(cs, s...)
if ctx != nil {
cmd = exec.CommandContext(ctx, os.Args[0], cs...)
} else {
cmd = exec.Command(os.Args[0], cs...)
}
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
path := os.Getenv("LD_LIBRARY_PATH")
if path != "" {
cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+path)
}
return cmd
}
func helperCommand(t *testing.T, s ...string) *exec.Cmd {
return helperCommandContext(t, nil, s...)
}
func TestEcho(t *testing.T) {
bs, err := helperCommand(t, "echo", "foo bar", "baz").Output()
if err != nil {
t.Errorf("echo: %v", err)
}
if g, e := string(bs), "foo bar baz\n"; g != e {
t.Errorf("echo: want %q, got %q", e, g)
}
}
func TestCommandRelativeName(t *testing.T) {
testenv.MustHaveExec(t)
// Run our own binary as a relative path
// (e.g. "_test/exec.test") our parent directory.
base := filepath.Base(os.Args[0]) // "exec.test"
dir := filepath.Dir(os.Args[0]) // "/tmp/go-buildNNNN/os/exec/_test"
if dir == "." {
t.Skip("skipping; running test at root somehow")
}
parentDir := filepath.Dir(dir) // "/tmp/go-buildNNNN/os/exec"
dirBase := filepath.Base(dir) // "_test"
if dirBase == "." {
t.Skipf("skipping; unexpected shallow dir of %q", dir)
}
cmd := exec.Command(filepath.Join(dirBase, base), "-test.run=TestHelperProcess", "--", "echo", "foo")
cmd.Dir = parentDir
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
out, err := cmd.Output()
if err != nil {
t.Errorf("echo: %v", err)
}
if g, e := string(out), "foo\n"; g != e {
t.Errorf("echo: want %q, got %q", e, g)
}
}
func TestCatStdin(t *testing.T) {
// Cat, testing stdin and stdout.
input := "Input string\nLine 2"
p := helperCommand(t, "cat")
p.Stdin = strings.NewReader(input)
bs, err := p.Output()
if err != nil {
t.Errorf("cat: %v", err)
}
s := string(bs)
if s != input {
t.Errorf("cat: want %q, got %q", input, s)
}
}
func TestEchoFileRace(t *testing.T) {
cmd := helperCommand(t, "echo")
stdin, err := cmd.StdinPipe()
if err != nil {
t.Fatalf("StdinPipe: %v", err)
}
if err := cmd.Start(); err != nil {
t.Fatalf("Start: %v", err)
}
wrote := make(chan bool)
go func() {
defer close(wrote)
fmt.Fprint(stdin, "echo\n")
}()
if err := cmd.Wait(); err != nil {
t.Fatalf("Wait: %v", err)
}
<-wrote
}
func TestCatGoodAndBadFile(t *testing.T) {
// Testing combined output and error values.
bs, err := helperCommand(t, "cat", "/bogus/file.foo", "exec_test.go").CombinedOutput()
if _, ok := err.(*exec.ExitError); !ok {
t.Errorf("expected *exec.ExitError from cat combined; got %T: %v", err, err)
}
s := string(bs)
sp := strings.SplitN(s, "\n", 2)
if len(sp) != 2 {
t.Fatalf("expected two lines from cat; got %q", s)
}
errLine, body := sp[0], sp[1]
if !strings.HasPrefix(errLine, "Error: open /bogus/file.foo") {
t.Errorf("expected stderr to complain about file; got %q", errLine)
}
if !strings.Contains(body, "func TestHelperProcess(t *testing.T)") {
t.Errorf("expected test code; got %q (len %d)", body, len(body))
}
}
func TestNoExistExecutable(t *testing.T) {
// Can't run a non-existent executable
err := exec.Command("/no-exist-executable").Run()
if err == nil {
t.Error("expected error from /no-exist-executable")
}
}
func TestExitStatus(t *testing.T) {
// Test that exit values are returned correctly
cmd := helperCommand(t, "exit", "42")
err := cmd.Run()
want := "exit status 42"
switch runtime.GOOS {
case "plan9":
want = fmt.Sprintf("exit status: '%s %d: 42'", filepath.Base(cmd.Path), cmd.ProcessState.Pid())
}
if werr, ok := err.(*exec.ExitError); ok {
if s := werr.Error(); s != want {
t.Errorf("from exit 42 got exit %q, want %q", s, want)
}
} else {
t.Fatalf("expected *exec.ExitError from exit 42; got %T: %v", err, err)
}
}
func TestExitCode(t *testing.T) {
// Test that exit code are returned correctly
cmd := helperCommand(t, "exit", "42")
cmd.Run()
want := 42
if runtime.GOOS == "plan9" {
want = 1
}
got := cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}
cmd = helperCommand(t, "/no-exist-executable")
cmd.Run()
want = 2
if runtime.GOOS == "plan9" {
want = 1
}
got = cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}
cmd = helperCommand(t, "exit", "255")
cmd.Run()
want = 255
if runtime.GOOS == "plan9" {
want = 1
}
got = cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}
cmd = helperCommand(t, "cat")
cmd.Run()
want = 0
got = cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}
// Test when command does not call Run().
cmd = helperCommand(t, "cat")
want = -1
got = cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}
}
func TestPipes(t *testing.T) {
check := func(what string, err error) {
if err != nil {
t.Fatalf("%s: %v", what, err)
}
}
// Cat, testing stdin and stdout.
c := helperCommand(t, "pipetest")
stdin, err := c.StdinPipe()
check("StdinPipe", err)
stdout, err := c.StdoutPipe()
check("StdoutPipe", err)
stderr, err := c.StderrPipe()
check("StderrPipe", err)
outbr := bufio.NewReader(stdout)
errbr := bufio.NewReader(stderr)
line := func(what string, br *bufio.Reader) string {
line, _, err := br.ReadLine()
if err != nil {
t.Fatalf("%s: %v", what, err)
}
return string(line)
}
err = c.Start()
check("Start", err)
_, err = stdin.Write([]byte("O:I am output\n"))
check("first stdin Write", err)
if g, e := line("first output line", outbr), "O:I am output"; g != e {
t.Errorf("got %q, want %q", g, e)
}
_, err = stdin.Write([]byte("E:I am error\n"))
check("second stdin Write", err)
if g, e := line("first error line", errbr), "E:I am error"; g != e {
t.Errorf("got %q, want %q", g, e)
}
_, err = stdin.Write([]byte("O:I am output2\n"))
check("third stdin Write 3", err)
if g, e := line("second output line", outbr), "O:I am output2"; g != e {
t.Errorf("got %q, want %q", g, e)
}
stdin.Close()
err = c.Wait()
check("Wait", err)
}
const stdinCloseTestString = "Some test string."
// Issue 6270.
func TestStdinClose(t *testing.T) {
check := func(what string, err error) {
if err != nil {
t.Fatalf("%s: %v", what, err)
}
}
cmd := helperCommand(t, "stdinClose")
stdin, err := cmd.StdinPipe()
check("StdinPipe", err)
// Check that we can access methods of the underlying os.File.`
if _, ok := stdin.(interface {
Fd() uintptr
}); !ok {
t.Error("can't access methods of underlying *os.File")
}
check("Start", cmd.Start())
go func() {
_, err := io.Copy(stdin, strings.NewReader(stdinCloseTestString))
check("Copy", err)
// Before the fix, this next line would race with cmd.Wait.
check("Close", stdin.Close())
}()
check("Wait", cmd.Wait())
}
// Issue 17647.
// It used to be the case that TestStdinClose, above, would fail when
// run under the race detector. This test is a variant of TestStdinClose
// that also used to fail when run under the race detector.
// This test is run by cmd/dist under the race detector to verify that
// the race detector no longer reports any problems.
func TestStdinCloseRace(t *testing.T) {
cmd := helperCommand(t, "stdinClose")
stdin, err := cmd.StdinPipe()
if err != nil {
t.Fatalf("StdinPipe: %v", err)
}
if err := cmd.Start(); err != nil {
t.Fatalf("Start: %v", err)
}
go func() {
// We don't check the error return of Kill. It is
// possible that the process has already exited, in
// which case Kill will return an error "process
// already finished". The purpose of this test is to
// see whether the race detector reports an error; it
// doesn't matter whether this Kill succeeds or not.
cmd.Process.Kill()
}()
go func() {
// Send the wrong string, so that the child fails even
// if the other goroutine doesn't manage to kill it first.
// This test is to check that the race detector does not
// falsely report an error, so it doesn't matter how the
// child process fails.
io.Copy(stdin, strings.NewReader("unexpected string"))
if err := stdin.Close(); err != nil {
t.Errorf("stdin.Close: %v", err)
}
}()
if err := cmd.Wait(); err == nil {
t.Fatalf("Wait: succeeded unexpectedly")
}
}
// Issue 5071
func TestPipeLookPathLeak(t *testing.T) {
// If we are reading from /proc/self/fd we (should) get an exact result.
tolerance := 0
// Reading /proc/self/fd is more reliable than calling lsof, so try that
// first.
numOpenFDs := func() (int, []byte, error) {
fds, err := ioutil.ReadDir("/proc/self/fd")
if err != nil {
return 0, nil, err
}
return len(fds), nil, nil
}
want, before, err := numOpenFDs()
if err != nil {
// We encountered a problem reading /proc/self/fd (we might be on
// a platform that doesn't have it). Fall back onto lsof.
t.Logf("using lsof because: %v", err)
numOpenFDs = func() (int, []byte, error) {
// Android's stock lsof does not obey the -p option,
// so extra filtering is needed.
// https://golang.org/issue/10206
if runtime.GOOS == "android" {
// numOpenFDsAndroid handles errors itself and
// might skip or fail the test.
n, lsof := numOpenFDsAndroid(t)
return n, lsof, nil
}
lsof, err := exec.Command("lsof", "-b", "-n", "-p", strconv.Itoa(os.Getpid())).Output()
return bytes.Count(lsof, []byte("\n")), lsof, err
}
// lsof may see file descriptors associated with the fork itself,
// so we allow some extra margin if we have to use it.
// https://golang.org/issue/19243
tolerance = 5
// Retry reading the number of open file descriptors.
want, before, err = numOpenFDs()
if err != nil {
t.Log(err)
t.Skipf("skipping test; error finding or running lsof")
}
}
for i := 0; i < 6; i++ {
cmd := exec.Command("something-that-does-not-exist-executable")
cmd.StdoutPipe()
cmd.StderrPipe()
cmd.StdinPipe()
if err := cmd.Run(); err == nil {
t.Fatal("unexpected success")
}
}
got, after, err := numOpenFDs()
if err != nil {
// numOpenFDs has already succeeded once, it should work here.
t.Errorf("unexpected failure: %v", err)
}
if got-want > tolerance {
t.Errorf("number of open file descriptors changed: got %v, want %v", got, want)
if before != nil {
t.Errorf("before:\n%v\n", before)
}
if after != nil {
t.Errorf("after:\n%v\n", after)
}
}
}
func numOpenFDsAndroid(t *testing.T) (n int, lsof []byte) {
raw, err := exec.Command("lsof").Output()
if err != nil {
t.Skip("skipping test; error finding or running lsof")
}
// First find the PID column index by parsing the first line, and
// select lines containing pid in the column.
pid := []byte(strconv.Itoa(os.Getpid()))
pidCol := -1
s := bufio.NewScanner(bytes.NewReader(raw))
for s.Scan() {
line := s.Bytes()
fields := bytes.Fields(line)
if pidCol < 0 {
for i, v := range fields {
if bytes.Equal(v, []byte("PID")) {
pidCol = i
break
}
}
lsof = append(lsof, line...)
continue
}
if bytes.Equal(fields[pidCol], pid) {
lsof = append(lsof, '\n')
lsof = append(lsof, line...)
}
}
if pidCol < 0 {
t.Fatal("error processing lsof output: unexpected header format")
}
if err := s.Err(); err != nil {
t.Fatalf("error processing lsof output: %v", err)
}
return bytes.Count(lsof, []byte("\n")), lsof
}
var testedAlreadyLeaked = false
// basefds returns the number of expected file descriptors
// to be present in a process at start.
// stdin, stdout, stderr, epoll/kqueue, maybe testlog
func basefds() uintptr {
n := os.Stderr.Fd() + 1
// The poll (epoll/kqueue) descriptor can be numerically
// either between stderr and the testlog-fd, or after
// testlog-fd.
if poll.IsPollDescriptor(n) {
n++
}
for _, arg := range os.Args {
if strings.HasPrefix(arg, "-test.testlogfile=") {
n++
}
}
return n
}
func closeUnexpectedFds(t *testing.T, m string) {
for fd := basefds(); fd <= 101; fd++ {
if poll.IsPollDescriptor(fd) {
continue
}
err := os.NewFile(fd, "").Close()
if err == nil {
t.Logf("%s: Something already leaked - closed fd %d", m, fd)
}
}
}
func TestExtraFilesFDShuffle(t *testing.T) {
t.Skip("flaky test; see https://golang.org/issue/5780")
switch runtime.GOOS {
case "darwin":
// TODO(cnicolaou): https://golang.org/issue/2603
// leads to leaked file descriptors in this test when it's
// run from a builder.
closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
case "netbsd":
// https://golang.org/issue/3955
closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
case "windows":
t.Skip("no operating system support; skipping")
}
// syscall.StartProcess maps all the FDs passed to it in
// ProcAttr.Files (the concatenation of stdin,stdout,stderr and
// ExtraFiles) into consecutive FDs in the child, that is:
// Files{11, 12, 6, 7, 9, 3} should result in the file
// represented by FD 11 in the parent being made available as 0
// in the child, 12 as 1, etc.
//
// We want to test that FDs in the child do not get overwritten
// by one another as this shuffle occurs. The original implementation
// was buggy in that in some data dependent cases it would overwrite
// stderr in the child with one of the ExtraFile members.
// Testing for this case is difficult because it relies on using
// the same FD values as that case. In particular, an FD of 3
// must be at an index of 4 or higher in ProcAttr.Files and
// the FD of the write end of the Stderr pipe (as obtained by
// StderrPipe()) must be the same as the size of ProcAttr.Files;
// therefore we test that the read end of this pipe (which is what
// is returned to the parent by StderrPipe() being one less than
// the size of ProcAttr.Files, i.e. 3+len(cmd.ExtraFiles).
//
// Moving this test case around within the overall tests may
// affect the FDs obtained and hence the checks to catch these cases.
npipes := 2
c := helperCommand(t, "extraFilesAndPipes", strconv.Itoa(npipes+1))
rd, wr, _ := os.Pipe()
defer rd.Close()
if rd.Fd() != 3 {
t.Errorf("bad test value for test pipe: fd %d", rd.Fd())
}
stderr, _ := c.StderrPipe()
wr.WriteString("_LAST")
wr.Close()
pipes := make([]struct {
r, w *os.File
}, npipes)
data := []string{"a", "b"}
for i := 0; i < npipes; i++ {
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("unexpected error creating pipe: %s", err)
}
pipes[i].r = r
pipes[i].w = w
w.WriteString(data[i])
c.ExtraFiles = append(c.ExtraFiles, pipes[i].r)
defer func() {
r.Close()
w.Close()
}()
}
// Put fd 3 at the end.
c.ExtraFiles = append(c.ExtraFiles, rd)
stderrFd := int(stderr.(*os.File).Fd())
if stderrFd != ((len(c.ExtraFiles) + 3) - 1) {
t.Errorf("bad test value for stderr pipe")
}
expected := "child: " + strings.Join(data, "") + "_LAST"
err := c.Start()
if err != nil {
t.Fatalf("Run: %v", err)
}
ch := make(chan string, 1)
go func(ch chan string) {
buf := make([]byte, 512)
n, err := stderr.Read(buf)
if err != nil {
t.Errorf("Read: %s", err)
ch <- err.Error()
} else {
ch <- string(buf[:n])
}
close(ch)
}(ch)
select {
case m := <-ch:
if m != expected {
t.Errorf("Read: '%s' not '%s'", m, expected)
}
case <-time.After(5 * time.Second):
t.Errorf("Read timedout")
}
c.Wait()
}
func TestExtraFiles(t *testing.T) {
testenv.MustHaveExec(t)
if runtime.GOOS == "windows" {
t.Skipf("skipping test on %q", runtime.GOOS)
}
// Ensure that file descriptors have not already been leaked into
// our environment.
if !testedAlreadyLeaked {
testedAlreadyLeaked = true
closeUnexpectedFds(t, "TestExtraFiles")
}
// Force network usage, to verify the epoll (or whatever) fd
// doesn't leak to the child,
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
// Make sure duplicated fds don't leak to the child.
f, err := ln.(*net.TCPListener).File()
if err != nil {
t.Fatal(err)
}
defer f.Close()
ln2, err := net.FileListener(f)
if err != nil {
t.Fatal(err)
}
defer ln2.Close()
// Force TLS root certs to be loaded (which might involve
// cgo), to make sure none of that potential C code leaks fds.
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
// quiet expected TLS handshake error "remote error: bad certificate"
ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
ts.StartTLS()
defer ts.Close()
_, err = http.Get(ts.URL)
if err == nil {
t.Errorf("success trying to fetch %s; want an error", ts.URL)
}
tf, err := ioutil.TempFile("", "")
if err != nil {
t.Fatalf("TempFile: %v", err)
}
defer os.Remove(tf.Name())
defer tf.Close()
const text = "Hello, fd 3!"
_, err = tf.Write([]byte(text))
if err != nil {
t.Fatalf("Write: %v", err)
}
_, err = tf.Seek(0, io.SeekStart)
if err != nil {
t.Fatalf("Seek: %v", err)
}
c := helperCommand(t, "read3")
var stdout, stderr bytes.Buffer
c.Stdout = &stdout
c.Stderr = &stderr
c.ExtraFiles = []*os.File{tf}
err = c.Run()
if err != nil {
t.Fatalf("Run: %v; stdout %q, stderr %q", err, stdout.Bytes(), stderr.Bytes())
}
if stdout.String() != text {
t.Errorf("got stdout %q, stderr %q; want %q on stdout", stdout.String(), stderr.String(), text)
}
}
func TestExtraFilesRace(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("no operating system support; skipping")
}
listen := func() net.Listener {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
return ln
}
listenerFile := func(ln net.Listener) *os.File {
f, err := ln.(*net.TCPListener).File()
if err != nil {
t.Fatal(err)
}
return f
}
runCommand := func(c *exec.Cmd, out chan<- string) {
bout, err := c.CombinedOutput()
if err != nil {
out <- "ERROR:" + err.Error()
} else {
out <- string(bout)
}
}
for i := 0; i < 10; i++ {
la := listen()
ca := helperCommand(t, "describefiles")
ca.ExtraFiles = []*os.File{listenerFile(la)}
lb := listen()
cb := helperCommand(t, "describefiles")
cb.ExtraFiles = []*os.File{listenerFile(lb)}
ares := make(chan string)
bres := make(chan string)
go runCommand(ca, ares)
go runCommand(cb, bres)
if got, want := <-ares, fmt.Sprintf("fd3: listener %s\n", la.Addr()); got != want {
t.Errorf("iteration %d, process A got:\n%s\nwant:\n%s\n", i, got, want)
}
if got, want := <-bres, fmt.Sprintf("fd3: listener %s\n", lb.Addr()); got != want {
t.Errorf("iteration %d, process B got:\n%s\nwant:\n%s\n", i, got, want)
}
la.Close()
lb.Close()
for _, f := range ca.ExtraFiles {
f.Close()
}
for _, f := range cb.ExtraFiles {
f.Close()
}
}
}
// TestHelperProcess isn't a real test. It's used as a helper process
// for TestParameterRun.
func TestHelperProcess(*testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
defer os.Exit(0)
// Determine which command to use to display open files.
ofcmd := "lsof"
switch runtime.GOOS {
case "dragonfly", "freebsd", "netbsd", "openbsd":
ofcmd = "fstat"
case "plan9":
ofcmd = "/bin/cat"
case "aix":
ofcmd = "procfiles"
}
args := os.Args
for len(args) > 0 {
if args[0] == "--" {
args = args[1:]
break
}
args = args[1:]
}
if len(args) == 0 {
fmt.Fprintf(os.Stderr, "No command\n")
os.Exit(2)
}
cmd, args := args[0], args[1:]
switch cmd {
case "echo":
iargs := []interface{}{}
for _, s := range args {
iargs = append(iargs, s)
}
fmt.Println(iargs...)
case "echoenv":
for _, s := range args {
fmt.Println(os.Getenv(s))
}
os.Exit(0)
case "cat":
if len(args) == 0 {
io.Copy(os.Stdout, os.Stdin)
return
}
exit := 0
for _, fn := range args {
f, err := os.Open(fn)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
exit = 2
} else {
defer f.Close()
io.Copy(os.Stdout, f)
}
}
os.Exit(exit)
case "pipetest":
bufr := bufio.NewReader(os.Stdin)
for {
line, _, err := bufr.ReadLine()
if err == io.EOF {
break
} else if err != nil {
os.Exit(1)
}
if bytes.HasPrefix(line, []byte("O:")) {
os.Stdout.Write(line)
os.Stdout.Write([]byte{'\n'})
} else if bytes.HasPrefix(line, []byte("E:")) {
os.Stderr.Write(line)
os.Stderr.Write([]byte{'\n'})
} else {
os.Exit(1)
}
}
case "stdinClose":
b, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if s := string(b); s != stdinCloseTestString {
fmt.Fprintf(os.Stderr, "Error: Read %q, want %q", s, stdinCloseTestString)
os.Exit(1)
}
os.Exit(0)
case "read3": // read fd 3
fd3 := os.NewFile(3, "fd3")
bs, err := ioutil.ReadAll(fd3)
if err != nil {
fmt.Printf("ReadAll from fd 3: %v", err)
os.Exit(1)
}
switch runtime.GOOS {
case "dragonfly":
// TODO(jsing): Determine why DragonFly is leaking
// file descriptors...
case "darwin":
// TODO(bradfitz): broken? Sometimes.
// https://golang.org/issue/2603
// Skip this additional part of the test for now.
case "netbsd":
// TODO(jsing): This currently fails on NetBSD due to
// the cloned file descriptors that result from opening
// /dev/urandom.
// https://golang.org/issue/3955
case "solaris":
// TODO(aram): This fails on Solaris because libc opens
// its own files, as it sees fit. Darwin does the same,
// see: https://golang.org/issue/2603
default:
// Now verify that there are no other open fds.
var files []*os.File
for wantfd := basefds() + 1; wantfd <= 100; wantfd++ {
if poll.IsPollDescriptor(wantfd) {
continue
}
f, err := os.Open(os.Args[0])
if err != nil {
fmt.Printf("error opening file with expected fd %d: %v", wantfd, err)
os.Exit(1)
}
if got := f.Fd(); got != wantfd {
fmt.Printf("leaked parent file. fd = %d; want %d\n", got, wantfd)
var args []string
switch runtime.GOOS {
case "plan9":
args = []string{fmt.Sprintf("/proc/%d/fd", os.Getpid())}
case "aix":
args = []string{fmt.Sprint(os.Getpid())}
default:
args = []string{"-p", fmt.Sprint(os.Getpid())}
}
out, _ := exec.Command(ofcmd, args...).CombinedOutput()
fmt.Print(string(out))
os.Exit(1)
}
files = append(files, f)
}
for _, f := range files {
f.Close()
}
}
// Referring to fd3 here ensures that it is not
// garbage collected, and therefore closed, while
// executing the wantfd loop above. It doesn't matter
// what we do with fd3 as long as we refer to it;
// closing it is the easy choice.
fd3.Close()
os.Stdout.Write(bs)
case "exit":
n, _ := strconv.Atoi(args[0])
os.Exit(n)
case "describefiles":
f := os.NewFile(3, fmt.Sprintf("fd3"))
ln, err := net.FileListener(f)
if err == nil {
fmt.Printf("fd3: listener %s\n", ln.Addr())
ln.Close()
}
os.Exit(0)
case "extraFilesAndPipes":
n, _ := strconv.Atoi(args[0])
pipes := make([]*os.File, n)
for i := 0; i < n; i++ {
pipes[i] = os.NewFile(uintptr(3+i), strconv.Itoa(i))
}
response := ""
for i, r := range pipes {
ch := make(chan string, 1)
go func(c chan string) {
buf := make([]byte, 10)
n, err := r.Read(buf)
if err != nil {
fmt.Fprintf(os.Stderr, "Child: read error: %v on pipe %d\n", err, i)
os.Exit(1)
}
c <- string(buf[:n])
close(c)
}(ch)
select {
case m := <-ch:
response = response + m
case <-time.After(5 * time.Second):
fmt.Fprintf(os.Stderr, "Child: Timeout reading from pipe: %d\n", i)
os.Exit(1)
}
}
fmt.Fprintf(os.Stderr, "child: %s", response)
os.Exit(0)
case "exec":
cmd := exec.Command(args[1])
cmd.Dir = args[0]
output, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "Child: %s %s", err, string(output))
os.Exit(1)
}
fmt.Printf("%s", string(output))
os.Exit(0)
case "lookpath":
p, err := exec.LookPath(args[0])
if err != nil {
fmt.Fprintf(os.Stderr, "LookPath failed: %v\n", err)
os.Exit(1)
}
fmt.Print(p)
os.Exit(0)
case "stderrfail":
fmt.Fprintf(os.Stderr, "some stderr text\n")
os.Exit(1)
case "sleep":
time.Sleep(3 * time.Second)
os.Exit(0)
default:
fmt.Fprintf(os.Stderr, "Unknown command %q\n", cmd)
os.Exit(2)
}
}
type delayedInfiniteReader struct{}
func (delayedInfiniteReader) Read(b []byte) (int, error) {
time.Sleep(100 * time.Millisecond)
for i := range b {
b[i] = 'x'
}
return len(b), nil
}
// Issue 9173: ignore stdin pipe writes if the program completes successfully.
func TestIgnorePipeErrorOnSuccess(t *testing.T) {
testenv.MustHaveExec(t)
// We really only care about testing this on Unixy and Windowsy things.
if runtime.GOOS == "plan9" {
t.Skipf("skipping test on %q", runtime.GOOS)
}
testWith := func(r io.Reader) func(*testing.T) {
return func(t *testing.T) {
cmd := helperCommand(t, "echo", "foo")
var out bytes.Buffer
cmd.Stdin = r
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
t.Fatal(err)
}
if got, want := out.String(), "foo\n"; got != want {
t.Errorf("output = %q; want %q", got, want)
}
}
}
t.Run("10MB", testWith(strings.NewReader(strings.Repeat("x", 10<<20))))
t.Run("Infinite", testWith(delayedInfiniteReader{}))
}
type badWriter struct{}
func (w *badWriter) Write(data []byte) (int, error) {
return 0, io.ErrUnexpectedEOF
}
func TestClosePipeOnCopyError(t *testing.T) {
testenv.MustHaveExec(t)
if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
t.Skipf("skipping test on %s - no yes command", runtime.GOOS)
}
cmd := exec.Command("yes")
cmd.Stdout = new(badWriter)
c := make(chan int, 1)
go func() {
err := cmd.Run()
if err == nil {
t.Errorf("yes completed successfully")
}
c <- 1
}()
select {
case <-c:
// ok
case <-time.After(5 * time.Second):
t.Fatalf("yes got stuck writing to bad writer")
}
}
func TestOutputStderrCapture(t *testing.T) {
testenv.MustHaveExec(t)
cmd := helperCommand(t, "stderrfail")
_, err := cmd.Output()
ee, ok := err.(*exec.ExitError)
if !ok {
t.Fatalf("Output error type = %T; want ExitError", err)
}
got := string(ee.Stderr)
want := "some stderr text\n"
if got != want {
t.Errorf("ExitError.Stderr = %q; want %q", got, want)
}
}
func TestContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
c := helperCommandContext(t, ctx, "pipetest")
stdin, err := c.StdinPipe()
if err != nil {
t.Fatal(err)
}
stdout, err := c.StdoutPipe()
if err != nil {
t.Fatal(err)
}
if err := c.Start(); err != nil {
t.Fatal(err)
}
if _, err := stdin.Write([]byte("O:hi\n")); err != nil {
t.Fatal(err)
}
buf := make([]byte, 5)
n, err := io.ReadFull(stdout, buf)
if n != len(buf) || err != nil || string(buf) != "O:hi\n" {
t.Fatalf("ReadFull = %d, %v, %q", n, err, buf[:n])
}
waitErr := make(chan error, 1)
go func() {
waitErr <- c.Wait()
}()
cancel()
select {
case err := <-waitErr:
if err == nil {
t.Fatal("expected Wait failure")
}
case <-time.After(3 * time.Second):
t.Fatal("timeout waiting for child process death")
}
}
func TestContextCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c := helperCommandContext(t, ctx, "cat")
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
c.Stdin = r
stdout, err := c.StdoutPipe()
if err != nil {
t.Fatal(err)
}
readDone := make(chan struct{})
go func() {
defer close(readDone)
var a [1024]byte
for {
n, err := stdout.Read(a[:])
if err != nil {
if err != io.EOF {
t.Errorf("unexpected read error: %v", err)
}
return
}
t.Logf("%s", a[:n])
}
}()
if err := c.Start(); err != nil {
t.Fatal(err)
}
if err := r.Close(); err != nil {
t.Fatal(err)
}
if _, err := io.WriteString(w, "echo"); err != nil {
t.Fatal(err)
}
cancel()
// Calling cancel should have killed the process, so writes
// should now fail. Give the process a little while to die.
start := time.Now()
for {
if _, err := io.WriteString(w, "echo"); err != nil {
break
}
if time.Since(start) > time.Second {
t.Fatal("canceling context did not stop program")
}
time.Sleep(time.Millisecond)
}
if err := w.Close(); err != nil {
t.Errorf("error closing write end of pipe: %v", err)
}
<-readDone
if err := c.Wait(); err == nil {
t.Error("program unexpectedly exited successfully")
} else {
t.Logf("exit status: %v", err)
}
}
// test that environment variables are de-duped.
func TestDedupEnvEcho(t *testing.T) {
testenv.MustHaveExec(t)
cmd := helperCommand(t, "echoenv", "FOO")
cmd.Env = append(cmd.Env, "FOO=bad", "FOO=good")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
if got, want := strings.TrimSpace(string(out)), "good"; got != want {
t.Errorf("output = %q; want %q", got, want)
}
}
|
{
"pile_set_name": "Github"
}
|
#####
# LONG_XOR
#####
szpr: LONG_XOR(r, rlv)
13
EMIT_INSTRUCTION
EMIT_Commutative(IA32_XOR, P(p), Binary.getClearResult(P(p)), Binary.getClearVal1(P(p)), Binary.getClearVal2(P(p)));
### Memory operands ###
szpr: LONG_XOR(r, load64)
15
EMIT_INSTRUCTION
EMIT_Commutative(IA32_XOR, P(p), Binary.getClearResult(P(p)), Binary.getClearVal1(P(p)), consumeMO());
szpr: LONG_XOR(load64, rlv)
15
EMIT_INSTRUCTION
EMIT_Commutative(IA32_XOR, P(p), Binary.getClearResult(P(p)), Binary.getClearVal2(P(p)), consumeMO());
stm: LONG_STORE(LONG_XOR(LONG_LOAD(rlv,rlv),rlv),OTHER_OPERAND(rlv, rlv))
ADDRESS_EQUAL(P(p), PLL(p), 17)
EMIT_INSTRUCTION
EMIT_Commutative(IA32_XOR, P(p), MO_S(P(p), QW), MO_S(P(p), QW), Binary.getClearVal2(PL(p)) );
stm: LONG_STORE(LONG_XOR(r,LONG_LOAD(rlv,rlv)),OTHER_OPERAND(rlv, rlv))
ADDRESS_EQUAL(P(p), PLR(p), 17)
EMIT_INSTRUCTION
EMIT_Commutative(IA32_XOR, P(p), MO_S(P(p), QW), MO_S(P(p), QW), Binary.getClearVal1(PL(p)) );
stm: LONG_ASTORE(LONG_XOR(LONG_ALOAD(rlv,rlv),rlv),OTHER_OPERAND(rlv, rlv))
ARRAY_ADDRESS_EQUAL(P(p), PLL(p), 17)
EMIT_INSTRUCTION
EMIT_Commutative(IA32_XOR, P(p), MO_AS(P(p), QW_S, QW), MO_AS(P(p), QW_S, QW), Binary.getClearVal2(PL(p)) );
stm: LONG_ASTORE(LONG_XOR(r,LONG_ALOAD(rlv,rlv)),OTHER_OPERAND(rlv, rlv))
ARRAY_ADDRESS_EQUAL(P(p), PLR(p), 17)
EMIT_INSTRUCTION
EMIT_Commutative(IA32_XOR, P(p), MO_AS(P(p), QW_S, QW), MO_AS(P(p), QW_S, QW), Binary.getClearVal1(PL(p)) );
|
{
"pile_set_name": "Github"
}
|
section.code, section.code * {
-webkit-user-select: auto !important;
}
html,body{
margin:0;
padding:0;
height: 100%;
}
body {
font-family: Helvetica, Arial, sans-serif;
position: relative;
-webkit-font-smoothing: antialiased;
}
body.light {
background: #fff;
}
body.dark {
color: #F0F1F1;
background: #333;
}
body.light {
color: #181919;
}
h1 {
font-weight: 200;
}
#wrapper {
width: 100%;
background: inherit;
position: relative;
}
#site {
width: 100%;
position: relative;
z-index: 10;
background: inherit;
left: 0;
transition: all 0.2s ease-out;
-webkit-transition: all 0.2s ease-out;
transform: translate3d(0, 0, 0);
-webkit-transform: translate3d(0, 0, 0);
}
#site:before{
position: absolute;
content: '';
left: -4px;
height: 100%;
width: 4px;
background: #3B3E3E;
}
#site.open {
transform: translate3d(250px, 0, 0);
-webkit-transform: translate3d(250px, 0, 0);
}
pre {
font-family: menlo, sans-serif;
font-size: 12px;
}
/* Main Header */
#main-header {
color: #373435;
background: #fff;
height: 80px;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 20px 0 0 0;
position: relative;
}
#main-header hgroup {
text-align: center;
}
#main-header hgroup h1 {
font-size: 30px;
margin: 0 0 0 14px;
}
#main-header hgroup a, a {
color: #464646;
text-decoration: none;
}
#main-header hgroup a:hover {
color: #000;
}
#main-header hgroup p {
font-size: 13px;
color: #999;
margin: 0;
}
#main-header nav {
display: none;
}
.topcoat-icon--menu-stack {
background: url("../../img/hamburger_dark.svg") no-repeat;
background-size: cover;
}
#slide-menu-button {
position: absolute;
top: 20px;
left: 20px;
display: inline-block;
vertical-align: top;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding;
-moz-background-clip: padding;
background-clip: padding-box;
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-o-text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
padding: 0 0.5rem;
line-height: 2rem;
letter-spacing: 1px;
color: #454545;
text-shadow: 0 1px #fff;
vertical-align: baseline;
-webkit-box-shadow: inset 0 1px #fff;
box-shadow: inset 0 1px #fff;
-webkit-border-radius: 3px;
border-radius: 3px;
width: 2.6rem;
height: 2.6rem;
line-height: 2.6rem;
border: 1px solid transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
#slide-menu:disabled,
#slide-menu.is-disabled {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
#slide-menu-button:active,
#slide-menu-button.is-active {
color: #454545;
text-shadow: 0 1px #fff;
background-color: #d3d7d7;
border: 1px solid #a5a8a8;
-webkit-box-shadow: inset 0 1px rgba(0,0,0,0.12);
box-shadow: inset 0 1px rgba(0,0,0,0.12);
}
#slide-menu-button span {
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
position: relative;
display: inline-block;
vertical-align: top;
overflow: hidden;
vertical-align: middle;
width: 1.3rem;
height: 1.3rem;
}
#download-btn {
display: none;
}
/* Content */
#content {
width: 100%;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px 20px 20px 20px;
}
#content section.component > div.markup > p {
font-size: 12px;
color: #999;
}
#content section.component > div.markup > p:after {
content: ':';
}
/* Code */
#content section.code {
margin-top: 16px;
background: #FFF;
border: 1px solid #E0E0E0;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 4px 12px;
font-size: 13px;
-moz-border-radius: 1px;
-webkit-border-radius: 1px;
border-radius: 1px;
font-weight: 400;
display: none;
}
article.component {
padding: 0 0 10px;
}
#content section.code h3 {
margin: 0;
font-size: 12px;
color: #000;
font-weight: 400;
}
#content header h2 {
font-weight: 300;
margin: 10px 0 25px;
font-size: 20px;
display: block-block;
padding-right: 10px;
}
#content header{
position: relative;
}
#content pre {
padding: 0;
margin: 2px 0 10px;
}
.showcode {
margin: 10px 0;
}
.showcode a, section.examples a, a {
color: #288edf;
text-decoration: none;
}
.showcode a:hover, section.examples a:hover, a:hover {
text-decoration: underline;
}
section.examples ul {
margin: 0 0 20px;
padding: 0 0 0 20px;
}
section.examples h4 {
margin-bottom: 5px;
}
section.examples li {
color: #58595A;
}
/* Side Nav */
#sideNav {
background: #4A4D4E;
position: absolute;
width: 100%;
z-index: 1;
height: 100%;
left: 0;
}
#sideNav ul {
list-style: none;
margin: 0;
padding: 0;
}
#sideNav li a {
color: #F0F1F1;
display: block;
height: 46px;
font-size: 16px;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 12px 0 0 20px;
text-decoration: none;
}
#sideNav nav.site, #sideNav .combo {
border-bottom: 1px solid #58595A;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
display: block;
}
#pageNav li {
border-bottom: 1px solid #58595A;
}
@media screen and (min-width: 650px) {
#site.open {
transform: translate3d(0, 0, 0);
-webkit-transform: translate3d(0, 0, 0);
}
#main-header nav {
display: inline-block;
position: absolute;
right: 0;
top: 40px;
}
#main-header ul {
list-style: none;
}
#main-header nav li {
display: inline-block;
margin: 0 18px;
}
#main-header nav li#download-btn {
display: none;
}
#main-header nav li a {
text-decoration: none;
font-size: 20px;
color: #7F7F7F;
}
#main-header nav li.selected a {
color: #373435;
}
#slide-menu-button{
display: none;
}
#main-header hgroup {
text-align: left;
position: absolute;
display: inline-block;
top: 12px;
}
#main-header {
color: #373435;
background: #fff;
height: 80px;
}
#content {
padding-left: 240px;
}
/* Side Nav */
#sideNav {
background: transparent;
width: 220px;
z-index: 20;
left: 10px;
top: 150px;
height: auto;
}
#sideNav nav.site {
display: none;
}
#sideNav .combo {
border-bottom: none;
padding: 0px 0;
}
#sideNav li {
margin: 0;
padding: 0;
border: none;
}
#sideNav li a {
padding: 8px 0 0 0px;
height: auto;
margin: 0;
display: block;
}
body.light #sideNav li a {
color: #797B7B;
}
body.light #pageNav li {
}
}
@media screen and (min-width: 880px) {
#content {
padding-left: 300px;
}
#sideNav li a {
display: block;
text-decoration: none;
}
#sideNav li a:hover {
text-decoration: underline;
}
#content header h2 {
font-size: 28px;
}
#content header:before {
top: 30px;
}
section.code div {
display: inline-block;
width: 100%;
vertical-align: top;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.max-width {
max-width: 1180px;
position: relative;
margin: 0 auto;
}
header#main-header .max-width {
top: -10px;
}
#main-header nav li a {
font-size: 22px;
}
#main-header nav {
display: inline-block;
}
#main-header nav li {
margin: 0 25px;
}
#main-header nav li:last-child {
margin-right: 0;
}
}
@media screen and (min-width: 940px) {
#main-header nav li#download-btn {
display: inline-block;
}
#main-header nav li a#download-btn{
position:relative;
top: -15px;
display:inline-block;
box-sizing:border-box;
-moz-box-sizing:border-box;
background-clip:padding-box;
font:inherit;
background:transparent;
-webkit-user-select:none;
-moz-user-select:none;
user-select:none;
text-overflow:ellipsis;
white-space:nowrap;
overflow:hidden;
font-size:16px;
line-height:3rem;
letter-spacing:1px;
color:#454545;
text-shadow:0 1px #fff;
vertical-align:top;
background-color:#e5e9e8;
box-shadow:inset 0 1px #fff;
border:1px solid #a5a8a8;
border-radius:6px;
margin:0;
padding:0 1.25rem;
}
#main-header nav li a#download-btn, #main-header nav li a#download-btn:hover {
border:1px solid #143250;
background-color:#288edf;
box-shadow:inset 0 1px rgba(255,255,255,0.36);
color:#fff;
font-weight:500;
text-shadow:0 -1px rgba(0,0,0,0.36);
}
#main-header nav li a#download-btn:hover {
background-color:#2f9cf3;
}
#main-header nav li a#download-btn:active, #main-header nav li a#download-btn.is-active {
background-color:#0380e8;
box-shadow:inset 0 1px rgba(0,0,0,0.12);
}
#main-header nav li a#download-btn:disabled, #main-header nav li a#download-btn.is-disabled {
opacity:.3;
cursor:default;
pointer-events:none;
}
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_162) on Tue Jan 23 20:22:17 PST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>NumberSerializers.Base (jackson-databind 2.9.0 API)</title>
<meta name="date" content="2018-01-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="NumberSerializers.Base (jackson-databind 2.9.0 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/NumberSerializers.Base.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.html" title="class in com.fasterxml.jackson.databind.ser.std"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.DoubleSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html" target="_top">Frames</a></li>
<li><a href="NumberSerializers.Base.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.classes.inherited.from.class.com.fasterxml.jackson.databind.JsonSerializer">Nested</a> | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.fasterxml.jackson.databind.ser.std</div>
<h2 title="Class NumberSerializers.Base" class="title">Class NumberSerializers.Base<T></h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html" title="class in com.fasterxml.jackson.databind">com.fasterxml.jackson.databind.JsonSerializer</a><T></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">com.fasterxml.jackson.databind.ser.std.StdSerializer</a><T></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdScalarSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">com.fasterxml.jackson.databind.ser.std.StdScalarSerializer</a><T></li>
<li>
<ul class="inheritance">
<li>com.fasterxml.jackson.databind.ser.std.NumberSerializers.Base<T></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../../com/fasterxml/jackson/databind/jsonFormatVisitors/JsonFormatVisitable.html" title="interface in com.fasterxml.jackson.databind.jsonFormatVisitors">JsonFormatVisitable</a>, <a href="../../../../../../com/fasterxml/jackson/databind/jsonschema/SchemaAware.html" title="interface in com.fasterxml.jackson.databind.jsonschema">SchemaAware</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/ContextualSerializer.html" title="interface in com.fasterxml.jackson.databind.ser">ContextualSerializer</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a></dd>
</dl>
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.DoubleSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">NumberSerializers.DoubleSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.FloatSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">NumberSerializers.FloatSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.IntegerSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">NumberSerializers.IntegerSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.IntLikeSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">NumberSerializers.IntLikeSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.LongSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">NumberSerializers.LongSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.ShortSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">NumberSerializers.ShortSerializer</a></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.html" title="class in com.fasterxml.jackson.databind.ser.std">NumberSerializers</a></dd>
</dl>
<hr>
<br>
<pre>protected abstract static class <span class="typeNameLabel">NumberSerializers.Base<T></span>
extends <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdScalarSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">StdScalarSerializer</a><T>
implements <a href="../../../../../../com/fasterxml/jackson/databind/ser/ContextualSerializer.html" title="interface in com.fasterxml.jackson.databind.ser">ContextualSerializer</a></pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../serialized-form.html#com.fasterxml.jackson.databind.ser.std.NumberSerializers.Base">Serialized Form</a></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested.class.summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested.classes.inherited.from.class.com.fasterxml.jackson.databind.JsonSerializer">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from class com.fasterxml.jackson.databind.<a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html" title="class in com.fasterxml.jackson.databind">JsonSerializer</a></h3>
<code><a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.None.html" title="class in com.fasterxml.jackson.databind">JsonSerializer.None</a></code></li>
</ul>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html#Z:Z_isInt">_isInt</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected <a href="http://fasterxml.github.com/jackson-core/javadoc/2.9/com/fasterxml/jackson/core/JsonParser.NumberType.html?is-external=true" title="class or interface in com.fasterxml.jackson.core">JsonParser.NumberType</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html#Z:Z_numberType">_numberType</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html#Z:Z_schemaType">_schemaType</a></span></code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="fields.inherited.from.class.com.fasterxml.jackson.databind.ser.std.StdSerializer">
<!-- -->
</a>
<h3>Fields inherited from class com.fasterxml.jackson.databind.ser.std.<a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">StdSerializer</a></h3>
<code><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#Z:Z_handledType">_handledType</a></code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier</th>
<th class="colLast" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html#Base-java.lang.Class-com.fasterxml.jackson.core.JsonParser.NumberType-java.lang.String-">Base</a></span>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html?is-external=true" title="class or interface in java.lang">Class</a><?> cls,
<a href="http://fasterxml.github.com/jackson-core/javadoc/2.9/com/fasterxml/jackson/core/JsonParser.NumberType.html?is-external=true" title="class or interface in com.fasterxml.jackson.core">JsonParser.NumberType</a> numberType,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> schemaType)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html#acceptJsonFormatVisitor-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-">acceptJsonFormatVisitor</a></span>(<a href="../../../../../../com/fasterxml/jackson/databind/jsonFormatVisitors/JsonFormatVisitorWrapper.html" title="interface in com.fasterxml.jackson.databind.jsonFormatVisitors">JsonFormatVisitorWrapper</a> visitor,
<a href="../../../../../../com/fasterxml/jackson/databind/JavaType.html" title="class in com.fasterxml.jackson.databind">JavaType</a> typeHint)</code>
<div class="block">Default implementation specifies no format.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html" title="class in com.fasterxml.jackson.databind">JsonSerializer</a><?></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html#createContextual-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-">createContextual</a></span>(<a href="../../../../../../com/fasterxml/jackson/databind/SerializerProvider.html" title="class in com.fasterxml.jackson.databind">SerializerProvider</a> prov,
<a href="../../../../../../com/fasterxml/jackson/databind/BeanProperty.html" title="interface in com.fasterxml.jackson.databind">BeanProperty</a> property)</code>
<div class="block">Method called to see if a different (or differently configured) serializer
is needed to serialize values of specified property.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../../../../../../com/fasterxml/jackson/databind/JsonNode.html" title="class in com.fasterxml.jackson.databind">JsonNode</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html#getSchema-com.fasterxml.jackson.databind.SerializerProvider-java.lang.reflect.Type-">getSchema</a></span>(<a href="../../../../../../com/fasterxml/jackson/databind/SerializerProvider.html" title="class in com.fasterxml.jackson.databind">SerializerProvider</a> provider,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Type.html?is-external=true" title="class or interface in java.lang.reflect">Type</a> typeHint)</code>
<div class="block">Default implementation simply claims type is "string"; usually
overriden by custom serializers.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.com.fasterxml.jackson.databind.ser.std.StdScalarSerializer">
<!-- -->
</a>
<h3>Methods inherited from class com.fasterxml.jackson.databind.ser.std.<a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdScalarSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">StdScalarSerializer</a></h3>
<code><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdScalarSerializer.html#serializeWithType-T-com.fasterxml.jackson.core.JsonGenerator-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.jsontype.TypeSerializer-">serializeWithType</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.com.fasterxml.jackson.databind.ser.std.StdSerializer">
<!-- -->
</a>
<h3>Methods inherited from class com.fasterxml.jackson.databind.ser.std.<a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">StdSerializer</a></h3>
<code><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#Z:Z_neitherNull-java.lang.Object-java.lang.Object-">_neitherNull</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#Z:Z_nonEmpty-java.util.Collection-">_nonEmpty</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#createSchemaNode-java.lang.String-">createSchemaNode</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#createSchemaNode-java.lang.String-boolean-">createSchemaNode</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#findAnnotatedContentSerializer-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-">findAnnotatedContentSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#findContextualConvertingSerializer-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-com.fasterxml.jackson.databind.JsonSerializer-">findContextualConvertingSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#findConvertingContentSerializer-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-com.fasterxml.jackson.databind.JsonSerializer-">findConvertingContentSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#findFormatFeature-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-java.lang.Class-com.fasterxml.jackson.annotation.JsonFormat.Feature-">findFormatFeature</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#findFormatOverrides-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-java.lang.Class-">findFormatOverrides</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#findIncludeOverrides-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-java.lang.Class-">findIncludeOverrides</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#findPropertyFilter-com.fasterxml.jackson.databind.SerializerProvider-java.lang.Object-java.lang.Object-">findPropertyFilter</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#getSchema-com.fasterxml.jackson.databind.SerializerProvider-java.lang.reflect.Type-boolean-">getSchema</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#handledType--">handledType</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#isDefaultSerializer-com.fasterxml.jackson.databind.JsonSerializer-">isDefaultSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#serialize-T-com.fasterxml.jackson.core.JsonGenerator-com.fasterxml.jackson.databind.SerializerProvider-">serialize</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#visitArrayFormat-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatTypes-">visitArrayFormat</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#visitArrayFormat-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-com.fasterxml.jackson.databind.JsonSerializer-com.fasterxml.jackson.databind.JavaType-">visitArrayFormat</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#visitFloatFormat-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-com.fasterxml.jackson.core.JsonParser.NumberType-">visitFloatFormat</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#visitIntFormat-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-com.fasterxml.jackson.core.JsonParser.NumberType-">visitIntFormat</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#visitIntFormat-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-com.fasterxml.jackson.core.JsonParser.NumberType-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonValueFormat-">visitIntFormat</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#visitStringFormat-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-">visitStringFormat</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#visitStringFormat-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonValueFormat-">visitStringFormat</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#wrapAndThrow-com.fasterxml.jackson.databind.SerializerProvider-java.lang.Throwable-java.lang.Object-int-">wrapAndThrow</a>, <a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#wrapAndThrow-com.fasterxml.jackson.databind.SerializerProvider-java.lang.Throwable-java.lang.Object-java.lang.String-">wrapAndThrow</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.com.fasterxml.jackson.databind.JsonSerializer">
<!-- -->
</a>
<h3>Methods inherited from class com.fasterxml.jackson.databind.<a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html" title="class in com.fasterxml.jackson.databind">JsonSerializer</a></h3>
<code><a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html#getDelegatee--">getDelegatee</a>, <a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html#isEmpty-com.fasterxml.jackson.databind.SerializerProvider-T-">isEmpty</a>, <a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html#isEmpty-T-">isEmpty</a>, <a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html#isUnwrappingSerializer--">isUnwrappingSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html#properties--">properties</a>, <a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html#replaceDelegatee-com.fasterxml.jackson.databind.JsonSerializer-">replaceDelegatee</a>, <a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html#unwrappingSerializer-com.fasterxml.jackson.databind.util.NameTransformer-">unwrappingSerializer</a>, <a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html#usesObjectId--">usesObjectId</a>, <a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html#withFilterId-java.lang.Object-">withFilterId</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></h3>
<code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#clone--" title="class or interface in java.lang">clone</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#equals-java.lang.Object-" title="class or interface in java.lang">equals</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#finalize--" title="class or interface in java.lang">finalize</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#getClass--" title="class or interface in java.lang">getClass</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#hashCode--" title="class or interface in java.lang">hashCode</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#notify--" title="class or interface in java.lang">notify</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#notifyAll--" title="class or interface in java.lang">notifyAll</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#toString--" title="class or interface in java.lang">toString</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#wait--" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#wait-long-" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#wait-long-int-" title="class or interface in java.lang">wait</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="Z:Z_numberType">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>_numberType</h4>
<pre>protected final <a href="http://fasterxml.github.com/jackson-core/javadoc/2.9/com/fasterxml/jackson/core/JsonParser.NumberType.html?is-external=true" title="class or interface in com.fasterxml.jackson.core">JsonParser.NumberType</a> _numberType</pre>
</li>
</ul>
<a name="Z:Z_schemaType">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>_schemaType</h4>
<pre>protected final <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> _schemaType</pre>
</li>
</ul>
<a name="Z:Z_isInt">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>_isInt</h4>
<pre>protected final boolean _isInt</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Base-java.lang.Class-com.fasterxml.jackson.core.JsonParser.NumberType-java.lang.String-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Base</h4>
<pre>protected Base(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html?is-external=true" title="class or interface in java.lang">Class</a><?> cls,
<a href="http://fasterxml.github.com/jackson-core/javadoc/2.9/com/fasterxml/jackson/core/JsonParser.NumberType.html?is-external=true" title="class or interface in com.fasterxml.jackson.core">JsonParser.NumberType</a> numberType,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> schemaType)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getSchema-com.fasterxml.jackson.databind.SerializerProvider-java.lang.reflect.Type-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getSchema</h4>
<pre>public <a href="../../../../../../com/fasterxml/jackson/databind/JsonNode.html" title="class in com.fasterxml.jackson.databind">JsonNode</a> getSchema(<a href="../../../../../../com/fasterxml/jackson/databind/SerializerProvider.html" title="class in com.fasterxml.jackson.databind">SerializerProvider</a> provider,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Type.html?is-external=true" title="class or interface in java.lang.reflect">Type</a> typeHint)</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from class: <code><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#getSchema-com.fasterxml.jackson.databind.SerializerProvider-java.lang.reflect.Type-">StdSerializer</a></code></span></div>
<div class="block">Default implementation simply claims type is "string"; usually
overriden by custom serializers.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../../com/fasterxml/jackson/databind/jsonschema/SchemaAware.html#getSchema-com.fasterxml.jackson.databind.SerializerProvider-java.lang.reflect.Type-">getSchema</a></code> in interface <code><a href="../../../../../../com/fasterxml/jackson/databind/jsonschema/SchemaAware.html" title="interface in com.fasterxml.jackson.databind.jsonschema">SchemaAware</a></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdScalarSerializer.html#getSchema-com.fasterxml.jackson.databind.SerializerProvider-java.lang.reflect.Type-">getSchema</a></code> in class <code><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdScalarSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">StdScalarSerializer</a><<a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html" title="type parameter in NumberSerializers.Base">T</a>></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>provider</code> - The serializer provider.</dd>
<dd><code>typeHint</code> - A hint about the type.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd><a href="http://json-schema.org/">Json-schema</a> for this serializer.</dd>
</dl>
</li>
</ul>
<a name="acceptJsonFormatVisitor-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>acceptJsonFormatVisitor</h4>
<pre>public void acceptJsonFormatVisitor(<a href="../../../../../../com/fasterxml/jackson/databind/jsonFormatVisitors/JsonFormatVisitorWrapper.html" title="interface in com.fasterxml.jackson.databind.jsonFormatVisitors">JsonFormatVisitorWrapper</a> visitor,
<a href="../../../../../../com/fasterxml/jackson/databind/JavaType.html" title="class in com.fasterxml.jackson.databind">JavaType</a> typeHint)
throws <a href="../../../../../../com/fasterxml/jackson/databind/JsonMappingException.html" title="class in com.fasterxml.jackson.databind">JsonMappingException</a></pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from class: <code><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdSerializer.html#acceptJsonFormatVisitor-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-">StdSerializer</a></code></span></div>
<div class="block">Default implementation specifies no format. This behavior is usually
overriden by custom serializers.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../../com/fasterxml/jackson/databind/jsonFormatVisitors/JsonFormatVisitable.html#acceptJsonFormatVisitor-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-">acceptJsonFormatVisitor</a></code> in interface <code><a href="../../../../../../com/fasterxml/jackson/databind/jsonFormatVisitors/JsonFormatVisitable.html" title="interface in com.fasterxml.jackson.databind.jsonFormatVisitors">JsonFormatVisitable</a></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdScalarSerializer.html#acceptJsonFormatVisitor-com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper-com.fasterxml.jackson.databind.JavaType-">acceptJsonFormatVisitor</a></code> in class <code><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/StdScalarSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std">StdScalarSerializer</a><<a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html" title="type parameter in NumberSerializers.Base">T</a>></code></dd>
<dd><code>typeHint</code> - Type of element (entity like property) being visited</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../../../com/fasterxml/jackson/databind/JsonMappingException.html" title="class in com.fasterxml.jackson.databind">JsonMappingException</a></code></dd>
</dl>
</li>
</ul>
<a name="createContextual-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>createContextual</h4>
<pre>public <a href="../../../../../../com/fasterxml/jackson/databind/JsonSerializer.html" title="class in com.fasterxml.jackson.databind">JsonSerializer</a><?> createContextual(<a href="../../../../../../com/fasterxml/jackson/databind/SerializerProvider.html" title="class in com.fasterxml.jackson.databind">SerializerProvider</a> prov,
<a href="../../../../../../com/fasterxml/jackson/databind/BeanProperty.html" title="interface in com.fasterxml.jackson.databind">BeanProperty</a> property)
throws <a href="../../../../../../com/fasterxml/jackson/databind/JsonMappingException.html" title="class in com.fasterxml.jackson.databind">JsonMappingException</a></pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../../../com/fasterxml/jackson/databind/ser/ContextualSerializer.html#createContextual-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-">ContextualSerializer</a></code></span></div>
<div class="block">Method called to see if a different (or differently configured) serializer
is needed to serialize values of specified property.
Note that instance that this method is called on is typically shared one and
as a result method should <b>NOT</b> modify this instance but rather construct
and return a new instance. This instance should only be returned as-is, in case
it is already suitable for use.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../../com/fasterxml/jackson/databind/ser/ContextualSerializer.html#createContextual-com.fasterxml.jackson.databind.SerializerProvider-com.fasterxml.jackson.databind.BeanProperty-">createContextual</a></code> in interface <code><a href="../../../../../../com/fasterxml/jackson/databind/ser/ContextualSerializer.html" title="interface in com.fasterxml.jackson.databind.ser">ContextualSerializer</a></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>prov</code> - Serializer provider to use for accessing config, other serializers</dd>
<dd><code>property</code> - Method or field that represents the property
(and is used to access value to serialize).
Should be available; but there may be cases where caller cannot provide it and
null is passed instead (in which case impls usually pass 'this' serializer as is)</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Serializer to use for serializing values of specified property;
may be this instance or a new instance.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../../../com/fasterxml/jackson/databind/JsonMappingException.html" title="class in com.fasterxml.jackson.databind">JsonMappingException</a></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/NumberSerializers.Base.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.html" title="class in com.fasterxml.jackson.databind.ser.std"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../com/fasterxml/jackson/databind/ser/std/NumberSerializers.DoubleSerializer.html" title="class in com.fasterxml.jackson.databind.ser.std"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/ser/std/NumberSerializers.Base.html" target="_top">Frames</a></li>
<li><a href="NumberSerializers.Base.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.classes.inherited.from.class.com.fasterxml.jackson.databind.JsonSerializer">Nested</a> | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2008–2018 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
#include "gauge_wrapper.h"
#include "allocator_mgr.h"
#include "wxgui_defs.h"
#include "wxgui_helpers.h"
#include "xmlutils.h"
#include <wx/gauge.h>
GaugeWrapper::GaugeWrapper()
: wxcWidget(ID_WXGAUGE)
{
PREPEND_STYLE(wxGA_HORIZONTAL, true);
PREPEND_STYLE(wxGA_VERTICAL, false);
PREPEND_STYLE(wxGA_SMOOTH, false);
AddProperty(new StringProperty(
PROP_RANGE, wxT("100"),
_("Integer range (maximum value) of the gauge. It is ignored when the gauge is used in indeterminate mode.")));
AddProperty(new StringProperty(PROP_VALUE, wxT("10"), _("Sets the position of the gauge")));
m_namePattern = wxT("m_gauge");
SetName(GenerateName());
}
GaugeWrapper::~GaugeWrapper() {}
wxcWidget* GaugeWrapper::Clone() const { return new GaugeWrapper(); }
wxString GaugeWrapper::CppCtorCode() const
{
// wxGauge(wxWindow* parent, wxWindowID id, int range, const wxPoint& pos = wxDefaultPosition, const wxSize& size =
// wxDefaultSize, long style = wxGA_HORIZONTAL, const wxValidator& validator = wxDefaultValidator, const wxString&
// name = "gauge")
wxString cpp;
cpp << GetName() << wxT(" = new ") << GetRealClassName() << "(" << GetWindowParent() << wxT(", ") << WindowID()
<< wxT(", ") << PropertyString(PROP_RANGE) << wxT(", ") << wxT("wxDefaultPosition, ") << SizeAsString()
<< wxT(", ") << StyleFlags(wxT("wxGA_HORIZONTAL")) << wxT(");\n");
cpp << CPPCommonAttributes();
int pos = wxCrafter::ToNumber(PropertyString(PROP_VALUE), 0);
cpp << GetName() << wxT("->SetValue(") << pos << wxT(");\n");
return cpp;
}
void GaugeWrapper::GetIncludeFile(wxArrayString& headers) const { headers.Add(wxT("#include <wx/gauge.h>")); }
wxString GaugeWrapper::GetWxClassName() const { return wxT("wxGauge"); }
void GaugeWrapper::ToXRC(wxString& text, XRC_TYPE type) const
{
text << XRCPrefix() << wxT("<range>") << wxCrafter::ToNumber(PropertyString(PROP_RANGE), 100) << wxT("</range>")
<< wxT("<value>") << wxCrafter::ToNumber(PropertyString(PROP_VALUE), 10) << wxT("</value>") << XRCStyle()
<< XRCCommonAttributes() << XRCSize() << XRCSuffix();
}
void GaugeWrapper::LoadPropertiesFromXRC(const wxXmlNode* node)
{
// First call the base-class for the standard things
wxcWidget::LoadPropertiesFromXRC(node);
wxXmlNode* propertynode = XmlUtils::FindFirstByTagName(node, wxT("range"));
if(propertynode) { SetPropertyString(PROP_RANGE, propertynode->GetNodeContent()); }
propertynode = XmlUtils::FindFirstByTagName(node, wxT("value"));
if(propertynode) { SetPropertyString(PROP_VALUE, propertynode->GetNodeContent()); }
}
void GaugeWrapper::LoadPropertiesFromwxSmith(const wxXmlNode* node)
{
// First call the base-class for the standard things
wxcWidget::LoadPropertiesFromwxSmith(node);
wxXmlNode* propertynode = XmlUtils::FindFirstByTagName(node, wxT("range"));
if(propertynode) { SetPropertyString(PROP_RANGE, propertynode->GetNodeContent()); }
propertynode = XmlUtils::FindFirstByTagName(node, wxT("value"));
if(propertynode) { SetPropertyString(PROP_VALUE, propertynode->GetNodeContent()); }
}
void GaugeWrapper::LoadPropertiesFromwxFB(const wxXmlNode* node)
{
// First call the base-class for the standard things
wxcWidget::LoadPropertiesFromwxFB(node);
wxXmlNode* propertynode = XmlUtils::FindNodeByName(node, "property", "range");
if(propertynode) { SetPropertyString(PROP_RANGE, propertynode->GetNodeContent()); }
propertynode = XmlUtils::FindNodeByName(node, "property", "value");
if(propertynode) { SetPropertyString(PROP_VALUE, propertynode->GetNodeContent()); }
}
|
{
"pile_set_name": "Github"
}
|
[Desktop Entry]
Version=1.0
Name=VLC
GenericName=VLC media player
Comment=Read, capture, broadcast your multimedia streams
Exec=vlc.wrapper
TryExec=vlc.wrapper
Icon=vlc
Terminal=false
Type=Application
Categories=AudioVideo;Player;Recorder;
MimeType=video/dv;video/mpeg;video/x-mpeg;video/msvideo;video/quicktime;video/x-anim;video/x-avi;video/x-ms-asf;video/x-ms-wmv;video/x-msvideo;video/x-nsv;video/x-flc;video/x-fli;video/x-flv;video/vnd.rn-realvideo;video/mp4;video/mp4v-es;video/mp2t;application/ogg;application/x-ogg;video/x-ogm+ogg;audio/x-vorbis+ogg;audio/ogg;video/ogg;application/x-matroska;audio/x-matroska;video/x-matroska;video/webm;audio/webm;audio/x-mp3;audio/x-mpeg;audio/mpeg;audio/x-wav;audio/x-mpegurl;audio/x-scpls;audio/x-m4a;audio/x-ms-asf;audio/x-ms-asx;audio/x-ms-wax;application/vnd.rn-realmedia;audio/x-real-audio;audio/x-pn-realaudio;application/x-flac;audio/x-flac;application/x-shockwave-flash;misc/ultravox;audio/vnd.rn-realaudio;audio/x-pn-aiff;audio/x-pn-au;audio/x-pn-wav;audio/x-pn-windows-acm;image/vnd.rn-realpix;audio/x-pn-realaudio-plugin;application/x-extension-mp4;audio/mp4;audio/amr;audio/amr-wb;x-content/video-vcd;x-content/video-svcd;x-content/video-dvd;x-content/audio-cdda;x-content/audio-player;application/xspf+xml;x-scheme-handler/mms;x-scheme-handler/rtmp;x-scheme-handler/rtsp;video/vnd.mpegurl;
Keywords=Player;Capture;DVD;Audio;Video;Server;Broadcast;
[AppImageHub]
# Dear upstream developer, please include update information in your AppImage
# (e.g., with appimagetool -u) so that users can easily update the AppImage
X-AppImage-Signature=no valid OpenPGP data found. the signature could not be verified. Please remember that the signature file (.sig or .asc) should be the first file given on the command line.
X-AppImage-Type=2
X-AppImage-Architecture=x86_64
|
{
"pile_set_name": "Github"
}
|
{
"name": "RiskSense",
"description": "RiskSense is a cloud-based platform that provides vulnerability management and prioritization to measure and control cybersecurity risk.",
"support": "partner",
"currentVersion": "1.0.2",
"author": "RiskSense",
"url": "https://www.risksense.com",
"email": "",
"created": "2020-04-14T00:00:00Z",
"categories": [
"Vulnerability Management"
],
"tags": [],
"useCases": [],
"keywords": [],
"githubUser": [
"crestdatasystems"
]
}
|
{
"pile_set_name": "Github"
}
|
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0";
object mut;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -1 -1 0 0 0 0];
internalField uniform 0;
boundaryField
{
front
{
type mutkWallFunction;
value uniform 0;
}
back
{
type mutkWallFunction;
value uniform 0;
}
walls
{
type mutkWallFunction;
value uniform 0;
}
porosityWall
{
type mutkWallFunction;
value uniform 0;
}
inlet
{
type calculated;
value uniform 0;
}
outlet
{
type calculated;
value uniform 0;
}
}
// ************************************************************************* //
|
{
"pile_set_name": "Github"
}
|
package simpledb;
import java.util.HashMap;
import java.util.Set;
import java.util.Vector;
/** A PlanCache is a helper class that can be used to store the best
* way to order a given set of joins */
public class PlanCache {
HashMap<Set<LogicalJoinNode>,Vector<LogicalJoinNode>> bestOrders= new HashMap<Set<LogicalJoinNode>,Vector<LogicalJoinNode>>();
HashMap<Set<LogicalJoinNode>,Double> bestCosts= new HashMap<Set<LogicalJoinNode>,Double>();
HashMap<Set<LogicalJoinNode>,Integer> bestCardinalities = new HashMap<Set<LogicalJoinNode>,Integer>();
/** Add a new cost, cardinality and ordering for a particular join set. Does not verify that the
new cost is less than any previously added cost -- simply adds or replaces an existing plan for the
specified join set
@param s the set of joins for which a new ordering (plan) is being added
@param cost the estimated cost of the specified plan
@param card the estimatied cardinality of the specified plan
@param order the ordering of the joins in the plan
*/
void addPlan(Set<LogicalJoinNode> s, double cost, int card, Vector<LogicalJoinNode> order) {
bestOrders.put(s,order);
bestCosts.put(s,cost);
bestCardinalities.put(s,card);
}
/** Find the best join order in the cache for the specified plan
@param s the set of joins to look up the best order for
@return the best order for s in the cache
*/
Vector<LogicalJoinNode> getOrder(Set<LogicalJoinNode> s) {
return bestOrders.get(s);
}
/** Find the cost of the best join order in the cache for the specified plan
@param s the set of joins to look up the best cost for
@return the cost of the best order for s in the cache
*/
double getCost(Set<LogicalJoinNode> s) {
return bestCosts.get(s);
}
/** Find the cardinality of the best join order in the cache for the specified plan
@param s the set of joins to look up the best cardinality for
@return the cardinality of the best order for s in the cache
*/
int getCard(Set<LogicalJoinNode> s) {
return bestCardinalities.get(s);
}
}
|
{
"pile_set_name": "Github"
}
|
---
---
kind: Service
foo: bar
key: value
alist:
- 1
- 2
- 3
---
---
---
kind: Pod
key2: value2
image: somewhere:latest
---
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
</dict>
</plist>
|
{
"pile_set_name": "Github"
}
|
---
-api-id: P:Windows.UI.Xaml.VisualStateManager.CustomVisualStateManagerProperty
-api-type: winrt property
---
<!-- Property syntax
public Windows.UI.Xaml.DependencyProperty CustomVisualStateManagerProperty { get; }
-->
# Windows.UI.Xaml.VisualStateManager.CustomVisualStateManagerProperty
## -description
Identifies the **VisualStateManager.CustomVisualStateManager** dependency property.
## -property-value
The identifier for the **VisualStateManager.CustomVisualStateManager** dependency property.
## -remarks
## -examples
## -see-also
|
{
"pile_set_name": "Github"
}
|
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Hardware.Camera2;
using Android.Graphics;
using Android.Hardware.Camera2.Params;
using Android.Media;
using Camera2Basic;
using Camera2Basic.Listeners;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Java.IO;
using Java.Lang;
using Java.Util;
using Java.Util.Concurrent;
using Boolean = Java.Lang.Boolean;
using Math = Java.Lang.Math;
using Orientation = Android.Content.Res.Orientation;
using System.Collections.Generic;
using Size = Android.Util.Size;
using Point = Android.Graphics.Point;
using System;
using ConferenceVision.Services;
[assembly: ExportRenderer(typeof(ConferenceVision.Views.Renderers.CameraPreview), typeof(ConferenceVision.Droid.Renderers.CameraPreviewRenderer))]
namespace ConferenceVision.Droid.Renderers
{
public class CameraPreviewRenderer : ViewRenderer<Views.Renderers.CameraPreview, AutoFitTextureView>, ICamera2Basic
{
private static readonly SparseIntArray ORIENTATIONS = new SparseIntArray();
public static readonly int REQUEST_CAMERA_PERMISSION = 1;
// Tag for the {@link Log}.
private static readonly string TAG = "Camera2BasicFragment";
// Max preview width that is guaranteed by Camera2 API
private static readonly int MAX_PREVIEW_WIDTH = 1920;
// Max preview height that is guaranteed by Camera2 API
private static readonly int MAX_PREVIEW_HEIGHT = 1080;
// TextureView.ISurfaceTextureListener handles several lifecycle events on a TextureView
private Camera2BasicSurfaceTextureListener mSurfaceTextureListener;
// ID of the current {@link CameraDevice}.
private string mCameraId;
// An AutoFitTextureView for camera preview
private AutoFitTextureView mTextureView;
// A {@link CameraCaptureSession } for camera preview.
public CameraCaptureSession mCaptureSession { get; set; }
// A reference to the opened CameraDevice
public CameraDevice mCameraDevice { get; set; }
// The size of the camera preview
private Size mPreviewSize;
// CameraDevice.StateListener is called when a CameraDevice changes its state
private CameraStateListener mStateCallback;
// An additional thread for running tasks that shouldn't block the UI.
private HandlerThread mBackgroundThread;
// A {@link Handler} for running tasks in the background.
public Handler mBackgroundHandler { get; set; }
// An {@link ImageReader} that handles still image capture.
private ImageReader mImageReader;
// This is the output file for our picture.
public File mFile;
// This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
// still image is ready to be saved.
private ImageAvailableListener mOnImageAvailableListener;
//{@link CaptureRequest.Builder} for the camera preview
public CaptureRequest.Builder mPreviewRequestBuilder { get; set; }
// {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder}
public CaptureRequest mPreviewRequest { get; set; }
// The current state of camera state for taking pictures.
public Camera2BasicState mState { get; set; } = Camera2BasicState.STATE_PREVIEW;
// A {@link Semaphore} to prevent the app from exiting before closing the camera.
public Semaphore mCameraOpenCloseLock { get; set; } = new Semaphore(1);
// Whether the current camera device supports Flash or not.
private bool mFlashSupported;
// Orientation of the camera sensor
private int mSensorOrientation;
// A {@link CameraCaptureSession.CaptureCallback} that handles events related to JPEG capture.
public CameraCaptureListener mCaptureCallback { get; set; }
public Activity Activity { get; set; }
byte[] imageBytes;
public CameraPreviewRenderer(Context context) : base(context)
{
ORIENTATIONS.Append((int)SurfaceOrientation.Rotation0, 90);
ORIENTATIONS.Append((int)SurfaceOrientation.Rotation90, 0);
ORIENTATIONS.Append((int)SurfaceOrientation.Rotation180, 270);
ORIENTATIONS.Append((int)SurfaceOrientation.Rotation270, 180);
}
Android.Views.View view;
protected override void OnElementChanged(ElementChangedEventArgs<Views.Renderers.CameraPreview> e)
{
if (Xamarin.Forms.DesignMode.IsDesignModeEnabled)
{
return;
}
if (e.OldElement != null) // Clear old element event
{
}
if (e.NewElement != null)
{
e.NewElement.StartRecording = (() => { TakePicture(); });
e.NewElement.StopRecording = (() => { CloseCamera(); });
if (Control == null)
{
Activity = this.Context as Activity;
SetNativeControl(new AutoFitTextureView(Context));
}
mTextureView = Control as AutoFitTextureView;
mStateCallback = new CameraStateListener(this);
mSurfaceTextureListener = new Camera2BasicSurfaceTextureListener(this);
//mFile = new File(Activity.GetExternalFilesDir(null), $"{Element.Filename}.jpg");
//var path = System.IO.Path.Combine(
// System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments),
// $"{Element.Filename}"
//);
var path = System.IO.Path.Combine(
DependencyService.Get<IMediaFolder>().Path,
Element.Filename);
mFile = new File(
path
);
mCaptureCallback = new CameraCaptureListener(this);
mOnImageAvailableListener = new ImageAvailableListener(this, mFile);
StartTheCamera();
}
base.OnElementChanged(e);
}
private void StartTheCamera()
{
StartBackgroundThread();
// When the screen is turned off and turned back on, the SurfaceTexture is already
// available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
// a camera and start preview from here (otherwise, we wait until the surface is ready in
// the SurfaceTextureListener).
if (mTextureView.IsAvailable)
{
OpenCamera(mTextureView.Width, mTextureView.Height);
}
else
{
mTextureView.SurfaceTextureListener = mSurfaceTextureListener;
}
}
public void OnCaptureComplete()
{
var exists = mFile.Exists();
if (exists)
{
Element.OnMediaSaved(
$"{Element.Filename}",
string.Empty,
isLandscape(),
0);
}
}
bool isLandscape()
{
var orientation = Resources.Configuration.Orientation;
return orientation == Orientation.Landscape;
}
private static Size ChooseOptimalSize(Size[] choices, int textureViewWidth,
int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio)
{
// Collect the supported resolutions that are at least as big as the preview Surface
var bigEnough = new List<Size>();
// Collect the supported resolutions that are smaller than the preview Surface
var notBigEnough = new List<Size>();
int w = aspectRatio.Width;
int h = aspectRatio.Height;
for (var i = 0; i < choices.Length; i++)
{
Size option = choices[i];
if ((option.Width <= maxWidth) && (option.Height <= maxHeight) &&
option.Height == option.Width * h / w)
{
if (option.Width >= textureViewWidth &&
option.Height >= textureViewHeight)
{
bigEnough.Add(option);
}
else
{
notBigEnough.Add(option);
}
}
}
// Pick the smallest of those big enough. If there is no one big enough, pick the
// largest of those not big enough.
if (bigEnough.Count > 0)
{
return (Size)Collections.Min(bigEnough, new CompareSizesByArea());
}
else if (notBigEnough.Count > 0)
{
return (Size)Collections.Max(notBigEnough, new CompareSizesByArea());
}
else
{
Log.Error(TAG, "Couldn't find any suitable preview size");
return choices[0];
}
}
//protected override void OnLayout(bool changed, int l, int t, int r, int b)
//{
// base.OnLayout(changed, l, t, r, b);
// Control.Measure(global::Android.Views.View.MeasureSpec.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly),
// global::Android.Views.View.MeasureSpec.MakeMeasureSpec(b - t, MeasureSpecMode.Exactly)
// );// measures control at the size just before layout
// Control.Layout(0, 0, r - l, b - t); // coords relative to self, at 0,0
//}
// Sets up member variables related to camera.
private void SetUpCameraOutputs(int width, int height)
{
var activity = Activity;
var manager = (CameraManager)activity.GetSystemService(Context.CameraService);
try
{
for (var i = 0; i < manager.GetCameraIdList().Length; i++)
{
var cameraId = manager.GetCameraIdList()[i];
CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId);
// We don't use a front facing camera in this sample.
var facing = (Integer)characteristics.Get(CameraCharacteristics.LensFacing);
if (facing != null && facing == (Integer.ValueOf((int)LensFacing.Front)))
{
continue;
}
var map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
if (map == null)
{
continue;
}
// For still image captures, we use the largest available size.
Size largest = (Size)Collections.Max(Arrays.AsList(map.GetOutputSizes((int)ImageFormatType.Jpeg)),
new CompareSizesByArea());
mImageReader = ImageReader.NewInstance(largest.Width, largest.Height, ImageFormatType.Jpeg, /*maxImages*/2);
mImageReader.SetOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
// Find out if we need to swap dimension to get the preview size relative to sensor
// coordinate.
var displayRotation = activity.WindowManager.DefaultDisplay.Rotation;
//noinspection ConstantConditions
mSensorOrientation = (int)characteristics.Get(CameraCharacteristics.SensorOrientation);
bool swappedDimensions = false;
switch (displayRotation)
{
case SurfaceOrientation.Rotation0:
case SurfaceOrientation.Rotation180:
if (mSensorOrientation == 90 || mSensorOrientation == 270)
{
swappedDimensions = true;
}
break;
case SurfaceOrientation.Rotation90:
case SurfaceOrientation.Rotation270:
if (mSensorOrientation == 0 || mSensorOrientation == 180)
{
swappedDimensions = true;
}
break;
default:
Log.Error(TAG, "Display rotation is invalid: " + displayRotation);
break;
}
Point displaySize = new Point();
activity.WindowManager.DefaultDisplay.GetSize(displaySize);
var rotatedPreviewWidth = width;
var rotatedPreviewHeight = height;
var maxPreviewWidth = displaySize.X;
var maxPreviewHeight = displaySize.Y;
if (swappedDimensions)
{
rotatedPreviewWidth = height;
rotatedPreviewHeight = width;
maxPreviewWidth = displaySize.Y;
maxPreviewHeight = displaySize.X;
}
if (maxPreviewWidth > MAX_PREVIEW_WIDTH)
{
maxPreviewWidth = MAX_PREVIEW_WIDTH;
}
if (maxPreviewHeight > MAX_PREVIEW_HEIGHT)
{
maxPreviewHeight = MAX_PREVIEW_HEIGHT;
}
// Danger, W.R.! Attempting to use too large a preview size could exceed the camera
// bus' bandwidth limitation, resulting in gorgeous previews but the storage of
// garbage capture data.
mPreviewSize = ChooseOptimalSize(map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture))),
rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
maxPreviewHeight, largest);
// We fit the aspect ratio of TextureView to the size of preview we picked.
var orientation = Resources.Configuration.Orientation;
if (orientation == Orientation.Landscape)
{
mTextureView.SetAspectRatio(mPreviewSize.Width, mPreviewSize.Height);
}
else
{
mTextureView.SetAspectRatio(mPreviewSize.Height, mPreviewSize.Width);
}
// Check if the flash is supported.
var available = (Boolean)characteristics.Get(CameraCharacteristics.FlashInfoAvailable);
if (available == null)
{
mFlashSupported = false;
}
else
{
mFlashSupported = (bool)available;
}
mCameraId = cameraId;
return;
}
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
catch (NullPointerException e)
{
// Currently an NPE is thrown when the Camera2API is used but not supported on the
// device this code runs.
//ErrorDialog.NewInstance(GetString(Resource.String.camera_error)).Show(ChildFragmentManager, FRAGMENT_DIALOG);
}
}
// Opens the camera specified by {@link Camera2BasicFragment#mCameraId}.
public void OpenCamera(int width, int height)
{
SetUpCameraOutputs(width, height);
ConfigureTransform(width, height);
var activity = Activity;
var manager = (CameraManager)activity.GetSystemService(Context.CameraService);
try
{
if (!mCameraOpenCloseLock.TryAcquire(2500, TimeUnit.Milliseconds))
{
throw new RuntimeException("Time out waiting to lock camera opening.");
}
if (!string.IsNullOrEmpty(mCameraId))
manager.OpenCamera(mCameraId, mStateCallback, mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
catch (InterruptedException e)
{
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}
// Closes the current {@link CameraDevice}.
private void CloseCamera()
{
if (mCaptureSession == null)
return;
try
{
mCameraOpenCloseLock.Acquire();
if (null != mCaptureSession)
{
try
{
mCaptureSession.StopRepeating();
mCaptureSession.AbortCaptures();
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
catch (IllegalStateException e)
{
e.PrintStackTrace();
}
mCaptureSession.Close();
mCaptureSession = null;
}
if (null != mCameraDevice)
{
mCameraDevice.Close();
mCameraDevice = null;
}
if (null != mImageReader)
{
mImageReader.Close();
mImageReader = null;
}
}
catch (InterruptedException e)
{
throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
}
finally
{
mCameraOpenCloseLock.Release();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
CloseCamera();
StopBackgroundThread();
if (Element != null)
{
Element.StartRecording = null;
Element.StopRecording = null;
}
}
base.Dispose(disposing);
}
// Starts a background thread and its {@link Handler}.
private void StartBackgroundThread()
{
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.Start();
mBackgroundHandler = new Handler(mBackgroundThread.Looper);
}
// Stops the background thread and its {@link Handler}.
private void StopBackgroundThread()
{
if (mBackgroundThread == null)
return;
mBackgroundThread.QuitSafely();
try
{
mBackgroundThread.Join();
mBackgroundThread = null;
mBackgroundHandler = null;
}
catch (InterruptedException e)
{
e.PrintStackTrace();
}
}
// Creates a new {@link CameraCaptureSession} for camera preview.
public void CreateCameraPreviewSession()
{
try
{
SurfaceTexture texture = mTextureView.SurfaceTexture;
if (texture == null)
{
throw new IllegalStateException("texture is null");
}
// We configure the size of default buffer to be the size of camera preview we want.
texture.SetDefaultBufferSize(mPreviewSize.Width, mPreviewSize.Height);
// This is the output Surface we need to start preview.
Surface surface = new Surface(texture);
// We set up a CaptureRequest.Builder with the output Surface.
mPreviewRequestBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.Preview);
mPreviewRequestBuilder.AddTarget(surface);
// Here, we create a CameraCaptureSession for camera preview.
List<Surface> surfaces = new List<Surface>();
surfaces.Add(surface);
surfaces.Add(mImageReader.Surface);
mCameraDevice.CreateCaptureSession(surfaces, new CameraCaptureSessionCallback(this), null);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
public static T Cast<T>(Java.Lang.Object obj) where T : class
{
var propertyInfo = obj.GetType().GetProperty("Instance");
return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}
// Configures the necessary {@link android.graphics.Matrix}
// transformation to `mTextureView`.
// This method should be called after the camera preview size is determined in
// setUpCameraOutputs and also the size of `mTextureView` is fixed.
public void ConfigureTransform(int viewWidth, int viewHeight)
{
Activity activity = Activity;
if (null == mTextureView || null == mPreviewSize || null == activity)
{
return;
}
var rotation = (int)activity.WindowManager.DefaultDisplay.Rotation;
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mPreviewSize.Height, mPreviewSize.Width);
float centerX = viewRect.CenterX();
float centerY = viewRect.CenterY();
if ((int)SurfaceOrientation.Rotation90 == rotation || (int)SurfaceOrientation.Rotation270 == rotation)
{
bufferRect.Offset(centerX - bufferRect.CenterX(), centerY - bufferRect.CenterY());
matrix.SetRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.Fill);
float scale = Math.Max((float)viewHeight / mPreviewSize.Height, (float)viewWidth / mPreviewSize.Width);
matrix.PostScale(scale, scale, centerX, centerY);
matrix.PostRotate(90 * (rotation - 2), centerX, centerY);
}
else if ((int)SurfaceOrientation.Rotation180 == rotation)
{
matrix.PostRotate(180, centerX, centerY);
}
mTextureView.SetTransform(matrix);
}
// Initiate a still image capture.
private void TakePicture()
{
//LockFocus();
CaptureStillPicture();
}
// Lock the focus as the first step for a still image capture.
private void LockFocus()
{
try
{
// This is how to tell the camera to lock focus.
mPreviewRequestBuilder.Set(CaptureRequest.ControlAfTrigger, (int)ControlAFTrigger.Start);
// Tell #mCaptureCallback to wait for the lock.
mState = Camera2BasicState.STATE_WAITING_LOCK;
mCaptureSession.Capture(mPreviewRequestBuilder.Build(), mCaptureCallback,
mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
// Run the precapture sequence for capturing a still image. This method should be called when
// we get a response in {@link #mCaptureCallback} from {@link #lockFocus()}.
public void RunPrecaptureSequence()
{
try
{
// This is how to tell the camera to trigger.
mPreviewRequestBuilder.Set(CaptureRequest.ControlAePrecaptureTrigger, (int)ControlAEPrecaptureTrigger.Start);
// Tell #mCaptureCallback to wait for the precapture sequence to be set.
mState = Camera2BasicState.STATE_WAITING_PRECAPTURE;
mCaptureSession.Capture(mPreviewRequestBuilder.Build(), mCaptureCallback, mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
private CaptureRequest.Builder stillCaptureBuilder;
// Capture a still picture. This method should be called when we get a response in
// {@link #mCaptureCallback} from both {@link #lockFocus()}.
public void CaptureStillPicture()
{
try
{
var activity = Activity;
if (null == activity || null == mCameraDevice)
{
return;
}
// This is the CaptureRequest.Builder that we use to take a picture.
if (stillCaptureBuilder == null)
stillCaptureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
stillCaptureBuilder.AddTarget(mImageReader.Surface);
// Use the same AE and AF modes as the preview.
stillCaptureBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.ContinuousPicture);
//SetAutoFlash(stillCaptureBuilder);
// Orientation
int rotation = (int)activity.WindowManager.DefaultDisplay.Rotation;
stillCaptureBuilder.Set(CaptureRequest.JpegOrientation, GetOrientation(rotation));
mCaptureSession.StopRepeating();
mCaptureSession.Capture(stillCaptureBuilder.Build(), new CameraCaptureStillPictureSessionCallback(this), null);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
// Retrieves the JPEG orientation from the specified screen rotation.
private int GetOrientation(int rotation)
{
// Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
// We have to take that into account and rotate JPEG properly.
// For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
// For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
return (ORIENTATIONS.Get(rotation) + mSensorOrientation + 270) % 360;
}
// Unlock the focus. This method should be called when still image capture sequence is
// finished.
public void UnlockFocus()
{
try
{
// Reset the auto-focus trigger
mPreviewRequestBuilder.Set(CaptureRequest.ControlAfTrigger, (int)ControlAFTrigger.Cancel);
//SetAutoFlash(mPreviewRequestBuilder);
mCaptureSession.Capture(mPreviewRequestBuilder.Build(), mCaptureCallback,
mBackgroundHandler);
// After this, the camera will go back to the normal state of preview.
mState = Camera2BasicState.STATE_PREVIEW;
mCaptureSession.SetRepeatingRequest(mPreviewRequest, mCaptureCallback,
mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
/** @file
IA32 CPU Exception Handler functons.
Copyright (c) 2012 - 2015, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <CpuExceptionCommon.h>
CONST UINT32 mErrorCodeFlag = 0x00027d00;
/**
Common exception handler.
It will print out the location where exception occured and then halt the system.
This function will never return.
@param[in] Stack Current stack address pointer.
@param[in] ExceptionType Exception type code.
**/
VOID
EFIAPI
CommonExceptionHandler (
IN UINT32 *Stack,
IN UINT8 ExceptionType
)
{
UINT32 *Ptr;
// Skip the ExceptionType on the stack
Ptr = Stack + 1;
// Skip the ErrorCode on the stack
if (ExceptionType < CPU_EXCEPTION_NUM) {
if (mErrorCodeFlag & (1 << ExceptionType)) {
Ptr++;
}
}
DEBUG ((DEBUG_ERROR, "Exception #%d from 0x%04X:0x%08X !!!\n", ExceptionType, Ptr[1], Ptr[0]));
CpuHalt (NULL);
}
/**
Update exception handler in IDT table .
This function is used to update the IDT exception handler with current stage.
@param[in] IdtDescritor If non-zero, it is new IDT descriptor to be updated.
if it is 0, the IDT descriptor will be retrieved from IDT base register.
**/
STATIC
VOID
UpdateExceptionHandler2 (
IN VOID *IdtDescriptor
)
{
UINT64 *IdtTable;
IA32_IDT_GATE_DESCRIPTOR IdtGateDescriptor;
UINT32 Index;
UINT32 Address;
IA32_DESCRIPTOR Idtr;
EXCEPTION_HANDLER_TEMPLATE_MAP TemplateMap;
if (IdtDescriptor == NULL) {
AsmReadIdtr (&Idtr);
} else {
Idtr = *(IA32_DESCRIPTOR *) IdtDescriptor;
}
IdtTable = (UINT64 *)Idtr.Base;
IdtGateDescriptor.Uint64 = 0;
IdtGateDescriptor.Bits.Selector = AsmReadCs ();
IdtGateDescriptor.Bits.GateType = IA32_IDT_GATE_TYPE_INTERRUPT_32;
AsmGetTemplateAddressMap (&TemplateMap);
for (Index = 0; Index < CPU_EXCEPTION_NUM; Index ++) {
Address = TemplateMap.ExceptionStart + TemplateMap.ExceptionStubHeaderSize * Index;
IdtGateDescriptor.Bits.OffsetHigh = (UINT16)(Address >> 16);
IdtGateDescriptor.Bits.OffsetLow = (UINT16)Address;
IdtTable[Index] = IdtGateDescriptor.Uint64;
}
if (IdtDescriptor != NULL) {
AsmWriteIdtr (&Idtr);
}
}
/**
Update exception handler in IDT table .
This function is used to update the IDT exception handler with current stage.
@param[in] IdtDescriptor If not NULL, it is new IDT descriptor to be updated.
if it is NULL, the IDT descriptor will be retrieved from IDT base register.
**/
VOID
UpdateExceptionHandler (
IN IA32_DESCRIPTOR *IdtDescriptor
)
{
UpdateDebugAgentIdt (IdtDescriptor, UpdateExceptionHandler2);
}
|
{
"pile_set_name": "Github"
}
|
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from decimal import Decimal
from typing import Any, Dict
import mock
from datadog_checks.base.stubs.aggregator import AggregatorStub
from datadog_checks.snowflake import SnowflakeCheck, queries
from .conftest import CHECK_NAME
EXPECTED_TAGS = ['account:test_acct.us-central1.gcp']
def test_storage_metrics(dd_run_check, aggregator, instance):
# type: (AggregatorStub, Dict[str, Any]) -> None
expected_storage = [(Decimal('0.000000'), Decimal('1206.000000'), Decimal('19.200000'))]
with mock.patch('datadog_checks.snowflake.SnowflakeCheck.execute_query_raw', return_value=expected_storage):
check = SnowflakeCheck(CHECK_NAME, {}, [instance])
check._conn = mock.MagicMock()
check._query_manager.queries = [queries.StorageUsageMetrics]
dd_run_check(check)
aggregator.assert_metric('snowflake.storage.storage_bytes.total', value=0.0, tags=EXPECTED_TAGS)
aggregator.assert_metric('snowflake.storage.stage_bytes.total', value=1206.0, tags=EXPECTED_TAGS)
aggregator.assert_metric('snowflake.storage.failsafe_bytes.total', value=19.2, tags=EXPECTED_TAGS)
def test_db_storage_metrics(dd_run_check, aggregator, instance):
# type: (AggregatorStub, Dict[str, Any]) -> None
expected_db_storage_usage = [('SNOWFLAKE_DB', Decimal('133.000000'), Decimal('9.100000'))]
expected_tags = EXPECTED_TAGS + ['database:SNOWFLAKE_DB']
with mock.patch(
'datadog_checks.snowflake.SnowflakeCheck.execute_query_raw', return_value=expected_db_storage_usage
):
check = SnowflakeCheck(CHECK_NAME, {}, [instance])
check._conn = mock.MagicMock()
check._query_manager.queries = [queries.DatabaseStorageMetrics]
dd_run_check(check)
aggregator.assert_metric('snowflake.storage.database.storage_bytes', value=133.0, tags=expected_tags)
aggregator.assert_metric('snowflake.storage.database.failsafe_bytes', value=9.1, tags=expected_tags)
def test_credit_usage_metrics(dd_run_check, aggregator, instance):
# type: (AggregatorStub, Dict[str, Any]) -> None
expected_credit_usage = [
(
'WAREHOUSE_METERING',
'COMPUTE_WH',
Decimal('12.000000000'),
Decimal('1.000000000'),
Decimal('0.80397000'),
Decimal('0.066997500000'),
Decimal('12.803970000'),
Decimal('1.066997500000'),
)
]
expected_tags = EXPECTED_TAGS + ['service_type:WAREHOUSE_METERING', 'service:COMPUTE_WH']
with mock.patch('datadog_checks.snowflake.SnowflakeCheck.execute_query_raw', return_value=expected_credit_usage):
check = SnowflakeCheck(CHECK_NAME, {}, [instance])
check._conn = mock.MagicMock()
check._query_manager.queries = [queries.CreditUsage]
dd_run_check(check)
aggregator.assert_metric('snowflake.billing.cloud_service.sum', count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.billing.cloud_service.avg', count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.billing.total_credit.sum', count=1)
aggregator.assert_metric('snowflake.billing.total_credit.avg', count=1)
aggregator.assert_metric('snowflake.billing.virtual_warehouse.sum', count=1)
aggregator.assert_metric('snowflake.billing.virtual_warehouse.avg', count=1)
def test_warehouse_usage_metrics(dd_run_check, aggregator, instance):
# type: (AggregatorStub, Dict[str, Any]) -> None
expected_wh_usage = [
(
'COMPUTE_WH',
Decimal('13.000000000'),
Decimal('1.000000000'),
Decimal('0.870148056'),
Decimal('0.066934465846'),
Decimal('13.870148056'),
Decimal('1.066934465846'),
)
]
expected_tags = EXPECTED_TAGS + ['warehouse:COMPUTE_WH']
with mock.patch('datadog_checks.snowflake.SnowflakeCheck.execute_query_raw', return_value=expected_wh_usage):
check = SnowflakeCheck(CHECK_NAME, {}, [instance])
check._conn = mock.MagicMock()
check._query_manager.queries = [queries.WarehouseCreditUsage]
dd_run_check(check)
aggregator.assert_metric('snowflake.billing.warehouse.cloud_service.avg', count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.billing.warehouse.total_credit.avg', count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.billing.warehouse.virtual_warehouse.avg', count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.billing.warehouse.cloud_service.sum', count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.billing.warehouse.total_credit.sum', count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.billing.warehouse.virtual_warehouse.sum', count=1, tags=expected_tags)
def test_login_metrics(dd_run_check, aggregator, instance):
# type: (AggregatorStub, Dict[str, Any]) -> None
expected_login_metrics = [('SNOWFLAKE_UI', 2, 6, 8), ('PYTHON_DRIVER', 0, 148, 148)]
with mock.patch('datadog_checks.snowflake.SnowflakeCheck.execute_query_raw', return_value=expected_login_metrics):
check = SnowflakeCheck(CHECK_NAME, {}, [instance])
check._conn = mock.MagicMock()
check._query_manager.queries = [queries.LoginMetrics]
dd_run_check(check)
snowflake_tags = EXPECTED_TAGS + ['client_type:SNOWFLAKE_UI']
aggregator.assert_metric('snowflake.logins.fail.count', value=2, tags=snowflake_tags)
aggregator.assert_metric('snowflake.logins.success.count', value=6, tags=snowflake_tags)
aggregator.assert_metric('snowflake.logins.total', value=8, tags=snowflake_tags)
python_tags = EXPECTED_TAGS + ['client_type:PYTHON_DRIVER']
aggregator.assert_metric('snowflake.logins.fail.count', value=0, tags=python_tags)
aggregator.assert_metric('snowflake.logins.success.count', value=148, tags=python_tags)
aggregator.assert_metric('snowflake.logins.total', value=148, tags=python_tags)
def test_warehouse_load(dd_run_check, aggregator, instance):
# type: (AggregatorStub, Dict[str, Any]) -> None
expected_wl_metrics = [
('COMPUTE_WH', Decimal('0.000446667'), Decimal('0E-9'), Decimal('0E-9'), Decimal('0E-9')),
]
expected_tags = EXPECTED_TAGS + ['warehouse:COMPUTE_WH']
with mock.patch('datadog_checks.snowflake.SnowflakeCheck.execute_query_raw', return_value=expected_wl_metrics):
check = SnowflakeCheck(CHECK_NAME, {}, [instance])
check._conn = mock.MagicMock()
check._query_manager.queries = [queries.WarehouseLoad]
dd_run_check(check)
aggregator.assert_metric('snowflake.query.executed', value=0.000446667, tags=expected_tags)
aggregator.assert_metric('snowflake.query.queued_overload', value=0, count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.query.queued_provision', value=0, count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.query.blocked', value=0, count=1, tags=expected_tags)
def test_query_metrics(dd_run_check, aggregator, instance):
# type: (AggregatorStub, Dict[str, Any]) -> None
expected_query_metrics = [
(
'USE',
'COMPUTE_WH',
'SNOWFLAKE',
None,
Decimal('4.333333'),
Decimal('24.555556'),
Decimal('0.000000'),
Decimal('0.000000'),
Decimal('0.000000'),
),
]
expected_tags = EXPECTED_TAGS + ['warehouse:COMPUTE_WH', 'database:SNOWFLAKE', 'schema:None', 'query_type:USE']
with mock.patch('datadog_checks.snowflake.SnowflakeCheck.execute_query_raw', return_value=expected_query_metrics):
check = SnowflakeCheck(CHECK_NAME, {}, [instance])
check._conn = mock.MagicMock()
check._query_manager.queries = [queries.QueryHistory]
dd_run_check(check)
aggregator.assert_metric('snowflake.query.execution_time', value=4.333333, tags=expected_tags)
aggregator.assert_metric('snowflake.query.compilation_time', value=24.555556, tags=expected_tags)
aggregator.assert_metric('snowflake.query.bytes_scanned', value=0, count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.query.bytes_written', value=0, count=1, tags=expected_tags)
aggregator.assert_metric('snowflake.query.bytes_deleted', value=0, count=1, tags=expected_tags)
def test_version_metadata(dd_run_check, instance, datadog_agent):
expected_version = [('4.30.2',)]
version_metadata = {
'version.major': '4',
'version.minor': '30',
'version.patch': '2',
'version.raw': '4.30.2',
'version.scheme': 'semver',
}
with mock.patch('datadog_checks.snowflake.SnowflakeCheck.execute_query_raw', return_value=expected_version):
check = SnowflakeCheck(CHECK_NAME, {}, [instance])
check.check_id = 'test:123'
check._conn = mock.MagicMock()
check._query_manager.queries = []
dd_run_check(check)
datadog_agent.assert_metadata('test:123', version_metadata)
|
{
"pile_set_name": "Github"
}
|
# Copyright (c) 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This is a dependency-free, header-only, library, and it needs to stay that
# way to facilitate pulling it into various third-party projects. So, this
# file is here to protect against accidentally introducing external
# dependencies or depending on internal implementation details.
source_set("base_numerics") {
visibility = [ "//base/*" ]
sources = [
"checked_math_impl.h",
"clamped_math_impl.h",
"safe_conversions_arm_impl.h",
"safe_conversions_impl.h",
"safe_math_arm_impl.h",
"safe_math_clang_gcc_impl.h",
"safe_math_shared_impl.h",
]
public = [
"checked_math.h",
"clamped_math.h",
"math_constants.h",
"ranges.h",
"safe_conversions.h",
"safe_math.h",
]
}
|
{
"pile_set_name": "Github"
}
|
((output (((f.ml (1 0) (1 7)) @closed) ((f.ml (2 0) (2 11)) (@deprecated))))
(warnings ()))
|
{
"pile_set_name": "Github"
}
|
/*
* Linux ethernet bridge
*
* Authors:
* Lennert Buytenhek <buytenh@gnu.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#ifndef _BR_PRIVATE_H
#define _BR_PRIVATE_H
#include <linux/netdevice.h>
#include <linux/if_bridge.h>
#include <net/route.h>
#define BR_HASH_BITS 8
#define BR_HASH_SIZE (1 << BR_HASH_BITS)
#define BR_HOLD_TIME (1*HZ)
#define BR_PORT_BITS 10
#define BR_MAX_PORTS (1<<BR_PORT_BITS)
#define BR_VERSION "2.3"
/* Path to usermode spanning tree program */
#define BR_STP_PROG "/sbin/bridge-stp"
typedef struct bridge_id bridge_id;
typedef struct mac_addr mac_addr;
typedef __u16 port_id;
struct bridge_id
{
unsigned char prio[2];
unsigned char addr[6];
};
struct mac_addr
{
unsigned char addr[6];
};
struct net_bridge_fdb_entry
{
struct hlist_node hlist;
struct net_bridge_port *dst;
struct rcu_head rcu;
unsigned long ageing_timer;
mac_addr addr;
unsigned char is_local;
unsigned char is_static;
};
struct net_bridge_port_group {
struct net_bridge_port *port;
struct net_bridge_port_group *next;
struct hlist_node mglist;
struct rcu_head rcu;
struct timer_list timer;
struct timer_list query_timer;
__be32 addr;
u32 queries_sent;
};
struct net_bridge_mdb_entry
{
struct hlist_node hlist[2];
struct hlist_node mglist;
struct net_bridge *br;
struct net_bridge_port_group *ports;
struct rcu_head rcu;
struct timer_list timer;
struct timer_list query_timer;
__be32 addr;
u32 queries_sent;
};
struct net_bridge_mdb_htable
{
struct hlist_head *mhash;
struct rcu_head rcu;
struct net_bridge_mdb_htable *old;
u32 size;
u32 max;
u32 secret;
u32 ver;
};
struct net_bridge_port
{
struct net_bridge *br;
struct net_device *dev;
struct list_head list;
/* STP */
u8 priority;
u8 state;
u16 port_no;
unsigned char topology_change_ack;
unsigned char config_pending;
port_id port_id;
port_id designated_port;
bridge_id designated_root;
bridge_id designated_bridge;
u32 path_cost;
u32 designated_cost;
struct timer_list forward_delay_timer;
struct timer_list hold_timer;
struct timer_list message_age_timer;
struct kobject kobj;
struct rcu_head rcu;
unsigned long flags;
#define BR_HAIRPIN_MODE 0x00000001
#ifdef CONFIG_BRIDGE_IGMP_SNOOPING
u32 multicast_startup_queries_sent;
unsigned char multicast_router;
struct timer_list multicast_router_timer;
struct timer_list multicast_query_timer;
struct hlist_head mglist;
struct hlist_node rlist;
#endif
};
struct net_bridge
{
spinlock_t lock;
struct list_head port_list;
struct net_device *dev;
spinlock_t hash_lock;
struct hlist_head hash[BR_HASH_SIZE];
struct list_head age_list;
unsigned long feature_mask;
#ifdef CONFIG_BRIDGE_NETFILTER
struct rtable fake_rtable;
#endif
unsigned long flags;
#define BR_SET_MAC_ADDR 0x00000001
/* STP */
bridge_id designated_root;
bridge_id bridge_id;
u32 root_path_cost;
unsigned long max_age;
unsigned long hello_time;
unsigned long forward_delay;
unsigned long bridge_max_age;
unsigned long ageing_time;
unsigned long bridge_hello_time;
unsigned long bridge_forward_delay;
u8 group_addr[ETH_ALEN];
u16 root_port;
enum {
BR_NO_STP, /* no spanning tree */
BR_KERNEL_STP, /* old STP in kernel */
BR_USER_STP, /* new RSTP in userspace */
} stp_enabled;
unsigned char topology_change;
unsigned char topology_change_detected;
#ifdef CONFIG_BRIDGE_IGMP_SNOOPING
unsigned char multicast_router;
u8 multicast_disabled:1;
u32 hash_elasticity;
u32 hash_max;
u32 multicast_last_member_count;
u32 multicast_startup_queries_sent;
u32 multicast_startup_query_count;
unsigned long multicast_last_member_interval;
unsigned long multicast_membership_interval;
unsigned long multicast_querier_interval;
unsigned long multicast_query_interval;
unsigned long multicast_query_response_interval;
unsigned long multicast_startup_query_interval;
spinlock_t multicast_lock;
struct net_bridge_mdb_htable *mdb;
struct hlist_head router_list;
struct hlist_head mglist;
struct timer_list multicast_router_timer;
struct timer_list multicast_querier_timer;
struct timer_list multicast_query_timer;
#endif
struct timer_list hello_timer;
struct timer_list tcn_timer;
struct timer_list topology_change_timer;
struct timer_list gc_timer;
struct kobject *ifobj;
};
struct br_input_skb_cb {
struct net_device *brdev;
int igmp;
int mrouters_only;
};
#define BR_INPUT_SKB_CB(__skb) ((struct br_input_skb_cb *)(__skb)->cb)
extern struct notifier_block br_device_notifier;
extern const u8 br_group_address[ETH_ALEN];
/* called under bridge lock */
static inline int br_is_root_bridge(const struct net_bridge *br)
{
return !memcmp(&br->bridge_id, &br->designated_root, 8);
}
/* br_device.c */
extern void br_dev_setup(struct net_device *dev);
extern netdev_tx_t br_dev_xmit(struct sk_buff *skb,
struct net_device *dev);
/* br_fdb.c */
extern int br_fdb_init(void);
extern void br_fdb_fini(void);
extern void br_fdb_flush(struct net_bridge *br);
extern void br_fdb_changeaddr(struct net_bridge_port *p,
const unsigned char *newaddr);
extern void br_fdb_cleanup(unsigned long arg);
extern void br_fdb_delete_by_port(struct net_bridge *br,
const struct net_bridge_port *p, int do_all);
extern struct net_bridge_fdb_entry *__br_fdb_get(struct net_bridge *br,
const unsigned char *addr);
extern int br_fdb_test_addr(struct net_device *dev, unsigned char *addr);
extern int br_fdb_fillbuf(struct net_bridge *br, void *buf,
unsigned long count, unsigned long off);
extern int br_fdb_insert(struct net_bridge *br,
struct net_bridge_port *source,
const unsigned char *addr);
extern void br_fdb_update(struct net_bridge *br,
struct net_bridge_port *source,
const unsigned char *addr);
/* br_forward.c */
extern void br_deliver(const struct net_bridge_port *to,
struct sk_buff *skb);
extern int br_dev_queue_push_xmit(struct sk_buff *skb);
extern void br_forward(const struct net_bridge_port *to,
struct sk_buff *skb, struct sk_buff *skb0);
extern int br_forward_finish(struct sk_buff *skb);
extern void br_flood_deliver(struct net_bridge *br, struct sk_buff *skb);
extern void br_flood_forward(struct net_bridge *br, struct sk_buff *skb,
struct sk_buff *skb2);
/* br_if.c */
extern void br_port_carrier_check(struct net_bridge_port *p);
extern int br_add_bridge(struct net *net, const char *name);
extern int br_del_bridge(struct net *net, const char *name);
extern void br_net_exit(struct net *net);
extern int br_add_if(struct net_bridge *br,
struct net_device *dev);
extern int br_del_if(struct net_bridge *br,
struct net_device *dev);
extern int br_min_mtu(const struct net_bridge *br);
extern void br_features_recompute(struct net_bridge *br);
/* br_input.c */
extern int br_handle_frame_finish(struct sk_buff *skb);
extern struct sk_buff *br_handle_frame(struct net_bridge_port *p,
struct sk_buff *skb);
/* br_ioctl.c */
extern int br_dev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
extern int br_ioctl_deviceless_stub(struct net *net, unsigned int cmd, void __user *arg);
/* br_multicast.c */
#ifdef CONFIG_BRIDGE_IGMP_SNOOPING
extern int br_multicast_rcv(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb);
extern struct net_bridge_mdb_entry *br_mdb_get(struct net_bridge *br,
struct sk_buff *skb);
extern void br_multicast_add_port(struct net_bridge_port *port);
extern void br_multicast_del_port(struct net_bridge_port *port);
extern void br_multicast_enable_port(struct net_bridge_port *port);
extern void br_multicast_disable_port(struct net_bridge_port *port);
extern void br_multicast_init(struct net_bridge *br);
extern void br_multicast_open(struct net_bridge *br);
extern void br_multicast_stop(struct net_bridge *br);
extern void br_multicast_deliver(struct net_bridge_mdb_entry *mdst,
struct sk_buff *skb);
extern void br_multicast_forward(struct net_bridge_mdb_entry *mdst,
struct sk_buff *skb, struct sk_buff *skb2);
extern int br_multicast_set_router(struct net_bridge *br, unsigned long val);
extern int br_multicast_set_port_router(struct net_bridge_port *p,
unsigned long val);
extern int br_multicast_toggle(struct net_bridge *br, unsigned long val);
extern int br_multicast_set_hash_max(struct net_bridge *br, unsigned long val);
static inline bool br_multicast_is_router(struct net_bridge *br)
{
return br->multicast_router == 2 ||
(br->multicast_router == 1 &&
timer_pending(&br->multicast_router_timer));
}
#else
static inline int br_multicast_rcv(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
return 0;
}
static inline struct net_bridge_mdb_entry *br_mdb_get(struct net_bridge *br,
struct sk_buff *skb)
{
return NULL;
}
static inline void br_multicast_add_port(struct net_bridge_port *port)
{
}
static inline void br_multicast_del_port(struct net_bridge_port *port)
{
}
static inline void br_multicast_enable_port(struct net_bridge_port *port)
{
}
static inline void br_multicast_disable_port(struct net_bridge_port *port)
{
}
static inline void br_multicast_init(struct net_bridge *br)
{
}
static inline void br_multicast_open(struct net_bridge *br)
{
}
static inline void br_multicast_stop(struct net_bridge *br)
{
}
static inline void br_multicast_deliver(struct net_bridge_mdb_entry *mdst,
struct sk_buff *skb)
{
}
static inline void br_multicast_forward(struct net_bridge_mdb_entry *mdst,
struct sk_buff *skb,
struct sk_buff *skb2)
{
}
static inline bool br_multicast_is_router(struct net_bridge *br)
{
return 0;
}
#endif
/* br_netfilter.c */
#ifdef CONFIG_BRIDGE_NETFILTER
extern int br_netfilter_init(void);
extern void br_netfilter_fini(void);
extern void br_netfilter_rtable_init(struct net_bridge *);
#else
#define br_netfilter_init() (0)
#define br_netfilter_fini() do { } while(0)
#define br_netfilter_rtable_init(x)
#endif
/* br_stp.c */
extern void br_log_state(const struct net_bridge_port *p);
extern struct net_bridge_port *br_get_port(struct net_bridge *br,
u16 port_no);
extern void br_init_port(struct net_bridge_port *p);
extern void br_become_designated_port(struct net_bridge_port *p);
/* br_stp_if.c */
extern void br_stp_enable_bridge(struct net_bridge *br);
extern void br_stp_disable_bridge(struct net_bridge *br);
extern void br_stp_set_enabled(struct net_bridge *br, unsigned long val);
extern void br_stp_enable_port(struct net_bridge_port *p);
extern void br_stp_disable_port(struct net_bridge_port *p);
extern void br_stp_recalculate_bridge_id(struct net_bridge *br);
extern void br_stp_change_bridge_id(struct net_bridge *br, const unsigned char *a);
extern void br_stp_set_bridge_priority(struct net_bridge *br,
u16 newprio);
extern void br_stp_set_port_priority(struct net_bridge_port *p,
u8 newprio);
extern void br_stp_set_path_cost(struct net_bridge_port *p,
u32 path_cost);
extern ssize_t br_show_bridge_id(char *buf, const struct bridge_id *id);
/* br_stp_bpdu.c */
struct stp_proto;
extern void br_stp_rcv(const struct stp_proto *proto, struct sk_buff *skb,
struct net_device *dev);
/* br_stp_timer.c */
extern void br_stp_timer_init(struct net_bridge *br);
extern void br_stp_port_timer_init(struct net_bridge_port *p);
extern unsigned long br_timer_value(const struct timer_list *timer);
/* br.c */
#if defined(CONFIG_ATM_LANE) || defined(CONFIG_ATM_LANE_MODULE)
extern int (*br_fdb_test_addr_hook)(struct net_device *dev, unsigned char *addr);
#endif
/* br_netlink.c */
extern int br_netlink_init(void);
extern void br_netlink_fini(void);
extern void br_ifinfo_notify(int event, struct net_bridge_port *port);
#ifdef CONFIG_SYSFS
/* br_sysfs_if.c */
extern const struct sysfs_ops brport_sysfs_ops;
extern int br_sysfs_addif(struct net_bridge_port *p);
/* br_sysfs_br.c */
extern int br_sysfs_addbr(struct net_device *dev);
extern void br_sysfs_delbr(struct net_device *dev);
#else
#define br_sysfs_addif(p) (0)
#define br_sysfs_addbr(dev) (0)
#define br_sysfs_delbr(dev) do { } while(0)
#endif /* CONFIG_SYSFS */
#endif
|
{
"pile_set_name": "Github"
}
|
@media \0screen {
body { background: red; }
}
|
{
"pile_set_name": "Github"
}
|
/* Copyright 2016 Sam Hewitt.
*
* This file is part of the Paper GTK theme.
*
* The Paper GTK theme 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.
*
* The Paper GTK theme is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with the Paper GTK theme. If not, see http://www.gnu.org/licenses/.
*/
/************************
* Sidebar & Source List *
************************/
.sidebar,
.sidebar .view,
.sidebar GtkScrolledWindow,
.source-list,
.source-list.view {
background-color: @background;
color: @foreground;
}
GtkDialog .sidebar,
GtkDialog .sidebar .view,
GtkDialog .sidebar GtkScrolledWindow {
background-color: shade (@background, 1.07);
}
.sidebar,
.sidebar .view,
.sidebar .view:selected:backdrop,
.sidebar .view:hover:selected:backdrop,
.source-list,
.source-list.view,
.source-list.view:selected:backdrop,
.source-list.view:hover:selected:backdrop {
}
.sidebar,
.source-list {
-GtkTreeView-horizontal-separator: 1px;
-GtkTreeView-vertical-separator: 6px;
}
.sidebar .separator,
.source-list .separator {
color: @separator;
}
.sidebar .separator:backdrop,
.source-list .separator:backdrop {
color: @backdrop_separator;
}
.sidebar:backdrop,
.source-list:backdrop {
border: solid @backdrop_border;
border-left-width: 1px;
}
.source-list.category-expander {
color: transparent;
}
.sidebar .view:hover,
.source-list.view:hover {
background-color: shade (@background, 1.02);
}
.sidebar .view:selected,
.sidebar .view:hover:selected,
.sidebar.view:selected,
.sidebar.view:hover:selected,
.source-list.view:selected,
.source-list.view:hover:selected,
.source-list.view:selected:focus,
.source-list.category-expander:hover {
color: @selection_foreground;
background-color: @selection;
box-shadow: none;
}
GtkDialog .sidebar .view:selected,
GtkDialog .sidebar .view:hover:selected {
color: @selection_foreground;
background-color: @selection;
}
.sidebar .view:selected:backdrop,
.sidebar .view:hover:selected:backdrop,
.source-list.view:selected:backdrop,
.source-list.view:hover:selected:backdrop {
color: alpha(@selection, 0.5);
}
GtkDialog .sidebar .view:selected:backdrop,
GtkDialog .sidebar .view:hover:selected:backdrop {
color: alpha(@selection, 0.5);
}
.sidebar-pane-separator,
.sidebar-pane-separator:hover,
.sidebar-pane-separator:selected {
border-width: 0;
-GtkPaned-handle-size: 1;
background-image: none;
/*background-color: shade (@background, 0.75);*/
}
.sidebar .scrollbar.trough,
.sidebar .scrollbars-junction,
.source-list .scrollbar.trough,
.source-list .scrollbars-junction {
background-color: @background;
}
.source-list.badge,
.source-list.badge:hover,
.source-list.badge:selected,
.source-list.badge:selected:focus,
.source-list.badge:hover:selected {
background-image: none;
background-color: alpha(#000, 0.4);
color: @background;
border-radius: 10px;
padding: 0 6px;
margin: 0 3px;
border-width: 0;
}
.source-list.badge:selected,
.source-list.badge:hover:selected {
color: @background;
}
.source-list.badge:selected:backdrop,
.source-list.badge:selected:hover:backdrop {
background-image: none;
background-color: alpha(#000, 0.2);
color: shade (@background, 0.95);
}
.sidebar .separator {
color: @separator;
}
.sidebar .separator:backdrop {
color: @backdrop_separator;
}
|
{
"pile_set_name": "Github"
}
|
package dasm
import (
"fmt"
"shanhu.io/smlvm/arch"
)
// Dasm disassembles a byte block.
func Dasm(bs []byte, addr uint32) []*Line {
var ret []*Line
base := addr
add := func(b []byte) {
inst := arch.Endian.Uint32(b)
ret = append(ret, NewLine(addr, inst))
addr += 4
}
nline := len(bs) / 4
for i := 0; i < nline; i++ {
off := i * 4
add(bs[off : off+4])
}
// residue
if len(bs)%4 != 0 {
var buf [4]byte
copy(buf[:], bs[nline*4:])
add(buf[:])
}
// link the jumps
for _, line := range ret {
if !line.IsJump {
continue
}
index := int(line.To-base) / 4
if index >= 0 && index < nline {
line.ToLine = ret[index]
}
}
return ret
}
// Print prints a byte block as assembly lines.
func Print(bs []byte, addr uint32) {
lines := Dasm(bs, addr)
for _, line := range lines {
fmt.Println(line)
}
}
|
{
"pile_set_name": "Github"
}
|
const _ = require('underscore');
const files = require('../fs/files');
const buildmessage = require('../utils/buildmessage.js');
const utils = require('../utils/utils.js');
const runLog = require('./run-log.js');
const release = require('../packaging/release.js');
const Console = require('../console/console.js').Console;
const Proxy = require('./run-proxy.js').Proxy;
const Selenium = require('./run-selenium.js').Selenium;
const AppRunner = require('./run-app.js').AppRunner;
const MongoRunner = require('./run-mongo.js').MongoRunner;
const Updater = require('./run-updater.js').Updater;
class Runner {
constructor({
appHost,
appPort,
banner,
disableOplog,
cordovaRunner,
mongoUrl,
onFailure,
oplogUrl,
projectContext,
proxyHost,
proxyPort,
quiet,
rootUrl,
selenium,
seleniumBrowser,
noReleaseCheck,
...optionsForAppRunner
}) {
const self = this;
self.projectContext = projectContext;
if (typeof proxyPort === 'undefined') {
throw new Error('no proxyPort?');
}
const listenPort = proxyPort;
const mongoPort = parseInt(listenPort, 10) + 1;
self.specifiedAppPort = appPort;
self.regenerateAppPort();
self.stopped = false;
self.noReleaseCheck = noReleaseCheck;
self.quiet = quiet;
self.banner = banner || files.convertToOSPath(
files.prettyPath(self.projectContext.projectDir)
);
if (rootUrl) {
self.rootUrl = rootUrl;
} else {
self.rootUrl = utils.formatUrl({
protocol: 'http',
hostname: proxyHost || "localhost",
port: listenPort,
});
}
self.proxy = new Proxy({
listenPort,
listenHost: proxyHost,
proxyToPort: self.appPort,
proxyToHost: appHost,
onFailure
});
buildmessage.capture(function () {
self.projectContext.resolveConstraints();
});
const packageMap = self.projectContext.packageMap;
const hasMongoDevServerPackage =
packageMap && packageMap.getInfo('mongo-dev-server') != null;
self.mongoRunner = null;
if (mongoUrl) {
oplogUrl = disableOplog ? null : oplogUrl;
} else if (hasMongoDevServerPackage
|| process.env.METEOR_TEST_FAKE_MONGOD_CONTROL_PORT) {
// The mongo-dev-server package is required to start Mongo, but
// tests using fake-mongod are exempted.
self.mongoRunner = new MongoRunner({
projectLocalDir: self.projectContext.projectLocalDir,
port: mongoPort,
onFailure,
// For testing mongod failover, run with 3 mongod if the env var is
// set. Note that data is not preserved from one run to the next.
multiple: !!process.env.METEOR_TEST_MULTIPLE_MONGOD_REPLSET
});
mongoUrl = self.mongoRunner.mongoUrl();
oplogUrl = disableOplog ? null : self.mongoRunner.oplogUrl();
} else {
// Don't start a mongodb server.
// Set monogUrl to a specific value to prevent MongoDB connections
// and to allow a check for printing a message if `mongo-dev-server`
// is added while the app is running.
// The check and message is printed by the `mongo-dev-server` package.
mongoUrl = 'no-mongo-server';
}
self.updater = new Updater();
self.appRunner = new AppRunner({
...optionsForAppRunner,
projectContext: self.projectContext,
port: self.appPort,
listenHost: appHost,
mongoUrl,
oplogUrl,
rootUrl: self.rootUrl,
proxy: self.proxy,
noRestartBanner: self.quiet,
cordovaRunner: cordovaRunner
});
self.selenium = null;
if (selenium) {
self.selenium = new Selenium({
runner: self,
browser: seleniumBrowser
});
}
}
// XXX leave a pidfile and check if we are already running
start() {
const self = this;
self.proxy.start();
// print the banner only once we've successfully bound the port
if (! self.quiet && ! self.stopped) {
runLog.log("[[[[[ " + self.banner + " ]]]]]\n");
runLog.log("Started proxy.", { arrow: true });
}
var unblockAppRunner = self.appRunner.makeBeforeStartPromise();
function startMongo(tries = 3) {
self._startMongoAsync().then(
ok => unblockAppRunner(),
error => {
--tries;
const left = tries + (tries === 1 ? " try" : " tries");
Console.error(
`Error starting Mongo (${left} left): ${error.message}`
);
if (tries > 0) {
self.mongoRunner.stop();
setTimeout(() => startMongo(tries), 1000);
} else {
self.mongoRunner._fail();
}
}
);
}
startMongo();
if (!self.noReleaseCheck && ! self.stopped) {
self.updater.start();
}
if (! self.stopped) {
buildmessage.enterJob({ title: "starting your app" }, function () {
self.appRunner.start();
});
if (! self.quiet && ! self.stopped) {
runLog.log("Started your app.", { arrow: true });
}
}
if (! self.stopped && ! self.quiet) {
runLog.log("");
if (process.env.UNIX_SOCKET_PATH) {
runLog.log(
`App running; UNIX domain socket: ${process.env.UNIX_SOCKET_PATH}`,
{ arrow: true }
);
} else {
runLog.log("App running at: " + self.rootUrl, { arrow: true });
}
if (process.platform === "win32") {
runLog.log(" Type Control-C twice to stop.");
runLog.log("");
}
}
if (self.selenium && ! self.stopped) {
buildmessage.enterJob({ title: "starting Selenium" }, function () {
self.selenium.start();
});
if (! self.quiet && ! self.stopped) {
runLog.log("Started Selenium.", { arrow: true });
}
}
// XXX It'd be nice to (cosmetically) handle failure better. Right
// now we overwrite the "starting foo..." message with the
// error. It'd be better to overwrite it with "failed to start
// foo" and then print the error.
}
async _startMongoAsync() {
if (! this.stopped && this.mongoRunner) {
this.mongoRunner.start();
if (! this.stopped && ! this.quiet) {
runLog.log("Started MongoDB.", { arrow: true });
}
}
}
// Idempotent
stop() {
const self = this;
if (self.stopped) {
return;
}
self.stopped = true;
self.proxy.stop();
self.updater.stop();
self.mongoRunner && self.mongoRunner.stop();
self.appRunner.stop();
self.selenium && self.selenium.stop();
// XXX does calling this 'finish' still make sense now that runLog is a
// singleton?
runLog.finish();
}
// Call this whenever you want to regenerate the app's port (if it is not
// explicitly specified by the user).
//
// Rationale: if we randomly chose a port that's in use and the app failed to
// listen on it, we should try a different port when we restart the app!
regenerateAppPort() {
const self = this;
if (self.specifiedAppPort) {
self.appPort = self.specifiedAppPort;
} else {
self.appPort = require('../utils/utils.js').randomPort();
}
if (self.proxy) {
self.proxy.proxyToPort = self.appPort;
}
if (self.appRunner) {
self.appRunner.port = self.appPort;
}
}
}
// Run the app and all of its associated processes. Runs (and does not
// return) until an unrecoverable failure happens. Logs to
// stdout. Returns a suggested exit code.
//
// If 'once' is set, run the app process exactly once and pass through
// its exit code. Return an exit code of 255 if the app process was
// killed by a signal and 254 if the app process could not start
// (build failure, invalid program name, database couldn't start, and
// so on).
//
// If the 'once' option is not set, the default, restart the app
// process if it crashes or if source files change. (Non-app
// processes, such as the database, are always restarted as
// necessary.) The function will only return if there is an
// unrecoverable error, which generally means an error that could not
// be fixed by source code changes (such as the database refusing to
// run), but also currently includes Meteor version mismatches. So the
// exit code will always be 254 because in all other cases we'll
// persevere.
//
// Options:
//
// - proxyPort: the port to connect to to access the application (we will
// run a proxy here that proxies to the actual app process). required
// - buildOptions: 'buildOptions' argument to bundler.bundle()
// - settingsFile: path to file containing deploy-time settings
// - once: see above
// - banner: replace the application path that is normally printed on
// startup with an arbitrary string (eg, 'Tests')
// - rootUrl: tell the app that traffic at this URL will be routed to
// it at '/' (used by the app to construct absolute URLs)
// - disableOplog: don't use oplog tailing
// - mongoUrl: don't start a mongo process; instead use the mongo at
// this mongo URL
// - oplogUrl: URL of the mongo oplog to use. if mongoUrl isn't
// set (we're starting a mongo) a default will be provided, but can
// be overridden. if mongoUrl is set, you must set this or you don't
// get oplog tailing.
// - recordPackageUsage: (default true) if set to false, don't send
// information about packages used by this app to the package stats
// server.
exports.run = function (options) {
var runOptions = _.clone(options);
var once = runOptions.once;
var promise = new Promise(function (resolve) {
runOptions.onFailure = function () {
// Ensure that runner stops now. You might think this is unnecessary
// because the runner is stopped immediately after promise.await(), but if
// the failure happens while runner.start() is still running, we want the
// rest of start to stop, and it's not like resolve() magically makes
// us jump to a promise.await() that hasn't happened yet!.
runner.stop();
resolve({ outcome: 'failure' });
};
runOptions.onRunEnd = function (result) {
if (once ||
result.outcome === "conflicting-versions" ||
result.outcome === "wrong-release" ||
result.outcome === "outdated-cordova-platforms" ||
result.outcome === "outdated-cordova-plugins" ||
(result.outcome === "terminated" &&
result.signal === undefined && result.code === undefined)) {
resolve(result);
return false; // stop restarting
}
runner.regenerateAppPort();
return true; // restart it
};
});
runOptions.watchForChanges = ! once;
runOptions.quiet = false;
// Ensure process.env.NODE_ENV matches the build mode, with the following precedence:
// 1. Passed in build mode (if development or production)
// 2. Existing process.env.NODE_ENV (if it's valid)
// 3. Default to development (in both cases) otherwise
// NOTE: because this code only runs when using `meteor run` or `meteor test[-packages`,
// We *don't* end up defaulting NODE_ENV in this way when bundling/deploying.
// In those cases, it will default to "production" in packages/meteor/*_env.js
// We *override* NODE_ENV if build mode is one of these values
let buildMode = runOptions.buildOptions.buildMode;
if (buildMode === "development" || buildMode === "production") {
process.env.NODE_ENV = buildMode;
}
let nodeEnv = process.env.NODE_ENV;
// We *never* override buildMode (it can be "test")
if (!buildMode) {
if (nodeEnv === "development" || nodeEnv === "production") {
runOptions.buildOptions.buildMode = nodeEnv;
} else {
runOptions.buildOptions.buildMode = "development";
}
}
if (!nodeEnv) {
process.env.NODE_ENV = "development";
}
var runner = new Runner(runOptions);
runner.start();
var result = promise.await();
runner.stop();
if (result.outcome === "conflicting-versions") {
Console.error(
"The constraint solver could not find a set of package versions to",
"use that would satisfy the constraints of .meteor/versions and",
".meteor/packages. This could be caused by conflicts in",
".meteor/versions, conflicts in .meteor/packages, and/or",
"inconsistent changes to the dependencies in local packages.");
return 254;
}
if (result.outcome === "outdated-cordova-plugins") {
Console.error("Your app's Cordova plugins have changed.");
Console.error("Restart meteor to use the new set of plugins.");
return 254;
}
if (result.outcome === "outdated-cordova-platforms") {
Console.error("Your app's platforms have changed.");
Console.error("Restart meteor to use the new set of platforms.");
return 254;
}
if (result.outcome === "wrong-release") {
if (once) {
// We lost a race where the user ran 'meteor update' and 'meteor
// run --once' simultaneously.
throw new Error("wrong release?");
}
// If the user did not specify a --release on the command line,
// and simultaneously runs `meteor update` during this run, just
// exit and let them restart the run. (We can do something fancy
// like allowing this to work if the tools version didn't change,
// or even springboarding if the tools version does change, but
// this (which prevents weird errors) is a start.)
var from = release.current.getDisplayName();
var to = result.displayReleaseNeeded;
Console.error(
"Your app has been updated to " + to + " from " + from + ".",
"Restart meteor to use the new release.");
return 254;
}
if (result.outcome === "failure" ||
(result.outcome === "terminated" &&
result.signal === undefined && result.code === undefined)) {
// Fatal problem with something other than the app process. An
// explanation should already have been logged.
return 254;
}
if (once && result.outcome === "bundle-fail") {
Console.arrowError("Build failed:\n\n" +
result.errors.formatMessages());
return 254;
}
if (once && result.outcome === "terminated") {
if (result.signal) {
Console.error("Killed (" + result.signal + ")");
return 255;
} else if (typeof result.code === "number") {
// We used to print 'Your application is exiting' here, but that
// seems unnecessarily chatty? once mode is otherwise silent
return result.code;
} else {
// If there is neither a code nor a signal, it means that we
// failed to start the process. We logged the reason. Probably a
// bad program name.
return 254;
}
}
throw new Error("unexpected outcome " + result.outcome);
};
|
{
"pile_set_name": "Github"
}
|
{
"id": "record-player",
"name": "Record Player",
"category": "Furniture",
"games": {
"nl": {
"orderable": true,
"sellPrice": {
"currency": "bells",
"value": 350
},
"sources": [
"Nookling stores"
],
"buyPrices": [
{
"currency": "bells",
"value": 1400
}
]
}
}
}
|
{
"pile_set_name": "Github"
}
|
//
// DirectoryIterator_UNIX.h
//
// $Id: //poco/1.4/Foundation/include/Poco/DirectoryIterator_UNIX.h#1 $
//
// Library: Foundation
// Package: Filesystem
// Module: DirectoryIterator
//
// Definition of the DirectoryIteratorImpl class for UNIX.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Foundation_DirectoryIterator_UNIX_INCLUDED
#define Foundation_DirectoryIterator_UNIX_INCLUDED
#include "Poco/Foundation.h"
#include <dirent.h>
namespace Poco {
class Foundation_API DirectoryIteratorImpl
{
public:
DirectoryIteratorImpl(const std::string& path);
~DirectoryIteratorImpl();
void duplicate();
void release();
const std::string& get() const;
const std::string& next();
private:
DIR* _pDir;
std::string _current;
int _rc;
};
//
// inlines
//
const std::string& DirectoryIteratorImpl::get() const
{
return _current;
}
inline void DirectoryIteratorImpl::duplicate()
{
++_rc;
}
inline void DirectoryIteratorImpl::release()
{
if (--_rc == 0)
delete this;
}
} // namespace Poco
#endif // Foundation_DirectoryIterator_UNIX_INCLUDED
|
{
"pile_set_name": "Github"
}
|
# -----------------------------------------------------------------------------
# calclex.py
# -----------------------------------------------------------------------------
import ply.lex as lex
tokens = (
'NAME','NUMBER',
'PLUS','MINUS','TIMES','DIVIDE','EQUALS',
'LPAREN','RPAREN',
)
# Tokens
t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'
t_EQUALS = r'='
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
def t_NUMBER(t):
r'\d+'
try:
t.value = int(t.value)
except ValueError:
print("Integer value too large %s" % t.value)
t.value = 0
return t
t_ignore = " \t"
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Build the lexer
import os.path
lexer = lex.lex(optimize=True, outputdir=os.path.dirname(__file__))
|
{
"pile_set_name": "Github"
}
|
@charset "UTF-8";
/*
* jQuery File Upload Plugin CSS Example
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
body {
padding-top: 60px;
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
</head>
<body>
<div align="center">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="550" height="400">
<param name="movie" value="swf/5-28-2.swf">
<param name="quality" value="high">
<embed src="swf/5-28-2.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="550" height="400"></embed></object>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
var baseToString = require('./_baseToString'),
castSlice = require('./_castSlice'),
charsEndIndex = require('./_charsEndIndex'),
stringToArray = require('./_stringToArray'),
toString = require('./toString');
/** Used to match leading and trailing whitespace. */
var reTrimEnd = /\s+$/;
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimEnd, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}
module.exports = trimEnd;
|
{
"pile_set_name": "Github"
}
|
var baseToString = require('./_baseToString'),
castSlice = require('./_castSlice'),
charsEndIndex = require('./_charsEndIndex'),
stringToArray = require('./_stringToArray'),
toString = require('./toString');
/** Used to match leading and trailing whitespace. */
var reTrimEnd = /\s+$/;
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimEnd, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}
module.exports = trimEnd;
|
{
"pile_set_name": "Github"
}
|
---
title: My First Post
---
This is my first post!
|
{
"pile_set_name": "Github"
}
|
// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------
module.exports = class extends think.Model {
/**
* 获取分类详细信息
* @param {milit} id 分类ID或者标识
* @param {string} field 查询字段
* @return {array} 分类信息
*/
async info(id, field) {
field = think.isEmpty(field) || '';
const map = {};
if (think.isNumberString(id)) {
map.id = id;
} else {
map.name = id;
}
return await this.field(field).where(map).find();
}
/**
* 获取分类树,指定分类则返回指定分类及其子分类,不指定则返回所有分类树
*
*/
async gettree(id, field, where = {}) {
id = id || 0, field = field || true;
/* 获取当前分类信息 */
// if(id){
// console.log(id);
// let ids = id;
// let info = await this.info(ids);
// console.log(info);
// let id = info.id;
// }
// 获取所有分类
const map = think.extend({'status': {'>': -1}}, where);
let list = await this.field(field).where(map).order('sort ASC').select();
for (const v of list) {
if (!think.isEmpty(v.name)) {
v.url = `/${v.name}`;
} else {
v.url = `/${v.id}`;
}
}
// console.log(list);
list = get_children(list, id);
const info = list;
return info;
}
/**
* 获取分类信息并缓存分类
* @param integer id 分类ID
* @param string field 要获取的字段名
* @return string 分类信息
*/
async get_category(id, field) {
field = field || null;
const list = await think.cache('sys_category_list', () => {
return this.getallcate();
}, {timeout: 365 * 24 * 3600});
/* 非法分类ID */
if (think.isEmpty(id) || !think.isNumberString(id)) {
return list;
} else if (list[id]) {
if (think.isEmpty(list) || list[id].status != 1) { // 不存在分类,或分类被禁用
return '';
}
/// / console.log(list);
// console.log(list[id]);
// console.log(think.isNumber(field));
return think.isEmpty(field) ? list[id] : list[id][field];
} else {
return '';
}
}
async getallcate() {
const lists = {};
const cate = await this.select();
for (const v of cate) {
if (!think.isEmpty(v.name)) {
v.url = `/${v.name}`;
} else {
v.url = `/${v.id}`;
}
lists[v.id] = v;
}
return lists;
}
/**
* 获取参数的所有父级分类
* @param int id 分类id
* @param true true 带url
* @return array 参数分类和父类的信息集合
* @author
*/
async get_parent_category(id, url) {
const breadcrumb = [];
while (id != 0) {
const nav = await this.where({'id': id}).field('id,title,pid,allow_publish,name,mold').find();
if (url) {
if (!think.isEmpty(nav.name)) {
nav.url = `/${nav.name}`;
} else {
nav.url = `/${nav.id}`;
}
}
breadcrumb.push(nav);
id = nav.pid;
}
return breadcrumb.reverse();
}
async get_sub_category(id) {
const cat = await this.select();
const data = sub_cate(cat, id);
// console.log(data);
const arr = [];
for (const v of data) {
if (think.isString(v)) {
for (const val of v.split(',')) {
arr.push(Number(val));
};
} else {
arr.push(v);
}
}
return arr;
}
/**
* 验证分类是否允许发布内容
* @param id 分类id
* @returns {boolean} true-允许发布内容,false-不允许发布内容
*/
async check_category(id) {
if (think.isObject(id)) {
id.type = !think.isEmpty(id.type) ? id.type : 2;
let type = await this.get_category(id.category_id, 'type');
type = type.split(',');
return in_array(id.type, type);
} else {
const publish = await this.get_category(id, 'allow_publish');
return !!publish;
}
}
/**
* 获取当前分类的文档类型
* @param id
* @returns {*}文档类型对象
*/
async get_type_bycate(id) {
id = id || null;
if (think.isEmpty(id)) {
return false;
}
const type_list = think.config('document_model_type');
let model_type = await this.where({id: id}).getField('type', 1);
model_type = model_type[0].split(',');
for (const key in type_list) {
if (!in_array(key, model_type)) {
delete type_list[key];
}
}
return type_list;
}
/**
*
* @param data
* @returns {*}
*/
async updates(data) {
if (think.isEmpty(data)) {
return false;
}
let res;
/* 添加或更新数据 */
if (think.isEmpty(data.id)) {
data.create_time = new Date().getTime();
data.model = think.isArray(data.model) ? data.model.join(',') : data.model;
data.model_sub = think.isArray(data.model_sub) ? data.model_sub.join(',') : data.model_sub;
data.type = think.isArray(data.type) ? data.type.join(',') : data.model;
// console.log(data);
res = await this.add(data);
if (res) {
// 构造权限
const priv = [];
if (!think.isEmpty(data.priv_roleid)) {
if (think.isArray(data.priv_roleid)) {
// 构造 角色权限
for (const v of data.priv_roleid) {
const arr = v.split(',');
const obj = {};
obj.catid = res;
obj.siteid = 1;
obj.roleid = arr[1];
obj.action = arr[0];
obj.is_admin = 1;
priv.push(obj);
}
} else {
const arr = (data.priv_roleid).split(',');
priv.push({ catid: res, siteid: 1, roleid: arr[1], action: arr[0], is_admin: 1 });
}
}
if (!think.isEmpty(data.priv_groupid)) {
// 构造 用户组权限
if (think.isArray(data.priv_groupid)) {
for (const v of data.priv_groupid) {
const arr = v.split(',');
const obj = {};
obj.catid = res;
obj.siteid = 1;
obj.roleid = arr[1];
obj.action = arr[0];
obj.is_admin = 0;
priv.push(obj);
}
} else {
const arr = (data.priv_groupid).split(',');
priv.push({ catid: res, siteid: 1, roleid: arr[1], action: arr[0], is_admin: 0 });
}
}
if (!think.isEmpty(priv)) {
await this.model('category_priv').addMany(priv);
}
}
} else {
data.update_time = new Date().getTime();
data.model = think.isArray(data.model) ? data.model.join(',') : data.model;
data.model_sub = think.isArray(data.model_sub) ? data.model_sub.join(',') : data.model_sub;
data.type = think.isArray(data.type) ? data.type.join(',') : '';
res = await this.update(data);
if (res) {
// 构造权限
const priv = [];
if (!think.isEmpty(data.priv_roleid)) {
if (think.isArray(data.priv_roleid)) {
// 构造 角色权限
for (const v of data.priv_roleid) {
const arr = v.split(',');
const obj = {};
obj.catid = data.id;
obj.siteid = 1;
obj.roleid = arr[1];
obj.action = arr[0];
obj.is_admin = 1;
priv.push(obj);
}
} else {
const arr = (data.priv_roleid).split(',');
priv.push({ catid: data.id, siteid: 1, roleid: arr[1], action: arr[0], is_admin: 1 });
}
}
if (!think.isEmpty(data.priv_groupid)) {
// 构造 用户组权限
if (think.isArray(data.priv_groupid)) {
for (const v of data.priv_groupid) {
const arr = v.split(',');
const obj = {};
obj.catid = data.id;
obj.siteid = 1;
obj.roleid = arr[1];
obj.action = arr[0];
obj.is_admin = 0;
priv.push(obj);
}
} else {
const arr = (data.priv_groupid).split(',');
priv.push({ catid: data.id, siteid: 1, roleid: arr[1], action: arr[0], is_admin: 0 });
}
}
await this.model('category_priv').delete({where: {catid: data.id}});
if (!think.isEmpty(priv)) {
await this.model('category_priv').addMany(priv);
}
}
}
// 清除缓存
await update_cache('category');
return res;
}
/**
*
*/
async get_all_category(map = {}) {
// let list ="22";
const list = await think.cache('all_category', () => {
return this.get_colunm();
}, {timeout: 365 * 24 * 3600});
if (think.isEmpty(map)) {
return list;
} else {
return think._.filter(list, map);
}
}
async get_colunm() {
const lists = await this.where({status: 1}).field('id,title as name,name as title,pid,allow_publish,isapp,mold,description,icon').order('pid,sort').select();
for (const v of lists) {
if (!think.isEmpty(v.title)) {
v.url = `/${v.title}`;
} else {
v.url = `/${v.id}`;
}
}
// console.log(lists);
return lists;
}
// 获取栏目分组
async get_groups(cid) {
let group;
let groups = await this.where({id: cid}).getField('groups', true);
if (!think.isEmpty(groups)) {
const cate = await get_cate(cid);
if (groups.search(/\r\n/ig) > -1) {
groups = groups.split('\r\n');
const arr = [];
groups.forEach(n => {
const obj = {};
n = n.split(':');
obj.url = cate.url + '/' + n[0];
obj.name = n[1];
obj.id = Number(n[0]);
arr.push(obj);
});
group = arr;
}
}
return group;
}
};
|
{
"pile_set_name": "Github"
}
|
{
"type": "bundle",
"id": "bundle--9d7b4098-1afa-446f-baf7-605b8d074b97",
"spec_version": "2.0",
"objects": [
{
"id": "relationship--b41c9b77-536b-49bc-8cb9-a873aa121002",
"created_by_ref": "identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5",
"description": "[PoisonIvy](https://attack.mitre.org/software/S0012) uses the Camellia cipher to encrypt communications.(Citation: FireEye Poison Ivy)",
"object_marking_refs": [
"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168"
],
"external_references": [
{
"source_name": "FireEye Poison Ivy",
"description": "FireEye. (2014). POISON IVY: Assessing Damage and Extracting Intelligence. Retrieved November 12, 2014.",
"url": "https://www.fireeye.com/content/dam/fireeye-www/global/en/current-threats/pdfs/rpt-poison-ivy.pdf"
}
],
"source_ref": "malware--b42378e0-f147-496f-992a-26a49705395b",
"relationship_type": "uses",
"target_ref": "attack-pattern--24bfaeba-cb0d-4525-b3dc-507c77ecec41",
"type": "relationship",
"modified": "2020-03-21T00:08:07.216Z",
"created": "2017-12-14T16:46:06.044Z"
}
]
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package precis
import "errors"
// This file contains tables and code related to context rules.
type catBitmap uint16
const (
// These bits, once set depending on the current value, are never unset.
bJapanese catBitmap = 1 << iota
bArabicIndicDigit
bExtendedArabicIndicDigit
// These bits are set on each iteration depending on the current value.
bJoinStart
bJoinMid
bJoinEnd
bVirama
bLatinSmallL
bGreek
bHebrew
// These bits indicated which of the permanent bits need to be set at the
// end of the checks.
bMustHaveJapn
permanent = bJapanese | bArabicIndicDigit | bExtendedArabicIndicDigit | bMustHaveJapn
)
const finalShift = 10
var errContext = errors.New("precis: contextual rule violated")
func init() {
// Programmatically set these required bits as, manually setting them seems
// too error prone.
for i, ct := range categoryTransitions {
categoryTransitions[i].keep |= permanent
categoryTransitions[i].accept |= ct.term
}
}
var categoryTransitions = []struct {
keep catBitmap // mask selecting which bits to keep from the previous state
set catBitmap // mask for which bits to set for this transition
// These bitmaps are used for rules that require lookahead.
// term&accept == term must be true, which is enforced programmatically.
term catBitmap // bits accepted as termination condition
accept catBitmap // bits that pass, but not sufficient as termination
// The rule function cannot take a *context as an argument, as it would
// cause the context to escape, adding significant overhead.
rule func(beforeBits catBitmap) (doLookahead bool, err error)
}{
joiningL: {set: bJoinStart},
joiningD: {set: bJoinStart | bJoinEnd},
joiningT: {keep: bJoinStart, set: bJoinMid},
joiningR: {set: bJoinEnd},
viramaModifier: {set: bVirama},
viramaJoinT: {set: bVirama | bJoinMid},
latinSmallL: {set: bLatinSmallL},
greek: {set: bGreek},
greekJoinT: {set: bGreek | bJoinMid},
hebrew: {set: bHebrew},
hebrewJoinT: {set: bHebrew | bJoinMid},
japanese: {set: bJapanese},
katakanaMiddleDot: {set: bMustHaveJapn},
zeroWidthNonJoiner: {
term: bJoinEnd,
accept: bJoinMid,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bVirama != 0 {
return false, nil
}
if before&bJoinStart == 0 {
return false, errContext
}
return true, nil
},
},
zeroWidthJoiner: {
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bVirama == 0 {
err = errContext
}
return false, err
},
},
middleDot: {
term: bLatinSmallL,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bLatinSmallL == 0 {
return false, errContext
}
return true, nil
},
},
greekLowerNumeralSign: {
set: bGreek,
term: bGreek,
rule: func(before catBitmap) (doLookAhead bool, err error) {
return true, nil
},
},
hebrewPreceding: {
set: bHebrew,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bHebrew == 0 {
err = errContext
}
return false, err
},
},
arabicIndicDigit: {
set: bArabicIndicDigit,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bExtendedArabicIndicDigit != 0 {
err = errContext
}
return false, err
},
},
extendedArabicIndicDigit: {
set: bExtendedArabicIndicDigit,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bArabicIndicDigit != 0 {
err = errContext
}
return false, err
},
},
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package precis
import "errors"
// This file contains tables and code related to context rules.
type catBitmap uint16
const (
// These bits, once set depending on the current value, are never unset.
bJapanese catBitmap = 1 << iota
bArabicIndicDigit
bExtendedArabicIndicDigit
// These bits are set on each iteration depending on the current value.
bJoinStart
bJoinMid
bJoinEnd
bVirama
bLatinSmallL
bGreek
bHebrew
// These bits indicated which of the permanent bits need to be set at the
// end of the checks.
bMustHaveJapn
permanent = bJapanese | bArabicIndicDigit | bExtendedArabicIndicDigit | bMustHaveJapn
)
const finalShift = 10
var errContext = errors.New("precis: contextual rule violated")
func init() {
// Programmatically set these required bits as, manually setting them seems
// too error prone.
for i, ct := range categoryTransitions {
categoryTransitions[i].keep |= permanent
categoryTransitions[i].accept |= ct.term
}
}
var categoryTransitions = []struct {
keep catBitmap // mask selecting which bits to keep from the previous state
set catBitmap // mask for which bits to set for this transition
// These bitmaps are used for rules that require lookahead.
// term&accept == term must be true, which is enforced programmatically.
term catBitmap // bits accepted as termination condition
accept catBitmap // bits that pass, but not sufficient as termination
// The rule function cannot take a *context as an argument, as it would
// cause the context to escape, adding significant overhead.
rule func(beforeBits catBitmap) (doLookahead bool, err error)
}{
joiningL: {set: bJoinStart},
joiningD: {set: bJoinStart | bJoinEnd},
joiningT: {keep: bJoinStart, set: bJoinMid},
joiningR: {set: bJoinEnd},
viramaModifier: {set: bVirama},
viramaJoinT: {set: bVirama | bJoinMid},
latinSmallL: {set: bLatinSmallL},
greek: {set: bGreek},
greekJoinT: {set: bGreek | bJoinMid},
hebrew: {set: bHebrew},
hebrewJoinT: {set: bHebrew | bJoinMid},
japanese: {set: bJapanese},
katakanaMiddleDot: {set: bMustHaveJapn},
zeroWidthNonJoiner: {
term: bJoinEnd,
accept: bJoinMid,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bVirama != 0 {
return false, nil
}
if before&bJoinStart == 0 {
return false, errContext
}
return true, nil
},
},
zeroWidthJoiner: {
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bVirama == 0 {
err = errContext
}
return false, err
},
},
middleDot: {
term: bLatinSmallL,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bLatinSmallL == 0 {
return false, errContext
}
return true, nil
},
},
greekLowerNumeralSign: {
set: bGreek,
term: bGreek,
rule: func(before catBitmap) (doLookAhead bool, err error) {
return true, nil
},
},
hebrewPreceding: {
set: bHebrew,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bHebrew == 0 {
err = errContext
}
return false, err
},
},
arabicIndicDigit: {
set: bArabicIndicDigit,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bExtendedArabicIndicDigit != 0 {
err = errContext
}
return false, err
},
},
extendedArabicIndicDigit: {
set: bExtendedArabicIndicDigit,
rule: func(before catBitmap) (doLookAhead bool, err error) {
if before&bArabicIndicDigit != 0 {
err = errContext
}
return false, err
},
},
}
|
{
"pile_set_name": "Github"
}
|
//
// connection.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "connection.hpp"
#include <vector>
#include <boost/bind/bind.hpp>
#include "request_handler.hpp"
namespace http {
namespace server2 {
connection::connection(asio::io_context& io_context,
request_handler& handler)
: socket_(io_context),
request_handler_(handler)
{
}
asio::ip::tcp::socket& connection::socket()
{
return socket_;
}
void connection::start()
{
socket_.async_read_some(asio::buffer(buffer_),
boost::bind(&connection::handle_read, shared_from_this(),
asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
void connection::handle_read(const asio::error_code& e,
std::size_t bytes_transferred)
{
if (!e)
{
boost::tribool result;
boost::tie(result, boost::tuples::ignore) = request_parser_.parse(
request_, buffer_.data(), buffer_.data() + bytes_transferred);
if (result)
{
request_handler_.handle_request(request_, reply_);
asio::async_write(socket_, reply_.to_buffers(),
boost::bind(&connection::handle_write, shared_from_this(),
asio::placeholders::error));
}
else if (!result)
{
reply_ = reply::stock_reply(reply::bad_request);
asio::async_write(socket_, reply_.to_buffers(),
boost::bind(&connection::handle_write, shared_from_this(),
asio::placeholders::error));
}
else
{
socket_.async_read_some(asio::buffer(buffer_),
boost::bind(&connection::handle_read, shared_from_this(),
asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
}
// If an error occurs then no new asynchronous operations are started. This
// means that all shared_ptr references to the connection object will
// disappear and the object will be destroyed automatically after this
// handler returns. The connection class's destructor closes the socket.
}
void connection::handle_write(const asio::error_code& e)
{
if (!e)
{
// Initiate graceful connection closure.
asio::error_code ignored_ec;
socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignored_ec);
}
// No new asynchronous operations are started. This means that all shared_ptr
// references to the connection object will disappear and the object will be
// destroyed automatically after this handler returns. The connection class's
// destructor closes the socket.
}
} // namespace server2
} // namespace http
|
{
"pile_set_name": "Github"
}
|
// Copyright (C) 2009-2012 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE_1_0.txt or a copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Home at http://www.boost.org/libs/local_function
#if !BOOST_PP_IS_ITERATING
# ifndef BOOST_LOCAL_FUNCTION_AUX_FUNCTION_HPP_
# define BOOST_LOCAL_FUNCTION_AUX_FUNCTION_HPP_
# include <boost/local_function/config.hpp>
# include <boost/local_function/aux_/member.hpp>
# include <boost/call_traits.hpp>
# include <boost/typeof/typeof.hpp>
# include <boost/config.hpp>
# include <boost/preprocessor/iteration/iterate.hpp>
# include <boost/preprocessor/repetition/repeat.hpp>
# include <boost/preprocessor/repetition/enum.hpp>
# include <boost/preprocessor/punctuation/comma_if.hpp>
# include <boost/preprocessor/arithmetic/add.hpp>
# include <boost/preprocessor/arithmetic/sub.hpp>
# include <boost/preprocessor/arithmetic/inc.hpp>
# include <boost/preprocessor/control/iif.hpp>
# include <boost/preprocessor/cat.hpp>
// PRIVATE //
#define BOOST_LOCAL_FUNCTION_AUX_FUNCTION_THIS_FILE_ \
"boost/local_function/aux_/function.hpp"
// PUBLIC //
#define BOOST_LOCAL_FUNCTION_AUX_FUNCTION_INIT_CALL_FUNC \
BOOST_LOCAL_FUNCTION_AUX_SYMBOL( (init_call) )
#define BOOST_LOCAL_FUNCTION_AUX_typename_seq(z, n, unused) \
(typename)
#define BOOST_LOCAL_FUNCTION_AUX_arg_type(z, arg_n, unused) \
BOOST_PP_CAT(Arg, arg_n)
#define BOOST_LOCAL_FUNCTION_AUX_arg_typedef(z, arg_n, unused) \
typedef \
BOOST_LOCAL_FUNCTION_AUX_arg_type(z, arg_n, ~) \
/* name must follow Boost.FunctionTraits arg1_type, arg2_type, ... */ \
BOOST_PP_CAT(BOOST_PP_CAT(arg, BOOST_PP_INC(arg_n)), _type) \
;
#define BOOST_LOCAL_FUNCTION_AUX_comma_arg_tparam(z, arg_n, unused) \
, typename BOOST_LOCAL_FUNCTION_AUX_arg_type(z, arg_n, ~)
#define BOOST_LOCAL_FUNCTION_AUX_arg_param_type(z, arg_n, comma01) \
BOOST_PP_COMMA_IF(comma01) \
typename ::boost::call_traits< \
BOOST_LOCAL_FUNCTION_AUX_arg_type(z, arg_n, ~) \
>::param_type
#define BOOST_LOCAL_FUNCTION_AUX_arg_name(z, arg_n, comma01) \
BOOST_PP_COMMA_IF(comma01) \
BOOST_PP_CAT(arg, arg_n)
#define BOOST_LOCAL_FUNCTION_AUX_arg_param_decl(z, arg_n, unused) \
BOOST_LOCAL_FUNCTION_AUX_arg_param_type(z, arg_n, 0 /* no leading comma */)\
BOOST_LOCAL_FUNCTION_AUX_arg_name(z, arg_n, 0 /* no leading comma */)
#define BOOST_LOCAL_FUNCTION_AUX_bind_type(z, bind_n, unused) \
BOOST_PP_CAT(Bind, bind_n)
#define BOOST_LOCAL_FUNCTION_AUX_comma_bind_type(z, bind_n, unused) \
, BOOST_LOCAL_FUNCTION_AUX_bind_type(z, bind_n, ~)
#define BOOST_LOCAL_FUNCTION_AUX_comma_bind_ref(z, bind_n, unused) \
, BOOST_LOCAL_FUNCTION_AUX_bind_type(z, bind_n, ~) &
#define BOOST_LOCAL_FUNCTION_AUX_comma_bind_tparam(z, bind_n, unused) \
, typename BOOST_LOCAL_FUNCTION_AUX_bind_type(z, bind_n, ~)
#define BOOST_LOCAL_FUNCTION_AUX_bind_name(z, bind_n, unused) \
BOOST_PP_CAT(bing, bind_n)
#define BOOST_LOCAL_FUNCTION_AUX_comma_bind_param_decl(z, bind_n, unused) \
, \
BOOST_LOCAL_FUNCTION_AUX_bind_type(z, bind_n, ~) & \
BOOST_LOCAL_FUNCTION_AUX_bind_name(z, bind_n, ~)
#define BOOST_LOCAL_FUNCTION_AUX_bind_member(z, bind_n, unsued) \
BOOST_PP_CAT(BOOST_LOCAL_FUNCTION_AUX_bind_name(z, bind_n, ~), _)
#define BOOST_LOCAL_FUNCTION_AUX_comma_bind_member_deref(z, bind_n, unsued) \
, member_deref< BOOST_LOCAL_FUNCTION_AUX_bind_type(z, bind_n, ~) >( \
BOOST_LOCAL_FUNCTION_AUX_bind_member(z, bind_n, ~))
#define BOOST_LOCAL_FUNCTION_AUX_bind_member_init(z, bind_n, unused) \
BOOST_LOCAL_FUNCTION_AUX_bind_member(z, bind_n, ~) = member_addr( \
BOOST_LOCAL_FUNCTION_AUX_bind_name(z, bind_n, ~));
#define BOOST_LOCAL_FUNCTION_AUX_bind_member_decl(z, bind_n, unused) \
/* must be ptr (not ref) so can use default constr */ \
typename member_type< \
BOOST_LOCAL_FUNCTION_AUX_bind_type(z, bind_n, ~) \
>::pointer BOOST_LOCAL_FUNCTION_AUX_bind_member(z, bind_n, ~) ;
#define BOOST_LOCAL_FUNCTION_AUX_call_ptr(z, n, unused) \
BOOST_PP_CAT(call_ptr, n)
#define BOOST_LOCAL_FUNCTION_AUX_call_name(z, n, unused) \
BOOST_PP_CAT(call, n)
#define BOOST_LOCAL_FUNCTION_AUX_call_member(z, n, unused) \
BOOST_PP_CAT(BOOST_LOCAL_FUNCTION_AUX_call_name(z, n, unused), _)
#define BOOST_LOCAL_FUNCTION_AUX_call_typedef(z, n, arity) \
typedef R (*BOOST_LOCAL_FUNCTION_AUX_call_ptr(z, n, ~))( \
object_ptr \
BOOST_PP_IIF(BOOST_LOCAL_FUNCTION_CONFIG_LOCALS_AS_TPARAMS, \
BOOST_PP_TUPLE_EAT(3) \
, \
BOOST_PP_REPEAT_ ## z \
)(BOOST_LOCAL_FUNCTION_CONFIG_BIND_MAX, \
BOOST_LOCAL_FUNCTION_AUX_comma_bind_ref, ~) \
BOOST_PP_REPEAT_ ## z(BOOST_PP_SUB(arity, n), \
BOOST_LOCAL_FUNCTION_AUX_arg_param_type, 1 /* leading comma */)\
);
#define BOOST_LOCAL_FUNCTION_AUX_comma_call_param_decl(z, n, unused) \
, \
BOOST_LOCAL_FUNCTION_AUX_call_ptr(z, n, ~) \
BOOST_LOCAL_FUNCTION_AUX_call_name(z, n, ~)
#define BOOST_LOCAL_FUNCTION_AUX_call_decl(z, n, unused) \
BOOST_LOCAL_FUNCTION_AUX_call_ptr(z, n, ~) \
BOOST_LOCAL_FUNCTION_AUX_call_member(z, n, ~);
#define BOOST_LOCAL_FUNCTION_AUX_call_init(z, n, unused) \
BOOST_LOCAL_FUNCTION_AUX_call_member(z, n, ~) = \
BOOST_LOCAL_FUNCTION_AUX_call_name(z, n, ~);
#define BOOST_LOCAL_FUNCTION_AUX_operator_call(z, defaults_n, arity) \
/* precondition: object_ && call_function_ */ \
inline R operator()( \
BOOST_PP_ENUM_ ## z(BOOST_PP_SUB(arity, defaults_n), \
BOOST_LOCAL_FUNCTION_AUX_arg_param_decl, ~) \
) /* cannot be const because of binds (same as for local ftor) */ { \
/* run-time: do not assert preconditions here for efficiency */ \
/* run-time: this function call is done via a function pointer */ \
/* so unfortunately does not allow for compiler inlining */ \
/* optimizations (an alternative using virtual function was also */ \
/* investigated but also virtual functions cannot be optimized */ \
/* plus they require virtual table lookups to the alternative */ \
/* performed worst) */ \
return BOOST_LOCAL_FUNCTION_AUX_call_member(z, defaults_n, ~)( \
object_ \
BOOST_PP_IIF( \
BOOST_LOCAL_FUNCTION_CONFIG_LOCALS_AS_TPARAMS,\
BOOST_PP_TUPLE_EAT(3) \
, \
BOOST_PP_REPEAT_ ## z \
)(BOOST_LOCAL_FUNCTION_CONFIG_BIND_MAX, \
BOOST_LOCAL_FUNCTION_AUX_comma_bind_member_deref, ~) \
BOOST_PP_REPEAT_ ## z(BOOST_PP_SUB(arity, defaults_n), \
BOOST_LOCAL_FUNCTION_AUX_arg_name, 1 /* leading comma */) \
); \
}
namespace boost { namespace local_function { namespace aux {
template<
typename F
, size_t defaults
#if !BOOST_LOCAL_FUNCTION_CONFIG_LOCALS_AS_TPARAMS
BOOST_PP_REPEAT(BOOST_LOCAL_FUNCTION_CONFIG_BIND_MAX,
BOOST_LOCAL_FUNCTION_AUX_comma_bind_tparam, ~)
#endif
>
class function {}; // Empty template, only use its specializations.
// Iterate within namespace.
# define BOOST_PP_ITERATION_PARAMS_1 \
(3, (0, BOOST_LOCAL_FUNCTION_CONFIG_FUNCTION_ARITY_MAX, \
BOOST_LOCAL_FUNCTION_AUX_FUNCTION_THIS_FILE_))
# include BOOST_PP_ITERATE() // Iterate over function arity.
} } } // namespace
// Register type for type-of emu (NAME use TYPEOF to deduce this fctor type).
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
BOOST_TYPEOF_REGISTER_TEMPLATE(boost::local_function::aux::function,
(typename) // For `F` tparam.
(size_t) // For `defaults` tparam.
// MSVC error if using #if instead of PP_IIF here.
BOOST_PP_IIF(BOOST_LOCAL_FUNCTION_CONFIG_LOCALS_AS_TPARAMS,
BOOST_PP_TUPLE_EAT(3) // Nothing.
,
BOOST_PP_REPEAT // For bind tparams.
)(BOOST_LOCAL_FUNCTION_CONFIG_BIND_MAX,
BOOST_LOCAL_FUNCTION_AUX_typename_seq, ~)
)
#undef BOOST_LOCAL_FUNCTION_AUX_typename_seq
#undef BOOST_LOCAL_FUNCTION_AUX_arg_type
#undef BOOST_LOCAL_FUNCTION_AUX_arg_typedef
#undef BOOST_LOCAL_FUNCTION_AUX_comma_arg_tparam
#undef BOOST_LOCAL_FUNCTION_AUX_arg_param_type
#undef BOOST_LOCAL_FUNCTION_AUX_arg_name
#undef BOOST_LOCAL_FUNCTION_AUX_arg_param_decl
#undef BOOST_LOCAL_FUNCTION_AUX_bind_type
#undef BOOST_LOCAL_FUNCTION_AUX_comma_bind_type
#undef BOOST_LOCAL_FUNCTION_AUX_comma_bind_ref
#undef BOOST_LOCAL_FUNCTION_AUX_comma_bind_tparam
#undef BOOST_LOCAL_FUNCTION_AUX_bind_name
#undef BOOST_LOCAL_FUNCTION_AUX_comma_bind_param_decl
#undef BOOST_LOCAL_FUNCTION_AUX_bind_member
#undef BOOST_LOCAL_FUNCTION_AUX_comma_bind_member_deref
#undef BOOST_LOCAL_FUNCTION_AUX_bind_member_init
#undef BOOST_LOCAL_FUNCTION_AUX_bind_member_decl
#undef BOOST_LOCAL_FUNCTION_AUX_call_ptr
#undef BOOST_LOCAL_FUNCTION_AUX_call_name
#undef BOOST_LOCAL_FUNCTION_AUX_call_member
#undef BOOST_LOCAL_FUNCTION_AUX_call_typedef
#undef BOOST_LOCAL_FUNCTION_AUX_comma_call_param_decl
#undef BOOST_LOCAL_FUNCTION_AUX_call_decl
#undef BOOST_LOCAL_FUNCTION_AUX_call_init
#undef BOOST_LOCAL_FUNCTION_AUX_operator_call
# endif // #include guard
#elif BOOST_PP_ITERATION_DEPTH() == 1
# define BOOST_LOCAL_FUNCTION_AUX_arity BOOST_PP_FRAME_ITERATION(1)
# define BOOST_PP_ITERATION_PARAMS_2 \
(3, (0, BOOST_LOCAL_FUNCTION_AUX_arity, \
BOOST_LOCAL_FUNCTION_AUX_FUNCTION_THIS_FILE_))
# include BOOST_PP_ITERATE() // Iterate over default params count.
# undef BOOST_LOCAL_FUNCTION_AUX_arity
#elif BOOST_PP_ITERATION_DEPTH() == 2
# define BOOST_LOCAL_FUNCTION_AUX_defaults BOOST_PP_FRAME_ITERATION(2)
template<
typename R
BOOST_PP_REPEAT(BOOST_LOCAL_FUNCTION_AUX_arity,
BOOST_LOCAL_FUNCTION_AUX_comma_arg_tparam, ~)
#if !BOOST_LOCAL_FUNCTION_CONFIG_LOCALS_AS_TPARAMS
BOOST_PP_REPEAT(BOOST_LOCAL_FUNCTION_CONFIG_BIND_MAX,
BOOST_LOCAL_FUNCTION_AUX_comma_bind_tparam, ~)
#endif
>
class function<
R (
BOOST_PP_ENUM(BOOST_LOCAL_FUNCTION_AUX_arity,
BOOST_LOCAL_FUNCTION_AUX_arg_type, ~)
)
, BOOST_LOCAL_FUNCTION_AUX_defaults
#if !BOOST_LOCAL_FUNCTION_CONFIG_LOCALS_AS_TPARAMS
BOOST_PP_REPEAT(BOOST_LOCAL_FUNCTION_CONFIG_BIND_MAX,
BOOST_LOCAL_FUNCTION_AUX_comma_bind_type, ~)
#endif
> {
// The object type will actually be a local class which cannot be passed as
// a template parameter so a generic `void*` pointer is used to hold the
// object (this pointer will then be cased by the call-function implemented
// by the local class itself). This is the trick used to pass a local
// function as a template parameter. This trick uses function pointers for
// the call-functions and function pointers cannot always be optimized by
// the compiler (they cannot be inlined) thus this trick increased run-time
// (another trick using virtual functions for the local class was also
// investigated but also virtual functions cannot be inlined plus they
// require virtual tables lookups so the virtual functions trick measured
// worst run-time performance than the function pointer trick).
typedef void* object_ptr;
BOOST_PP_REPEAT(BOOST_PP_INC(BOOST_LOCAL_FUNCTION_AUX_defaults),
BOOST_LOCAL_FUNCTION_AUX_call_typedef, // INC for no defaults.
BOOST_LOCAL_FUNCTION_AUX_arity)
public:
// Provide public type interface following Boost.Function names
// (traits must be defined in both this and the local functor).
BOOST_STATIC_CONSTANT(size_t, arity = BOOST_LOCAL_FUNCTION_AUX_arity);
typedef R result_type;
BOOST_PP_REPEAT(BOOST_LOCAL_FUNCTION_AUX_arity,
BOOST_LOCAL_FUNCTION_AUX_arg_typedef, ~)
// NOTE: Must have default constructor for init without function name in
// function macro expansion.
// Cannot be private but it should never be used by programmers directly
// so used internal symbol.
inline void BOOST_LOCAL_FUNCTION_AUX_FUNCTION_INIT_CALL_FUNC(
object_ptr object
#if !BOOST_LOCAL_FUNCTION_CONFIG_LOCALS_AS_TPARAMS
BOOST_PP_REPEAT(BOOST_LOCAL_FUNCTION_CONFIG_BIND_MAX,
BOOST_LOCAL_FUNCTION_AUX_comma_bind_param_decl, ~)
#endif
BOOST_PP_REPEAT(BOOST_PP_INC(BOOST_LOCAL_FUNCTION_AUX_defaults),
BOOST_LOCAL_FUNCTION_AUX_comma_call_param_decl, ~)
) {
object_ = object;
#if !BOOST_LOCAL_FUNCTION_CONFIG_LOCALS_AS_TPARAMS
BOOST_PP_REPEAT(BOOST_LOCAL_FUNCTION_CONFIG_BIND_MAX,
BOOST_LOCAL_FUNCTION_AUX_bind_member_init, ~)
#endif
BOOST_PP_REPEAT(BOOST_PP_INC(BOOST_LOCAL_FUNCTION_AUX_defaults),
BOOST_LOCAL_FUNCTION_AUX_call_init, ~) // INC for no defaults.
unused_ = 0; // To avoid a GCC uninitialized warning.
}
// Result operator(Arg1, ..., ArgN-1, ArgN) -- iff defaults >= 0
// Result operator(Arg1, ..., ArgN-1) -- iff defaults >= 1
// ... -- etc
BOOST_PP_REPEAT(BOOST_PP_INC(BOOST_LOCAL_FUNCTION_AUX_defaults),
BOOST_LOCAL_FUNCTION_AUX_operator_call, // INC for no defaults.
BOOST_LOCAL_FUNCTION_AUX_arity)
private:
object_ptr object_;
#if !BOOST_LOCAL_FUNCTION_CONFIG_LOCALS_AS_TPARAMS
BOOST_PP_REPEAT(BOOST_LOCAL_FUNCTION_CONFIG_BIND_MAX,
BOOST_LOCAL_FUNCTION_AUX_bind_member_decl, ~)
#endif
BOOST_PP_REPEAT(BOOST_PP_INC(BOOST_LOCAL_FUNCTION_AUX_defaults),
BOOST_LOCAL_FUNCTION_AUX_call_decl, ~) // INC for no defaults.
// run-time: this unused void* member variable allows for compiler
// optimizations (at least on MSVC it reduces invocation time of about 50%)
void* unused_;
};
# undef BOOST_LOCAL_FUNCTION_AUX_defaults
#endif // iteration
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" ?>
<!DOCTYPE translationbundle>
<translationbundle lang="bn">
<translation id="130631256467250065">পরের বার আপনি আপনার ডিভাইস পুনরারম্ভ করলে আপনার পরিবর্তনগুলি প্রভাবী হবে৷</translation>
<translation id="275588974610408078">Chromium-এ ক্র্যাশ প্রতিবেদন উপলব্ধ নেই৷</translation>
<translation id="3064346599913645280">আপনি একটি নিরাপদ Chromium পৃষ্ঠা দেখছেন</translation>
<translation id="3550966579244642892">Chromium OS তার প্রাথমিক সেটআপ সম্পূর্ণ করেনি।</translation>
<translation id="4365115785552740256">Chromium <ph name="BEGIN_LINK_CHROMIUM" /> Chromium<ph name="END_LINK_CHROMIUM" /> ওপেন সোর্স প্রকল্প এবং অন্যান্য <ph name="BEGIN_LINK_OSS" />ওপেন সোর্স সফ্টওয়্যার<ph name="END_LINK_OSS" /> দিয়ে করা সম্ভব হয়েছে৷</translation>
<translation id="4559775032954821361">Chromium মেনুতে
যান >
<ph name="SETTINGS_TITLE" />
>
<ph name="ADVANCED_TITLE" />
>
<ph name="PROXIES_TITLE" />
>
LAN সেটিংস
এবং "আপনার LAN এর জন্য একটি প্রক্সি সার্ভার ব্যবহার করুন" চেকবাক্সটি অনির্বাচন করুন৷</translation>
<translation id="48558539577516920">আপনার ফায়ারওয়াল বা অ্যান্টিভাইরাস সেটিংসে Chromium কে নেটওয়ার্ক অ্যাক্সেস
করতে অনুমতি দিন।</translation>
<translation id="580822234363523061">Chromium মেনুতে
যান >
<ph name="SETTINGS_TITLE" />
>
<ph name="ADVANCED_TITLE" />
>
<ph name="PROXIES_TITLE" />
এবং আপনার কনফিগারেশন "প্রক্সি নয়" বা "সরাসরি" তে সেট আছে কি না নিশ্চিত করুন৷</translation>
<translation id="6613594504749178791">আপনার পরিবর্তনগুলি পরবর্তী সময় আপনি Chromium আবার চালু হলে ফলপ্রদ হবে৷</translation>
<translation id="7861509383340276692">Chromium মেনুতে
যান >
<ph name="SETTINGS_TITLE" />
>
<ph name="ADVANCED_TITLE" />
এবং অনির্বাচন করুন "<ph name="NO_PREFETCH_DESCRIPTION" />৷"
যদি এটি সমস্যাটির সমাধান না করে, তাহলে উন্নত কার্য সম্পাদনার জন্য আবার এই বিকল্পটি নির্বাচন করা সুপারিশ আমরা করি৷</translation>
<translation id="8187289872471304532">Applications > System Preferences > Network > Advanced > Proxies এ যান
এবং নির্বাচিত থাকা যে কোনো প্রক্সি অনির্বাচন করুন৷</translation>
<translation id="8684913864886094367">Chromium সঠিকভাবে বন্ধ হয়নি৷</translation>
</translationbundle>
|
{
"pile_set_name": "Github"
}
|
# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) [](https://travis-ci.org/stefanpenner/es6-promise)
This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js) extracted by @jakearchibald, if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js).
For API details and how to use promises, see the <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises HTML5Rocks article</a>.
## Downloads
* [es6-promise 27.86 KB (7.33 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.js)
* [es6-promise-min 6.17 KB (2.4 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.min.js)
## Node.js
To install:
```sh
npm install es6-promise
```
To use:
```js
var Promise = require('es6-promise').Promise;
```
## Bower
To install:
```sh
bower install es6-promise --save
```
## Usage in IE<9
`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example.
However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production:
```js
promise['catch'](function(err) {
// ...
});
```
Or use `.then` instead:
```js
promise.then(undefined, function(err) {
// ...
});
```
## Auto-polyfill
To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet:
```js
require('es6-promise').polyfill();
```
Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called.
## Building & Testing
You will need to have PhantomJS installed globally in order to run the tests.
`npm install -g phantomjs`
* `npm run build` to build
* `npm test` to run tests
* `npm start` to run a build watcher, and webserver to test
* `npm run test:server` for a testem test runner and watching builder
|
{
"pile_set_name": "Github"
}
|
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cldr
import (
"archive/zip"
"bytes"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
)
// A Decoder loads an archive of CLDR data.
type Decoder struct {
dirFilter []string
sectionFilter []string
loader Loader
cldr *CLDR
curLocale string
}
// SetSectionFilter takes a list top-level LDML element names to which
// evaluation of LDML should be limited. It automatically calls SetDirFilter.
func (d *Decoder) SetSectionFilter(filter ...string) {
d.sectionFilter = filter
// TODO: automatically set dir filter
}
// SetDirFilter limits the loading of LDML XML files of the specied directories.
// Note that sections may be split across directories differently for different CLDR versions.
// For more robust code, use SetSectionFilter.
func (d *Decoder) SetDirFilter(dir ...string) {
d.dirFilter = dir
}
// A Loader provides access to the files of a CLDR archive.
type Loader interface {
Len() int
Path(i int) string
Reader(i int) (io.ReadCloser, error)
}
var fileRe = regexp.MustCompile(".*/(.*)/(.*)\\.xml")
// Decode loads and decodes the files represented by l.
func (d *Decoder) Decode(l Loader) (cldr *CLDR, err error) {
d.cldr = makeCLDR()
for i := 0; i < l.Len(); i++ {
fname := l.Path(i)
if m := fileRe.FindStringSubmatch(fname); m != nil {
if len(d.dirFilter) > 0 && !in(d.dirFilter, m[1]) {
continue
}
var r io.Reader
if r, err = l.Reader(i); err == nil {
err = d.decode(m[1], m[2], r)
}
if err != nil {
return nil, err
}
}
}
d.cldr.finalize(d.sectionFilter)
return d.cldr, nil
}
func (d *Decoder) decode(dir, id string, r io.Reader) error {
var v interface{}
var l *LDML
cldr := d.cldr
switch {
case dir == "supplemental":
v = cldr.supp
case dir == "transforms":
return nil
case dir == "bcp47":
v = cldr.bcp47
case dir == "validity":
return nil
default:
ok := false
if v, ok = cldr.locale[id]; !ok {
l = &LDML{}
v, cldr.locale[id] = l, l
}
}
x := xml.NewDecoder(r)
if err := x.Decode(v); err != nil {
log.Printf("%s/%s: %v", dir, id, err)
return err
}
if l != nil {
if l.Identity == nil {
return fmt.Errorf("%s/%s: missing identity element", dir, id)
}
// TODO: verify when CLDR bug http://unicode.org/cldr/trac/ticket/8970
// is resolved.
// path := strings.Split(id, "_")
// if lang := l.Identity.Language.Type; lang != path[0] {
// return fmt.Errorf("%s/%s: language was %s; want %s", dir, id, lang, path[0])
// }
}
return nil
}
type pathLoader []string
func makePathLoader(path string) (pl pathLoader, err error) {
err = filepath.Walk(path, func(path string, _ os.FileInfo, err error) error {
pl = append(pl, path)
return err
})
return pl, err
}
func (pl pathLoader) Len() int {
return len(pl)
}
func (pl pathLoader) Path(i int) string {
return pl[i]
}
func (pl pathLoader) Reader(i int) (io.ReadCloser, error) {
return os.Open(pl[i])
}
// DecodePath loads CLDR data from the given path.
func (d *Decoder) DecodePath(path string) (cldr *CLDR, err error) {
loader, err := makePathLoader(path)
if err != nil {
return nil, err
}
return d.Decode(loader)
}
type zipLoader struct {
r *zip.Reader
}
func (zl zipLoader) Len() int {
return len(zl.r.File)
}
func (zl zipLoader) Path(i int) string {
return zl.r.File[i].Name
}
func (zl zipLoader) Reader(i int) (io.ReadCloser, error) {
return zl.r.File[i].Open()
}
// DecodeZip loads CLDR data from the zip archive for which r is the source.
func (d *Decoder) DecodeZip(r io.Reader) (cldr *CLDR, err error) {
buffer, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
archive, err := zip.NewReader(bytes.NewReader(buffer), int64(len(buffer)))
if err != nil {
return nil, err
}
return d.Decode(zipLoader{archive})
}
|
{
"pile_set_name": "Github"
}
|
#
# Copyright (C) 2006-2009 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
I2C_MENU:=I2C support
ModuleConfVar=$(word 1,$(subst :,$(space),$(1)))
ModuleFullPath=$(LINUX_DIR)/$(word 2,$(subst :,$(space),$(1))).ko
ModuleKconfig=$(foreach mod,$(1),$(call ModuleConfVar,$(mod)))
ModuleFiles=$(foreach mod,$(1),$(call ModuleFullPath,$(mod)))
ModuleAuto=$(call AutoLoad,$(1),$(foreach mod,$(2),$(basename $(notdir $(call ModuleFullPath,$(mod))))),$(3))
define i2c_defaults
SUBMENU:=$(I2C_MENU)
KCONFIG:=$(call ModuleKconfig,$(1))
FILES:=$(call ModuleFiles,$(1))
AUTOLOAD:=$(call ModuleAuto,$(2),$(1),$(3))
endef
I2C_CORE_MODULES:= \
CONFIG_I2C:drivers/i2c/i2c-core \
CONFIG_I2C_CHARDEV:drivers/i2c/i2c-dev
ifeq ($(CONFIG_OF),y)
I2C_CORE_MODULES+=CONFIG_OF_I2C:drivers/of/of_i2c@lt3.12
endif
define KernelPackage/i2c-core
$(call i2c_defaults,$(I2C_CORE_MODULES),51)
TITLE:=I2C support
endef
define KernelPackage/i2c-core/description
Kernel modules for I2C support
endef
$(eval $(call KernelPackage,i2c-core))
I2C_ALGOBIT_MODULES:= \
CONFIG_I2C_ALGOBIT:drivers/i2c/algos/i2c-algo-bit
define KernelPackage/i2c-algo-bit
$(call i2c_defaults,$(I2C_ALGOBIT_MODULES),55)
TITLE:=I2C bit-banging interfaces
DEPENDS:=kmod-i2c-core
endef
define KernelPackage/i2c-algo-bit/description
Kernel modules for I2C bit-banging interfaces
endef
$(eval $(call KernelPackage,i2c-algo-bit))
I2C_ALGOPCA_MODULES:= \
CONFIG_I2C_ALGOPCA:drivers/i2c/algos/i2c-algo-pca
define KernelPackage/i2c-algo-pca
$(call i2c_defaults,$(I2C_ALGOPCA_MODULES),55)
TITLE:=I2C PCA 9564 interfaces
DEPENDS:=kmod-i2c-core
endef
define KernelPackage/i2c-algo-pca/description
Kernel modules for I2C PCA 9564 interfaces
endef
$(eval $(call KernelPackage,i2c-algo-pca))
I2C_ALGOPCF_MODULES:= \
CONFIG_I2C_ALGOPCF:drivers/i2c/algos/i2c-algo-pcf
define KernelPackage/i2c-algo-pcf
$(call i2c_defaults,$(I2C_ALGOPCF_MODULES),55)
TITLE:=I2C PCF 8584 interfaces
DEPENDS:=kmod-i2c-core
endef
define KernelPackage/i2c-algo-pcf/description
Kernel modules for I2C PCF 8584 interfaces
endef
$(eval $(call KernelPackage,i2c-algo-pcf))
I2C_GPIO_MODULES:= \
CONFIG_I2C_GPIO:drivers/i2c/busses/i2c-gpio
define KernelPackage/i2c-gpio
$(call i2c_defaults,$(I2C_GPIO_MODULES),59)
TITLE:=GPIO-based bitbanging I2C
DEPENDS:=@GPIO_SUPPORT +kmod-i2c-algo-bit
endef
define KernelPackage/i2c-gpio/description
Kernel modules for a very simple bitbanging I2C driver utilizing the
arch-neutral GPIO API to control the SCL and SDA lines.
endef
$(eval $(call KernelPackage,i2c-gpio))
I2C_MPC_MODULES:=\
CONFIG_I2C_MPC:drivers/i2c/busses/i2c-mpc
define KernelPackage/i2c-mpc
$(call i2c_defaults,$(I2C_MPC_MODULES),59)
TITLE:=MPC I2C accessors
DEPENDS:=@TARGET_mpc52xx||TARGET_mpc83xx||TARGET_mpc85xx +kmod-i2c-core
endef
define KernelPackage/i2c-mpc/description
Kernel module for Freescale MPC52xx MPC83xx MPC85xx I2C accessors
endef
$(eval $(call KernelPackage,i2c-mpc))
I2C_IBM_IIC_MODULES:=\
CONFIG_I2C_IBM_IIC:drivers/i2c/busses/i2c-ibm_iic
define KernelPackage/i2c-ibm-iic
$(call i2c_defaults,$(OF_I2C_MODULES),59)
TITLE:=IBM PPC 4xx on-chip I2C interface support
DEPENDS:=@TARGET_ppc40x||TARGET_ppc4xx +kmod-i2c-core
endef
define KernelPackage/i2c-ibm-iic/description
Kernel module for IIC peripheral found on embedded IBM PPC4xx based systems
endef
$(eval $(call KernelPackage,i2c-ibm-iic))
I2C_MV64XXX_MODULES:=\
CONFIG_I2C_MV64XXX:drivers/i2c/busses/i2c-mv64xxx
define KernelPackage/i2c-mv64xxx
$(call i2c_defaults,$(I2C_MV64XXX_MODULES),59)
TITLE:=Orion Platform I2C interface support
DEPENDS:=@TARGET_kirkwood||TARGET_orion||TARGET_mvebu +kmod-i2c-core
endef
define KernelPackage/i2c-mv64xxx/description
Kernel module for I2C interface on the Kirkwood, Orion and Armada XP/370
family processors
endef
$(eval $(call KernelPackage,i2c-mv64xxx))
I2C_TINY_USB_MODULES:= \
CONFIG_I2C_TINY_USB:drivers/i2c/busses/i2c-tiny-usb
define KernelPackage/i2c-tiny-usb
$(call i2c_defaults,$(I2C_TINY_USB_MODULES),59)
TITLE:=I2C Tiny USB adaptor
DEPENDS:=@USB_SUPPORT kmod-i2c-core +kmod-usb-core
endef
define KernelPackage/i2c-tiny-usb/description
Kernel module for the I2C Tiny USB adaptor developed
by Till Harbaum (http://www.harbaum.org/till/i2c_tiny_usb)
endef
$(eval $(call KernelPackage,i2c-tiny-usb))
I2C_PIIX4_MODULES:= \
CONFIG_I2C_PIIX4:drivers/i2c/busses/i2c-piix4
define KernelPackage/i2c-piix4
$(call i2c_defaults,$(I2C_PIIX4_MODULES),59)
TITLE:=Intel PIIX4 and compatible I2C interfaces
DEPENDS:=@PCI_SUPPORT @(x86||x86_64) kmod-i2c-core
endef
define KernelPackage/i2c-piix4/description
Support for the Intel PIIX4 family of mainboard I2C interfaces,
specifically Intel PIIX4, Intel 440MX, ATI IXP200, ATI IXP300,
ATI IXP400, ATI SB600, ATI SB700/SP5100, ATI SB800, AMD Hudson-2,
AMD ML, AMD CZ, Serverworks OSB4, Serverworks CSB5,
Serverworks CSB6, Serverworks HT-1000, Serverworks HT-1100 and
SMSC Victory66.
endef
$(eval $(call KernelPackage,i2c-piix4))
I2C_MUX_MODULES:= \
CONFIG_I2C_MUX:drivers/i2c/i2c-mux
define KernelPackage/i2c-mux
$(call i2c_defaults,$(I2C_MUX_MODULES),51)
TITLE:=I2C bus multiplexing support
DEPENDS:=kmod-i2c-core
endef
define KernelPackage/i2c-mux/description
Kernel modules for I2C bus multiplexing support
endef
$(eval $(call KernelPackage,i2c-mux))
I2C_MUX_GPIO_MODULES:= \
CONFIG_I2C_MUX_GPIO:drivers/i2c/muxes/i2c-mux-gpio
define KernelPackage/i2c-mux-gpio
$(call i2c_defaults,$(I2C_MUX_GPIO_MODULES),51)
TITLE:=GPIO-based I2C mux/switches
DEPENDS:=kmod-i2c-mux
endef
define KernelPackage/i2c-mux-gpio/description
Kernel modules for GENERIC_GPIO I2C bus mux/switching devices
endef
$(eval $(call KernelPackage,i2c-mux-gpio))
I2C_MUX_PCA954x_MODULES:= \
CONFIG_I2C_MUX_PCA954x:drivers/i2c/muxes/i2c-mux-pca954x
define KernelPackage/i2c-mux-pca954x
$(call i2c_defaults,$(I2C_MUX_PCA954x_MODULES),51)
TITLE:=Philips PCA954x I2C mux/switches
DEPENDS:=kmod-i2c-mux
endef
define KernelPackage/i2c-mux-pca954x/description
Kernel modules for PCA954x I2C bus mux/switching devices
endef
$(eval $(call KernelPackage,i2c-mux-pca954x))
I2C_MUX_PCA9541_MODULES:= \
CONFIG_I2C_MUX_PCA9541:drivers/i2c/muxes/i2c-mux-pca9541
define KernelPackage/i2c-mux-pca9541
$(call i2c_defaults,$(I2C_MUX_PCA9541_MODULES),51)
TITLE:=Philips PCA9541 I2C mux/switches
DEPENDS:=kmod-i2c-mux
endef
define KernelPackage/i2c-mux-pca9541/description
Kernel modules for PCA9541 I2C bus mux/switching devices
endef
$(eval $(call KernelPackage,i2c-mux-pca9541))
|
{
"pile_set_name": "Github"
}
|
$(function(){
//SyntaxHighlighter
//---------------
SyntaxHighlighter.all();
// form
// ---------------------------------------------------
var $form = $('#generator__form');
var $item = $form.find('.generator__form__item');
var $target = $('.js-generator__preview__target');
var $codeTarget = $('.js-generator-code-target');
var dummyAddress = 'https://example123.com';
var options = {
type : [
'browser' ,
'phone' ,
'tablet' ,
'desktop' ,
'laptop'
],
size : [
'1x',
'2x',
'3x',
'4x',
'5x',
'6x',
'7x',
'8x',
'9x'
],
theme : [
'black',
'white'
],
orientation : [
'portrait',
'landscape'
]
}
var enableCtrlObj = {
browser : ['type','size','address'],
phone : ['type','size','theme','orientation'],
tablet : ['type','size','theme','orientation'],
desktop : ['type','size'],
laptop : ['type','size']
}
ge_init();
function ge_init (){
for(var k in options){
var target = $('.js-ge-' + k , $form);
for (var i = 0; i < options[k].length; i++) {
target.append('<option value="'+options[k][i]+'">'+options[k][i]+'</option>');
}
}
changeMock();
}
function changeMock(){
var opt = {}
var contentTmp = $target.find('.df-content').html();
$('.generator__form__item').each(function(i) {
opt[$(this).attr('name')] = $(this).val();
});
$target.removeClass().addClass('generator__preview__target').html(contentTmp).deviceMock(opt);
enableCtrl(opt.type , enableCtrlObj);
$codeTarget.val( generateCode(opt , enableCtrlObj) );
}
function enableCtrl(nowType , enableObj){
var myEnable = enableObj[nowType];
$item.attr("disabled", "disabled");
setTimeout(function(){
for (var i = 0; i < myEnable.length; i++) {
$("[name="+myEnable[i]+"]" , $form ).removeAttr("disabled");
}
}, 0);
}
function generateCode(nowOpt , enableObj){
var obj = {};
var code = "";
var loopCount = 1;
for (var i = 0; i < enableObj[nowOpt.type].length; i++) {
obj[enableObj[nowOpt.type][i]] = nowOpt[enableObj[nowOpt.type][i]];
}
code += '<!-- includes -->\n';
code += '<link rel="stylesheet" type="text\/css" href="path\/to\/assets\/css\/jquery.devicemock.css">\n';
code += '<script src="jquery.js"><\/script>\n';
code += '<script src="path\/to\/assets\/js\/jquery.devicemock.1.0.0.js"><\/script>\n';
code += '\n';
code += '<!-- element -->\n';
code += '<div class="your-selector"><!-- something... --></div>\n';
code += '\n';
code += '<!-- script -->\n';
code += '<script type="text\/javascript">\n';
code += ' $(".your-selector").deviceMock({\n';
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
code += ' ' + prop + ' : "' + obj[prop] + '"';
}
code += ',\n';
loopCount++;
}
code += ' imgPath : "path\/to\/assets\/img/" \/\/ path of asset images';
code += ',\n';
code += ' cssPrefix : "df-" \/\/ css namespace ( "df-" is default )';
code += '\n';
code += ' });\n';
code += '<\/script>\n';
return code;
}
$item.change(function(event) {
changeMock();
});
});
// UI
// ---------------------------------------------------
$(function(){
var flg_nav_open = false;
var $html = $('html');
var $body = $('body');
var $uiTrigger = $('.js-ui-trigger');
var $viewport = $('.viewport');
function toggleNav(){
if(flg_nav_open){
closeNav();
} else {
openNav();
}
}
function openNav (){
flg_nav_open = true;
console.log('open');
// Scroll Off
$(window).on('touchmove.noScroll', function(e) {
e.preventDefault();
});
$body.removeClass('js-nav-close js-nav-close-end');
setTimeout(function(){
$body.addClass('js-nav-open');
}, 50);
setTimeout(function(){
$body.addClass('js-nav-open-end');
}, 550);
}
function closeNav (){
flg_nav_open = false;
// Scroll On
$(window).off('.noScroll');
console.log('close');
$body.removeClass('js-nav-open js-nav-open-end');
setTimeout(function(){
$body.addClass('js-nav-close');
}, 50);
setTimeout(function(){
$body.addClass('js-nav-close-end');
}, 550);
}
function setCenter ( center , target ){
target.css({
'transform-origin': ' center ' + center + 'px',
'-webkit-transform-origin': ' center ' + center + 'px'
});
}
$(window).bind("resize load scroll",function(){
var scrolled = $(window).scrollTop();
var winH = $(window).height();
setCenter( (scrolled + winH/2) , $viewport );
});
$uiTrigger.on('click', function(event) {
event.preventDefault();
toggleNav();
});
});
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
from .common import *
|
{
"pile_set_name": "Github"
}
|
{{#if error}}
<div class="alert alert-danger" role="alert">
<strong>{{error}}</strong>
{{#if errorDetails}}
<div>{{errorDetails}}</div>
{{/if}}
</div>
{{/if}}
<form action="/login" method="post">
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-lg btn-primary">Log In</button>
</form>
|
{
"pile_set_name": "Github"
}
|
platform :ios, '8.0'
use_frameworks!(true)
target 'TestProject' do
pod 'QueryKit'
end
target 'TestProjectTests' do
pod 'Quick'
end
|
{
"pile_set_name": "Github"
}
|
# 1. 顺序容器 内的元素按其位置存储和访问 (sequential container) vector deque list forward_list array string
容器(container),顾名思义表示对象的集合,这些对象的类型都相同,
每个对象都有一个自己的索引,用这个索引我们就可以方便的访问该对象了。
只有顺序容器的构造函数才接受大小参数,关联容器并不支持。
vector 可变大小数组。支持快速随机访问。在尾部之外的位置插入或删除元素可能很慢。
vector<int> vi(10, -1); // 10个-1
deque 双端队列。支持快速快速访问。在头尾位置插入/删除速度很快。
deque<double> deqd(10); // 10个元素 0
list 双向链表。只支持双向顺序访问。在list中任何位置进行插入/删除操作速度都很快。
list<int> li(5,1); // 5个1
forward_list 单向链表。只支持单向顺序访问。在链表任何位置进行插入/删除操作速度都很快。
forward_list<string> fls(10); // 10个元素 0
array 固定大小数组。支持快速随机访问,不能添加或删除元素。
array<int, 42> ia; // 42个int的数组, 支持拷贝构造
array<int, 42> ia2 = ia;
而内置数组不支持拷贝构造.
std::array也提供了 at() 函数。
string 与vector相似的容器,但专门用于保存字符。随机访问快,在尾部插入/删除都很快。
## 以下是一些选择容器的基本原则(具体视情况而定,这里只是一般情况):
1、通常vector是最好的选择,除非你有很好的理由选择其他容器;
2、如果程序有很多小的元素,且空间额外开销很重要,则不要使用 list 或 forward_list 容器;
3、如果程序要求随机访问,应使用 vector 或 deque 容器;
4、如果程序要在头尾位置插入/删除,且不会在中间位置进行插入/删除操作,则应使用deque容器。
## a. vector 连续存储结构,每个元素在内存上是连续的 尾部插入 push_back() 与 尾部插删除 pop_back()
vector<vector<int>> vvi;//相当于二维数组
STL中的vector容器就是动态大小数组。
vector<int> v;
v.push_back(k); 在后面插入 k 这个元素
v.size() 返回容器中实际元素的个数
v.resize() 重新设定容器的大小
v.at(index) 返回索引位置的元素
v.begin() 返回第一个元素的迭代器 vector<T>::iterator
v.end() 返回最后一个元素后面位置的迭代器
v.front() 返回第一个元素
v.back() 返回最后一个元素
v.empty() 返回1为空,0为非空
v.swap() 交换两容器
rbegin() 返回逆向容器中的第一个元素的迭代器
rend() 返回逆向容器中的最后一个元素后面位置的迭代器
clear() 清除容器中所有元素
insert() 插入
max_size() 返回最大数据量
v.erase() 擦除元素
#include <vector> //头文件包含
using namespace std; //或者using std::vector;
//vector定义并初始化
vector<int> v1;
for (int i=0;i<10;i++)
v1.push_back(i+1); // 从后面一次插入元素
//使用迭代器遍历vector
vector<int>::iterator iter = v1.begin();
for (;iter!=v1.end();iter++)
{
cout<<*iter<<" ";
}
vector容器中存储的元素在内存中是连续存储的。
假如容器中没有空间容纳新元素,此时由于元素必须连续存储以便索引访问,
所以不能在内存中随便找个地方存储这个新的元素,于是vector必须重新分配空间 v.resize(10),
用于存放原来的元素和新添加的元素:
存放在旧容器中的元素被复制到新的容器中,接着插入新的元素,最后撤销旧的存储空间。
为了使vector容器实现快速的内存分配,
其实际分配的容量要比当前所需的空间多一些,vector容器预留这些空间,用于存放新的元素。
v.push_back(val)
先将容器c中的元素拷贝到新的内存空间中,
然后在将val值拷贝到新空间的末尾,
最后析构掉原始空间。
当push_back检测到空间不足时,将自动以 2倍 的方式扩展空间。
对于大量数据来说,这是一个弊端,可以使用可以使用 vector::reserve 方法来改善。
push_back()使用 vector::insert 方法实现,在容器尾部insert来实现的。
void push_back(_Elem _Ch)
{ // insert element at end
insert(end(), _Ch); // 算法
}
pop_back() 使用vector::earse,擦除最后一个位置元素来实现的。
删除容器尾部元素,同时c.size()会减少。
void pop_back()
{ // erase element at end
erase(this->_Mysize - 1); // throws if _Mysize == 0
}
v.shrink_to_fit();
// 为了不让vector浪费太多的内存,我们在最后调用了shrink_to_fit。
// 该函数会为元素分配足够的空间,将剩余的元素移到该空间内,并且删除之前那个比较大的内存空间。
// 会将多余的空间归还给系统
### vector 优点:
随机存取,即 vi[i] 操作 和 vi.at(i)。
at() 函数会检查给定的索引值是否越界,如果越界则返回一个异常。
因为检查越界要花费一些时间,所以at函数会让程序慢一些。
当需要非常快的索引成员时,并能保证索引不越界,我们会使用[]快速访问vector实例。
很多情况下,at() 函数在牺牲一点性能的基础上,有助于发现程序内在的bug。
默认使用 at() 函数时一个好习惯。
当代码的性能很差,但有没有bug存在时,可以使用性能更高的操作符[]来替代at函数。
动态操作, 尾部插入 vi.push_back() 与 尾部插删除 vi.pop_back()
自动调整内存,节省空间
try{} catch(){} 捕获 vector访问越界 异常
```c
try{
temp = v.at(k);
}
catch(std::out_of_range &e){
std::cout << e.what() << std::endl;
}
```
### vector缺点:
实现插入与删除操作效率低
只能在尾部插入与删除,在头部插入与删除消耗时间规模与容器大小成正比,它会将后面的元素依次前移。
当动态添加的数据超过默认内存大小时,要进行整体的重新分配,拷贝与释放。
### 快速删除未排序的vector中的元素,最后一个元素替换到需要删除的地方,再 pop_back() 删除最后一个元素
注意此操作会改变数组顺序,对于未排序的数组没什么问题,对于已排序的数组不可用,或者删除之后再排序
```c
// 输入 vector,和要删除的 元素的索引 idx
template <typename T>
void quick_remove_at(std::vector<T> &v, std::size_t idx)
{
if (idx < v.size()) // 索引为出界
{
v[idx] = std::move(v.back());// 最后的元素移动到要删除的位置
// std::move(v.back()); // 避免拷贝,相当于只是拷贝了指针
// *it = v.back(); // 会进行拷贝
v.pop_back(); // 删除最后的元素
}
}
// 输入 vector,和要删除的 元素的迭代器 it
template <typename T>
void quick_remove_at(std::vector<T> &v,
typename std::vector<T>::iterator it)
{
if (it != std::end(v))// 迭代器未出界
{
*it = std::move(v.back());// 最后的元素移动到要删除的位置
v.pop_back(); // 删除最后的元素
}
}
```

## b. list 双端链表 非连续存储结构,具有双链表结构,支持排序 sort排序
[list参考](http://blog.csdn.net/qq_22186119/article/details/77937179)
list容器中添加元素时,只需要创建一个新的元素,
然后将该元素连接到已经存在的链表中,
不需要重新分配存储空间,也不用复制任何已存在的元素。
非连续存储结构,具有双链表结构,每个元素维护一对前向和后向指针,因此支持前向/后向遍历。
支持高效的随机插入/删除操作,但随机访问效率低下,且由于需要额外维护指针,开销也比较大。
每一个结点都包括一个信息快Info、一个前驱指针Pre、一个后驱指针Post。
可以不分配必须的内存大小方便的进行添加和删除操作。
使用的是非连续的内存空间进行存储。
list<char> lit;
//-----------链表可以从两端插入-------------------
lit.push_back('b');
lit.push_front('d');
//-----------链表打印-------------------
list<char>::iterator it;
for(it=lit.begin();it!=lit.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
//-----------链表可以从两端删除-------------------
lit.pop_back();
lit.pop_front();
//-------------删除所有的a---------------------------------
//lit.remove('a'); //删除所有的a;
//-----------将list里的数据倒序排列---------------
lit.reverse();
//-------------移除连续且相同的a,只剩下一个;--------------------------------
lit.unique(); //移除连续且相同的a,只剩下一个;
list<char> lit1;
list<char>::iterator it1;
//-------------将一个链表插入到另一个链表---------------------------------
it1=find(lit.begin(),lit.end(),'f'); //先的找到要插入的位置,在该位置的前一个插入;
////lit.splice(it1,lit1); //将第二个链lit1表插入到第一个链表lit中;合并后的链表就没了,因为传的是&
// 打印函数
void printList(const list<int>& a)
{
// 注意形参中是const list,所以下面也需要用const_iterator
// 否则distance无法使用
list<int>::const_iterator iter;
for (iter = a.begin(); iter != a.end(); ++iter)
{// 计算数组下标,distance包含在algorithm中 #include<algorithm>
size_t index = distance(a.begin(), iter);
cout << "a[" << index << "] = " << *iter << endl;
}
cout << endl;
}
list<int> a;
// push_front、push_back插入数据
a.push_front(4);
a.push_front(3);
a.push_front(2);
a.push_front(1);
a.push_back(50);
printList(a);
// insert插入数据
list<int>::iterator iter;
iter = a.begin();
a.insert(iter, 0);
a.insert(++iter, 10);
a.insert(++iter, 4, 20); // 插入4个20
printList(a);
// sort排序
cout << "sort排序" << endl;
a.sort();
printList(a);
// reverse逆序
cout << "reverse逆序" << endl;
a.reverse();
printList(a);
// erase删除指定元素
cout << "erase删除指定元素" << endl;
a.erase(iter);
printList(a);
// erase删除指定区间的元素
cout << "erase删除指定区间元素" << endl;
a.erase(++a.begin(), --a.end());
printList(a);
### list 优点:
1)不使用连续内存完成动态操作。
2)在内部方便的进行插入和删除操作 动态操作,插入与删除效率高
3)可在两端进行push、pop
### list缺点:
1) 不能进行内部的随机访问,即不支持[ ]操作符和vector.at()
2) 不能进行内部的随机访问,即不支持[ ]操作符和vector.at()
## c. deque 双端队列 连续存储结构
deque连续存储结构,即其每个元素在内存上也是连续的,类似于vector,
不同之处在于,deque提供了两级数组结构, 第一级完全类似于vector,代表实际容器;
另一级维护容器的首位地址。
这样,deque除了具有vector的所有功能外,还支持高效的首/尾端插入/删除操作。
deque 双端队列 double-end queue
deque是在功能上合并了vector和list。
//
deque<int> a;
// 在末尾插入数据
a.push_back(3);
a.push_back(4);
a.push_back(5);
// 在开头插入数据
a.push_front(2);
a.push_front(1);
a.push_front(0);
// 以数组方式输出
for (size_t n = 0; n < a.size(); ++n)
cout << "a[" << n << "] = " << a[n] << endl;
cout << endl;
//删除末尾的数据
a.pop_back();
//删除开头的数据
a.pop_front();
// 以迭代器方式输出
deque<int>::iterator iter;
for (iter = a.begin(); iter < a.end(); ++iter)
{
// 计算数组下标,distance包含在algorithm中 #include<algorithm>
int index = distance(a.begin(), iter);
cout << "a[" << index << "] = " << *iter << endl;
}
### deque 优点:
1)随机访问,即[]操作和deque.at()
2) 在内部方便的进行插入和删除操作
3)可在双端进行pop,push
### deque 缺点:
占用内存多。
### vector、deque、list三种容器的特点
vector:支持快速随机访问、可高效的在vector容器 尾部 添加删除数据
deque:支持快速随机访问、可高效的在deque容器 头部和尾部 添加删除数据
list:支持顺序访问,但是在任何位置插入删除元素都很快。
相同点:三者都能实现resize()来重新调整容器的大小。
不同点:
1)vector能实现随即存取,即[]操作,而list不能,deque是二者的结合体,也能够实现索引操作[],但效率没有vector高。
2)vector适合在文件的末尾实现删除元素的操作pop_back()与插入操作push_back(),在中间时效率非常低下。
而list可以在容器的任何位置实现插入与删除操作。
原因:vector的元素地址连续,如果在中间插入与删除操作,可能会导致原来的内存地址不足以存储当前的元素,
需要重新分配内存地址,这就需要将原来的所有元素拷贝到新内存,释放旧的内存地址等操作,操作代价高昂。
而list元素内存地址不连续,用指针操作,其本身是一个双向链表,它的高效率体现在插入,删除以及排序等移动大量元素的操作。
a. vector与deque的迭代器支持算术运算,list的迭代器只能进行++/--操作,不支持普通的算术运算。
b. 向量中的iterator在使用后就释放了,但是链表list不同,它的迭代器在使用后还可以继续用;链表特有的;
### 选择容器类型的准则:
1)如果需要随机访问一个容器,vector 比 list好
2)如果经常 需要 插入或删除 容器元素,list比vector好
3)如果既要随机存取,又要关心两端数据的插入与删除,则选择 deque
a、若需要随机访问操作,则选择vector;
b、若已经知道需要存储元素的数目,则选择vector;
c、若需要随机插入/删除(不仅仅在两端),则选择list
d、只有需要在首端进行插入/删除操作的时候,还要 兼顾 随机访问效率,才 选择deque, 否则都选择vector。
e、若既需要随机插入/删除,又需要随机访问,则需要在vector与list间做个折中-deque。
f、当要存储的是大型负责类对象时,list要优于vector;
当然这时候也可以用vector来存储指向对象的指针,
同样会取得较高的效率,但是指针的维护非常容易出错,因此不推荐使用。
# 2. 关联容器 按关键字保存和访问 map (key-value键值对,类似字典的概念) set(只包含一个关键字(关键字即值))
map<名字,电话号码> 利用名字来查询电话号码类似电话簿
set<bad_checks_name> 定义一个曾经开过空头支票的客户的名字,在接收一张支票前查询其名字是否在其中。
只有顺序容器的构造函数才接受大小参数,关联容器并不支持。
#include <map>
#include <ext/hash_map>
#include <tr1/unordered_map>
using namespace std;
using namespace std::tr1;
//typedef map<int,int> MapKey; //采用map
//typedef hash_map<int,int> MapKey; //采用hash_map
typedef unordered_map<int,int> MapKey; //采用unordered_map
## 有序集合 RB树实现 红黑树
map 关联数组:保存关键字-值对
set 关键字即值,只保存关键字的容器
multimap 关键字可重复出现的 map
multiset 关键字可重复出现的 set
## 无序集合 哈希函数实现
unordered_map 哈希函数组织的map
unordered_set 哈希函数组织的set
unordered_multimap 哈希函数组织的multimap, 关键字可以重复出现
unordered_multiset 哈希函数组织的multiset, 关键字可以重复出现
## 无序集合 基于hash table(哈希表)
hash_map
hash_set
hash_multimap
hash_multiset
## 结果分析
运行效率方面:unordered_map最高,hash_map其次,而map效率最低
占用内存方面:hash_map内存占用最低,unordered_map其次,而map占用最高
## 使用map
### 使用map统计每个单词在输入中出现的次数 单词按字典序列 排序
map<string, size_t> word_count;//string 到 size_t 的空map
string word;
while(cin >> word) ++word_count[word];//提取word的计数器并将其加1
for(const auto &w : word_count) //对map中的每一个元素 pair类型 first成员保存关键字 second成员保存对应的值
cout << w.first << " occurs " << w.second
<< ((w.second > 1)? "times" : "time") << endl;// 报告每个单词出现的次数 单词按 字典排序
###
[map 创建一张百万富翁的列表](https://github.com/Ewenwan/CPP-17-STL-cookbook/blob/master/content/chapter2/chapter2-5-chinese.md)
## 使用 set
### 使用set保存需要忽略统计的单词
map<string, size_t> word_count;//string 到 size_t 的空map
set<string> exclude = {"The", "But", "And", "Or", "An", "A",
"the", "but", "and", "or", "an", "a"};//需要剔除的单词
string word;
while(cin >> word)
if(exclude.find(word) == exclude.end()) ++word_count[word];// 统计合理的词的出现次数
// exclude.find(word) word没有在exclude中出现时,返回 exclude.end()
## 初始化关联容器
//map初始化为空
map<string, size_t> word_count;//string 到 size_t 的空map
//set的列表初始化
set<string> exclude = {"The", "But", "And", "Or", "An", "A",
"the", "but", "and", "or", "an", "a"};//需要剔除的单词
//map的列表初始化 三个元素 将姓 映射为 名字
map<string, string> authers = {{"Jyly", "Jeam"},
{"Aust", "Amy"},
{"Dickens", "Charles"} };
// multimap multisetde初始化,一个单词对应多个相互关联的词义,就是说 关键字可以重复出现
vector<int> ivec;
for(vector<int>::size_type i = 0; i != 10; ++i){
ivec.push_back(i);
ivec.push_back(i);// 每个数重复保存一次
}
// iset包含来自ivec的不重复的元素 含有10个元素
set<int> iset(ivec.cbegin(), ivec.cend());
// multiset 包含ivec的所有20个元素
multiset<int> miset(ivec.cbegin(), ivec.cend());
## pair类型 是用来生成 特点类型 的模板 first 和 second 来访问 map的元素是 pair类型 make_pair(v1, v2)
pair<string, string> anon;//
pair<string, size_t> word_count;//
pair<string, vector<int>> line;//保存 string 和 vector<int>
pair<string, string> author{"James", "Joyce"};//列表初始化
// pair类型的返回值类型函数
pair<string, int> process(vector<string> &v){
if(!v.empty())//back() 返回最后一个元素
return {v.back(), v.back().size()};//列表初始化
// return pair<string, int>(v.back(), v.back().size());
// return make_pair(v.back(), v.back().size()):
else
return pair<string, int>();//隐式构造返回值
}
### 关联容器类型 key_type value_type 对于set是一样的 而对于map不一样 还有一个 mapped_type
set<string>::value_type va;//va 是一个string
set<string>::key_type vb;//vb 也是一个string
map<string, int>::key_type vc;//vc 是一个string
map<string, int>::mapped_type vd;//vd 是一个int
mep<string, int>::value_type ve;//ve map元素的类型 是pair类型 pair<const string, int>
### 关联容器迭代器
map<string, size_t> word_count;//string 到 size_t 的空map
auto map_it = word_count.begin();//迭代器指针
// *map_it 是一个指向 pair<const string, size_t>类型对象的 引用
cout << map_it->first;//打印关键字
cout << " " << map_it->second;//
map_it->first = "new key";//错误 map的关键字类型 是 const的 不能改变 可以读取
++map_it->second;//正确 值类型不是const 可以改变
//set的关键字也是只读的即const,不能被改变的
set<int> iset = {0,1,2,3,4,5,6,7,8,9};//列表初始化
set<int>::iterator set_it = iset.begin();
if( set_it != iset.end()){
*set_it = 42;// 错误 不能修改set的关键字
cout << *set_it << endl;//可以读取set的关键字
}
### 遍历关联容器
map<string, size_t> word_count;//string 到 size_t 的空map
string word;
while(cin >> word) ++word_count[word];//提取word的计数器并将其加1
// 范围for访问
for(const auto &w : word_count) //对map中的每一个元素 pair类型 first成员保存关键字 second成员保存对应的值
cout << w.first << " occurs " << w.second
<< ((w.second > 1)? "times" : "time") << endl;// 报告每个单词出现的次数
//迭代器访问
auto map_it = word_count.cbegin();//迭代器指针
// *map_it 是一个指向 pair<const string, size_t>类型对象的 引用
while(mep_it != word_count.cend()){
cout << map_it->first << " occurs "
<< map_it->second
<< ((w.second > 1)? "times" : "time") << endl;// 报告每个单词出现的次数
++map_it;//递增迭代器,移动到下一个元素
}
### 向map中添加元素
word_count.insert({word, 1});// c++11标准最方便
word_count.insert(make_pair(word, 1));
word_count.insert(pair<string, size_t>(word, 1));
word_count.insert(map<string, size_t>::value_type(word, 1));
### 向multimap中添加元素
multimap<string, string> authors;
authors.insert({"Breath, John", "Sot-Weed Factor"});//插入第一个元素,关键字为 Breath, John
authors.insert({"Breath, John", "Lost in the funhouse"});//插入第二个元素,关键字也为 Breath, John
### multimap的访问
string search_item("Breath, John");
auto cnt = authors.count(search_item);//关键字出现的次数
auto iter = authors.find(search_item);//关键字指向的 值序列
while(cnt){
cout << iter->second << endl;//打印作者的每一个书名
++iter;//前进到下一步书
--cnt;//记录剩余未打印的书本数量
}
// 迭代器lower_bound 范围for 访问
for(auto beg = authors.lower_bound(search_item), end = authors.upper_bound(search_item);
beg != end; ++beg)
cout << beg->second <<endl;//打印作者的每一个书名
// 范围for equal _range() 访问
for(auto pose = authors.equal _range(search_item); pose.first != pose.second; ++pose.first)
cout << pose.first->second << endl;//打印作者的每一个书名
## 无序容器 无序 存储
unordered_map<string, size_t> word_count;//string 到 size_t 的空unordered_map 无序map
string word;
while(cin >> word) ++word_count[word];//提取word的计数器并将其加1
for(const auto &w : word_count) //对map中的每一个元素 pair类型 first成员保存关键字 second成员保存对应的值
cout << w.first << " occurs " << w.second
<< ((w.second > 1)? "times" : "time") << endl;// 报告每个单词出现的次数 单词 无序
### 无序容器的存储方式
#### 管理桶
> 无序容器在存储组织上为一组桶(bucket),每个桶保存零个或多个元素,使用一个hash function(哈希函数)将元素映射到桶,
> 为了访问元素,容器首先计算元素的哈希值,它指出应该搜索哪个桶,容器将具有固定哈希值的所有元素都保存在相应的桶中。
#### 对于存储自定义类型的 无序容器 需要自己定义哈希函数 和比较函数(==) 来实现存储
//哈希函数
size_t hasher(const Sales_data &sd){
return hash<string>()(sd.isbn());//h哈希类型
}
//比较函数
bool eqOp(const Sales_data &lhs, const Sales_data &rhs){
return lhs.isbn() == rhs.isbn();// 比较函数
}
// 定义特定类的 unordered_multiset
using = sd_unordered_multiset = unordered_multiset<Sales_data, decltype(hasher)*, decltype(eqOp)*>// 两个函数指针
|
{
"pile_set_name": "Github"
}
|
#include "rpygen_wrapper.hpp"
RPYBUILD_PYBIND11_MODULE(m)
{
initWrapper(m);
}
|
{
"pile_set_name": "Github"
}
|
feature 'List orders', js: true do
let!(:user) { FactoryBot.create(:user) }
let!(:john) { FactoryBot.create(:user, :john) }
let!(:vacation_request_type) { FactoryBot.create(:order_type, :vacation_request, name: 'Vacation request') }
let!(:support_request_type) { FactoryBot.create(:order_type, :support_request, name: 'Support request') }
let!(:vacation_request_order) { FactoryBot.create(:order, :order_vacation_request) }
let!(:support_request_order) { FactoryBot.create(:order, :order_support_request, order_type: support_request_type) }
let!(:problem_descriptions) { 'Problem description' }
let!(:contract_number) { 111 }
before(:each) do
signin(user.email, user.password)
click_on 'Orders'
expect(page).to have_content 'Orders list'
expect_widget_presence
end
scenario 'with correct filter defaults' do
# "Orders list" tab is active by default
expect(active_tab 'Orders list').not_to be_nil
# "Order type" select
expect(label('order_type_id')).to eq('Order type')
expect(placeholder('order_type_id')).to eq('Order type')
expect(select2_default_text('order_type_id')).to eq('Order type')
expect(select_options('order_type_id')).to eq(['Empty order type',
'Support request',
'Vacation request'])
# "Order status" select
expect(label('state')).to eq('Order status')
expect(placeholder('state')).to eq('Order status')
expect(select2_default_text('state')).to eq('Order status')
expect(select_options('state')).to eq(['New',
'In progress',
'Completed'])
# "Archived" select
expect(label('archived')).to eq('Archived')
expect(placeholder('archived')).to eq('Archived')
expect(select2_text('archived')).to eq("\nNo")
expect(select_options('archived')).to eq(%w(Yes No))
# "User" multiple select
expect(label('user_id')).to eq('User')
expect(placeholder('user_id[]')).to eq('User')
expect(select2_multiple_text('user_id[]')).to eq([user.full_name, 'Empty'])
expect(select_options('user_id[]')).to eq([user.full_name, 'Empty'])
# enter 2 symbols in lookup and find users
expect(success_select_search('user_id[]', 'Jo')).to eq([john.full_name, user.full_name])
# Calendar "from"
expect(label('created_at_from')).to eq('from')
expect(calendar_value('created_at_from')).to eq(in_current_locale((DateTime.now - 1.day).beginning_of_day))
# Calendar "to"
expect(label('created_at_to')).to eq('to')
expect(calendar_value('created_at_to')).to eq(in_current_locale((DateTime.now).end_of_day))
# Estimated execution date "from"
expect(label('estimated_exec_date_from')).to eq('from')
expect(calendar_value('estimated_exec_date_from')).to be_nil
# Estimated execution date "to"
expect(label('estimated_exec_date_to')).to eq('to')
expect(calendar_value('estimated_exec_date_to')).to be_nil
end
scenario 'with changing filter parameters' do
current_orders_list = [['ORD-1', 'Empty order type', 'In progress',
in_current_locale(vacation_request_order.created_at), '', 'ext_code', '',
in_current_locale(vacation_request_order.estimated_exec_date)]]
# "Order type"
change_select2_value('order_type_id', 'Vacation request')
search_button.click
wait_for_ajax
expect(empty_order_list).not_to eq(nil)
change_select2_value('order_type_id', 'Empty order type')
search_button.click
wait_for_ajax
expect(orders_list).to eq(current_orders_list)
# "Archived"
change_select2_value('archived', 'Yes')
search_button.click
wait_for_ajax
expect(empty_order_list).not_to eq(nil)
change_select2_value('archived', 'No')
search_button.click
wait_for_ajax
expect(orders_list).to eq(current_orders_list)
# "Order status"
change_select2_value('state', 'New')
search_button.click
wait_for_ajax
expect(empty_order_list).not_to eq(nil)
change_select2_value('state', 'In progress')
search_button.click
wait_for_ajax
expect(orders_list).to eq(current_orders_list)
# Calendar "From"
calendar_date_button('created_at_from').click
calendar_clear_button('created_at_from').click
expect(calendar_value('created_at_from')).to eq(nil)
search_button.click
wait_for_ajax
expect(orders_list).to eq(current_orders_list)
set_datetime_picker_date('created_at_from', in_current_locale(vacation_request_order.created_at + 1.minute))
search_button.click
wait_for_ajax
expect(empty_order_list).not_to eq(nil)
calendar_date_button('created_at_from').click
calendar_clear_button('created_at_from').click
search_button.click
wait_for_ajax
expect(orders_list).to eq(current_orders_list)
# Calendar "To"
set_datetime_picker_date('created_at_to', in_current_locale(vacation_request_order.created_at - 1.minute))
search_button.click
wait_for_ajax
expect(empty_order_list).not_to eq(nil)
set_datetime_picker_date('created_at_to', in_current_locale(vacation_request_order.created_at + 1.minute))
search_button.click
wait_for_ajax
expect(orders_list).to eq(current_orders_list)
# Estimated execution date "From"
set_datetime_picker_date('estimated_exec_date_from', in_current_locale(vacation_request_order.estimated_exec_date + 1.minute))
search_button.click
wait_for_ajax
expect(empty_order_list).not_to be_nil
calendar_date_button('estimated_exec_date_from').click
calendar_clear_button('estimated_exec_date_from').click
search_button.click
wait_for_ajax
expect(orders_list).to eq(current_orders_list)
# Estimated execution date "To"
set_datetime_picker_date('estimated_exec_date_to', in_current_locale(vacation_request_order.estimated_exec_date - 1.minute))
search_button.click
wait_for_ajax
expect(empty_order_list).not_to be_nil
set_datetime_picker_date('estimated_exec_date_to', in_current_locale(vacation_request_order.estimated_exec_date + 1.minute))
search_button.click
wait_for_ajax
expect(orders_list).to eq(current_orders_list)
# "User"
select2_cross('user_id[]', 'Empty').click
search_button.click
wait_for_ajax
expect(empty_order_list).not_to eq(nil)
# Filter by User isn't set
select2_cross('user_id[]', 'Christopher Johnson').click
search_button.click
wait_for_ajax
expect(orders_list).to eq(current_orders_list)
end
scenario 'with filter by custom fields' do
result_orders_list = [['ORD-2', 'Support request', 'In progress',
in_current_locale(support_request_order.created_at), '', 'support_ext_code', '',
in_current_locale(support_request_order.estimated_exec_date)]]
# default state
expect(label('custom_field_select')).to eq('Filter by custom fields')
expect(placeholder('custom_field_select')).to eq('Select field')
expect(select2_default_text('custom_field_select')).to eq('Select field')
expect(select_options('custom_field_select')).to eq([])
# activate custom field filter selector
change_select2_value('order_type_id', 'Support request')
wait_for_ajax
expect(select2_text('custom_field_select')).to eq('Creation date')
expect(select_options('custom_field_select')).to eq(['Creation date',
'Problem description',
'Callback',
'Contract number'])
# custom field filter with type 'string'
change_select2_value('custom_field_select', 'Problem description')
expect(select2_text('custom_field_select')).to eq('Problem description')
add_custom_field_filter
expect(label('problemDescription')).to eq('Problem description')
fill_in('custom_fields[problemDescription]', with: problem_descriptions.reverse)
search_button.click
wait_for_ajax
expect(empty_order_list).not_to eq(nil)
fill_in('custom_fields[problemDescription]', with: problem_descriptions)
search_button.click
wait_for_ajax
expect(orders_list).to eq(result_orders_list)
# custom field filter with type 'boolean'
change_select2_value('custom_field_select', 'Callback')
expect(select2_text('custom_field_select')).to eq('Callback')
add_custom_field_filter
expect(label('callBack')).to eq('Callback')
search_button.click
wait_for_ajax
expect(empty_order_list).not_to be_nil
click_checkbox_div('callBack')
search_button.click
wait_for_ajax
expect(orders_list).to eq(result_orders_list)
# custom field filter with type 'number'
change_select2_value('custom_field_select', 'Contract number')
expect(select2_text('custom_field_select')).to eq('Contract number')
add_custom_field_filter
expect(label('contractNumber')).to eq('Contract number')
fill_in('custom_fields[contractNumber]', with: contract_number + 1)
search_button.click
wait_for_ajax
expect(empty_order_list).not_to be_nil
fill_in('custom_fields[contractNumber]', with: contract_number)
search_button.click
wait_for_ajax
expect(orders_list).to eq(result_orders_list)
# custom field filter with type 'datetime'
change_select2_value('custom_field_select', 'Creation date')
expect(select2_text('custom_field_select')).to eq('Creation date')
add_custom_field_filter
expect(label('creationDate')).to eq('Creation date')
set_datetime_picker_date('custom_fields[creationDate][from]',
in_current_locale(DateTime.iso8601(support_request_order.data['creationDate']) + 1.day))
search_button.click
wait_for_ajax
expect(empty_order_list).not_to be_nil
set_datetime_picker_date('custom_fields[creationDate][from]',
in_current_locale(DateTime.iso8601(support_request_order.data['creationDate']) - 1.day))
search_button.click
wait_for_ajax
expect(orders_list).to eq(result_orders_list)
# order type removing should clear all custom field filters
select2_clear_cross('order_type_id').click
expect(placeholder('custom_field_select')).to eq('Select field')
expect(select2_default_text('custom_field_select')).to eq('Select field')
expect(select_options('custom_field_select')).to eq([])
expect(page).not_to have_selector('[name="custom_fields[problemDescription]"]')
expect(page).not_to have_selector('[name="custom_fields[callBack]"]')
expect(page).not_to have_selector('[name="custom_fields[contractNumber]"]')
expect(page).not_to have_selector('[name="custom_fields[creationDate]"]')
end
scenario 'with correct search by code' do
tab('Find order').click
input_by_label('code').set(vacation_request_order.code)
search_button_by_action('/orders/search_by/code').click
wait_for_ajax
expect(header.text).to eq('ORD-1 Empty order type')
end
scenario 'with correct search by ext code' do
tab('Find order').click
input_by_label('ext_code').set(vacation_request_order.ext_code)
search_button_by_action('/orders/search_by/ext_code').click
wait_for_ajax
expect(header.text).to eq('ORD-1 Empty order type')
end
feature 'with profile' do
common_fields = %w(code order_type_code state created_at user ext_code archived estimated_exec_date)
custom_fields = %w(creationDate problemDescription callBack contractNumber)
scenario 'display fields hidden if order type not set' do
expect(label('order_type_id')).to eq('Order type')
expect(placeholder('order_type_id')).to eq('Order type')
expect(select2_text('order_type_id')).to eq('Order type')
search_button.click
wait_for_ajax
expect(page).not_to have_content('Display fields')
end
scenario 'edit display fields' do
change_select2_value('order_type_id', 'Support request')
search_button.click
wait_for_ajax
expect(page).to have_content('Display fields')
expect(checked_multiselect_options('column-settings')).to eq(common_fields)
wait_for_ajax
expect(order_list_table_cols).not_to include('Creation date', 'Problem description', 'Callback', 'Contract number')
click_on_multiselect_options('column-settings', custom_fields)
expect(checked_multiselect_options('column-settings')).to eq(common_fields + custom_fields)
wait_for_ajax
expect(order_list_table_cols).to include('Creation date', 'Problem description', 'Callback', 'Contract number')
click_on_multiselect_options('column-settings', %w(code order_type_code))
wait_for_ajax
expect(order_list_table_cols).not_to include('Order type')
# 'Code' column can not be hidden
expect(order_list_table_cols).to include('Code')
end
end
feature 'with ordering' do
let!(:support_request_order_for_ordering) { FactoryBot.create(:order,
:order_support_request_for_ordering,
order_type: support_request_type) }
let(:order_2) { ['ORD-2', 'Support request', 'In progress',
in_current_locale(support_request_order.created_at), '', 'support_ext_code', '',
in_current_locale(support_request_order.estimated_exec_date)] }
let(:order_3) { ['ORD-3', 'Support request', 'In progress',
in_current_locale(support_request_order_for_ordering.created_at), '', 'support_ext_code', '',
in_current_locale(support_request_order_for_ordering.estimated_exec_date)] }
scenario 'by default fields' do
# "Order type"
change_select2_value('order_type_id', 'Support request')
search_button.click
wait_for_ajax
expect(orders_list).to eq([order_3, order_2])
order_list_table_header('Code').click
wait_for_ajax
expect(orders_list).to eq([order_2, order_3])
order_list_table_header('Code').click
wait_for_ajax
expect(orders_list).to eq([order_3, order_2])
end
scenario 'by custom fields' do
order_2_with_contract = order_2 + [support_request_order.data['contractNumber'].to_s]
order_3_with_contract = order_3 + [support_request_order_for_ordering.data['contractNumber'].to_s]
# "Order type"
change_select2_value('order_type_id', 'Support request')
search_button.click
wait_for_ajax
expect(orders_list).to eq([order_3, order_2])
# Add Contract number to orders table
click_on_multiselect_options('column-settings', %w(contractNumber))
wait_for_ajax
expect(orders_list).to eq([order_3_with_contract, order_2_with_contract])
# Check sorting
order_list_table_header('Contract number').click
wait_for_ajax
expect(orders_list).to eq([order_2_with_contract, order_3_with_contract])
order_list_table_header('Contract number').click
wait_for_ajax
expect(orders_list).to eq([order_3_with_contract, order_2_with_contract])
end
end
end
|
{
"pile_set_name": "Github"
}
|
1
301
601
868
1168
1468
1542
|
{
"pile_set_name": "Github"
}
|
3034 House Davion Mech - Light C
Ostscout OTT-7J,1
Spider SDR-5V,2
Commando COM-2D,3
Wasp WSP-1A,4
Javelin JVN-10N,5
Valkyrie VLK-QA,6
Stinger STG-3R,5
Locust LCT-1V,4
Firestarter FS9-H,3
Valkyrie VLK-QA,2
Jenner JR7-D,1
|
{
"pile_set_name": "Github"
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import com.adobe.test.Assert;
// var SECTION = "RegExp";
// var VERSION = "as3";
// var TITLE = "https://bugzilla.mozilla.org/show_bug.cgi?id=550269";
// CVE-2008-0674: large number of characters with Unicode code points greater than 255
var utf8RegExp:String = "[^ABCDEFGHIJKLMNOPQRSTUVWXYZÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃÃÑÒÓÔÕÖØÙÚÛÜÃÞĀĂĄĆĈĊČĎÄÄ’Ä”Ä–Ä˜ÄšÄœÄžÄ Ä¢Ä¤Ä¦Ä¨ÄªÄ¬Ä®Ä°Ä²Ä´Ä¶Ä¹Ä»Ä½Ä¿ÅŃŅŇŊŌŎÅÅ’Å”Å–Å˜ÅšÅœÅžÅ Å¢Å¤Å¦Å¨ÅªÅ¬Å®Å°Å²Å´Å¶Å¸Å¹Å»Å½ÆÆ‚Æ„Æ†Æ‡Æ‰ÆŠÆ‹ÆŽÆÆÆ‘Æ“Æ”Æ–Æ—Æ˜ÆœÆÆŸÆ ƢƤƦƧƩƬƮƯƱƲƳƵƷƸƼDŽLJNJÇÇÇ‘Ç“Ç•Ç—Ç™Ç›ÇžÇ Ç¢Ç¤Ç¦Ç¨ÇªÇ¬Ç®Ç±Ç´Ç¶Ç·Ç¸ÇºÇ¼Ç¾È€È‚È„È†ÈˆÈŠÈŒÈŽÈÈ’È”È–È˜ÈšÈœÈžÈ È¢È¤È¦È¨ÈªÈ¬È®È°È²ÈºÈ»È½È¾ÉΆΈΉΊΌΎÎΑΒΓΔΕΖΗΘΙΚΛΜÎÎžÎŸÎ Î¡Î£Î¤Î¥Î¦Î§Î¨Î©ÎªÎ«Ï’Ï“Ï”Ï˜ÏšÏœÏžÏ Ï¢Ï¤Ï¦Ï¨ÏªÏ¬Ï®Ï´Ï·Ï¹ÏºÏ½Ï¾Ï¿Ð€ÐЂЃЄЅІЇЈЉЊЋЌÐÐŽÐÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬÐÐ®Ð¯Ñ Ñ¢Ñ¤Ñ¦Ñ¨ÑªÑ¬Ñ®Ñ°Ñ²Ñ´Ñ¶Ñ¸ÑºÑ¼Ñ¾Ò€ÒŠÒŒÒŽÒÒ’Ò”Ò–Ò˜ÒšÒœÒžÒ Ò¢Ò¤Ò¦Ò¨ÒªÒ¬Ò®Ò°Ò²Ò´Ò¶Ò¸ÒºÒ¼Ò¾Ó€ÓÓƒÓ…Ó‡Ó‰Ó‹ÓÓÓ’Ó”Ó–Ó˜ÓšÓœÓžÓ Ó¢Ó¤Ó¦Ó¨ÓªÓ¬Ó®Ó°Ó²Ó´Ó¶Ó¸Ô€Ô‚Ô„Ô†ÔˆÔŠÔŒÔŽÔ±Ô²Ô³Ô´ÔµÔ¶Ô·Ô¸Ô¹ÔºÔ»Ô¼Ô½Ô¾Ô¿Õ€ÕÕ‚ÕƒÕ„Õ…Õ†Õ‡ÕˆÕ‰ÕŠÕ‹ÕŒÕÕŽÕÕՑՒՓՔՕՖႠႡႢႣႤႥႦႧႨႩႪႫႬá‚ႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀáƒáƒ‚ჃჄჅḀḂḄḆḈḊḌḎá¸á¸’ḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎá¹á¹’ṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎáºáº’ẔẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎá»á»’ỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸἈἉἊἋἌá¼á¼Žá¼á¼˜á¼™á¼šá¼›á¼œá¼á¼¨á¼©á¼ªá¼«á¼¬á¼á¼®á¼¯á¼¸á¼¹á¼ºá¼»á¼¼á¼½á¼¾á¼¿á½ˆá½‰á½Šá½‹á½Œá½á½™á½›á½á½Ÿá½¨á½©á½ªá½«á½¬á½á½®á½¯á¾¸á¾¹á¾ºá¾»á¿ˆá¿‰á¿Šá¿‹á¿˜á¿™á¿šá¿›á¿¨á¿©á¿ªá¿«á¿¬á¿¸á¿¹á¿ºá¿»abcdefghijklmnopqrstuvwxyzªµºßà áâãäåæçèéêëìÃîïðñòóôõöøùúûüýþÿÄăąćĉċÄÄđēĕėęěÄğġģĥħĩīÄįıijĵķĸĺļľŀłńņňʼnŋÅÅőœŕŗřśÅşšţťŧũūÅÅ¯Å±Å³ÅµÅ·ÅºÅ¼Å¾Å¿Æ€ÆƒÆ…ÆˆÆŒÆÆ’Æ•Æ™ÆšÆ›ÆžÆ¡Æ£Æ¥Æ¨ÆªÆ«ÆÆ°Æ´Æ¶Æ¹ÆºÆ½Æ¾Æ¿Ç†Ç‰ÇŒÇŽÇǒǔǖǘǚǜÇǟǡǣǥǧǩǫÇǯǰdzǵǹǻǽǿÈȃȅȇȉȋÈÈȑȓȕȗșțÈȟȡȣȥȧȩȫÈȯȱȳȴȵȶȷȸȹȼȿɀÉɑɒɓɔɕɖɗɘəɚɛɜÉÉžÉŸÉ É¡É¢É£É¤É¥É¦É§É¨É©ÉªÉ«É¬ÉɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀÊʂʃʄʅʆʇʈʉʊʋʌÊÊŽÊÊʑʒʓʔʕʖʗʘʙʚʛʜÊÊžÊŸÊ Ê¡Ê¢Ê£Ê¤Ê¥Ê¦Ê§Ê¨Ê©ÊªÊ«Ê¬ÊʮʯÎάÎήίΰαβγδεζηθικλμνξοπÏςστυφχψωϊϋόÏÏŽÏϑϕϖϗϙϛÏϟϡϣϥϧϩϫÏϯϰϱϲϳϵϸϻϼабвгдежзийклмнопрÑтуфхцчшщъыьÑÑŽÑÑёђѓєѕіїјљњћќÑўџѡѣѥѧѩѫÑѯѱѳѵѷѹѻѽѿÒÒ‹ÒÒÒ‘Ò“Ò•Ò—Ò™Ò›ÒÒŸÒ¡Ò£Ò¥Ò§Ò©Ò«ÒүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӑӓӕӗәӛÓÓŸÓ¡Ó£Ó¥Ó§Ó©Ó«ÓÓ¯Ó±Ó³ÓµÓ·Ó¹ÔÔƒÔ…Ô‡Ô‰Ô‹ÔÔÕ¡Õ¢Õ£Õ¤Õ¥Õ¦Õ§Õ¨Õ©ÕªÕ«Õ¬ÕÕ®Õ¯Õ°Õ±Õ²Õ³Õ´ÕµÕ¶Õ·Õ¸Õ¹ÕºÕ»Õ¼Õ½Õ¾Õ¿Ö€Öւփքօֆևᴀá´á´‚ᴃᴄᴅᴆᴇᴈᴉᴊᴋᴌá´á´Žá´á´á´‘ᴒᴓᴔᴕᴖᴗᴘᴙᴚᴛᴜá´á´žá´Ÿá´ ᴡᴢᴣᴤᴥᴦᴧᴨᴩᴪᴫᵢᵣᵤᵥᵦᵧᵨᵩᵪᵫᵬáµáµ®áµ¯áµ°áµ±áµ²áµ³áµ´áµµáµ¶áµ·áµ¹áµºáµ»áµ¼áµ½áµ¾áµ¿á¶€á¶á¶‚ᶃᶄᶅᶆᶇᶈᶉᶊᶋᶌá¶á¶Žá¶á¶á¶‘ᶒᶓᶔᶕᶖᶗᶘᶙᶚá¸á¸ƒá¸…ḇḉḋá¸á¸á¸‘ḓḕḗḙḛá¸á¸Ÿá¸¡á¸£á¸¥á¸§á¸©á¸«á¸á¸¯á¸±á¸³á¸µá¸·á¸¹á¸»á¸½á¸¿á¹á¹ƒá¹…ṇṉṋá¹á¹á¹‘ṓṕṗṙṛá¹á¹Ÿá¹¡á¹£á¹¥á¹§á¹©á¹«á¹á¹¯á¹±á¹³á¹µá¹·á¹¹á¹»á¹½á¹¿áºáºƒáº…ẇẉẋáºáºáº‘ẓẕẖẗẘẙẚẛạảấầẩẫáºáº¯áº±áº³áºµáº·áº¹áº»áº½áº¿á»á»ƒá»…ệỉịá»á»á»‘ồổỗộớá»á»Ÿá»¡á»£á»¥á»§á»©á»«á»á»¯á»±á»³á»µá»·á»¹á¼€á¼á¼‚ἃἄἅἆἇá¼á¼‘ἒἓἔἕἠἡἢἣἤἥἦἧἰἱἲἳἴἵἶἷὀá½á½‚ὃὄὅá½á½‘ὒὓὔὕὖὗὠὡὢὣὤὥὦὧὰάὲέὴήὶίὸόὺύὼώᾀá¾á¾‚ᾃᾄᾅᾆᾇá¾á¾‘ᾒᾓᾔᾕᾖᾗᾠᾡᾢᾣᾤᾥᾦᾧᾰᾱᾲᾳᾴᾶᾷιῂῃῄῆῇá¿á¿‘ῒΐῖῗῠῡῢΰῤῥῦῧῲῳῴῶῷâ²â²ƒâ²…ⲇⲉⲋâ²â²â²‘ⲓⲕⲗⲙⲛâ²â²Ÿâ²¡â²£â²¥â²§â²©â²«â²â²¯â²±â²³â²µâ²·â²¹â²»â²½â²¿â³â³ƒâ³…ⳇⳉⳋâ³â³â³‘ⳓⳕⳗⳙⳛâ³â³Ÿâ³¡â³£â³¤â´€â´â´‚ⴃⴄⴅⴆⴇⴈⴉⴊⴋⴌâ´â´Žâ´â´â´‘ⴒⴓⴔⴕⴖⴗⴘⴙⴚⴛⴜâ´â´žâ´Ÿâ´ ⴡⴢⴣⴤⴥffï¬ï¬‚ffifflſtstﬓﬔﬕﬖﬗ\d-_^]";
var evilRegExp:RegExp = new RegExp(utf8RegExp);
evilRegExp.exec("Hello World");
// If testcase runs then we are good, previously this would crash
Assert.expectEq(
"CVE-2008-0674",
true,
true
);
// CVE-2008-2371 begins with an option and contains multiple branches.
var optionsRegExp:String = "(?i)[\xc3\xa9\xc3\xbd]|[\xc3\xa9\xc3\xbdA]";
var evilRegExp2:RegExp = new RegExp(optionsRegExp);
evilRegExp2.exec("Hello World");
// If testcase runs then we are good, previously this would crash
Assert.expectEq(
"CVE-2008-2371",
true,
true
);
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python3
#GI_TYPELIB_PATH=$PREFIX/lib/girepository-1.0/ ./period-type.py
###############################################################################
#
# Copyright (C) 2015 William Yu <williamyu@gnome.org>
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of either:
#
# The LGPL as published by the Free Software Foundation, version
# 2.1, available at: https://www.gnu.org/licenses/lgpl-2.1.txt
#
# Or:
#
# The Mozilla Public License Version 2.0. You may obtain a copy of
# the License at https://www.mozilla.org/MPL/
#
###############################################################################
import gi
gi.require_version('ICalGLib', '3.0')
from gi.repository import ICalGLib
string = "19970101T183248Z/19970102T071625Z";
period = ICalGLib.Period.new_from_string(string);
retrieved_string = period.as_ical_string();
assert(retrieved_string == string);
null_period = ICalGLib.Period.new_null_period();
assert(null_period.is_null_period() == 1);
assert(period.is_null_period() == 0);
assert(null_period.is_valid_period() == 1);
assert(period.is_valid_period() == 1);
start = period.get_start();
assert(start.get_year() == 1997);
assert(start.get_month() == 1);
assert(start.get_day() == 1);
assert(start.get_hour() == 18);
assert(start.get_minute() == 32);
assert(start.get_second() == 48);
end = period.get_end();
assert(end.get_year() == 1997);
assert(end.get_month() == 1);
assert(end.get_day() == 2);
assert(end.get_hour() == 7);
assert(end.get_minute() == 16);
assert(end.get_second() == 25);
duration = period.get_duration();
assert(duration.as_int() == 0);
string = "19970101T182346Z/PT5H30M";
period = ICalGLib.Period.new_from_string(string);
retrieved_string = period.as_ical_string();
assert(retrieved_string == string);
start = period.get_start();
assert(start.get_year() == 1997);
assert(start.get_month() == 1);
assert(start.get_day() == 1);
assert(start.get_hour() == 18);
assert(start.get_minute() == 23);
assert(start.get_second() == 46);
end = period.get_end();
assert(end.get_year() == 0);
assert(end.get_month() == 0);
assert(end.get_day() == 0);
assert(end.get_hour() == 0);
assert(end.get_minute() == 0);
assert(end.get_second() == 0);
duration = period.get_duration();
assert(duration.as_ical_string() == "PT5H30M");
|
{
"pile_set_name": "Github"
}
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
// +build aix
/*
Input to cgo -godefs. See also mkerrors.sh and mkall.sh
*/
// +godefs map struct_in_addr [4]byte /* in_addr */
// +godefs map struct_in6_addr [16]byte /* in6_addr */
package unix
/*
#include <sys/types.h>
#include <sys/time.h>
#include <sys/limits.h>
#include <sys/un.h>
#include <utime.h>
#include <sys/utsname.h>
#include <sys/poll.h>
#include <termios.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <netinet/in.h>
#include <netinet/icmp6.h>
#include <dirent.h>
#include <fcntl.h>
#include <gcrypt.h>
enum {
sizeofPtr = sizeof(void*),
};
union sockaddr_all {
struct sockaddr s1; // this one gets used for fields
struct sockaddr_in s2; // these pad it out
struct sockaddr_in6 s3;
struct sockaddr_un s4;
struct sockaddr_dl s5;
};
struct sockaddr_any {
struct sockaddr addr;
char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
};
*/
import "C"
// Machine characteristics; for internal use.
const (
sizeofPtr = C.sizeofPtr
sizeofShort = C.sizeof_short
sizeofInt = C.sizeof_int
sizeofLong = C.sizeof_long
sizeofLongLong = C.sizeof_longlong
PathMax = C.PATH_MAX
)
// Basic types
type (
_C_short C.short
_C_int C.int
_C_long C.long
_C_long_long C.longlong
)
type off64 C.off64_t
type off C.off_t
type Mode_t C.mode_t
// Time
type Timespec C.struct_timespec
type StTimespec C.struct_st_timespec
type Timeval C.struct_timeval
type Timeval32 C.struct_timeval32
type Timex C.struct_timex
type Time_t C.time_t
type Tms C.struct_tms
type Utimbuf C.struct_utimbuf
type Timezone C.struct_timezone
// Processes
type Rusage C.struct_rusage
type Rlimit C.struct_rlimit64
type Pid_t C.pid_t
type _Gid_t C.gid_t
type dev_t C.dev_t
// Files
type Stat_t C.struct_stat
type StatxTimestamp C.struct_statx_timestamp
type Statx_t C.struct_statx
type Dirent C.struct_dirent
// Sockets
type RawSockaddrInet4 C.struct_sockaddr_in
type RawSockaddrInet6 C.struct_sockaddr_in6
type RawSockaddrUnix C.struct_sockaddr_un
type RawSockaddr C.struct_sockaddr
type RawSockaddrAny C.struct_sockaddr_any
type _Socklen C.socklen_t
type Cmsghdr C.struct_cmsghdr
type ICMPv6Filter C.struct_icmp6_filter
type Iovec C.struct_iovec
type IPMreq C.struct_ip_mreq
type IPv6Mreq C.struct_ipv6_mreq
type IPv6MTUInfo C.struct_ip6_mtuinfo
type Linger C.struct_linger
type Msghdr C.struct_msghdr
const (
SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
SizeofLinger = C.sizeof_struct_linger
SizeofIPMreq = C.sizeof_struct_ip_mreq
SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
SizeofMsghdr = C.sizeof_struct_msghdr
SizeofCmsghdr = C.sizeof_struct_cmsghdr
SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
)
// Routing and interface messages
const (
SizeofIfMsghdr = C.sizeof_struct_if_msghdr
)
type IfMsgHdr C.struct_if_msghdr
// Misc
type FdSet C.fd_set
type Utsname C.struct_utsname
type Ustat_t C.struct_ustat
type Sigset_t C.sigset_t
const (
AT_FDCWD = C.AT_FDCWD
AT_REMOVEDIR = C.AT_REMOVEDIR
AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
)
// Terminal handling
type Termios C.struct_termios
type Termio C.struct_termio
type Winsize C.struct_winsize
//poll
type PollFd struct {
Fd int32
Events uint16
Revents uint16
}
const (
POLLERR = C.POLLERR
POLLHUP = C.POLLHUP
POLLIN = C.POLLIN
POLLNVAL = C.POLLNVAL
POLLOUT = C.POLLOUT
POLLPRI = C.POLLPRI
POLLRDBAND = C.POLLRDBAND
POLLRDNORM = C.POLLRDNORM
POLLWRBAND = C.POLLWRBAND
POLLWRNORM = C.POLLWRNORM
)
//flock_t
type Flock_t C.struct_flock64
// Statfs
type Statfs_t C.struct_statfs
const RNDGETENTCNT = 0x80045200
|
{
"pile_set_name": "Github"
}
|
* Add options to open temp and output directories.
- Add options to right-click menu
- Add options to toolbar?
* Customize the right-click menu based on APP_STATE
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
<foo>
<bar>
<a>1</a>
<b>2</b>
<c>3</c>
<a>4</a>
</bar>
</foo>
</root>
|
{
"pile_set_name": "Github"
}
|
// SPDX-License-Identifier: GPL-2.0+
#include <common.h>
#include <exports.h>
/*
* Author: Arun Dharankar <ADharankar@ATTBI.Com>
*
* A very simple thread/schedular model:
* - only one master thread, and no parent child relation maintained
* - parent thread cannot be stopped or deleted
* - no permissions or credentials
* - no elaborate safety checks
* - cooperative multi threading
* - Simple round-robin scheduleing with no priorities
* - no metering/statistics collection
*
* Basic idea of implementing this is to allow more than one tests to
* execute "simultaneously".
*
* This may be modified such thread_yield may be called in syscalls, and
* timer interrupts.
*/
#define MAX_THREADS 8
#define CTX_SIZE 512
#define STK_SIZE 8*1024
#define STATE_EMPTY 0
#define STATE_RUNNABLE 1
#define STATE_STOPPED 2
#define STATE_TERMINATED 2
#define MASTER_THREAD 0
#define RC_FAILURE (-1)
#define RC_SUCCESS (0)
typedef vu_char *jmp_ctx;
unsigned long setctxsp (vu_char *sp);
int ppc_setjmp(jmp_ctx env);
void ppc_longjmp(jmp_ctx env, int val);
#define setjmp ppc_setjmp
#define longjmp ppc_longjmp
struct lthread {
int state;
int retval;
char stack[STK_SIZE];
uchar context[CTX_SIZE];
int (*func) (void *);
void *arg;
};
static volatile struct lthread lthreads[MAX_THREADS];
static volatile int current_tid = MASTER_THREAD;
static uchar dbg = 0;
#define PDEBUG(fmt, args...) { \
if(dbg != 0) { \
printf("[%s %d %s]: ",__FILE__,__LINE__,__FUNCTION__);\
printf(fmt, ##args); \
printf("\n"); \
} \
}
static int testthread (void *);
static void sched_init (void);
static int thread_create (int (*func) (void *), void *arg);
static int thread_start (int id);
static void thread_yield (void);
static int thread_delete (int id);
static int thread_join (int *ret);
#if 0 /* not used yet */
static int thread_stop (int id);
#endif /* not used yet */
/* An example of schedular test */
#define NUMTHREADS 7
int sched (int ac, char *av[])
{
int i, j;
int tid[NUMTHREADS];
int names[NUMTHREADS];
app_startup(av);
sched_init ();
for (i = 0; i < NUMTHREADS; i++) {
names[i] = i;
j = thread_create (testthread, (void *) &names[i]);
if (j == RC_FAILURE)
printf ("schedtest: Failed to create thread %d\n", i);
if (j > 0) {
printf ("schedtest: Created thread with id %d, name %d\n",
j, i);
tid[i] = j;
}
}
printf ("schedtest: Threads created\n");
printf ("sched_test: function=0x%08x\n", (unsigned)testthread);
for (i = 0; i < NUMTHREADS; i++) {
printf ("schedtest: Setting thread %d runnable\n", tid[i]);
thread_start (tid[i]);
thread_yield ();
}
printf ("schedtest: Started %d threads\n", NUMTHREADS);
while (1) {
printf ("schedtest: Waiting for threads to complete\n");
if (tstc () && getc () == 0x3) {
printf ("schedtest: Aborting threads...\n");
for (i = 0; i < NUMTHREADS; i++) {
printf ("schedtest: Deleting thread %d\n", tid[i]);
thread_delete (tid[i]);
}
return RC_SUCCESS;
}
j = -1;
i = thread_join (&j);
if (i == RC_FAILURE) {
printf ("schedtest: No threads pending, "
"exiting schedular test\n");
return RC_SUCCESS;
}
printf ("schedtest: thread is %d returned %d\n", i, j);
thread_yield ();
}
return RC_SUCCESS;
}
static int testthread (void *name)
{
int i;
printf ("testthread: Begin executing thread, myname %d, &i=0x%08x\n",
*(int *) name, (unsigned)&i);
printf ("Thread %02d, i=%d\n", *(int *) name, i);
for (i = 0; i < 0xffff * (*(int *) name + 1); i++) {
if (tstc () && getc () == 0x3) {
printf ("testthread: myname %d terminating.\n",
*(int *) name);
return *(int *) name + 1;
}
if (i % 100 == 0)
thread_yield ();
}
printf ("testthread: returning %d, i=0x%x\n",
*(int *) name + 1, i);
return *(int *) name + 1;
}
static void sched_init (void)
{
int i;
for (i = MASTER_THREAD + 1; i < MAX_THREADS; i++)
lthreads[i].state = STATE_EMPTY;
current_tid = MASTER_THREAD;
lthreads[current_tid].state = STATE_RUNNABLE;
PDEBUG ("sched_init: master context = 0x%08x",
(unsigned)lthreads[current_tid].context);
return;
}
static void thread_yield (void)
{
static int i;
PDEBUG ("thread_yield: current tid=%d", current_tid);
#define SWITCH(new) \
if(lthreads[new].state == STATE_RUNNABLE) { \
PDEBUG("thread_yield: %d match, ctx=0x%08x", \
new, \
(unsigned)lthreads[current_tid].context); \
if(setjmp(lthreads[current_tid].context) == 0) { \
current_tid = new; \
PDEBUG("thread_yield: tid %d returns 0", \
new); \
longjmp(lthreads[new].context, 1); \
} else { \
PDEBUG("thread_yield: tid %d returns 1", \
new); \
return; \
} \
}
for (i = current_tid + 1; i < MAX_THREADS; i++) {
SWITCH (i);
}
if (current_tid != 0) {
for (i = 0; i <= current_tid; i++) {
SWITCH (i);
}
}
PDEBUG ("thread_yield: returning from thread_yield");
return;
}
static int thread_create (int (*func) (void *), void *arg)
{
int i;
for (i = MASTER_THREAD + 1; i < MAX_THREADS; i++) {
if (lthreads[i].state == STATE_EMPTY) {
lthreads[i].state = STATE_STOPPED;
lthreads[i].func = func;
lthreads[i].arg = arg;
PDEBUG ("thread_create: returns new tid %d", i);
return i;
}
}
PDEBUG ("thread_create: returns failure");
return RC_FAILURE;
}
static int thread_delete (int id)
{
if (id <= MASTER_THREAD || id > MAX_THREADS)
return RC_FAILURE;
if (current_tid == id)
return RC_FAILURE;
lthreads[id].state = STATE_EMPTY;
return RC_SUCCESS;
}
static void thread_launcher (void)
{
PDEBUG ("thread_launcher: invoking func=0x%08x",
(unsigned)lthreads[current_tid].func);
lthreads[current_tid].retval =
lthreads[current_tid].func (lthreads[current_tid].arg);
PDEBUG ("thread_launcher: tid %d terminated", current_tid);
lthreads[current_tid].state = STATE_TERMINATED;
thread_yield ();
printf ("thread_launcher: should NEVER get here!\n");
return;
}
static int thread_start (int id)
{
PDEBUG ("thread_start: id=%d", id);
if (id <= MASTER_THREAD || id > MAX_THREADS) {
return RC_FAILURE;
}
if (lthreads[id].state != STATE_STOPPED)
return RC_FAILURE;
if (setjmp (lthreads[current_tid].context) == 0) {
lthreads[id].state = STATE_RUNNABLE;
current_tid = id;
PDEBUG ("thread_start: to be stack=0%08x",
(unsigned)lthreads[id].stack);
setctxsp ((vu_char *)<hreads[id].stack[STK_SIZE]);
thread_launcher ();
}
PDEBUG ("thread_start: Thread id=%d started, parent returns", id);
return RC_SUCCESS;
}
#if 0 /* not used so far */
static int thread_stop (int id)
{
if (id <= MASTER_THREAD || id >= MAX_THREADS)
return RC_FAILURE;
if (current_tid == id)
return RC_FAILURE;
lthreads[id].state = STATE_STOPPED;
return RC_SUCCESS;
}
#endif /* not used so far */
static int thread_join (int *ret)
{
int i, j = 0;
PDEBUG ("thread_join: *ret = %d", *ret);
if (!(*ret == -1 || *ret > MASTER_THREAD || *ret < MAX_THREADS)) {
PDEBUG ("thread_join: invalid tid %d", *ret);
return RC_FAILURE;
}
if (*ret == -1) {
PDEBUG ("Checking for tid = -1");
while (1) {
/* PDEBUG("thread_join: start while-loopn"); */
j = 0;
for (i = MASTER_THREAD + 1; i < MAX_THREADS; i++) {
if (lthreads[i].state == STATE_TERMINATED) {
*ret = lthreads[i].retval;
lthreads[i].state = STATE_EMPTY;
/* PDEBUG("thread_join: returning retval %d of tid %d",
ret, i); */
return RC_SUCCESS;
}
if (lthreads[i].state != STATE_EMPTY) {
PDEBUG ("thread_join: %d used slots tid %d state=%d",
j, i, lthreads[i].state);
j++;
}
}
if (j == 0) {
PDEBUG ("thread_join: all slots empty!");
return RC_FAILURE;
}
/* PDEBUG("thread_join: yielding"); */
thread_yield ();
/* PDEBUG("thread_join: back from yield"); */
}
}
if (lthreads[*ret].state == STATE_TERMINATED) {
i = *ret;
*ret = lthreads[*ret].retval;
lthreads[*ret].state = STATE_EMPTY;
PDEBUG ("thread_join: returing %d for tid %d", *ret, i);
return RC_SUCCESS;
}
PDEBUG ("thread_join: thread %d is not terminated!", *ret);
return RC_FAILURE;
}
|
{
"pile_set_name": "Github"
}
|
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# $Id: manifest.ttl,v 1.10 2007/09/20 14:26:51 aseaborne Exp $
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix : <http://www.w3.org/2001/sw/DataAccess/tests/data-r2/open-world/manifest#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix dawgt: <http://www.w3.org/2001/sw/DataAccess/tests/test-dawg#> .
@prefix mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#> .
@prefix qt: <http://www.w3.org/2001/sw/DataAccess/tests/test-query#> .
<> rdf:type mf:Manifest ;
rdfs:label "open world value testing tests" ;
mf:entries
(
:open-eq-01 :open-eq-02 :open-eq-03 :open-eq-04 :open-eq-05 :open-eq-06
:open-eq-07 :open-eq-08 :open-eq-09 :open-eq-10 :open-eq-11 :open-eq-12
:date-1 :date-2 :date-3 :date-4
:open-cmp-01 :open-cmp-02
) .
:open-eq-01 a mf:QueryEvaluationTest ;
mf:name "open-eq-01" ;
rdfs:comment "graph match - no lexical form in data (assumes no value matching)" ;
mf:action
[ qt:query <open-eq-01.rq> ;
qt:data <data-1.ttl> ] ;
mf:result <open-eq-01-result.srx> ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-02 a mf:QueryEvaluationTest ;
mf:name "open-eq-02" ;
rdfs:comment "graph match - unknown type" ;
mf:action
[ qt:query <open-eq-02.rq> ;
qt:data <data-1.ttl> ] ;
mf:result <open-eq-02-result.srx> ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-03 a mf:QueryEvaluationTest ;
mf:name "open-eq-03" ;
rdfs:comment "Filter(?v=1)" ;
mf:action
[ qt:query <open-eq-03.rq> ;
qt:data <data-1.ttl> ] ;
mf:result <open-eq-03-result.srx> ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-04 a mf:QueryEvaluationTest ;
mf:name "open-eq-04" ;
rdfs:comment "Filter(?v!=1)" ;
mf:action
[ qt:query <open-eq-04.rq> ;
qt:data <data-1.ttl> ] ;
mf:result <open-eq-04-result.srx> ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-05 a mf:QueryEvaluationTest ;
mf:name "open-eq-05" ;
rdfs:comment "FILTER(?v = unknown type)" ;
mf:action
[ qt:query <open-eq-05.rq> ;
qt:data <data-1.ttl> ] ;
mf:result <open-eq-05-result.srx> ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-06 a mf:QueryEvaluationTest ;
mf:name "open-eq-06" ;
rdfs:comment "FILTER(?v != unknown type)" ;
mf:action
[ qt:query <open-eq-06.rq> ;
qt:data <data-1.ttl> ] ;
mf:result <open-eq-06-result.srx> ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-07 a mf:QueryEvaluationTest ;
mf:name "open-eq-07" ;
rdfs:comment "Test of '=' " ;
mf:action
[ qt:query <open-eq-07.rq> ;
qt:data <data-2.ttl> ] ;
mf:result <open-eq-07-result.srx> ;
mf:requires mf:LangTagAwareness ;
mf:requires mf:StringSimpleLiteralCmp ;
mf:notable mf:IllFormedLiteral ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-08 a mf:QueryEvaluationTest ;
mf:name "open-eq-08" ;
rdfs:comment "Test of '!='" ;
mf:action
[ qt:query <open-eq-08.rq> ;
qt:data <data-2.ttl> ] ;
mf:result <open-eq-08-result.srx> ;
mf:requires mf:StringSimpleLiteralCmp ;
mf:requires mf:LangTagAwareness ;
mf:requires mf:KnownTypesDefault2Neq ;
mf:notable mf:IllFormedLiteral ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-09 a mf:QueryEvaluationTest ;
mf:name "open-eq-09" ;
rdfs:comment "Test of '='" ;
mf:action
[ qt:query <open-eq-09.rq> ;
qt:data <data-2.ttl> ] ;
mf:result <open-eq-09-result.srx> ;
mf:notable mf:IllFormedLiteral ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-10 a mf:QueryEvaluationTest ;
mf:name "open-eq-10" ;
rdfs:comment "Test of '!='" ;
mf:action
[ qt:query <open-eq-10.rq> ;
qt:data <data-2.ttl> ] ;
mf:result <open-eq-10-result.srx> ;
mf:notable mf:IllFormedLiteral ;
mf:requires mf:KnownTypesDefault2Neq ;
mf:requires mf:LangTagAwareness ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-11 a mf:QueryEvaluationTest ;
mf:name "open-eq-11" ;
rdfs:comment "test of '=' || '!='" ;
mf:action
[ qt:query <open-eq-11.rq> ;
qt:data <data-2.ttl> ] ;
mf:result <open-eq-11-result.srx> ;
mf:notable mf:IllFormedLiteral ;
mf:requires mf:KnownTypesDefault2Neq ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-eq-12 a mf:QueryEvaluationTest ;
mf:name "open-eq-12" ;
rdfs:comment "find pairs that don't value-compare" ;
mf:action
[ qt:query <open-eq-12.rq> ;
qt:data <data-2.ttl> ] ;
mf:result <open-eq-12-result.srx> ;
mf:notable mf:IllFormedLiteral ;
mf:requires mf:KnownTypesDefault2Neq ;
mf:requires mf:LangTagAwareness ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:date-1 a mf:QueryEvaluationTest ;
mf:name "date-1" ;
rdfs:comment "Added type : xsd:date '='" ;
mf:action
[ qt:query <date-1.rq> ;
qt:data <data-3.ttl> ] ;
mf:result <date-1-result.srx> ;
mf:requires mf:XsdDateOperations ;
.
# Fixed test (was wrong) - needs reapproving
# Decision at http://lists.w3.org/Archives/Public/public-rdf-dawg/2007JulSep/att-0118/04-dawg-minutes.html to leave test not approved
## dawgt:approval dawgt:Approved ;
## dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:date-2 a mf:QueryEvaluationTest ;
mf:name "date-2" ;
rdfs:comment "Added type : xsd:date '!='" ;
mf:action
[ qt:query <date-2.rq> ;
qt:data <data-3.ttl> ] ;
mf:result <date-2-result.srx> ;
mf:requires mf:XsdDateOperations ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:date-3 a mf:QueryEvaluationTest ;
mf:name "date-3" ;
rdfs:comment "Added type : xsd:date '>'" ;
mf:action
[ qt:query <date-3.rq> ;
qt:data <data-3.ttl> ] ;
mf:result <date-3-result.srx> ;
mf:requires mf:XsdDateOperations ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:date-4 a mf:QueryEvaluationTest ;
mf:name "date-4" ;
rdfs:comment "xsd:date ORDER BY" ;
mf:action
[ qt:query <date-4.rq> ;
qt:data <data-3.ttl> ] ;
mf:result <date-4-result.srx> ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-cmp-01 a mf:QueryEvaluationTest ;
mf:name "open-cmp-01" ;
rdfs:comment "Find things that compare with < or >" ;
mf:action
[ qt:query <open-cmp-01.rq> ;
qt:data <data-4.ttl> ] ;
mf:result <open-cmp-01-result.srx> ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html> .
:open-cmp-02 a mf:QueryEvaluationTest ;
mf:name "open-cmp-02" ;
rdfs:comment "Find things that compare with <= and >" ;
mf:action
[ qt:query <open-cmp-02.rq> ;
qt:data <data-4.ttl> ] ;
mf:result <open-cmp-02-result.srx> ;
dawgt:approval dawgt:Approved ;
dawgt:approvedBy <http://lists.w3.org/Archives/Public/public-rdf-dawg/2007JulSep/att-0118/04-dawg-minutes.html> .
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TankView.View {
/// <summary>
/// Interaction logic for PreviewDataImage.xaml
/// </summary>
public partial class PreviewDataImage : UserControl {
public PreviewDataImage() {
InitializeComponent();
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*!
* Copyright 2017 The SwitchyOmega Authors. Please see the AUTHORS file
* for details.
* Based on Bootstrap v3.3.2 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/* Dialog */
body, html {
margin: 0;
padding: 0;
}
p {
margin: 0 0 1em 0;
}
.om-dialog {
min-width: 400px;
padding: 10px 10px;
font-size: 14px;
}
.om-text-danger {
color: #a94442;
}
.om-dialog-help {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #737373;
}
.om-dialog-controls {
margin-bottom: 0;
}
.om-dialog-controls .om-btn-primary {
float: right;
}
/* Button */
.om-btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: 400;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px
}
.om-btn.active, .om-btn:active {
background-image: none;
outline: 0;
-webkit-box-shadow: inset 0 3px 5px rgba(0,0,0,.125);
box-shadow: inset 0 3px 5px rgba(0,0,0,.125);
}
.om-btn-default {
color: #333;
background-color: #fff;
border-color: #ccc;
}
.om-btn-default:hover {
background-color: #e6e6e6;
border-color: #adadad;
}
.om-btn-primary {
color: #fff;
background-color: #337ab7;
border-color: #2e6da4;
}
.om-btn-primary:hover {
color: #fff;
background-color: #286090;
border-color: #204d74;
}
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.