code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
/*
* Webpack development server configuration
*
* This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if
* the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload.
*/
'use strict';
import webpack from 'webpack';
import path from 'path';
import autoprefixer from 'autoprefixer';
const API_URL = process.env['__API_URL__'] || 'http://localhost:3001/'; //eslint-disable-line
export default {
output: {
path: path.join(__dirname, '.tmp'),
filename: 'bundle.js',
publicPath: '/static/'
},
devtool: 'eval-source-map',
entry: [
'whatwg-fetch',
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'react-hot-loader/patch',
'./src/index.js'
],
module: {
preLoaders: [{
test: /\.(js|jsx)$/,
exclude: [/node_modules/, /vendor/],
loader: 'eslint-loader'
}],
loaders: [{
test: /\.(js|jsx)$/,
include: path.join(__dirname, 'src'),
loader: 'babel-loader'
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!postcss-loader!sass-loader'
},
{
test: /\.json/,
loader: 'json-loader'
}, {
test: /\.(png|jpg|ttf|svg|eot|woff|woff2)/,
loader: 'url-loader?limit=8192'
}]
},
postcss: [
autoprefixer({ browsers: 'last 2 versions' })
],
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
__DEV__: true,
__DEVTOOLS__: false,
__API_URL__: `\'${API_URL}\'`
})
]
};
| Java |
// This code will add an event listener to each anchor of the topbar after being dynamically replaced by "interchange"
$("body").on("click", function(event){
// If the active element is one of the topbar's links continues
if($(event.target).hasClass("topbarLink")) {
// The parent li element of the current active link is stored
var activeLink = $(event.target).parent();
// Takes each link and checks if its parent li element is active, removing "active" class if so.
$("#topNavContent li:not(.divider)").each(function(){
// If the li element has nested li's with links they are checked also.
if($(this).hasClass("has-dropdown")){
var dropdownList = $(this).children(".dropdown").children().not(".divider");
dropdownList.each(function(){
if($(this).hasClass("active")){
$(this).removeClass("active");
}
});
}
// The direct li element's "active" class is removed
if($(this).hasClass("active")){
$(this).removeClass("active");
}
});
// After having all topbar li elements deactivated, "active" class is added to the currently active link's li parent
if(!$(activeLink).hasClass("active")){
$(activeLink).addClass("active");
}
}
});
// This variable is used to know if this script will be loaded at the time of checking it in the JS manager
activeLinkActivatorLoaded = true; | Java |
const elixir = require('laravel-elixir');
elixir((mix) => {
// Mix all Sass files into one
mix.sass('app.scss');
// Mix all vendor scripts together
mix.scripts(
[
'jquery/dist/jquery.min.js',
'bootstrap-sass/assets/javascripts/bootstrap.min.js',
'bootstrap-sass/assets/javascripts/bootstrap/dropdown.js'
],
'resources/assets/js/vendor.js',
'node_modules'
);
// Mix all script files into one
mix.scripts(
['vendor.js', 'app.js'],
'public/js/app.js'
);
// Copy vendor assets to public
mix.copy('node_modules/bootstrap-sass/assets/fonts/bootstrap/','public/fonts/bootstrap')
.copy('node_modules/font-awesome/fonts', 'public/fonts');
});
/*
var elixir = require('laravel-elixir');
elixir(function(mix) {
// Mix all scss files into one css file
mix.sass([
'charts.scss',
'app.scss'
], 'public/css/app.css');
// Mix all chart JS files into a master charts file
mix.scriptsIn(
'resources/assets/js/charts',
'public/js/charts.js'
);
// Mix common JS files into one file
mix.scripts([
'app.js'
], 'public/js/app.js');
});
*/
| Java |
require 'spec_helper'
describe User do
context 'fields' do
it { should have_field(:email).of_type(String)}
it { should have_field(:encrypted_password).of_type(String)}
it { should have_field(:roles).of_type(Array)}
end
context 'Mass assignment' do
it { should allow_mass_assignment_of(:email) }
it { should allow_mass_assignment_of(:roles) }
it { should allow_mass_assignment_of(:password) }
it { should allow_mass_assignment_of(:password_confirmation) }
end
context 'Required fields' do
it { should validate_presence_of(:roles)}
end
context 'Associations' do
it { should embed_one :profile }
end
end
| Java |
import {Map} from 'immutable';
export function getInteractiveLayerIds(mapStyle) {
let interactiveLayerIds = [];
if (Map.isMap(mapStyle) && mapStyle.has('layers')) {
interactiveLayerIds = mapStyle.get('layers')
.filter(l => l.get('interactive'))
.map(l => l.get('id'))
.toJS();
} else if (Array.isArray(mapStyle.layers)) {
interactiveLayerIds = mapStyle.layers.filter(l => l.interactive)
.map(l => l.id);
}
return interactiveLayerIds;
} | Java |
<!doctype html>
<html>
<head>
</head>
<body>
<h1>Milestones - Codenautas</h1>
<div id=milestones></div>
<script src=milestones.js></script>
</body>
</html>
| Java |
/*
* Created on 24/02/2014
*
*/
package net.rlviana.pricegrabber.model.entity.common;
import net.rlviana.pricegrabber.context.JPAPersistenceContext;
import net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
* @author ramon
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JPAPersistenceContext.class})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@Transactional
public class CurrencyTest extends AbstractReadOnlyEntityTest<Currency, String> {
private static final Logger LOGGER = LoggerFactory.getLogger(CurrencyTest.class);
@Test
public void testFindAll() {
}
@Test
public void testFindByCriteria() {
}
/**
* @return
* @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getEntityPKFindOK()
*/
@Override
protected String getEntityPKFindOK() {
return "EU";
}
/**
* @return
* @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getEntityPKFindKO()
*/
@Override
protected String getEntityPKFindKO() {
return "NEU";
}
/**
* @return
* @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getTestClass()
*/
@Override
protected Class<Currency> getTestClass() {
return Currency.class;
}
}
| Java |
package machinelearningservices
// 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.
// AllocationState enumerates the values for allocation state.
type AllocationState string
const (
// AllocationStateResizing ...
AllocationStateResizing AllocationState = "Resizing"
// AllocationStateSteady ...
AllocationStateSteady AllocationState = "Steady"
)
// PossibleAllocationStateValues returns an array of possible values for the AllocationState const type.
func PossibleAllocationStateValues() []AllocationState {
return []AllocationState{AllocationStateResizing, AllocationStateSteady}
}
// ApplicationSharingPolicy enumerates the values for application sharing policy.
type ApplicationSharingPolicy string
const (
// ApplicationSharingPolicyPersonal ...
ApplicationSharingPolicyPersonal ApplicationSharingPolicy = "Personal"
// ApplicationSharingPolicyShared ...
ApplicationSharingPolicyShared ApplicationSharingPolicy = "Shared"
)
// PossibleApplicationSharingPolicyValues returns an array of possible values for the ApplicationSharingPolicy const type.
func PossibleApplicationSharingPolicyValues() []ApplicationSharingPolicy {
return []ApplicationSharingPolicy{ApplicationSharingPolicyPersonal, ApplicationSharingPolicyShared}
}
// ClusterPurpose enumerates the values for cluster purpose.
type ClusterPurpose string
const (
// ClusterPurposeDenseProd ...
ClusterPurposeDenseProd ClusterPurpose = "DenseProd"
// ClusterPurposeDevTest ...
ClusterPurposeDevTest ClusterPurpose = "DevTest"
// ClusterPurposeFastProd ...
ClusterPurposeFastProd ClusterPurpose = "FastProd"
)
// PossibleClusterPurposeValues returns an array of possible values for the ClusterPurpose const type.
func PossibleClusterPurposeValues() []ClusterPurpose {
return []ClusterPurpose{ClusterPurposeDenseProd, ClusterPurposeDevTest, ClusterPurposeFastProd}
}
// ComputeInstanceAuthorizationType enumerates the values for compute instance authorization type.
type ComputeInstanceAuthorizationType string
const (
// ComputeInstanceAuthorizationTypePersonal ...
ComputeInstanceAuthorizationTypePersonal ComputeInstanceAuthorizationType = "personal"
)
// PossibleComputeInstanceAuthorizationTypeValues returns an array of possible values for the ComputeInstanceAuthorizationType const type.
func PossibleComputeInstanceAuthorizationTypeValues() []ComputeInstanceAuthorizationType {
return []ComputeInstanceAuthorizationType{ComputeInstanceAuthorizationTypePersonal}
}
// ComputeInstanceState enumerates the values for compute instance state.
type ComputeInstanceState string
const (
// ComputeInstanceStateCreateFailed ...
ComputeInstanceStateCreateFailed ComputeInstanceState = "CreateFailed"
// ComputeInstanceStateCreating ...
ComputeInstanceStateCreating ComputeInstanceState = "Creating"
// ComputeInstanceStateDeleting ...
ComputeInstanceStateDeleting ComputeInstanceState = "Deleting"
// ComputeInstanceStateJobRunning ...
ComputeInstanceStateJobRunning ComputeInstanceState = "JobRunning"
// ComputeInstanceStateRestarting ...
ComputeInstanceStateRestarting ComputeInstanceState = "Restarting"
// ComputeInstanceStateRunning ...
ComputeInstanceStateRunning ComputeInstanceState = "Running"
// ComputeInstanceStateSettingUp ...
ComputeInstanceStateSettingUp ComputeInstanceState = "SettingUp"
// ComputeInstanceStateSetupFailed ...
ComputeInstanceStateSetupFailed ComputeInstanceState = "SetupFailed"
// ComputeInstanceStateStarting ...
ComputeInstanceStateStarting ComputeInstanceState = "Starting"
// ComputeInstanceStateStopped ...
ComputeInstanceStateStopped ComputeInstanceState = "Stopped"
// ComputeInstanceStateStopping ...
ComputeInstanceStateStopping ComputeInstanceState = "Stopping"
// ComputeInstanceStateUnknown ...
ComputeInstanceStateUnknown ComputeInstanceState = "Unknown"
// ComputeInstanceStateUnusable ...
ComputeInstanceStateUnusable ComputeInstanceState = "Unusable"
// ComputeInstanceStateUserSettingUp ...
ComputeInstanceStateUserSettingUp ComputeInstanceState = "UserSettingUp"
// ComputeInstanceStateUserSetupFailed ...
ComputeInstanceStateUserSetupFailed ComputeInstanceState = "UserSetupFailed"
)
// PossibleComputeInstanceStateValues returns an array of possible values for the ComputeInstanceState const type.
func PossibleComputeInstanceStateValues() []ComputeInstanceState {
return []ComputeInstanceState{ComputeInstanceStateCreateFailed, ComputeInstanceStateCreating, ComputeInstanceStateDeleting, ComputeInstanceStateJobRunning, ComputeInstanceStateRestarting, ComputeInstanceStateRunning, ComputeInstanceStateSettingUp, ComputeInstanceStateSetupFailed, ComputeInstanceStateStarting, ComputeInstanceStateStopped, ComputeInstanceStateStopping, ComputeInstanceStateUnknown, ComputeInstanceStateUnusable, ComputeInstanceStateUserSettingUp, ComputeInstanceStateUserSetupFailed}
}
// ComputeType enumerates the values for compute type.
type ComputeType string
const (
// ComputeTypeAKS ...
ComputeTypeAKS ComputeType = "AKS"
// ComputeTypeAmlCompute ...
ComputeTypeAmlCompute ComputeType = "AmlCompute"
// ComputeTypeComputeInstance ...
ComputeTypeComputeInstance ComputeType = "ComputeInstance"
// ComputeTypeDatabricks ...
ComputeTypeDatabricks ComputeType = "Databricks"
// ComputeTypeDataFactory ...
ComputeTypeDataFactory ComputeType = "DataFactory"
// ComputeTypeDataLakeAnalytics ...
ComputeTypeDataLakeAnalytics ComputeType = "DataLakeAnalytics"
// ComputeTypeHDInsight ...
ComputeTypeHDInsight ComputeType = "HDInsight"
// ComputeTypeSynapseSpark ...
ComputeTypeSynapseSpark ComputeType = "SynapseSpark"
// ComputeTypeVirtualMachine ...
ComputeTypeVirtualMachine ComputeType = "VirtualMachine"
)
// PossibleComputeTypeValues returns an array of possible values for the ComputeType const type.
func PossibleComputeTypeValues() []ComputeType {
return []ComputeType{ComputeTypeAKS, ComputeTypeAmlCompute, ComputeTypeComputeInstance, ComputeTypeDatabricks, ComputeTypeDataFactory, ComputeTypeDataLakeAnalytics, ComputeTypeHDInsight, ComputeTypeSynapseSpark, ComputeTypeVirtualMachine}
}
// ComputeTypeBasicCompute enumerates the values for compute type basic compute.
type ComputeTypeBasicCompute string
const (
// ComputeTypeBasicComputeComputeTypeAKS ...
ComputeTypeBasicComputeComputeTypeAKS ComputeTypeBasicCompute = "AKS"
// ComputeTypeBasicComputeComputeTypeAmlCompute ...
ComputeTypeBasicComputeComputeTypeAmlCompute ComputeTypeBasicCompute = "AmlCompute"
// ComputeTypeBasicComputeComputeTypeCompute ...
ComputeTypeBasicComputeComputeTypeCompute ComputeTypeBasicCompute = "Compute"
// ComputeTypeBasicComputeComputeTypeComputeInstance ...
ComputeTypeBasicComputeComputeTypeComputeInstance ComputeTypeBasicCompute = "ComputeInstance"
// ComputeTypeBasicComputeComputeTypeDatabricks ...
ComputeTypeBasicComputeComputeTypeDatabricks ComputeTypeBasicCompute = "Databricks"
// ComputeTypeBasicComputeComputeTypeDataFactory ...
ComputeTypeBasicComputeComputeTypeDataFactory ComputeTypeBasicCompute = "DataFactory"
// ComputeTypeBasicComputeComputeTypeDataLakeAnalytics ...
ComputeTypeBasicComputeComputeTypeDataLakeAnalytics ComputeTypeBasicCompute = "DataLakeAnalytics"
// ComputeTypeBasicComputeComputeTypeHDInsight ...
ComputeTypeBasicComputeComputeTypeHDInsight ComputeTypeBasicCompute = "HDInsight"
// ComputeTypeBasicComputeComputeTypeVirtualMachine ...
ComputeTypeBasicComputeComputeTypeVirtualMachine ComputeTypeBasicCompute = "VirtualMachine"
)
// PossibleComputeTypeBasicComputeValues returns an array of possible values for the ComputeTypeBasicCompute const type.
func PossibleComputeTypeBasicComputeValues() []ComputeTypeBasicCompute {
return []ComputeTypeBasicCompute{ComputeTypeBasicComputeComputeTypeAKS, ComputeTypeBasicComputeComputeTypeAmlCompute, ComputeTypeBasicComputeComputeTypeCompute, ComputeTypeBasicComputeComputeTypeComputeInstance, ComputeTypeBasicComputeComputeTypeDatabricks, ComputeTypeBasicComputeComputeTypeDataFactory, ComputeTypeBasicComputeComputeTypeDataLakeAnalytics, ComputeTypeBasicComputeComputeTypeHDInsight, ComputeTypeBasicComputeComputeTypeVirtualMachine}
}
// ComputeTypeBasicComputeNodesInformation enumerates the values for compute type basic compute nodes
// information.
type ComputeTypeBasicComputeNodesInformation string
const (
// ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute ...
ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute ComputeTypeBasicComputeNodesInformation = "AmlCompute"
// ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation ...
ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation ComputeTypeBasicComputeNodesInformation = "ComputeNodesInformation"
)
// PossibleComputeTypeBasicComputeNodesInformationValues returns an array of possible values for the ComputeTypeBasicComputeNodesInformation const type.
func PossibleComputeTypeBasicComputeNodesInformationValues() []ComputeTypeBasicComputeNodesInformation {
return []ComputeTypeBasicComputeNodesInformation{ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute, ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation}
}
// ComputeTypeBasicComputeSecrets enumerates the values for compute type basic compute secrets.
type ComputeTypeBasicComputeSecrets string
const (
// ComputeTypeBasicComputeSecretsComputeTypeAKS ...
ComputeTypeBasicComputeSecretsComputeTypeAKS ComputeTypeBasicComputeSecrets = "AKS"
// ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets ...
ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets ComputeTypeBasicComputeSecrets = "ComputeSecrets"
// ComputeTypeBasicComputeSecretsComputeTypeDatabricks ...
ComputeTypeBasicComputeSecretsComputeTypeDatabricks ComputeTypeBasicComputeSecrets = "Databricks"
// ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine ...
ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine ComputeTypeBasicComputeSecrets = "VirtualMachine"
)
// PossibleComputeTypeBasicComputeSecretsValues returns an array of possible values for the ComputeTypeBasicComputeSecrets const type.
func PossibleComputeTypeBasicComputeSecretsValues() []ComputeTypeBasicComputeSecrets {
return []ComputeTypeBasicComputeSecrets{ComputeTypeBasicComputeSecretsComputeTypeAKS, ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets, ComputeTypeBasicComputeSecretsComputeTypeDatabricks, ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine}
}
// ComputeTypeBasicCreateServiceRequest enumerates the values for compute type basic create service request.
type ComputeTypeBasicCreateServiceRequest string
const (
// ComputeTypeBasicCreateServiceRequestComputeTypeACI ...
ComputeTypeBasicCreateServiceRequestComputeTypeACI ComputeTypeBasicCreateServiceRequest = "ACI"
// ComputeTypeBasicCreateServiceRequestComputeTypeAKS ...
ComputeTypeBasicCreateServiceRequestComputeTypeAKS ComputeTypeBasicCreateServiceRequest = "AKS"
// ComputeTypeBasicCreateServiceRequestComputeTypeCreateServiceRequest ...
ComputeTypeBasicCreateServiceRequestComputeTypeCreateServiceRequest ComputeTypeBasicCreateServiceRequest = "CreateServiceRequest"
// ComputeTypeBasicCreateServiceRequestComputeTypeCustom ...
ComputeTypeBasicCreateServiceRequestComputeTypeCustom ComputeTypeBasicCreateServiceRequest = "Custom"
)
// PossibleComputeTypeBasicCreateServiceRequestValues returns an array of possible values for the ComputeTypeBasicCreateServiceRequest const type.
func PossibleComputeTypeBasicCreateServiceRequestValues() []ComputeTypeBasicCreateServiceRequest {
return []ComputeTypeBasicCreateServiceRequest{ComputeTypeBasicCreateServiceRequestComputeTypeACI, ComputeTypeBasicCreateServiceRequestComputeTypeAKS, ComputeTypeBasicCreateServiceRequestComputeTypeCreateServiceRequest, ComputeTypeBasicCreateServiceRequestComputeTypeCustom}
}
// ComputeTypeBasicServiceResponseBase enumerates the values for compute type basic service response base.
type ComputeTypeBasicServiceResponseBase string
const (
// ComputeTypeBasicServiceResponseBaseComputeTypeACI ...
ComputeTypeBasicServiceResponseBaseComputeTypeACI ComputeTypeBasicServiceResponseBase = "ACI"
// ComputeTypeBasicServiceResponseBaseComputeTypeAKS ...
ComputeTypeBasicServiceResponseBaseComputeTypeAKS ComputeTypeBasicServiceResponseBase = "AKS"
// ComputeTypeBasicServiceResponseBaseComputeTypeCustom ...
ComputeTypeBasicServiceResponseBaseComputeTypeCustom ComputeTypeBasicServiceResponseBase = "Custom"
// ComputeTypeBasicServiceResponseBaseComputeTypeServiceResponseBase ...
ComputeTypeBasicServiceResponseBaseComputeTypeServiceResponseBase ComputeTypeBasicServiceResponseBase = "ServiceResponseBase"
)
// PossibleComputeTypeBasicServiceResponseBaseValues returns an array of possible values for the ComputeTypeBasicServiceResponseBase const type.
func PossibleComputeTypeBasicServiceResponseBaseValues() []ComputeTypeBasicServiceResponseBase {
return []ComputeTypeBasicServiceResponseBase{ComputeTypeBasicServiceResponseBaseComputeTypeACI, ComputeTypeBasicServiceResponseBaseComputeTypeAKS, ComputeTypeBasicServiceResponseBaseComputeTypeCustom, ComputeTypeBasicServiceResponseBaseComputeTypeServiceResponseBase}
}
// DeploymentType enumerates the values for deployment type.
type DeploymentType string
const (
// DeploymentTypeBatch ...
DeploymentTypeBatch DeploymentType = "Batch"
// DeploymentTypeGRPCRealtimeEndpoint ...
DeploymentTypeGRPCRealtimeEndpoint DeploymentType = "GRPCRealtimeEndpoint"
// DeploymentTypeHTTPRealtimeEndpoint ...
DeploymentTypeHTTPRealtimeEndpoint DeploymentType = "HttpRealtimeEndpoint"
)
// PossibleDeploymentTypeValues returns an array of possible values for the DeploymentType const type.
func PossibleDeploymentTypeValues() []DeploymentType {
return []DeploymentType{DeploymentTypeBatch, DeploymentTypeGRPCRealtimeEndpoint, DeploymentTypeHTTPRealtimeEndpoint}
}
// EncryptionStatus enumerates the values for encryption status.
type EncryptionStatus string
const (
// EncryptionStatusDisabled ...
EncryptionStatusDisabled EncryptionStatus = "Disabled"
// EncryptionStatusEnabled ...
EncryptionStatusEnabled EncryptionStatus = "Enabled"
)
// PossibleEncryptionStatusValues returns an array of possible values for the EncryptionStatus const type.
func PossibleEncryptionStatusValues() []EncryptionStatus {
return []EncryptionStatus{EncryptionStatusDisabled, EncryptionStatusEnabled}
}
// IdentityType enumerates the values for identity type.
type IdentityType string
const (
// IdentityTypeApplication ...
IdentityTypeApplication IdentityType = "Application"
// IdentityTypeKey ...
IdentityTypeKey IdentityType = "Key"
// IdentityTypeManagedIdentity ...
IdentityTypeManagedIdentity IdentityType = "ManagedIdentity"
// IdentityTypeUser ...
IdentityTypeUser IdentityType = "User"
)
// PossibleIdentityTypeValues returns an array of possible values for the IdentityType const type.
func PossibleIdentityTypeValues() []IdentityType {
return []IdentityType{IdentityTypeApplication, IdentityTypeKey, IdentityTypeManagedIdentity, IdentityTypeUser}
}
// LoadBalancerType enumerates the values for load balancer type.
type LoadBalancerType string
const (
// LoadBalancerTypeInternalLoadBalancer ...
LoadBalancerTypeInternalLoadBalancer LoadBalancerType = "InternalLoadBalancer"
// LoadBalancerTypePublicIP ...
LoadBalancerTypePublicIP LoadBalancerType = "PublicIp"
)
// PossibleLoadBalancerTypeValues returns an array of possible values for the LoadBalancerType const type.
func PossibleLoadBalancerTypeValues() []LoadBalancerType {
return []LoadBalancerType{LoadBalancerTypeInternalLoadBalancer, LoadBalancerTypePublicIP}
}
// NodeState enumerates the values for node state.
type NodeState string
const (
// NodeStateIdle ...
NodeStateIdle NodeState = "idle"
// NodeStateLeaving ...
NodeStateLeaving NodeState = "leaving"
// NodeStatePreempted ...
NodeStatePreempted NodeState = "preempted"
// NodeStatePreparing ...
NodeStatePreparing NodeState = "preparing"
// NodeStateRunning ...
NodeStateRunning NodeState = "running"
// NodeStateUnusable ...
NodeStateUnusable NodeState = "unusable"
)
// PossibleNodeStateValues returns an array of possible values for the NodeState const type.
func PossibleNodeStateValues() []NodeState {
return []NodeState{NodeStateIdle, NodeStateLeaving, NodeStatePreempted, NodeStatePreparing, NodeStateRunning, NodeStateUnusable}
}
// OperationName enumerates the values for operation name.
type OperationName string
const (
// OperationNameCreate ...
OperationNameCreate OperationName = "Create"
// OperationNameDelete ...
OperationNameDelete OperationName = "Delete"
// OperationNameReimage ...
OperationNameReimage OperationName = "Reimage"
// OperationNameRestart ...
OperationNameRestart OperationName = "Restart"
// OperationNameStart ...
OperationNameStart OperationName = "Start"
// OperationNameStop ...
OperationNameStop OperationName = "Stop"
)
// PossibleOperationNameValues returns an array of possible values for the OperationName const type.
func PossibleOperationNameValues() []OperationName {
return []OperationName{OperationNameCreate, OperationNameDelete, OperationNameReimage, OperationNameRestart, OperationNameStart, OperationNameStop}
}
// OperationStatus enumerates the values for operation status.
type OperationStatus string
const (
// OperationStatusCreateFailed ...
OperationStatusCreateFailed OperationStatus = "CreateFailed"
// OperationStatusDeleteFailed ...
OperationStatusDeleteFailed OperationStatus = "DeleteFailed"
// OperationStatusInProgress ...
OperationStatusInProgress OperationStatus = "InProgress"
// OperationStatusReimageFailed ...
OperationStatusReimageFailed OperationStatus = "ReimageFailed"
// OperationStatusRestartFailed ...
OperationStatusRestartFailed OperationStatus = "RestartFailed"
// OperationStatusStartFailed ...
OperationStatusStartFailed OperationStatus = "StartFailed"
// OperationStatusStopFailed ...
OperationStatusStopFailed OperationStatus = "StopFailed"
// OperationStatusSucceeded ...
OperationStatusSucceeded OperationStatus = "Succeeded"
)
// PossibleOperationStatusValues returns an array of possible values for the OperationStatus const type.
func PossibleOperationStatusValues() []OperationStatus {
return []OperationStatus{OperationStatusCreateFailed, OperationStatusDeleteFailed, OperationStatusInProgress, OperationStatusReimageFailed, OperationStatusRestartFailed, OperationStatusStartFailed, OperationStatusStopFailed, OperationStatusSucceeded}
}
// OrderString enumerates the values for order string.
type OrderString string
const (
// OrderStringCreatedAtAsc ...
OrderStringCreatedAtAsc OrderString = "CreatedAtAsc"
// OrderStringCreatedAtDesc ...
OrderStringCreatedAtDesc OrderString = "CreatedAtDesc"
// OrderStringUpdatedAtAsc ...
OrderStringUpdatedAtAsc OrderString = "UpdatedAtAsc"
// OrderStringUpdatedAtDesc ...
OrderStringUpdatedAtDesc OrderString = "UpdatedAtDesc"
)
// PossibleOrderStringValues returns an array of possible values for the OrderString const type.
func PossibleOrderStringValues() []OrderString {
return []OrderString{OrderStringCreatedAtAsc, OrderStringCreatedAtDesc, OrderStringUpdatedAtAsc, OrderStringUpdatedAtDesc}
}
// OsType enumerates the values for os type.
type OsType string
const (
// OsTypeLinux ...
OsTypeLinux OsType = "Linux"
// OsTypeWindows ...
OsTypeWindows OsType = "Windows"
)
// PossibleOsTypeValues returns an array of possible values for the OsType const type.
func PossibleOsTypeValues() []OsType {
return []OsType{OsTypeLinux, OsTypeWindows}
}
// PrivateEndpointConnectionProvisioningState enumerates the values for private endpoint connection
// provisioning state.
type PrivateEndpointConnectionProvisioningState string
const (
// PrivateEndpointConnectionProvisioningStateCreating ...
PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating"
// PrivateEndpointConnectionProvisioningStateDeleting ...
PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting"
// PrivateEndpointConnectionProvisioningStateFailed ...
PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed"
// PrivateEndpointConnectionProvisioningStateSucceeded ...
PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded"
)
// PossiblePrivateEndpointConnectionProvisioningStateValues returns an array of possible values for the PrivateEndpointConnectionProvisioningState const type.
func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState {
return []PrivateEndpointConnectionProvisioningState{PrivateEndpointConnectionProvisioningStateCreating, PrivateEndpointConnectionProvisioningStateDeleting, PrivateEndpointConnectionProvisioningStateFailed, PrivateEndpointConnectionProvisioningStateSucceeded}
}
// PrivateEndpointServiceConnectionStatus enumerates the values for private endpoint service connection status.
type PrivateEndpointServiceConnectionStatus string
const (
// PrivateEndpointServiceConnectionStatusApproved ...
PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved"
// PrivateEndpointServiceConnectionStatusDisconnected ...
PrivateEndpointServiceConnectionStatusDisconnected PrivateEndpointServiceConnectionStatus = "Disconnected"
// PrivateEndpointServiceConnectionStatusPending ...
PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending"
// PrivateEndpointServiceConnectionStatusRejected ...
PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected"
// PrivateEndpointServiceConnectionStatusTimeout ...
PrivateEndpointServiceConnectionStatusTimeout PrivateEndpointServiceConnectionStatus = "Timeout"
)
// PossiblePrivateEndpointServiceConnectionStatusValues returns an array of possible values for the PrivateEndpointServiceConnectionStatus const type.
func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus {
return []PrivateEndpointServiceConnectionStatus{PrivateEndpointServiceConnectionStatusApproved, PrivateEndpointServiceConnectionStatusDisconnected, PrivateEndpointServiceConnectionStatusPending, PrivateEndpointServiceConnectionStatusRejected, PrivateEndpointServiceConnectionStatusTimeout}
}
// ProvisioningState enumerates the values for provisioning state.
type ProvisioningState string
const (
// ProvisioningStateCanceled ...
ProvisioningStateCanceled ProvisioningState = "Canceled"
// ProvisioningStateCreating ...
ProvisioningStateCreating ProvisioningState = "Creating"
// ProvisioningStateDeleting ...
ProvisioningStateDeleting ProvisioningState = "Deleting"
// ProvisioningStateFailed ...
ProvisioningStateFailed ProvisioningState = "Failed"
// ProvisioningStateSucceeded ...
ProvisioningStateSucceeded ProvisioningState = "Succeeded"
// ProvisioningStateUnknown ...
ProvisioningStateUnknown ProvisioningState = "Unknown"
// ProvisioningStateUpdating ...
ProvisioningStateUpdating ProvisioningState = "Updating"
)
// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type.
func PossibleProvisioningStateValues() []ProvisioningState {
return []ProvisioningState{ProvisioningStateCanceled, ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateSucceeded, ProvisioningStateUnknown, ProvisioningStateUpdating}
}
// QuotaUnit enumerates the values for quota unit.
type QuotaUnit string
const (
// QuotaUnitCount ...
QuotaUnitCount QuotaUnit = "Count"
)
// PossibleQuotaUnitValues returns an array of possible values for the QuotaUnit const type.
func PossibleQuotaUnitValues() []QuotaUnit {
return []QuotaUnit{QuotaUnitCount}
}
// ReasonCode enumerates the values for reason code.
type ReasonCode string
const (
// ReasonCodeNotAvailableForRegion ...
ReasonCodeNotAvailableForRegion ReasonCode = "NotAvailableForRegion"
// ReasonCodeNotAvailableForSubscription ...
ReasonCodeNotAvailableForSubscription ReasonCode = "NotAvailableForSubscription"
// ReasonCodeNotSpecified ...
ReasonCodeNotSpecified ReasonCode = "NotSpecified"
)
// PossibleReasonCodeValues returns an array of possible values for the ReasonCode const type.
func PossibleReasonCodeValues() []ReasonCode {
return []ReasonCode{ReasonCodeNotAvailableForRegion, ReasonCodeNotAvailableForSubscription, ReasonCodeNotSpecified}
}
// RemoteLoginPortPublicAccess enumerates the values for remote login port public access.
type RemoteLoginPortPublicAccess string
const (
// RemoteLoginPortPublicAccessDisabled ...
RemoteLoginPortPublicAccessDisabled RemoteLoginPortPublicAccess = "Disabled"
// RemoteLoginPortPublicAccessEnabled ...
RemoteLoginPortPublicAccessEnabled RemoteLoginPortPublicAccess = "Enabled"
// RemoteLoginPortPublicAccessNotSpecified ...
RemoteLoginPortPublicAccessNotSpecified RemoteLoginPortPublicAccess = "NotSpecified"
)
// PossibleRemoteLoginPortPublicAccessValues returns an array of possible values for the RemoteLoginPortPublicAccess const type.
func PossibleRemoteLoginPortPublicAccessValues() []RemoteLoginPortPublicAccess {
return []RemoteLoginPortPublicAccess{RemoteLoginPortPublicAccessDisabled, RemoteLoginPortPublicAccessEnabled, RemoteLoginPortPublicAccessNotSpecified}
}
// ResourceIdentityType enumerates the values for resource identity type.
type ResourceIdentityType string
const (
// ResourceIdentityTypeNone ...
ResourceIdentityTypeNone ResourceIdentityType = "None"
// ResourceIdentityTypeSystemAssigned ...
ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned"
// ResourceIdentityTypeSystemAssignedUserAssigned ...
ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned,UserAssigned"
// ResourceIdentityTypeUserAssigned ...
ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned"
)
// PossibleResourceIdentityTypeValues returns an array of possible values for the ResourceIdentityType const type.
func PossibleResourceIdentityTypeValues() []ResourceIdentityType {
return []ResourceIdentityType{ResourceIdentityTypeNone, ResourceIdentityTypeSystemAssigned, ResourceIdentityTypeSystemAssignedUserAssigned, ResourceIdentityTypeUserAssigned}
}
// SSHPublicAccess enumerates the values for ssh public access.
type SSHPublicAccess string
const (
// SSHPublicAccessDisabled ...
SSHPublicAccessDisabled SSHPublicAccess = "Disabled"
// SSHPublicAccessEnabled ...
SSHPublicAccessEnabled SSHPublicAccess = "Enabled"
)
// PossibleSSHPublicAccessValues returns an array of possible values for the SSHPublicAccess const type.
func PossibleSSHPublicAccessValues() []SSHPublicAccess {
return []SSHPublicAccess{SSHPublicAccessDisabled, SSHPublicAccessEnabled}
}
// Status enumerates the values for status.
type Status string
const (
// StatusFailure ...
StatusFailure Status = "Failure"
// StatusInvalidQuotaBelowClusterMinimum ...
StatusInvalidQuotaBelowClusterMinimum Status = "InvalidQuotaBelowClusterMinimum"
// StatusInvalidQuotaExceedsSubscriptionLimit ...
StatusInvalidQuotaExceedsSubscriptionLimit Status = "InvalidQuotaExceedsSubscriptionLimit"
// StatusInvalidVMFamilyName ...
StatusInvalidVMFamilyName Status = "InvalidVMFamilyName"
// StatusOperationNotEnabledForRegion ...
StatusOperationNotEnabledForRegion Status = "OperationNotEnabledForRegion"
// StatusOperationNotSupportedForSku ...
StatusOperationNotSupportedForSku Status = "OperationNotSupportedForSku"
// StatusSuccess ...
StatusSuccess Status = "Success"
// StatusUndefined ...
StatusUndefined Status = "Undefined"
)
// PossibleStatusValues returns an array of possible values for the Status const type.
func PossibleStatusValues() []Status {
return []Status{StatusFailure, StatusInvalidQuotaBelowClusterMinimum, StatusInvalidQuotaExceedsSubscriptionLimit, StatusInvalidVMFamilyName, StatusOperationNotEnabledForRegion, StatusOperationNotSupportedForSku, StatusSuccess, StatusUndefined}
}
// Status1 enumerates the values for status 1.
type Status1 string
const (
// Status1Auto ...
Status1Auto Status1 = "Auto"
// Status1Disabled ...
Status1Disabled Status1 = "Disabled"
// Status1Enabled ...
Status1Enabled Status1 = "Enabled"
)
// PossibleStatus1Values returns an array of possible values for the Status1 const type.
func PossibleStatus1Values() []Status1 {
return []Status1{Status1Auto, Status1Disabled, Status1Enabled}
}
// UnderlyingResourceAction enumerates the values for underlying resource action.
type UnderlyingResourceAction string
const (
// UnderlyingResourceActionDelete ...
UnderlyingResourceActionDelete UnderlyingResourceAction = "Delete"
// UnderlyingResourceActionDetach ...
UnderlyingResourceActionDetach UnderlyingResourceAction = "Detach"
)
// PossibleUnderlyingResourceActionValues returns an array of possible values for the UnderlyingResourceAction const type.
func PossibleUnderlyingResourceActionValues() []UnderlyingResourceAction {
return []UnderlyingResourceAction{UnderlyingResourceActionDelete, UnderlyingResourceActionDetach}
}
// UsageUnit enumerates the values for usage unit.
type UsageUnit string
const (
// UsageUnitCount ...
UsageUnitCount UsageUnit = "Count"
)
// PossibleUsageUnitValues returns an array of possible values for the UsageUnit const type.
func PossibleUsageUnitValues() []UsageUnit {
return []UsageUnit{UsageUnitCount}
}
// ValueFormat enumerates the values for value format.
type ValueFormat string
const (
// ValueFormatJSON ...
ValueFormatJSON ValueFormat = "JSON"
)
// PossibleValueFormatValues returns an array of possible values for the ValueFormat const type.
func PossibleValueFormatValues() []ValueFormat {
return []ValueFormat{ValueFormatJSON}
}
// VariantType enumerates the values for variant type.
type VariantType string
const (
// VariantTypeControl ...
VariantTypeControl VariantType = "Control"
// VariantTypeTreatment ...
VariantTypeTreatment VariantType = "Treatment"
)
// PossibleVariantTypeValues returns an array of possible values for the VariantType const type.
func PossibleVariantTypeValues() []VariantType {
return []VariantType{VariantTypeControl, VariantTypeTreatment}
}
// VMPriceOSType enumerates the values for vm price os type.
type VMPriceOSType string
const (
// VMPriceOSTypeLinux ...
VMPriceOSTypeLinux VMPriceOSType = "Linux"
// VMPriceOSTypeWindows ...
VMPriceOSTypeWindows VMPriceOSType = "Windows"
)
// PossibleVMPriceOSTypeValues returns an array of possible values for the VMPriceOSType const type.
func PossibleVMPriceOSTypeValues() []VMPriceOSType {
return []VMPriceOSType{VMPriceOSTypeLinux, VMPriceOSTypeWindows}
}
// VMPriority enumerates the values for vm priority.
type VMPriority string
const (
// VMPriorityDedicated ...
VMPriorityDedicated VMPriority = "Dedicated"
// VMPriorityLowPriority ...
VMPriorityLowPriority VMPriority = "LowPriority"
)
// PossibleVMPriorityValues returns an array of possible values for the VMPriority const type.
func PossibleVMPriorityValues() []VMPriority {
return []VMPriority{VMPriorityDedicated, VMPriorityLowPriority}
}
// VMTier enumerates the values for vm tier.
type VMTier string
const (
// VMTierLowPriority ...
VMTierLowPriority VMTier = "LowPriority"
// VMTierSpot ...
VMTierSpot VMTier = "Spot"
// VMTierStandard ...
VMTierStandard VMTier = "Standard"
)
// PossibleVMTierValues returns an array of possible values for the VMTier const type.
func PossibleVMTierValues() []VMTier {
return []VMTier{VMTierLowPriority, VMTierSpot, VMTierStandard}
}
// WebServiceState enumerates the values for web service state.
type WebServiceState string
const (
// WebServiceStateFailed ...
WebServiceStateFailed WebServiceState = "Failed"
// WebServiceStateHealthy ...
WebServiceStateHealthy WebServiceState = "Healthy"
// WebServiceStateTransitioning ...
WebServiceStateTransitioning WebServiceState = "Transitioning"
// WebServiceStateUnhealthy ...
WebServiceStateUnhealthy WebServiceState = "Unhealthy"
// WebServiceStateUnschedulable ...
WebServiceStateUnschedulable WebServiceState = "Unschedulable"
)
// PossibleWebServiceStateValues returns an array of possible values for the WebServiceState const type.
func PossibleWebServiceStateValues() []WebServiceState {
return []WebServiceState{WebServiceStateFailed, WebServiceStateHealthy, WebServiceStateTransitioning, WebServiceStateUnhealthy, WebServiceStateUnschedulable}
}
| Java |
#include "utfgrid_encode.h"
#include <unordered_map>
#include <glog/logging.h>
#include <jsoncpp/json/value.h>
#include <mapnik/unicode.hpp>
struct value_to_json_visitor {
Json::Value operator() (const mapnik::value_null& val) {return Json::Value();}
Json::Value operator() (const mapnik::value_bool& val) {return Json::Value(val);}
Json::Value operator() (const mapnik::value_integer& val) {return Json::Value(static_cast<uint>(val));}
Json::Value operator() (const mapnik::value_double& val) {return Json::Value(val);}
Json::Value operator() (const mapnik::value_unicode_string& val) {
std::string utf8_str;
mapnik::to_utf8(val, utf8_str);
return Json::Value(utf8_str);
}
};
std::string encode_utfgrid(const mapnik::grid_view& utfgrid, uint size) {
Json::Value root(Json::objectValue);
Json::Value& jgrid = root["grid"];
jgrid = Json::Value(Json::arrayValue);
using lookup_type = mapnik::grid::lookup_type;
using value_type = mapnik::grid::value_type;
using feature_type = mapnik::grid::feature_type;
using keys_type = std::unordered_map<lookup_type, value_type>;
std::vector<lookup_type> key_order;
keys_type keys;
const mapnik::grid::feature_key_type& feature_keys = utfgrid.get_feature_keys();
std::uint16_t codepoint = 32;
for (uint y = 0; y < utfgrid.height(); y += size) {
std::string line;
const value_type* row = utfgrid.get_row(y);
for (uint x = 0; x < utfgrid.width(); x += size) {
value_type feature_id = row[x];
auto feature_itr = feature_keys.find(feature_id);
lookup_type val;
if (feature_itr == feature_keys.end()) {
feature_id = mapnik::grid::base_mask;
} else {
val = feature_itr->second;
}
auto key_iter = keys.find(val);
if (key_iter == keys.end()) {
// Create a new entry for this key. Skip the codepoints that
// can't be encoded directly in JSON.
if (codepoint == 34) ++codepoint; // Skip "
else if (codepoint == 92) ++codepoint; // Skip backslash
if (feature_id == mapnik::grid::base_mask) {
keys[""] = codepoint;
key_order.push_back("");
} else {
keys[val] = codepoint;
key_order.push_back(val);
}
line.append(reinterpret_cast<char*>(&codepoint), sizeof(codepoint));
++codepoint;
} else {
line.append(reinterpret_cast<char*>(&key_iter->second), sizeof(key_iter->second));
}
}
jgrid.append(Json::Value(line));
}
Json::Value& jkeys = root["keys"];
jkeys = Json::Value(Json::arrayValue);
for (const auto& key_id : key_order) {
jkeys.append(key_id);
}
Json::Value& jdata = root["data"];
const feature_type& g_features = utfgrid.get_grid_features();
const std::set<std::string>& attributes = utfgrid.get_fields();
feature_type::const_iterator feat_end = g_features.end();
for (const std::string& key_item : key_order)
{
if (key_item.empty()) {
continue;
}
feature_type::const_iterator feat_itr = g_features.find(key_item);
if (feat_itr == feat_end) {
continue;
}
bool found = false;
Json::Value jfeature(Json::objectValue);
mapnik::feature_ptr feature = feat_itr->second;
for (const std::string& attr : attributes) {
value_to_json_visitor val_to_json;
if (attr == "__id__") {
jfeature[attr] = static_cast<uint>(feature->id());
} else if (feature->has_key(attr)) {
found = true;
jfeature[attr] = mapnik::util::apply_visitor(val_to_json, feature->get(attr));
}
}
if (found) {
jdata[feat_itr->first] = jfeature;
}
}
return root.toStyledString();
}
| Java |
package me.moodcat.api;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import lombok.Getter;
import me.moodcat.database.embeddables.VAVector;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* A mood represents a vector in the valence-arousal plane which will be attached to song.
*/
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Mood {
// CHECKSTYLE:OFF
ANGRY(new VAVector(-0.6, 0.6), "Angry"),
CALM(new VAVector(0.3, -0.9), "Calm"),
EXCITING(new VAVector(0.4, 0.8), "Exciting"),
HAPPY(new VAVector(0.7, 0.6), "Happy"),
NERVOUS(new VAVector(-0.7, 0.4), "Nervous"),
PLEASING(new VAVector(0.6, 0.3), "Pleasing"),
PEACEFUL(new VAVector(0.5, -0.7), "Peaceful"),
RELAXED(new VAVector(0.6, -0.3), "Relaxed"),
SAD(new VAVector(-0.7, -0.2), "Sad"),
SLEEPY(new VAVector(-0.2, -0.9), "Sleepy");
// CHECKSTYLE:ON
/**
* List of all names that represent moods. Used in {@link #nameRepresentsMood(String)}.
* By storing this once, we save a lot of unnecessary list creations.
*/
private static final List<String> MOOD_NAMES = Arrays.asList(Mood.values()).stream()
.map(moodValue -> moodValue.getName())
.collect(Collectors.toList());
/**
* The vector that represents this mood.
*
* @return The vector of this mood.
*/
@Getter
@JsonIgnore
private final VAVector vector;
/**
* Readable name for the frontend.
*
* @return The readable name of this mood.
*/
@Getter
private final String name;
private Mood(final VAVector vector, final String name) {
this.vector = vector;
this.name = name;
}
/**
* Get the mood that is closest to the given vector.
*
* @param vector
* The vector to determine the mood for.
* @return The Mood that is closest to the vector.
*/
public static Mood closestTo(final VAVector vector) {
double distance = Double.MAX_VALUE;
Mood mood = null;
for (final Mood m : Mood.values()) {
final double moodDistance = m.vector.distance(vector);
if (moodDistance < distance) {
distance = moodDistance;
mood = m;
}
}
return mood;
}
/**
* Get the vector that represents the average of the provided list of moods.
*
* @param moods
* The textual list of moods.
* @return The average vector, or the zero-vector if no moods were found.
*/
public static VAVector createTargetVector(final List<String> moods) {
final List<VAVector> actualMoods = moods.stream()
.filter(Mood::nameRepresentsMood)
.map(mood -> Mood.valueOf(mood.toUpperCase(Locale.ROOT)))
.map(mood -> mood.getVector())
.collect(Collectors.toList());
return VAVector.average(actualMoods);
}
private static boolean nameRepresentsMood(final String mood) {
return MOOD_NAMES.contains(mood);
}
}
| Java |
<!-- CONTAINER BODY -->
<div class="panel-group" >
<div class="panel panel-default" >
<div class="panel-body">
<h4>Filmovi</h4>
<!-- Film List -->
<hr/>
<?php foreach($list as $row): ?>
<div class="row text-left">
<div class="col-sm-4 col-fix-140">
<?PHP
$id = $row['IDFilm'];
$path = $row['Poster'];
$link = site_url("index/film/$id");
echo "<a href="."$link"."><img src='"."$path"."' alt='Image' style='height:200px'></a>";
?>
</div>
<div class="col-sm-8">
<?php
$naslov = $row['Naziv'];
echo "<b>$naslov</b>";
?>
<table class="opis">
<tr>
<td><i>Ocena</i></td>
<td>
<?php
$ocena = $row['Ocena'];
echo "<div>";
for($k=0; $k<10; $k++){
if($k < $ocena)
echo "<span class='glyphicon glyphicon-star positiv-rate'></span>";
else
echo "<span class='glyphicon glyphicon-star negative-rate'></span>";
}
echo "</div>";
?>
</td>
</tr>
<?php
$original = $row['OriginalNaziv'];
echo "<tr>";
echo "<td><i>Originalni naslov</i></td>";
echo "<td><b>$original</b></td>";
echo "</tr>";
$datum = $row['PocetakPrikazivanja'];
echo "<tr>";
echo "<td><i>Pocetak prikazivanja</i></td>";
echo "<td><b>$datum</b></td>";
echo "</tr>";
$duzina = $row['Duzina'];
echo "<tr>";
echo "<td><i>Duzina trajanja</i></td>";
echo "<td><b>$duzina min</b></td>";
echo "</tr>";
$zanr = $row['Zanr'];
echo "<tr>";
echo "<td><i>Zanr</i></td>";
echo "<td><b>$zanr</b></td>";
echo "</tr>";
$reziser = $row['Reziser'];
echo "<tr>";
echo "<td><i>Reziser</i></td>";
echo "<td><b>$reziser</b></td>";
echo "</tr>";
$poreklo = $row['Poreklo'];
echo "<tr>";
echo "<td><i>Drzava</i></td>";
echo "<td><b>$poreklo</b></td>";
echo "</tr>";
?>
</table>
</div>
</div>
<hr/>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
| Java |
<?php
$lang = array(
'addons' => 'Add-ons',
'accessories' => 'Accessories',
'modules' => 'Modules',
'extensions' => 'Extensions',
'plugins' => 'Plugins',
'accessory' => 'Accessory',
'module' => 'Module',
'extension' => 'Extension',
'rte_tool' => 'Rich Text Editor Tool',
'addons_accessories' => 'Accessories',
'addons_modules' => 'Modules',
'addons_plugins' => 'Plugins',
'addons_extensions' => 'Extensions',
'addons_fieldtypes' => 'Fieldtypes',
'accessory_name' => 'Accessory Name',
'fieldtype_name' => 'Fieldtype Name',
'install' => 'Install',
'uninstall' => 'Uninstall',
'installed' => 'Installed',
'not_installed' => 'Not Installed',
'uninstalled' => 'Uninstalled',
'remove' => 'Remove',
'preferences_updated' => 'Preferences Updated',
'extension_enabled' => 'Extension Enabled',
'extension_disabled' => 'Extension Disabled',
'extensions_enabled' => 'Extensions Enabled',
'extensions_disabled' => 'Extensions Disabled',
'delete_fieldtype_confirm' => 'Are you sure you want to remove this fieldtype?',
'delete_fieldtype' => 'Remove Fieldtype',
'data_will_be_lost' => 'All data associated with this fieldtype, including all associated channel data, will be permanently deleted!',
'global_settings_saved' => 'Settings Saved',
'package_settings' => 'Package Settings',
'component' => 'Component',
'current_status' => 'Current Status',
'required_by' => 'Required by:',
'available_to_member_groups' => 'Available to Member Groups',
'specific_page' => 'Specific Page?',
'description' => 'Description',
'version' => 'Version',
'status' => 'Status',
'fieldtype' => 'Fieldtype',
'edit_accessory_preferences' => 'Edit Accessory Preferences',
'member_group_assignment' => 'Assigned Member Groups',
'page_assignment' => 'Assigned Pages',
'none' => 'None',
'and_more' => 'and %x more...',
'plugins_not_available' => 'Plugin Feed Disabled in Beta Version.',
'no_extension_id' => 'No Extension Specified',
// IGNORE
''=>'');
/* End of file addons_lang.php */
/* Location: ./system/expressionengine/language/english/addons_lang.php */ | Java |
# ux - Micro Xylph
ux は軽量でシンプルな動作を目標としたソフトウェアシンセサイザです。C# で作られており、Mono 上でも動作します。
## 概要
ux は [Xylph](http://www.johokagekkan.go.jp/2011/u-20/xylph.html) (シルフ) の後継として開発されています。Xylph の開発で得られた最低限必要な機能を絞り、なおかつ Xylph よりも軽快に動作するよう設計されています。C# で記述しつつ、極力高速な動作が目標です。
ux は モノフォニック、複数パート、ポルタメント、ビブラートなどの機能を持ち、音源として矩形波、16 段三角波、ユーザ波形、線形帰還シフトレジスタによる擬似ノイズ、4 オペレータ FM 音源を搭載しています。
現在 Wiki を構築中です。ハンドルの詳細など仕様については Wiki を参照してください: https://github.com/nanase/ux/wiki
## バイナリ
過去のリリース(v0.1.5-dev以前)は [Releases](//github.com/nanase/ux/releases) よりダウンロード可能です。これらは uxPlayer を同梱しており実行可能となっています。
それ以降の最新リリースでは DLL のみの配布とします。uxPlayer のバイナリダウンロードは[こちらのリポジトリ](//github.com/nanase/uxPlayer)をご参照ください。
## TODO in v0.3-dev
* 音源
- [ ] エフェクト(リバーヴ)の追加
* セレクタ(Selector)
- [ ] 新ポリフォニックアルゴリズムの追加
## 姉妹リポジトリ
* [ux++](//github.com/nanase/uxpp) - C++ 実装
* [rbux](//github.com/nanase/rbux) - Ruby 実装
## 備考
* _ux_ と表記して _Micro Xylph (マイクロシルフ)_ と呼称し、プロジェクト内での表記も `ux` です(TeX のようなものです)。
* 性能を重視するためモノフォニック実装(1パート1音)です。ただし uxMidi でのドラムパートのみ 8 音のポリフォニックです。
* この仕様により大抵の MIDI ファイルは正常に再生できません。特に和音を持っている部分は音が抜けます。
* 音色がとにかく_貧弱_です。これは音源定義XMLファイルに充分な定義が無いためです。
- リポジトリ内の以下のファイルが音源定義XMLファイルです。
+ [nanase/ux/uxConsole/ux_preset.xml](//github.com/nanase/ux/blob/v0.2-dev/uxConsole/ux_preset.xml)
+ [nanase/ux/uxPlayer/ux_preset.xml](//github.com/nanase/ux/blob/v0.2-dev/uxPlayer/ux_preset.xml)
- 最新の定義ファイルを Gist に置いています: [gist.github.com/nanase/6068233](//gist.github.com/nanase/6068233)
## 動作確認
* Mono 2.10.8.1 (Linux Mint 14 64 bit)
* .NET Framework 4.5 (Windows 7 64 bit)
* (内部プロジェクトは互換性を理由に .NET Framework 4.0 をターゲットにしています)
## ライセンス
**[MIT ライセンス](//github.com/nanase/ux/blob/v0.2-dev/LICENSE)**
Copyright © 2013-2014 Tomona Nanase
| Java |
---
title: L.esri.Layers.TiledMapLayer
layout: documentation.hbs
---
# {{page.data.title}}
Inherits from [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer)
Access tiles from ArcGIS Online and ArcGIS Server as well as visualize and identify features.
Is you have Feature Services published in ArcGIS Online you can create a static set of tiles using your Feature Service. You can find details about that process in the [ArcGIS Online Help](http://doc.arcgis.com/en/arcgis-online/share-maps/publish-tiles.htm#ESRI_SECTION1_F68FCBD33BD54117B23232D41A762E89)
**Your map service must be published using the Web Mercator Auxiliary Sphere tiling scheme (WKID 102100/3857) and the default scale options used by Google Maps, Bing Maps and [ArcGIS Online](http://resources.arcgis.com/en/help/arcgisonline-content/index.html#//011q00000002000000). Esri Leaflet will not support any other spatial reference for tile layers.**
### Constructor
<table>
<thead>
<tr>
<th>Constructor</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code class="nobr">L.esri.tiledMapLayer({{{param 'Object' 'options'}}})</code></td>
<td>The <code>options</code> parameter can accept the same options as <a href="http://leafletjs.com/reference.html#tilelayer"><code>L.ImageOverlay</code></a>. You also must pass a <code>url</code> key in your <code>options</code>.</td>
</tr>
</tbody>
</table>
### Options
`L.esri.TiledMapLayer` also accepts all [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer-options) options.
| Option | Type | Default | Description |
| --- | --- | --- | --- |
`url` | `String` | | *Required* URL of the [Map Service](http://resources.arcgis.com/en/help/arcgis-rest-api/#/Map_Service/02r3000000w2000000) with a tile cache.
| `correctZoomLevels` | `Boolean` | `true` | If your tiles were generated in web mercator but at non-standard zoom levels this will remap then to the standard zoom levels.
| `zoomOffsetAllowance` | `Number` | `0.1` | If `correctZoomLevels` is enabled this controls the amount of tolerance if the difference at each scale level for remapping tile levels.
| `proxy` | `String` | `false` | URL of an [ArcGIS API for JavaScript proxy](https://developers.arcgis.com/javascript/jshelp/ags_proxy.html) or [ArcGIS Resource Proxy](https://github.com/Esri/resource-proxy) to use for proxying POST requests. |
| `useCors` | `Boolean` | `true` | Dictates if the service should use CORS when making GET requests. |
| `token` | `String` | `null` | Will use this token to authenticate all calls to the service.
### Methods
`L.esri.BasemapLayer` inherits all methods from [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer).
<table>
<thead>
<tr>
<th>Method</th>
<th>Returns</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>authenticate(<String> token)</code></td>
<td><code>this</code></td>
<td>Authenticates this service with a new token and runs any pending requests that required a token.</td>
</tr>
<tr>
<td><code>metadata(<Function> callback, <Object> context)</code></td>
<td><code>this</code></td>
<td>
Requests metadata about this Feature Layer. Callback will be called with `error` and `metadata`.
<pre class="js"><code>featureLayer.metadata(function(error, metadata){
console.log(metadata);
});</code></pre>
</td>
</tr>
<tr>
<td><code>identify()</code></td>
<td><code>this</code></td>
<td>
Returns a new <a href="/api-reference/tasks/identify-features.html"><code>L.esri.services.IdentifyFeatures</code></a> object that can be used to identify features on this layer. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error.
<pre class="js"><code>featureLayer.identify()
.at(latlng, latlngbounds, 5)
.run(function(error, featureCollection){
console.log(featureCollection);
});</code></pre>
</td>
</tr>
</tbody>
</table>
### Events
`L.esri.TiledMapLayer` fires all [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer) events.
### Example
```js
var map = L.map('map').setView([37.7614, -122.3911], 12);
L.esri.tiledMapLayer("http://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer", {
maxZoom: 15
}).addTo(map);
```
| Java |
import time
import multiprocessing
from flask import Flask
app = Flask(__name__)
backProc = None
def testFun():
print('Starting')
while True:
time.sleep(3)
print('looping')
time.sleep(3)
print('3 Seconds Later')
@app.route('/')
def root():
return 'Started a background process with PID ' + str(backProc.pid) + " is running: " + str(backProc.is_alive())
@app.route('/kill')
def kill():
backProc.terminate()
return 'killed: ' + str(backProc.pid)
@app.route('/kill_all')
def kill_all():
proc = multiprocessing.active_children()
for p in proc:
p.terminate()
return 'killed all'
@app.route('/active')
def active():
proc = multiprocessing.active_children()
arr = []
for p in proc:
print(p.pid)
arr.append(p.pid)
return str(arr)
@app.route('/start')
def start():
global backProc
backProc = multiprocessing.Process(target=testFun, args=(), daemon=True)
backProc.start()
return 'started: ' + str(backProc.pid)
if __name__ == '__main__':
app.run()
| Java |
package forscher.nocket.page.gen.ajax;
import gengui.annotations.Eager;
import java.io.Serializable;
public class AjaxTargetUpdateTestInner implements Serializable {
private String feld1;
private String feld2;
public String getEagerFeld1() {
return feld1;
}
@Eager
public void setEagerFeld1(String feld1) {
this.feld1 = feld1;
}
public String getFeld2() {
return feld2;
}
public void setFeld2(String feld2) {
this.feld2 = feld2;
}
}
| Java |
---
layout: single
title: Vue와 Firebase로 모던웹사이트 만들기 43 파이어베이스 함수에서 권한 확인하기
category: vf
tag: [vue,node,express,vuetify,firebase,vscode]
comments: true
sidebar:
nav: "vf"
toc: true
toc_label: "목차"
toc_icon: "list"
---
파이어베이스 함수(functions)에서 토큰을 확인하고 풀어헤친 토큰정보(claims)로 권한에 따른 결과를 보냅니다.
# 영상
{% include video id="x6_Q0GvDu74" provider="youtube" %}
| Java |
'''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class SubusersGetRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.user_nick = None
def getapiname(self):
return 'taobao.subusers.get'
| Java |
var textDivTopIndex = -1;
/**
* Creates a div that contains a textfiled, a plus and a minus button
* @param {String | undefined} textContent string to be added to the given new textField as value
* @returns new div
*/
function createTextDiv( textContent ) {
textDivTopIndex++;
var newTextDiv = document.createElement("DIV");
newTextDiv.className = "inputTextDiv form-group row";
newTextDiv.id = "uriArray"+textDivTopIndex;
newTextDiv.setAttribute("index", textDivTopIndex);
//newTextDiv.innerHTML = "hasznaltauto.hu url:";
//textfield that asks for a car uri and its align-responsible container
var textField = document.createElement("INPUT");
textField.id = uriInputFieldIdPrefix + textDivTopIndex;
textField.type = "url";
textField.name = "carUri"+textDivTopIndex;
textField.className = "form-control";
textField.placeholder = "hasznaltauto.hu url";
textField.value = (textContent === undefined) ? "" : textContent;
//all textfield has it, but there is to be 10 at maximum so the logic overhead would be greater(always the last one should have it) than this efficiency decrease
addEvent( textField, "focus", addOnFocus);
var textFieldAlignerDiv = document.createElement("DIV");
textFieldAlignerDiv.className = "col-xs-10 col-sm-10 col-sm-10";
textFieldAlignerDiv.appendChild(textField);
//add a new input field, or remove current
var inputButtonMinus = document.createElement("BUTTON");
inputButtonMinus.className = "btn btn-default btn-sm col-xs-1 col-sm-1 col-md-1 form-control-static";
inputButtonMinus.type = "button"; //avoid submit, which is default for buttons on forms
inputButtonMinus.innerHTML = "-";
inputButtonMinus.id = "inputButtonMinus" + textDivTopIndex;
newTextDiv.appendChild(textFieldAlignerDiv);
newTextDiv.appendChild(inputButtonMinus);
currentInputUriCount++;
return newTextDiv
}
function addOnFocus(event) {
if ( isLastField(event.target) && currentInputUriCount < 10 ) {
var addedTextDiv = createTextDiv();
formElement.insertBefore(addedTextDiv, sendButtonDiv);
event.stopPropagation();
}
}
function isLastField(field) {
textDivTopIndex = 0;
$(".inputTextDiv").each(function(index) {
textDivTopIndex = ( $(this).attr("index") > textDivTopIndex ) ? $(this).attr("index") : textDivTopIndex;
});
return textDivTopIndex == field.parentElement.parentElement.getAttribute("index") || currentInputUriCount === 1;
} | Java |
#pragma once
#include "ofMain.h"
#include "ofxOsc.h"
#include "VHPtriggerArea.h"
#include "ofxXmlSettings.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
// variables
// Cam
ofVideoGrabber vidGrabber;
ofTexture videoTexture;
ofTexture contrastTexture;
ofTexture backgroundTexture;
unsigned char * background;
unsigned char * pixels;
unsigned char * buffer;
unsigned char * timeBuffer;
int camWidth;
int camHeight;
int totalPixels;
float contrast_e[2];
float contrast_f[2];
float percent;
float colorFactor[3];
// triggerArea
VHPtriggerArea area;
// OSC
ofxOscReceiver receiver;
// info
ofTrueTypeFont font;
// settings
ofxXmlSettings XML;
};
| Java |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace MtgApiManager.Lib.Dto.Set
{
internal class RootSetListDto : IMtgResponse
{
[JsonPropertyName("sets")]
public List<SetDto> Sets { get; set; }
}
} | Java |
---
tags: perl
layout: post
title: "Chris, meet testing"
---
<p>I need to start writing software as if it will be
released to lots of people tomorrow :) Interestingly, the
potential (up to 90% I'd say) release of OpenInteract has
coincided with my first reading of Kent Beck's book <a
href="http://www1.fatbrain.com/asp/bookinfo/bookinfo.asp?theisbn=0201616416">Extreme
Programming Explained</a>. I know, I'm probably a whole 18
months (meaning: eternity) behind the rest of the software
development community, but it's new to me.
<p>Anyway, XP places a lot of emphasis on testing, an area
where my discipline is sorely lacking. The happy coincidence
is that releasing for other people also forces me to write
tests, just so they'll know everything at least nominally
works. This way, I have an excuse to get in the habit of
doing something I should be doing anyway. Happy day!
<p>A nice side benefit of the SPOPS DBI tests is that it
should be easy to find out whether particular DBD drivers
support the necessary <tt>{NAME}</tt> and <tt>{TYPE}</tt> attributes or not.
(I think drivers for most 'modern' databases do.)
<p>Cleaning up the code (which isn't much of the work) and
making it presentable (read: installable by someone other
than me) also means that I get to hack around a bit in the
<tt>Makefile.PL</tt> and <tt>ExtUtils::MakeMaker</tt> land. Eeek! But it's
coming along -- it's done for SPOPS, I just need to figure
out how to get a normal script (to install the packages,
etc.) to run after 'make install'. This is a very powerful
software package, and the perl way is to make easy things
easy, so... where's the easy part? (Personally, I don't
qualify editing a Makefile as easy, but I can be a little
dense sometimes.)
<p>The nutty thing is that you can (apparently) use
E::MM to create PPM files (for ActivePerl users) and for
this you can use the 'PPM_INSTALL_SCRIPT' key to specify a
program to run after the package/module is installed. So
someone recognized this as a good idea to do. Double
eeek!
<p><em>(Originally posted <a href="http://www.advogato.org/person/cwinters/diary.html?start=20">elsewhere</a>)</em></p>
| Java |
# frozen_string_literal: true
RSpec.describe Faraday::Response::RaiseError do
let(:conn) do
Faraday.new do |b|
b.response :raise_error
b.adapter :test do |stub|
stub.get('ok') { [200, { 'Content-Type' => 'text/html' }, '<body></body>'] }
stub.get('bad-request') { [400, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('unauthorized') { [401, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('forbidden') { [403, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('not-found') { [404, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('proxy-error') { [407, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('conflict') { [409, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('unprocessable-entity') { [422, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('4xx') { [499, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('nil-status') { [nil, { 'X-Reason' => 'nil' }, 'fail'] }
stub.get('server-error') { [500, { 'X-Error' => 'bailout' }, 'fail'] }
end
end
end
it 'raises no exception for 200 responses' do
expect { conn.get('ok') }.not_to raise_error
end
it 'raises Faraday::BadRequestError for 400 responses' do
expect { conn.get('bad-request') }.to raise_error(Faraday::BadRequestError) do |ex|
expect(ex.message).to eq('the server responded with status 400')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(400)
expect(ex.response_status).to eq(400)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::UnauthorizedError for 401 responses' do
expect { conn.get('unauthorized') }.to raise_error(Faraday::UnauthorizedError) do |ex|
expect(ex.message).to eq('the server responded with status 401')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(401)
expect(ex.response_status).to eq(401)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ForbiddenError for 403 responses' do
expect { conn.get('forbidden') }.to raise_error(Faraday::ForbiddenError) do |ex|
expect(ex.message).to eq('the server responded with status 403')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(403)
expect(ex.response_status).to eq(403)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ResourceNotFound for 404 responses' do
expect { conn.get('not-found') }.to raise_error(Faraday::ResourceNotFound) do |ex|
expect(ex.message).to eq('the server responded with status 404')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(404)
expect(ex.response_status).to eq(404)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ProxyAuthError for 407 responses' do
expect { conn.get('proxy-error') }.to raise_error(Faraday::ProxyAuthError) do |ex|
expect(ex.message).to eq('407 "Proxy Authentication Required"')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(407)
expect(ex.response_status).to eq(407)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ConflictError for 409 responses' do
expect { conn.get('conflict') }.to raise_error(Faraday::ConflictError) do |ex|
expect(ex.message).to eq('the server responded with status 409')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(409)
expect(ex.response_status).to eq(409)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::UnprocessableEntityError for 422 responses' do
expect { conn.get('unprocessable-entity') }.to raise_error(Faraday::UnprocessableEntityError) do |ex|
expect(ex.message).to eq('the server responded with status 422')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(422)
expect(ex.response_status).to eq(422)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::NilStatusError for nil status in response' do
expect { conn.get('nil-status') }.to raise_error(Faraday::NilStatusError) do |ex|
expect(ex.message).to eq('http status could not be derived from the server response')
expect(ex.response[:headers]['X-Reason']).to eq('nil')
expect(ex.response[:status]).to be_nil
expect(ex.response_status).to be_nil
expect(ex.response_body).to eq('fail')
expect(ex.response_headers['X-Reason']).to eq('nil')
end
end
it 'raises Faraday::ClientError for other 4xx responses' do
expect { conn.get('4xx') }.to raise_error(Faraday::ClientError) do |ex|
expect(ex.message).to eq('the server responded with status 499')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(499)
expect(ex.response_status).to eq(499)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ServerError for 500 responses' do
expect { conn.get('server-error') }.to raise_error(Faraday::ServerError) do |ex|
expect(ex.message).to eq('the server responded with status 500')
expect(ex.response[:headers]['X-Error']).to eq('bailout')
expect(ex.response[:status]).to eq(500)
expect(ex.response_status).to eq(500)
expect(ex.response_body).to eq('fail')
expect(ex.response_headers['X-Error']).to eq('bailout')
end
end
describe 'request info' do
let(:conn) do
Faraday.new do |b|
b.response :raise_error
b.adapter :test do |stub|
stub.post(url, request_body, request_headers) do
[400, { 'X-Reason' => 'because' }, 'keep looking']
end
end
end
end
let(:request_body) { JSON.generate({ 'item' => 'sth' }) }
let(:request_headers) { { 'Authorization' => 'Basic 123' } }
let(:url_path) { 'request' }
let(:query_params) { 'full=true' }
let(:url) { "#{url_path}?#{query_params}" }
subject(:perform_request) do
conn.post url do |req|
req.headers['Authorization'] = 'Basic 123'
req.body = request_body
end
end
it 'returns the request info in the exception' do
expect { perform_request }.to raise_error(Faraday::BadRequestError) do |ex|
expect(ex.response[:request][:method]).to eq(:post)
expect(ex.response[:request][:url]).to eq(URI("http:/#{url}"))
expect(ex.response[:request][:url_path]).to eq("/#{url_path}")
expect(ex.response[:request][:params]).to eq({ 'full' => 'true' })
expect(ex.response[:request][:headers]).to match(a_hash_including(request_headers))
expect(ex.response[:request][:body]).to eq(request_body)
end
end
end
end
| Java |
class CreateBudgetsUsers < ActiveRecord::Migration
def change
create_table :budgets_users do |t|
t.integer :user_id
t.integer :budget_id
t.timestamps
end
end
end
| Java |
package org.anodyneos.xp.tagext;
import javax.servlet.jsp.el.ELException;
import org.anodyneos.xp.XpContext;
import org.anodyneos.xp.XpException;
import org.anodyneos.xp.XpOutput;
import org.xml.sax.SAXException;
/**
* @author jvas
*/
public interface XpTag {
void doTag(XpOutput out) throws XpException, ELException, SAXException;
XpTag getParent();
void setXpBody(XpFragment xpBody);
void setXpContext(XpContext xpc);
void setParent(XpTag parent);
}
| Java |
'use strict';
/**
* Stripe library
*
* @module core/lib/c_l_stripe
* @license MIT
* @copyright 2016 Chris Turnbull <https://github.com/christurnbull>
*/
module.exports = function(app, db, lib) {
return {
/**
* Donate
*/
donate: function(inObj, cb) {
var number, expiry, cvc, currency;
try {
number = parseInt(inObj.body.number);
var exp = inObj.body.expiry.split('/');
expiry = {
month: parseInt(exp[0]),
year: parseInt(exp[1])
};
cvc = parseInt(inObj.body.cvc);
currency = inObj.body.currency.toLowerCase();
} catch (e) {
return cb([{
msg: 'Invalid details.',
desc: 'Payment has not been made'
}], null);
}
// stripe supported zero-decimal currencies
var zeroDecimal = {
BIF: 'Burundian Franc',
CLP: 'Chilean Peso',
DJF: 'Djiboutian Franc',
GNF: 'Guinean Franc',
JPY: 'Japanese Yen',
KMF: 'Comorian Franc',
KRW: 'South Korean Won',
MGA: 'Malagasy Ariary',
PYG: 'Paraguayan Guaraní',
RWF: 'Rwandan Franc',
VND: 'Vietnamese Đồng',
VUV: 'Vanuatu Vatu',
XAF: 'Central African Cfa Franc',
XOF: 'West African Cfa Franc',
XPF: 'Cfp Franc'
};
var amount = inObj.body.amount;
if (!zeroDecimal.hasOwnProperty(currency.toUpperCase())) {
// all other supoprted currencies are decimal
amount = amount * 100;
}
var stripeData = {
amount: amount,
currency: currency.toLowerCase(),
description: 'Donation from ' + inObj.body.name,
source: {
number: number,
exp_month: expiry.month,
exp_year: expiry.year,
cvc: cvc,
object: 'card',
customer: inObj.body.customer,
email: inObj.body.email
}
};
lib.core.stripe.charges.create(stripeData, function(err, charge) {
if (err) {
return cb(err, null);
}
// save to database etc...
return cb(null, [charge]);
});
}
};
};
| Java |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;
namespace MR.AspNetCore.Jobs.Server
{
public class InfiniteRetryProcessorTest
{
[Fact]
public async Task Process_ThrowingProcessingCanceledException_Returns()
{
// Arrange
var services = new ServiceCollection();
services.AddLogging();
var loggerFactory = services.BuildServiceProvider().GetService<ILoggerFactory>();
var inner = new ThrowsProcessingCanceledExceptionProcessor();
var p = new InfiniteRetryProcessor(inner, loggerFactory);
var context = new ProcessingContext();
// Act
await p.ProcessAsync(context);
}
private class ThrowsProcessingCanceledExceptionProcessor : IProcessor
{
public Task ProcessAsync(ProcessingContext context)
{
throw new OperationCanceledException();
}
}
}
}
| Java |
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct _notify_raceboss_cry_msg_request_zocl
{
char wszCryMsg[10][65];
};
END_ATF_NAMESPACE
| Java |
/*
artifact generator: C:\My\wizzi\v5\node_modules\wizzi-js\lib\artifacts\js\module\gen\main.js
primary source IttfDocument: c:\my\wizzi\v5\plugins\wizzi-core\src\ittf\root\legacy.js.ittf
*/
'use strict';
module.exports = require('wizzi-legacy-v4');
| Java |
---
title: "Puppet"
description: "Deregister Sensu clients from the client registry if they no
longer have an associated Puppet node."
version: 1.0
weight: 12
---
**ENTERPRISE: Built-in integrations are available for [Sensu Enterprise][1]
users only.**
# Puppet Integration
- [Overview](#overview)
- [Configuration](#configuration)
- [Example(s)](#examples)
- [Integration Specification](#integration-specification)
- [`puppet` attributes](#puppet-attributes)
- [`ssl` attributes](#ssl-attributes)
## Overview
Deregister Sensu clients from the client registry if they no longer have an
associated [Puppet][2] node. The `puppet` enterprise handler requires access to
a SSL truststore and keystore, containing a valid (and whitelisted) Puppet
certificate, private key, and CA. The local Puppet agent certificate, private
key, and CA can be used.
## Configuration
### Example(s)
The following is an example global configuration for the `puppet` enterprise
handler (integration).
~~~ json
{
"puppet": {
"endpoint": "https://10.0.1.12:8081/pdb/query/v4/nodes/",
"ssl": {
"keystore_file": "/etc/sensu/ssl/puppet/keystore.jks",
"keystore_password": "secret",
"truststore_file": "/etc/sensu/ssl/puppet/truststore.jks",
"truststore_password": "secret"
},
"timeout": 10
}
}
~~~
The Puppet enterprise handler is most commonly used as part of the `keepalive`
set handler. For example:
~~~ json
{
"handlers": {
"keepalive": {
"type": "set",
"handlers": [
"pagerduty",
"puppet"
]
}
}
}
~~~
When querying PuppetDB for a node, by default, Sensu will use the Sensu client's
name for the Puppet node name. Individual Sensu clients can override the name of
their corresponding Puppet node, using specific client definition attributes.
The following is an example client definition, specifying its Puppet node name.
~~~ json
{
"client": {
"name": "i-424242",
"address": "8.8.8.8",
"subscriptions": [
"production",
"webserver"
],
"puppet": {
"node_name": "webserver01.example.com"
}
}
}
~~~
### Integration Specification
_NOTE: the following integration definition attributes may be overwritten by
the corresponding Sensu [client definition `puppet` attributes][3], which are
included in [event data][4]._
#### `puppet` attributes
The following attributes are configured within the `{"puppet": {} }`
[configuration scope][5].
`endpoint`
: description
: The PuppetDB API endpoint (URL). If an API path is not specified,
`/pdb/query/v4/nodes/` will be used.
: required
: true
: type
: String
: example
: ~~~ shell
"endpoint": "https://10.0.1.12:8081/pdb/query/v4/nodes/"
~~~
`ssl`
: description
: A set of attributes that configure SSL for PuppetDB API queries.
: required
: true
: type
: Hash
: example
: ~~~ shell
"ssl": {}
~~~
#### `ssl` attributes
The following attributes are configured within the `{"puppet": { "ssl": {} } }`
[configuration scope][3].
##### EXAMPLE {#ssl-attributes-example}
~~~ json
{
"puppet": {
"endpoint": "https://10.0.1.12:8081/pdb/query/v4/nodes/",
"...": "...",
"ssl": {
"keystore_file": "/etc/sensu/ssl/puppet/keystore.jks",
"keystore_password": "secret",
"truststore_file": "/etc/sensu/ssl/puppet/truststore.jks",
"truststore_password": "secret"
}
}
}
~~~
##### ATTRIBUTES {#ssl-attributes-specification}
`keystore_file`
: description
: The file path for the SSL certificate keystore.
: required
: true
: type
: String
: example
: ~~~ shell
"keystore_file": "/etc/sensu/ssl/puppet/keystore.jks"
~~~
`keystore_password`
: description
: The SSL certificate keystore password.
: required
: true
: type
: String
: example
: ~~~ shell
"keystore_password": "secret"
~~~
`truststore_file`
: description
: The file path for the SSL certificate truststore.
: required
: true
: type
: String
: example
: ~~~ shell
"truststore_file": "/etc/sensu/ssl/puppet/truststore.jks"
~~~
`truststore_password`
: description
: The SSL certificate truststore password.
: required
: true
: type
: String
: example
: ~~~ shell
"truststore_password": "secret"
~~~
[?]: #
[1]: /enterprise
[2]: https://puppet.com?ref=sensu-enterprise
[3]: ../../reference/clients.html#puppet-attributes
[4]: ../../reference/events.html#event-data
[5]: ../../reference/configuration.html#configuration-scopes
| Java |
#!/bin/env node
'use strict';
var winston = require('winston'),
path = require('path'),
mcapi = require('mailchimp-api'),
Parser = require('./lib/parser'),
ApiWrapper = require('./lib/api-wrapper');
var date = new Date();
date = date.toJSON().replace(/(-|:)/g, '.');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, { level: 'silly'});
winston.add(winston.transports.File, {
filename: path.join('./', 'logs', 'sxla' + date + '.log'),
level: 'silly',
timestamp: true
});
winston.info('*********** APPLICATION STARTED ***********');
var apiKey = process.env.MAILCHIMP_SXLA_API_KEY;
var listId = process.env.MAILCHIMP_SXLA_LIST_ID;
winston.debug('apiKey: ', apiKey);
winston.debug('listId: ', listId);
var api = new ApiWrapper(mcapi, apiKey, listId, winston);
var parser = new Parser(winston);
parser.parseCsv(__dirname + '/data/soci14-15.csv', function (data) {
api.batchSubscribe(data);
});
| Java |
+++
hook = "A list of the best podcasts that I'm listening to this year."
published_at = 2016-08-28T01:13:48Z
title = "Podcasts 2016"
+++
After moving to the big city, I've spent a lot more time on foot over the past
few years. I eventually picked up another habit that pairs with walking
perfectly: podcasts.
As of 2016, here are my favorites:
* [Common Sense][common-sense]: Dan Carlin on the American political system.
Dan takes the side of neither party, but comments on them from the outside in
a very informed way. He has the incredible gift to be able to speak for hours
in a way that's hugely information-dense. No co-host required.
* [Hardcore History][hardcore-history]: Dan Carlin's podcast on history, and
maybe _the_ best podcast that's out there right now. Dan's impassioned
approach to the subject makes every episode great. In particular, check on
the series on the fall of the Roman republic and the exploits of Genghis
Khan.
* [Road Work][road-work]: John Roderick (a musician) and Dan Benjamin (a
podcaster) talk about things. I know that doesn't sound very interesting, but
Roderick has a way with words and is one of the world's great story tellers.
* [Waking Up with Sam Harris][waking-up]: Sam Harris is best known for his
atheism, but only because that's his most controversial pursuit. He's a great
thinker in general, and the most articulate person that you'll ever hear.
Topics range from current events, society, or interviews with various
intellectuals, and as you'd expect, a healthy dose of criticism on religious
radicalism.
And some others that deserve mention:
* [8-4 Play][8-4-play]: Focuses on recent developments in gaming, specifically
in Japan. I don't play many video games anymore, but I still find it
fascinating.
* [99% Invisible][99-invisible]: A podcast on architecture and design that
manages to drudge up original material that's as interesting as it is
obscure.
* [The Bike Shed][bike-shed]: Titled with a concept that every programmer will
know well, this one is unsurprisingly about -- software. Episode quality is
variable, but there's occasionally some great content on advanced topics like
Rust and ORM internals.
* [Planet Money][planet-money]: These guys really have a real knack for making
economics interesting. Its major weakness is that it never trackles a subject
in depth.
* [Radiolab][radiolab]: Covers scientific subjects and comes with good
interviews and some great sound editing. It's only downside is that the hosts
have a bad habit of brushing up against the realm of pseudo-science.
* [Roderick on the Line][roderick]: A slight variation of _Road Work_ above,
this one is John Roderick and Merlin Mann talking about things. Recent
episodes have been a little lackluster, but comb through the backlog for some
incredible stories.
* [Song Exploder][song-exploder]: The best edited podcast on the list; breaks
down popular songs and has their composer talk through the thinking and
process that went into their creation. For best results, check the back
catalog for songs that you like.
[8-4-play]: https://overcast.fm/itunes393557569/8-4-play
[99-invisible]:https://overcast.fm/itunes394775318/99-invisible
[bike-shed]: https://overcast.fm/itunes935763119/the-bike-shed
[common-sense]: https://overcast.fm/itunes155974141/common-sense-with-dan-carlin
[hardcore-history]: https://overcast.fm/itunes173001861/dan-carlins-hardcore-history
[planet-money]: https://overcast.fm/itunes290783428/planet-money
[radiolab]: https://overcast.fm/itunes152249110/radiolab
[road-work]: https://overcast.fm/itunes1030602911/road-work
[roderick]: https://overcast.fm/itunes471418144/roderick-on-the-line
[song-exploder]: https://overcast.fm/itunes788236947/song-exploder
[waking-up]: https://overcast.fm/itunes733163012/waking-up-with-sam-harris
| Java |
module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
this.addBowerPackageToProject('jsoneditor');
}
};
| Java |
# Wiper
Wiper allows you to recursively delete specified folders.
Say that you want to delete all 'obj' folders in a certain root folder.
Type in 'obj' as the folder name to delete and select the root folder.
Perform a dry run to list all folders that will be affected.
Hit the delete button and you're done!
| Java |
import AMD from '../../amd/src/amd.e6';
import Core from '../../core/src/core.e6';
import Event from '../../event/src/event.e6';
import Detect from '../../detect/src/detect.e6';
import Module from '../../modules/src/base.es6';
import ModulesApi from '../../modules/src/api.e6';
window.Moff = new Core();
window.Moff.amd = new AMD();
window.Moff.event = new Event();
window.Moff.Module = new Module();
window.Moff.detect = new Detect();
window.Moff.modules = new ModulesApi();
| Java |
<html><body>
<h4>Windows 10 x64 (19042.610)</h4><br>
<h2>_PNP_DEVICE_DELETE_TYPE</h2>
<font face="arial"> QueryRemoveDevice = 0n0<br>
CancelRemoveDevice = 0n1<br>
RemoveDevice = 0n2<br>
SurpriseRemoveDevice = 0n3<br>
EjectDevice = 0n4<br>
RemoveFailedDevice = 0n5<br>
RemoveUnstartedFailedDevice = 0n6<br>
MaxDeviceDeleteType = 0n7<br>
</font></body></html> | Java |
---
archive: tag
layout: archive
permalink: /tag/Simpsons/
tag: Simpsons
title: Archive for Simpsons
---
| Java |
# == Schema Information
#
# Table name: templates
#
# id :integer not null, primary key
# name :string
# image :string
# description :text
# created_at :datetime not null
# updated_at :datetime not null
#
require 'rails_helper'
RSpec.describe Template, type: :model do
describe "relationships" do
it { should have_many(:cards).dependent(:restrict_with_error) }
end
describe "validators" do
it { should validate_presence_of(:name) }
it { should validate_presence_of(:image) }
end
end
| Java |
namespace RapidFTP.Chilkat.Tests.Utilities
{
using System.Diagnostics;
using RapidFTP.Models;
using RapidFTP.Utilities;
using Xunit;
using Xunit.Extensions;
public class UnixPathTest
{
[InlineData("/lv1", 1)]
[InlineData("/lv1/lv2", 2)]
[InlineData("/lv1/lv2/", 2)]
[InlineData("/lv1/lv2/lv3", 3)]
[InlineData("/lv1/lv2/lv3/lv4", 4)]
[InlineData("/lv1/lv2/lv3/lv4/lv5", 5)]
[Theory]
public void GetRelatedDirectories_GivenPath_ShouldSuccess(string path, int length)
{
var relatedDirectories = UnixPath.GetRelatedDirectories(path);
Assert.Equal(length, relatedDirectories.Length);
foreach (var directory in relatedDirectories)
{
Trace.WriteLine(directory);
}
}
[InlineData("/", true)]
[InlineData("/lv1", true)]
[InlineData("/lv1/lv2", true)]
[InlineData("/lv1/lv2/", true)]
[InlineData("/lv1/lv2/lv_3", true)]
[InlineData("/lv1/lv2/lv-3", true)]
[InlineData("lv1", false)]
[InlineData("lv1/lv2", false)]
[InlineData("", false)]
[InlineData("/lv1/*", false)]
[Theory]
public void IsWellFormed(string path, bool expected)
{
var result = UnixPath.IsWellFormed(path, ItemType.Directory);
Assert.Equal(expected, result);
}
}
} | Java |
package org.real2space.neumann.evaris.core.structure;
/**
* Project Neumann
*
* @author RealTwo-Space
* @version 0
*
* created 2016/11/01
* added "extends Ring<F>" 2016/11/9
*/
public interface Field<F> extends Ring<F> {
/*
* Multiply this member by an inverse of "other".
*/
public void divide (F other);
/*
* Returns an inverse of this member.
*/
public F inverse ();
} | Java |
# coding: utf-8
import unittest
from config_reader import ConfigReader
class TestConfigReader(unittest.TestCase):
def setUp(self):
self.config = ConfigReader("""
<root>
<person>
<name>山田</name>
<age>15</age>
</person>
<person>
<name>佐藤</name>
<age>43</age>
</person>
</root>
""")
def test_get_names(self):
self.assertEqual(self.config.get_names(), ['山田', '佐藤'])
def test_get_ages(self):
self.assertEqual(self.config.get_ages(), ['15', '43'])
| Java |
# project/server/tests/test_user.py
import datetime
import unittest
from flask_login import current_user
from base import BaseTestCase
from project.server import bcrypt
from project.server.models import User
from project.server.user.forms import LoginForm
class TestUserBlueprint(BaseTestCase):
def test_correct_login(self):
# Ensure login behaves correctly with correct credentials.
with self.client:
response = self.client.post(
"/login",
data=dict(email="ad@min.com", password="admin_user"),
follow_redirects=True,
)
self.assertIn(b"Welcome", response.data)
self.assertIn(b"Logout", response.data)
self.assertIn(b"Members", response.data)
self.assertTrue(current_user.email == "ad@min.com")
self.assertTrue(current_user.is_active())
self.assertEqual(response.status_code, 200)
def test_logout_behaves_correctly(self):
# Ensure logout behaves correctly - regarding the session.
with self.client:
self.client.post(
"/login",
data=dict(email="ad@min.com", password="admin_user"),
follow_redirects=True,
)
response = self.client.get("/logout", follow_redirects=True)
self.assertIn(b"You were logged out. Bye!", response.data)
self.assertFalse(current_user.is_active)
def test_logout_route_requires_login(self):
# Ensure logout route requres logged in user.
response = self.client.get("/logout", follow_redirects=True)
self.assertIn(b"Please log in to access this page", response.data)
def test_member_route_requires_login(self):
# Ensure member route requres logged in user.
response = self.client.get("/members", follow_redirects=True)
self.assertIn(b"Please log in to access this page", response.data)
def test_validate_success_login_form(self):
# Ensure correct data validates.
form = LoginForm(email="ad@min.com", password="admin_user")
self.assertTrue(form.validate())
def test_validate_invalid_email_format(self):
# Ensure invalid email format throws error.
form = LoginForm(email="unknown", password="example")
self.assertFalse(form.validate())
def test_get_by_id(self):
# Ensure id is correct for the current/logged in user.
with self.client:
self.client.post(
"/login",
data=dict(email="ad@min.com", password="admin_user"),
follow_redirects=True,
)
self.assertTrue(current_user.id == 1)
def test_registered_on_defaults_to_datetime(self):
# Ensure that registered_on is a datetime.
with self.client:
self.client.post(
"/login",
data=dict(email="ad@min.com", password="admin_user"),
follow_redirects=True,
)
user = User.query.filter_by(email="ad@min.com").first()
self.assertIsInstance(user.registered_on, datetime.datetime)
def test_check_password(self):
# Ensure given password is correct after unhashing.
user = User.query.filter_by(email="ad@min.com").first()
self.assertTrue(
bcrypt.check_password_hash(user.password, "admin_user")
)
self.assertFalse(bcrypt.check_password_hash(user.password, "foobar"))
def test_validate_invalid_password(self):
# Ensure user can't login when the pasword is incorrect.
with self.client:
response = self.client.post(
"/login",
data=dict(email="ad@min.com", password="foo_bar"),
follow_redirects=True,
)
self.assertIn(b"Invalid email and/or password.", response.data)
def test_register_route(self):
# Ensure about route behaves correctly.
response = self.client.get("/register", follow_redirects=True)
self.assertIn(b"<h1>Register</h1>\n", response.data)
def test_user_registration(self):
# Ensure registration behaves correctlys.
with self.client:
response = self.client.post(
"/register",
data=dict(
email="test@tester.com",
password="testing",
confirm="testing",
),
follow_redirects=True,
)
self.assertIn(b"Welcome", response.data)
self.assertTrue(current_user.email == "test@tester.com")
self.assertTrue(current_user.is_active())
self.assertEqual(response.status_code, 200)
if __name__ == "__main__":
unittest.main()
| Java |
inside = lambda x, y: 4*x*x+y*y <= 100
def coll(sx, sy, dx, dy):
m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): m = m2
return (sx + dx*m, sy + dy*m)
def norm(x, y):
l = (x*x + y*y)**0.5
return (x/l, y/l)
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
for I in range(999):
sx, sy = coll(sx, sy, dx, dy)
if sy > 0 and abs(sx) <= 0.01:
print(I)
break
mx, my = norm(1, -4*sx/sy)
d = mx*dx + my*dy
dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d
| Java |
# Git Back Control of Your Code
## A Simple and Straightforward Workflow for Working with Git and Github
Becoming a better developer is about finding the process and workflow that works best for you and the rest of the team. I believe that version control is something all developers should use. Specifically, I think that git is a great option.
There can be a bit of a learning curve with version control, but once you start using it, it becomes essential.
If you are looking for a more interactive approach to learning git, then [give Try Git a shot](http://try.github.com/).
*This post is a follow-up to [a presentation I gave](http://www.gristmill.io/workshops/3-git-back-control-of-your-code-learning-how-to-manage-your-code-with-git-github) on using Git and Github. Going through [the slides](http://brettchalupa.github.com/git-presentation/) should give you a quick overview of what was covered. This post is meant to take it one step further for those who could not attend.*
## Why use version control?
The first question you are probably asking yourself is, "Why even use version control? I've got Dropbox! That's my version control." Getouttahere. Dropbox isn't version control. It's hosting for backups with somewhat deep OS integration. It's a good tool, but it's not a tool that should be used for managing your project's code.
Developers should be using version control because:
* Keeps a track-record of all of the changes you have ever made, ever
* Allows for collaboration with other developers without stepping on toes
* Provides a form of back-up by hosting a repository on another server, whether it is on the web or locally
It's essential to programming. Working in an environment without version control is terrifying.
## Why use git?
The next logic question is why use git? What about subversion or mercurial?
Use whatever fits your needs the best. Version control systems, IDEs, and code libraries are tools. They are supposed to make your life easier. Use what you are most comfortable with. Use the tool best for the job. Use whatever it is that will help you become a better developer. It's up to you.
Here are the reasons why I prefer to use git:
1. Github. This may be a strange reason, but Github is a reason why I use git.
2. The strong community and vast amount of resources.
3. The fact that [it is a distributed version control system](http://www.joelonsoftware.com/items/2010/03/17.html).
If git isn't for you or you prefer another type of version control, then that's totally fine.
## Why use Github?
There are a few options for git hosting out on the web. The two most common are probably [GitHub](http://github.com) and [Bitbucket](http://bitbucket.org). The two are very similar in terms of their features (Bitbucket also supports Mercurial, another distributed version control system). The major difference between the two is that Bitbucket allows for free private and public repositories. GitHub only allows for free public repositories. What this means is that if you want to host private projects on GitHub, then you need to pay money. If that's not for you or you can't afford it, then use Bitbucket. Most of this guide applies for use with Bitbucket or GitHub.
That being said, I prefer to use GitHub over Bitbucket because:
* Pull Requests - GitHub simply handles pull requests in a much nicer fashion, allowing people to comment on specific files in a commit or just on the pull request in general.
* The [help section](http://help.github.com) is super useful. It's well written, organized, and more than enough to get anyone going.
* [Gists](http://gist.github.com) - paste snippets of code publically or privately with features like comments and forking.
Moral of the story, try both out and see what works for you.
## Useful Terminal Commands
This guide should really be called *Using git and Github (with the terminal)*. That's the core of this guide - using the terminal. Whether it is msysgit on Windows or Terminal for Unix users, we will be using commands the entire time.
Beginning to use the terminal can be a daunting task. The nice thing is, there is only about a handful of commands you'll use daily. Once you get the hang of those, the workflow starts to make sense.
Here are a few of the most common commands you'll use when working with the terminal.
* `pwd` - print working directory a.k.a. where am I?
* `ls` - list files and directories in current directory a.k.a. what do we have here?
* `cd path/to/location` - change directory
* `touch path/to/file.rb` - create a file
* `mkdir path/to/directory` - create a directory
* `rm path/to/file.rb` - remove a specific file
### Flags
Flags are little extra magical parameters you can pass in with terminal commands. They're pretty useful, and as you explore and research, you will continue to discover more.
* `-a` - show all
* `ls -a` - show all files in the current directory, not hidden and hidden
* `git branch -a` - show all of the local and remote branches for the current git repository
* `-v` - show the current version of anything
* `ruby -v` - display the current version of Ruby installed
* `-h` or `--help` - list the flag options of the command you're running, when in doubt run -h
## Setting up git
[Follow this guide.](http://help.github.com/) That's it. Really. Github's guide on getting started with git on Windows, Mac, or Linux is precise and the best resource out there.
help.github.com will be your best friend while you learn to use git and Github (and even when you continue to use it).
## Adding to the Codebase
To start off, if you haven't already, you need to clone the project:
`git clone git@github.com:projectowner/project-name.git`
After the project is done cloning, change your directory to the project:
`cd project_name`
Once you've changed directories, you're almost ready to code. Next up is to make sure you're on the proper branch. To see what branch you are on, use the following:
`git branch`
If you're on master branch, there's probably a problem. You need to change branches or create a new one. Let's assume you need to create a new one. Please do the following command (where bc is your initials, this makes identifying who is working on what branch much easier):
`git branch bc/branch_name`
If you were to do
`git branch`
again, you'd see your new branch! To switch to that branch, simply do the following:
`git checkout bc/branch_name`
If you're feeling really snazzy, you can create a branch and switch to it at the same time by running:
`git checkout -b bc/branch_name`
Now you're ready to code! Once you're all done (or you think you're done), go ahead and add those changes. First, to see what changes have been made, simply do:
`git status`
You'll see any of the files you've added, changed, or removed. The most basic and quick command to add your changes to a commit is:
`git add .`
This will add of your new files and changes to the commit. To delete files, all you need to do is the following command:
`git rm file.rb`
If you delete your files a different way, you still need to run the command above to make git aware of the changes. If you erase a lot of files at once, here is a helpful command to make git aware of the changes:
`git add -u`
Once you've staged all of your changes to your commit, go ahead and make that commit!
`git commit -m "Your commit message!"`
Wow, great job! You're almost there. Next, all you need to do is push those commits to the remote repository on Github, and you're a git wizard.
`git push origin bc/branch_name`
## Merging Branches
You've created a branch, made some changes, saved those changes, and pushed them to your branch on the repository on Github. Now you think you're done coding your feature and you're ready to merge your branch into the master branch (or development branch depending on your structure). Now just hold your goddamned horses for a minute. Before you merge to master, you need to open a pull request. To do such a thing, navigate to your branch on the project in Github. Above all of the code on the upper-right, you will see a little button that says "Pull Request". Click that bad boy to open a pull request.
Once you've opened a pull request, everyone will be notified via email (if they have that setting on) and a Github notification. What happens next is out of your hands for a little while. At least one other programmer needs to go through your code and make sure it's up to snuff. Make sure it's properly commented, it makes sense, and there is no [code smell](http://en.wikipedia.org/wiki/Code_smell). If there are some problems, expect them to leave some comments where the problems lie. You need to go through the code, make your changes, commit those changes, and push them again.
How you and your team handle pull requests is up to you. In my opinion, it's best practice to have *at least* one other person review your code. Once they give you an _LGPA_ or a _Looks Good, Pull Away!_, you're ready to close & merge the Pull Request. Click the little button at the bottom of the pull request, and you're almost ready to start working on your next feature.
You've got to remember to clean up though. Switch to your development or master branch:
`git checkout master`
Now go ahead and delete your local branch:
`git branch -d bc/branch_name`
Next you've got to delete your branch on Github:
`git push origin :bc/branch_name`
A few last steps and you've merged your first feature into the codebase. You've got to pull from the master branch on Github to get the lastest changes from the Pull Request merge:
`git pull origin master`
Now you're done merging you're branch. You've cleaned up and got your latest changes from the merge. Start the whole process over from the beginning and code away.
*It's worth noting that this is probably a lazy approach to handling merges. [There's a ton of discussion on this topic and the proper ways to do it.](http://longair.net/blog/2009/04/16/git-fetch-and-merge/)*
## Other Useful git Commands
There is a lot more to git than what was covered in this document. As everyone uses tools more and more, there is a hope to continue to learn more about that tool. As I learn more, I will be updating this with other important git commands and concepts.
### Rebase
If you're on the branch `bc/current_working_branch` and you want to make sure you're not going to have merge commits, you'll want to rebase often.
First, run:
`git fetch origin master`
Then, run:
`git rebase origin/master`
This will put your commits on top of the latest `origin/master` commit. This will not update your local master branch, so be advised.
If you want to do an interactive rebase, it's the same process except that you say `git rebase -i origin/master`. I usually do a regular rebase before I do an interactive rebase so I can go ahead and fix any conflicts without the added confusion of an interactive rebase.
### Reset
If you mess up and want to go back a commit (or even more), simply do:
`git reset --hard HEAD~1`
The `HEAD~1` means ONE commit before head. If you wanted to do FOUR commits before the head, simply do `HEAD~4`
Or, you could look at the output of git log, find the commit id of the commit you want to back up to, and then do this:
`git reset --hard <sha1-commit-id>`
If you already pushed it, you will need to do a force push to get rid of it:
`git push origin HEAD --force`
### Stashing Changes
If you're ever working on code and need to store or **stash** your changes for later, there is a command for that. Run the following command to safely stash your changes in current branch away.
`git stash`
When you're ready to have those changes back, you can run:
`git stash pop`
Stashing is useful if two people are working on the same branch at the same time. If person A has made some code changes and person B has as well there may be some conflicts. Person A most likely wants to get the changes person B made, so if person A stashes their current changes and pulls from the branch then pops the stash, person A's changes will be reflected with person B's changes.
## Additional Resources
* [git Homepage](http://git-scm.com/)
* [git cheat sheet by TOWER](http://www.git-tower.com/files/cheatsheet/Git_Cheat_Sheet_grey.pdf)
* [Try Git](http://try.github.com/) | Java |
//
// main.c
// demo14
//
// Created by weichen on 15/1/9.
// Copyright (c) 2015年 weichen. All rights reserved.
//
#include <stdio.h>
int main() {
// 求输入的数的平均数,并输出大于平均数的数字
int x = 0; //输入的数
double num = 0; //总和(这个定义为double, 因为计算结果可能出现浮点数)
int count = 0; //个数
double per; //平均数(结果也定义double)
printf("请输入一些数:");
scanf("%d", &x);
//不等于0时执行累计;输入等于0的值,来终止循环,并执行后面的代码
while(x != 0)
{
num += x;
count++;
scanf("%d", &x);
}
if(count > 0)
{
per = num / count;
printf("%f \n", per);
}
return 0;
}
| Java |
---
layout: default
description: "你来到了没有知识的荒原 🙊"
header-img: "img/404-bg.jpg"
permalink: /404.html
---
<!-- Page Header -->
<header class="intro-header" style="background-image: url('{{ site.baseurl }}/{% if page.header-img %}{{ page.header-img }}{% else %}{{ site.header-img }}{% endif %}')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="site-heading" id="tag-heading">
<h1>404</h1>
<span class="subheading">{{ page.description }}</span>
</div>
</div>
</div>
</div>
</header>
<script>
document.body.classList.add('page-fullscreen');
</script>
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Plugwise implementation: energykit.plugwise — EnergyKit 0.1.0 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '0.1.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="EnergyKit 0.1.0 documentation" href="index.html" />
<link rel="prev" title="Fake data implementation: energykit.fake" href="energykit.fake.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="energykit.fake.html" title="Fake data implementation: energykit.fake"
accesskey="P">previous</a> |</li>
<li><a href="index.html">EnergyKit 0.1.0 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="module-energykit.plugwise">
<span id="plugwise-implementation-energykit-plugwise"></span><h1>Plugwise implementation: <a class="reference internal" href="#module-energykit.plugwise" title="energykit.plugwise"><tt class="xref py py-mod docutils literal"><span class="pre">energykit.plugwise</span></tt></a><a class="headerlink" href="#module-energykit.plugwise" title="Permalink to this headline">¶</a></h1>
<span class="target" id="module-energykit.plugwise.datasource"></span><dl class="class">
<dt id="energykit.plugwise.datasource.DataSource">
<em class="property">class </em><tt class="descclassname">energykit.plugwise.datasource.</tt><tt class="descname">DataSource</tt><a class="reference internal" href="_modules/energykit/plugwise/datasource.html#DataSource"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#energykit.plugwise.datasource.DataSource" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference internal" href="energykit.html#energykit.datasource.DataSource" title="energykit.datasource.DataSource"><tt class="xref py py-class docutils literal"><span class="pre">energykit.datasource.DataSource</span></tt></a>, <a class="reference internal" href="energykit.html#energykit.pubsub.PubSub" title="energykit.pubsub.PubSub"><tt class="xref py py-class docutils literal"><span class="pre">energykit.pubsub.PubSub</span></tt></a></p>
</dd></dl>
<span class="target" id="module-energykit.plugwise.datastream"></span><dl class="class">
<dt id="energykit.plugwise.datastream.DataStream">
<em class="property">class </em><tt class="descclassname">energykit.plugwise.datastream.</tt><tt class="descname">DataStream</tt><big>(</big><em>source</em>, <em>key</em>, <em>type=0</em><big>)</big><a class="reference internal" href="_modules/energykit/plugwise/datastream.html#DataStream"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#energykit.plugwise.datastream.DataStream" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference internal" href="energykit.html#energykit.datastream.DataStream" title="energykit.datastream.DataStream"><tt class="xref py py-class docutils literal"><span class="pre">energykit.datastream.DataStream</span></tt></a></p>
</dd></dl>
<span class="target" id="module-energykit.plugwise.datainterval"></span><dl class="class">
<dt id="energykit.plugwise.datainterval.DataInterval">
<em class="property">class </em><tt class="descclassname">energykit.plugwise.datainterval.</tt><tt class="descname">DataInterval</tt><big>(</big><em>stream</em>, <em>start_time=None</em>, <em>end_time=None</em><big>)</big><a class="reference internal" href="_modules/energykit/plugwise/datainterval.html#DataInterval"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#energykit.plugwise.datainterval.DataInterval" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <a class="reference internal" href="energykit.html#energykit.datainterval.DataInterval" title="energykit.datainterval.DataInterval"><tt class="xref py py-class docutils literal"><span class="pre">energykit.datainterval.DataInterval</span></tt></a></p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="energykit.fake.html"
title="previous chapter">Fake data implementation: <tt class="docutils literal"><span class="pre">energykit.fake</span></tt></a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/energykit.plugwise.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="energykit.fake.html" title="Fake data implementation: energykit.fake"
>previous</a> |</li>
<li><a href="index.html">EnergyKit 0.1.0 documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2013, Sander Dijkhuis, Interactive Institute.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2b1.
</div>
</body>
</html> | Java |
/**
* Module dependencies
*/
const express = require('express');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const compression = require('compression');
const helmet = require('helmet');
const hpp = require('hpp');
const config = require('./config');
const api = require('./api');
const pages = require('./app');
/**
* Create app and router
*/
const app = express();
/**
* Set express trust proxy
*/
app.set('trust proxy', true);
/**
* Set static directory
*/
app.use(express.static(__dirname + '/public'));
/**
* Add middlewares
*/
app.use(compression());
app.use(helmet());
app.use(hpp());
/**
* Ping route
*/
app.get('/ping', (req, res) => res.send('Pong'));
/**
* Add router
*/
app.use('/api', api);
/**
* Mount template router
*/
app.use('/', pages);
/**
* Port
*/
const port = process.env.PORT || config.server.port;
/**
* Cluster
*/
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i += 1) {
cluster.fork();
}
cluster.on('online', (worker) => {
console.log(`Worker ${worker.process.pid} is online`);
});
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died`);
console.log('Starting a new worker');
cluster.fork();
});
} else {
app.listen(port, '0.0.0.0', () => {
console.log(`App listening on port ${port}.`);
});
}
/**
* Handle unhandled exceptions
*/
process.on('unhandledException', err => console.log(err.toString()));
/**
* Expose app
*/
module.exports = app;
| Java |
class UsersController < ApplicationController
def new
end
def create
user = User.new(
email: params[:email],
password: params[:password],
password_confirmation: params[:password_confirmation])
if user.save
session[:user_id] = user.id
flash[:success] = "Successfully Created User Account"
redirect_to '/'
else
flash[:warning] = "Invalid Email or Password"
redirect_to '/signup'
end
end
end
| Java |
#!/bin/sh
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# use filter instead of exclude so missing patterns dont' throw errors
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\""
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "$BUILT_PRODUCTS_DIR/SWXMLHash-watchOS/SWXMLHash.framework"
install_framework "$BUILT_PRODUCTS_DIR/SwiftBus-watchOS/SwiftBus.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "$BUILT_PRODUCTS_DIR/SWXMLHash-watchOS/SWXMLHash.framework"
install_framework "$BUILT_PRODUCTS_DIR/SwiftBus-watchOS/SwiftBus.framework"
fi
| Java |
<div id="top" class="container-fluid">
<div class="navbar navbar-default navbar-fixed-top" style="border-bottom: 1px solid #666 !important;">
<h1 class="homeTitle pull-left">Books Library</h1>
<a href="#/#/top" title="Top" class="btn btn-primary page-scroll home glyphicon glyphicon-plane pull-right"></a>
</div>
<div class="filters">
<form class="form-inline">
<div class="form-group">
<label for="orderProp">
Find me the best
</label>
<select ng-model="orderProp" id="orderProp" class="form-control" ng-change="currentPage=0">
<option value="">All</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Fiction">Fiction</option>
</select>
</div>
<div class="form-group">
<label for="orderG">
books about
</label>
<select ng-model="orderG" id="orderG" class="form-control" ng-change="currentPage=0">
<option value="">All</option>
<option value="{{book.genre.name}}" ng-repeat="book in books | unique:'genre'">{{book.genre.name}}</option>
</select>
</div>
<div class="form-group col-lg-2 col-xs-12 col-sm-3">
<div class="input-group">
<input ng-model="query" id="query" class="form-control" placeholder="Search Books" ng-change="currentPage=0">
<span class="input-group-addon glyphicon glyphicon-search" id="basic-addon2"></span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row bookWrapper">
<div ng-repeat="book in books | filter:query | filter:(orderProp || undefined):true | filter:(orderG || undefined):true | orderBy:orderProp | startFrom:currentPage*pageSize | limitTo:pageSize" class="bookContent clearfix">
<div class="col-xs-8 col-sm-5 col-md-4 bookList clearfix">
<div>
<a href="#/books/{{book.id}}" ng-click="currentObj(book)"><img class="coverImg" ng-src="{{book.cover}}"></a>
</div>
<div class="bookname">
<h4><a href="#/books/{{book.id}}" ng-click="currentObj(book)">{{book.name}}</a></h4>
<p><b><u>{{'by ' + book.author.name}}</u></b></p>
<p><i>{{book.genre.category}}{{', ' + book.genre.name}}</i></p>
<p><span class="right">{{book.published | date}}{{', ' + convertPublishedDate(book.published)}}</span></p>
<p><span class="glyphicon glyphicon-heart"></span>{{' ' + book.likes + ' '}} Likes</p>
</div>
</div>
</div>
</div>
<div class="row navigation pagination-lg">
<ul class="pagination pagination-lg">
<li>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1" class="btn">
<span aria-hidden="true">«</span>
</button>
</li>
<li><a href="javascript:void(0)">{{numberOfPages()==0 ? currentPage : currentPage+1}}</a></li>
<li><a href="javascript:void(0)">/</a></li>
<li><a href="javascript:void(0)">{{numberOfPages()}}</a></li>
<li>
<button ng-disabled="(currentPage + 1) == numberOfPages() || numberOfPages()==0" ng-click="currentPage=currentPage+1" class="btn">
<span aria-hidden="true">»</span>
</button>
</li>
</ul>
</nav>
</div>
| Java |
#include <vector>
#include <iostream>
struct point
{
double x;
double y;
};
int main()
{
// Generate a lot of uniformly distributed 2d points in the range -1,-1 to +1,+1.
enum { numXSamples = 10000 };
enum { numYSamples = 10000 };
std::vector<point> points;
points.reserve(numXSamples * numYSamples);
for(int x = 0;x < numXSamples;++x)
{
for(int y = 0;y < numXSamples;++y)
{
point p = {-1.0 + 2.0 * x / (numXSamples-1),-1.0 + 2.0 * y / (numYSamples-1)};
points.push_back(p);
}
}
// Count the ratio of points inside the unit circle.
int numerator = 0;
int denominator = 0;
for(auto pointIt = points.begin();pointIt != points.end();++pointIt)
{
if(pointIt->x * pointIt->x + pointIt->y * pointIt->y < 1.0)
{
++numerator;
}
++denominator;
}
// Derive the area of the unit circle.
auto circleArea = 4.0 * (double)numerator / denominator;
std::cout << "result: " << circleArea << std::endl;
return 0;
} | Java |
#!/usr/bin/env bash
# Copyright (c) 2016 Ericsson AB
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# $1 = a file or a directory
NAME=$(basename $0)
function _sed() {
sed -i 's/#\s*include\s\(\"\|<\).*\/\(.*\)\(\"\|>\).*/#include \"\2\"/g' $@
}
if [ -f $1 ]; then
_sed $1
elif [ -d $1 ]; then
# Enter directory
cd $1
# Save all files in one array
files=($(find -type f))
number_of_files=${#files[*]}
[ $number_of_files -eq 0 ] && exit
_sed ${files[*]}
fi
| Java |
//
// RBViewController.h
// Pods
//
// Created by Param Aggarwal on 01/02/15.
//
//
#import <UIKit/UIKit.h>
#import "RBViewControllerModel.h"
@interface RBViewController : UIViewController
+ (instancetype)create:(RBViewControllerModel *)model;
- (void)update:(RBViewControllerModel *)model;
- (void)updateChildren:(RBViewControllerModel *)model;
@end
| Java |
<p>
Disponemos de una amplia gama de piensos fisiológicos y de prescripción veterinaria; nuestras auxiliares nutricionistas le asesorarán sobre cualquier aspecto relacionado con la alimentación de su mascota.
</p>
<p>
Contamos con sección especializada en alimentación de animales exóticos.
</p>
<p>
Asimismo, podrá encontrar gran variedad de juguetes y complementos seleccionados pensando en la comodidad, seguridad y diversión de nuestras mascotas.
</p> | Java |
class CreateVersions < ActiveRecord::Migration
def change
create_table :versions do |t|
t.string :item_type, :null => false
t.integer :item_id, :null => false
t.string :event, :null => false
t.string :whodunnit
t.text :object
t.string :locale
t.datetime :created_at
end
add_index :versions, [:item_type, :item_id]
end
end
| Java |
<!DOCTYPE html>
<html>
<head>
<title>Piframe</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="robots" content="noindex"/>
<meta name="viewport" content="width=device-width"/>
<script type="text/javascript" src="lib/jquery/jquery-1.12.0.min.js"></script>
<link rel="stylesheet" href="lib/owl-carousel/owl.carousel.css"/>
<link rel="stylesheet" href="lib/owl-carousel/owl.theme.css"/>
<link rel="stylesheet" href="lib/owl-carousel/owl.transitions.css">
<script src="lib/owl-carousel/owl.carousel.min.js"></script>
<script src="lib/date/date.js"></script>
<script src="lib/date/date-fr-FR.js"></script>
<link rel="stylesheet" href="lib/piframe/piframe.css"/>
<script src="lib/piframe/piframe.js"></script>
</head>
<body>
<div class="loadingContainer"></div>
<div class="owl-carousel mediaContainer"></div>
<div class="mediaTooltip"></div>
</body>
</html> | Java |
using System;
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using MahApps.Metro.Controls;
using NHotkey;
using NHotkey.Wpf;
using QuickHelper.ViewModels;
using QuickHelper.Windows;
using Application = System.Windows.Application;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
namespace QuickHelper
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
public MainWindow()
{
InitializeComponent();
this.PreviewKeyDown += MainWindow_PreviewKeyDown;
this.InitTrayIcon();
HotkeyManager.Current.AddOrReplace(
"Bring to focus",
Key.OemQuestion,
ModifierKeys.Control | ModifierKeys.Windows,
OnBringToFocus);
HotkeyManager.Current.AddOrReplace(
"Bring to focus",
Key.Q, ModifierKeys.Control | ModifierKeys.Shift | ModifierKeys.Alt,
OnBringToFocus);
}
public void OnBringToFocus(object sender, HotkeyEventArgs eventArgs)
{
OpenApplication();
}
private void OpenApplication()
{
ViewModel.FilterText = WindowsHelper.GetActiveProcessFileName();
if (!this.IsVisible)
{
this.Show();
}
if (this.WindowState == WindowState.Minimized)
{
this.WindowState = WindowState.Maximized;
}
this.Activate();
this.Topmost = true; // important
this.Topmost = false; // important
this.Focus(); // important
}
protected MainViewModel ViewModel
{
get { return this.DataContext as MainViewModel; }
}
private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
if (string.IsNullOrWhiteSpace(this.ViewModel.FilterText))
{
this.Hide();
}
else
{
this.ViewModel.ClearFilter();
}
}
}
private NotifyIcon _notifyIcon;
private void InitTrayIcon()
{
_notifyIcon = new NotifyIcon();
_notifyIcon.Icon = new Icon(SystemIcons.Question, 40, 40);
_notifyIcon.Visible = true;
_notifyIcon.DoubleClick += (sender, args) =>
{
this.Show();
var menu = this.FindResource("TrayContextMenu") as System.Windows.Controls.ContextMenu;
menu.IsOpen = false;
this.WindowState = WindowState.Normal;
};
_notifyIcon.MouseClick += (sender, args) =>
{
if (args.Button == MouseButtons.Right)
{
var menu = this.FindResource("TrayContextMenu") as System.Windows.Controls.ContextMenu;
menu.IsOpen = true;
}
};
}
protected override void OnStateChanged(EventArgs e)
{
if (WindowState == WindowState.Minimized)
this.Hide();
base.OnStateChanged(e);
}
protected void Menu_Exit(object sender, RoutedEventArgs e)
{
_notifyIcon.Visible = false;
Application.Current.Shutdown();
}
protected void Menu_Open(object sender, RoutedEventArgs e)
{
OpenApplication();
}
}
}
| Java |
package com.comandante.creeper.command.commands;
import com.comandante.creeper.common.FriendlyTime;
import org.junit.Test;
public class FriendlyTimeTest {
@Test
public void testFriendlyParsing() throws Exception {
FriendlyTime friendlyTime = new FriendlyTime(400);
System.out.println("Friendly Long: " + friendlyTime.getFriendlyFormatted());
System.out.println("Friendly Short: " + friendlyTime.getFriendlyFormattedShort());
}
} | Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TrackR")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TrackR")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d9aa4e01-1571-4721-b6b8-a402f67af6b2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
# React Drop-down Time Picker
Time picker for ReactJS based on the [Cozi Calendar](https://www.cozi.com/calendar) time picker. [See the demo](https://dpalma.github.io/react-dropdown-timepicker/).
[](https://travis-ci.org/dpalma/react-dropdown-timepicker)
## Installation
```shell
$ npm install --save react-dropdown-timepicker
```
## Usage
```javascript
import TimePicker from 'react-dropdown-timepicker';
render() {
<TimePicker
time={this.state.time}
onChange={this.handleTimeChange.bind(this)} />
}
```
| Java |
package fs.command;
import fs.App;
import fs.Disk;
import fs.util.FileUtils;
import java.util.Arrays;
/**
*
* @author José Andrés García Sáenz <jags9415@gmail.com>
*/
public class CreateFileCommand extends Command {
public final static String COMMAND = "mkfile";
@Override
public void execute(String[] args) {
if (args.length != 2 && args.length != 3) {
reportSyntaxError();
return;
}
String path = args[1];
String content = String.join(" ", Arrays.copyOfRange(args, 2, args.length));
App app = App.getInstance();
Disk disk = app.getDisk();
if (disk.exists(path) && !FileUtils.promptForVirtualOverride(path)) {
return;
}
try {
disk.createFile(path, content);
}
catch (Exception ex) {
reportError(ex);
}
}
@Override
protected String getName() {
return CreateFileCommand.COMMAND;
}
@Override
protected String getDescription() {
return "Create a file and set its content.";
}
@Override
protected String getSyntax() {
return getName() + " FILENAME \"<CONTENT>\"";
}
}
| Java |
import { A, O } from 'b-o-a';
import { State } from '../types/state';
import currentPage$ from '../props/current-page';
import signIn$ from '../props/sign-in';
import spots$ from '../props/spots';
import spotForm$ from '../props/spot-form';
import stampRallies$ from '../props/stamp-rallies';
import stampRally$ from '../props/stamp-rally';
import stampRallyForm$ from '../props/stamp-rally-form';
import token$ from '../props/token';
const getDefaultState = (): State => {
return {
googleApiKey: process.env.GOOGLE_API_KEY,
currentPage: 'sign_in#index',
signIn: {
email: null,
password: null
},
spots: [],
spotForm: {
name: null
},
stampRallies: [],
stampRally: null,
stampRallyForm: {
name: null
},
token: {
token: null,
userId: null
}
};
};
const $ = (action$: O<A<any>>, state: State): O<State> => {
const s = (state ? state : getDefaultState());
return O
.combineLatest(
currentPage$(s.currentPage, action$),
signIn$(s.signIn, action$),
token$(s.token, action$),
spots$(s.spots, action$),
spotForm$(s.spotForm, action$),
stampRallies$(s.stampRallies, action$),
stampRally$(s.stampRally, action$),
stampRallyForm$(s.stampRallyForm, action$),
(
currentPage,
signIn,
token,
spots,
spotForm,
stampRallies,
stampRally,
stampRallyForm
): State => {
return Object.assign({}, s, {
currentPage,
signIn,
token,
spots,
spotForm,
stampRallies,
stampRally,
stampRallyForm
});
}
)
.do(console.log.bind(console)) // logger for state
.share();
};
export { $ };
| Java |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013-2013 Bluecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "netbase.h"
#include "util.h"
#ifndef WIN32
#include <sys/fcntl.h>
#endif
#include "strlcpy.h"
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
using namespace std;
// Settings
typedef std::pair<CService, int> proxyType;
static proxyType proxyInfo[NET_MAX];
static proxyType nameproxyInfo;
int nConnectTimeout = 5000;
bool fNameLookup = false;
static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
enum Network ParseNetwork(std::string net) {
boost::to_lower(net);
if (net == "ipv4") return NET_IPV4;
if (net == "ipv6") return NET_IPV6;
if (net == "tor") return NET_TOR;
if (net == "i2p") return NET_I2P;
return NET_UNROUTABLE;
}
void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
size_t colon = in.find_last_of(':');
// if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
bool fHaveColon = colon != in.npos;
bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
char *endp = NULL;
int n = strtol(in.c_str() + colon + 1, &endp, 10);
if (endp && *endp == 0 && n >= 0) {
in = in.substr(0, colon);
if (n > 0 && n < 0x10000)
portOut = n;
}
}
if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
hostOut = in.substr(1, in.size()-2);
else
hostOut = in;
}
bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
vIP.clear();
{
CNetAddr addr;
if (addr.SetSpecial(std::string(pszName))) {
vIP.push_back(addr);
return true;
}
}
struct addrinfo aiHint;
memset(&aiHint, 0, sizeof(struct addrinfo));
aiHint.ai_socktype = SOCK_STREAM;
aiHint.ai_protocol = IPPROTO_TCP;
#ifdef WIN32
# ifdef USE_IPV6
aiHint.ai_family = AF_UNSPEC;
# else
aiHint.ai_family = AF_INET;
# endif
aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
#else
# ifdef USE_IPV6
aiHint.ai_family = AF_UNSPEC;
# else
aiHint.ai_family = AF_INET;
# endif
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif
struct addrinfo *aiRes = NULL;
int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
if (nErr)
return false;
struct addrinfo *aiTrav = aiRes;
while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
{
if (aiTrav->ai_family == AF_INET)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
}
#ifdef USE_IPV6
if (aiTrav->ai_family == AF_INET6)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
}
#endif
aiTrav = aiTrav->ai_next;
}
freeaddrinfo(aiRes);
return (vIP.size() > 0);
}
bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
if (pszName[0] == 0)
return false;
char psz[256];
char *pszHost = psz;
strlcpy(psz, pszName, sizeof(psz));
if (psz[0] == '[' && psz[strlen(psz)-1] == ']')
{
pszHost = psz+1;
psz[strlen(psz)-1] = 0;
}
return LookupIntern(pszHost, vIP, nMaxSolutions, fAllowLookup);
}
bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions)
{
return LookupHost(pszName, vIP, nMaxSolutions, false);
}
bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
{
if (pszName[0] == 0)
return false;
int port = portDefault;
std::string hostname = "";
SplitHostPort(std::string(pszName), port, hostname);
std::vector<CNetAddr> vIP;
bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
if (!fRet)
return false;
vAddr.resize(vIP.size());
for (unsigned int i = 0; i < vIP.size(); i++)
vAddr[i] = CService(vIP[i], port);
return true;
}
bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
{
std::vector<CService> vService;
bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
if (!fRet)
return false;
addr = vService[0];
return true;
}
bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
{
return Lookup(pszName, addr, portDefault, false);
}
bool static Socks4(const CService &addrDest, SOCKET& hSocket)
{
printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
if (!addrDest.IsIPv4())
{
closesocket(hSocket);
return error("Proxy destination is not IPv4");
}
char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
{
closesocket(hSocket);
return error("Cannot get proxy destination address");
}
memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
char* pszSocks4 = pszSocks4IP;
int nSize = sizeof(pszSocks4IP);
int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
if (ret != nSize)
{
closesocket(hSocket);
return error("Error sending to proxy");
}
char pchRet[8];
if (recv(hSocket, pchRet, 8, 0) != 8)
{
closesocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet[1] != 0x5a)
{
closesocket(hSocket);
if (pchRet[1] != 0x5b)
printf("ERROR: Proxy returned error %d\n", pchRet[1]);
return false;
}
printf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
return true;
}
bool static Socks5(string strDest, int port, SOCKET& hSocket)
{
printf("SOCKS5 connecting %s\n", strDest.c_str());
if (strDest.size() > 255)
{
closesocket(hSocket);
return error("Hostname too long");
}
char pszSocks5Init[] = "\5\1\0";
char *pszSocks5 = pszSocks5Init;
ssize_t nSize = sizeof(pszSocks5Init) - 1;
ssize_t ret = send(hSocket, pszSocks5, nSize, MSG_NOSIGNAL);
if (ret != nSize)
{
closesocket(hSocket);
return error("Error sending to proxy");
}
char pchRet1[2];
if (recv(hSocket, pchRet1, 2, 0) != 2)
{
closesocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
{
closesocket(hSocket);
return error("Proxy failed to initialize");
}
string strSocks5("\5\1");
strSocks5 += '\000'; strSocks5 += '\003';
strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
strSocks5 += strDest;
strSocks5 += static_cast<char>((port >> 8) & 0xFF);
strSocks5 += static_cast<char>((port >> 0) & 0xFF);
ret = send(hSocket, strSocks5.c_str(), strSocks5.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)strSocks5.size())
{
closesocket(hSocket);
return error("Error sending to proxy");
}
char pchRet2[4];
if (recv(hSocket, pchRet2, 4, 0) != 4)
{
closesocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet2[0] != 0x05)
{
closesocket(hSocket);
return error("Proxy failed to accept request");
}
if (pchRet2[1] != 0x00)
{
closesocket(hSocket);
switch (pchRet2[1])
{
case 0x01: return error("Proxy error: general failure");
case 0x02: return error("Proxy error: connection not allowed");
case 0x03: return error("Proxy error: network unreachable");
case 0x04: return error("Proxy error: host unreachable");
case 0x05: return error("Proxy error: connection refused");
case 0x06: return error("Proxy error: TTL expired");
case 0x07: return error("Proxy error: protocol error");
case 0x08: return error("Proxy error: address type not supported");
default: return error("Proxy error: unknown");
}
}
if (pchRet2[2] != 0x00)
{
closesocket(hSocket);
return error("Error: malformed proxy response");
}
char pchRet3[256];
switch (pchRet2[3])
{
case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
case 0x03:
{
ret = recv(hSocket, pchRet3, 1, 0) != 1;
if (ret)
return error("Error reading from proxy");
int nRecv = pchRet3[0];
ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
break;
}
default: closesocket(hSocket); return error("Error: malformed proxy response");
}
if (ret)
{
closesocket(hSocket);
return error("Error reading from proxy");
}
if (recv(hSocket, pchRet3, 2, 0) != 2)
{
closesocket(hSocket);
return error("Error reading from proxy");
}
printf("SOCKS5 connected %s\n", strDest.c_str());
return true;
}
bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
{
hSocketRet = INVALID_SOCKET;
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
return false;
}
SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == INVALID_SOCKET)
return false;
#ifdef SO_NOSIGPIPE
int set = 1;
setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif
#ifdef WIN32
u_long fNonblock = 1;
if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
#endif
{
closesocket(hSocket);
return false;
}
if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
// WSAEINVAL is here because some legacy version of winsock uses it
if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
{
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
if (nRet == 0)
{
printf("connection timeout\n");
closesocket(hSocket);
return false;
}
if (nRet == SOCKET_ERROR)
{
printf("select() for connection failed: %i\n",WSAGetLastError());
closesocket(hSocket);
return false;
}
socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
closesocket(hSocket);
return false;
}
if (nRet != 0)
{
printf("connect() failed after select(): %s\n",strerror(nRet));
closesocket(hSocket);
return false;
}
}
#ifdef WIN32
else if (WSAGetLastError() != WSAEISCONN)
#else
else
#endif
{
printf("connect() failed: %i\n",WSAGetLastError());
closesocket(hSocket);
return false;
}
}
// this isn't even strictly necessary
// CNode::ConnectNode immediately turns the socket back to non-blocking
// but we'll turn it back to blocking just in case
#ifdef WIN32
fNonblock = 0;
if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
#endif
{
closesocket(hSocket);
return false;
}
hSocketRet = hSocket;
return true;
}
bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
assert(net >= 0 && net < NET_MAX);
if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
return false;
if (nSocksVersion != 0 && !addrProxy.IsValid())
return false;
proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
return true;
}
bool GetProxy(enum Network net, CService &addrProxy) {
assert(net >= 0 && net < NET_MAX);
if (!proxyInfo[net].second)
return false;
addrProxy = proxyInfo[net].first;
return true;
}
bool SetNameProxy(CService addrProxy, int nSocksVersion) {
if (nSocksVersion != 0 && nSocksVersion != 5)
return false;
if (nSocksVersion != 0 && !addrProxy.IsValid())
return false;
nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
return true;
}
bool GetNameProxy() {
return nameproxyInfo.second != 0;
}
bool IsProxy(const CNetAddr &addr) {
for (int i=0; i<NET_MAX; i++) {
if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
return true;
}
return false;
}
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
{
const proxyType &proxy = proxyInfo[addrDest.GetNetwork()];
// no proxy needed
if (!proxy.second)
return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
SOCKET hSocket = INVALID_SOCKET;
// first connect to proxy server
if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
return false;
// do socks negotiation
switch (proxy.second) {
case 4:
if (!Socks4(addrDest, hSocket))
return false;
break;
case 5:
if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
return false;
break;
default:
return false;
}
hSocketRet = hSocket;
return true;
}
bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
{
string strDest;
int port = portDefault;
SplitHostPort(string(pszDest), port, strDest);
SOCKET hSocket = INVALID_SOCKET;
CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxyInfo.second), port);
if (addrResolved.IsValid()) {
addr = addrResolved;
return ConnectSocket(addr, hSocketRet, nTimeout);
}
addr = CService("0.0.0.0:0");
if (!nameproxyInfo.second)
return false;
if (!ConnectSocketDirectly(nameproxyInfo.first, hSocket, nTimeout))
return false;
switch(nameproxyInfo.second)
{
default:
case 4: return false;
case 5:
if (!Socks5(strDest, port, hSocket))
return false;
break;
}
hSocketRet = hSocket;
return true;
}
void CNetAddr::Init()
{
memset(ip, 0, 16);
}
void CNetAddr::SetIP(const CNetAddr& ipIn)
{
memcpy(ip, ipIn.ip, sizeof(ip));
}
static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
static const unsigned char pchGarliCat[] = {0xFD,0x60,0xDB,0x4D,0xDD,0xB5};
bool CNetAddr::SetSpecial(const std::string &strName)
{
if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
if (vchAddr.size() != 16-sizeof(pchOnionCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
return true;
}
if (strName.size()>11 && strName.substr(strName.size() - 11, 11) == ".oc.b32.i2p") {
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
if (vchAddr.size() != 16-sizeof(pchGarliCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
ip[i + sizeof(pchGarliCat)] = vchAddr[i];
return true;
}
return false;
}
CNetAddr::CNetAddr()
{
Init();
}
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
memcpy(ip, pchIPv4, 12);
memcpy(ip+12, &ipv4Addr, 4);
}
#ifdef USE_IPV6
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
memcpy(ip, &ipv6Addr, 16);
}
#endif
CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(pszIp, vIP, 1, fAllowLookup))
*this = vIP[0];
}
CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
*this = vIP[0];
}
int CNetAddr::GetByte(int n) const
{
return ip[15-n];
}
bool CNetAddr::IsIPv4() const
{
return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
}
bool CNetAddr::IsIPv6() const
{
return (!IsIPv4() && !IsTor() && !IsI2P());
}
bool CNetAddr::IsRFC1918() const
{
return IsIPv4() && (
GetByte(3) == 10 ||
(GetByte(3) == 192 && GetByte(2) == 168) ||
(GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
}
bool CNetAddr::IsRFC3927() const
{
return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
}
bool CNetAddr::IsRFC3849() const
{
return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
}
bool CNetAddr::IsRFC3964() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
}
bool CNetAddr::IsRFC6052() const
{
static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}
bool CNetAddr::IsRFC4380() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
}
bool CNetAddr::IsRFC4862() const
{
static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}
bool CNetAddr::IsRFC4193() const
{
return ((GetByte(15) & 0xFE) == 0xFC);
}
bool CNetAddr::IsRFC6145() const
{
static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}
bool CNetAddr::IsRFC4843() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
}
bool CNetAddr::IsTor() const
{
return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}
bool CNetAddr::IsI2P() const
{
return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
}
bool CNetAddr::IsLocal() const
{
// IPv4 loopback
if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
return true;
// IPv6 loopback (::1/128)
static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
if (memcmp(ip, pchLocal, 16) == 0)
return true;
return false;
}
bool CNetAddr::IsMulticast() const
{
return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
|| (GetByte(15) == 0xFF);
}
bool CNetAddr::IsValid() const
{
// Clean up 3-byte shifted addresses caused by garbage in size field
// of addr messages from versions before 0.2.9 checksum.
// Two consecutive addr messages look like this:
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
// so if the first length field is garbled, it reads the second batch
// of addr misaligned by 3 bytes.
if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
return false;
// unspecified IPv6 address (::/128)
unsigned char ipNone[16] = {};
if (memcmp(ip, ipNone, 16) == 0)
return false;
// documentation IPv6 address
if (IsRFC3849())
return false;
if (IsIPv4())
{
// INADDR_NONE
uint32_t ipNone = INADDR_NONE;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
// 0
ipNone = 0;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
}
return true;
}
bool CNetAddr::IsRoutable() const
{
return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor() && !IsI2P()) || IsRFC4843() || IsLocal());
}
enum Network CNetAddr::GetNetwork() const
{
if (!IsRoutable())
return NET_UNROUTABLE;
if (IsIPv4())
return NET_IPV4;
if (IsTor())
return NET_TOR;
if (IsI2P())
return NET_I2P;
return NET_IPV6;
}
std::string CNetAddr::ToStringIP() const
{
if (IsTor())
return EncodeBase32(&ip[6], 10) + ".onion";
if (IsI2P())
return EncodeBase32(&ip[6], 10) + ".oc.b32.i2p";
CService serv(*this, 0);
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t socklen = sizeof(sockaddr);
if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
char name[1025] = "";
if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
return std::string(name);
}
if (IsIPv4())
return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
else
return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
}
std::string CNetAddr::ToString() const
{
return ToStringIP();
}
bool operator==(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) == 0);
}
bool operator!=(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) != 0);
}
bool operator<(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) < 0);
}
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
if (!IsIPv4())
return false;
memcpy(pipv4Addr, ip+12, 4);
return true;
}
#ifdef USE_IPV6
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
{
memcpy(pipv6Addr, ip, 16);
return true;
}
#endif
// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
std::vector<unsigned char> vchRet;
int nClass = NET_IPV6;
int nStartByte = 0;
int nBits = 16;
// all local addresses belong to the same group
if (IsLocal())
{
nClass = 255;
nBits = 0;
}
// all unroutable addresses belong to the same group
if (!IsRoutable())
{
nClass = NET_UNROUTABLE;
nBits = 0;
}
// for IPv4 addresses, '1' + the 16 higher-order bits of the IP
// includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
else if (IsIPv4() || IsRFC6145() || IsRFC6052())
{
nClass = NET_IPV4;
nStartByte = 12;
}
// for 6to4 tunneled addresses, use the encapsulated IPv4 address
else if (IsRFC3964())
{
nClass = NET_IPV4;
nStartByte = 2;
}
// for Teredo-tunneled IPv6 addresses, use the encapsulated IPv4 address
else if (IsRFC4380())
{
vchRet.push_back(NET_IPV4);
vchRet.push_back(GetByte(3) ^ 0xFF);
vchRet.push_back(GetByte(2) ^ 0xFF);
return vchRet;
}
else if (IsTor())
{
nClass = NET_TOR;
nStartByte = 6;
nBits = 4;
}
else if (IsI2P())
{
nClass = NET_I2P;
nStartByte = 6;
nBits = 4;
}
// for he.net, use /36 groups
else if (GetByte(15) == 0x20 && GetByte(14) == 0x11 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
nBits = 36;
// for the rest of the IPv6 network, use /32 groups
else
nBits = 32;
vchRet.push_back(nClass);
while (nBits >= 8)
{
vchRet.push_back(GetByte(15 - nStartByte));
nStartByte++;
nBits -= 8;
}
if (nBits > 0)
vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
return vchRet;
}
uint64 CNetAddr::GetHash() const
{
uint256 hash = Hash(&ip[0], &ip[16]);
uint64 nRet;
memcpy(&nRet, &hash, sizeof(nRet));
return nRet;
}
void CNetAddr::print() const
{
printf("CNetAddr(%s)\n", ToString().c_str());
}
// private extensions to enum Network, only returned by GetExtNetwork,
// and only used in GetReachabilityFrom
static const int NET_UNKNOWN = NET_MAX + 0;
static const int NET_TEREDO = NET_MAX + 1;
int static GetExtNetwork(const CNetAddr *addr)
{
if (addr == NULL)
return NET_UNKNOWN;
if (addr->IsRFC4380())
return NET_TEREDO;
return addr->GetNetwork();
}
/** Calculates a metric for how reachable (*this) is from a given partner */
int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
{
enum Reachability {
REACH_UNREACHABLE,
REACH_DEFAULT,
REACH_TEREDO,
REACH_IPV6_WEAK,
REACH_IPV4,
REACH_IPV6_STRONG,
REACH_PRIVATE
};
if (!IsRoutable())
return REACH_UNREACHABLE;
int ourNet = GetExtNetwork(this);
int theirNet = GetExtNetwork(paddrPartner);
bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
switch(theirNet) {
case NET_IPV4:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4;
}
case NET_IPV6:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV4: return REACH_IPV4;
case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunneled
}
case NET_TOR:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
case NET_TOR: return REACH_PRIVATE;
}
case NET_I2P:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_I2P: return REACH_PRIVATE;
}
case NET_TEREDO:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
}
case NET_UNKNOWN:
case NET_UNROUTABLE:
default:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
case NET_I2P: return REACH_PRIVATE; // assume connections from unroutable addresses are
case NET_TOR: return REACH_PRIVATE; // either from Tor/I2P, or don't care about our address
}
}
}
void CService::Init()
{
port = 0;
}
CService::CService()
{
Init();
}
CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
{
}
CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
{
}
#ifdef USE_IPV6
CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
{
}
#endif
CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
{
assert(addr.sin_family == AF_INET);
}
#ifdef USE_IPV6
CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
{
assert(addr.sin6_family == AF_INET6);
}
#endif
bool CService::SetSockAddr(const struct sockaddr *paddr)
{
switch (paddr->sa_family) {
case AF_INET:
*this = CService(*(const struct sockaddr_in*)paddr);
return true;
#ifdef USE_IPV6
case AF_INET6:
*this = CService(*(const struct sockaddr_in6*)paddr);
return true;
#endif
default:
return false;
}
}
CService::CService(const char *pszIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
*this = ip;
}
CService::CService(const std::string &strIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
*this = ip;
}
unsigned short CService::GetPort() const
{
return port;
}
bool operator==(const CService& a, const CService& b)
{
return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
}
bool operator!=(const CService& a, const CService& b)
{
return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
}
bool operator<(const CService& a, const CService& b)
{
return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
}
bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
{
if (IsIPv4()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
return false;
*addrlen = sizeof(struct sockaddr_in);
struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
memset(paddrin, 0, *addrlen);
if (!GetInAddr(&paddrin->sin_addr))
return false;
paddrin->sin_family = AF_INET;
paddrin->sin_port = htons(port);
return true;
}
#ifdef USE_IPV6
if (IsIPv6()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
return false;
*addrlen = sizeof(struct sockaddr_in6);
struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
memset(paddrin6, 0, *addrlen);
if (!GetIn6Addr(&paddrin6->sin6_addr))
return false;
paddrin6->sin6_family = AF_INET6;
paddrin6->sin6_port = htons(port);
return true;
}
#endif
return false;
}
std::vector<unsigned char> CService::GetKey() const
{
std::vector<unsigned char> vKey;
vKey.resize(18);
memcpy(&vKey[0], ip, 16);
vKey[16] = port / 0x100;
vKey[17] = port & 0x0FF;
return vKey;
}
std::string CService::ToStringPort() const
{
return strprintf("%i", port);
}
std::string CService::ToStringIPPort() const
{
if (IsIPv4() || IsTor() || IsI2P()) {
return ToStringIP() + ":" + ToStringPort();
} else {
return "[" + ToStringIP() + "]:" + ToStringPort();
}
}
std::string CService::ToString() const
{
return ToStringIPPort();
}
void CService::print() const
{
printf("CService(%s)\n", ToString().c_str());
}
void CService::SetPort(unsigned short portIn)
{
port = portIn;
}
| Java |
/*
组件列表 外在肌肤,水嫩丝滑
生成时间:Sat Dec 17 2016 破门狂人R2-D2为您服务!
*/
.list{
}
.lib-list-item{
display: block;
color: #393939;
border: 1px solid #ddd;
border-radius: 5px;
text-align: center;
line-height: 2.2;
}
.lib-list-item:hover{
box-shadow:0px 2px 10px #c9c9c9;
color: #f6eaa2;
text-shadow:none;
background-color: #2c4c8c;
}
.lib-list-item>div{
width: 100%;
height: 150px;
overflow: hidden;
background-position: center;
background-size: 100% auto;
} | Java |
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html lang="en" xmlns="http://www.w3.org/1999/html"> <!--<![endif]-->
<head>
<!-- Basic Page Needs
================================================== -->
<meta charset="utf-8" />
<title>icon-laptop: Font Awesome Icons</title>
<meta name="description" content="Font Awesome, the iconic font designed for Bootstrap">
<meta name="author" content="Dave Gandy">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!--<meta name="viewport" content="initial-scale=1; maximum-scale=1">-->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- CSS
================================================== -->
<link rel="stylesheet" href="../../assets/css/site.css">
<link rel="stylesheet" href="../../assets/css/pygments.css">
<link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome.css">
<!--[if IE 7]>
<link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome-ie7.css">
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<script type="text/javascript" src="//use.typekit.net/wnc7ioh.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30136587-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body data-spy="scroll" data-target=".navbar">
<div class="wrapper"> <!-- necessary for sticky footer. wrap all content except footer -->
<div class="navbar navbar-inverse navbar-static-top hidden-print">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="../../"><i class="icon-flag"></i> Font Awesome</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="hidden-tablet "><a href="../../">Home</a></li>
<li><a href="../../get-started/">Get Started</a></li>
<li class="dropdown-split-left"><a href="../../icons/">Icons</a></li>
<li class="dropdown dropdown-split-right hidden-phone">
<a href="javascript:" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-caret-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li><a href="../../icons/"><i class="icon-flag icon-fixed-width"></i> Icons</a></li>
<li class="divider"></li>
<li><a href="../../icons/#new"><i class="icon-shield icon-fixed-width"></i> New Icons in 3.2.1</a></li>
<li><a href="../../icons/#web-application"><i class="icon-camera-retro icon-fixed-width"></i> Web Application Icons</a></li>
<li><a href="../../icons/#currency"><i class="icon-won icon-fixed-width"></i> Currency Icons</a></li>
<li><a href="../../icons/#text-editor"><i class="icon-file-text-alt icon-fixed-width"></i> Text Editor Icons</a></li>
<li><a href="../../icons/#directional"><i class="icon-hand-right icon-fixed-width"></i> Directional Icons</a></li>
<li><a href="../../icons/#video-player"><i class="icon-play-sign icon-fixed-width"></i> Video Player Icons</a></li>
<li><a href="../../icons/#brand"><i class="icon-github icon-fixed-width"></i> Brand Icons</a></li>
<li><a href="../../icons/#medical"><i class="icon-medkit icon-fixed-width"></i> Medical Icons</a></li>
</ul>
</li>
<li class="dropdown-split-left"><a href="../../examples/">Examples</a></li>
<li class="dropdown dropdown-split-right hidden-phone">
<a href="javascript:" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-caret-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li><a href="../../examples/">Examples</a></li>
<li class="divider"></li>
<li><a href="../../examples/#new-styles">New Styles</a></li>
<li><a href="../../examples/#inline-icons">Inline Icons</a></li>
<li><a href="../../examples/#larger-icons">Larger Icons</a></li>
<li><a href="../../examples/#bordered-pulled">Bordered & Pulled</a></li>
<li><a href="../../examples/#buttons">Buttons</a></li>
<li><a href="../../examples/#button-groups">Button Groups</a></li>
<li><a href="../../examples/#button-dropdowns">Button Dropdowns</a></li>
<li><a href="../../examples/#bulleted-lists">Bulleted Lists</a></li>
<li><a href="../../examples/#navigation">Navigation</a></li>
<li><a href="../../examples/#form-inputs">Form Inputs</a></li>
<li><a href="../../examples/#animated-spinner">Animated Spinner</a></li>
<li><a href="../../examples/#rotated-flipped">Rotated & Flipped</a></li>
<li><a href="../../examples/#stacked">Stacked</a></li>
<li><a href="../../examples/#custom">Custom CSS</a></li>
</ul>
</li>
<li><a href="../../whats-new/">
<span class="hidden-tablet">What's </span>New</a>
</li>
<li><a href="../../community/">Community</a></li>
<li><a href="../../license/">License</a></li>
</ul>
<ul class="nav pull-right">
<li><a href="http://blog.fontawesome.io">Blog</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="jumbotron jumbotron-icon">
<div class="container">
<div class="info-icons">
<i class="icon-laptop icon-6"></i>
<span class="hidden-phone">
<i class="icon-laptop icon-5"></i>
<span class="hidden-tablet"><i class="icon-laptop icon-4"></i> </span>
<i class="icon-laptop icon-3"></i>
<i class="icon-laptop icon-2"></i>
</span>
<i class="icon-laptop icon-1"></i>
</div>
<h1 class="info-class">
icon-laptop
<small>
<i class="icon-laptop"></i> ·
Unicode: <span class="upper">f109</span> ·
Created: v3.0 ·
Categories:
Web Application Icons
</small>
</h1>
</div>
</div>
<div class="container">
<section>
<div class="row-fluid">
<div class="span9">
<p>After you get <a href="../../integration/">up and running</a>, you can place Font Awesome icons just about anywhere with the <code><i></code> tag:</p>
<div class="well well-transparent">
<div style="font-size: 24px; line-height: 1.5em;">
<i class="icon-laptop"></i> icon-laptop
</div>
</div>
<div class="highlight"><pre><code class="html"><span class="nt"><i</span> <span class="na">class=</span><span class="s">"icon-laptop"</span><span class="nt">></i></span> icon-laptop
</code></pre></div>
<br>
<div class="lead"><i class="icon-info-sign"></i> Looking for more? Check out the <a href="../../examples/">examples</a>.</div>
</div>
<div class="span3">
<div class="info-ad"><div id="carbonads-container"><div class="carbonad"><div id="azcarbon"></div><script type="text/javascript">var z = document.createElement("script"); z.type = "text/javascript"; z.async = true; z.src = "http://engine.carbonads.com/z/32291/azcarbon_2_1_0_VERT"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(z, s);</script></div></div>
</div>
</div>
</div>
</section>
</div>
<div class="push"><!-- necessary for sticky footer --></div>
</div>
<footer class="footer hidden-print">
<div class="container text-center">
<div>
<i class="icon-flag"></i> Font Awesome 3.2.1
<span class="hidden-phone">·</span><br class="visible-phone">
Created and Maintained by <a href="http://twitter.com/davegandy">Dave Gandy</a>
</div>
<div>
Font Awesome licensed under <a href="http://scripts.sil.org/OFL">SIL OFL 1.1</a>
<span class="hidden-phone">·</span><br class="visible-phone">
Code licensed under <a href="http://opensource.org/licenses/mit-license.html">MIT License</a>
<span class="hidden-phone hidden-tablet">·</span><br class="visible-phone visible-tablet">
Documentation licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>
</div>
<div>
Thanks to <a href="http://maxcdn.com"><i class="icon-maxcdn"></i> MaxCDN</a> for providing the excellent <a href="http://www.bootstrapcdn.com/#tab_fontawesome">BootstrapCDN for Font Awesome</a>
</div>
<div class="project">
<a href="https://github.com/FortAwesome/Font-Awesome">GitHub Project</a> ·
<a href="https://github.com/FortAwesome/Font-Awesome/issues">Issues</a>
</div>
</div>
</footer>
<script src="http://platform.twitter.com/widgets.js"></script>
<script src="../../assets/js/jquery-1.7.1.min.js"></script>
<script src="../../assets/js/ZeroClipboard-1.1.7.min.js"></script>
<script src="../../assets/js/bootstrap-2.3.1.min.js"></script>
<script src="../../assets/js/site.js"></script>
</body>
</html>
| Java |
'use strict';
/*
* * angular-socialshare v0.0.2
* * ♡ CopyHeart 2014 by Dayanand Prabhu http://djds4rce.github.io
* * Copying is an act of love. Please copy.
* */
angular.module('djds4rce.angular-socialshare', [])
.factory('$FB', ['$window', function($window) {
return {
init: function(fbId) {
if (fbId) {
this.fbId = fbId;
$window.fbAsyncInit = function() {
FB.init({
appId: fbId,
channelUrl: 'app/channel.html',
status: true,
xfbml: true
});
};
(function(d) {
var js,
id = 'facebook-jssdk',
ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
} else {
throw ("FB App Id Cannot be blank");
}
}
};
}]).directive('facebook', ['$http', function($http) {
return {
scope: {
callback: '=',
shares: '='
},
transclude: true,
template: '<div class="facebookButton">' +
'<div class="pluginButton">' +
'<div class="pluginButtonContainer">' +
'<div class="pluginButtonImage">' +
'<button type="button">' +
'<i class="pluginButtonIcon img sp_plugin-button-2x sx_plugin-button-2x_favblue"></i>' +
'</button>' +
'</div>' +
'<span class="pluginButtonLabel">Share</span>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="facebookCount">' +
'<div class="pluginCountButton pluginCountNum">' +
'<span ng-transclude></span>' +
'</div>' +
'<div class="pluginCountButtonNub"><s></s><i></i></div>' +
'</div>',
link: function(scope, element, attr) {
attr.$observe('url', function() {
if (attr.shares && attr.url) {
$http.get('https://api.facebook.com/method/links.getStats?urls=' + attr.url + '&format=json', {withCredentials: false}).success(function(res) {
var count = (res[0] && res[0].total_count) ? res[0].total_count.toString() : 0;
var decimal = '';
if (count.length > 6) {
if (count.slice(-6, -5) != "0") {
decimal = '.' + count.slice(-6, -5);
}
count = count.slice(0, -6);
count = count + decimal + 'M';
} else if (count.length > 3) {
if (count.slice(-3, -2) != "0") {
decimal = '.' + count.slice(-3, -2);
}
count = count.slice(0, -3);
count = count + decimal + 'k';
}
scope.shares = count;
}).error(function() {
scope.shares = 0;
});
}
element.unbind();
element.bind('click', function(e) {
FB.ui({
method: 'share',
href: attr.url
}, function(response){
if (scope.callback !== undefined && typeof scope.callback === "function") {
scope.callback(response);
}
});
e.preventDefault();
});
});
}
};
}]).directive('facebookFeedShare', ['$http', function($http) {
return {
scope: {
callback: '=',
shares: '='
},
transclude: true,
template: '<div class="facebookButton">' +
'<div class="pluginButton">' +
'<div class="pluginButtonContainer">' +
'<div class="pluginButtonImage">' +
'<button type="button">' +
'<i class="pluginButtonIcon img sp_plugin-button-2x sx_plugin-button-2x_favblue"></i>' +
'</button>' +
'</div>' +
'<span class="pluginButtonLabel">Share</span>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="facebookCount">' +
'<div class="pluginCountButton pluginCountNum">' +
'<span ng-transclude></span>' +
'</div>' +
'<div class="pluginCountButtonNub"><s></s><i></i></div>' +
'</div>',
link: function(scope, element, attr) {
attr.$observe('url', function() {
if (attr.shares && attr.url) {
$http.get('https://api.facebook.com/method/links.getStats?urls=' + attr.url + '&format=json', {withCredentials: false}).success(function(res) {
var count = res[0] ? res[0].total_count.toString() : 0;
var decimal = '';
if (count.length > 6) {
if (count.slice(-6, -5) != "0") {
decimal = '.' + count.slice(-6, -5);
}
count = count.slice(0, -6);
count = count + decimal + 'M';
} else if (count.length > 3) {
if (count.slice(-3, -2) != "0") {
decimal = '.' + count.slice(-3, -2);
}
count = count.slice(0, -3);
count = count + decimal + 'k';
}
scope.shares = count;
}).error(function() {
scope.shares = 0;
});
}
element.unbind();
element.bind('click', function(e) {
FB.ui({
method: 'feed',
link: attr.url,
picture: attr.picture,
name: attr.name,
caption: attr.caption,
description: attr.description
}, function(response){
if (scope.callback !== undefined && typeof scope.callback === "function") {
scope.callback(response);
}
});
e.preventDefault();
});
});
}
};
}]).directive('twitter', ['$timeout', function($timeout) {
return {
link: function(scope, element, attr) {
var renderTwitterButton = debounce(function() {
if (attr.url) {
$timeout(function() {
element[0].innerHTML = '';
twttr.widgets.createShareButton(
attr.url,
element[0],
function() {}, {
count: attr.count,
text: attr.text,
via: attr.via,
size: attr.size
}
);
});
}
}, 75);
attr.$observe('url', renderTwitterButton);
attr.$observe('text', renderTwitterButton);
}
};
}]).directive('linkedin', ['$timeout', '$http', '$window', function($timeout, $http, $window) {
return {
scope: {
shares: '='
},
transclude: true,
template: '<div class="linkedinButton">' +
'<div class="pluginButton">' +
'<div class="pluginButtonContainer">' +
'<div class="pluginButtonImage">in' +
'</div>' +
'<span class="pluginButtonLabel"><span>Share</span></span>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="linkedinCount">' +
'<div class="pluginCountButton">' +
'<div class="pluginCountButtonRight">' +
'<div class="pluginCountButtonLeft">' +
'<span ng-transclude></span>' +
'</div>' +
'</div>' +
'</div>' +
'</div>',
link: function(scope, element, attr) {
var renderLinkedinButton = debounce(function() {
if (attr.shares && attr.url) {
$http.jsonp('https://www.linkedin.com/countserv/count/share?url=' + attr.url + '&callback=JSON_CALLBACK&format=jsonp').success(function(res) {
scope.shares = res.count.toLocaleString();
}).error(function() {
scope.shares = 0;
});
}
$timeout(function() {
element.unbind();
element.bind('click', function() {
var url = encodeURIComponent(attr.url).replace(/'/g, "%27").replace(/"/g, "%22")
$window.open("//www.linkedin.com/shareArticle?mini=true&url=" + url + "&title=" + attr.title + "&summary=" + attr.summary);
});
});
}, 100);
attr.$observe('url', renderLinkedinButton);
attr.$observe('title', renderLinkedinButton);
attr.$observe('summary', renderLinkedinButton);
}
};
}]).directive('gplus', [function() {
return {
link: function(scope, element, attr) {
var googleShare = debounce(function() {
if (typeof gapi == "undefined") {
(function() {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
po.onload = renderGoogleButton;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
} else {
renderGoogleButton();
}
}, 100);
//voodo magic
var renderGoogleButton = (function(ele, attr) {
return function() {
var googleButton = document.createElement('div');
var id = attr.id || randomString(5);
attr.id = id;
googleButton.setAttribute('id', id);
element.innerHTML = '';
element.append(googleButton);
if (attr.class && attr.class.indexOf('g-plusone') != -1) {
window.gapi.plusone.render(id, attr);
} else {
window.gapi.plus.render(id, attr);
}
}
}(element, attr));
attr.$observe('href', googleShare);
}
};
}]).directive('tumblrText', [function() {
return {
link: function(scope, element, attr) {
var tumblr_button = document.createElement("a");
var renderTumblrText = debounce(function() {
tumblr_button.setAttribute("href", "https://www.tumblr.com/share/link?url=" + encodeURIComponent(attr.url) + "&name=" + encodeURIComponent(attr.name) + "&description=" + encodeURIComponent(attr.description));
tumblr_button.setAttribute("title", attr.title || "Share on Tumblr");
tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
element[0].innerHTML = '';
element.append(tumblr_button);
}, 100);
attr.$observe('url', renderTumblrText);
attr.$observe('name', renderTumblrText);
attr.$observe('description', renderTumblrText);
}
}
}]).directive('tumblrQoute', [function() {
return {
link: function(scope, element, attr) {
var tumblr_button = document.createElement("a");
var renderTumblrQoute = debounce(function() {
tumblr_button.setAttribute("href", "https://www.tumblr.com/share/quote?quote=" + encodeURIComponent(attr.qoute) + "&source=" + encodeURIComponent(attr.source));
tumblr_button.setAttribute("title", attr.title || "Share on Tumblr");
tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
element[0].innerHTML = '';
element.append(tumblr_button);
}, 100);
attr.$observe('qoute', renderTumblrQoute);
attr.$observe('source', renderTumblrQoute);
}
}
}]).directive('tumblrImage', [function() {
return {
link: function(scope, element, attr) {
var tumblr_button = document.createElement("a");
var renderTumblrImage = debounce(function() {
tumblr_button.setAttribute("href", "https://www.tumblr.com/share/photo?source=" + encodeURIComponent(attr.source) + "&caption=" + encodeURIComponent(attr.caption) + "&clickthru=" + encodeURIComponent(attr.clickthru));
tumblr_button.setAttribute("title", attr.title || "Share on Tumblr");
tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
element[0].innerHTML = '';
element.append(tumblr_button);
}, 100);
attr.$observe('source', renderTumblrImage);
attr.$observe('caption', renderTumblrImage);
attr.$observe('clickthru', renderTumblrImage);
}
}
}]).directive('tumblrVideo', [function() {
return {
link: function(scope, element, attr) {
var tumblr_button = document.createElement("a");
var renderTumblrVideo = debounce(function() {
tumblr_button.setAttribute("href", "https://www.tumblr.com/share/video?embed=" + encodeURIComponent(attr.embedcode) + "&caption=" + encodeURIComponent(attr.caption));
tumblr_button.setAttribute("title", attr.title || "Share on Tumblr");
tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
element[0].innerHTML = '';
element.append(tumblr_button);
}, 100);
attr.$observe('embedcode', renderTumblrVideo);
attr.$observe('caption', renderTumblrVideo);
}
}
}]).directive('pintrest', ['$window', '$timeout', function($window, $timeout) {
return {
template: '<a href="{{href}}" data-pin-do="{{pinDo}}" data-pin-config="{{pinConfig}}"><img src="//assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png" /></a>',
link: function(scope, element, attr) {
var pintrestButtonRenderer = debounce(function() {
var pin_button = document.createElement("a");
pin_button.setAttribute("href", '//www.pinterest.com/pin/create/button/?url=' + encodeURIComponent(attr.href) + '&media=' + encodeURIComponent(attr.img) + '&description=' + encodeURIComponent(attr.description));
pin_button.setAttribute("pinDo", attr.pinDo || "buttonPin");
pin_button.setAttribute("pinConfig", attr.pinConfig || "beside");
element[0].innerHTML = '';
element.append(pin_button);
$timeout(function() {
$window.parsePins(element);
});
}, 100);
attr.$observe('href', pintrestButtonRenderer);
attr.$observe('img', pintrestButtonRenderer);
attr.$observe('description', pintrestButtonRenderer);
}
}
}]);
//Simple Debounce Implementation
//http://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
//http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript
/**
* RANDOM STRING GENERATOR
*
* Info: http://stackoverflow.com/a/27872144/383904
* Use: randomString(length [,"A"] [,"N"] );
* Default: return a random alpha-numeric string
* Arguments: If you use the optional "A", "N" flags:
* "A" (Alpha flag) return random a-Z string
* "N" (Numeric flag) return random 0-9 string
*/
function randomString(len, an) {
an = an && an.toLowerCase();
var str = "",
i = 0,
min = an == "a" ? 10 : 0,
max = an == "n" ? 10 : 62;
for (; i++ < len;) {
var r = Math.random() * (max - min) + min << 0;
str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48);
}
return str;
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Globalization;
namespace DevTreks.Extensions
{
/// <summary>
///Purpose: Serialize and deserialize a food nutrition cost object.
/// This calculator is used with inputs to calculate costs.
///Author: www.devtreks.org
///Date: 2014, June
///References: www.devtreks.org/helptreks/linkedviews/help/linkedview/HelpFile/148
///NOTES 1. Extends the base object MNSR1 object
///</summary>
public class MNC1Calculator : MNSR1
{
public MNC1Calculator()
: base()
{
//health care cost object
InitMNC1Properties();
}
//copy constructor
public MNC1Calculator(MNC1Calculator lca1Calc)
: base(lca1Calc)
{
CopyMNC1Properties(lca1Calc);
}
//need to store locals and update parent input.ocprice, aohprice, capprice
public Input MNCInput { get; set; }
public virtual void InitMNC1Properties()
{
//avoid null references to properties
this.InitCalculatorProperties();
this.InitSharedObjectProperties();
this.InitMNSR1Properties();
this.MNCInput = new Input();
}
public virtual void CopyMNC1Properties(
MNC1Calculator calculator)
{
this.CopyCalculatorProperties(calculator);
this.CopySharedObjectProperties(calculator);
this.CopyMNSR1Properties(calculator);
this.MNCInput = new Input(calculator.MNCInput);
}
//set the class properties using the XElement
public virtual void SetMNC1Properties(XElement calculator,
XElement currentElement)
{
this.SetCalculatorProperties(calculator);
//need the aggregating params (label, groupid, typeid and Date for sorting)
this.SetSharedObjectProperties(currentElement);
this.SetMNSR1Properties(calculator);
}
//attname and attvalue generally passed in from a reader
public virtual void SetMNC1Property(string attName,
string attValue)
{
this.SetMNSR1Property(attName, attValue);
}
public void SetMNC1Attributes(string attNameExtension,
ref XElement calculator)
{
//must remove old unwanted attributes
if (calculator != null)
{
//do not remove atts here, they were removed in prior this.MNCInput.SetInputAtts
//and now include good locals
//this also sets the aggregating atts
this.SetAndRemoveCalculatorAttributes(attNameExtension, ref calculator);
}
this.SetMNSR1Attributes(attNameExtension, ref calculator);
}
public virtual void SetMNC1Attributes(string attNameExtension,
ref XmlWriter writer)
{
//note must first use use either setanalyzeratts or SetCalculatorAttributes(attNameExtension, ref writer);
this.SetMNSR1Attributes(attNameExtension, ref writer);
}
public bool SetMNC1Calculations(
MN1CalculatorHelper.CALCULATOR_TYPES calculatorType,
CalculatorParameters calcParameters, ref XElement calculator,
ref XElement currentElement)
{
bool bHasCalculations = false;
string sErrorMessage = string.Empty;
InitMNC1Properties();
//deserialize xml to object
//set the base input properties (updates base input prices)
//locals come from input
this.MNCInput.SetInputProperties(calcParameters,
calculator, currentElement);
//set the calculator
this.SetMNC1Properties(calculator, currentElement);
bHasCalculations = RunMNC1Calculations(calcParameters);
if (calcParameters.SubApplicationType == Constants.SUBAPPLICATION_TYPES.inputprices)
{
//serialize object back to xml and fill in updates list
//this also removes atts
this.MNCInput.SetInputAttributes(calcParameters,
ref currentElement, calcParameters.Updates);
}
else
{
//no db updates outside base output
this.MNCInput.SetInputAttributes(calcParameters,
ref currentElement, null);
}
//this sets and removes some atts
this.SetMNC1Attributes(string.Empty, ref calculator);
//set the totals into calculator
this.MNCInput.SetNewInputAttributes(calcParameters, ref calculator);
//set calculatorid (primary way to display calculation attributes)
CalculatorHelpers.SetCalculatorId(
calculator, currentElement);
calcParameters.ErrorMessage = sErrorMessage;
return bHasCalculations;
}
public bool RunMNC1Calculations(CalculatorParameters calcParameters)
{
bool bHasCalculations = false;
//first figure quantities
UpdateBaseInputUnitPrices(calcParameters);
//then figure whether ocamount or capamount should be used as a multiplier
//times calcd by stock.multiplier
double multiplier = GetMultiplierForMNSR1();
//run cost calcs
bHasCalculations = this.RunMNSR1Calculations(calcParameters, multiplier);
return bHasCalculations;
}
private void UpdateBaseInputUnitPrices(
CalculatorParameters calcParameters)
{
//is being able to change ins and outs in tech elements scalable?? double check
//check illegal divisors
this.ContainerSizeInSSUnits = (this.ContainerSizeInSSUnits == 0)
? -1 : this.ContainerSizeInSSUnits;
this.TypicalServingsPerContainer = this.ContainerSizeInSSUnits / this.TypicalServingSize;
this.ActualServingsPerContainer = this.ContainerSizeInSSUnits / this.ActualServingSize;
//Actual serving size has to be 1 unit of hh measure
if (calcParameters.SubApplicationType == Constants.SUBAPPLICATION_TYPES.inputprices)
{
//tech analysis can change from base
this.MNCInput.OCAmount = 1;
}
//calculate OCPrice as a unit cost per serving (not per each unit of serving or ContainerSizeInSSUnits)
this.MNCInput.OCPrice = this.ContainerPrice / this.ActualServingsPerContainer;
//serving size is the unit cost
this.MNCInput.OCUnit = string.Concat(this.ActualServingSize, " ", this.ServingSizeUnit);
//transfer capprice (benefits need to track the package price using calculator.props)
this.MNCInput.CAPPrice = this.ContainerPrice;
this.MNCInput.CAPUnit = this.ContainerUnit;
if (this.MNCInput.CAPAmount > 0)
{
this.ServingCost = this.MNCInput.CAPPrice * this.MNCInput.CAPAmount;
this.MNCInput.TotalCAP = this.ServingCost;
}
else
{
//calculate cost per actual serving
//note that this can change when the input is added elsewhere
this.ServingCost = this.MNCInput.OCPrice * this.MNCInput.OCAmount;
this.MNCInput.TotalOC = this.ServingCost;
}
}
public double GetMultiplierForMNSR1()
{
double multiplier = 1;
if (this.MNCInput.CAPAmount > 0)
{
//cap budget can use container size for nutrient values
multiplier = this.ActualServingsPerContainer * this.MNCInput.CAPAmount;
}
else if (this.MNCInput.CAPAmount <= 0)
{
//op budget can use ocamount for nutrient values
multiplier = this.MNCInput.OCAmount;
}
return multiplier;
}
}
}
| Java |
angular.module('myApp.toDoController', []).
controller('ToDoCtrl', ['$scope', '$state', '$http', '$route', function ($scope, $state, $http, $route) {
$scope.$state = $state;
$scope.addToDo = function() {
// Just in case...
if ($scope.toDoList.length > 50) {
alert("Exceeded to-do limit!!!");
return;
}
if (!$scope.newToDoName || !$scope.newToDoDesc) {
alert("Please fill out both fields!");
return;
}
var newToDo = {
'todo': $scope.newToDoName,
'description': $scope.newToDoDesc
};
$http.post('/to-dos/add-to-do', newToDo).
success(function(data, status, headers, config) {
}).
then(function(answer){
$scope.newToDoName = '';
$scope.newToDoDesc = '';
getToDos();
});
};
$scope.editToDoId = '';
$scope.editToDo = function(toDo) {
// Set the ID of the todo being edited
$scope.editToDoId = toDo._id;
// Reset the to do list in case we were editing other to dos
getToDos();
};
$scope.confirmEditToDo = function() {
// Get the data from the ToDo of interest
var toDoToEdit = '';
for (var i=0; i<$scope.toDoList.length; i++) {
if ($scope.toDoList[i]._id === $scope.editToDoId){
toDoToEdit = {
"todo" : $scope.toDoList[i].todo,
"description" : $scope.toDoList[i].description
};
break;
}
}
if (!toDoToEdit) {
alert("Could not get edited to-do!");
return;
} else if (!toDoToEdit.todo || !toDoToEdit.description) {
alert("Please fill out both fields!");
return;
}
$http.put('/to-dos/update-to-do/' + $scope.editToDoId, toDoToEdit).
success(function(data, status, headers, config) {
$scope.editToDoId = '';
}).
then(function(answer){
getToDos();
});
};
$scope.deleteToDo = function(toDo) {
var confirmation = confirm('Are you sure you want to delete?');
if (!confirmation){
return;
}
$http.delete('/to-dos/delete-to-do/' + toDo._id).
success(function(data, status, headers, config) {
}).
then(function(answer){
getToDos();
});
};
$scope.cancelEditToDo = function() {
$scope.editToDoId = '';
getToDos();
};
var getToDos = function() {
$http.get('/to-dos/to-dos').success(function(data, status, headers, config) {
$scope.toDoList = data;
});
};
// Execute these functions on page load
angular.element(document).ready(function () {
getToDos();
});
}]); | Java |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.cosmos.internal.query;
import com.azure.data.cosmos.BadRequestException;
import com.azure.data.cosmos.BridgeInternal;
import com.azure.data.cosmos.CommonsBridgeInternal;
import com.azure.data.cosmos.internal.DocumentCollection;
import com.azure.data.cosmos.FeedOptions;
import com.azure.data.cosmos.Resource;
import com.azure.data.cosmos.SqlQuerySpec;
import com.azure.data.cosmos.internal.HttpConstants;
import com.azure.data.cosmos.internal.OperationType;
import com.azure.data.cosmos.internal.PartitionKeyRange;
import com.azure.data.cosmos.internal.ResourceType;
import com.azure.data.cosmos.internal.RxDocumentServiceRequest;
import com.azure.data.cosmos.internal.Strings;
import com.azure.data.cosmos.internal.Utils;
import com.azure.data.cosmos.internal.caches.RxCollectionCache;
import com.azure.data.cosmos.internal.routing.PartitionKeyInternal;
import com.azure.data.cosmos.internal.routing.Range;
import org.apache.commons.lang3.StringUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
* While this class is public, but it is not part of our published public APIs.
* This is meant to be internally used only by our sdk.
*/
public class DocumentQueryExecutionContextFactory {
private final static int PageSizeFactorForTop = 5;
private static Mono<Utils.ValueHolder<DocumentCollection>> resolveCollection(IDocumentQueryClient client, SqlQuerySpec query,
ResourceType resourceTypeEnum, String resourceLink) {
RxCollectionCache collectionCache = client.getCollectionCache();
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
OperationType.Query,
resourceTypeEnum,
resourceLink, null
// TODO AuthorizationTokenType.INVALID)
); //this request doesnt actually go to server
return collectionCache.resolveCollectionAsync(request);
}
public static <T extends Resource> Flux<? extends IDocumentQueryExecutionContext<T>> createDocumentQueryExecutionContextAsync(
IDocumentQueryClient client,
ResourceType resourceTypeEnum,
Class<T> resourceType,
SqlQuerySpec query,
FeedOptions feedOptions,
String resourceLink,
boolean isContinuationExpected,
UUID correlatedActivityId) {
// return proxy
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = Flux.just(new Utils.ValueHolder<>(null));
if (resourceTypeEnum.isCollectionChild()) {
collectionObs = resolveCollection(client, query, resourceTypeEnum, resourceLink).flux();
}
DefaultDocumentQueryExecutionContext<T> queryExecutionContext = new DefaultDocumentQueryExecutionContext<T>(
client,
resourceTypeEnum,
resourceType,
query,
feedOptions,
resourceLink,
correlatedActivityId,
isContinuationExpected);
if (ResourceType.Document != resourceTypeEnum) {
return Flux.just(queryExecutionContext);
}
Mono<PartitionedQueryExecutionInfo> queryExecutionInfoMono =
com.azure.data.cosmos.internal.query.QueryPlanRetriever.getQueryPlanThroughGatewayAsync(client, query, resourceLink);
return collectionObs.single().flatMap(collectionValueHolder ->
queryExecutionInfoMono.flatMap(partitionedQueryExecutionInfo -> {
QueryInfo queryInfo =
partitionedQueryExecutionInfo.getQueryInfo();
// Non value aggregates must go through
// DefaultDocumentQueryExecutionContext
// Single partition query can serve queries like SELECT AVG(c
// .age) FROM c
// SELECT MIN(c.age) + 5 FROM c
// SELECT MIN(c.age), MAX(c.age) FROM c
// while pipelined queries can only serve
// SELECT VALUE <AGGREGATE>. So we send the query down the old
// pipeline to avoid a breaking change.
// Should be fixed by adding support for nonvalueaggregates
if (queryInfo.hasAggregates() && !queryInfo.hasSelectValue()) {
if (feedOptions != null && feedOptions.enableCrossPartitionQuery()) {
return Mono.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST,
"Cross partition query only supports 'VALUE " +
"<AggreateFunc>' for aggregates"));
}
return Mono.just(queryExecutionContext);
}
Mono<List<PartitionKeyRange>> partitionKeyRanges;
// The partitionKeyRangeIdInternal is no more a public API on FeedOptions, but have the below condition
// for handling ParallelDocumentQueryTest#partitionKeyRangeId
if (feedOptions != null && !StringUtils.isEmpty(CommonsBridgeInternal.partitionKeyRangeIdInternal(feedOptions))) {
partitionKeyRanges = queryExecutionContext.getTargetPartitionKeyRangesById(collectionValueHolder.v.resourceId(),
CommonsBridgeInternal.partitionKeyRangeIdInternal(feedOptions));
} else {
List<Range<String>> queryRanges =
partitionedQueryExecutionInfo.getQueryRanges();
if (feedOptions != null && feedOptions.partitionKey() != null) {
PartitionKeyInternal internalPartitionKey =
feedOptions.partitionKey()
.getInternalPartitionKey();
Range<String> range = Range.getPointRange(internalPartitionKey
.getEffectivePartitionKeyString(internalPartitionKey,
collectionValueHolder.v.getPartitionKey()));
queryRanges = Collections.singletonList(range);
}
partitionKeyRanges = queryExecutionContext
.getTargetPartitionKeyRanges(collectionValueHolder.v.resourceId(), queryRanges);
}
return partitionKeyRanges
.flatMap(pkranges -> createSpecializedDocumentQueryExecutionContextAsync(client,
resourceTypeEnum,
resourceType,
query,
feedOptions,
resourceLink,
isContinuationExpected,
partitionedQueryExecutionInfo,
pkranges,
collectionValueHolder.v.resourceId(),
correlatedActivityId).single());
})).flux();
}
public static <T extends Resource> Flux<? extends IDocumentQueryExecutionContext<T>> createSpecializedDocumentQueryExecutionContextAsync(
IDocumentQueryClient client,
ResourceType resourceTypeEnum,
Class<T> resourceType,
SqlQuerySpec query,
FeedOptions feedOptions,
String resourceLink,
boolean isContinuationExpected,
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo,
List<PartitionKeyRange> targetRanges,
String collectionRid,
UUID correlatedActivityId) {
if (feedOptions == null) {
feedOptions = new FeedOptions();
}
int initialPageSize = Utils.getValueOrDefault(feedOptions.maxItemCount(),
ParallelQueryConfig.ClientInternalPageSize);
BadRequestException validationError = Utils.checkRequestOrReturnException(
initialPageSize > 0 || initialPageSize == -1, "MaxItemCount", "Invalid MaxItemCount %s", initialPageSize);
if (validationError != null) {
return Flux.error(validationError);
}
QueryInfo queryInfo = partitionedQueryExecutionInfo.getQueryInfo();
if (!Strings.isNullOrEmpty(queryInfo.getRewrittenQuery())) {
query = new SqlQuerySpec(queryInfo.getRewrittenQuery(), query.parameters());
}
boolean getLazyFeedResponse = queryInfo.hasTop();
// We need to compute the optimal initial page size for order-by queries
if (queryInfo.hasOrderBy()) {
int top;
if (queryInfo.hasTop() && (top = partitionedQueryExecutionInfo.getQueryInfo().getTop()) > 0) {
int pageSizeWithTop = Math.min(
(int)Math.ceil(top / (double)targetRanges.size()) * PageSizeFactorForTop,
top);
if (initialPageSize > 0) {
initialPageSize = Math.min(pageSizeWithTop, initialPageSize);
}
else {
initialPageSize = pageSizeWithTop;
}
}
// TODO: do not support continuation in string format right now
// else if (isContinuationExpected)
// {
// if (initialPageSize < 0)
// {
// initialPageSize = (int)Math.Max(feedOptions.MaxBufferedItemCount, ParallelQueryConfig.GetConfig().DefaultMaximumBufferSize);
// }
//
// initialPageSize = Math.Min(
// (int)Math.Ceiling(initialPageSize / (double)targetRanges.Count) * PageSizeFactorForTop,
// initialPageSize);
// }
}
return PipelinedDocumentQueryExecutionContext.createAsync(
client,
resourceTypeEnum,
resourceType,
query,
feedOptions,
resourceLink,
collectionRid,
partitionedQueryExecutionInfo,
targetRanges,
initialPageSize,
isContinuationExpected,
getLazyFeedResponse,
correlatedActivityId);
}
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coq bench</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../../..">Unstable</a></li>
<li><a href=".">8.4.dev / contrib:aac-tactics dev</a></li>
<li class="active"><a href="">2014-12-13 08:31:47</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../../../../../about.html">About</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href=".">« Up</a>
<h1>
contrib:aac-tactics
<small>
dev
<span class="label label-info">Not compatible with this Coq</span>
</small>
</h1>
<p><em><script>document.write(moment("2014-12-13 08:31:47 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2014-12-13 08:31:47 UTC)</em><p>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:aac-tactics/coq:contrib:aac-tactics.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>The package is valid.
</pre></dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --dry-run coq:contrib:aac-tactics.dev coq.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>768</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.4.dev).
The following dependencies couldn't be met:
- coq:contrib:aac-tactics -> coq >= dev
Your request can't be satisfied:
- Conflicting version constraints for coq
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --dry-run coq:contrib:aac-tactics.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>3 s</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- remove coq.8.4.dev
=== 1 to remove ===
=-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Removing coq.8.4.dev.
[WARNING] Directory /home/bench/.opam/system/lib/coq is not empty, not removing
[WARNING] Directory /home/bench/.opam/system/share/coq is not empty, not removing
The following actions will be performed:
- install coq.hott [required by coq:contrib:aac-tactics]
- install coq:contrib:aac-tactics.dev
=== 2 to install ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
=-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Building coq.hott:
./configure -configdir /home/bench/.opam/system/lib/coq/config -mandir /home/bench/.opam/system/man -docdir /home/bench/.opam/system/doc -prefix /home/bench/.opam/system -usecamlp5 -camlp5dir /home/bench/.opam/system/lib/camlp5 -coqide no
make -j4
make install
Installing coq.hott.
Building coq:contrib:aac-tactics.dev:
coq_makefile -f Make -o Makefile
make -j4
make install
Installing coq:contrib:aac-tactics.dev.
</pre></dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html> | Java |
import sys
MAX_NUM_STORED_LINES = 200
MAX_NUM_LINES = 10
LINEWIDTH = 80
class CmdText(object):
"""
Represents a command line text device. Text is split into lines
corresponding to the linewidth of the device.
"""
def __init__(self):
"""
Construct empty object.
"""
self.num_lines = 0
self.remaining_lines = MAX_NUM_LINES
self.lines = []
def insert(self, string):
"""
Insert string at the end. This always begins a new line.
"""
if (self.num_lines >= MAX_NUM_LINES):
pass
input_num_lines = num_lines(string)
#if (input_num_lines > self.remaining_lines):
# num = self.remaining_lines
#else:
# num = input_num_lines
num = input_num_lines
new_lines = get_lines(string)
self.lines += new_lines[-num:]
self.update_num_lines()
def merge_after(self, obj):
"""
Merge with another CmdText object by appending the input objects content.
"""
self.lines
def strip_lines(self):
"""
Remove excessive number of lines. This deletes the oldest half.
"""
if (self.num_lines > MAX_NUM_STORED_LINES):
for i in range(MAX_NUM_STORED_LINES // 2):
self.lines.pop(i)
def update_num_lines(self):
"""
Update the number of lines member.
"""
self.num_lines = len(self.lines)
def get_line(self, n):
"""
Return the line with index n.
"""
if n < self.num_lines:
return self.lines[n]
else:
raise IndexError("Line index out of range.")
def print_screen(self):
"""
Return MAX_NUM_LINES lines.
"""
return self.lines[-MAX_NUM_LINES:]
def __iter__(self):
"""
Iterator for CmdText object.
"""
for l in self.lines:
yield l
def __getitem__(self, ind):
return self.lines[ind]
def num_lines(string):
"""
Return number of lines.
"""
line_list = string.split("\n")
num = len(line_list)
for l in line_list:
num += (len(string) // LINEWIDTH + 1)
return num
def get_lines(string):
"""
Return list of lines extracted from string.
"""
line_list = string.split('\n')
new_list = []
for l in line_list:
new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)]
return new_list
class Command(CmdText):
def __init__(self, string, rind=None):
CmdText.__init__(self)
self.insert(string)
if (rind is not None):
self.response = rind
class Response(CmdText):
def __init__(self, string, cind=None):
CmdText.__init__(self)
self.insert(string)
if (cind is not None):
self.command = cind
class TestCase(object):
"""
Base class for tests.
"""
@classmethod
def run(cls):
"""
Runs all tests (methods which begin with 'test').
"""
#print(cls)
max_len = max([len(a) for a in cls.__dict__])
for key in cls.__dict__:
if key.startswith("test"):
fill = max_len - len(key)
sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill))
try:
cls.__dict__[key]()
except:
raise
else:
print("Test passed!")
print("All tests passed!")
class StaticTest(TestCase):
"""
Tests for static methods.
"""
def test_get_lines_with_empty_string():
assert get_lines("") == [""]
def test_get_lines_with_short_string():
assert len(get_lines("a"*(LINEWIDTH-1))) == 1
def test_get_lines_with_long_string():
assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2
def test_get_lines_with_very_long_string():
assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4
def test_get_lines_with_long_text_string():
text = "This is a test string, which should simulate real text. The command should" \
+ " correctly split this text into two lines."
LINEWIDTH = 80
correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]]
assert len(get_lines(text)) == len(text) // LINEWIDTH + 1
assert get_lines(text) == correct_lines
class CmdTextTest(object):
"""
Tests for CmdText class methods.
"""
pass | Java |
<?php
require_once (__DIR__ . '/../lib/bootstrap.php');
require_once (__DIR__ . '/lib/TestListener.php');
use PHPUnit\Framework\TestCase;
use Selenide\By, Selenide\Condition, Selenide\Selenide;
class ListenerTest extends TestCase
{
/**
* @var Selenide
*/
protected static $wd = null;
protected static $timeout = 5;
/**
* Url for test page in tests/www/webdrivertest.html
* @var string
*/
protected static $testUrl = '/';
protected static $baseUrl = 'http://127.0.0.1:8000';
protected static $config = null;
protected $backupStaticAttributesBlacklist = array(
'SelenideTest' => array('wd'),
);
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
self::$wd = new \Selenide\Selenide();
self::$wd->configuration()->baseUrl = self::config('selenium/baseUrl');
self::$wd->configuration()->host = self::config('selenium/host');
self::$wd->configuration()->port = self::config('selenium/port');
self::$wd->connect();
self::$wd->getDriver()->webDriver()->timeout()->implicitWait(1);
self::$wd->open(self::$testUrl);
$listener = new TestListener();
self::$wd->addListener($listener);
}
public function setUp()
{
parent::setUp();
self::$wd->getReport()->disable();
self::$wd->configuration()->timeout = self::$timeout;
TestListener::clean();
}
protected static function config($path)
{
if (self::$config === null) {
$configPath = __DIR__ . '/etc/config.php';
$devPath = __DIR__ . '/etc/config.dev.php';
$config = include ($configPath);
if (file_exists($devPath)) {
//only top level group replace
$devCfg = include ($devPath);
foreach ($devCfg as $name => $opts) {
$config[$name] = $opts;
}
}
self::$config = $config;
}
$path = explode('/', trim($path, '/'));
$value = self::$config;
foreach ($path as $nodeName) {
$value = $value[$nodeName];
}
return $value;
}
public function testListener_Click_CallListener()
{
$description = __METHOD__;
self::$wd
->description($description)
->find(By::withText('textTwo'))
->should(Condition::withText("textTwo"))
->shouldNot(Condition::withText("textOne"))
->click();
$this->assertCount(2, TestListener::$data, 'No data in listener');
$event = TestListener::$data[1];
$this->assertArrayHasKey('method', $event, 'No data about method');
$this->assertArrayHasKey('element', $event, 'No data about element');
$this->assertArrayHasKey('locator', $event, 'No data about locator');
$this->assertArrayHasKey('description', $event, 'No data about description');
$this->assertEquals('beforeClick', $event['method'], 'Must be called Listener::beforeClick');
$this->assertInstanceOf('Selenide\SelenideElement', $event['element'], 'Element must be is SelenideElement');
$this->assertGreaterThan(10, strlen($event['locator']), 'Locator too short');
$this->assertEquals(
$description, $event['description'], 'Description must equals is selenide->description()'
);
}
public function testListener_SetValue_CallListener()
{
$description = __METHOD__;
$textValue = 'washtub';
self::$wd
->description($description)
->find(By::id('e_textarea'))
->setValue($textValue);
$this->assertCount(2, TestListener::$data, 'No data in listener');
$event = TestListener::$data[1];
$this->assertArrayHasKey('method', $event, 'No data about method');
$this->assertArrayHasKey('element', $event, 'No data about element');
$this->assertArrayHasKey('locator', $event, 'No data about locator');
$this->assertArrayHasKey('value', $event, 'No data about value');
$this->assertArrayHasKey('description', $event, 'No data about description');
$this->assertEquals('beforeSetValue', $event['method'], 'Must be called Listener::beforeClick');
$this->assertEquals($textValue, $event['value'], 'Bad value of setValue');
$this->assertInstanceOf('Selenide\SelenideElement', $event['element'], 'Element must be is SelenideElement');
$this->assertGreaterThan(10, strlen($event['locator']), 'Locator too short');
$this->assertEquals(
$description, $event['description'], 'Description must equals is selenide->description()'
);
}
public function testListener_Assert_CallListener()
{
$description = __METHOD__;
self::$wd
->description($description)
->find(By::withText('textTwo'))
->assert(Condition::visible());
$this->assertCount(2, TestListener::$data, 'No data in listener');
$event = TestListener::$data[1];
$this->assertArrayHasKey('method', $event, 'No data about method');
$this->assertArrayHasKey('locator', $event, 'No data about locator');
$this->assertArrayHasKey('condition', $event, 'No data about condition');
$this->assertEquals('beforeAssert', $event['method'], 'Must be called Listener::beforeAssert');
$this->assertInstanceOf(
'Selenide\Condition_Rule', $event['condition'], 'Condition must be is Selenide\Condition_Rule'
);
$this->assertGreaterThan(10, strlen($event['locator']), 'Locator too short');
}
public function testListener_AssertNot_CallListener()
{
$description = __METHOD__;
self::$wd
->description($description)
->find(By::withText('textTwo'))
->assertNot(Condition::size(20));
$this->assertCount(2, TestListener::$data, 'No data in listener');
$event = TestListener::$data[1];
$this->assertArrayHasKey('method', $event, 'No data about method');
$this->assertArrayHasKey('locator', $event, 'No data about locator');
$this->assertArrayHasKey('condition', $event, 'No data about condition');
$this->assertEquals('beforeAssertNot', $event['method'], 'Must be called Listener::beforeAssertNot');
$this->assertInstanceOf(
'Selenide\Condition_Rule', $event['condition'], 'Condition must be is Selenide\Condition_Rule'
);
$this->assertGreaterThan(10, strlen($event['locator']), 'Locator too short');
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace Anfloga.Rendering
{
public class BloomRenderer : IEffectsRenderer
{
public int Height { get; set; }
public int Width { get; set; }
public float BloomIntensity { get; set; } = 2f;
public float BaseIntensity { get; set; } = 0.9f;
public float BloomSaturation { get; set; } = 1.5f;
public float BaseSaturation { get; set; } = 1.0f;
SpriteBatch spriteBatch;
RenderTarget2D target1;
RenderTarget2D target2;
Effect bloomEffect;
BloomExtractRenderer extractRenderer;
BlurRenderer blurRenderer;
GraphicsDevice device;
bool initialized = false;
public BloomRenderer(Effect bloomCombineEffect)
{
this.bloomEffect = bloomCombineEffect;
}
public void Initialize(GraphicsDevice device, Camera camera)
{
Height = device.PresentationParameters.BackBufferHeight;
Width = device.PresentationParameters.BackBufferWidth;
this.device = device;
spriteBatch = new SpriteBatch(this.device);
// use half size texture for extract and blur
target1 = new RenderTarget2D(device, Width / 2, Height / 2);
target2 = new RenderTarget2D(device, Width, Height);
extractRenderer = new BloomExtractRenderer();
extractRenderer.Initialize(this.device, camera);
blurRenderer = new BlurRenderer();
blurRenderer.Initialize(this.device, camera);
bloomEffect.Parameters["BloomIntensity"].SetValue(BloomIntensity);
bloomEffect.Parameters["BaseIntensity"].SetValue(BaseIntensity);
bloomEffect.Parameters["BloomSaturation"].SetValue(BloomSaturation);
bloomEffect.Parameters["BaseSaturation"].SetValue(BaseSaturation);
initialized = true;
}
public void Draw(RenderTarget2D src, RenderTarget2D dest)
{
if(!initialized)
{
throw new Exception("Draw was called before effect was initialized!");
}
// draw src buffer with extract effect to target1 buffer
extractRenderer.Draw(src, target1);
// draw extract buffer to target2 with blur
blurRenderer.Draw(target1, target2);
int destWidth = dest != null ? dest.Width : Width;
int destHeight = dest != null ? dest.Height : Height;
// finally perform our bloom combine
device.Textures[1] = src; // setting this allows the shader to operate on the src texture
device.SetRenderTarget(dest);
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, bloomEffect);
spriteBatch.Draw(target2, new Rectangle(0, 0, destWidth, destHeight), Color.White);
spriteBatch.End();
}
}
}
| Java |
#[macro_export]
macro_rules! punctuator {
($lexer: ident, $p: ident) => ({
$lexer.iter.next();
Ok(Token::Punctuator(Punctuator::$p, $lexer.lo, $lexer.lo + 1))
})
}
// Advance iter and hi position if pattern match
#[macro_export]
macro_rules! take {
($lexer: ident, $($p: pat)|*) => (
match $lexer.iter.peek() {
$(
Some(&(i, $p)) => {
$lexer.iter.next();
$lexer.hi = i + 1;
true
}
)*
_ => false
});
}
#[macro_export]
macro_rules! take_while {
($lexer: ident, $($p: pat)|*) => ({
let mut is_taken = false;
while let Some(&(p, c)) = $lexer.iter.peek() {
match c {
$(
$p => {
$lexer.iter.next();
$lexer.hi = p + 1;
is_taken = true;
}
)*
_ => {
break;
}
}
}
is_taken
});
}
#[macro_export]
macro_rules! take_while_not {
($lexer: ident, $($p: pat)|*) => ({
let mut is_taken = false;
while let Some(&(p, c)) = $lexer.iter.peek() {
match c {
$(
$p => {
$lexer.hi = p;
break;
}
)*
_ => {
$lexer.iter.next();
is_taken = true;
}
}
}
is_taken
});
}
#[macro_export]
macro_rules! peek {
($lexer: ident, $($p: pat)|*) => (
match $lexer.iter.peek() {
$(
Some(&(_, $p)) => true,
)*
_ => false
});
}
// Advance iter if pattern match, keep hi position unchange
#[macro_export]
macro_rules! follow_by {
($lexer: ident, $($p: pat)|*) => (
match $lexer.iter.peek() {
$(
Some(&(_, $p)) => {
$lexer.iter.next();
true
}
)*
_ => false
});
}
| Java |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#ifndef APPLESEED_FOUNDATION_UTILITY_TEST_LOGGERTESTLISTENER_H
#define APPLESEED_FOUNDATION_UTILITY_TEST_LOGGERTESTLISTENER_H
// appleseed.main headers.
#include "main/dllsymbol.h"
// Forward declarations.
namespace foundation { class ITestListener; }
namespace foundation { class Logger; }
namespace foundation
{
//
// A test listener that forwards messages to a logger.
//
// Factory function.
APPLESEED_DLLSYMBOL ITestListener* create_logger_test_listener(
Logger& logger,
const bool verbose = false);
} // namespace foundation
#endif // !APPLESEED_FOUNDATION_UTILITY_TEST_LOGGERTESTLISTENER_H
| Java |
/*
* Copyright (c) 2010, ETH Zurich.
* All rights reserved.
*
* INTERFACE NAME: mem
* INTEFACE FILE: ../if/mem.if
* INTERFACE DESCRIPTION: Memory allocation RPC interface
*
* This file is distributed under the terms in the attached LICENSE
* file. If you do not find this file, copies can be found by
* writing to:
* ETH Zurich D-INFK, Universitaetstr.6, CH-8092 Zurich.
* Attn: Systems Group.
*
* THIS FILE IS AUTOMATICALLY GENERATED BY FLOUNDER: DO NOT EDIT!
*/
#include <barrelfish/barrelfish.h>
#include <flounder/flounder_support.h>
#include <if/mem_defs.h>
/*
* Export function
*/
errval_t mem_export(void *st, idc_export_callback_fn *export_cb, mem_connect_fn *connect_cb, struct waitset *ws, idc_export_flags_t flags)
{
struct mem_export *e = malloc(sizeof(struct mem_export ));
if (e == NULL) {
return(LIB_ERR_MALLOC_FAIL);
}
// fill in common parts of export struct
e->connect_cb = connect_cb;
e->waitset = ws;
e->st = st;
(e->common).export_callback = export_cb;
(e->common).flags = flags;
(e->common).connect_cb_st = e;
(e->common).export_cb_st = st;
// fill in connect handler for each enabled backend
#ifdef CONFIG_FLOUNDER_BACKEND_LMP
(e->common).lmp_connect_callback = mem_lmp_connect_handler;
#endif // CONFIG_FLOUNDER_BACKEND_LMP
#ifdef CONFIG_FLOUNDER_BACKEND_UMP
(e->common).ump_connect_callback = mem_ump_connect_handler;
#endif // CONFIG_FLOUNDER_BACKEND_UMP
#ifdef CONFIG_FLOUNDER_BACKEND_UMP_IPI
(e->common).ump_connect_callback = mem_ump_ipi_connect_handler;
#endif // CONFIG_FLOUNDER_BACKEND_UMP_IPI
#ifdef CONFIG_FLOUNDER_BACKEND_MULTIHOP
(e->common).multihop_connect_callback = mem_multihop_connect_handler;
#endif // CONFIG_FLOUNDER_BACKEND_MULTIHOP
return(idc_export_service(&(e->common)));
}
/*
* Generic bind function
*/
static void mem_bind_continuation_direct(void *st, errval_t err, struct mem_binding *_binding)
{
// This bind cont function uses the different backends in the following order:
// lmp ump_ipi ump multihop
struct flounder_generic_bind_attempt *b = st;
switch (b->driver_num) {
case 0:
(b->driver_num)++;
#ifdef CONFIG_FLOUNDER_BACKEND_LMP
// try next backend
b->binding = malloc(sizeof(struct mem_lmp_binding ));
assert((b->binding) != NULL);
err = mem_lmp_bind(b->binding, b->iref, mem_bind_continuation_direct, b, b->waitset, b->flags, DEFAULT_LMP_BUF_WORDS);
if (err_is_fail(err)) {
free(b->binding);
_binding = NULL;
goto out;
} else {
return;
}
#else
// skip non-enabled backend (fall through)
#endif // CONFIG_FLOUNDER_BACKEND_LMP
case 1:
#ifdef CONFIG_FLOUNDER_BACKEND_LMP
if (err_is_ok(err)) {
goto out;
} else {
free(b->binding);
if (err_no(err) == MON_ERR_IDC_BIND_NOT_SAME_CORE) {
goto try_next_1;
} else {
// report permanent failure to user
_binding = NULL;
goto out;
}
}
try_next_1:
#endif // CONFIG_FLOUNDER_BACKEND_LMP
(b->driver_num)++;
#ifdef CONFIG_FLOUNDER_BACKEND_UMP_IPI
// try next backend
b->binding = malloc(sizeof(struct mem_ump_ipi_binding ));
assert((b->binding) != NULL);
err = mem_ump_ipi_bind(b->binding, b->iref, mem_bind_continuation_direct, b, b->waitset, b->flags, DEFAULT_UMP_BUFLEN, DEFAULT_UMP_BUFLEN);
if (err_is_fail(err)) {
free(b->binding);
_binding = NULL;
goto out;
} else {
return;
}
#else
// skip non-enabled backend (fall through)
#endif // CONFIG_FLOUNDER_BACKEND_UMP_IPI
case 2:
#ifdef CONFIG_FLOUNDER_BACKEND_UMP_IPI
if (err_is_ok(err)) {
goto out;
} else {
free(b->binding);
if (true) {
goto try_next_2;
} else {
// report permanent failure to user
_binding = NULL;
goto out;
}
}
try_next_2:
#endif // CONFIG_FLOUNDER_BACKEND_UMP_IPI
(b->driver_num)++;
#ifdef CONFIG_FLOUNDER_BACKEND_UMP
// try next backend
b->binding = malloc(sizeof(struct mem_ump_binding ));
assert((b->binding) != NULL);
err = mem_ump_bind(b->binding, b->iref, mem_bind_continuation_direct, b, b->waitset, b->flags, DEFAULT_UMP_BUFLEN, DEFAULT_UMP_BUFLEN);
if (err_is_fail(err)) {
free(b->binding);
_binding = NULL;
goto out;
} else {
return;
}
#else
// skip non-enabled backend (fall through)
#endif // CONFIG_FLOUNDER_BACKEND_UMP
case 3:
#ifdef CONFIG_FLOUNDER_BACKEND_UMP
if (err_is_ok(err)) {
goto out;
} else {
free(b->binding);
if (true) {
goto try_next_3;
} else {
// report permanent failure to user
_binding = NULL;
goto out;
}
}
try_next_3:
#endif // CONFIG_FLOUNDER_BACKEND_UMP
(b->driver_num)++;
#ifdef CONFIG_FLOUNDER_BACKEND_MULTIHOP
// try next backend
b->binding = malloc(sizeof(struct mem_multihop_binding ));
assert((b->binding) != NULL);
err = mem_multihop_bind(b->binding, b->iref, mem_bind_continuation_direct, b, b->waitset, b->flags);
if (err_is_fail(err)) {
free(b->binding);
_binding = NULL;
goto out;
} else {
return;
}
#else
// skip non-enabled backend (fall through)
#endif // CONFIG_FLOUNDER_BACKEND_MULTIHOP
case 4:
#ifdef CONFIG_FLOUNDER_BACKEND_MULTIHOP
if (err_is_ok(err)) {
goto out;
} else {
free(b->binding);
if (!true) {
_binding = NULL;
goto out;
}
}
#endif // CONFIG_FLOUNDER_BACKEND_MULTIHOP
err = FLOUNDER_ERR_GENERIC_BIND_NO_MORE_DRIVERS;
_binding = NULL;
goto out;
default:
assert(!("invalid state"));
}
out:
((mem_bind_continuation_fn *)(b->callback))(b->st, err, _binding);
free(b);
}
static void mem_bind_contination_multihop(void *st, errval_t err, struct mem_binding *_binding)
{
// This bind cont function uses the different backends in the following order:
// lmp multihop ump_ipi ump
struct flounder_generic_bind_attempt *b = st;
switch (b->driver_num) {
case 0:
(b->driver_num)++;
#ifdef CONFIG_FLOUNDER_BACKEND_LMP
// try next backend
b->binding = malloc(sizeof(struct mem_lmp_binding ));
assert((b->binding) != NULL);
err = mem_lmp_bind(b->binding, b->iref, mem_bind_contination_multihop, b, b->waitset, b->flags, DEFAULT_LMP_BUF_WORDS);
if (err_is_fail(err)) {
free(b->binding);
_binding = NULL;
goto out;
} else {
return;
}
#else
// skip non-enabled backend (fall through)
#endif // CONFIG_FLOUNDER_BACKEND_LMP
case 1:
#ifdef CONFIG_FLOUNDER_BACKEND_LMP
if (err_is_ok(err)) {
goto out;
} else {
free(b->binding);
if (err_no(err) == MON_ERR_IDC_BIND_NOT_SAME_CORE) {
goto try_next_1;
} else {
// report permanent failure to user
_binding = NULL;
goto out;
}
}
try_next_1:
#endif // CONFIG_FLOUNDER_BACKEND_LMP
(b->driver_num)++;
#ifdef CONFIG_FLOUNDER_BACKEND_MULTIHOP
// try next backend
b->binding = malloc(sizeof(struct mem_multihop_binding ));
assert((b->binding) != NULL);
err = mem_multihop_bind(b->binding, b->iref, mem_bind_contination_multihop, b, b->waitset, b->flags);
if (err_is_fail(err)) {
free(b->binding);
_binding = NULL;
goto out;
} else {
return;
}
#else
// skip non-enabled backend (fall through)
#endif // CONFIG_FLOUNDER_BACKEND_MULTIHOP
case 2:
#ifdef CONFIG_FLOUNDER_BACKEND_MULTIHOP
if (err_is_ok(err)) {
goto out;
} else {
free(b->binding);
if (true) {
goto try_next_2;
} else {
// report permanent failure to user
_binding = NULL;
goto out;
}
}
try_next_2:
#endif // CONFIG_FLOUNDER_BACKEND_MULTIHOP
(b->driver_num)++;
#ifdef CONFIG_FLOUNDER_BACKEND_UMP_IPI
// try next backend
b->binding = malloc(sizeof(struct mem_ump_ipi_binding ));
assert((b->binding) != NULL);
err = mem_ump_ipi_bind(b->binding, b->iref, mem_bind_contination_multihop, b, b->waitset, b->flags, DEFAULT_UMP_BUFLEN, DEFAULT_UMP_BUFLEN);
if (err_is_fail(err)) {
free(b->binding);
_binding = NULL;
goto out;
} else {
return;
}
#else
// skip non-enabled backend (fall through)
#endif // CONFIG_FLOUNDER_BACKEND_UMP_IPI
case 3:
#ifdef CONFIG_FLOUNDER_BACKEND_UMP_IPI
if (err_is_ok(err)) {
goto out;
} else {
free(b->binding);
if (true) {
goto try_next_3;
} else {
// report permanent failure to user
_binding = NULL;
goto out;
}
}
try_next_3:
#endif // CONFIG_FLOUNDER_BACKEND_UMP_IPI
(b->driver_num)++;
#ifdef CONFIG_FLOUNDER_BACKEND_UMP
// try next backend
b->binding = malloc(sizeof(struct mem_ump_binding ));
assert((b->binding) != NULL);
err = mem_ump_bind(b->binding, b->iref, mem_bind_contination_multihop, b, b->waitset, b->flags, DEFAULT_UMP_BUFLEN, DEFAULT_UMP_BUFLEN);
if (err_is_fail(err)) {
free(b->binding);
_binding = NULL;
goto out;
} else {
return;
}
#else
// skip non-enabled backend (fall through)
#endif // CONFIG_FLOUNDER_BACKEND_UMP
case 4:
#ifdef CONFIG_FLOUNDER_BACKEND_UMP
if (err_is_ok(err)) {
goto out;
} else {
free(b->binding);
if (!true) {
_binding = NULL;
goto out;
}
}
#endif // CONFIG_FLOUNDER_BACKEND_UMP
err = FLOUNDER_ERR_GENERIC_BIND_NO_MORE_DRIVERS;
_binding = NULL;
goto out;
default:
assert(!("invalid state"));
}
out:
((mem_bind_continuation_fn *)(b->callback))(b->st, err, _binding);
free(b);
}
errval_t mem_bind(iref_t iref, mem_bind_continuation_fn *_continuation, void *st, struct waitset *waitset, idc_bind_flags_t flags)
{
// allocate state
struct flounder_generic_bind_attempt *b = malloc(sizeof(struct flounder_generic_bind_attempt ));
if (b == NULL) {
return(LIB_ERR_MALLOC_FAIL);
}
// fill in binding state
b->iref = iref;
b->waitset = waitset;
b->driver_num = 0;
b->callback = _continuation;
b->st = st;
b->flags = flags;
if (flags & IDC_BIND_FLAG_MULTIHOP) {
mem_bind_contination_multihop(b, SYS_ERR_OK, NULL);
} else {
mem_bind_continuation_direct(b, SYS_ERR_OK, NULL);
}
return(SYS_ERR_OK);
}
/*
* Copyright (c) 2010, ETH Zurich.
* All rights reserved.
*
* INTERFACE NAME: mem
* INTEFACE FILE: ../if/mem.if
* INTERFACE DESCRIPTION: Memory allocation RPC interface
*
* This file is distributed under the terms in the attached LICENSE
* file. If you do not find this file, copies can be found by
* writing to:
* ETH Zurich D-INFK, Universitaetstr.6, CH-8092 Zurich.
* Attn: Systems Group.
*
* THIS FILE IS AUTOMATICALLY GENERATED BY FLOUNDER: DO NOT EDIT!
*/
/*
* Generated Stub for LMP on x86_64
*/
#include <string.h>
#include <barrelfish/barrelfish.h>
#include <flounder/flounder_support.h>
#include <flounder/flounder_support_lmp.h>
#include <if/mem_defs.h>
/*
* Send handler functions
*/
static void mem_allocate_call__lmp_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_lmp_binding *b = arg;
errval_t err;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
err = lmp_chan_send3(&(b->chan), b->flags, NULL_CAP, mem_allocate_call__msgnum | (((uintptr_t )(((_binding->tx_union).allocate_call).bits)) << 16), ((_binding->tx_union).allocate_call).minbase, ((_binding->tx_union).allocate_call).maxlimit);
if (err_is_ok(err)) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
} else {
break;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
if (lmp_err_is_transient(err)) {
// Construct retry closure and register it
struct event_closure retry_closure = (struct event_closure){ .handler = mem_allocate_call__lmp_send_handler, .arg = arg };
err = lmp_chan_register_send(&(b->chan), _binding->waitset, retry_closure);
assert(err_is_ok(err));
} else {
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
}
static void mem_allocate_response__lmp_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_lmp_binding *b = arg;
errval_t err;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
err = lmp_chan_send2(&(b->chan), b->flags, ((_binding->tx_union).allocate_response).mem_cap, mem_allocate_response__msgnum, ((_binding->tx_union).allocate_response).ret);
if (err_is_ok(err)) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
} else {
break;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
if (lmp_err_is_transient(err)) {
// Construct retry closure and register it
struct event_closure retry_closure = (struct event_closure){ .handler = mem_allocate_response__lmp_send_handler, .arg = arg };
err = lmp_chan_register_send(&(b->chan), _binding->waitset, retry_closure);
assert(err_is_ok(err));
} else {
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
}
static void mem_steal_call__lmp_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_lmp_binding *b = arg;
errval_t err;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
err = lmp_chan_send3(&(b->chan), b->flags, NULL_CAP, mem_steal_call__msgnum | (((uintptr_t )(((_binding->tx_union).steal_call).bits)) << 16), ((_binding->tx_union).steal_call).minbase, ((_binding->tx_union).steal_call).maxlimit);
if (err_is_ok(err)) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
} else {
break;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
if (lmp_err_is_transient(err)) {
// Construct retry closure and register it
struct event_closure retry_closure = (struct event_closure){ .handler = mem_steal_call__lmp_send_handler, .arg = arg };
err = lmp_chan_register_send(&(b->chan), _binding->waitset, retry_closure);
assert(err_is_ok(err));
} else {
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
}
static void mem_steal_response__lmp_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_lmp_binding *b = arg;
errval_t err;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
err = lmp_chan_send2(&(b->chan), b->flags, ((_binding->tx_union).steal_response).mem_cap, mem_steal_response__msgnum, ((_binding->tx_union).steal_response).ret);
if (err_is_ok(err)) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
} else {
break;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
if (lmp_err_is_transient(err)) {
// Construct retry closure and register it
struct event_closure retry_closure = (struct event_closure){ .handler = mem_steal_response__lmp_send_handler, .arg = arg };
err = lmp_chan_register_send(&(b->chan), _binding->waitset, retry_closure);
assert(err_is_ok(err));
} else {
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
}
static void mem_available_call__lmp_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_lmp_binding *b = arg;
errval_t err;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
err = lmp_chan_send1(&(b->chan), b->flags, NULL_CAP, mem_available_call__msgnum);
if (err_is_ok(err)) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
} else {
break;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
if (lmp_err_is_transient(err)) {
// Construct retry closure and register it
struct event_closure retry_closure = (struct event_closure){ .handler = mem_available_call__lmp_send_handler, .arg = arg };
err = lmp_chan_register_send(&(b->chan), _binding->waitset, retry_closure);
assert(err_is_ok(err));
} else {
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
}
static void mem_available_response__lmp_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_lmp_binding *b = arg;
errval_t err;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
err = lmp_chan_send3(&(b->chan), b->flags, NULL_CAP, mem_available_response__msgnum, ((_binding->tx_union).available_response).mem_avail, ((_binding->tx_union).available_response).mem_total);
if (err_is_ok(err)) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
} else {
break;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
if (lmp_err_is_transient(err)) {
// Construct retry closure and register it
struct event_closure retry_closure = (struct event_closure){ .handler = mem_available_response__lmp_send_handler, .arg = arg };
err = lmp_chan_register_send(&(b->chan), _binding->waitset, retry_closure);
assert(err_is_ok(err));
} else {
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
}
static void mem_free_monitor_call__lmp_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_lmp_binding *b = arg;
errval_t err;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
err = lmp_chan_send2(&(b->chan), b->flags, ((_binding->tx_union).free_monitor_call).mem_cap, mem_free_monitor_call__msgnum | (((uintptr_t )(((_binding->tx_union).free_monitor_call).bits)) << 16), ((_binding->tx_union).free_monitor_call).base);
if (err_is_ok(err)) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
} else {
break;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
if (lmp_err_is_transient(err)) {
// Construct retry closure and register it
struct event_closure retry_closure = (struct event_closure){ .handler = mem_free_monitor_call__lmp_send_handler, .arg = arg };
err = lmp_chan_register_send(&(b->chan), _binding->waitset, retry_closure);
assert(err_is_ok(err));
} else {
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
}
static void mem_free_monitor_response__lmp_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_lmp_binding *b = arg;
errval_t err;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
err = lmp_chan_send2(&(b->chan), b->flags, NULL_CAP, mem_free_monitor_response__msgnum, ((_binding->tx_union).free_monitor_response).err);
if (err_is_ok(err)) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
} else {
break;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
if (lmp_err_is_transient(err)) {
// Construct retry closure and register it
struct event_closure retry_closure = (struct event_closure){ .handler = mem_free_monitor_response__lmp_send_handler, .arg = arg };
err = lmp_chan_register_send(&(b->chan), _binding->waitset, retry_closure);
assert(err_is_ok(err));
} else {
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
}
/*
* Message sender functions
*/
static errval_t mem_allocate_call__lmp_send(struct mem_binding *_binding, struct event_closure _continuation, uint8_t bits, mem_genpaddr_t minbase, mem_genpaddr_t maxlimit)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_allocate_call__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).allocate_call).bits = bits;
((_binding->tx_union).allocate_call).minbase = minbase;
((_binding->tx_union).allocate_call).maxlimit = maxlimit;
FL_DEBUG("lmp TX mem.allocate_call\n");
// try to send!
mem_allocate_call__lmp_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_allocate_response__lmp_send(struct mem_binding *_binding, struct event_closure _continuation, mem_errval_t ret, struct capref mem_cap)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_allocate_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).allocate_response).ret = ret;
((_binding->tx_union).allocate_response).mem_cap = mem_cap;
FL_DEBUG("lmp TX mem.allocate_response\n");
// try to send!
mem_allocate_response__lmp_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_steal_call__lmp_send(struct mem_binding *_binding, struct event_closure _continuation, uint8_t bits, mem_genpaddr_t minbase, mem_genpaddr_t maxlimit)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_steal_call__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).steal_call).bits = bits;
((_binding->tx_union).steal_call).minbase = minbase;
((_binding->tx_union).steal_call).maxlimit = maxlimit;
FL_DEBUG("lmp TX mem.steal_call\n");
// try to send!
mem_steal_call__lmp_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_steal_response__lmp_send(struct mem_binding *_binding, struct event_closure _continuation, mem_errval_t ret, struct capref mem_cap)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_steal_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).steal_response).ret = ret;
((_binding->tx_union).steal_response).mem_cap = mem_cap;
FL_DEBUG("lmp TX mem.steal_response\n");
// try to send!
mem_steal_response__lmp_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_available_call__lmp_send(struct mem_binding *_binding, struct event_closure _continuation)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_available_call__msgnum;
_binding->tx_msg_fragment = 0;
FL_DEBUG("lmp TX mem.available_call\n");
// try to send!
mem_available_call__lmp_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_available_response__lmp_send(struct mem_binding *_binding, struct event_closure _continuation, mem_genpaddr_t mem_avail, mem_genpaddr_t mem_total)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_available_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).available_response).mem_avail = mem_avail;
((_binding->tx_union).available_response).mem_total = mem_total;
FL_DEBUG("lmp TX mem.available_response\n");
// try to send!
mem_available_response__lmp_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_free_monitor_call__lmp_send(struct mem_binding *_binding, struct event_closure _continuation, struct capref mem_cap, mem_genpaddr_t base, uint8_t bits)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_free_monitor_call__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).free_monitor_call).mem_cap = mem_cap;
((_binding->tx_union).free_monitor_call).base = base;
((_binding->tx_union).free_monitor_call).bits = bits;
FL_DEBUG("lmp TX mem.free_monitor_call\n");
// try to send!
mem_free_monitor_call__lmp_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_free_monitor_response__lmp_send(struct mem_binding *_binding, struct event_closure _continuation, mem_errval_t err)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_free_monitor_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).free_monitor_response).err = err;
FL_DEBUG("lmp TX mem.free_monitor_response\n");
// try to send!
mem_free_monitor_response__lmp_send_handler(_binding);
return(SYS_ERR_OK);
}
/*
* Send vtable
*/
static struct mem_tx_vtbl mem_lmp_tx_vtbl = {
.allocate_call = mem_allocate_call__lmp_send,
.allocate_response = mem_allocate_response__lmp_send,
.steal_call = mem_steal_call__lmp_send,
.steal_response = mem_steal_response__lmp_send,
.available_call = mem_available_call__lmp_send,
.available_response = mem_available_response__lmp_send,
.free_monitor_call = mem_free_monitor_call__lmp_send,
.free_monitor_response = mem_free_monitor_response__lmp_send,
};
/*
* Receive handler
*/
void mem_lmp_rx_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_lmp_binding *b = arg;
errval_t err;
struct lmp_recv_msg msg = LMP_RECV_MSG_INIT;
struct capref cap;
struct event_closure recv_closure = (struct event_closure){ .handler = mem_lmp_rx_handler, .arg = arg };
do {
// try to retrieve a message from the channel
err = lmp_chan_recv(&(b->chan), &msg, &cap);
// check if we succeeded
if (err_is_fail(err)) {
if (err_no(err) == LIB_ERR_NO_LMP_MSG) {
// no message
break;
} else {
// real error
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_LMP_CHAN_RECV));
return;
}
}
// allocate a new receive slot if needed
if (!capref_is_null(cap)) {
err = lmp_chan_alloc_recv_slot(&(b->chan));
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_LMP_ALLOC_RECV_SLOT));
}
}
// is this the start of a new message?
if ((_binding->rx_msgnum) == 0) {
// check message length
if (((msg.buf).msglen) == 0) {
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_EMPTY_MSG);
break;
}
// unmarshall message number from first word, set fragment to 0
_binding->rx_msgnum = (((msg.words)[0]) & 0xffff);
_binding->rx_msg_fragment = 0;
}
// switch on message number and fragment number
switch (_binding->rx_msgnum) {
case mem_allocate_call__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
// check length
if (((msg.buf).msglen) > 4) {
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_LENGTH);
goto out;
}
((_binding->rx_union).allocate_call).bits = ((((msg.words)[0]) >> 16) & 0xff);
((_binding->rx_union).allocate_call).minbase = ((msg.words)[1]);
((_binding->rx_union).allocate_call).maxlimit = ((msg.words)[2]);
FL_DEBUG("lmp RX mem.allocate_call\n");
assert(((_binding->rx_vtbl).allocate_call) != NULL);
((_binding->rx_vtbl).allocate_call)(_binding, ((_binding->rx_union).allocate_call).bits, ((_binding->rx_union).allocate_call).minbase, ((_binding->rx_union).allocate_call).maxlimit);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_allocate_response__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
// check length
if (((msg.buf).msglen) > 4) {
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_LENGTH);
goto out;
}
((_binding->rx_union).allocate_response).ret = ((msg.words)[1]);
((_binding->rx_union).allocate_response).mem_cap = cap;
FL_DEBUG("lmp RX mem.allocate_response\n");
assert(((_binding->rx_vtbl).allocate_response) != NULL);
((_binding->rx_vtbl).allocate_response)(_binding, ((_binding->rx_union).allocate_response).ret, ((_binding->rx_union).allocate_response).mem_cap);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_steal_call__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
// check length
if (((msg.buf).msglen) > 4) {
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_LENGTH);
goto out;
}
((_binding->rx_union).steal_call).bits = ((((msg.words)[0]) >> 16) & 0xff);
((_binding->rx_union).steal_call).minbase = ((msg.words)[1]);
((_binding->rx_union).steal_call).maxlimit = ((msg.words)[2]);
FL_DEBUG("lmp RX mem.steal_call\n");
assert(((_binding->rx_vtbl).steal_call) != NULL);
((_binding->rx_vtbl).steal_call)(_binding, ((_binding->rx_union).steal_call).bits, ((_binding->rx_union).steal_call).minbase, ((_binding->rx_union).steal_call).maxlimit);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_steal_response__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
// check length
if (((msg.buf).msglen) > 4) {
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_LENGTH);
goto out;
}
((_binding->rx_union).steal_response).ret = ((msg.words)[1]);
((_binding->rx_union).steal_response).mem_cap = cap;
FL_DEBUG("lmp RX mem.steal_response\n");
assert(((_binding->rx_vtbl).steal_response) != NULL);
((_binding->rx_vtbl).steal_response)(_binding, ((_binding->rx_union).steal_response).ret, ((_binding->rx_union).steal_response).mem_cap);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_available_call__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
// check length
if (((msg.buf).msglen) > 4) {
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_LENGTH);
goto out;
}
FL_DEBUG("lmp RX mem.available_call\n");
assert(((_binding->rx_vtbl).available_call) != NULL);
((_binding->rx_vtbl).available_call)(_binding);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_available_response__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
// check length
if (((msg.buf).msglen) > 4) {
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_LENGTH);
goto out;
}
((_binding->rx_union).available_response).mem_avail = ((msg.words)[1]);
((_binding->rx_union).available_response).mem_total = ((msg.words)[2]);
FL_DEBUG("lmp RX mem.available_response\n");
assert(((_binding->rx_vtbl).available_response) != NULL);
((_binding->rx_vtbl).available_response)(_binding, ((_binding->rx_union).available_response).mem_avail, ((_binding->rx_union).available_response).mem_total);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_free_monitor_call__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
// check length
if (((msg.buf).msglen) > 4) {
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_LENGTH);
goto out;
}
((_binding->rx_union).free_monitor_call).bits = ((((msg.words)[0]) >> 16) & 0xff);
((_binding->rx_union).free_monitor_call).base = ((msg.words)[1]);
((_binding->rx_union).free_monitor_call).mem_cap = cap;
FL_DEBUG("lmp RX mem.free_monitor_call\n");
assert(((_binding->rx_vtbl).free_monitor_call) != NULL);
((_binding->rx_vtbl).free_monitor_call)(_binding, ((_binding->rx_union).free_monitor_call).mem_cap, ((_binding->rx_union).free_monitor_call).base, ((_binding->rx_union).free_monitor_call).bits);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_free_monitor_response__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
// check length
if (((msg.buf).msglen) > 4) {
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_LENGTH);
goto out;
}
((_binding->rx_union).free_monitor_response).err = ((msg.words)[1]);
FL_DEBUG("lmp RX mem.free_monitor_response\n");
assert(((_binding->rx_vtbl).free_monitor_response) != NULL);
((_binding->rx_vtbl).free_monitor_response)(_binding, ((_binding->rx_union).free_monitor_response).err);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_MSGNUM);
goto out;
}
} while (err_is_ok(err));
out:
// re-register for another receive notification
err = lmp_chan_register_recv(&(b->chan), _binding->waitset, recv_closure);
assert(err_is_ok(err));
}
/*
* Control functions
*/
static bool mem_lmp_can_send(struct mem_binding *b)
{
return((b->tx_msgnum) == 0);
}
static errval_t mem_lmp_register_send(struct mem_binding *b, struct waitset *ws, struct event_closure _continuation)
{
return(flounder_support_register(ws, &(b->register_chanstate), _continuation, mem_lmp_can_send(b)));
}
static void mem_lmp_default_error_handler(struct mem_binding *b, errval_t err)
{
DEBUG_ERR(err, "asynchronous error in Flounder-generated mem lmp binding (default handler)");
abort();
}
static errval_t mem_lmp_change_waitset(struct mem_binding *_binding, struct waitset *ws)
{
struct mem_lmp_binding *b = (void *)(_binding);
// Migrate register and TX continuation notifications
flounder_support_migrate_notify(&(_binding->register_chanstate), ws);
flounder_support_migrate_notify(&(_binding->tx_cont_chanstate), ws);
// change waitset on binding
_binding->waitset = ws;
// Migrate send and receive notifications
lmp_chan_migrate_recv(&(b->chan), ws);
lmp_chan_migrate_send(&(b->chan), ws);
return(SYS_ERR_OK);
}
static errval_t mem_lmp_control(struct mem_binding *_binding, idc_control_t control)
{
struct mem_lmp_binding *b = (void *)(_binding);
b->flags = idc_control_to_lmp_flags(control, b->flags);
return(SYS_ERR_OK);
}
/*
* Functions to initialise/destroy the binding state
*/
void mem_lmp_init(struct mem_lmp_binding *b, struct waitset *waitset)
{
(b->b).st = NULL;
(b->b).waitset = waitset;
event_mutex_init(&((b->b).mutex), waitset);
(b->b).can_send = mem_lmp_can_send;
(b->b).register_send = mem_lmp_register_send;
(b->b).error_handler = mem_lmp_default_error_handler;
(b->b).tx_vtbl = mem_lmp_tx_vtbl;
memset(&((b->b).rx_vtbl), 0, sizeof((b->b).rx_vtbl));
flounder_support_waitset_chanstate_init(&((b->b).register_chanstate));
flounder_support_waitset_chanstate_init(&((b->b).tx_cont_chanstate));
(b->b).tx_msgnum = 0;
(b->b).rx_msgnum = 0;
(b->b).tx_msg_fragment = 0;
(b->b).rx_msg_fragment = 0;
(b->b).tx_str_pos = 0;
(b->b).rx_str_pos = 0;
(b->b).tx_str_len = 0;
(b->b).rx_str_len = 0;
(b->b).bind_cont = NULL;
lmp_chan_init(&(b->chan));
(b->b).change_waitset = mem_lmp_change_waitset;
(b->b).control = mem_lmp_control;
b->flags = LMP_SEND_FLAGS_DEFAULT;
}
void mem_lmp_destroy(struct mem_lmp_binding *b)
{
flounder_support_waitset_chanstate_destroy(&((b->b).register_chanstate));
flounder_support_waitset_chanstate_destroy(&((b->b).tx_cont_chanstate));
lmp_chan_destroy(&(b->chan));
}
/*
* Bind function
*/
static void mem_lmp_bind_continuation(void *st, errval_t err, struct lmp_chan *chan)
{
struct mem_lmp_binding *b = st;
if (err_is_ok(err)) {
// allocate a cap receive slot
err = lmp_chan_alloc_recv_slot(chan);
if (err_is_fail(err)) {
err = err_push(err, LIB_ERR_LMP_ALLOC_RECV_SLOT);
goto fail;
}
// register for receive
err = lmp_chan_register_recv(chan, (b->b).waitset, (struct event_closure){ .handler = mem_lmp_rx_handler, .arg = b });
if (err_is_fail(err)) {
err = err_push(err, LIB_ERR_CHAN_REGISTER_RECV);
goto fail;
}
} else {
fail:
mem_lmp_destroy(b);
}
((b->b).bind_cont)((b->b).st, err, &(b->b));
}
errval_t mem_lmp_bind(struct mem_lmp_binding *b, iref_t iref, mem_bind_continuation_fn *_continuation, void *st, struct waitset *waitset, idc_bind_flags_t flags, size_t lmp_buflen)
{
errval_t err;
mem_lmp_init(b, waitset);
(b->b).st = st;
(b->b).bind_cont = _continuation;
err = lmp_chan_bind(&(b->chan), (struct lmp_bind_continuation){ .handler = mem_lmp_bind_continuation, .st = b }, &((b->b).event_qnode), iref, lmp_buflen);
if (err_is_fail(err)) {
mem_lmp_destroy(b);
}
return(err);
}
/*
* Connect callback for export
*/
errval_t mem_lmp_connect_handler(void *st, size_t buflen_words, struct capref endpoint, struct lmp_chan **retchan)
{
struct mem_export *e = st;
errval_t err;
// allocate storage for binding
struct mem_lmp_binding *b = malloc(sizeof(struct mem_lmp_binding ));
if (b == NULL) {
return(LIB_ERR_MALLOC_FAIL);
}
struct mem_binding *_binding = &(b->b);
mem_lmp_init(b, e->waitset);
// run user's connect handler
err = ((e->connect_cb)(e->st, _binding));
if (err_is_fail(err)) {
// connection refused
mem_lmp_destroy(b);
return(err);
}
// accept the connection and setup the channel
// FIXME: user policy needed to decide on the size of the message buffer?
err = lmp_chan_accept(&(b->chan), buflen_words, endpoint);
if (err_is_fail(err)) {
err = err_push(err, LIB_ERR_LMP_CHAN_ACCEPT);
(_binding->error_handler)(_binding, err);
return(err);
}
// allocate a cap receive slot
err = lmp_chan_alloc_recv_slot(&(b->chan));
if (err_is_fail(err)) {
err = err_push(err, LIB_ERR_LMP_ALLOC_RECV_SLOT);
(_binding->error_handler)(_binding, err);
return(err);
}
// register for receive
err = lmp_chan_register_recv(&(b->chan), _binding->waitset, (struct event_closure){ .handler = mem_lmp_rx_handler, .arg = b });
if (err_is_fail(err)) {
err = err_push(err, LIB_ERR_CHAN_REGISTER_RECV);
(_binding->error_handler)(_binding, err);
return(err);
}
*retchan = (&(b->chan));
return(SYS_ERR_OK);
}
/*
* Copyright (c) 2010, ETH Zurich.
* All rights reserved.
*
* INTERFACE NAME: mem
* INTEFACE FILE: ../if/mem.if
* INTERFACE DESCRIPTION: Memory allocation RPC interface
*
* This file is distributed under the terms in the attached LICENSE
* file. If you do not find this file, copies can be found by
* writing to:
* ETH Zurich D-INFK, Universitaetstr.6, CH-8092 Zurich.
* Attn: Systems Group.
*
* THIS FILE IS AUTOMATICALLY GENERATED BY FLOUNDER: DO NOT EDIT!
*/
#ifdef CONFIG_FLOUNDER_BACKEND_UMP
/*
* Generated Stub for UMP
*/
#include <barrelfish/barrelfish.h>
#include <barrelfish/monitor_client.h>
#include <flounder/flounder_support.h>
#include <flounder/flounder_support_ump.h>
#include <if/mem_defs.h>
/*
* Send handler function
*/
static void mem_ump_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_ump_binding *b = arg;
errval_t err;
err = SYS_ERR_OK;
volatile struct ump_message *msg;
struct ump_control ctrl;
bool tx_notify = false;
// do we need to (and can we) send a cap ack?
if ((((b->ump_state).capst).tx_cap_ack) && flounder_stub_ump_can_send(&(b->ump_state))) {
flounder_stub_ump_send_cap_ack(&(b->ump_state));
((b->ump_state).capst).tx_cap_ack = false;
tx_notify = true;
}
// Switch on current outgoing message number
switch (_binding->tx_msgnum) {
case 0:
break;
case mem_allocate_call__msgnum:
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// check if we can send another message
if (!flounder_stub_ump_can_send(&(b->ump_state))) {
tx_notify = true;
break;
}
// send the next fragment
msg = ump_chan_get_next(&((b->ump_state).chan), &ctrl);
flounder_stub_ump_control_fill(&(b->ump_state), &ctrl, mem_allocate_call__msgnum);
(msg->data)[0] = (((_binding->tx_union).allocate_call).bits);
(msg->data)[1] = (((_binding->tx_union).allocate_call).minbase);
(msg->data)[2] = (((_binding->tx_union).allocate_call).maxlimit);
flounder_stub_ump_barrier();
(msg->header).control = ctrl;
(_binding->tx_msg_fragment)++;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
case 1:
// we've sent all the fragments, we must just be waiting for caps
assert((((b->ump_state).capst).tx_capnum) <= 0);
break;
default:
assert(!("invalid fragment"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_allocate_response__msgnum:
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// check if we can send another message
if (!flounder_stub_ump_can_send(&(b->ump_state))) {
tx_notify = true;
break;
}
// send the next fragment
msg = ump_chan_get_next(&((b->ump_state).chan), &ctrl);
flounder_stub_ump_control_fill(&(b->ump_state), &ctrl, mem_allocate_response__msgnum);
(msg->data)[0] = (((_binding->tx_union).allocate_response).ret);
flounder_stub_ump_barrier();
(msg->header).control = ctrl;
(_binding->tx_msg_fragment)++;
if ((((b->ump_state).capst).tx_capnum) == 2) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
return;
case 1:
// we've sent all the fragments, we must just be waiting for caps
assert((((b->ump_state).capst).tx_capnum) <= 1);
break;
default:
assert(!("invalid fragment"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_steal_call__msgnum:
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// check if we can send another message
if (!flounder_stub_ump_can_send(&(b->ump_state))) {
tx_notify = true;
break;
}
// send the next fragment
msg = ump_chan_get_next(&((b->ump_state).chan), &ctrl);
flounder_stub_ump_control_fill(&(b->ump_state), &ctrl, mem_steal_call__msgnum);
(msg->data)[0] = (((_binding->tx_union).steal_call).bits);
(msg->data)[1] = (((_binding->tx_union).steal_call).minbase);
(msg->data)[2] = (((_binding->tx_union).steal_call).maxlimit);
flounder_stub_ump_barrier();
(msg->header).control = ctrl;
(_binding->tx_msg_fragment)++;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
case 1:
// we've sent all the fragments, we must just be waiting for caps
assert((((b->ump_state).capst).tx_capnum) <= 0);
break;
default:
assert(!("invalid fragment"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_steal_response__msgnum:
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// check if we can send another message
if (!flounder_stub_ump_can_send(&(b->ump_state))) {
tx_notify = true;
break;
}
// send the next fragment
msg = ump_chan_get_next(&((b->ump_state).chan), &ctrl);
flounder_stub_ump_control_fill(&(b->ump_state), &ctrl, mem_steal_response__msgnum);
(msg->data)[0] = (((_binding->tx_union).steal_response).ret);
flounder_stub_ump_barrier();
(msg->header).control = ctrl;
(_binding->tx_msg_fragment)++;
if ((((b->ump_state).capst).tx_capnum) == 2) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
return;
case 1:
// we've sent all the fragments, we must just be waiting for caps
assert((((b->ump_state).capst).tx_capnum) <= 1);
break;
default:
assert(!("invalid fragment"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_available_call__msgnum:
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// check if we can send another message
if (!flounder_stub_ump_can_send(&(b->ump_state))) {
tx_notify = true;
break;
}
// send the next fragment
msg = ump_chan_get_next(&((b->ump_state).chan), &ctrl);
flounder_stub_ump_control_fill(&(b->ump_state), &ctrl, mem_available_call__msgnum);
flounder_stub_ump_barrier();
(msg->header).control = ctrl;
(_binding->tx_msg_fragment)++;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
case 1:
// we've sent all the fragments, we must just be waiting for caps
assert((((b->ump_state).capst).tx_capnum) <= 0);
break;
default:
assert(!("invalid fragment"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_available_response__msgnum:
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// check if we can send another message
if (!flounder_stub_ump_can_send(&(b->ump_state))) {
tx_notify = true;
break;
}
// send the next fragment
msg = ump_chan_get_next(&((b->ump_state).chan), &ctrl);
flounder_stub_ump_control_fill(&(b->ump_state), &ctrl, mem_available_response__msgnum);
(msg->data)[0] = (((_binding->tx_union).available_response).mem_avail);
(msg->data)[1] = (((_binding->tx_union).available_response).mem_total);
flounder_stub_ump_barrier();
(msg->header).control = ctrl;
(_binding->tx_msg_fragment)++;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
case 1:
// we've sent all the fragments, we must just be waiting for caps
assert((((b->ump_state).capst).tx_capnum) <= 0);
break;
default:
assert(!("invalid fragment"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_free_monitor_call__msgnum:
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// check if we can send another message
if (!flounder_stub_ump_can_send(&(b->ump_state))) {
tx_notify = true;
break;
}
// send the next fragment
msg = ump_chan_get_next(&((b->ump_state).chan), &ctrl);
flounder_stub_ump_control_fill(&(b->ump_state), &ctrl, mem_free_monitor_call__msgnum);
(msg->data)[0] = (((_binding->tx_union).free_monitor_call).bits);
(msg->data)[1] = (((_binding->tx_union).free_monitor_call).base);
flounder_stub_ump_barrier();
(msg->header).control = ctrl;
(_binding->tx_msg_fragment)++;
if ((((b->ump_state).capst).tx_capnum) == 2) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
return;
case 1:
// we've sent all the fragments, we must just be waiting for caps
assert((((b->ump_state).capst).tx_capnum) <= 1);
break;
default:
assert(!("invalid fragment"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_free_monitor_response__msgnum:
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// check if we can send another message
if (!flounder_stub_ump_can_send(&(b->ump_state))) {
tx_notify = true;
break;
}
// send the next fragment
msg = ump_chan_get_next(&((b->ump_state).chan), &ctrl);
flounder_stub_ump_control_fill(&(b->ump_state), &ctrl, mem_free_monitor_response__msgnum);
(msg->data)[0] = (((_binding->tx_union).free_monitor_response).err);
flounder_stub_ump_barrier();
(msg->header).control = ctrl;
(_binding->tx_msg_fragment)++;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
case 1:
// we've sent all the fragments, we must just be waiting for caps
assert((((b->ump_state).capst).tx_capnum) <= 0);
break;
default:
assert(!("invalid fragment"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
default:
assert(!("invalid msgnum"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
// Send a notification if necessary
if (tx_notify) {
}
}
/*
* Capability sender function
*/
static void mem_ump_cap_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_ump_binding *b = arg;
errval_t err;
err = SYS_ERR_OK;
assert(((b->ump_state).capst).rx_cap_ack);
assert(((b->ump_state).capst).monitor_mutex_held);
// Switch on current outgoing message
switch (_binding->tx_msgnum) {
case mem_allocate_response__msgnum:
// Switch on current outgoing cap
switch (((b->ump_state).capst).tx_capnum) {
case 0:
err = flounder_stub_send_cap(&((b->ump_state).capst), ((b->ump_state).chan).monitor_binding, ((b->ump_state).chan).monitor_id, ((_binding->tx_union).allocate_response).mem_cap, true, mem_ump_cap_send_handler);
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
break;
}
break;
case 1:
flounder_support_monitor_mutex_unlock(((b->ump_state).chan).monitor_binding);
if ((_binding->tx_msg_fragment) == 1) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
break;
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_steal_response__msgnum:
// Switch on current outgoing cap
switch (((b->ump_state).capst).tx_capnum) {
case 0:
err = flounder_stub_send_cap(&((b->ump_state).capst), ((b->ump_state).chan).monitor_binding, ((b->ump_state).chan).monitor_id, ((_binding->tx_union).steal_response).mem_cap, true, mem_ump_cap_send_handler);
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
break;
}
break;
case 1:
flounder_support_monitor_mutex_unlock(((b->ump_state).chan).monitor_binding);
if ((_binding->tx_msg_fragment) == 1) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
break;
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_free_monitor_call__msgnum:
// Switch on current outgoing cap
switch (((b->ump_state).capst).tx_capnum) {
case 0:
err = flounder_stub_send_cap(&((b->ump_state).capst), ((b->ump_state).chan).monitor_binding, ((b->ump_state).chan).monitor_id, ((_binding->tx_union).free_monitor_call).mem_cap, true, mem_ump_cap_send_handler);
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
break;
}
break;
case 1:
flounder_support_monitor_mutex_unlock(((b->ump_state).chan).monitor_binding);
if ((_binding->tx_msg_fragment) == 1) {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
break;
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
default:
assert(!("invalid message number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
}
/*
* Receive handler
*/
void mem_ump_rx_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_ump_binding *b = arg;
errval_t err;
err = SYS_ERR_OK;
volatile struct ump_message *msg;
int msgnum;
while (true) {
// try to retrieve a message from the channel
err = ump_chan_recv(&((b->ump_state).chan), &msg);
// check if we succeeded
if (err_is_fail(err)) {
if (err_no(err) == LIB_ERR_NO_UMP_MSG) {
// no message
break;
} else {
// real error
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_UMP_CHAN_RECV));
return;
}
}
// process control word
msgnum = flounder_stub_ump_control_process(&(b->ump_state), (msg->header).control);
// is this a dummy message (ACK)?
if (msgnum == FL_UMP_ACK) {
goto loopnext;
}
// is this a cap ack for a pending tx message
if (msgnum == FL_UMP_CAP_ACK) {
assert(!(((b->ump_state).capst).rx_cap_ack));
((b->ump_state).capst).rx_cap_ack = true;
if (((b->ump_state).capst).monitor_mutex_held) {
mem_ump_cap_send_handler(b);
}
goto loopnext;
}
// is this the start of a new message?
if ((_binding->rx_msgnum) == 0) {
_binding->rx_msgnum = msgnum;
_binding->rx_msg_fragment = 0;
}
// switch on message number and fragment number
switch (_binding->rx_msgnum) {
case mem_allocate_call__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
((_binding->rx_union).allocate_call).bits = (((msg->data)[0]) & 0xff);
((_binding->rx_union).allocate_call).minbase = ((msg->data)[1]);
((_binding->rx_union).allocate_call).maxlimit = ((msg->data)[2]);
FL_DEBUG("ump RX mem.allocate_call\n");
assert(((_binding->rx_vtbl).allocate_call) != NULL);
((_binding->rx_vtbl).allocate_call)(_binding, ((_binding->rx_union).allocate_call).bits, ((_binding->rx_union).allocate_call).minbase, ((_binding->rx_union).allocate_call).maxlimit);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_allocate_response__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
((b->ump_state).capst).tx_cap_ack = true;
((b->ump_state).capst).rx_capnum = 0;
((_binding->rx_union).allocate_response).ret = ((msg->data)[0]);
(_binding->rx_msg_fragment)++;
if ((((b->ump_state).capst).rx_capnum) == 1) {
FL_DEBUG("ump RX mem.allocate_response\n");
assert(((_binding->rx_vtbl).allocate_response) != NULL);
((_binding->rx_vtbl).allocate_response)(_binding, ((_binding->rx_union).allocate_response).ret, ((_binding->rx_union).allocate_response).mem_cap);
_binding->rx_msgnum = 0;
} else {
// don't process anything else until we're done
goto out_no_reregister;
}
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_steal_call__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
((_binding->rx_union).steal_call).bits = (((msg->data)[0]) & 0xff);
((_binding->rx_union).steal_call).minbase = ((msg->data)[1]);
((_binding->rx_union).steal_call).maxlimit = ((msg->data)[2]);
FL_DEBUG("ump RX mem.steal_call\n");
assert(((_binding->rx_vtbl).steal_call) != NULL);
((_binding->rx_vtbl).steal_call)(_binding, ((_binding->rx_union).steal_call).bits, ((_binding->rx_union).steal_call).minbase, ((_binding->rx_union).steal_call).maxlimit);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_steal_response__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
((b->ump_state).capst).tx_cap_ack = true;
((b->ump_state).capst).rx_capnum = 0;
((_binding->rx_union).steal_response).ret = ((msg->data)[0]);
(_binding->rx_msg_fragment)++;
if ((((b->ump_state).capst).rx_capnum) == 1) {
FL_DEBUG("ump RX mem.steal_response\n");
assert(((_binding->rx_vtbl).steal_response) != NULL);
((_binding->rx_vtbl).steal_response)(_binding, ((_binding->rx_union).steal_response).ret, ((_binding->rx_union).steal_response).mem_cap);
_binding->rx_msgnum = 0;
} else {
// don't process anything else until we're done
goto out_no_reregister;
}
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_available_call__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
FL_DEBUG("ump RX mem.available_call\n");
assert(((_binding->rx_vtbl).available_call) != NULL);
((_binding->rx_vtbl).available_call)(_binding);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_available_response__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
((_binding->rx_union).available_response).mem_avail = ((msg->data)[0]);
((_binding->rx_union).available_response).mem_total = ((msg->data)[1]);
FL_DEBUG("ump RX mem.available_response\n");
assert(((_binding->rx_vtbl).available_response) != NULL);
((_binding->rx_vtbl).available_response)(_binding, ((_binding->rx_union).available_response).mem_avail, ((_binding->rx_union).available_response).mem_total);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_free_monitor_call__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
((b->ump_state).capst).tx_cap_ack = true;
((b->ump_state).capst).rx_capnum = 0;
((_binding->rx_union).free_monitor_call).bits = (((msg->data)[0]) & 0xff);
((_binding->rx_union).free_monitor_call).base = ((msg->data)[1]);
(_binding->rx_msg_fragment)++;
if ((((b->ump_state).capst).rx_capnum) == 1) {
FL_DEBUG("ump RX mem.free_monitor_call\n");
assert(((_binding->rx_vtbl).free_monitor_call) != NULL);
((_binding->rx_vtbl).free_monitor_call)(_binding, ((_binding->rx_union).free_monitor_call).mem_cap, ((_binding->rx_union).free_monitor_call).base, ((_binding->rx_union).free_monitor_call).bits);
_binding->rx_msgnum = 0;
} else {
// don't process anything else until we're done
goto out_no_reregister;
}
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
case mem_free_monitor_response__msgnum:
switch (_binding->rx_msg_fragment) {
case 0:
((_binding->rx_union).free_monitor_response).err = ((msg->data)[0]);
FL_DEBUG("ump RX mem.free_monitor_response\n");
assert(((_binding->rx_vtbl).free_monitor_response) != NULL);
((_binding->rx_vtbl).free_monitor_response)(_binding, ((_binding->rx_union).free_monitor_response).err);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
goto out;
}
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_MSGNUM);
goto out;
}
loopnext:
// send an ack if the channel is now full
if (flounder_stub_ump_needs_ack(&(b->ump_state))) {
// run our send process if we need to
if ((((b->ump_state).capst).tx_cap_ack) || ((_binding->tx_msgnum) != 0)) {
mem_ump_send_handler(b);
} else {
flounder_stub_ump_send_ack(&(b->ump_state));
}
}
}
out:
// register for receive notification
err = ump_chan_register_recv(&((b->ump_state).chan), _binding->waitset, (struct event_closure){ .handler = mem_ump_rx_handler, .arg = _binding });
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_CHAN_REGISTER_RECV));
}
out_no_reregister:
__attribute__((unused));
// run our send process, if we need to
if ((((b->ump_state).capst).tx_cap_ack) || ((_binding->tx_msgnum) != 0)) {
mem_ump_send_handler(b);
} else {
// otherwise send a forced ack if the channel is now full
if (flounder_stub_ump_needs_ack(&(b->ump_state))) {
flounder_stub_ump_send_ack(&(b->ump_state));
}
}
}
/*
* Cap send/receive handlers
*/
static void mem_ump_cap_rx_handler(void *arg, errval_t success, struct capref cap, uint32_t capid)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_ump_binding *b = arg;
errval_t err;
err = SYS_ERR_OK;
assert(capid == (((b->ump_state).capst).rx_capnum));
// Check if there's an associated error
// FIXME: how should we report this to the user? at present we just deliver a NULL capref
if (err_is_fail(success)) {
DEBUG_ERR(err, "error in cap transfer");
}
// Switch on current incoming message
switch (_binding->rx_msgnum) {
case mem_allocate_response__msgnum:
// Switch on current incoming cap
switch ((((b->ump_state).capst).rx_capnum)++) {
case 0:
((_binding->rx_union).allocate_response).mem_cap = cap;
if ((_binding->rx_msg_fragment) == 1) {
FL_DEBUG("ump RX mem.allocate_response\n");
assert(((_binding->rx_vtbl).allocate_response) != NULL);
((_binding->rx_vtbl).allocate_response)(_binding, ((_binding->rx_union).allocate_response).ret, ((_binding->rx_union).allocate_response).mem_cap);
_binding->rx_msgnum = 0;
// register for receive notification
err = ump_chan_register_recv(&((b->ump_state).chan), _binding->waitset, (struct event_closure){ .handler = mem_ump_rx_handler, .arg = _binding });
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_CHAN_REGISTER_RECV));
}
}
break;
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_steal_response__msgnum:
// Switch on current incoming cap
switch ((((b->ump_state).capst).rx_capnum)++) {
case 0:
((_binding->rx_union).steal_response).mem_cap = cap;
if ((_binding->rx_msg_fragment) == 1) {
FL_DEBUG("ump RX mem.steal_response\n");
assert(((_binding->rx_vtbl).steal_response) != NULL);
((_binding->rx_vtbl).steal_response)(_binding, ((_binding->rx_union).steal_response).ret, ((_binding->rx_union).steal_response).mem_cap);
_binding->rx_msgnum = 0;
// register for receive notification
err = ump_chan_register_recv(&((b->ump_state).chan), _binding->waitset, (struct event_closure){ .handler = mem_ump_rx_handler, .arg = _binding });
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_CHAN_REGISTER_RECV));
}
}
break;
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_free_monitor_call__msgnum:
// Switch on current incoming cap
switch ((((b->ump_state).capst).rx_capnum)++) {
case 0:
((_binding->rx_union).free_monitor_call).mem_cap = cap;
if ((_binding->rx_msg_fragment) == 1) {
FL_DEBUG("ump RX mem.free_monitor_call\n");
assert(((_binding->rx_vtbl).free_monitor_call) != NULL);
((_binding->rx_vtbl).free_monitor_call)(_binding, ((_binding->rx_union).free_monitor_call).mem_cap, ((_binding->rx_union).free_monitor_call).base, ((_binding->rx_union).free_monitor_call).bits);
_binding->rx_msgnum = 0;
// register for receive notification
err = ump_chan_register_recv(&((b->ump_state).chan), _binding->waitset, (struct event_closure){ .handler = mem_ump_rx_handler, .arg = _binding });
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_CHAN_REGISTER_RECV));
}
}
break;
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
default:
assert(!("invalid message number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
}
/*
* Monitor mutex acquire continuation
*/
static void mem_ump_monitor_mutex_cont(void *arg)
{
struct mem_ump_binding *b = arg;
assert(!(((b->ump_state).capst).monitor_mutex_held));
((b->ump_state).capst).monitor_mutex_held = true;
if (((b->ump_state).capst).rx_cap_ack) {
mem_ump_cap_send_handler(b);
}
}
/*
* Message sender functions
*/
static errval_t mem_allocate_call__ump_send(struct mem_binding *_binding, struct event_closure _continuation, uint8_t bits, mem_genpaddr_t minbase, mem_genpaddr_t maxlimit)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_allocate_call__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).allocate_call).bits = bits;
((_binding->tx_union).allocate_call).minbase = minbase;
((_binding->tx_union).allocate_call).maxlimit = maxlimit;
FL_DEBUG("ump TX mem.allocate_call\n");
// try to send!
mem_ump_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_allocate_response__ump_send(struct mem_binding *_binding, struct event_closure _continuation, mem_errval_t ret, struct capref mem_cap)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_allocate_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).allocate_response).ret = ret;
((_binding->tx_union).allocate_response).mem_cap = mem_cap;
FL_DEBUG("ump TX mem.allocate_response\n");
// init cap send state
((((struct mem_ump_binding *)(_binding))->ump_state).capst).tx_capnum = 0;
((((struct mem_ump_binding *)(_binding))->ump_state).capst).rx_cap_ack = false;
((((struct mem_ump_binding *)(_binding))->ump_state).capst).monitor_mutex_held = false;
// wait to acquire the monitor binding mutex
flounder_support_monitor_mutex_enqueue(((((struct mem_ump_binding *)(_binding))->ump_state).chan).monitor_binding, &(_binding->event_qnode), (struct event_closure){ .handler = mem_ump_monitor_mutex_cont, .arg = _binding });
// try to send!
mem_ump_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_steal_call__ump_send(struct mem_binding *_binding, struct event_closure _continuation, uint8_t bits, mem_genpaddr_t minbase, mem_genpaddr_t maxlimit)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_steal_call__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).steal_call).bits = bits;
((_binding->tx_union).steal_call).minbase = minbase;
((_binding->tx_union).steal_call).maxlimit = maxlimit;
FL_DEBUG("ump TX mem.steal_call\n");
// try to send!
mem_ump_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_steal_response__ump_send(struct mem_binding *_binding, struct event_closure _continuation, mem_errval_t ret, struct capref mem_cap)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_steal_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).steal_response).ret = ret;
((_binding->tx_union).steal_response).mem_cap = mem_cap;
FL_DEBUG("ump TX mem.steal_response\n");
// init cap send state
((((struct mem_ump_binding *)(_binding))->ump_state).capst).tx_capnum = 0;
((((struct mem_ump_binding *)(_binding))->ump_state).capst).rx_cap_ack = false;
((((struct mem_ump_binding *)(_binding))->ump_state).capst).monitor_mutex_held = false;
// wait to acquire the monitor binding mutex
flounder_support_monitor_mutex_enqueue(((((struct mem_ump_binding *)(_binding))->ump_state).chan).monitor_binding, &(_binding->event_qnode), (struct event_closure){ .handler = mem_ump_monitor_mutex_cont, .arg = _binding });
// try to send!
mem_ump_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_available_call__ump_send(struct mem_binding *_binding, struct event_closure _continuation)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_available_call__msgnum;
_binding->tx_msg_fragment = 0;
FL_DEBUG("ump TX mem.available_call\n");
// try to send!
mem_ump_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_available_response__ump_send(struct mem_binding *_binding, struct event_closure _continuation, mem_genpaddr_t mem_avail, mem_genpaddr_t mem_total)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_available_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).available_response).mem_avail = mem_avail;
((_binding->tx_union).available_response).mem_total = mem_total;
FL_DEBUG("ump TX mem.available_response\n");
// try to send!
mem_ump_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_free_monitor_call__ump_send(struct mem_binding *_binding, struct event_closure _continuation, struct capref mem_cap, mem_genpaddr_t base, uint8_t bits)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_free_monitor_call__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).free_monitor_call).mem_cap = mem_cap;
((_binding->tx_union).free_monitor_call).base = base;
((_binding->tx_union).free_monitor_call).bits = bits;
FL_DEBUG("ump TX mem.free_monitor_call\n");
// init cap send state
((((struct mem_ump_binding *)(_binding))->ump_state).capst).tx_capnum = 0;
((((struct mem_ump_binding *)(_binding))->ump_state).capst).rx_cap_ack = false;
((((struct mem_ump_binding *)(_binding))->ump_state).capst).monitor_mutex_held = false;
// wait to acquire the monitor binding mutex
flounder_support_monitor_mutex_enqueue(((((struct mem_ump_binding *)(_binding))->ump_state).chan).monitor_binding, &(_binding->event_qnode), (struct event_closure){ .handler = mem_ump_monitor_mutex_cont, .arg = _binding });
// try to send!
mem_ump_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_free_monitor_response__ump_send(struct mem_binding *_binding, struct event_closure _continuation, mem_errval_t err)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and arguments
_binding->tx_msgnum = mem_free_monitor_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).free_monitor_response).err = err;
FL_DEBUG("ump TX mem.free_monitor_response\n");
// try to send!
mem_ump_send_handler(_binding);
return(SYS_ERR_OK);
}
/*
* Send vtable
*/
static struct mem_tx_vtbl mem_ump_tx_vtbl = {
.allocate_call = mem_allocate_call__ump_send,
.allocate_response = mem_allocate_response__ump_send,
.steal_call = mem_steal_call__ump_send,
.steal_response = mem_steal_response__ump_send,
.available_call = mem_available_call__ump_send,
.available_response = mem_available_response__ump_send,
.free_monitor_call = mem_free_monitor_call__ump_send,
.free_monitor_response = mem_free_monitor_response__ump_send,
};
/*
* Control functions
*/
static bool mem_ump_can_send(struct mem_binding *b)
{
return((b->tx_msgnum) == 0);
}
static errval_t mem_ump_register_send(struct mem_binding *b, struct waitset *ws, struct event_closure _continuation)
{
return(flounder_support_register(ws, &(b->register_chanstate), _continuation, mem_ump_can_send(b)));
}
static void mem_ump_default_error_handler(struct mem_binding *b, errval_t err)
{
DEBUG_ERR(err, "asynchronous error in Flounder-generated mem ump binding (default handler)");
abort();
}
static errval_t mem_ump_change_waitset(struct mem_binding *_binding, struct waitset *ws)
{
struct mem_ump_binding *b = (void *)(_binding);
errval_t err;
// change waitset on private monitor binding if we have one
if ((((b->ump_state).chan).monitor_binding) != get_monitor_binding()) {
err = flounder_support_change_monitor_waitset(((b->ump_state).chan).monitor_binding, ws);
if (err_is_fail(err)) {
return(err_push(err, FLOUNDER_ERR_CHANGE_MONITOR_WAITSET));
}
}
// change waitset on binding
_binding->waitset = ws;
// re-register for receive (if previously registered)
err = ump_chan_deregister_recv(&((b->ump_state).chan));
if (err_is_fail(err) && (err_no(err) != LIB_ERR_CHAN_NOT_REGISTERED)) {
return(err_push(err, LIB_ERR_CHAN_DEREGISTER_RECV));
}
if (err_is_ok(err)) {
err = ump_chan_register_recv(&((b->ump_state).chan), _binding->waitset, (struct event_closure){ .handler = mem_ump_rx_handler, .arg = _binding });
if (err_is_fail(err)) {
return(err_push(err, LIB_ERR_CHAN_REGISTER_RECV));
}
}
return(SYS_ERR_OK);
}
static errval_t mem_ump_control(struct mem_binding *_binding, idc_control_t control)
{
// no control flags are supported
return(SYS_ERR_OK);
}
/*
* Function to destroy the binding state
*/
void mem_ump_destroy(struct mem_ump_binding *b)
{
flounder_support_waitset_chanstate_destroy(&((b->b).register_chanstate));
flounder_support_waitset_chanstate_destroy(&((b->b).tx_cont_chanstate));
ump_chan_destroy(&((b->ump_state).chan));
}
/*
* Bind function
*/
static void mem_ump_bind_continuation(void *st, errval_t err, struct ump_chan *chan, struct capref notify_cap)
{
struct mem_binding *_binding = st;
struct mem_ump_binding *b = st;
if (err_is_ok(err)) {
// notify cap ignored
// setup cap handlers
(((b->ump_state).chan).cap_handlers).st = b;
(((b->ump_state).chan).cap_handlers).cap_receive_handler = mem_ump_cap_rx_handler;
// register for receive notification
err = ump_chan_register_recv(&((b->ump_state).chan), _binding->waitset, (struct event_closure){ .handler = mem_ump_rx_handler, .arg = _binding });
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_CHAN_REGISTER_RECV));
}
} else {
mem_ump_destroy(b);
}
(_binding->bind_cont)(_binding->st, err, _binding);
}
errval_t mem_ump_init(struct mem_ump_binding *b, struct waitset *waitset, volatile void *inbuf, size_t inbufsize, volatile void *outbuf, size_t outbufsize)
{
errval_t err;
struct mem_binding *_binding = &(b->b);
(b->b).st = NULL;
(b->b).waitset = waitset;
event_mutex_init(&((b->b).mutex), waitset);
(b->b).can_send = mem_ump_can_send;
(b->b).register_send = mem_ump_register_send;
(b->b).error_handler = mem_ump_default_error_handler;
(b->b).tx_vtbl = mem_ump_tx_vtbl;
memset(&((b->b).rx_vtbl), 0, sizeof((b->b).rx_vtbl));
flounder_support_waitset_chanstate_init(&((b->b).register_chanstate));
flounder_support_waitset_chanstate_init(&((b->b).tx_cont_chanstate));
(b->b).tx_msgnum = 0;
(b->b).rx_msgnum = 0;
(b->b).tx_msg_fragment = 0;
(b->b).rx_msg_fragment = 0;
(b->b).tx_str_pos = 0;
(b->b).rx_str_pos = 0;
(b->b).tx_str_len = 0;
(b->b).rx_str_len = 0;
(b->b).bind_cont = NULL;
flounder_stub_ump_state_init(&(b->ump_state), b);
err = ump_chan_init(&((b->ump_state).chan), inbuf, inbufsize, outbuf, outbufsize);
if (err_is_fail(err)) {
mem_ump_destroy(b);
return(err_push(err, LIB_ERR_UMP_CHAN_INIT));
}
(b->b).change_waitset = mem_ump_change_waitset;
(b->b).control = mem_ump_control;
// register for receive notification
err = ump_chan_register_recv(&((b->ump_state).chan), _binding->waitset, (struct event_closure){ .handler = mem_ump_rx_handler, .arg = _binding });
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_CHAN_REGISTER_RECV));
}
return(err);
}
static void mem_ump_new_monitor_binding_continuation(void *st, errval_t err, struct monitor_binding *monitor_binding)
{
struct mem_binding *_binding = st;
struct mem_ump_binding *b = st;
if (err_is_fail(err)) {
err = err_push(err, LIB_ERR_MONITOR_CLIENT_BIND);
goto out;
}
((b->ump_state).chan).monitor_binding = monitor_binding;
// start the bind on the new monitor binding
err = ump_chan_bind(&((b->ump_state).chan), (struct ump_bind_continuation){ .handler = mem_ump_bind_continuation, .st = b }, &(_binding->event_qnode), b->iref, monitor_binding, b->inchanlen, b->outchanlen, NULL_CAP);
out:
if (err_is_fail(err)) {
(_binding->bind_cont)(_binding->st, err, _binding);
mem_ump_destroy(b);
}
}
errval_t mem_ump_bind(struct mem_ump_binding *b, iref_t iref, mem_bind_continuation_fn *_continuation, void *st, struct waitset *waitset, idc_bind_flags_t flags, size_t inchanlen, size_t outchanlen)
{
errval_t err;
(b->b).st = NULL;
(b->b).waitset = waitset;
event_mutex_init(&((b->b).mutex), waitset);
(b->b).can_send = mem_ump_can_send;
(b->b).register_send = mem_ump_register_send;
(b->b).error_handler = mem_ump_default_error_handler;
(b->b).tx_vtbl = mem_ump_tx_vtbl;
memset(&((b->b).rx_vtbl), 0, sizeof((b->b).rx_vtbl));
flounder_support_waitset_chanstate_init(&((b->b).register_chanstate));
flounder_support_waitset_chanstate_init(&((b->b).tx_cont_chanstate));
(b->b).tx_msgnum = 0;
(b->b).rx_msgnum = 0;
(b->b).tx_msg_fragment = 0;
(b->b).rx_msg_fragment = 0;
(b->b).tx_str_pos = 0;
(b->b).rx_str_pos = 0;
(b->b).tx_str_len = 0;
(b->b).rx_str_len = 0;
(b->b).bind_cont = NULL;
flounder_stub_ump_state_init(&(b->ump_state), b);
(b->b).change_waitset = mem_ump_change_waitset;
(b->b).control = mem_ump_control;
(b->b).st = st;
(b->b).bind_cont = _continuation;
b->iref = iref;
b->inchanlen = inchanlen;
b->outchanlen = outchanlen;
// do we need a new monitor binding?
if (flags & IDC_BIND_FLAG_RPC_CAP_TRANSFER) {
err = monitor_client_new_binding(mem_ump_new_monitor_binding_continuation, b, waitset, DEFAULT_LMP_BUF_WORDS);
} else {
err = ump_chan_bind(&((b->ump_state).chan), (struct ump_bind_continuation){ .handler = mem_ump_bind_continuation, .st = b }, &((b->b).event_qnode), iref, get_monitor_binding(), inchanlen, outchanlen, NULL_CAP);
}
if (err_is_fail(err)) {
mem_ump_destroy(b);
}
return(err);
}
/*
* Connect callback for export
*/
errval_t mem_ump_connect_handler(void *st, struct monitor_binding *mb, uintptr_t mon_id, struct capref frame, size_t inchanlen, size_t outchanlen, struct capref notify_cap)
{
struct mem_export *e = st;
errval_t err;
// allocate storage for binding
struct mem_ump_binding *b = malloc(sizeof(struct mem_ump_binding ));
if (b == NULL) {
return(LIB_ERR_MALLOC_FAIL);
}
struct mem_binding *_binding = &(b->b);
(b->b).st = NULL;
(b->b).waitset = (e->waitset);
event_mutex_init(&((b->b).mutex), e->waitset);
(b->b).can_send = mem_ump_can_send;
(b->b).register_send = mem_ump_register_send;
(b->b).error_handler = mem_ump_default_error_handler;
(b->b).tx_vtbl = mem_ump_tx_vtbl;
memset(&((b->b).rx_vtbl), 0, sizeof((b->b).rx_vtbl));
flounder_support_waitset_chanstate_init(&((b->b).register_chanstate));
flounder_support_waitset_chanstate_init(&((b->b).tx_cont_chanstate));
(b->b).tx_msgnum = 0;
(b->b).rx_msgnum = 0;
(b->b).tx_msg_fragment = 0;
(b->b).rx_msg_fragment = 0;
(b->b).tx_str_pos = 0;
(b->b).rx_str_pos = 0;
(b->b).tx_str_len = 0;
(b->b).rx_str_len = 0;
(b->b).bind_cont = NULL;
flounder_stub_ump_state_init(&(b->ump_state), b);
(b->b).change_waitset = mem_ump_change_waitset;
(b->b).control = mem_ump_control;
// run user's connect handler
err = ((e->connect_cb)(e->st, _binding));
if (err_is_fail(err)) {
// connection refused
mem_ump_destroy(b);
return(err);
}
// accept the connection and setup the channel
err = ump_chan_accept(&((b->ump_state).chan), mon_id, frame, inchanlen, outchanlen);
if (err_is_fail(err)) {
err = err_push(err, LIB_ERR_UMP_CHAN_ACCEPT);
(_binding->error_handler)(_binding, err);
return(err);
}
// notify cap ignored
// setup cap handlers
(((b->ump_state).chan).cap_handlers).st = b;
(((b->ump_state).chan).cap_handlers).cap_receive_handler = mem_ump_cap_rx_handler;
// register for receive notification
err = ump_chan_register_recv(&((b->ump_state).chan), _binding->waitset, (struct event_closure){ .handler = mem_ump_rx_handler, .arg = _binding });
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err_push(err, LIB_ERR_CHAN_REGISTER_RECV));
}
// send back bind reply
ump_chan_send_bind_reply(mb, &((b->ump_state).chan), SYS_ERR_OK, mon_id, NULL_CAP);
return(SYS_ERR_OK);
}
#endif // CONFIG_FLOUNDER_BACKEND_UMP
/*
* Copyright (c) 2010, ETH Zurich.
* All rights reserved.
*
* INTERFACE NAME: mem
* INTEFACE FILE: ../if/mem.if
* INTERFACE DESCRIPTION: Memory allocation RPC interface
*
* This file is distributed under the terms in the attached LICENSE
* file. If you do not find this file, copies can be found by
* writing to:
* ETH Zurich D-INFK, Universitaetstr.6, CH-8092 Zurich.
* Attn: Systems Group.
*
* THIS FILE IS AUTOMATICALLY GENERATED BY FLOUNDER: DO NOT EDIT!
*/
#ifdef CONFIG_FLOUNDER_BACKEND_MULTIHOP
/*
* Generated Stub for Multihop on x86_64
*/
#include <string.h>
#include <barrelfish/barrelfish.h>
#include <flounder/flounder_support.h>
#include <if/mem_defs.h>
/*
* Capability sender function
*/
static void mem_multihop_cap_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
errval_t err = SYS_ERR_OK;
// Switch on current outgoing message
switch (_binding->tx_msgnum) {
case mem_allocate_response__msgnum:
// Switch on current outgoing cap
switch ((mb->capst).tx_capnum) {
case 0:
err = multihop_send_capability(&(mb->chan), MKCONT(mem_multihop_cap_send_handler, _binding), &(mb->capst), ((_binding->tx_union).allocate_response).mem_cap);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_multihop_cap_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
break;
}
break;
case 1:
if (multihop_chan_is_window_full(&(mb->chan))) {
mb->trigger_chan = true;
break;
} else {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
break;
}
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_steal_response__msgnum:
// Switch on current outgoing cap
switch ((mb->capst).tx_capnum) {
case 0:
err = multihop_send_capability(&(mb->chan), MKCONT(mem_multihop_cap_send_handler, _binding), &(mb->capst), ((_binding->tx_union).steal_response).mem_cap);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_multihop_cap_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
break;
}
break;
case 1:
if (multihop_chan_is_window_full(&(mb->chan))) {
mb->trigger_chan = true;
break;
} else {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
break;
}
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_free_monitor_call__msgnum:
// Switch on current outgoing cap
switch ((mb->capst).tx_capnum) {
case 0:
err = multihop_send_capability(&(mb->chan), MKCONT(mem_multihop_cap_send_handler, _binding), &(mb->capst), ((_binding->tx_union).free_monitor_call).mem_cap);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_multihop_cap_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
break;
}
break;
case 1:
if (multihop_chan_is_window_full(&(mb->chan))) {
mb->trigger_chan = true;
break;
} else {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
break;
}
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
default:
assert(!("invalid message number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
}
/*
* Send handler functions
*/
static void mem_allocate_call__multihop_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
errval_t err = SYS_ERR_OK;
uint64_t *msg;
uint64_t msg_size;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// Calculate size of message & allocate it
msg_size = 24;
assert(msg_size != 0);
msg = malloc(msg_size);
// copy words from fixed size fragments
// [[MsgCode,ArgFieldFragment uint8 [NamedField "bits"] 0],[ArgFieldFragment uint64 [NamedField "minbase"] 0],[ArgFieldFragment uint64 [NamedField "maxlimit"] 0]]
msg[0] = (mem_allocate_call__msgnum | (((uint64_t )(((_binding->tx_union).allocate_call).bits)) << 16));
msg[1] = (((_binding->tx_union).allocate_call).minbase);
msg[2] = (((_binding->tx_union).allocate_call).maxlimit);
// copy strings
// copy buffers
// try to send!
(_binding->tx_msg_fragment)++;
mb->message = msg;
err = multihop_send_message(&(mb->chan), MKCONT(mem_allocate_call__multihop_send_handler, _binding), msg, msg_size);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
(_binding->tx_msg_fragment)--;
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_allocate_call__multihop_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
break;
} else {
return;
}
case 1:
// all fragments are sent
free(mb->message);
if (multihop_chan_is_window_full(&(mb->chan))) {
mb->trigger_chan = true;
return;
} else {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
static void mem_allocate_response__multihop_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
errval_t err = SYS_ERR_OK;
uint64_t *msg;
uint64_t msg_size;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// Calculate size of message & allocate it
msg_size = 16;
assert(msg_size != 0);
msg = malloc(msg_size);
// copy words from fixed size fragments
// [[MsgCode],[ArgFieldFragment uint64 [NamedField "ret"] 0]]
msg[0] = mem_allocate_response__msgnum;
msg[1] = (((_binding->tx_union).allocate_response).ret);
// copy strings
// copy buffers
// try to send!
(_binding->tx_msg_fragment)++;
mb->message = msg;
err = multihop_send_message(&(mb->chan), MKCONT(mem_allocate_response__multihop_send_handler, _binding), msg, msg_size);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
(_binding->tx_msg_fragment)--;
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_allocate_response__multihop_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
break;
} else {
return;
}
case 1:
free(mb->message);
// send caps
mem_multihop_cap_send_handler(mb);
return;
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
static void mem_steal_call__multihop_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
errval_t err = SYS_ERR_OK;
uint64_t *msg;
uint64_t msg_size;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// Calculate size of message & allocate it
msg_size = 24;
assert(msg_size != 0);
msg = malloc(msg_size);
// copy words from fixed size fragments
// [[MsgCode,ArgFieldFragment uint8 [NamedField "bits"] 0],[ArgFieldFragment uint64 [NamedField "minbase"] 0],[ArgFieldFragment uint64 [NamedField "maxlimit"] 0]]
msg[0] = (mem_steal_call__msgnum | (((uint64_t )(((_binding->tx_union).steal_call).bits)) << 16));
msg[1] = (((_binding->tx_union).steal_call).minbase);
msg[2] = (((_binding->tx_union).steal_call).maxlimit);
// copy strings
// copy buffers
// try to send!
(_binding->tx_msg_fragment)++;
mb->message = msg;
err = multihop_send_message(&(mb->chan), MKCONT(mem_steal_call__multihop_send_handler, _binding), msg, msg_size);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
(_binding->tx_msg_fragment)--;
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_steal_call__multihop_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
break;
} else {
return;
}
case 1:
// all fragments are sent
free(mb->message);
if (multihop_chan_is_window_full(&(mb->chan))) {
mb->trigger_chan = true;
return;
} else {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
static void mem_steal_response__multihop_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
errval_t err = SYS_ERR_OK;
uint64_t *msg;
uint64_t msg_size;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// Calculate size of message & allocate it
msg_size = 16;
assert(msg_size != 0);
msg = malloc(msg_size);
// copy words from fixed size fragments
// [[MsgCode],[ArgFieldFragment uint64 [NamedField "ret"] 0]]
msg[0] = mem_steal_response__msgnum;
msg[1] = (((_binding->tx_union).steal_response).ret);
// copy strings
// copy buffers
// try to send!
(_binding->tx_msg_fragment)++;
mb->message = msg;
err = multihop_send_message(&(mb->chan), MKCONT(mem_steal_response__multihop_send_handler, _binding), msg, msg_size);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
(_binding->tx_msg_fragment)--;
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_steal_response__multihop_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
break;
} else {
return;
}
case 1:
free(mb->message);
// send caps
mem_multihop_cap_send_handler(mb);
return;
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
static void mem_available_call__multihop_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
errval_t err = SYS_ERR_OK;
uint64_t *msg;
uint64_t msg_size;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// Calculate size of message & allocate it
msg_size = 8;
assert(msg_size != 0);
msg = malloc(msg_size);
// copy words from fixed size fragments
// [[MsgCode]]
msg[0] = mem_available_call__msgnum;
// copy strings
// copy buffers
// try to send!
(_binding->tx_msg_fragment)++;
mb->message = msg;
err = multihop_send_message(&(mb->chan), MKCONT(mem_available_call__multihop_send_handler, _binding), msg, msg_size);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
(_binding->tx_msg_fragment)--;
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_available_call__multihop_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
break;
} else {
return;
}
case 1:
// all fragments are sent
free(mb->message);
if (multihop_chan_is_window_full(&(mb->chan))) {
mb->trigger_chan = true;
return;
} else {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
static void mem_available_response__multihop_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
errval_t err = SYS_ERR_OK;
uint64_t *msg;
uint64_t msg_size;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// Calculate size of message & allocate it
msg_size = 24;
assert(msg_size != 0);
msg = malloc(msg_size);
// copy words from fixed size fragments
// [[MsgCode],[ArgFieldFragment uint64 [NamedField "mem_avail"] 0],[ArgFieldFragment uint64 [NamedField "mem_total"] 0]]
msg[0] = mem_available_response__msgnum;
msg[1] = (((_binding->tx_union).available_response).mem_avail);
msg[2] = (((_binding->tx_union).available_response).mem_total);
// copy strings
// copy buffers
// try to send!
(_binding->tx_msg_fragment)++;
mb->message = msg;
err = multihop_send_message(&(mb->chan), MKCONT(mem_available_response__multihop_send_handler, _binding), msg, msg_size);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
(_binding->tx_msg_fragment)--;
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_available_response__multihop_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
break;
} else {
return;
}
case 1:
// all fragments are sent
free(mb->message);
if (multihop_chan_is_window_full(&(mb->chan))) {
mb->trigger_chan = true;
return;
} else {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
static void mem_free_monitor_call__multihop_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
errval_t err = SYS_ERR_OK;
uint64_t *msg;
uint64_t msg_size;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// Calculate size of message & allocate it
msg_size = 16;
assert(msg_size != 0);
msg = malloc(msg_size);
// copy words from fixed size fragments
// [[MsgCode,ArgFieldFragment uint8 [NamedField "bits"] 0],[ArgFieldFragment uint64 [NamedField "base"] 0]]
msg[0] = (mem_free_monitor_call__msgnum | (((uint64_t )(((_binding->tx_union).free_monitor_call).bits)) << 16));
msg[1] = (((_binding->tx_union).free_monitor_call).base);
// copy strings
// copy buffers
// try to send!
(_binding->tx_msg_fragment)++;
mb->message = msg;
err = multihop_send_message(&(mb->chan), MKCONT(mem_free_monitor_call__multihop_send_handler, _binding), msg, msg_size);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
(_binding->tx_msg_fragment)--;
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_free_monitor_call__multihop_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
break;
} else {
return;
}
case 1:
free(mb->message);
// send caps
mem_multihop_cap_send_handler(mb);
return;
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
static void mem_free_monitor_response__multihop_send_handler(void *arg)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
errval_t err = SYS_ERR_OK;
uint64_t *msg;
uint64_t msg_size;
// Switch on current outgoing message fragment
switch (_binding->tx_msg_fragment) {
case 0:
// Calculate size of message & allocate it
msg_size = 16;
assert(msg_size != 0);
msg = malloc(msg_size);
// copy words from fixed size fragments
// [[MsgCode],[ArgFieldFragment uint64 [NamedField "err"] 0]]
msg[0] = mem_free_monitor_response__msgnum;
msg[1] = (((_binding->tx_union).free_monitor_response).err);
// copy strings
// copy buffers
// try to send!
(_binding->tx_msg_fragment)++;
mb->message = msg;
err = multihop_send_message(&(mb->chan), MKCONT(mem_free_monitor_response__multihop_send_handler, _binding), msg, msg_size);
if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
(_binding->tx_msg_fragment)--;
err = multihop_chan_register_send(&(mb->chan), _binding->waitset, MKCONT(mem_free_monitor_response__multihop_send_handler, _binding));
assert(err_is_ok(err));
}
if (err_is_fail(err)) {
break;
} else {
return;
}
case 1:
// all fragments are sent
free(mb->message);
if (multihop_chan_is_window_full(&(mb->chan))) {
mb->trigger_chan = true;
return;
} else {
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
return;
}
default:
assert(!("invalid fragment"));
err = FLOUNDER_ERR_INVALID_STATE;
}
// Report error to user
(_binding->error_handler)(_binding, err);
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->register_chanstate));
flounder_support_deregister_chan(&(_binding->tx_cont_chanstate));
}
/*
* Cap receive handlers
*/
void mem_multihop_caps_rx_handler(void *arg, errval_t success, struct capref cap, uint32_t capid)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
assert(capid == ((mb->capst).rx_capnum));
// Check if there's an associated error
// FIXME: how should we report this to the user? at present we just deliver a NULL capref
if (err_is_fail(success)) {
DEBUG_ERR(success, "could not send cap over multihop channel");
}
// Switch on current incoming message
switch (_binding->rx_msgnum) {
case mem_allocate_response__msgnum:
// Switch on current incoming cap
switch (((mb->capst).rx_capnum)++) {
case 0:
((_binding->rx_union).allocate_response).mem_cap = cap;
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
FL_DEBUG("multihop RX mem.allocate_response\n");
assert(((_binding->rx_vtbl).allocate_response) != NULL);
((_binding->rx_vtbl).allocate_response)(_binding, ((_binding->rx_union).allocate_response).ret, ((_binding->rx_union).allocate_response).mem_cap);
_binding->rx_msgnum = 0;
break;
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_steal_response__msgnum:
// Switch on current incoming cap
switch (((mb->capst).rx_capnum)++) {
case 0:
((_binding->rx_union).steal_response).mem_cap = cap;
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
FL_DEBUG("multihop RX mem.steal_response\n");
assert(((_binding->rx_vtbl).steal_response) != NULL);
((_binding->rx_vtbl).steal_response)(_binding, ((_binding->rx_union).steal_response).ret, ((_binding->rx_union).steal_response).mem_cap);
_binding->rx_msgnum = 0;
break;
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
case mem_free_monitor_call__msgnum:
// Switch on current incoming cap
switch (((mb->capst).rx_capnum)++) {
case 0:
((_binding->rx_union).free_monitor_call).mem_cap = cap;
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
FL_DEBUG("multihop RX mem.free_monitor_call\n");
assert(((_binding->rx_vtbl).free_monitor_call) != NULL);
((_binding->rx_vtbl).free_monitor_call)(_binding, ((_binding->rx_union).free_monitor_call).mem_cap, ((_binding->rx_union).free_monitor_call).base, ((_binding->rx_union).free_monitor_call).bits);
_binding->rx_msgnum = 0;
break;
default:
assert(!("invalid cap number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
break;
default:
assert(!("invalid message number"));
(_binding->error_handler)(_binding, FLOUNDER_ERR_INVALID_STATE);
}
}
/*
* Message sender functions
*/
static errval_t mem_allocate_call__multihop_send(struct mem_binding *_binding, struct event_closure _continuation, uint8_t bits, mem_genpaddr_t minbase, mem_genpaddr_t maxlimit)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and the arguments
_binding->tx_msgnum = mem_allocate_call__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).allocate_call).bits = bits;
((_binding->tx_union).allocate_call).minbase = minbase;
((_binding->tx_union).allocate_call).maxlimit = maxlimit;
FL_DEBUG("multihop TX mem.allocate_call\n");
// try to send!
mem_allocate_call__multihop_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_allocate_response__multihop_send(struct mem_binding *_binding, struct event_closure _continuation, mem_errval_t ret, struct capref mem_cap)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and the arguments
_binding->tx_msgnum = mem_allocate_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).allocate_response).ret = ret;
((_binding->tx_union).allocate_response).mem_cap = mem_cap;
FL_DEBUG("multihop TX mem.allocate_response\n");
// try to send!
mem_allocate_response__multihop_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_steal_call__multihop_send(struct mem_binding *_binding, struct event_closure _continuation, uint8_t bits, mem_genpaddr_t minbase, mem_genpaddr_t maxlimit)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and the arguments
_binding->tx_msgnum = mem_steal_call__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).steal_call).bits = bits;
((_binding->tx_union).steal_call).minbase = minbase;
((_binding->tx_union).steal_call).maxlimit = maxlimit;
FL_DEBUG("multihop TX mem.steal_call\n");
// try to send!
mem_steal_call__multihop_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_steal_response__multihop_send(struct mem_binding *_binding, struct event_closure _continuation, mem_errval_t ret, struct capref mem_cap)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and the arguments
_binding->tx_msgnum = mem_steal_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).steal_response).ret = ret;
((_binding->tx_union).steal_response).mem_cap = mem_cap;
FL_DEBUG("multihop TX mem.steal_response\n");
// try to send!
mem_steal_response__multihop_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_available_call__multihop_send(struct mem_binding *_binding, struct event_closure _continuation)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and the arguments
_binding->tx_msgnum = mem_available_call__msgnum;
_binding->tx_msg_fragment = 0;
FL_DEBUG("multihop TX mem.available_call\n");
// try to send!
mem_available_call__multihop_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_available_response__multihop_send(struct mem_binding *_binding, struct event_closure _continuation, mem_genpaddr_t mem_avail, mem_genpaddr_t mem_total)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and the arguments
_binding->tx_msgnum = mem_available_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).available_response).mem_avail = mem_avail;
((_binding->tx_union).available_response).mem_total = mem_total;
FL_DEBUG("multihop TX mem.available_response\n");
// try to send!
mem_available_response__multihop_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_free_monitor_call__multihop_send(struct mem_binding *_binding, struct event_closure _continuation, struct capref mem_cap, mem_genpaddr_t base, uint8_t bits)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and the arguments
_binding->tx_msgnum = mem_free_monitor_call__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).free_monitor_call).mem_cap = mem_cap;
((_binding->tx_union).free_monitor_call).base = base;
((_binding->tx_union).free_monitor_call).bits = bits;
FL_DEBUG("multihop TX mem.free_monitor_call\n");
// try to send!
mem_free_monitor_call__multihop_send_handler(_binding);
return(SYS_ERR_OK);
}
static errval_t mem_free_monitor_response__multihop_send(struct mem_binding *_binding, struct event_closure _continuation, mem_errval_t err)
{
// check that we can accept an outgoing message
if ((_binding->tx_msgnum) != 0) {
return(FLOUNDER_ERR_TX_BUSY);
}
// register send continuation
if ((_continuation.handler) != NULL) {
errval_t _err;
_err = flounder_support_register(_binding->waitset, &(_binding->tx_cont_chanstate), _continuation, false);
// may fail if previous continuation hasn't fired yet
if (err_is_fail(_err)) {
if (err_no(_err) == LIB_ERR_CHAN_ALREADY_REGISTERED) {
return(FLOUNDER_ERR_TX_BUSY);
} else {
assert(!("shouldn't happen"));
return(_err);
}
}
}
// store message number and the arguments
_binding->tx_msgnum = mem_free_monitor_response__msgnum;
_binding->tx_msg_fragment = 0;
((_binding->tx_union).free_monitor_response).err = err;
FL_DEBUG("multihop TX mem.free_monitor_response\n");
// try to send!
mem_free_monitor_response__multihop_send_handler(_binding);
return(SYS_ERR_OK);
}
/*
* Send vtable
*/
static struct mem_tx_vtbl mem_multihop_tx_vtbl = {
.allocate_call = mem_allocate_call__multihop_send,
.allocate_response = mem_allocate_response__multihop_send,
.steal_call = mem_steal_call__multihop_send,
.steal_response = mem_steal_response__multihop_send,
.available_call = mem_available_call__multihop_send,
.available_response = mem_available_response__multihop_send,
.free_monitor_call = mem_free_monitor_call__multihop_send,
.free_monitor_response = mem_free_monitor_response__multihop_send,
};
/*
* Receive handler
*/
void mem_multihop_rx_handler(void *arg, uint8_t *message, size_t message_len)
{
// Get the binding state from our argument pointer
struct mem_binding *_binding = arg;
struct mem_multihop_binding *mb = arg;
uint8_t *msg;
// if this a dummy message?
if (message_len == 0) {
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
return;
}
// is this the start of a new message?
if ((_binding->rx_msgnum) == 0) {
// unmarshall message number from first word, set fragment to 0
_binding->rx_msgnum = ((message[0]) & 0xffff);
_binding->rx_msg_fragment = 0;
(mb->capst).rx_capnum = 0;
} else {
assert(!"should not happen");
}
// switch on message number
switch (_binding->rx_msgnum) {
case mem_allocate_call__msgnum:
// store fixed size fragments
((_binding->rx_union).allocate_call).bits = (((((uint64_t *)(message))[0]) >> 16) & 0xff);
((_binding->rx_union).allocate_call).minbase = (((uint64_t *)(message))[1]);
((_binding->rx_union).allocate_call).maxlimit = (((uint64_t *)(message))[2]);
msg = (message + 24);
// receive strings
// receive buffers
free(message);
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
FL_DEBUG("multihop RX mem.allocate_call\n");
assert(((_binding->rx_vtbl).allocate_call) != NULL);
((_binding->rx_vtbl).allocate_call)(_binding, ((_binding->rx_union).allocate_call).bits, ((_binding->rx_union).allocate_call).minbase, ((_binding->rx_union).allocate_call).maxlimit);
_binding->rx_msgnum = 0;
break;
case mem_allocate_response__msgnum:
// store fixed size fragments
((_binding->rx_union).allocate_response).ret = (((uint64_t *)(message))[1]);
msg = (message + 16);
// receive strings
// receive buffers
free(message);
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
(_binding->rx_msg_fragment)++;
break;
case mem_steal_call__msgnum:
// store fixed size fragments
((_binding->rx_union).steal_call).bits = (((((uint64_t *)(message))[0]) >> 16) & 0xff);
((_binding->rx_union).steal_call).minbase = (((uint64_t *)(message))[1]);
((_binding->rx_union).steal_call).maxlimit = (((uint64_t *)(message))[2]);
msg = (message + 24);
// receive strings
// receive buffers
free(message);
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
FL_DEBUG("multihop RX mem.steal_call\n");
assert(((_binding->rx_vtbl).steal_call) != NULL);
((_binding->rx_vtbl).steal_call)(_binding, ((_binding->rx_union).steal_call).bits, ((_binding->rx_union).steal_call).minbase, ((_binding->rx_union).steal_call).maxlimit);
_binding->rx_msgnum = 0;
break;
case mem_steal_response__msgnum:
// store fixed size fragments
((_binding->rx_union).steal_response).ret = (((uint64_t *)(message))[1]);
msg = (message + 16);
// receive strings
// receive buffers
free(message);
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
(_binding->rx_msg_fragment)++;
break;
case mem_available_call__msgnum:
// store fixed size fragments
msg = (message + 8);
// receive strings
// receive buffers
free(message);
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
FL_DEBUG("multihop RX mem.available_call\n");
assert(((_binding->rx_vtbl).available_call) != NULL);
((_binding->rx_vtbl).available_call)(_binding);
_binding->rx_msgnum = 0;
break;
case mem_available_response__msgnum:
// store fixed size fragments
((_binding->rx_union).available_response).mem_avail = (((uint64_t *)(message))[1]);
((_binding->rx_union).available_response).mem_total = (((uint64_t *)(message))[2]);
msg = (message + 24);
// receive strings
// receive buffers
free(message);
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
FL_DEBUG("multihop RX mem.available_response\n");
assert(((_binding->rx_vtbl).available_response) != NULL);
((_binding->rx_vtbl).available_response)(_binding, ((_binding->rx_union).available_response).mem_avail, ((_binding->rx_union).available_response).mem_total);
_binding->rx_msgnum = 0;
break;
case mem_free_monitor_call__msgnum:
// store fixed size fragments
((_binding->rx_union).free_monitor_call).bits = (((((uint64_t *)(message))[0]) >> 16) & 0xff);
((_binding->rx_union).free_monitor_call).base = (((uint64_t *)(message))[1]);
msg = (message + 16);
// receive strings
// receive buffers
free(message);
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
(_binding->rx_msg_fragment)++;
break;
case mem_free_monitor_response__msgnum:
// store fixed size fragments
((_binding->rx_union).free_monitor_response).err = (((uint64_t *)(message))[1]);
msg = (message + 16);
// receive strings
// receive buffers
free(message);
if (mb->trigger_chan) {
mb->trigger_chan = false;
_binding->tx_msgnum = 0;
flounder_support_trigger_chan(&(_binding->tx_cont_chanstate));
flounder_support_trigger_chan(&(_binding->register_chanstate));
}
FL_DEBUG("multihop RX mem.free_monitor_response\n");
assert(((_binding->rx_vtbl).free_monitor_response) != NULL);
((_binding->rx_vtbl).free_monitor_response)(_binding, ((_binding->rx_union).free_monitor_response).err);
_binding->rx_msgnum = 0;
break;
default:
(_binding->error_handler)(_binding, FLOUNDER_ERR_RX_INVALID_MSGNUM);
return;
}
}
/*
* Control functions
*/
static bool mem_multihop_can_send(struct mem_binding *b)
{
struct mem_multihop_binding *mb = (struct mem_multihop_binding *)(b);
return(((b->tx_msgnum) == 0) && (!multihop_chan_is_window_full(&(mb->chan))));
}
static errval_t mem_multihop_register_send(struct mem_binding *b, struct waitset *ws, struct event_closure _continuation)
{
return(flounder_support_register(ws, &(b->register_chanstate), _continuation, mem_multihop_can_send(b)));
}
static void mem_multihop_default_error_handler(struct mem_binding *b, errval_t err)
{
DEBUG_ERR(err, "asynchronous error in Flounder-generated mem multihop binding (default handler)");
abort();
}
static errval_t mem_multihop_change_waitset(struct mem_binding *_binding, struct waitset *ws)
{
struct mem_multihop_binding *mb = (void *)(_binding);
// change waitset on binding
_binding->waitset = ws;
// change waitset on multi-hop channel
return(multihop_chan_change_waitset(&(mb->chan), ws));
}
static errval_t mem_multihop_control(struct mem_binding *_binding, idc_control_t control)
{
// No control flags supported
return(SYS_ERR_OK);
}
/*
* Functions to initialise/destroy the binding state
*/
void mem_multihop_init(struct mem_multihop_binding *mb, struct waitset *waitset)
{
(mb->b).st = NULL;
(mb->b).waitset = waitset;
event_mutex_init(&((mb->b).mutex), waitset);
(mb->b).can_send = mem_multihop_can_send;
(mb->b).register_send = mem_multihop_register_send;
(mb->b).error_handler = mem_multihop_default_error_handler;
(mb->b).tx_vtbl = mem_multihop_tx_vtbl;
memset(&((mb->b).rx_vtbl), 0, sizeof((mb->b).rx_vtbl));
flounder_support_waitset_chanstate_init(&((mb->b).register_chanstate));
flounder_support_waitset_chanstate_init(&((mb->b).tx_cont_chanstate));
(mb->b).tx_msgnum = 0;
(mb->b).rx_msgnum = 0;
(mb->b).tx_msg_fragment = 0;
(mb->b).rx_msg_fragment = 0;
(mb->b).tx_str_pos = 0;
(mb->b).rx_str_pos = 0;
(mb->b).tx_str_len = 0;
(mb->b).rx_str_len = 0;
(mb->b).bind_cont = NULL;
(mb->b).change_waitset = mem_multihop_change_waitset;
(mb->b).control = mem_multihop_control;
mb->trigger_chan = false;
}
void mem_multihop_destroy(struct mem_multihop_binding *mb)
{
flounder_support_waitset_chanstate_destroy(&((mb->b).register_chanstate));
flounder_support_waitset_chanstate_destroy(&((mb->b).tx_cont_chanstate));
assert(! "NYI!");
}
/*
* Bind function
*/
static void mem_multihop_bind_continuation(void *st, errval_t err, struct multihop_chan *chan)
{
struct mem_multihop_binding *mb = st;
if (err_is_ok(err)) {
// set receive handlers
multihop_chan_set_receive_handler(&(mb->chan), (struct multihop_receive_handler){ .handler = mem_multihop_rx_handler, .arg = st });
multihop_chan_set_caps_receive_handlers(&(mb->chan), (struct monitor_cap_handlers){ .st = st, .cap_receive_handler = mem_multihop_caps_rx_handler });
} else {
mem_multihop_destroy(mb);
}
((mb->b).bind_cont)((mb->b).st, err, &(mb->b));
}
errval_t mem_multihop_bind(struct mem_multihop_binding *mb, iref_t iref, mem_bind_continuation_fn *_continuation, void *st, struct waitset *waitset, idc_bind_flags_t flags)
{
errval_t err;
mem_multihop_init(mb, waitset);
(mb->b).st = st;
(mb->b).bind_cont = _continuation;
err = multihop_chan_bind(&(mb->chan), (struct multihop_bind_continuation){ .handler = mem_multihop_bind_continuation, .st = mb }, iref, waitset);
if (err_is_fail(err)) {
mem_multihop_destroy(mb);
}
return(err);
}
/*
* Connect callback for export
*/
errval_t mem_multihop_connect_handler(void *st, multihop_vci_t vci)
{
struct mem_export *e = st;
errval_t err;
// allocate storage for binding
struct mem_multihop_binding *mb = malloc(sizeof(struct mem_multihop_binding ));
if (mb == NULL) {
return(LIB_ERR_MALLOC_FAIL);
}
// initialize binding
struct mem_binding *_binding = &(mb->b);
mem_multihop_init(mb, e->waitset);
(mb->chan).vci = vci;
// run user's connect handler
err = ((e->connect_cb)(e->st, _binding));
if (err_is_fail(err)) {
return(err);
}
// set receive handlers
multihop_chan_set_receive_handler(&(mb->chan), (struct multihop_receive_handler){ .handler = mem_multihop_rx_handler, .arg = mb });
multihop_chan_set_caps_receive_handlers(&(mb->chan), (struct monitor_cap_handlers){ .st = mb, .cap_receive_handler = mem_multihop_caps_rx_handler });
// send back bind reply
multihop_chan_send_bind_reply(&(mb->chan), SYS_ERR_OK, (mb->chan).vci, (mb->b).waitset);
return(err);
}
#endif // CONFIG_FLOUNDER_BACKEND_MULTIHOP
| Java |
/* from optimizations/bfs/topology-atomic.cu */
#define BFS_VARIANT "topology-atomic"
#define WORKPERTHREAD 1
#define VERTICALWORKPERTHREAD 12 // max value, see relax.
#define BLKSIZE 1024
#define BANKSIZE BLKSIZE
__global__
void initialize(foru *dist, unsigned int *nv) {
unsigned int ii = blockIdx.x * blockDim.x + threadIdx.x;
//printf("ii=%d, nv=%d.\n", ii, *nv);
if (ii < *nv) {
dist[ii] = MYINFINITY;
}
}
__global__
void dprocess(float *matrix, foru *dist, unsigned int *prev, bool *relaxed) {
__shared__ volatile unsigned int dNVERTICES;
unsigned int ii = blockIdx.x * blockDim.x + threadIdx.x;
unsigned int v;
unsigned int jj;
if (ii < dNVERTICES) {
unsigned int u = dNVERTICES;
foru mm = MYINFINITY;
//minimum <<< NVERTICES / BLKSIZE, BLKSIZE>>> (dist, relaxed, &u);
for (jj = 0; jj < dNVERTICES; ++jj) {
if (relaxed[jj] == false && dist[jj] < mm) {
mm = dist[jj];
u = jj;
}
}
if (u != dNVERTICES && dist[u] != MYINFINITY) {
relaxed[u] = true;
for (v = 0; v < dNVERTICES; ++v) {
if (matrix[u*dNVERTICES + v] > 0) {
foru alt = dist[u] + matrix[u*dNVERTICES + v];
if (alt < dist[v]) {
dist[v] = alt;
prev[v] = u;
}
}
}
}
}
}
__global__
void drelax(foru *dist, unsigned int *edgessrcdst, foru *edgessrcwt, unsigned int *psrc, unsigned int *noutgoing, unsigned int *nedges, unsigned int *nv, bool *changed, unsigned int *srcsrc, unsigned unroll) {
unsigned int workperthread = WORKPERTHREAD;
unsigned nn = workperthread * (blockIdx.x * blockDim.x + threadIdx.x);
unsigned int ii;
__shared__ int changedv[VERTICALWORKPERTHREAD * BLKSIZE];
int iichangedv = threadIdx.x;
int anotheriichangedv = iichangedv;
unsigned int nprocessed = 0;
// collect the work to be performed.
for (unsigned node = 0; node < workperthread; ++node, ++nn) {
changedv[iichangedv] = nn;
iichangedv += BANKSIZE;
}
// go over the worklist and keep updating it in a BFS manner.
while (anotheriichangedv < iichangedv) {
nn = changedv[anotheriichangedv];
anotheriichangedv += BANKSIZE;
if (nn < *nv) {
unsigned src = nn; // source node.
//if (src < *nv && psrc[srcsrc[src]]) {
unsigned int start = psrc[srcsrc[src]];
unsigned int end = start + noutgoing[src];
// go over all the target nodes for the source node.
for (ii = start; ii < end; ++ii) {
unsigned int u = src;
unsigned int v = edgessrcdst[ii]; // target node.
float wt = 1;
//if (wt > 0 && v < *nv) {
foru alt = dist[u] + wt;
if (alt < dist[v]) {
//dist[v] = alt;
atomicMin((unsigned *)&dist[v], (unsigned )alt);
if (++nprocessed < unroll) {
// add work to the worklist.
changedv[iichangedv] = v;
iichangedv += BANKSIZE;
}
}
//}
}
//}
}
}
if (nprocessed) {
*changed = true;
}
}
void bfs(Graph &graph, foru *dist)
{
cudaFuncSetCacheConfig(drelax, cudaFuncCachePreferShared);
foru zero = 0;
//unsigned int intzero = 0, intone = 1;
unsigned int NBLOCKS, FACTOR = 128;
unsigned int *nedges, hnedges;
unsigned int *nv;
bool *changed, hchanged;
int iteration = 0;
double starttime, endtime;
double runtime;
cudaEvent_t start, stop;
float time;
cudaDeviceProp deviceProp;
unsigned int NVERTICES;
cudaGetDeviceProperties(&deviceProp, 0);
NBLOCKS = deviceProp.multiProcessorCount;
NVERTICES = graph.nnodes;
hnedges = graph.nedges;
FACTOR = (NVERTICES + BLKSIZE * NBLOCKS - 1) / (BLKSIZE * NBLOCKS);
if (cudaMalloc((void **)&nv, sizeof(unsigned int)) != cudaSuccess) CudaTest("allocating nv failed");
cudaMemcpy(nv, &NVERTICES, sizeof(NVERTICES), cudaMemcpyHostToDevice);
if (cudaMalloc((void **)&nedges, sizeof(unsigned int)) != cudaSuccess) CudaTest("allocating nedges failed");
cudaMemcpy(nedges, &hnedges, sizeof(unsigned int), cudaMemcpyHostToDevice);
if (cudaMalloc((void **)&changed, sizeof(bool)) != cudaSuccess) CudaTest("allocating changed failed");
for (unsigned unroll=VERTICALWORKPERTHREAD; unroll <= VERTICALWORKPERTHREAD; ++unroll) {
//printf("initializing (nblocks=%d, blocksize=%d).\n", NBLOCKS*FACTOR, BLKSIZE);
//initialize <<<NBLOCKS*FACTOR, BLKSIZE>>> (dist, nv);
//__set_CUDAConfig(NBLOCKS*FACTOR, BLKSIZE);
printf("initialize kernel \n");
__set_CUDAConfig(1, 256);
initialize(dist, nv);
CudaTest("initializing failed");
cudaMemcpy(&dist[0], &zero, sizeof(zero), cudaMemcpyHostToDevice);
//printf("solving.\n");
starttime = rtclock();
cudaEventCreate(&start);
cudaEventCreate(&stop);
//cudaEventRecord(start, 0);
//do {
++iteration;
//printf("iteration %d.\n", iteration);
hchanged = false;
cudaMemcpy(changed, &hchanged, sizeof(bool), cudaMemcpyHostToDevice);
unsigned nblocks = NBLOCKS*FACTOR;
//sree: why are nedges and nv pointers?
//drelax <<<nblocks/WORKPERTHREAD, BLKSIZE>>> (dist, graph.edgessrcdst, graph.edgessrcwt, graph.psrc, graph.noutgoing, nedges, nv, changed, graph.srcsrc, unroll);
printf("drelax kernel \n");
__set_CUDAConfig(1, 256);
drelax(dist, graph.edgessrcdst, graph.edgessrcwt, graph.psrc, graph.noutgoing, nedges, nv, changed, graph.srcsrc, unroll);
CudaTest("solving failed");
cudaMemcpy(&hchanged, changed, sizeof(bool), cudaMemcpyDeviceToHost);
//} while (hchanged);
//cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&time, start, stop);
endtime = rtclock();
runtime = 1000*(endtime - starttime);
//printf("%d ms.\n", runtime);
printf("\n");
printf("\truntime [%s] = %.3lf ms.\n",
BFS_VARIANT, 1000 * (endtime - starttime));
printf("%d\t%f\n", unroll, runtime);
}
printf("iterations = %d.\n", iteration);
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `benchmark` fn in crate `test`.">
<meta name="keywords" content="rust, rustlang, rust-lang, benchmark">
<title>test::bench::benchmark - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
<link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<a href='../../test/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a>
<p class='location'><a href='../index.html'>test</a>::<wbr><a href='index.html'>bench</a></p><script>window.sidebarCurrent = {name: 'benchmark', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press 'S' to search, '?' for more options..."
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'>Function <a href='../index.html'>test</a>::<wbr><a href='index.html'>bench</a>::<wbr><a class='fn' href=''>benchmark</a><wbr><a class='stability Unstable' title=''>Unstable</a></span><span class='out-of-band'><span id='render-detail'>
<a id="collapse-all" href="#">[-]</a> <a id="expand-all" href="#">[+]</a>
</span><a id='src-8073' href='../../src/test/lib.rs.html#1129-1146'>[src]</a></span></h1>
<pre class='rust fn'>pub fn benchmark<F>(f: F) -> <a class='struct' href='../../test/struct.BenchSamples.html' title='test::BenchSamples'>BenchSamples</a> <span class='where'>where F: <a class='trait' href='../../core/ops/trait.FnMut.html' title='core::ops::FnMut'>FnMut</a>(&mut <a class='struct' href='../../test/struct.Bencher.html' title='test::Bencher'>Bencher</a>)</span></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "test";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html> | Java |
<!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_60) on Fri Dec 11 10:08:00 MST 2015 -->
<title>ca.ualberta.cs.xpertsapp.UITests.FriendTests</title>
<meta name="date" content="2015-12-11">
<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="ca.ualberta.cs.xpertsapp.UITests.FriendTests";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../ca/ualberta/cs/xpertsapp/UITests/BrowseTests/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../ca/ualberta/cs/xpertsapp/UITests/InventoryTests/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?ca/ualberta/cs/xpertsapp/UITests/FriendTests/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package ca.ualberta.cs.xpertsapp.UITests.FriendTests</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../ca/ualberta/cs/xpertsapp/UITests/FriendTests/ProfileControllerTest.html" title="class in ca.ualberta.cs.xpertsapp.UITests.FriendTests">ProfileControllerTest</a></td>
<td class="colLast">
<div class="block">Created by kmbaker on 11/3/15.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../ca/ualberta/cs/xpertsapp/UITests/FriendTests/ViewFriendProfileTest.html" title="class in ca.ualberta.cs.xpertsapp.UITests.FriendTests">ViewFriendProfileTest</a></td>
<td class="colLast">
<div class="block">Created by kmbaker on 11/3/15.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../ca/ualberta/cs/xpertsapp/UITests/BrowseTests/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../ca/ualberta/cs/xpertsapp/UITests/InventoryTests/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?ca/ualberta/cs/xpertsapp/UITests/FriendTests/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
#include <stdio.h>
#include <stdint.h>
#include <ibcrypt/chacha.h>
#include <ibcrypt/rand.h>
#include <ibcrypt/sha256.h>
#include <ibcrypt/zfree.h>
#include <libibur/util.h>
#include <libibur/endian.h>
#include "datafile.h"
#include "../util/log.h"
int write_datafile(char *path, void *arg, void *data, struct format_desc *f) {
int ret = -1;
uint8_t *payload = NULL;
uint64_t payload_len = 0;
uint64_t payload_num = 0;
uint8_t *prefix = NULL;
uint64_t pref_len = 0;
uint8_t symm_key[0x20];
uint8_t hmac_key[0x20];
uint8_t enc_key[0x20];
FILE *ff = fopen(path, "wb");
if(ff == NULL) {
ERR("failed to open file for writing: %s", path);
goto err;
}
pref_len = 0x50 + f->pref_len;
prefix = malloc(pref_len);
if(prefix == NULL) {
ERR("failed to allocate memory");
goto err;
}
void *cur = data;
while(cur) {
payload_len += f->datalen(cur);
payload_num++;
cur = *((void **) ((char*)cur + f->next_off));
}
encbe64(payload_num, &prefix[0]);
encbe64(payload_len, &prefix[8]);
if(cs_rand(&prefix[0x10], 0x20) != 0) {
ERR("failed to generate random numbers");
goto err;
}
if(f->p_fill(arg, &prefix[0x30]) != 0) {
goto err;
}
if(f->s_key(arg, &prefix[0x30], symm_key) != 0) {
goto err;
}
if(f->h_key(arg, &prefix[0x30], hmac_key) != 0) {
goto err;
}
hmac_sha256(hmac_key, 0x20, prefix, pref_len - 0x20, &prefix[pref_len - 0x20]);
SHA256_CTX kctx;
sha256_init(&kctx);
sha256_update(&kctx, symm_key, 0x20);
sha256_update(&kctx, &prefix[0x10], 0x20);
sha256_final(&kctx, enc_key);
payload = malloc(payload_len);
if(payload == NULL) {
ERR("failed to allocate memory");
goto err;
}
cur = data;
uint8_t *ptr = payload;
while(cur) {
ptr = f->datawrite(cur, ptr);
if(ptr == NULL) {
goto err;
}
cur = *((void **) ((char*)cur + f->next_off));
}
if(ptr - payload != payload_len) {
ERR("written length does not match expected");
goto err;
}
chacha_enc(enc_key, 0x20, 0, payload, payload, payload_len);
HMAC_SHA256_CTX hctx;
hmac_sha256_init(&hctx, hmac_key, 0x20);
hmac_sha256_update(&hctx, prefix, pref_len);
hmac_sha256_update(&hctx, payload, payload_len);
uint8_t mac[0x20];
hmac_sha256_final(&hctx, mac);
if(fwrite(prefix, 1, pref_len, ff) != pref_len) {
goto writerr;
}
if(payload_len > 0) {
if(fwrite(payload, 1, payload_len, ff) != payload_len) {
goto writerr;
}
}
if(fwrite(mac, 1, 0x20, ff) != 0x20) {
goto writerr;
}
ret = 0;
err:
if(ff) fclose(ff);
if(payload) zfree(payload, payload_len);
memsets(enc_key, 0, sizeof(enc_key));
memsets(symm_key, 0, sizeof(symm_key));
memsets(hmac_key, 0, sizeof(hmac_key));
return ret;
writerr:
ERR("failed to write to file: %s", path);
goto err;
}
int read_datafile(char *path, void *arg, void **data, struct format_desc *f) {
int ret = -1;
uint8_t *payload = NULL;
uint64_t payload_len = 0;
uint64_t payload_num = 0;
uint8_t *prefix = NULL;
uint64_t pref_len = 0;
uint8_t symm_key[0x20];
uint8_t hmac_key[0x20];
uint8_t enc_key[0x20];
uint8_t mac1[0x20];
uint8_t mac2c[0x20];
uint8_t mac2f[0x20];
FILE *ff = fopen(path, "rb");
if(ff == NULL) {
ERR("failed to open file for reading: %s", path);
goto err;
}
pref_len = 0x50 + f->pref_len;
prefix = malloc(pref_len);
if(prefix == NULL) {
ERR("failed to allocate memory");
goto err;
}
if(fread(prefix, 1, pref_len, ff) != pref_len) {
goto readerr;
}
payload_num = decbe64(&prefix[0]);
payload_len = decbe64(&prefix[8]);
if(f->s_key(arg, &prefix[0x30], symm_key) != 0) {
goto err;
}
if(f->h_key(arg, &prefix[0x30], hmac_key) != 0) {
goto err;
}
hmac_sha256(hmac_key, 0x20, prefix, pref_len - 0x20, mac1);
if(memcmp_ct(mac1, &prefix[pref_len-0x20], 0x20) != 0) {
ERR("invalid file");
goto err;
}
SHA256_CTX kctx;
sha256_init(&kctx);
sha256_update(&kctx, symm_key, 0x20);
sha256_update(&kctx, &prefix[0x10], 0x20);
sha256_final(&kctx, enc_key);
payload = malloc(payload_len);
if(payload == NULL) {
ERR("failed to allocate memory");
goto err;
}
if(fread(payload, 1, payload_len, ff) != payload_len) {
goto readerr;
}
if(fread(mac2f, 1, 0x20, ff) != 0x20) {
goto readerr;
}
HMAC_SHA256_CTX hctx;
hmac_sha256_init(&hctx, hmac_key, 0x20);
hmac_sha256_update(&hctx, prefix, pref_len);
hmac_sha256_update(&hctx, payload, payload_len);
hmac_sha256_final(&hctx, mac2c);
if(memcmp_ct(mac2c, mac2f, 0x20) != 0) {
ERR("invalid file");
goto err;
}
chacha_dec(enc_key, 0x20, 0, payload, payload, payload_len);
void **cur = data;
uint8_t *ptr = payload;
uint64_t i;
for(i = 0; (ptr - payload) < payload_len && i < payload_num; i++) {
ptr = f->dataread(cur, arg, ptr);
if(ptr == NULL) {
goto err;
}
cur = (void **) ((char*)(*cur) + f->next_off);
}
*cur = NULL;
if(i != payload_num) {
ERR("read num does not match expected");
goto err;
}
if(ptr - payload != payload_len) {
ERR("read length does not match expected");
goto err;
}
ret = 0;
err:
if(ff) fclose(ff);
if(payload) zfree(payload, payload_len);
memsets(enc_key, 0, sizeof(enc_key));
memsets(symm_key, 0, sizeof(symm_key));
memsets(hmac_key, 0, sizeof(hmac_key));
return ret;
readerr:
ERR("failed to read from file: %s", path);
goto err;
}
| Java |
# Acknowledgements
This application makes use of the following third party libraries:
## GreenAR
Copyright (c) 2017 Daniel Grenier <seanalair@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Generated by CocoaPods - https://cocoapods.org
| Java |
import CommuniqueApp from './communique-app';
CommuniqueApp.open();
| Java |
using System.Collections.Generic;
using System.IO;
using Reinforced.Typings.Fluent;
using Xunit;
namespace Reinforced.Typings.Tests.SpecificCases
{
public partial class SpecificTestCases
{
[Fact]
public void ReferencesPart6ByDanielWest()
{
/**
* Specific test case with equal folder names by Daniel West
*/
const string file1 = @"
export namespace Reinforced.Typings.Tests.SpecificCases {
export enum SomeEnum {
One = 0,
Two = 1
}
}";
const string file2 = @"
import * as Enum from '../../APIv2/Models/TimeAndAttendance/Enum';
export namespace Reinforced.Typings.Tests.SpecificCases {
export class SomeViewModel
{
public Enum: Enum.Reinforced.Typings.Tests.SpecificCases.SomeEnum;
}
}";
AssertConfiguration(s =>
{
s.Global(a => a.DontWriteWarningComment().UseModules(discardNamespaces: false));
s.ExportAsEnum<SomeEnum>().ExportTo("Areas/APIv2/Models/TimeAndAttendance/Enum.ts");
s.ExportAsClass<SomeViewModel>().WithPublicProperties().ExportTo("Areas/Reporting/Models/Model.ts");
}, new Dictionary<string, string>
{
{ Path.Combine(TargetDir, "Areas/APIv2/Models/TimeAndAttendance/Enum.ts"), file1 },
{ Path.Combine(TargetDir, "Areas/Reporting/Models/Model.ts"), file2 }
}, compareComments: true);
}
}
} | Java |
package com.avsystem.scex.util.function;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.Collection;
public class StringUtilImpl implements StringUtil {
public static final StringUtilImpl INSTANCE = new StringUtilImpl();
private StringUtilImpl() {
}
@Override
public String concat(String... parts) {
return StringFunctions.concat(parts);
}
@Override
public boolean contains(String list, String item) {
return StringFunctions.contains(list, item);
}
@Override
public double extract(String string) {
return StringFunctions.extract(string);
}
@Override
public String regexFind(String value, String pattern) {
return StringFunctions.regexFind(value, pattern);
}
@Override
public String regexFindGroup(String value, String pattern) {
return StringFunctions.regexFindGroup(value, pattern);
}
@Override
public boolean regexMatches(String value, String pattern) {
return StringFunctions.regexMatches(value, pattern);
}
@Override
public String regexReplace(String value, String pattern, String replacement) {
return StringFunctions.regexReplace(value, pattern, replacement);
}
@Override
public String regexReplaceAll(String value, String pattern, String replacement) {
return StringFunctions.regexReplaceAll(value, pattern, replacement);
}
@Override
public String slice(String item, int from) {
return StringFunctions.slice(item, from);
}
@Override
public String slice(String item, int from, int to, boolean dot) {
return StringFunctions.slice(item, from, to, dot);
}
@Override
public String stripToAlphanumeric(String source, String replacement) {
return StringFunctions.stripToAlphanumeric(source, replacement);
}
/**
* Remove end for string if exist
*
* @param source source string
* @param end string to remove from the end of source
* @return string with removed end
*/
@Override
public String removeEnd(String source, String end) {
if (source != null && end != null) {
return source.endsWith(end) ? source.substring(0, source.length() - end.length()) : source;
}
return null;
}
/**
* Remove start from string if exist
*
* @param source source string
* @param start string to remove from the start of source
* @return string with removed end
*/
@Override
public String removeStart(String source, String start) {
if (source != null && start != null) {
return source.startsWith(start) ? source.substring(start.length(), source.length()) : source;
}
return null;
}
@Override
public String removeTRRoot(String source) {
if (source != null) {
if (source.startsWith("InternetGatewayDevice.")) {
source = source.replaceFirst("InternetGatewayDevice.", "");
} else if (source.startsWith("Device.")) {
source = source.replaceFirst("Device.", "");
}
}
return source;
}
@Override
public String random(int length) {
return RandomStringUtils.randomAlphanumeric(length);
}
/**
* Left pad a String with a specified String.
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return right padded String
*/
@Override
public String leftPad(String str, int size, String padStr) {
return StringFunctions.leftPad(str, size, padStr);
}
/**
* Right pad a String with a specified String.
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String
*/
@Override
public String rightPad(String str, int size, String padStr) {
return StringFunctions.rightPad(str, size, padStr);
}
@Override
public String subString(String str, int from, int to) {
return StringUtils.substring(str, from, to);
}
@Override
public String[] split(String str, String separator) {
return StringUtils.split(str, separator);
}
@Override
public String trimToEmpty(String str) {
return StringUtils.trimToEmpty(str);
}
@Override
public String replace(String str, String find, String replacement) {
return StringUtils.replace(str, find, replacement);
}
@Override
public String join(Collection<String> list, String separator) {
return StringUtils.join(list, separator);
}
@Override
public boolean stringContains(String source, String item) {
return StringUtils.contains(source, item);
}
@Override
public String hmacMD5(String str, String key) {
return new HmacUtils(HmacAlgorithms.HMAC_MD5, key).hmacHex(str);
}
}
| Java |
require 'minitest_helper'
require 'mocha/setup'
module Sidekiq
module Statistic
describe 'Middleware' do
def to_number(i)
i.match('\.').nil? ? Integer(i) : Float(i) rescue i.to_s
end
before { Sidekiq.redis(&:flushdb) }
let(:date){ Time.now.utc.to_date }
let(:actual) do
Sidekiq.redis do |conn|
redis_hash = {}
conn
.hgetall(REDIS_HASH)
.each do |keys, value|
*keys, last = keys.split(":")
keys.inject(redis_hash){ |hash, key| hash[key] || hash[key] = {} }[last.to_sym] = to_number(value)
end
redis_hash.values.last
end
end
it 'records statistic for passed worker' do
middlewared {}
assert_equal 1, actual['HistoryWorker'][:passed]
assert_equal nil, actual['HistoryWorker'][:failed]
end
it 'records statistic for failed worker' do
begin
middlewared do
raise StandardError.new('failed')
end
rescue
end
assert_equal nil, actual['HistoryWorker'][:passed]
assert_equal 1, actual['HistoryWorker'][:failed]
end
it 'records statistic for any workers' do
middlewared { sleep 0.001 }
begin
middlewared do
sleep 0.1
raise StandardError.new('failed')
end
rescue
end
middlewared { sleep 0.001 }
assert_equal 2, actual['HistoryWorker'][:passed]
assert_equal 1, actual['HistoryWorker'][:failed]
end
it 'support multithreaded calculations' do
workers = []
20.times do
workers << Thread.new do
25.times { middlewared {} }
end
end
workers.each(&:join)
assert_equal 500, actual['HistoryWorker'][:passed]
end
it 'removes 1/4 the timelist entries after crossing max_timelist_length' do
workers = []
Sidekiq::Statistic.configuration.max_timelist_length = 10
11.times do
middlewared {}
end
assert_equal 8, Sidekiq.redis { |conn| conn.llen("#{Time.now.strftime "%Y-%m-%d"}:HistoryWorker:timeslist") }
end
it 'supports ActiveJob workers' do
message = {
'class' => 'ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper',
'wrapped' => 'RealWorkerClassName'
}
middlewared(ActiveJobWrapper, message) {}
assert_equal actual.keys, ['RealWorkerClassName']
assert_equal 1, actual['RealWorkerClassName'][:passed]
assert_equal nil, actual['RealWorkerClassName'][:failed]
end
it 'supports mailers called from AJ' do
message = {
'class' => 'ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper',
'wrapped' => 'ActionMailer::DeliveryJob',
'args' => [{
'job_class' => 'ActionMailer::DeliveryJob',
'job_id'=>'cdcc67fb-8fdc-490c-9226-9c7f46a2dbaf',
'queue_name'=>'mailers',
'arguments' => ['WrappedMailer', 'welcome_email', 'deliver_now']
}]
}
middlewared(ActiveJobWrapper, message) {}
assert_equal actual.keys, ['WrappedMailer']
assert_equal 1, actual['WrappedMailer'][:passed]
assert_equal nil, actual['WrappedMailer'][:failed]
end
it 'records statistic for more than one worker' do
middlewared{}
middlewared(OtherHistoryWorker){}
assert_equal 1, actual['HistoryWorker'][:passed]
assert_equal nil, actual['HistoryWorker'][:failed]
assert_equal 1, actual['OtherHistoryWorker'][:passed]
assert_equal nil, actual['OtherHistoryWorker'][:failed]
end
it 'records queue statistic for each worker' do
message = { 'queue' => 'default' }
middlewared(HistoryWorker, message){}
message = { 'queue' => 'test' }
middlewared(HistoryWorkerWithQueue, message){}
assert_equal 'default', actual['HistoryWorker'][:queue]
assert_equal 'test', actual['HistoryWorkerWithQueue'][:queue]
end
end
end
end
| Java |
PHP with classes and PhpUnit | Java |
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *bitcoin_strings[] = {
QT_TRANSLATE_NOOP("bitcoin-core", ""
"%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=amkoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"AmKoin Alert\" admin@foo.com\n"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:"
"@STRENGTH)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv4: %s"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv6, "
"falling back to IPv4: %s"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Cannot obtain a lock on data directory %s. AmKoin is probably already "
"running."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Enter regression test mode, which uses a special chain in which blocks can "
"be solved instantly. This is intended for regression testing tools and app "
"development."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: The transaction was rejected! This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds!"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a relevant alert is received (%s in cmd is replaced by "
"message)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: "
"86400)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: "
"27000)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Set the number of script verification threads (up to 16, 0 = auto, <0 = "
"leave that many cores free, default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"mining or merchant applications"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Unable to bind to %s on this computer. AmKoin is probably already running."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: Displayed transactions may not be correct! You may need to upgrade, "
"or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong AmKoin will not work properly."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"You must set rpcpassword=<password> in the configuration file:\n"
"%s\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions."),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "AmKoin version"),
QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect through socks proxy"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of AmKoin"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error opening block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: system error: "),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to read block info"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to read block"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to sync block index"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block index"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block info"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write file info"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write to coin database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write transaction index"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write undo data"),
QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"),
QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using DNS lookup (default: 1 unless -connect)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Generate coins (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"),
QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 288, 0 = all)"),
QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-4, default: 3)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Incorrect or no genesis block found. Wrong datadir for network?"),
QT_TRANSLATE_NOOP("bitcoin-core", "Information"),
QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"),
QT_TRANSLATE_NOOP("bitcoin-core", "List commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 8333 or testnet: 18333)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Maintain a full transaction index (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("bitcoin-core", "Only accept block chain matching built-in checkpoints (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Output extra debugging information. Implies all other -debug* options"),
QT_TRANSLATE_NOOP("bitcoin-core", "Output extra network debugging information"),
QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the Bitcoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Select the version of socks proxy to use (4-5, default: 5)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or amkoind"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to debugger"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set the number of threads to service RPC calls (default: 4)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: amkoin.conf)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: amkoind.pid)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("bitcoin-core", "System error: "),
QT_TRANSLATE_NOOP("bitcoin-core", "This help message"),
QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"),
QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("bitcoin-core", "Transaction too large"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unknown -socks proxy version requested: %i"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"),
QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart AmKoin to complete"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("bitcoin-core", "You need to rebuild the database using -reindex to change -txindex"),
QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"),
}; | Java |
<!doctype html>
<!--[if IE 9 ]><html class="ie9" lang="en"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head>
<title>Flatastic - Checkout</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!--meta info-->
<meta name="author" content="">
<meta name="keywords" content="">
<meta name="description" content="">
<link rel="icon" type="image/ico" href="images/fav.ico">
<!--stylesheet include-->
<link rel="stylesheet" type="text/css" media="all" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" media="all" href="css/owl.carousel.css">
<link rel="stylesheet" type="text/css" media="all" href="css/owl.transitions.css">
<link rel="stylesheet" type="text/css" media="all" href="css/style.css">
<!--font include-->
<link href="css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<!--wide layout-->
<div class="wide_layout relative">
<!--[if (lt IE 9) | IE 9]>
<div style="background:#fff;padding:8px 0 10px;">
<div class="container" style="width:1170px;"><div class="row wrapper"><div class="clearfix" style="padding:9px 0 0;float:left;width:83%;"><i class="fa fa-exclamation-triangle scheme_color f_left m_right_10" style="font-size:25px;color:#e74c3c;"></i><b style="color:#e74c3c;">Attention! This page may not display correctly.</b> <b>You are using an outdated version of Internet Explorer. For a faster, safer browsing experience.</b></div><div class="t_align_r" style="float:left;width:16%;"><a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode" class="button_type_4 r_corners bg_scheme_color color_light d_inline_b t_align_c" target="_blank" style="margin-bottom:2px;">Update Now!</a></div></div></div></div>
<![endif]-->
<!--markup header-->
<header role="banner">
<!--header top part-->
<section class="h_top_part">
<div class="container">
<div class="row clearfix">
<div class="col-lg-4 col-md-4 col-sm-5 t_xs_align_c">
<p class="f_size_small">Welcome visitor can you <a href="#" data-popup="#login_popup">Log In</a> or <a href="#">Create an Account</a> </p>
</div>
<div class="col-lg-4 col-md-4 col-sm-2 t_align_c t_xs_align_c">
<p class="f_size_small">Call us toll free: <b class="color_dark">(123) 456-7890</b></p>
</div>
<nav class="col-lg-4 col-md-4 col-sm-5 t_align_r t_xs_align_c">
<ul class="d_inline_b horizontal_list clearfix f_size_small users_nav">
<li><a href="#" class="default_t_color">My Account</a></li>
<li><a href="#" class="default_t_color">Orders List</a></li>
<li><a href="#" class="default_t_color">Wishlist</a></li>
<li><a href="#" class="default_t_color">Checkout</a></li>
</ul>
</nav>
</div>
</div>
</section>
<!--header bottom part-->
<section class="h_bot_part container">
<div class="clearfix row">
<div class="col-lg-6 col-md-6 col-sm-4 t_xs_align_c">
<a href="index.html" class="logo m_xs_bottom_15 d_xs_inline_b">
<img src="images/logo.png" alt="">
</a>
</div>
<div class="col-lg-6 col-md-6 col-sm-8 t_align_r t_xs_align_c">
<ul class="d_inline_b horizontal_list clearfix t_align_l site_settings">
<!--like-->
<li>
<a role="button" href="#" class="button_type_1 color_dark d_block bg_light_color_1 r_corners tr_delay_hover box_s_none"><i class="fa fa-heart-o f_size_ex_large"></i><span class="count circle t_align_c">12</span></a>
</li>
<li class="m_left_5">
<a role="button" href="#" class="button_type_1 color_dark d_block bg_light_color_1 r_corners tr_delay_hover box_s_none"><i class="fa fa-files-o f_size_ex_large"></i><span class="count circle t_align_c">3</span></a>
</li>
<!--language settings-->
<li class="m_left_5 relative container3d">
<a role="button" href="#" class="button_type_2 color_dark d_block bg_light_color_1 r_corners tr_delay_hover box_s_none" id="lang_button"><img class="d_inline_middle m_right_10 m_mxs_right_0" src="images/flag_en.jpg" alt=""><span class="d_mxs_none">English</span></a>
<ul class="dropdown_list top_arrow color_light">
<li><a href="#" class="tr_delay_hover color_light"><img class="d_inline_middle" src="images/flag_en.jpg" alt="">English</a></li>
<li><a href="#" class="tr_delay_hover color_light"><img class="d_inline_middle" src="images/flag_fr.jpg" alt="">French</a></li>
<li><a href="#" class="tr_delay_hover color_light"><img class="d_inline_middle" src="images/flag_g.jpg" alt="">German</a></li>
<li><a href="#" class="tr_delay_hover color_light"><img class="d_inline_middle" src="images/flag_i.jpg" alt="">Italian</a></li>
<li><a href="#" class="tr_delay_hover color_light"><img class="d_inline_middle" src="images/flag_s.jpg" alt="">Spanish</a></li>
</ul>
</li>
<!--currency settings-->
<li class="m_left_5 relative container3d">
<a role="button" href="#" class="button_type_2 color_dark d_block bg_light_color_1 r_corners tr_delay_hover box_s_none" id="currency_button"><span class="scheme_color">$</span> <span class="d_mxs_none">US Dollar</span></a>
<ul class="dropdown_list top_arrow color_light">
<li><a href="#" class="tr_delay_hover color_light"><span class="scheme_color">$</span> US Dollar</a></li>
<li><a href="#" class="tr_delay_hover color_light"><span class="scheme_color">€</span> Euro</a></li>
<li><a href="#" class="tr_delay_hover color_light"><span class="scheme_color">£</span> Pound</a></li>
</ul>
</li>
<!--shopping cart-->
<li class="m_left_5 relative container3d" id="shopping_button">
<a role="button" href="#" class="button_type_3 color_light bg_scheme_color d_block r_corners tr_delay_hover box_s_none">
<span class="d_inline_middle shop_icon m_mxs_right_0">
<i class="fa fa-shopping-cart"></i>
<span class="count tr_delay_hover type_2 circle t_align_c">3</span>
</span>
<b class="d_mxs_none">$355</b>
</a>
<div class="shopping_cart top_arrow tr_all_hover r_corners">
<div class="f_size_medium sc_header">Recently added item(s)</div>
<ul class="products_list">
<li>
<div class="clearfix">
<!--product image-->
<img class="f_left m_right_10" src="images/shopping_c_img_1.jpg" alt="">
<!--product description-->
<div class="f_left product_description">
<a href="#" class="color_dark m_bottom_5 d_block">Cursus eleifend elit aenean auctor wisi et urna</a>
<span class="f_size_medium">Product Code PS34</span>
</div>
<!--product price-->
<div class="f_left f_size_medium">
<div class="clearfix">
1 x <b class="color_dark">$99.00</b>
</div>
<button class="close_product color_dark tr_hover"><i class="fa fa-times"></i></button>
</div>
</div>
</li>
<li>
<div class="clearfix">
<!--product image-->
<img class="f_left m_right_10" src="images/shopping_c_img_2.jpg" alt="">
<!--product description-->
<div class="f_left product_description">
<a href="#" class="color_dark m_bottom_5 d_block">Cursus eleifend elit aenean auctor wisi et urna</a>
<span class="f_size_medium">Product Code PS34</span>
</div>
<!--product price-->
<div class="f_left f_size_medium">
<div class="clearfix">
1 x <b class="color_dark">$99.00</b>
</div>
<button class="close_product color_dark tr_hover"><i class="fa fa-times"></i></button>
</div>
</div>
</li>
<li>
<div class="clearfix">
<!--product image-->
<img class="f_left m_right_10" src="images/shopping_c_img_3.jpg" alt="">
<!--product description-->
<div class="f_left product_description">
<a href="#" class="color_dark m_bottom_5 d_block">Cursus eleifend elit aenean auctor wisi et urna</a>
<span class="f_size_medium">Product Code PS34</span>
</div>
<!--product price-->
<div class="f_left f_size_medium">
<div class="clearfix">
1 x <b class="color_dark">$99.00</b>
</div>
<button class="close_product color_dark tr_hover"><i class="fa fa-times"></i></button>
</div>
</div>
</li>
</ul>
<!--total price-->
<ul class="total_price bg_light_color_1 t_align_r color_dark">
<li class="m_bottom_10">Tax: <span class="f_size_large sc_price t_align_l d_inline_b m_left_15">$0.00</span></li>
<li class="m_bottom_10">Discount: <span class="f_size_large sc_price t_align_l d_inline_b m_left_15">$37.00</span></li>
<li>Total: <b class="f_size_large bold scheme_color sc_price t_align_l d_inline_b m_left_15">$999.00</b></li>
</ul>
<div class="sc_footer t_align_c">
<a href="#" role="button" class="button_type_4 d_inline_middle bg_light_color_2 r_corners color_dark t_align_c tr_all_hover m_mxs_bottom_5">View Cart</a>
<a href="#" role="button" class="button_type_4 bg_scheme_color d_inline_middle r_corners tr_all_hover color_light">Checkout</a>
</div>
</div>
</li>
</ul>
</div>
</div>
</section>
<!--main menu container-->
<section class="menu_wrap relative">
<div class="container clearfix">
<!--button for responsive menu-->
<button id="menu_button" class="r_corners centered_db d_none tr_all_hover d_xs_block m_bottom_10">
<span class="centered_db r_corners"></span>
<span class="centered_db r_corners"></span>
<span class="centered_db r_corners"></span>
</button>
<!--main menu-->
<nav role="navigation" class="f_left f_xs_none d_xs_none">
<ul class="horizontal_list main_menu clearfix">
<li class="relative f_xs_none m_xs_bottom_5"><a href="index.html" class="tr_delay_hover color_light tt_uppercase"><b>Home</b></a>
<!--sub menu-->
<div class="sub_menu_wrap top_arrow d_xs_none type_2 tr_all_hover clearfix r_corners">
<ul class="sub_menu">
<li><a class="color_dark tr_delay_hover" href="index.html">Home Variant 1</a></li>
<li><a class="color_dark tr_delay_hover" href="index_layout_2.html">Home Variant 2</a></li>
<li><a class="color_dark tr_delay_hover" href="index_layout_wide.html">Home Variant 3</a></li>
<li><a class="color_dark tr_delay_hover" href="index_corporate.html">Home Variant 4</a></li>
</ul>
</div>
</li>
<li class="relative f_xs_none m_xs_bottom_5"><a href="index_layout_wide.html" class="tr_delay_hover color_light tt_uppercase"><b>Sliders</b></a>
<!--sub menu-->
<div class="sub_menu_wrap top_arrow d_xs_none type_2 tr_all_hover clearfix r_corners">
<ul class="sub_menu">
<li><a class="color_dark tr_delay_hover" href="index_layout_wide.html">Revolution Slider</a></li>
<li><a class="color_dark tr_delay_hover" href="index.html">Camera Slider</a></li>
<li><a class="color_dark tr_delay_hover" href="index_layout_2.html">Flex Slider</a></li>
</ul>
</div>
</li>
<li class="relative f_xs_none m_xs_bottom_5"><a href="category_grid.html" class="tr_delay_hover color_light tt_uppercase"><b>Shop</b></a>
<!--sub menu-->
<div class="sub_menu_wrap top_arrow d_xs_none tr_all_hover clearfix r_corners w_xs_auto">
<div class="f_left f_xs_none">
<b class="color_dark m_left_20 m_bottom_5 m_top_5 d_inline_b">Dresses</b>
<ul class="sub_menu first">
<li><a class="color_dark tr_delay_hover" href="#">Evening Dresses</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Casual Dresses</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Party Dresses</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Maxi Dresses</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Midi Dresses</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Strapless Dresses</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Day Dresses</a></li>
</ul>
</div>
<div class="f_left m_left_10 m_xs_left_0 f_xs_none">
<b class="color_dark m_left_20 m_bottom_5 m_top_5 d_inline_b">Accessories</b>
<ul class="sub_menu">
<li><a class="color_dark tr_delay_hover" href="#">Bags and Purces</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Belts</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Scarves</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Gloves</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Jewellery</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Sunglasses</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Hair Accessories</a></li>
</ul>
</div>
<div class="f_left m_left_10 m_xs_left_0 f_xs_none">
<b class="color_dark m_left_20 m_bottom_5 m_top_5 d_inline_b">Tops</b>
<ul class="sub_menu">
<li><a class="color_dark tr_delay_hover" href="#">Evening Tops</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Long Sleeved</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Short Sleeved</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Sleeveless</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Tanks</a></li>
<li><a class="color_dark tr_delay_hover" href="#">Tunics</a></li>
</ul>
</div>
<img src="images/woman_image_1.jpg" class="d_sm_none f_right m_bottom_10" alt="">
</div>
</li>
<li class="relative f_xs_none m_xs_bottom_5"><a href="#" class="tr_delay_hover color_light tt_uppercase"><b>Portfolio</b></a>
<!--sub menu-->
<div class="sub_menu_wrap top_arrow d_xs_none type_2 tr_all_hover clearfix r_corners">
<ul class="sub_menu">
<li><a class="color_dark tr_delay_hover" href="portfolio_two_columns.html">Portfolio 2 Columns</a></li>
<li><a class="color_dark tr_delay_hover" href="portfolio_three_columns.html">Portfolio 3 Columns</a></li>
<li><a class="color_dark tr_delay_hover" href="portfolio_four_columns.html">Portfolio 4 Columns</a></li>
<li><a class="color_dark tr_delay_hover" href="portfolio_masonry.html">Masonry Portfolio</a></li>
<li><a class="color_dark tr_delay_hover" href="portfolio_single_1.html">Single Portfolio Post v1</a></li>
<li><a class="color_dark tr_delay_hover" href="portfolio_single_2.html">Single Portfolio Post v2</a></li>
</ul>
</div>
</li>
<li class="relative current f_xs_none m_xs_bottom_5"><a href="category_grid.html" class="tr_delay_hover color_light tt_uppercase"><b>Pages</b></a>
<!--sub menu-->
<div class="sub_menu_wrap top_arrow d_xs_none type_2 tr_all_hover clearfix r_corners">
<ul class="sub_menu">
<li><a class="color_dark tr_delay_hover" href="category_grid.html">Grid View Category Page</a></li>
<li><a class="color_dark tr_delay_hover" href="category_list.html">List View Category Page</a></li>
<li><a class="color_dark tr_delay_hover" href="category_no_products.html">Category Page Without Products</a></li>
<li><a class="color_dark tr_delay_hover" href="product_page_sidebar.html">Product Page With Sidebar</a></li>
<li><a class="color_dark tr_delay_hover" href="full_width_product_page.html">Full Width Product Page</a></li>
<li><a class="color_dark tr_delay_hover" href="wishlist.html">Wishlist</a></li>
<li><a class="color_dark tr_delay_hover" href="compare_products.html">Compare Products</a></li>
<li><a class="color_dark tr_delay_hover" href="checkout.html">Checkout</a></li>
<li><a class="color_dark tr_delay_hover" href="manufacturers.html">Manufacturers</a></li>
<li><a class="color_dark tr_delay_hover" href="manufacturer_details.html">Manufacturer Page</a></li>
<li><a class="color_dark tr_delay_hover" href="orders_list.html">Orders List</a></li>
<li><a class="color_dark tr_delay_hover" href="order_details.html">Order Details</a></li>
</ul>
</div>
</li>
<li class="relative f_xs_none m_xs_bottom_5"><a href="blog.html" class="tr_delay_hover color_light tt_uppercase"><b>Blog</b></a>
<!--sub menu-->
<div class="sub_menu_wrap top_arrow d_xs_none type_2 tr_all_hover clearfix r_corners">
<ul class="sub_menu">
<li><a class="color_dark tr_delay_hover" href="blog.html">Blog page</a></li>
<li><a class="color_dark tr_delay_hover" href="blog_post.html">Single Blog Post page</a></li>
</ul>
</div>
</li>
<li class="relative f_xs_none m_xs_bottom_5"><a href="features_shortcodes.html" class="tr_delay_hover color_light tt_uppercase"><b>Features</b></a>
<!--sub menu-->
<div class="sub_menu_wrap top_arrow d_xs_none type_2 tr_all_hover clearfix r_corners">
<ul class="sub_menu">
<li><a class="color_dark tr_delay_hover" href="features_shortcodes.html">Shortcodes</a></li>
<li><a class="color_dark tr_delay_hover" href="features_typography.html">Typography</a></li>
</ul>
</div>
</li>
<li class="relative f_xs_none m_xs_bottom_5"><a href="contact.html" class="tr_delay_hover color_light tt_uppercase"><b>Contact</b></a></li>
</ul>
</nav>
<button class="f_right search_button tr_all_hover f_xs_none d_xs_none">
<i class="fa fa-search"></i>
</button>
</div>
<!--search form-->
<div class="searchform_wrap tf_xs_none tr_all_hover">
<div class="container vc_child h_inherit relative">
<form role="search" class="d_inline_middle full_width">
<input type="text" name="search" placeholder="Type text and hit enter" class="f_size_large">
</form>
<button class="close_search_form tr_all_hover d_xs_none color_dark">
<i class="fa fa-times"></i>
</button>
</div>
</div>
</section>
</header>
<!--breadcrumbs-->
<section class="breadcrumbs">
<div class="container">
<ul class="horizontal_list clearfix bc_list f_size_medium">
<li class="m_right_10 current"><a href="#" class="default_t_color">Home<i class="fa fa-angle-right d_inline_middle m_left_10"></i></a></li>
<li class="m_right_10 current"><a href="#" class="default_t_color">Checkout<i class="fa fa-angle-right d_inline_middle m_left_10"></i></a></li>
<li><a href="#" class="default_t_color">Shopping Cart</a></li>
</ul>
</div>
</section>
<!--content-->
<div class="page_content_offset">
<div class="container">
<div class="row clearfix">
<!--left content column-->
<section class="col-lg-9 col-md-9 col-sm-9 m_xs_bottom_30">
<h2 class="tt_uppercase color_dark m_bottom_25">Cart</h2>
<!--cart table-->
<table class="table_type_4 responsive_table full_width r_corners wraper shadow t_align_l t_xs_align_c m_bottom_30">
<thead>
<tr class="f_size_large">
<!--titles for td-->
<th>Product Image & Name</th>
<th>SKU</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody>
<tr>
<!--Product name and image-->
<td data-title="Product Image & name" class="t_md_align_c">
<img src="images/quick_view_img_10.jpg" alt="" class="m_md_bottom_5 d_xs_block d_xs_centered">
<a href="#" class="d_inline_b m_left_5 color_dark">Eget elementum vel</a>
</td>
<!--product key-->
<td data-title="SKU">PS01</td>
<!--product price-->
<td data-title="Price">
<s>$102.00</s>
<p class="f_size_large color_dark">$102.00</p>
</td>
<!--quanity-->
<td data-title="Quantity">
<div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10">
<button class="bg_tr d_block f_left" data-direction="down">-</button>
<input type="text" name="" readonly value="1" class="f_left">
<button class="bg_tr d_block f_left" data-direction="up">+</button>
</div>
<div>
<a href="#" class="color_dark"><i class="fa fa-check f_size_medium m_right_5"></i>Update</a><br>
<a href="#" class="color_dark"><i class="fa fa-times f_size_medium m_right_5"></i>Remove</a><br>
</div>
</td>
<!--subtotal-->
<td data-title="Subtotal">
<p class="f_size_large fw_medium scheme_color">$102.00</p>
</td>
</tr>
<tr>
<!--Product name and image-->
<td data-title="Product Image & name" class="t_md_align_c">
<img src="images/wishlist_img_1.jpg" alt="" class="m_md_bottom_5 d_xs_block d_xs_centered">
<a href="#" class="d_inline_b m_left_5 color_dark">Aenean nec eros</a>
</td>
<!--product key-->
<td data-title="SKU">PS02</td>
<!--product price-->
<td data-title="Price">
<p class="f_size_large color_dark">$52.00</p>
</td>
<!--quanity-->
<td data-title="Quantity">
<div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10">
<button class="bg_tr d_block f_left" data-direction="down">-</button>
<input type="text" name="" readonly value="1" class="f_left">
<button class="bg_tr d_block f_left" data-direction="up">+</button>
</div>
<div>
<a href="#" class="color_dark"><i class="fa fa-check f_size_medium m_right_5"></i>Update</a><br>
<a href="#" class="color_dark"><i class="fa fa-times f_size_medium m_right_5"></i>Remove</a><br>
</div>
</td>
<!--subtotal-->
<td data-title="Subtotal">
<p class="f_size_large fw_medium scheme_color">$52.00</p>
</td>
</tr>
<tr>
<!--Product name and image-->
<td data-title="Product Image & name" class="t_md_align_c">
<img src="images/wishlist_img_2.jpg" alt="" class="m_md_bottom_5 d_xs_block d_xs_centered">
<a href="#" class="d_inline_b m_left_5 color_dark">Ut tellus dolor dapibus</a>
</td>
<!--product key-->
<td data-title="SKU">PS03</td>
<!--product price-->
<td data-title="Price">
<p class="f_size_large color_dark">$360.00</p>
</td>
<!--quanity-->
<td data-title="Quantity">
<div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10">
<button class="bg_tr d_block f_left" data-direction="down">-</button>
<input type="text" name="" readonly value="1" class="f_left">
<button class="bg_tr d_block f_left" data-direction="up">+</button>
</div>
<div>
<a href="#" class="color_dark"><i class="fa fa-check f_size_medium m_right_5"></i>Update</a><br>
<a href="#" class="color_dark"><i class="fa fa-times f_size_medium m_right_5"></i>Remove</a><br>
</div>
</td>
<!--subtotal-->
<td data-title="Subtotal">
<p class="f_size_large fw_medium scheme_color">$360.00</p>
</td>
</tr>
<!--prices-->
<tr>
<td colspan="4">
<p class="fw_medium f_size_large t_align_r t_xs_align_c">Coupon Discount:</p>
</td>
<td colspan="1">
<p class="fw_medium f_size_large color_dark">$-74.96</p>
</td>
</tr>
<tr>
<td colspan="4">
<p class="fw_medium f_size_large t_align_r t_xs_align_c">Subtotal:</p>
</td>
<td colspan="1">
<p class="fw_medium f_size_large color_dark">$95.00</p>
</td>
</tr>
<tr>
<td colspan="4">
<p class="fw_medium f_size_large t_align_r t_xs_align_c">Payment Fee:</p>
</td>
<td colspan="1">
<p class="fw_medium f_size_large color_dark">$6.05</p>
</td>
</tr>
<tr>
<td colspan="4">
<p class="fw_medium f_size_large t_align_r t_xs_align_c">Shipment Fee:</p>
</td>
<td colspan="1">
<p class="fw_medium f_size_large color_dark">$0.00</p>
</td>
</tr>
<tr>
<td colspan="4">
<p class="fw_medium f_size_large t_align_r t_xs_align_c">Tax Total:</p>
</td>
<td colspan="1">
<p class="fw_medium f_size_large color_dark">$17.54</p>
</td>
</tr>
<!--total-->
<tr>
<td colspan="4" class="v_align_m d_ib_offset_large t_xs_align_l">
<!--coupon-->
<form class="d_ib_offset_0 d_inline_middle half_column d_xs_block w_xs_full m_xs_bottom_5">
<input type="text" placeholder="Enter your coupon code" name="" class="r_corners f_size_medium">
<button class="button_type_4 r_corners bg_light_color_2 m_left_5 mw_0 tr_all_hover color_dark">Save</button>
</form>
<p class="fw_medium f_size_large t_align_r scheme_color p_xs_hr_0 d_inline_middle half_column d_ib_offset_normal d_xs_block w_xs_full t_xs_align_c">Total:</p>
</td>
<td colspan="1" class="v_align_m">
<p class="fw_medium f_size_large scheme_color m_xs_bottom_10">$101.05</p>
</td>
</tr>
</tbody>
</table>
<!--tabs-->
<div class="tabs m_bottom_45">
<!--tabs navigation-->
<nav>
<ul class="tabs_nav horizontal_list clearfix">
<li><a href="#tab-1" class="bg_light_color_1 color_dark tr_delay_hover r_corners d_block">Login</a></li>
<li><a href="#tab-2" class="bg_light_color_1 color_dark tr_delay_hover r_corners d_block">Register</a></li>
</ul>
</nav>
<section class="tabs_content shadow r_corners">
<div id="tab-1">
<!--login form-->
<h5 class="fw_medium m_bottom_15">I am Already Registered</h5>
<form>
<ul>
<li class="clearfix m_bottom_15">
<div class="half_column type_2 f_left">
<label for="username" class="m_bottom_5 d_inline_b">Username</label>
<input type="text" id="username" name="" class="r_corners full_width m_bottom_5">
<a href="#" class="color_dark f_size_medium">Forgot your username?</a>
</div>
<div class="half_column type_2 f_left">
<label for="pass" class="m_bottom_5 d_inline_b">Password</label>
<input type="password" id="pass" name="" class="r_corners full_width m_bottom_5">
<a href="#" class="color_dark f_size_medium">Forgot your password?</a>
</div>
</li>
<li class="m_bottom_15">
<input type="checkbox" class="d_none" name="checkbox_4" id="checkbox_4"><label for="checkbox_4">Remember me</label>
</li>
<li><button class="button_type_4 r_corners bg_scheme_color color_light tr_all_hover">Log In</button></li>
</ul>
</form>
</div>
<div id="tab-2">
<form>
<ul>
<li class="m_bottom_25">
<label for="d_name" class="d_inline_b m_bottom_5 required">Displayed Name</label>
<input type="text" id="d_name" name="" class="r_corners full_width">
</li>
<li class="m_bottom_5">
<input type="checkbox" class="d_none" name="checkbox_5" id="checkbox_5"><label for="checkbox_5">Create an account</label>
</li>
<li class="m_bottom_15">
<label for="u_name" class="d_inline_b m_bottom_5 required">Username</label>
<input type="text" id="u_name" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="u_email" class="d_inline_b m_bottom_5 required">Email</label>
<input type="email" id="u_email" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="u_pass" class="d_inline_b m_bottom_5 required">Password</label>
<input type="password" id="u_pass" name="" class="r_corners full_width">
</li>
<li>
<label for="u_repeat_pass" class="d_inline_b m_bottom_5 required">Confirm Password</label>
<input type="password" id="u_repeat_pass" name="" class="r_corners full_width">
</li>
</ul>
</form>
</div>
</section>
</div>
<h2 class="color_dark tt_uppercase m_bottom_25">Bill To & Shipment Information</h2>
<div class="bs_inner_offsets bg_light_color_3 shadow r_corners m_bottom_45">
<div class="row clearfix">
<div class="col-lg-6 col-md-6 col-sm-6 m_xs_bottom_30">
<h5 class="fw_medium m_bottom_15">Bill To</h5>
<form>
<ul>
<li class="m_bottom_15">
<label for="c_name_1" class="d_inline_b m_bottom_5">Company Name</label>
<input type="text" id="c_name_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label class="d_inline_b m_bottom_5">Title</label>
<!--product name select-->
<div class="custom_select relative">
<div class="select_title type_2 r_corners relative color_dark mw_0">Mr</div>
<ul class="select_list d_none"></ul>
<select name="product_name">
<option value="Mr 1">Mr 1</option>
<option value="Ms">Ms</option>
</select>
</div>
</li>
<li class="m_bottom_15">
<label for="f_name_1" class="d_inline_b m_bottom_5 required">First Name</label>
<input type="text" id="f_name_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="m_name_1" class="d_inline_b m_bottom_5 required">Middle Name</label>
<input type="text" id="m_name_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="l_name_1" class="d_inline_b m_bottom_5 required">Last Name</label>
<input type="text" id="l_name_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="address_1" class="d_inline_b m_bottom_5 required">Address 1</label>
<input type="text" id="address_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="address_1_1" class="d_inline_b m_bottom_5 required">Address 2</label>
<input type="text" id="address_1_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="code_1" class="d_inline_b m_bottom_5 required">Zip / Postal Code</label>
<input type="text" id="code_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="city_1" class="d_inline_b m_bottom_5 required">City</label>
<input type="text" id="city_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label class="d_inline_b m_bottom_5 required">Country</label>
<!--product name select-->
<div class="custom_select relative">
<div class="select_title type_2 r_corners relative color_dark mw_0">Please select</div>
<ul class="select_list d_none"></ul>
<select name="product_name">
<option value="England">England</option>
<option value="Australia">Australia</option>
<option value="Austria">Austria</option>
</select>
</div>
</li>
<li class="m_bottom_15">
<label class="d_inline_b m_bottom_5 required">State / Province / Region</label>
<!--product name select-->
<div class="custom_select relative">
<div class="select_title type_2 r_corners relative color_dark mw_0">Please select</div>
<ul class="select_list d_none"></ul>
<select name="product_name">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</li>
<li class="m_bottom_15">
<label for="phone_1" class="d_inline_b m_bottom_5">Phone</label>
<input type="text" id="phone_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="m_phone_1" class="d_inline_b m_bottom_5">Mobile Phone</label>
<input type="text" id="m_phone_1" name="" class="r_corners full_width">
</li>
<li>
<label for="fax_1" class="d_inline_b m_bottom_5">Fax</label>
<input type="text" id="fax_1" name="" class="r_corners full_width">
</li>
</ul>
</form>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<h5 class="fw_medium m_bottom_15">Ship To</h5>
<form>
<ul>
<li class="m_bottom_5">
<input type="checkbox" checked class="d_none" name="checkbox_6" id="checkbox_6"><label for="checkbox_6">Add/Edit shipment address</label>
</li>
<li class="m_bottom_15">
<label for="a_name_1" class="d_inline_b m_bottom_5">Address Nickname</label>
<input type="text" id="a_name_1" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="c_name_2" class="d_inline_b m_bottom_5">Company Name</label>
<input type="text" id="c_name_2" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="f_name_2" class="d_inline_b m_bottom_5">First Name</label>
<input type="text" id="f_name_2" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="m_name_2" class="d_inline_b m_bottom_5">Middle Name</label>
<input type="text" id="m_name_2" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="l_name_2" class="d_inline_b m_bottom_5">Last Name</label>
<input type="text" id="l_name_2" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="address_2" class="d_inline_b m_bottom_5">Address 1</label>
<input type="text" id="address_2" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="address_1_2" class="d_inline_b m_bottom_5">Address 2</label>
<input type="text" id="address_1_2" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="code_2" class="d_inline_b m_bottom_5">Zip / Postal Code</label>
<input type="text" id="code_2" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="city_2" class="d_inline_b m_bottom_5">City</label>
<input type="text" id="city_2" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label class="d_inline_b m_bottom_5">Country</label>
<!--product name select-->
<div class="custom_select relative">
<div class="select_title type_2 r_corners relative color_dark mw_0">Please select</div>
<ul class="select_list d_none"></ul>
<select name="product_name">
<option value="England">England</option>
<option value="Australia">Australia</option>
<option value="Austria">Austria</option>
</select>
</div>
</li>
<li class="m_bottom_15">
<label class="d_inline_b m_bottom_5">State / Province / Region</label>
<!--product name select-->
<div class="custom_select relative">
<div class="select_title type_2 r_corners relative color_dark mw_0">Please select</div>
<ul class="select_list d_none"></ul>
<select name="product_name">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</li>
<li class="m_bottom_15">
<label for="phone_2" class="d_inline_b m_bottom_5">Phone</label>
<input type="text" id="phone_2" name="" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<label for="m_phone_2" class="d_inline_b m_bottom_5">Mobile Phone</label>
<input type="text" id="m_phone_2" name="" class="r_corners full_width">
</li>
<li>
<label for="fax_2" class="d_inline_b m_bottom_5">Fax</label>
<input type="text" id="fax_2" name="" class="r_corners full_width">
</li>
</ul>
</form>
</div>
</div>
</div>
<h2 class="tt_uppercase color_dark m_bottom_30">Shipment Information</h2>
<div class="bs_inner_offsets bg_light_color_3 shadow r_corners m_bottom_45">
<figure class="block_select clearfix relative m_bottom_15">
<input type="radio" checked name="radio_1" class="d_none">
<img src="images/shipment_logo.jpg" alt="" class="f_left m_right_20 f_mxs_none m_mxs_bottom_10">
<figcaption>
<h5 class="color_dark fw_medium m_bottom_15 m_sm_bottom_5">Shipment Method 1</h5>
<p>Ut tellus dolor, dapibus eget, elementum vel, cursus eleifend, elit. Aenean auctor wisi et urna. Aliquam erat volutpat. Duis ac turpis. Donec sit amet eros. Lorem ipsum dolor sit amet, consecvtetuer. </p>
</figcaption>
</figure>
<hr class="m_bottom_20">
<figure class="block_select clearfix relative">
<input type="radio" name="radio_1" class="d_none">
<img src="images/shipment_logo.jpg" alt="" class="f_left m_right_20 f_mxs_none m_mxs_bottom_10">
<figcaption>
<h5 class="color_dark fw_medium m_bottom_15 m_sm_bottom_5">Shipment Method 2</h5>
<p>Ut tellus dolor, dapibus eget, elementum vel, cursus eleifend, elit. Aenean auctor wisi et urna. Aliquam erat volutpat. Duis ac turpis. Donec sit amet eros.</p>
</figcaption>
</figure>
</div>
<h2 class="tt_uppercase color_dark m_bottom_30">Payment</h2>
<div class="bs_inner_offsets bg_light_color_3 shadow r_corners m_bottom_45">
<figure class="block_select clearfix relative m_bottom_15">
<input type="radio" checked name="radio_2" class="d_none">
<img src="images/payment_logo.jpg" alt="" class="f_left m_right_20 f_mxs_none m_mxs_bottom_10">
<figcaption class="d_table d_sm_block">
<div class="d_table_cell d_sm_block p_sm_right_0 p_right_45 m_mxs_bottom_5">
<h5 class="color_dark fw_medium m_bottom_15 m_sm_bottom_5">Payment Method 1</h5>
<p>Ut tellus dolor, dapibus eget, elementum vel, cursus eleifend, elit. Aenean auctor wisi et urna. Aliquam erat volutpat. Duis ac turp. Donec sit amet eros. </p>
</div>
<div class="d_table_cell d_sm_block discount">
<h5 class="color_dark fw_medium m_bottom_15 m_sm_bottom_0">Discount/Fee</h5>
<p class="color_dark">$8.48</p>
</div>
</figcaption>
</figure>
<hr class="m_bottom_20">
<figure class="block_select clearfix relative">
<input type="radio" name="radio_2" class="d_none">
<img src="images/payment_logo.jpg" alt="" class="f_left m_right_20 f_mxs_none m_mxs_bottom_10">
<figcaption>
<h5 class="color_dark fw_medium m_bottom_15 m_sm_bottom_5">Payment Method 2</h5>
<p>Lorem ipsum dolor sit amet, consecvtetuer adipiscing elit. Mauris fermentum dictum magna.
Sed laoreet aliquam leo. Ut tellus dolor, dapibus eget, elementum vel, cursus eleifend, elit.</p>
</figcaption>
</figure>
</div>
<h2 class="tt_uppercase color_dark m_bottom_30">Terms of service</h2>
<div class="bs_inner_offsets bg_light_color_3 shadow r_corners m_bottom_45">
<p class="m_bottom_10">Ut tellus dolor, dapibus eget, elementum vel, cursus eleifend, elit. Aenean auctor wisi et urna. Aliquam erat volutpat. Duis ac turpis. Donec sit amet eros. Lorem ipsum dolor sit amet, consecvtetuer adipiscing elit. Mauris fermentum dictum magna. Sed laoreet aliquam leo. Ut tellus dolor, dapibus eget, elementum vel, cursus eleifend, elit. Aenean auctor wisi et urna. Aliquam erat volutpat. Duis ac turpis. Integer rutrum ante eu lacus.Vestibulum libero nisl, porta vel, scelerisque eget, malesuada at, neque. </p>
<p>Vivamus eget nibh. Etiam cursus leo vel metus. Nulla facilisi. Aenean nec eros. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse sollicitudin velit sed leo. Ut pharetra augue nec augue. Nam elit agna,endrerit sit amet, tincidunt ac, viverra sed, nulla. Donec porta diam eu massa. Quisque diam lorem, interdum vitae,dapibus ac, scelerisque vitae, pede. Donec eget tellus non erat lacinia fermentum. Donec in velit vel ipsum auctor pulvinar. </p>
</div>
<h2 class="tt_uppercase color_dark m_bottom_30">Notes and special requests</h2>
<!--requests table-->
<table class="table_type_5 full_width r_corners wraper shadow t_align_l">
<tr>
<td colspan="2">
<label for="notes" class="d_inline_b m_bottom_5">Notes and special requests:</label>
<textarea id="notes" class="r_corners notes full_width"></textarea>
</td>
</tr>
<tr>
<td class="t_align_r">
<p class="f_size_large fw_medium">Coupon Discount:</p>
</td>
<td>
<p class="f_size_large fw_medium color_dark">$-74.96</p>
</td>
</tr>
<tr>
<td class="t_align_r">
<p class="f_size_large fw_medium">Subtotal:</p>
</td>
<td>
<p class="f_size_large fw_medium color_dark">$95.00</p>
</td>
</tr>
<tr>
<td class="t_align_r">
<p class="f_size_large fw_medium">Payment Fee:</p>
</td>
<td>
<p class="f_size_large fw_medium color_dark">$6.05</p>
</td>
</tr>
<tr>
<td class="t_align_r">
<p class="f_size_large fw_medium">Shipment Fee:</p>
</td>
<td>
<p class="f_size_large fw_medium color_dark">$0.00</p>
</td>
</tr>
<tr>
<td class="t_align_r">
<p class="f_size_large fw_medium">Tax Total:</p>
</td>
<td>
<p class="f_size_large fw_medium color_dark">$17.54</p>
</td>
</tr>
<tr>
<td class="t_align_r">
<p class="f_size_large fw_medium scheme_color">Total:</p>
</td>
<td>
<p class="f_size_large fw_medium scheme_color">$101.05</p>
</td>
</tr>
<tr>
<td colspan="2">
<input type="checkbox" name="checkbox_8" id="checkbox_8" class="d_none"><label for="checkbox_8">I agree to the Terms of Service (Terms of service)</label>
</td>
</tr>
<tr>
<td colspan="2">
<button class="button_type_6 bg_scheme_color f_size_large r_corners tr_all_hover color_light m_bottom_20">Confirm Purchase</button>
</td>
</tr>
</table>
</section>
<!--right column-->
<aside class="col-lg-3 col-md-3 col-sm-3">
<!--widgets-->
<figure class="widget shadow r_corners wrapper m_bottom_30">
<figcaption>
<h3 class="color_light">Categories</h3>
</figcaption>
<div class="widget_content">
<!--Categories list-->
<ul class="categories_list">
<li class="active">
<a href="#" class="f_size_large scheme_color d_block relative">
<b>Women</b>
<span class="bg_light_color_1 r_corners f_right color_dark talign_c"></span>
</a>
<!--second level-->
<ul>
<li class="active">
<a href="#" class="d_block f_size_large color_dark relative">
Dresses<span class="bg_light_color_1 r_corners f_right color_dark talign_c"></span>
</a>
<!--third level-->
<ul>
<li><a href="#" class="color_dark d_block">Evening Dresses</a></li>
<li><a href="#" class="color_dark d_block">Casual Dresses</a></li>
<li><a href="#" class="color_dark d_block">Party Dresses</a></li>
</ul>
</li>
<li>
<a href="#" class="d_block f_size_large color_dark relative">
Accessories<span class="bg_light_color_1 r_corners f_right color_dark talign_c"></span>
</a>
</li>
<li>
<a href="#" class="d_block f_size_large color_dark relative">
Tops<span class="bg_light_color_1 r_corners f_right color_dark talign_c"></span>
</a>
</li>
</ul>
</li>
<li>
<a href="#" class="f_size_large color_dark d_block relative">
<b>Men</b>
<span class="bg_light_color_1 r_corners f_right color_dark talign_c"></span>
</a>
<!--second level-->
<ul class="d_none">
<li>
<a href="#" class="d_block f_size_large color_dark relative">
Shorts<span class="bg_light_color_1 r_corners f_right color_dark talign_c"></span>
</a>
<!--third level-->
<ul class="d_none">
<li><a href="#" class="color_dark d_block">Evening</a></li>
<li><a href="#" class="color_dark d_block">Casual</a></li>
<li><a href="#" class="color_dark d_block">Party</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#" class="f_size_large color_dark d_block relative">
<b>Kids</b>
<span class="bg_light_color_1 r_corners f_right color_dark talign_c"></span>
</a>
</li>
</ul>
</div>
</figure>
<!--compare products-->
<figure class="widget shadow r_corners wrapper m_bottom_30">
<figcaption>
<h3 class="color_light">Compare Products</h3>
</figcaption>
<div class="widget_content">
<div class="clearfix m_bottom_15 relative cw_product">
<img src="images/bestsellers_img_1.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block bt_link">Ut tellus dolor dapibus</a>
<button type="button" class="f_size_medium f_right color_dark bg_tr tr_all_hover close_fieldset"><i class="fa fa-times lh_inherit"></i></button>
</div>
<hr class="m_bottom_15">
<div class="clearfix m_bottom_25 relative cw_product">
<img src="images/bestsellers_img_2.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block bt_link">Elemenum vel</a>
<button type="button" class="f_size_medium f_right color_dark bg_tr tr_all_hover close_fieldset"><i class="fa fa-times lh_inherit"></i></button>
</div>
<a href="#" class="color_dark"><i class="fa fa-files-o m_right_10"></i>Go to Compare</a>
</div>
</figure>
<!--wishlist-->
<figure class="widget shadow r_corners wrapper m_bottom_30">
<figcaption>
<h3 class="color_light">Wishlist</h3>
</figcaption>
<div class="widget_content">
<div class="clearfix m_bottom_15 relative cw_product">
<img src="images/bestsellers_img_1.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block bt_link">Ut tellus dolor dapibus</a>
<button type="button" class="f_size_medium f_right color_dark bg_tr tr_all_hover close_fieldset"><i class="fa fa-times lh_inherit"></i></button>
</div>
<hr class="m_bottom_15">
<div class="clearfix m_bottom_25 relative cw_product">
<img src="images/bestsellers_img_2.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block bt_link">Elemenum vel</a>
<button type="button" class="f_size_medium f_right color_dark bg_tr tr_all_hover close_fieldset"><i class="fa fa-times lh_inherit"></i></button>
</div>
<a href="#" class="color_dark"><i class="fa fa-heart-o m_right_10"></i>Go to Wishlist</a>
</div>
</figure>
<!--banner-->
<a href="#" class="d_block r_corners m_bottom_30">
<img src="images/banner_img_6.jpg" alt="">
</a>
<!--Bestsellers-->
<figure class="widget shadow r_corners wrapper m_bottom_30">
<figcaption>
<h3 class="color_light">Bestsellers</h3>
</figcaption>
<div class="widget_content">
<div class="clearfix m_bottom_15">
<img src="images/bestsellers_img_1.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block bt_link">Ut dolor dapibus</a>
<!--rating-->
<ul class="horizontal_list clearfix d_inline_b rating_list type_2 tr_all_hover m_bottom_10">
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li>
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
</ul>
<p class="scheme_color">$61.00</p>
</div>
<hr class="m_bottom_15">
<div class="clearfix m_bottom_15">
<img src="images/bestsellers_img_2.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block bt_link">Elementum vel</a>
<!--rating-->
<ul class="horizontal_list clearfix d_inline_b rating_list type_2 tr_all_hover m_bottom_10">
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li>
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
</ul>
<p class="scheme_color">$57.00</p>
</div>
<hr class="m_bottom_15">
<div class="clearfix m_bottom_5">
<img src="images/bestsellers_img_3.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block bt_link">Crsus eleifend elit</a>
<!--rating-->
<ul class="horizontal_list clearfix d_inline_b rating_list type_2 tr_all_hover m_bottom_10">
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li class="active">
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
<li>
<i class="fa fa-star-o empty tr_all_hover"></i>
<i class="fa fa-star active tr_all_hover"></i>
</li>
</ul>
<p class="scheme_color">$24.00</p>
</div>
</div>
</figure>
<!--tags-->
<figure class="widget shadow r_corners wrapper m_bottom_30">
<figcaption>
<h3 class="color_light">Tags</h3>
</figcaption>
<div class="widget_content">
<div class="tags_list">
<a href="#" class="color_dark d_inline_b v_align_b">accessories,</a>
<a href="#" class="color_dark d_inline_b f_size_ex_large v_align_b">bestseller,</a>
<a href="#" class="color_dark d_inline_b v_align_b">clothes,</a>
<a href="#" class="color_dark d_inline_b f_size_big v_align_b">dresses,</a>
<a href="#" class="color_dark d_inline_b v_align_b">fashion,</a>
<a href="#" class="color_dark d_inline_b f_size_large v_align_b">men,</a>
<a href="#" class="color_dark d_inline_b v_align_b">pants,</a>
<a href="#" class="color_dark d_inline_b v_align_b">sale,</a>
<a href="#" class="color_dark d_inline_b v_align_b">short,</a>
<a href="#" class="color_dark d_inline_b f_size_ex_large v_align_b">skirt,</a>
<a href="#" class="color_dark d_inline_b v_align_b">top,</a>
<a href="#" class="color_dark d_inline_b f_size_big v_align_b">women</a>
</div>
</div>
</figure>
<!--New products-->
<figure class="widget shadow r_corners wrapper m_bottom_30">
<figcaption>
<h3 class="color_light">New Products</h3>
</figcaption>
<div class="widget_content">
<div class="clearfix m_bottom_15">
<img src="images/new_products_img_1.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block m_bottom_5 bt_link">Ut tellus dolor dapibus</a>
<p class="scheme_color">$61.00</p>
</div>
<hr class="m_bottom_15">
<div class="clearfix m_bottom_15">
<img src="images/new_products_img_2.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block m_bottom_5 bt_link">Elementum vel</a>
<p class="scheme_color">$57.00</p>
</div>
<hr class="m_bottom_15">
<div class="clearfix m_bottom_5">
<img src="images/new_products_img_3.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block m_bottom_5 bt_link">Crsus eleifend elit</a>
<p class="scheme_color">$24.00</p>
</div>
</div>
</figure>
<!--Specials-->
<figure class="widget shadow r_corners wrapper m_bottom_30">
<figcaption class="clearfix relative">
<h3 class="color_light f_left f_sm_none m_sm_bottom_10 m_xs_bottom_0">Specials</h3>
<div class="f_right nav_buttons_wrap_type_2 tf_sm_none f_sm_none clearfix">
<button class="button_type_7 bg_cs_hover box_s_none f_size_ex_large color_light t_align_c bg_tr f_left tr_delay_hover r_corners sc_prev"><i class="fa fa-angle-left"></i></button>
<button class="button_type_7 bg_cs_hover box_s_none f_size_ex_large color_light t_align_c bg_tr f_left m_left_5 tr_delay_hover r_corners sc_next"><i class="fa fa-angle-right"></i></button>
</div>
</figcaption>
<div class="widget_content">
<div class="specials_carousel">
<!--carousel item-->
<div class="specials_item">
<a href="#" class="d_block d_xs_inline_b wrapper m_bottom_20">
<img class="tr_all_long_hover" src="images/product_img_6.jpg" alt="">
</a>
<h5 class="m_bottom_10"><a href="#" class="color_dark">Aliquam erat volutpat</a></h5>
<p class="f_size_large m_bottom_15"><s>$79.00</s> <span class="scheme_color">$36.00</span></p>
<button class="button_type_4 mw_sm_0 r_corners color_light bg_scheme_color tr_all_hover m_bottom_5">Add to Cart</button>
</div>
<!--carousel item-->
<div class="specials_item">
<a href="#" class="d_block d_xs_inline_b wrapper m_bottom_20">
<img class="tr_all_long_hover" src="images/product_img_7.jpg" alt="">
</a>
<h5 class="m_bottom_10"><a href="#" class="color_dark">Integer rutrum ante </a></h5>
<p class="f_size_large m_bottom_15"><s>$79.00</s> <span class="scheme_color">$36.00</span></p>
<button class="button_type_4 mw_sm_0 r_corners color_light bg_scheme_color tr_all_hover m_bottom_5">Add to Cart</button>
</div>
<!--carousel item-->
<div class="specials_item">
<a href="#" class="d_block d_xs_inline_b wrapper m_bottom_20">
<img class="tr_all_long_hover" src="images/product_img_5.jpg" alt="">
</a>
<h5 class="m_bottom_10"><a href="#" class="color_dark">Aliquam erat volutpat</a></h5>
<p class="f_size_large m_bottom_15"><s>$79.00</s> <span class="scheme_color">$36.00</span></p>
<button class="button_type_4 mw_sm_0 r_corners color_light bg_scheme_color tr_all_hover m_bottom_5">Add to Cart</button>
</div>
</div>
</div>
</figure>
<!--Popular articles-->
<figure class="widget shadow r_corners wrapper m_bottom_30">
<figcaption>
<h3 class="color_light">Popular Articles</h3>
</figcaption>
<div class="widget_content">
<article class="clearfix m_bottom_15">
<img src="images/article_img_1.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block bt_link p_vr_0">Aliquam erat volutpat.</a>
<p class="f_size_medium">50 comments</p>
</article>
<hr class="m_bottom_15">
<article class="clearfix m_bottom_15">
<img src="images/article_img_2.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block p_vr_0 bt_link">Integer rutrum ante </a>
<p class="f_size_medium">34 comments</p>
</article>
<hr class="m_bottom_15">
<article class="clearfix m_bottom_5">
<img src="images/article_img_3.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block p_vr_0 bt_link">Vestibulum libero nisl, porta vel</a>
<p class="f_size_medium">21 comments</p>
</article>
</div>
</figure>
<!--Latest articles-->
<figure class="widget shadow r_corners wrapper m_bottom_30">
<figcaption>
<h3 class="color_light">Latest Articles</h3>
</figcaption>
<div class="widget_content">
<article class="clearfix m_bottom_15">
<img src="images/article_img_4.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block bt_link p_vr_0">Aliquam erat volutpat.</a>
<p class="f_size_medium">25 January, 2013</p>
</article>
<hr class="m_bottom_15">
<article class="clearfix m_bottom_15">
<img src="images/article_img_5.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block p_vr_0 bt_link">Integer rutrum ante </a>
<p class="f_size_medium">21 January, 2013</p>
</article>
<hr class="m_bottom_15">
<article class="clearfix m_bottom_5">
<img src="images/article_img_6.jpg" alt="" class="f_left m_right_15 m_sm_bottom_10 f_sm_none f_xs_left m_xs_bottom_0">
<a href="#" class="color_dark d_block p_vr_0 bt_link">Vestibulum libero nisl, porta vel</a>
<p class="f_size_medium">18 January, 2013</p>
</article>
</div>
</figure>
</aside>
</div>
</div>
</div>
<!--markup footer-->
<footer id="footer">
<div class="footer_top_part">
<div class="container">
<div class="row clearfix">
<div class="col-lg-3 col-md-3 col-sm-3 m_xs_bottom_30">
<h3 class="color_light_2 m_bottom_20">About</h3>
<p class="m_bottom_25">Ut pharetra augue nec augue. Nam elit agna, endrerit sit amet, tincidunt ac, viverra sed, nulla. Donec porta diam eu massa. Quisque diam lorem, interdum vitae, dapibus ac, scelerisque.</p>
<!--social icons-->
<ul class="clearfix horizontal_list social_icons">
<li class="facebook m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Facebook</span>
<a href="#" class="r_corners t_align_c tr_delay_hover f_size_ex_large">
<i class="fa fa-facebook"></i>
</a>
</li>
<li class="twitter m_left_5 m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Twitter</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-twitter"></i>
</a>
</li>
<li class="google_plus m_left_5 m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Google Plus</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-google-plus"></i>
</a>
</li>
<li class="rss m_left_5 m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Rss</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-rss"></i>
</a>
</li>
<li class="pinterest m_left_5 m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Pinterest</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-pinterest"></i>
</a>
</li>
<li class="instagram m_left_5 m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Instagram</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-instagram"></i>
</a>
</li>
<li class="linkedin m_bottom_5 m_sm_left_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">LinkedIn</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-linkedin"></i>
</a>
</li>
<li class="vimeo m_left_5 m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Vimeo</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-vimeo-square"></i>
</a>
</li>
<li class="youtube m_left_5 m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Youtube</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-youtube-play"></i>
</a>
</li>
<li class="flickr m_left_5 m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Flickr</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-flickr"></i>
</a>
</li>
<li class="envelope m_left_5 m_bottom_5 relative">
<span class="tooltip tr_all_hover r_corners color_dark f_size_small">Contact Us</span>
<a href="#" class="r_corners f_size_ex_large t_align_c tr_delay_hover">
<i class="fa fa-envelope-o"></i>
</a>
</li>
</ul>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 m_xs_bottom_30">
<h3 class="color_light_2 m_bottom_20">The Service</h3>
<ul class="vertical_list">
<li><a class="color_light tr_delay_hover" href="#">My account<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">Order history<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">Wishlist<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">Vendor contact<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">Front page<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">Virtuemart categories<i class="fa fa-angle-right"></i></a></li>
</ul>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 m_xs_bottom_30">
<h3 class="color_light_2 m_bottom_20">Information</h3>
<ul class="vertical_list">
<li><a class="color_light tr_delay_hover" href="#">About us<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">New collection<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">Best sellers<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">Manufacturers<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">Privacy policy<i class="fa fa-angle-right"></i></a></li>
<li><a class="color_light tr_delay_hover" href="#">Terms & condition<i class="fa fa-angle-right"></i></a></li>
</ul>
</div>
<div class="col-lg-3 col-md-3 col-sm-3">
<h3 class="color_light_2 m_bottom_20">Newsletter</h3>
<p class="f_size_medium m_bottom_15">Sign up to our newsletter and get exclusive deals you wont find anywhere else straight to your inbox!</p>
<form id="newsletter">
<input type="email" placeholder="Your email address" class="m_bottom_20 r_corners f_size_medium full_width" name="newsletter-email">
<button type="submit" class="button_type_8 r_corners bg_scheme_color color_light tr_all_hover">Subscribe</button>
</form>
</div>
</div>
</div>
</div>
<!--copyright part-->
<div class="footer_bottom_part">
<div class="container clearfix t_mxs_align_c">
<p class="f_left f_mxs_none m_mxs_bottom_10">© 2014 <span class="color_light">Flatastic</span>. All Rights Reserved.</p>
<ul class="f_right horizontal_list clearfix f_mxs_none d_mxs_inline_b">
<li><img src="images/payment_img_1.png" alt=""></li>
<li class="m_left_5"><img src="images/payment_img_2.png" alt=""></li>
<li class="m_left_5"><img src="images/payment_img_3.png" alt=""></li>
<li class="m_left_5"><img src="images/payment_img_4.png" alt=""></li>
<li class="m_left_5"><img src="images/payment_img_5.png" alt=""></li>
</ul>
</div>
</div>
</footer>
</div>
<!--social widgets-->
<ul class="social_widgets d_xs_none">
<!--facebook-->
<li class="relative">
<button class="sw_button t_align_c facebook"><i class="fa fa-facebook"></i></button>
<div class="sw_content">
<h3 class="color_dark m_bottom_20">Join Us on Facebook</h3>
<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fenvato&width=235&height=258&colorscheme=light&show_faces=true&header=false&stream=false&show_border=false&appId=438889712801266" style="border:none; overflow:hidden; width:235px; height:258px;"></iframe>
</div>
</li>
<!--twitter feed-->
<li class="relative">
<button class="sw_button t_align_c twitter"><i class="fa fa-twitter"></i></button>
<div class="sw_content">
<h3 class="color_dark m_bottom_20">Latest Tweets</h3>
<div class="twitterfeed m_bottom_25"></div>
<a role="button" class="button_type_4 d_inline_b r_corners tr_all_hover color_light tw_color" href="https://twitter.com/fanfbmltemplate">Follow on Twitter</a>
</div>
</li>
<!--contact form-->
<li class="relative">
<button class="sw_button t_align_c contact"><i class="fa fa-envelope-o"></i></button>
<div class="sw_content">
<h3 class="color_dark m_bottom_20">Contact Us</h3>
<p class="f_size_medium m_bottom_15">Lorem ipsum dolor sit amet, consectetuer adipis mauris</p>
<form id="contactform" class="mini">
<input class="f_size_medium m_bottom_10 r_corners full_width" type="text" name="cf_name" placeholder="Your name">
<input class="f_size_medium m_bottom_10 r_corners full_width" type="email" name="cf_email" placeholder="Email">
<textarea class="f_size_medium r_corners full_width m_bottom_20" placeholder="Message" name="cf_message"></textarea>
<button type="submit" class="button_type_4 r_corners mw_0 tr_all_hover color_dark bg_light_color_2">Send</button>
</form>
</div>
</li>
<!--contact info-->
<li class="relative">
<button class="sw_button t_align_c googlemap"><i class="fa fa-map-marker"></i></button>
<div class="sw_content">
<h3 class="color_dark m_bottom_20">Store Location</h3>
<ul class="c_info_list">
<li class="m_bottom_10">
<div class="clearfix m_bottom_15">
<i class="fa fa-map-marker f_left color_dark"></i>
<p class="contact_e">8901 Marmora Road,<br> Glasgow, D04 89GR.</p>
</div>
<iframe class="r_corners full_width" id="gmap_mini" src="https://maps.google.com/maps?f=q&source=s_q&hl=ru&geocode=&q=Manhattan,+New+York,+NY,+United+States&aq=0&oq=monheten&sll=37.0625,-95.677068&sspn=65.430355,129.814453&t=m&ie=UTF8&hq=&hnear=%D0%9C%D0%B0%D0%BD%D1%85%D1%8D%D1%82%D1%82%D0%B5%D0%BD,+%D0%9D%D1%8C%D1%8E-%D0%99%D0%BE%D1%80%D0%BA,+%D0%9D%D1%8C%D1%8E+%D0%99%D0%BE%D1%80%D0%BA,+%D0%9D%D1%8C%D1%8E-%D0%99%D0%BE%D1%80%D0%BA&ll=40.790278,-73.959722&spn=0.015612,0.031693&z=13&output=embed"></iframe>
</li>
<li class="m_bottom_10">
<div class="clearfix m_bottom_10">
<i class="fa fa-phone f_left color_dark"></i>
<p class="contact_e">800-559-65-80</p>
</div>
</li>
<li class="m_bottom_10">
<div class="clearfix m_bottom_10">
<i class="fa fa-envelope f_left color_dark"></i>
<a class="contact_e default_t_color" href="mailto:#">info@companyname.com</a>
</div>
</li>
<li>
<div class="clearfix">
<i class="fa fa-clock-o f_left color_dark"></i>
<p class="contact_e">Monday - Friday: 08.00-20.00 <br>Saturday: 09.00-15.00<br> Sunday: closed</p>
</div>
</li>
</ul>
</div>
</li>
</ul>
<!--login popup-->
<div class="popup_wrap d_none" id="login_popup">
<section class="popup r_corners shadow">
<button class="bg_tr color_dark tr_all_hover text_cs_hover close f_size_large"><i class="fa fa-times"></i></button>
<h3 class="m_bottom_20 color_dark">Log In</h3>
<form>
<ul>
<li class="m_bottom_15">
<label for="username" class="m_bottom_5 d_inline_b">Username</label><br>
<input type="text" name="" id="username" class="r_corners full_width">
</li>
<li class="m_bottom_25">
<label for="password" class="m_bottom_5 d_inline_b">Password</label><br>
<input type="password" name="" id="password" class="r_corners full_width">
</li>
<li class="m_bottom_15">
<input type="checkbox" class="d_none" id="checkbox_10"><label for="checkbox_10">Remember me</label>
</li>
<li class="clearfix m_bottom_30">
<button class="button_type_4 tr_all_hover r_corners f_left bg_scheme_color color_light f_mxs_none m_mxs_bottom_15">Log In</button>
<div class="f_right f_size_medium f_mxs_none">
<a href="#" class="color_dark">Forgot your password?</a><br>
<a href="#" class="color_dark">Forgot your username?</a>
</div>
</li>
</ul>
</form>
<footer class="bg_light_color_1 t_mxs_align_c">
<h3 class="color_dark d_inline_middle d_mxs_block m_mxs_bottom_15">New Customer?</h3>
<a href="#" role="button" class="tr_all_hover r_corners button_type_4 bg_dark_color bg_cs_hover color_light d_inline_middle m_mxs_left_0">Create an Account</a>
</footer>
</section>
</div>
<button class="t_align_c r_corners tr_all_hover type_2 animate_ftl" id="go_to_top"><i class="fa fa-angle-up"></i></button>
<!--scripts include-->
<script src="js/jquery-2.1.0.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/retina.js"></script>
<script src="js/owl.carousel.min.js"></script>
<script src="js/waypoints.min.js"></script>
<script src="js/jquery.tweet.min.js"></script>
<script src="js/scripts.js"></script>
</body>
</html> | Java |
package work.notech.poker.room;
import work.notech.poker.logic.Cards;
import java.util.List;
public class GameRoom {
private Integer roomIds;
private List<Integer> clientIds;
private Cards cards;
public Integer getRoomIds() {
return roomIds;
}
public void setRoomIds(Integer roomIds) {
this.roomIds = roomIds;
}
public List<Integer> getClientIds() {
return clientIds;
}
public void setClientIds(List<Integer> clientIds) {
this.clientIds = clientIds;
}
public Cards getCards() {
return cards;
}
public void setCards(Cards cards) {
this.cards = cards;
}
}
| Java |
---
title: 22 Points to Go
author: rami
layout: lifestream
categories: [Lifestream]
tags: [jeddah, saudi-arabia, juve, path]
image: 22-points-to-go.jpg
---
10 games & 22 points to go. With games against the 20th place ,19,15,14,13,11. #Juve CC:@juventiknows.
{% include image.html url="/assets/images/content/lifestream/22-points-to-go.jpg" description="22 Points to Go" %}
| Java |
// Take well-formed json from a sensu check result a context rich html document to be mail to
// one or more addresses.
//
// LICENSE:
// Copyright 2016 Yieldbot. <devops@yieldbot.com>
// Released under the MIT License; see LICENSE
// for details.
package main
import (
"bytes"
"fmt"
"github.com/codegangsta/cli"
// "github.com/yieldbot/sensumailer/lib"
"github.com/yieldbot/sensuplugin/sensuhandler"
"github.com/yieldbot/sensuplugin/sensuutil"
// "log"
"net/smtp"
"os"
// "time"
)
func main() {
var emailAddress string
var smtpHost string
var smtpPort string
var emailSender string
var debug bool
app := cli.NewApp()
app.Name = "handler-mailer"
app.Usage = "Send context rich html alert notifications via email"
app.Action = func(c *cli.Context) {
if debug {
fmt.Printf("This is the sending address: %v \n", emailSender)
fmt.Printf("This is the recieving address: %v\n", emailAddress)
fmt.Printf("This is the smtp address: %v:%v\n", smtpHost, smtpPort)
sensuutil.Exit("debug")
}
// Get the sensu event data
sensuEvent := new(sensuhandler.SensuEvent)
sensuEvent = sensuEvent.AcquireSensuEvent()
// Connect to the remote SMTP server.
s, err := smtp.Dial(smtpHost + ":" + smtpPort)
if err != nil {
sensuutil.EHndlr(err)
}
defer s.Close()
// Set the sender and recipient.
s.Mail(emailSender)
s.Rcpt(emailAddress)
// Send the email body.
ws, err := s.Data()
if err != nil {
sensuutil.EHndlr(err)
}
defer ws.Close()
buf := bytes.NewBufferString("This is the email body.")
if _, err = buf.WriteTo(ws); err != nil {
sensuutil.EHndlr(err)
}
fmt.Printf("Email sent to %s\n", emailAddress)
}
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "address",
Value: "mattjones@yieldbot.com",
Usage: "email address to send to",
EnvVar: "SENSU_HANDLER_EMAIL_ADDRESS",
Destination: &emailAddress,
},
cli.StringFlag{
Name: "host",
Value: "localhost",
Usage: "smtp server",
EnvVar: "SENSU_HANDLER_EMAIL_HOST",
Destination: &smtpHost,
},
cli.StringFlag{
Name: "port",
Value: "25",
Usage: "smtp port",
EnvVar: "SENSU_HANDLER_EMAIL_PORT",
Destination: &smtpPort,
},
cli.StringFlag{
Name: "sender",
Value: "sensu@yieldbot.com",
Usage: "email sender",
EnvVar: "SENSU_HANDLER_EMAIL_SENDER",
Destination: &emailSender,
},
cli.BoolFlag{
Name: "debug",
Usage: "Print debugging info, no alerts will be sent",
Destination: &debug,
},
}
app.Run(os.Args)
}
| Java |
module.exports = [
'babel-polyfill',
'react',
'react-redux',
'react-router',
'react-dom',
'redux',
'redux-thunk',
'seamless-immutable',
'react-router-redux',
'history',
'lodash',
'styled-components',
'prop-types',
];
| Java |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* RequestDataCollector.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RequestDataCollector extends DataCollector implements EventSubscriberInterface
{
protected $controllers;
public function __construct()
{
$this->controllers = new \SplObjectStorage();
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$responseHeaders = $response->headers->all();
$cookies = array();
foreach ($response->headers->getCookies() as $cookie) {
$cookies[] = $this->getCookieHeader($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
}
if (count($cookies) > 0) {
$responseHeaders['Set-Cookie'] = $cookies;
}
$attributes = array();
foreach ($request->attributes->all() as $key => $value) {
$attributes[$key] = $this->varToString($value);
}
$content = null;
try {
$content = $request->getContent();
} catch (\LogicException $e) {
// the user already got the request content as a resource
$content = false;
}
$sessionMetadata = array();
$sessionAttributes = array();
$flashes = array();
if ($request->hasSession()) {
$session = $request->getSession();
if ($session->isStarted()) {
$sessionMetadata['Created'] = date(DATE_RFC822, $session->getMetadataBag()->getCreated());
$sessionMetadata['Last used'] = date(DATE_RFC822, $session->getMetadataBag()->getLastUsed());
$sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime();
$sessionAttributes = $session->all();
$flashes = $session->getFlashBag()->peekAll();
}
}
$this->data = array(
'format' => $request->getRequestFormat(),
'content' => $content,
'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html',
'status_code' => $response->getStatusCode(),
'request_query' => $request->query->all(),
'request_request' => $request->request->all(),
'request_headers' => $request->headers->all(),
'request_server' => $request->server->all(),
'request_cookies' => $request->cookies->all(),
'request_attributes' => $attributes,
'response_headers' => $responseHeaders,
'session_metadata' => $sessionMetadata,
'session_attributes' => $sessionAttributes,
'flashes' => $flashes,
'path_info' => $request->getPathInfo(),
'controller' => 'n/a',
'locale' => $request->getLocale(),
);
if (isset($this->controllers[$request])) {
$controller = $this->controllers[$request];
if (is_array($controller)) {
$r = new \ReflectionMethod($controller[0], $controller[1]);
$this->data['controller'] = array(
'class' => get_class($controller[0]),
'method' => $controller[1],
'file' => $r->getFilename(),
'line' => $r->getStartLine(),
);
} elseif ($controller instanceof \Closure) {
$this->data['controller'] = 'Closure';
} else {
$this->data['controller'] = (string) $controller ?: 'n/a';
}
unset($this->controllers[$request]);
}
}
public function getPathInfo()
{
return $this->data['path_info'];
}
public function getRequestRequest()
{
return new ParameterBag($this->data['request_request']);
}
public function getRequestQuery()
{
return new ParameterBag($this->data['request_query']);
}
public function getRequestHeaders()
{
return new HeaderBag($this->data['request_headers']);
}
public function getRequestServer()
{
return new ParameterBag($this->data['request_server']);
}
public function getRequestCookies()
{
return new ParameterBag($this->data['request_cookies']);
}
public function getRequestAttributes()
{
return new ParameterBag($this->data['request_attributes']);
}
public function getResponseHeaders()
{
return new ResponseHeaderBag($this->data['response_headers']);
}
public function getSessionMetadata()
{
return $this->data['session_metadata'];
}
public function getSessionAttributes()
{
return $this->data['session_attributes'];
}
public function getFlashes()
{
return $this->data['flashes'];
}
public function getContent()
{
return $this->data['content'];
}
public function getContentType()
{
return $this->data['content_type'];
}
public function getStatusCode()
{
return $this->data['status_code'];
}
public function getFormat()
{
return $this->data['format'];
}
public function getLocale()
{
return $this->data['locale'];
}
/**
* Gets the route name.
*
* The _route request attributes is automatically set by the Router Matcher.
*
* @return string The route
*/
public function getRoute()
{
return isset($this->data['request_attributes']['_route']) ? $this->data['request_attributes']['_route'] : '';
}
/**
* Gets the route parameters.
*
* The _route_params request attributes is automatically set by the RouterListener.
*
* @return array The parameters
*/
public function getRouteParams()
{
return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params'] : array();
}
/**
* Gets the controller.
*
* @return string The controller as a string
*/
public function getController()
{
return $this->data['controller'];
}
public function onKernelController(FilterControllerEvent $event)
{
$this->controllers[$event->getRequest()] = $event->getController();
}
public static function getSubscribedEvents()
{
return array(KernelEvents::CONTROLLER => 'onKernelController');
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'request';
}
private function getCookieHeader($name, $value, $expires, $path, $domain, $secure, $httponly)
{
$cookie = sprintf('%s=%s', $name, urlencode($value));
if (0 !== $expires) {
if (is_numeric($expires)) {
$expires = (int) $expires;
} elseif ($expires instanceof \DateTime) {
$expires = $expires->getTimestamp();
} else {
$expires = strtotime($expires);
if (false === $expires || -1 == $expires) {
throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid.', $expires));
}
}
$cookie .= '; expires='.substr(\DateTime::createFromFormat('U', $expires, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5);
}
if ($domain) {
$cookie .= '; domain='.$domain;
}
$cookie .= '; path='.$path;
if ($secure) {
$cookie .= '; secure';
}
if ($httponly) {
$cookie .= '; httponly';
}
return $cookie;
}
}
| Java |
package com.sunilson.pro4.activities;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.sunilson.pro4.R;
import com.sunilson.pro4.baseClasses.Liveticker;
import com.sunilson.pro4.exceptions.LivetickerSetException;
import com.sunilson.pro4.utilities.Constants;
import com.sunilson.pro4.views.SubmitButtonBig;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class AddLivetickerActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private ValueEventListener resultListener;
private DatabaseReference mReference, currentResultReference;
private boolean finished, startNow;
private String privacy = "public";
private String livetickerID;
private Calendar calendar;
private ArrayList<DatabaseReference> references = new ArrayList<>();
private CompoundButton.OnCheckedChangeListener switchListener;
@BindView(R.id.add_liveticker_date)
TextView dateTextView;
@BindView(R.id.add_liveticker_time)
TextView timeTextView;
@BindView(R.id.add_liveticker_title_edittext)
EditText titleEditText;
@BindView(R.id.add_liveticker_description_edittext)
EditText descriptionEditText;
@BindView(R.id.add_liveticker_status_edittext)
EditText statusEditText;
@BindView(R.id.add_liveticker_start_switch)
Switch dateSwitch;
@BindView(R.id.add_liveticker_privacy_switch)
Switch privacySwitch;
@BindView(R.id.add_liveticker_date_layout)
LinearLayout dateLayout;
@BindView(R.id.add_liveticker_privacy_title)
TextView privacyTitle;
@BindView(R.id.submit_button_view)
SubmitButtonBig submitButtonBig;
@OnClick(R.id.submit_button)
public void submit(View view) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null || user.isAnonymous()) {
Toast.makeText(this, R.string.add_liveticker_user_failure, Toast.LENGTH_SHORT).show();
return;
}
final Liveticker liveticker = new Liveticker();
try {
liveticker.setTitle(titleEditText.getText().toString());
liveticker.setDescription(descriptionEditText.getText().toString());
liveticker.setAuthorID(user.getUid());
liveticker.setStateTimestamp(calendar.getTimeInMillis());
liveticker.setPrivacy(privacy);
liveticker.setStatus(statusEditText.getText().toString());
} catch (LivetickerSetException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
loading(true);
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("/request/" + user.getUid() + "/addLiveticker/").push();
ref.setValue(liveticker).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
//Remove Event Listener from Queue, if it has been started
if (currentResultReference != null && resultListener != null) {
currentResultReference.removeEventListener(resultListener);
}
//Listen for results from Queue
DatabaseReference taskRef = FirebaseDatabase.getInstance().getReference("/result/" + user.getUid() + "/addLiveticker/" + ref.getKey());
//Add Listener to Reference and store Reference so we can later detach Listener
taskRef.addValueEventListener(resultListener);
currentResultReference = taskRef;
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_liveticker);
ButterKnife.bind(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mReference = FirebaseDatabase.getInstance().getReference();
initializeQueueListener();
calendar = Calendar.getInstance();
updateDateTime();
dateTextView.setOnClickListener(this);
timeTextView.setOnClickListener(this);
dateSwitch.setOnCheckedChangeListener(this);
privacySwitch.setOnCheckedChangeListener(this);
submitButtonBig.setText(getString(R.string.channel_edit_save), getString(R.string.loading));
}
@Override
protected void onStop() {
super.onStop();
//Remove Event Listener from Queue, if it has been started
if (currentResultReference != null && resultListener != null) {
currentResultReference.removeEventListener(resultListener);
}
}
@Override
protected void authChanged(FirebaseUser user) {
if (user.isAnonymous()) {
Intent i = new Intent(AddLivetickerActivity.this, MainActivity.class);
startActivity(i);
Toast.makeText(this, R.string.no_access_permission, Toast.LENGTH_SHORT).show();
}
}
/**
* Initialize Listener for "Add Liveticker Queue"
*/
private void initializeQueueListener() {
resultListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!finished) {
//Check what state the Queue event has
if (dataSnapshot.child("state").getValue() != null) {
//Liveticker was added successfully
if (dataSnapshot.child("state").getValue().toString().equals("success")) {
finished = true;
Intent i = new Intent();
i.putExtra("livetickerID", dataSnapshot.child("successDetails").getValue().toString());
setResult(Constants.ADD_LIVETICKER_RESULT_CODE, i);
finish();
} else if (dataSnapshot.child("state").getValue().toString().equals("error")) {
loading(false);
Toast.makeText(AddLivetickerActivity.this, dataSnapshot.child("errorDetails").getValue().toString(), Toast.LENGTH_LONG).show();
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
}
/**
* Change visual loading state
*
* @param loading
*/
private void loading(boolean loading) {
if (loading) {
submitButtonBig.loading(true);
} else {
submitButtonBig.loading(false);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.add_liveticker_date:
showDateDialog();
break;
case R.id.add_liveticker_time:
showTimeDialog();
break;
}
}
/**
* A dialog to pick a date and set the calendar to that date
*/
private void showDateDialog() {
DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateTime();
}
};
DatePickerDialog datePickerDialog = new DatePickerDialog(this, onDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() + 432000000);
datePickerDialog.show();
}
/**
* A dialog to pick a time and set the calendar to that time
*/
private void showTimeDialog() {
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
updateDateTime();
}
};
TimePickerDialog timePickerDialog = new TimePickerDialog(this, onTimeSetListener, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
timePickerDialog.show();
}
/**
* Update the Textviews with the current date from the calendar
*/
private void updateDateTime() {
Date date = calendar.getTime();
SimpleDateFormat formatDate = new SimpleDateFormat("dd.MM.yyyy", Locale.getDefault());
SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
dateTextView.setText(formatDate.format(date));
timeTextView.setText(formatTime.format(date));
}
/**
* When a switch gets toggled
*
* @param compoundButton Switch that was toggled
* @param b Value of switch
*/
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
switch (compoundButton.getId()) {
case R.id.add_liveticker_start_switch:
startNow = !startNow;
if (b) {
dateLayout.setVisibility(View.GONE);
} else {
dateLayout.setVisibility(View.VISIBLE);
}
break;
case R.id.add_liveticker_privacy_switch:
if (b) {
privacy = "public";
privacyTitle.setText(getString(R.string.add_liveticker_public_title));
} else {
privacy = "private";
privacyTitle.setText(getString(R.string.add_liveticker_public_title_private));
}
break;
}
}
}
| Java |
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>
{% block title %}Default Title{% endblock %}
</title>
{% block stylesheets %}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="{% static 'css/style.css' %}" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,600,300' rel='stylesheet' type='text/css'>
{% endblock %}
{% block javascript %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="{% static 'js/script.js' %}"></script>
{% endblock %}
{% block meta_tags %}
<meta name="viewport" content="width=device-width, initial-scale=1">
{% endblock %}
{% block extra_head %}{% endblock %}
</head>
<body>
<div id="wrap">
<main role="main">
<header>
{% include "maininclude/header.html" %}
</header>
<div class="container-fluid">
{% block main %}{% endblock %}
</div>
</main>
</div>
{% include "maininclude/footer.html" %}
</body>
</html> | Java |
import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
import { deleteUser, updateUserByUsername } from '../../lib/db'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
// You do not generally want to return the whole user object
// because it may contain sensitive field such as !!password!! Only return what needed
// const { name, username, favoriteColor } = req.user
// res.json({ user: { name, username, favoriteColor } })
res.json({ user: req.user })
})
.use((req, res, next) => {
// handlers after this (PUT, DELETE) all require an authenticated user
// This middleware to check if user is authenticated before continuing
if (!req.user) {
res.status(401).send('unauthenticated')
} else {
next()
}
})
.put((req, res) => {
const { name } = req.body
const user = updateUserByUsername(req, req.user.username, { name })
res.json({ user })
})
.delete((req, res) => {
deleteUser(req)
req.logOut()
res.status(204).end()
})
export default handler
| Java |
<?php
namespace Plumber\Tests\Deployer;
use Plumber\Server\Server;
class NoRsyncDeployerTest extends \PHPUnit_Framework_TestCase
{
public function testRsyncDeployWithNotExistingRsyncExcludeFile()
{
$server = new Server( 'localhost', 'julien', '/var/www/', 22 );
$deployer = new \Plumber\Deployer\NoRsyncDeployer();
$this->assertTrue( $deployer->deploy( $server, array() ), 'This deployer always returns true.' );
}
public function testGetDeployerName()
{
$deployer = new \Plumber\Deployer\NoRsyncDeployer();
$this->assertEquals( 'no rsync', $deployer->getName(), 'The name must be no rsync' );
}
} | Java |
!function(a){var b,c,d;return a.localStorage||(c={setItem:function(a,b,c){var d,e;return null==c&&(c=!1),d=c?-1:30,e=new Date,e.setDate(e.getDate()+d),document.cookie=""+a+"="+escape(b)+"; expires="+e.toUTCString()},getItem:function(a){return document.cookie.indexOf(-1!==""+a+"=")?unescape(document.cookie.split(""+a+"=")[1].split(";")[0].replace("=","")):!1},removeItem:function(a){return this.setItem(a,"",!0)}}),d=localStorage||c,b=function(){function a(b){return this.key=b,this instanceof a?this:new a(this.key)}return a.prototype.key=null,a.prototype.get=function(){var a,b;a=d.getItem(this.key);try{return JSON.parse(a)}catch(c){return b=c,a}},a.prototype.set=function(a){var b;try{JSON.parse(a)}catch(c){b=c,a=JSON.stringify(a)}return d.setItem(this.key,a),this},a.prototype.remove=function(){return d.removeItem(this.key),this},a}(),a.Wafer=b}(window); | Java |
import { injectReducer } from 'STORE/reducers'
export default store => ({
path : 'checkHistoryList.html',
getComponent(nextState, cb) {
require.ensure([], (require) => {
const CheckHistoryList = require('VIEW/CheckHistoryList').default
const reducer = require('REDUCER/checkHistoryList').default
injectReducer(store, { key: 'checkHistoryList', reducer })
cb(null, CheckHistoryList)
}, 'checkHistoryList')
}
})
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.