text
stringlengths 2
100k
| meta
dict |
---|---|
/*
Erica Sadun, http://ericasadun.com
iPhone Developer's Cookbook, 3.0 Edition
BSD License, Use at your own risk
*/
#import <UIKit/UIKit.h>
#import "SettingsViewController.h"
#import "TwitterOperation.h"
#import "KeychainItemWrapper.h"
#define COOKBOOK_PURPLE_COLOR [UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f]
#define BARBUTTON(TITLE, SELECTOR) [[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR] autorelease]
#define showAlert(format, ...) myShowAlert(__LINE__, (char *)__FUNCTION__, format, ##__VA_ARGS__)
// Simple Alert Utility
void myShowAlert(int line, char *functname, id formatstring,...)
{
va_list arglist;
if (!formatstring) return;
va_start(arglist, formatstring);
id outstring = [[[NSString alloc] initWithFormat:formatstring arguments:arglist] autorelease];
va_end(arglist);
UIAlertView *av = [[[UIAlertView alloc] initWithTitle:outstring message:nil delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil] autorelease];
[av show];
}
@interface TestBedViewController : UIViewController <UITextFieldDelegate, TwitterOperationDelegate>
{
IBOutlet UITextField *textField;
IBOutlet UIActivityIndicatorView *activity;
KeychainItemWrapper *wrapper;
}
@property (retain) KeychainItemWrapper *wrapper;
@end
@implementation TestBedViewController
@synthesize wrapper;
- (void) hideButtons
{
self.navigationItem.rightBarButtonItem = nil;
self.navigationItem.leftBarButtonItem = nil;
}
- (void) showButtons
{
self.navigationItem.rightBarButtonItem = BARBUTTON(@"Tweet", @selector(tweet:));
self.navigationItem.leftBarButtonItem = BARBUTTON(@"Settings", @selector(settings:));
}
- (void) doneTweeting : (NSString *) outstring
{
[activity stopAnimating];
if (outstring.length < 60) // probable error
showAlert(outstring);
else if ([outstring rangeOfString:@"uthentica"].location != NSNotFound)
showAlert(@"Failed to authenticate. Please check your user name and password.");
else
{
// probable success
showAlert(@"Success! Your message was tweeted.");
textField.text = @"";
}
[textField setEnabled:YES];
[self showButtons];
}
- (void) tweet: (UIBarButtonItem *) bbi
{
NSString *text = textField.text;
if (!text || (text.length == 0))
{
showAlert(@"Please enter text before you tweet.");
return;
}
[textField resignFirstResponder];
[textField setEnabled:NO];
[self hideButtons];
[activity startAnimating];
TwitterOperation *operation = [[[TwitterOperation alloc] init] autorelease];
operation.delegate = self;
operation.theText = text;
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
}
- (void) settings: (UIBarButtonItem *) bbi
{
SettingsViewController *svc = [[[SettingsViewController alloc] init] autorelease];
svc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
UINavigationController *nav = [[[UINavigationController alloc] initWithRootViewController:svc] autorelease];
[self.navigationController presentModalViewController:nav animated:YES];
}
- (void) viewDidAppear: (BOOL) animated
{
NSString *uname = [wrapper objectForKey:(id)kSecAttrAccount];
NSString *pword = [wrapper objectForKey:(id)kSecValueData];
if (uname && pword)
self.navigationItem.rightBarButtonItem = BARBUTTON(@"Tweet", @selector(tweet:));
}
- (void) viewDidLoad
{
self.title = @"iTweet";
self.wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"SharedTwitter" accessGroup:@"Y93A4XLA79.com.sadun.GenericKeychainSuite"];
[self.wrapper release];
self.navigationController.navigationBar.tintColor = COOKBOOK_PURPLE_COLOR;
self.navigationItem.leftBarButtonItem = BARBUTTON(@"Settings", @selector(settings:));
}
@end
@interface TestBedAppDelegate : NSObject <UIApplicationDelegate>
@end
@implementation TestBedAppDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application {
UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[TestBedViewController alloc] init]];
[window addSubview:nav.view];
[window makeKeyAndVisible];
}
@end
int main(int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
[pool release];
return retVal;
}
| {
"pile_set_name": "Github"
} |
["0.1.0"]
git-tree-sha1 = "2b93d8d8d3855a6d5d6a80c67e7602889edf8ed4"
| {
"pile_set_name": "Github"
} |
NO3NO2_NASA94
! Nitrate Photolysis to NO2 (NO3NO2)
! NO3 + hv -> NO2 + O(3P)
! Taken from the original RADM data, with NASA (1994) updates
! format: wl, abs_cs, qy
Centered
! With FAC, units are (cm^2/molecule)
FAC=1.0
400.000 0.0000000E+00 1.0000000E+00
405.000 2.7999999E-20 1.0000000E+00
410.000 4.4500000E-20 1.0000000E+00
415.000 5.3500000E-20 1.0000000E+00
420.000 8.1999997E-20 1.0000000E+00
425.000 1.0450000E-19 1.0000000E+00
430.000 1.2930000E-19 1.0000000E+00
435.000 1.8380000E-19 1.0000000E+00
440.000 1.9370001E-19 1.0000000E+00
445.000 2.2300001E-19 1.0000000E+00
450.000 2.8350000E-19 1.0000000E+00
455.000 3.3450000E-19 1.0000000E+00
460.000 3.7200000E-19 1.0000000E+00
465.000 4.3379998E-19 1.0000000E+00
470.000 5.0979999E-19 1.0000000E+00
475.000 6.0320001E-19 1.0000000E+00
480.000 6.4400002E-19 1.0000000E+00
485.000 6.8649999E-19 1.0000000E+00
490.000 8.8000002E-19 1.0000000E+00
495.000 9.6699999E-19 1.0000000E+00
500.000 9.8999995E-19 1.0000000E+00
505.000 1.0950000E-18 1.0000000E+00
510.000 1.3200000E-18 1.0000000E+00
515.000 1.4040000E-18 1.0000000E+00
520.000 1.4470000E-18 1.0000000E+00
525.000 1.4920000E-18 1.0000000E+00
530.000 1.9310000E-18 1.0000000E+00
535.000 2.0390000E-18 1.0000000E+00
540.000 1.8319999E-18 1.0000000E+00
545.000 1.8189999E-18 1.0000000E+00
550.000 2.3530000E-18 1.0000000E+00
555.000 2.6830000E-18 1.0000000E+00
560.000 3.0650001E-18 1.0000000E+00
565.000 2.5370000E-18 1.0000000E+00
570.000 2.4940000E-18 1.0000000E+00
575.000 2.6080000E-18 1.0000000E+00
580.000 2.9080000E-18 1.0000000E+00
585.000 2.6570001E-18 9.6818185E-01
590.000 4.7400001E-18 8.0909091E-01
595.000 3.7399999E-18 6.4999998E-01
600.000 1.6460000E-18 5.7777774E-01
605.000 3.4520001E-18 5.0555557E-01
610.000 1.7760000E-18 4.3333328E-01
615.000 2.1440000E-18 3.6111110E-01
620.000 4.2400000E-18 2.8888887E-01
625.000 9.5200002E-18 2.1666664E-01
630.000 5.6519998E-18 1.4444444E-01
635.000 1.6280000E-18 7.2222218E-02
640.000 1.3320000E-18 0.0000000E+00
644.800 8.3350001E-19 0.0000000E+00
651.100 6.0519997E-19 0.0000000E+00
660.000 8.1220004E-18 0.0000000E+00
670.000 1.4540000E-18 0.0000000E+00
680.000 3.3649999E-19 0.0000000E+00
690.000 1.7499999E-20 0.0000000E+00
700.000 0.0000000E+00 0.0000000E+00
| {
"pile_set_name": "Github"
} |
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.7
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: da5687cfb0df88348ae3ce5c912731ec
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/*
* cloudbeaver - Cloud Database Manager
* Copyright (C) 2020 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0.
* you may not use this file except in compliance with the License.
*/
import { observer } from 'mobx-react';
import styled, { css } from 'reshadow';
import { useStyles } from '@cloudbeaver/core-theming';
import { additionalProps, getValue, matchType } from '../helpers';
import { ObjectPropertyProps } from './ObjectPropertyProps';
const styles = css`
form-input {
display: flex;
width: 100%;
}
label-wrapper {
width: 25%;
box-sizing: border-box;
padding-right: 8px;
}
input-wrapper {
width: 75%;
box-sizing: border-box;
padding-left: 8px;
}
input {
font-size: 13px;
line-height: 24px;
}
label {
text-align: right;
font-size: 13px;
line-height: 26px;
}
`;
export const ObjectPropertyInput = observer(function ObjectPropertyInput({ objectProperty }: ObjectPropertyProps) {
const style = useStyles(styles);
if (!objectProperty) {
return null;
}
return styled(style)(
<form-input as="div">
<label-wrapper as="div">
<label htmlFor={objectProperty.id}
title={objectProperty.displayName}>{objectProperty.displayName}</label>
</label-wrapper>
<input-wrapper as="div">
<input
type={matchType(objectProperty.dataType)}
value={getValue(objectProperty.value)}
{...additionalProps(objectProperty)}
readOnly={true}
/>
</input-wrapper>
</form-input>
);
});
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="fileExtensions" value="java, properties, xml" />
<property name="tabWidth" value="4" />
<!-- Headers -->
<module name="Header">
<property name="headerFile" value="${workspace_loc}/configuration/checkstyle-header.txt" />
<property name="fileExtensions" value="java" />
<property name="ignoreLines" value="2" />
</module>
<!-- Javadoc Comments -->
<module name="JavadocPackage" />
<!-- Suppressions -->
<module name="SuppressionFilter">
<property name="file" value="${workspace_loc}/configuration/checkstyle-suppressions.xml" />
<property name="optional" value="false" />
</module>
<!-- Miscellaneous -->
<module name="LineLength">
<property name="max" value="140" />
</module>
<module name="NewlineAtEndOfFile" />
<module name="UniqueProperties">
<property name="fileExtensions" value="properties" />
</module>
<module name="TreeWalker">
<!-- Annotations -->
<module name="AnnotationLocation">
<property name="allowSamelineSingleParameterlessAnnotation" value="false" />
</module>
<module name="AnnotationUseStyle" />
<module name="MissingDeprecated" />
<module name="MissingOverride" />
<module name="PackageAnnotation" />
<!-- Blocks -->
<module name="AvoidNestedBlocks" />
<module name="EmptyBlock">
<property name="option" value="text" />
</module>
<module name="EmptyCatchBlock" />
<module name="LeftCurly">
<property name="ignoreEnums" value="false" />
</module>
<module name="NeedBraces" />
<module name="RightCurly" />
<!-- Class Design -->
<module name="FinalClass" />
<module name="HideUtilityClassConstructor" />
<module name="InnerTypeLast" />
<module name="InterfaceIsType" />
<module name="MutableException" />
<module name="OneTopLevelClass" />
<module name="VisibilityModifier" />
<!-- Coding -->
<module name="CovariantEquals" />
<module name="DeclarationOrder" />
<module name="DefaultComesLast" />
<module name="EmptyStatement" />
<module name="EqualsHashCode" />
<module name="ExplicitInitialization" />
<module name="FallThrough" />
<module name="IllegalInstantiation" />
<module name="IllegalThrows" />
<module name="IllegalToken" />
<module name="IllegalTokenText" />
<module name="IllegalType" />
<module name="InnerAssignment" />
<module name="MagicNumber" />
<module name="MissingCtor" />
<module name="MissingSwitchDefault" />
<module name="MultipleVariableDeclarations" />
<module name="NoArrayTrailingComma" />
<module name="NoClone" />
<module name="NoFinalizer" />
<module name="OneStatementPerLine" />
<module name="PackageAnnotation" />
<module name="ParameterAssignment" />
<module name="SimplifyBooleanExpression" />
<module name="SimplifyBooleanReturn" />
<module name="StringLiteralEquality" />
<module name="SuperClone" />
<module name="SuperFinalize" />
<module name="UnnecessarySemicolonAfterTypeMemberDeclaration" />
<module name="UnnecessaryParentheses" />
<!-- Imports -->
<module name="AvoidStarImport" />
<module name="AvoidStaticImport" />
<module name="ImportOrder">
<property name="groups" value="java,javax,javassist,android,dalvik,org,com"/>
<property name="ordered" value="true" />
<property name="separated" value="true" />
<property name="option" value="bottom"/>
<property name="sortStaticImportsAlphabetically" value="true" />
</module>
<module name="RedundantImport" />
<module name="UnusedImports" />
<!-- Javadoc Comments -->
<module name="AtclauseOrder" />
<module name="JavadocBlockTagLocation" />
<module name="JavadocContentLocationCheck" />
<module name="JavadocMethod">
<property name="validateThrows" value="true" />
</module>
<module name="JavadocParagraph" />
<module name="JavadocStyle" />
<module name="JavadocTagContinuationIndentation" />
<module name="JavadocType" />
<module name="JavadocVariable">
<property name="scope" value="public" />
</module>
<module name="NonEmptyAtclauseDescription" />
<!-- Modifiers -->
<module name="ModifierOrder" />
<module name="RedundantModifier" />
<!-- Naming Conventions -->
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false" />
<property name="allowedAbbreviationLength" value="1" />
</module>
<module name="AbstractClassName" />
<module name="CatchParameterName">
<property name="format" value="^(ex|[a-z][a-z][a-zA-Z]+)$" />
</module>
<module name="ClassTypeParameterName" />
<module name="ConstantName">
<property name="format" value="^([a-z][a-zA-Z0-9]+|[A-Z][A-Z0-9]*(_[A-Z0-9]+)*)$"/>
</module>
<module name="InterfaceTypeParameterName" />
<module name="LocalFinalVariableName" />
<module name="LocalVariableName">
<property name="allowOneCharVarInForLoop" value="true" />
</module>
<module name="MemberName" />
<module name="MethodName" />
<module name="MethodTypeParameterName" />
<module name="PackageName" />
<module name="ParameterName" />
<module name="StaticVariableName" />
<module name="TypeName" />
<!-- Size Violations -->
<module name=" AnonInnerLength " />
<module name="MethodLength">
<property name="max" value="200" />
</module>
<module name="OuterTypeNumber" />
<!-- Suppressions -->
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="@formatter\:off" />
<property name="onCommentFormat" value="@formatter\:on" />
<property name="checkFormat" value="SingleSpaceSeparator" />
</module>
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="@checkstyle off\: ([\w\|]+)"/>
<property name="onCommentFormat" value="@checkstyle on\: ([\w\|]+)"/>
<property name="checkFormat" value="$1"/>
</module>
<!-- Whitespace -->
<module name="EmptyForInitializerPad" />
<module name="EmptyForIteratorPad" />
<module name="GenericWhitespace" />
<module name="MethodParamPad" />
<module name="NoLineWrap" />
<module name="NoWhitespaceAfter">
<property name="tokens" value="INC, DEC, UNARY_MINUS, UNARY_PLUS, BNOT, LNOT, DOT, ARRAY_DECLARATOR, INDEX_OP"/>
</module>
<module name="NoWhitespaceBefore" />
<module name="OperatorWrap" />
<module name="ParenPad" />
<module name="RegexpSinglelineJava">
<property name="format" value="^\t* +([^\*]| \*)" />
<property name="message" value="Indent must use tab characters" />
</module>
<module name="SeparatorWrap">
<property name="tokens" value="COMMA, SEMI, ELLIPSIS, LPAREN, ARRAY_DECLARATOR, RBRACK"/>
</module>
<module name="SingleSpaceSeparator" />
<module name="TypecastParenPad" />
<module name="WhitespaceAfter" />
<module name="WhitespaceAround" />
<!-- Miscellaneous -->
<module name="ArrayTypeStyle" />
<module name="AvoidEscapedUnicodeCharacters" />
<module name="CommentsIndentation" />
<module name="EmptyLineSeparator">
<property name="allowMultipleEmptyLines" value="false" />
<property name="allowMultipleEmptyLinesInsideClassMembers" value="false" />
<property name="tokens" value="PACKAGE_DEF, IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF, STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="FinalParameters" />
<module name="Indentation" />
<module name="OuterTypeFilename" />
<module name="TodoComment">
<property name="format" value="(TODO)|(FIXME)" />
</module>
</module>
</module> | {
"pile_set_name": "Github"
} |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2017 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://oss.oracle.com/licenses/CDDL+GPL-1.1
* or LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.s1asdev.ejb.allowedmethods.remove.client;
import java.io.*;
import java.util.*;
import javax.ejb.EJBHome;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import org.omg.CORBA.ORB;
import com.sun.s1asdev.ejb.allowedmethods.remove.DriverHome;
import com.sun.s1asdev.ejb.allowedmethods.remove.Driver;
import com.sun.ejte.ccl.reporter.SimpleReporterAdapter;
public class Client {
private static SimpleReporterAdapter stat =
new SimpleReporterAdapter("appserv-tests");
public static void main (String[] args) {
stat.addDescription("ejb-allowedmethods-remove");
Client client = new Client(args);
client.doTest();
stat.printSummary("ejb-allowedmethods-remove");
}
public Client (String[] args) {
}
public void doTest() {
try {
Context ic = new InitialContext();
Object objref = ic.lookup("java:comp/env/ejb/Driver");
DriverHome home = (DriverHome)PortableRemoteObject.narrow
(objref, DriverHome.class);
Driver driver = home.create();
boolean ok = driver.test();
System.out.println("Test returned: " + ok);
stat.addStatus("ejbclient remote test", ((ok)? stat.PASS : stat.FAIL));
} catch(Exception e) {
System.out.println("Got exception: " + e.getMessage());
stat.addStatus("ejbclient remote test(-)" , stat.FAIL);
}
}
}
| {
"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.dromara.soul.web.forwarde;
import org.dromara.soul.plugin.api.RemoteAddressResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Parses the client address from the X-Forwarded-For header. If header is not present.
* falls back to {@link RemoteAddressResolver} and
* {@link ServerHttpRequest#getRemoteAddress()}. Use the static constructor methods which
* meets your security requirements.
*
* @author Andrew Fitzgerald
* @author xiaoyu
*/
public class ForwardedRemoteAddressResolver implements RemoteAddressResolver {
/**
* Forwarded-For header name.
*/
public static final String X_FORWARDED_FOR = "X-Forwarded-For";
private static final Logger LOGGER = LoggerFactory
.getLogger(ForwardedRemoteAddressResolver.class);
private final RemoteAddressResolver defaultRemoteIpResolver = new RemoteAddressResolver() {
};
private final int maxTrustedIndex;
/**
* Instantiates a new Forwarded remote address resolver.
*
* @param maxTrustedIndex the max trusted index
*/
public ForwardedRemoteAddressResolver(final int maxTrustedIndex) {
this.maxTrustedIndex = maxTrustedIndex;
}
/**
* Trust all forwarded remote address resolver.
*
* @return the forwarded remote address resolver
*/
public static ForwardedRemoteAddressResolver trustAll() {
return new ForwardedRemoteAddressResolver(Integer.MAX_VALUE);
}
/**
* Max trusted index forwarded remote address resolver.
*
* @param maxTrustedIndex the max trusted index
* @return the forwarded remote address resolver
*/
public static ForwardedRemoteAddressResolver maxTrustedIndex(final int maxTrustedIndex) {
Assert.isTrue(maxTrustedIndex > 0, "An index greater than 0 is required");
return new ForwardedRemoteAddressResolver(maxTrustedIndex);
}
@Override
public InetSocketAddress resolve(final ServerWebExchange exchange) {
List<String> xForwardedValues = extractXForwardedValues(exchange);
Collections.reverse(xForwardedValues);
if (!xForwardedValues.isEmpty()) {
int index = Math.min(xForwardedValues.size(), maxTrustedIndex) - 1;
return new InetSocketAddress(xForwardedValues.get(index), 0);
}
return defaultRemoteIpResolver.resolve(exchange);
}
private List<String> extractXForwardedValues(final ServerWebExchange exchange) {
List<String> xForwardedValues = exchange.getRequest().getHeaders()
.get(X_FORWARDED_FOR);
if (xForwardedValues == null || xForwardedValues.isEmpty()) {
return Collections.emptyList();
}
if (xForwardedValues.size() > 1) {
LOGGER.warn("Multiple X-Forwarded-For headers found, discarding all");
return Collections.emptyList();
}
List<String> values = Arrays.asList(xForwardedValues.get(0).split(", "));
if (values.size() == 1 && !StringUtils.hasText(values.get(0))) {
return Collections.emptyList();
}
return values;
}
}
| {
"pile_set_name": "Github"
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class LoaderOptimizationAttribute : Attribute
{
private readonly byte _val;
public LoaderOptimizationAttribute(byte value)
{
_val = value;
}
public LoaderOptimizationAttribute(LoaderOptimization value)
{
_val = (byte)value;
}
public LoaderOptimization Value => (LoaderOptimization)_val;
}
}
| {
"pile_set_name": "Github"
} |
#include "StdSDK.h" // Standard application includes
#include "About.h" // For non-static function prototypes
#include "resource.h" // For resource identifiers
#include "pizza.h"
#include <tchar.h>
//
// Function prototypes for static functions
//
static BOOL mainFrame_DisplayContextMenu (HWND hwnd, POINT pt) ;
static int findSubmenuPosition(HMENU hmenu, UINT id);
//
// Function prototypes for callback functions
//
BOOL CALLBACK mainFrame_SysColorChangeNotification (HWND hwnd, LPARAM lParam) ;
LRESULT CALLBACK mainFrameWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) ;
//
// Function prototypes for message handlers
//
static void mainFrame_OnCommand (HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) ;
static BOOL mainFrame_OnContextMenu (HWND hwnd, HWND hwndCtl, int xPos, int yPos) ;
static BOOL mainFrame_OnCreate (HWND hwnd, LPCREATESTRUCT lpCreateStruct) ;
static void mainFrame_OnDestroy (HWND hwnd) ;
static void mainFrame_OnDisplayChange (HWND hwnd, UINT cBitsPerPixel, UINT cxScreen, UINT cyScreen) ;
static void mainFrame_OnNCRButtonUp (HWND hwnd, int x, int y, UINT codeHitTest) ;
static void mainFrame_OnPaint (HWND hwnd) ;
static void mainFrame_OnPrintClient (HWND hwnd, HDC hdc, UINT uFlags) ;
static void mainFrame_OnRButtonDown (HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags) ;
static void mainFrame_OnSettingChange (HWND hwnd, UINT uiFlag, LPCTSTR pszMetrics) ;
static void mainFrame_OnSize (HWND hwnd, UINT state, int cx, int cy) ;
static void mainFrame_OnSysColorChange(HWND hwnd) ;
static void mainFrame_OnUserChanged (HWND hwnd) ;
static void mainFrame_OnWinIniChange (HWND hwnd, LPCTSTR pszSection) ;
static void mainFrame_OnEnterIdle(HWND hwnd, UINT source, HWND hwndSource) ;
//
// Typedefs
//
//
// LRESULT CALLBACK
// mainFrameWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
//
// hwnd Handle of window to which this message applies
// message Message number
// wParam Message parameter
// lParam Message parameter
//
// PURPOSE: Processes messages for the main window.
//
// MESSAGES:
//
// WM_COMMAND - notification from the menu or controls
// WM_CONTEXTMENU - request to display a context menu
// WM_CREATE - notification that a window is being created
// WM_DESTROY - window is being destroyed
// WM_DISPLAYCHANGE - display resolution change notification
// WM_NCRBUTTONUP - right button release in non-client area
// WM_PAINT - redraw all or part of the client area
// WM_PRINTCLIENT - request to draw all of client area into provided DC
// WM_RBUTTONDOWN - right button click in client area
// WM_SETTINGCHANGE - system parameter change notification
// WM_SIZE - window size has changed
// WM_SYSCOLORCHANGE - system color setting change notification
// WM_USERCHANGED - user log in/out notification
//
LRESULT CALLBACK
mainFrameWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{ /* message */
case WM_COMMAND: // Notification from menu or control
return HANDLE_WM_COMMAND (hwnd, wParam, lParam,
mainFrame_OnCommand) ;
case WM_CONTEXTMENU: // Request to display a context menu
return HANDLE_WM_CONTEXTMENU (hwnd, wParam, lParam,
mainFrame_OnContextMenu) ;
case WM_DESTROY: // Window is being destroyed
return HANDLE_WM_DESTROY (hwnd, wParam, lParam,
mainFrame_OnDestroy) ;
case WM_DISPLAYCHANGE: // Only comes through on plug'n'play systems
return HANDLE_WM_DISPLAYCHANGE (hwnd, wParam, lParam,
mainFrame_OnDisplayChange) ;
case WM_NCRBUTTONUP: // Right click on windows non-client area...
return HANDLE_WM_NCRBUTTONUP (hwnd, wParam, lParam,
mainFrame_OnNCRButtonUp) ;
case WM_PAINT: // Draw all or part of client area
return HANDLE_WM_PAINT (hwnd, wParam, lParam,
mainFrame_OnPaint) ;
case WM_PRINTCLIENT: // Draw all of client area into provided DC
return HANDLE_WM_PRINTCLIENT (hwnd, wParam, lParam,
mainFrame_OnPrintClient) ;
case WM_RBUTTONDOWN: // Right click in windows client area...
return HANDLE_WM_RBUTTONDOWN (hwnd, wParam, lParam,
mainFrame_OnRButtonDown) ;
case WM_SETTINGCHANGE: // An application changed a systemwide setting
// case WM_WININICHANGE: // A WIN.INI setting has changed
return HANDLE_WM_SETTINGCHANGE (hwnd, wParam, lParam,
mainFrame_OnSettingChange) ;
case WM_SIZE: // Window size has changed
return HANDLE_WM_SIZE (hwnd, wParam, lParam,
mainFrame_OnSize) ;
case WM_SYSCOLORCHANGE: // A change has been made to a system color setting
return HANDLE_WM_SYSCOLORCHANGE (hwnd, wParam, lParam,
mainFrame_OnSysColorChange) ;
case WM_USERCHANGED: // User logged in or out
return HANDLE_WM_USERCHANGED (hwnd, wParam, lParam,
mainFrame_OnUserChanged) ;
case WM_ENTERIDLE:
return HANDLE_WM_ENTERIDLE(hwnd, wParam, lParam,
mainFrame_OnEnterIdle) ;
default:
return DefWindowProc (hwnd, message, wParam, lParam) ;
}
}
static void mainFrame_OnAppAbout(HWND hwnd)
{
}
//
// static void mainFrame_OnPizza(HWND hwnd)
//
// hwnd: Main frame window handle
//
// EFFECT:
// Order Change Default Effect
// Yes No Place order
// No No Do nothing
// Yes Yes Change default; place order
// No Yes Ask for confirmation of change; do not place
static
void mainFrame_OnPizza(HWND hwnd)
{
PIZZA pizza;
LPPIZZA startwith = NULL;
startwith = getPizzaSelection(hwnd);
if(startwith != NULL)
{ /* has pizza */
pizza = *startwith; // make working copy
pizza.update_standard = FALSE;
if(getPizzaOrder (hwnd, &pizza))
{ /* successful order */
// If the user asked to change the standard order,
// honor this request now...
if(pizza.standard && pizza.update_standard)
*startwith = pizza; // copy result back
if(!orderPizza(hwnd, &pizza))
pizzaOrderFailure(hwnd, &pizza);
} /* successful order */
else
{ /* order cancelled */
if(pizza.standard && pizza.update_standard)
{ /* cancelled, but changed */
if(MessageBox(hwnd, _T("The order was cancelled, but you\n"
"asked to have the standard order\n"
"changed. Do you still want to change\n"
"the standard order?"),
_T("Confirm change"),
MB_ICONQUESTION | MB_YESNO) == IDYES)
{ /* change anyway */
*startwith = pizza; // copy result back
} /* change anyway */
} /* cancelled, but changed */
} /* order cancelled */
} /* has pizza */
releasePizza(startwith);
}
static void mainFrame_OnHelpTopics(HWND hwnd)
{
BOOL bGotHelp = WinHelp (hwnd, getHelpFileName (), HELP_FINDER, (DWORD) 0) ;
if (!bGotHelp)
MessageBox (GetFocus(),_T("Unable to activate help"),
getAppName (), MB_OK|MB_ICONERROR) ;
}
// void mainFrame_OnEnterIdle(HWND hwnd, UINT id, HWND hwndSource)
//
// EFFECT:
// Forwards the idle message to a dialog
//
static void
mainFrame_OnEnterIdle(HWND hwnd, UINT source, HWND hwndSource)
{
if(source == MSGF_DIALOGBOX)
FORWARD_WM_ENTERIDLE(hwndSource, source, NULL, SendMessage);
else
FORWARD_WM_ENTERIDLE(hwnd, source, hwndSource, DefWindowProc);
}
//
// void mainFrame_OnCommand (HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
//
// hwnd Handle of window to which this message applies
// id Specifies the identifier of the menu item, control, or accelerator.
// hwndCtl Handle of the control sending the message if the message
// is from a control, otherwise, this parameter is NULL.
// codeNotify Specifies the notification code if the message is from a control.
// This parameter is 1 when the message is from an accelerator.
// This parameter is 0 when the message is from a menu.
//
// PURPOSE:
//
// COMMENTS:
//
static void
mainFrame_OnCommand (HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch (id) {
case ID_APP_ABOUT:
doAbout(hwnd);
return ;
case ID_APP_EXIT:
DestroyWindow (hwnd) ;
return ;
case IDM_PIZZA:
mainFrame_OnPizza(hwnd);
return ;
case ID_HELP_HELP_TOPICS:
mainFrame_OnHelpTopics(hwnd);
return ;
// Here are all the other possible menu options,
// all of these are currently disabled:
// The File menu
case ID_FILE_NEW:
case ID_FILE_OPEN:
case ID_FILE_CLOSE:
case ID_FILE_SAVE:
case ID_FILE_SAVE_AS:
case ID_FILE_SAVE_ALL:
case ID_FILE_PAGE_SETUP:
case ID_FILE_PRINT:
// The Edit menu
case ID_EDIT_UNDO:
case ID_EDIT_REDO:
case ID_EDIT_CUT:
case ID_EDIT_COPY:
case ID_EDIT_PASTE:
case ID_EDIT_CLEAR:
case ID_EDIT_SELECT_ALL:
case ID_EDIT_PROPERTIES:
default:
FORWARD_WM_COMMAND (hwnd, id, hwndCtl, codeNotify, DefWindowProc) ;
}
}
//
// BOOL mainFrame_OnContextMenu (HWND hwnd, HWND hwndCtl, int xPos, int yPos)
//
// hwnd Handle of window to which this message applies
// hwndCtl Handle of the window in which the user right clicked the mouse
// This may be the frame window itself or a control.
// xPos Horizontal position of the cursor, in screen coordinates
// yPos Vertical position of the cursor, in screen coordinates
//
// PURPOSE: Notification that the user clicked the right
// mouse button in the window.
//
// COMMENTS: Normally a window processes this message by
// displaying a context menu using the TrackPopupMenu
// or TrackPopupMenuEx functions. If a window does not
// display a context menu it should pass this message
// to the DefWindowProc function.
//
static BOOL
mainFrame_OnContextMenu (HWND hwnd, HWND hwndCtl, int xPos, int yPos)
{
POINT pt = { xPos, yPos } ; // location of mouse click
RECT rc ; // client area of window
// Get the bounding rectangle of the client area.
GetClientRect (hwnd, &rc) ;
// Convert the mouse position to client coordinates.
ScreenToClient (hwnd, &pt) ;
// If the mouse click was in the client area,
// display the appropriate floating popup menu.
if (PtInRect (&rc, pt))
if (mainFrame_DisplayContextMenu (hwnd, pt))
return TRUE;
// Otherwise forward the message for default processing
return FORWARD_WM_CONTEXTMENU (hwnd, hwndCtl, xPos, yPos, DefWindowProc) ;
}
//
// BOOL mainFrame_OnCreate (HWND hwnd, LPCREATESTRUCT lpCreateStruct)
//
// hwnd Handle of window to which this message applies
// lpCreateStruct Points to a CREATESTRUCT structure that contains
// information about the window being created
//
// PURPOSE: Perform any per-window initialization in response
// to this message, such as creating any desired
// child windows such as toolbars and status bars.
//
// COMMENTS: Windows sends this message after the window is
// created, but before the window becomes visible.
// Return TRUE to continue creation of the window;
// otherwise return FALSE to fail the window creation.
//
static BOOL
mainFrame_OnCreate (HWND hwnd, LPCREATESTRUCT lpCreateStruct)
{
return TRUE ;
}
//
// void mainFrame_OnDestroy (HWND hwnd)
//
// hwnd Handle of window to which this message applies
//
// PURPOSE: Notification that the specified window is being destroyed.
// The window is no longer visible to the user.
//
// COMMENTS:
//
static void
mainFrame_OnDestroy (HWND hwnd)
{
// Tell WinHelp we don't need it any more...
WinHelp (hwnd, getHelpFileName (), HELP_QUIT, (DWORD) 0) ;
PostQuitMessage (0) ;
}
//
// void mainFrame_OnDisplayChange (HWND hwnd, UINT cBitsPerPixel,
// UINT cxScreen, UINT cyScreen)
//
// hwnd Handle of window to which this message applies
// cBitsPerPixel Specifies the new image depth of the display
// in bits per pixel.
// cxScreen Specifies the new horizontal resolution of the screen.
// cyScreen Specifies the new vertical resolution of the screen.
//
// PURPOSE: Windows calls this handler when the display
// resolution has changed.
//
// COMMENTS: Beta versions of Windows 95 sent this message twice,
// once in anticipation of a change to the display
// resolution and once after the display resolution
// changed. The cBitsPerPixel parameter was a Boolean
// value which indicated which notification applied.
//
// Windows 95 now only sends this message after the
// display resolution has changed and the cBitsPerPixel
// parameter has the semantics described above.
//
// VERSION NOTES: The WM_DISPLAYCHANGE message is implemented on Windows 95
// but not currently on the Windows NT.
//
static void
mainFrame_OnDisplayChange (HWND hwnd, UINT cBitsPerPixel, UINT cxScreen, UINT cyScreen)
{
FORWARD_WM_DISPLAYCHANGE (hwnd, cBitsPerPixel, cxScreen, cyScreen, DefWindowProc) ;
}
//
// void mainFrame_OnNCRButtonUp (HWND hwnd, int x, int y, UINT codeHitTest)
//
// hwnd Handle of window to which this message applies
// x Specifies the horizontal client coordinate of the mouse click.
// y Specifies the vertical client coordinate of the mouse click.
// codeHitTest Specifies the hit-test value returned by the DefWindowProc
// function as a result of processing the WM_NCHITTEST message.
//
// PURPOSE: Windows calls this handler when the user releases the right
// mouse button while the cursor is in the non-client area of
// a window.
//
// COMMENTS: Windows 95 user interface guildines state that you should
// display a window popup menu in certain circumstances in
// response to this message. The window pop-up menu is
// the popup menu associated with a window, in this case,
// the main frame window. Do not mistake the window popup
// menu for the "Window" drop-down menu found in MDI
// applications. The window popup menu replaces the
// Windows 3.x Control menu, also referred to as the System
// menu.
//
// Note: DefWindowProc on Windows 95 processes this message
// by sending a WM_CONTEXTMENU message. Therefore all context
// menu processing under Windows 95 is normally performed
// in response to the WM_CONTEXTMENU message.
// The user displays a window’s popup menu by clicking the
// right mouse button anywhere in the title bar area, excluding
// the title bar icon. Clicking on the title bar icon with
// the right button displays the pop-up menu for the object
// represented by the icon.
//
static void
mainFrame_OnNCRButtonUp (HWND hwnd, int x, int y, UINT codeHitTest)
{
switch (codeHitTest) {
case HTSYSMENU:
// Windows NT note:
// The user just clicked the right mouse button on the application's
// title bar icon. Normally you would now alter the default system menu
// however your application requires. See the Explorer for an example.
return ;
case HTCAPTION:
case HTREDUCE:
case HTZOOM:
// Windows NT note:
// The user just clicked the right mouse button on the application's
// title bar , excluding the title bar icon. Normally you would now
// display the window popup menu.
return ;
}
// Allow default message processing regardless
FORWARD_WM_NCRBUTTONUP (hwnd, x, y, codeHitTest, DefWindowProc) ;
}
//
// void mainFrame_OnPaint (HWND hwnd)
//
// hwnd Handle of window to which this message applies
//
// PURPOSE: Windows calls this handler when the window needs repainting.
//
// COMMENTS:
//
static void
mainFrame_OnPaint (HWND hwnd)
{
HDC hdc ;
PAINTSTRUCT ps ;
hdc = BeginPaint (hwnd, &ps) ;
// Your drawing code goes here...
EndPaint (hwnd, &ps) ;
}
//
// void mainFrame_OnPrintClient (HWND hwnd, HDC hdc, UINT uFlags)
//
// hwnd Handle of window to which this message applies
// hdc Handle of device context in which to draw client area
// uFlags Drawing flags from WM_PRINT message
//
// PURPOSE: Draw the client area into the provided device context
// which is typically a printer device context. You should
// drawing the entire client area, unlike WM_PRINT processing
// where you draw only the invalid area.
//
// COMMENTS:
//
// VERSION NOTES: The WM_PRINTCLIENT message is implemented on Windows 95
// but not currently on the Windows NT.
//
static void
mainFrame_OnPrintClient (HWND hwnd, HDC hdc, UINT uFlags)
{
// Your drawing code goes here
}
//
// void mainFrame_OnRButtonDown (HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags)
//
// hwnd Handle of window to which this message applies
// fDoubleClick TRUE when this is a double-click notification,
// FALSE when this is a single-click notification.
// x Specifies the horizontal client coordinate of the mouse click
// y Specifies the vertical client coordinate of the mouse click
// keyFlags Flags indicating the state of some virtual keys
//
// PURPOSE: Windows calls this handler when the user presses the right
// mouse button while the cursor is in the client area of a window.
//
// COMMENTS: Windows 95 user interface guidelines recommend you display
// the context menu for the item in the client area upon which
// the user just clicked.
//
//
static void
mainFrame_OnRButtonDown (HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags)
{
POINT pt = { x, y } ;
mainFrame_DisplayContextMenu (hwnd, pt) ;
}
//
// void mainFrame_OnSettingChange (HWND hwnd, UINT uiFlag, LPCTSTR pszMetrics)
// void mainFrame_OnWinIniChange (HWND hwnd, UINT unused, LPCTSTR pszSection)
//
// WM_SETTINGCHANGE:
// hwnd Handle of window to which this message applies
// uiFlag Specifies the systemwide parameter that has changed.
// pszMetrics Points to the string "WindowMetrics" when certain
// systemwide parameters have changed
//
// WM_WININICHANGE:
// hwnd Handle of window to which this message applies
// unused Unused, must be zero.
// pszSection Points to a string containing the name
// of the section that has changed
//
// PURPOSE: This is the appropriate place to reload any system
// metrics that the application has cached.
//
// COMMENTS: Windows 95 sends the WM_SETTINGCHANGE message to all
// windows after an application changes a system-wide
// setting by calling the SystemParametersInfo function.
//
// Windows NT sends the WM_WININICHANGE message to all
// windows after an application changes a system-wide
// setting by calling the SystemParametersInfo function.
//
// On all operating systems, an application sends the
// WM_WININICHANGE message to all top-level windows
// after making a change to the WIN.INI file
//
// VERSION NOTES: Microsoft assigned the same message code (26) to both
// the WM_SETTINGCHANGE and the WM_WININICHANGE messages.
// The only way to distinguish the two messages is to
// test the uiFlag parameter. A zero value means this is
// a WM_WININICHANGE message and a non-zero value means
// this is a WM_SETTINGCHANGE message.
//
static void
mainFrame_OnSettingChange (HWND hwnd, UINT uiFlag, LPCTSTR pszMetrics)
{
}
//
// void mainFrame_OnSize (HWND hwnd, UINT state, int cx, int cy)
//
// hwnd Handle of window to which this message applies
// state
// cx New horizontal extent of window
// cy New vertical extent of window
//
// PURPOSE: Notify child windows that parent changed size.
//
// COMMENTS:
//
static void mainFrame_OnSize (HWND hwnd, UINT state, int cx, int cy)
{
}
//
// void mainFrame_OnSysColorChange (HWND hwnd)
//
// hwnd Handle of window to which this message applies
//
// PURPOSE: Forward the WM_SYSCOLORCHANGE message to all child
// windows of this top-level window, as well as to all
// children of the child windows, if any.
//
// COMMENTS: Windows sends the WM_SYSCOLORCHANGE message to all
// top-level windows after a change has been made to
// the system color settings. Your top level window
// must forward the WM_SYSCOLORCHANGE message to its
// common controls; otherwise the controls will not be
// notified of the color change.
//
static void
mainFrame_OnSysColorChange (HWND hwnd)
{
EnumChildWindows (hwnd, mainFrame_SysColorChangeNotification, (LPARAM) NULL) ;
}
//
// static BOOL CALLBACK
// mainFrame_SysColorChangeNotification (HWND hwnd, LPARAM lParam)
//
// hwnd Handle of child window
// lParam Application-defined value specified as the last
// parameter on the EnumChildWindows function call.
//
// PURPOSE: Forward a WM_SYSCOLORCHANGE message to the
// specified child window.
//
// COMMENTS:
//
BOOL CALLBACK
mainFrame_SysColorChangeNotification (HWND hwnd, LPARAM lParam)
{
// Forward the message to a child window
FORWARD_WM_SYSCOLORCHANGE (hwnd, SendMessage) ;
// Keep on enumerating...
return TRUE ;
lParam ; // Parameter not referenced
}
//
// void mainFrame_OnUserChanged (HWND hwnd)
//
// hwnd Handle of window to which this message applies
//
// PURPOSE: This is the appropriate place to reload any cached
// user-specific information.
//
// COMMENTS: Windows sends the WM_USERCHANGED message to all windows
// after a user has logged on or off. When a user logs on
// or off, the system updates the user-specific settings.
// Windows sends the WM_USERCHANGED message immediately
// after updating the user-specific settings.
//
// VERSION NOTES: The WM_USERCHANGED message is implemented on Windows 95
// but not currently on the Windows NT.
//
static void
mainFrame_OnUserChanged (HWND hwnd)
{
}
//
// BOOL mainFrame_DisplayContextMenu (HWND hwnd, POINT pt)
//
// hwnd Handle of window to which this message applies
// pt Location of mouse click in client coordinates
//
// PURPOSE: Display the appropriate context menu for the object
// located at 'pt' in the main frame window.
//
// COMMENTS:
//
BOOL mainFrame_DisplayContextMenu (HWND hwnd, POINT pt)
{
HMENU hmenuBar, hmenuPopup ;
int pos;
// Determine the appropriate context menu to display.
// generally using the application state and mouse click coordinates.
// Bring up the 'Help' popup menu for lack of a better solution
// Get main menu handle
hmenuBar = GetMenu (hwnd) ;
ASSERT (NULL != hmenuBar) ;
pos = findSubmenuPosition(hmenuBar, ID_HELP_HELP_TOPICS);
ASSERT(pos != -1);
if(pos == -1)
return TRUE;
hmenuPopup = GetSubMenu (hmenuBar, pos) ;
ASSERT (NULL != hmenuPopup) ;
// Convert click location to screen coordinates
ClientToScreen (hwnd, &pt) ;
// Display the floating popup menu at the mouse click location
// Track the right mouse as this function is called during
// WM_CONTEXTMENU message processing.
return TrackPopupMenu (hmenuPopup,
TPM_LEFTALIGN | TPM_RIGHTBUTTON,
pt.x, pt.y, 0, hwnd, NULL) ;
}
/////////////////////////////////////////////////////////////
// findSubmenuPosition
// HMENU hmenu: Menu in which we are
// searching for submenu
// UINT id: ID for item in submenu
// RETURNS: int
// The position in the hmenu where the
// submenu containing 'id' is found. Value
// is -1 if no submenu containing the id
// can be found
static int findSubmenuPosition(HMENU hmenu, UINT id)
{
int i;
HMENU hSubMenu;
for (i = 0;
i < GetMenuItemCount(hmenu);
i++)
{ /* find submenu */
hSubMenu = GetSubMenu(hmenu, i);
if(hSubMenu == NULL)
continue ; // not a pop-up
if(GetMenuState(hSubMenu, id,
MF_BYCOMMAND) == 0xFFFFFFFF)
continue; // not in this menu
return i;
} /* find submenu */
return -1;
}
| {
"pile_set_name": "Github"
} |
// unordered_set implementation -*- C++ -*-
// Copyright (C) 2010-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This 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, or (at your option)
// any later version.
// This 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.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file bits/unordered_set.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{unordered_set}
*/
#ifndef _UNORDERED_SET_H
#define _UNORDERED_SET_H
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
/// Base types for unordered_set.
template<bool _Cache>
using __uset_traits = __detail::_Hashtable_traits<_Cache, true, true>;
template<typename _Value,
typename _Hash = hash<_Value>,
typename _Pred = std::equal_to<_Value>,
typename _Alloc = std::allocator<_Value>,
typename _Tr = __uset_traits<__cache_default<_Value, _Hash>::value>>
using __uset_hashtable = _Hashtable<_Value, _Value, _Alloc,
__detail::_Identity, _Pred, _Hash,
__detail::_Mod_range_hashing,
__detail::_Default_ranged_hash,
__detail::_Prime_rehash_policy, _Tr>;
/// Base types for unordered_multiset.
template<bool _Cache>
using __umset_traits = __detail::_Hashtable_traits<_Cache, true, false>;
template<typename _Value,
typename _Hash = hash<_Value>,
typename _Pred = std::equal_to<_Value>,
typename _Alloc = std::allocator<_Value>,
typename _Tr = __umset_traits<__cache_default<_Value, _Hash>::value>>
using __umset_hashtable = _Hashtable<_Value, _Value, _Alloc,
__detail::_Identity,
_Pred, _Hash,
__detail::_Mod_range_hashing,
__detail::_Default_ranged_hash,
__detail::_Prime_rehash_policy, _Tr>;
/**
* @brief A standard container composed of unique keys (containing
* at most one of each key value) in which the elements' keys are
* the elements themselves.
*
* @ingroup unordered_associative_containers
*
* @tparam _Value Type of key objects.
* @tparam _Hash Hashing function object type, defaults to hash<_Value>.
* @tparam _Pred Predicate function object type, defaults to
* equal_to<_Value>.
*
* @tparam _Alloc Allocator type, defaults to allocator<_Key>.
*
* Meets the requirements of a <a href="tables.html#65">container</a>, and
* <a href="tables.html#xx">unordered associative container</a>
*
* Base is _Hashtable, dispatched at compile time via template
* alias __uset_hashtable.
*/
template<class _Value,
class _Hash = hash<_Value>,
class _Pred = std::equal_to<_Value>,
class _Alloc = std::allocator<_Value> >
class unordered_set : __check_copy_constructible<_Alloc>
{
typedef __uset_hashtable<_Value, _Hash, _Pred, _Alloc> _Hashtable;
_Hashtable _M_h;
public:
// typedefs:
//@{
/// Public typedefs.
typedef typename _Hashtable::key_type key_type;
typedef typename _Hashtable::value_type value_type;
typedef typename _Hashtable::hasher hasher;
typedef typename _Hashtable::key_equal key_equal;
typedef typename _Hashtable::allocator_type allocator_type;
//@}
//@{
/// Iterator-related typedefs.
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename _Hashtable::iterator iterator;
typedef typename _Hashtable::const_iterator const_iterator;
typedef typename _Hashtable::local_iterator local_iterator;
typedef typename _Hashtable::const_local_iterator const_local_iterator;
typedef typename _Hashtable::size_type size_type;
typedef typename _Hashtable::difference_type difference_type;
//@}
// construct/destroy/copy
/**
* @brief Default constructor creates no elements.
* @param __n Initial number of buckets.
* @param __hf A hash functor.
* @param __eql A key equality functor.
* @param __a An allocator object.
*/
explicit
unordered_set(size_type __n = 10,
const hasher& __hf = hasher(),
const key_equal& __eql = key_equal(),
const allocator_type& __a = allocator_type())
: _M_h(__n, __hf, __eql, __a)
{ }
/**
* @brief Builds an %unordered_set from a range.
* @param __first An input iterator.
* @param __last An input iterator.
* @param __n Minimal initial number of buckets.
* @param __hf A hash functor.
* @param __eql A key equality functor.
* @param __a An allocator object.
*
* Create an %unordered_set consisting of copies of the elements from
* [__first,__last). This is linear in N (where N is
* distance(__first,__last)).
*/
template<typename _InputIterator>
unordered_set(_InputIterator __f, _InputIterator __l,
size_type __n = 0,
const hasher& __hf = hasher(),
const key_equal& __eql = key_equal(),
const allocator_type& __a = allocator_type())
: _M_h(__f, __l, __n, __hf, __eql, __a)
{ }
/// Copy constructor.
unordered_set(const unordered_set&) = default;
/// Move constructor.
unordered_set(unordered_set&&) = default;
/**
* @brief Builds an %unordered_set from an initializer_list.
* @param __l An initializer_list.
* @param __n Minimal initial number of buckets.
* @param __hf A hash functor.
* @param __eql A key equality functor.
* @param __a An allocator object.
*
* Create an %unordered_set consisting of copies of the elements in the
* list. This is linear in N (where N is @a __l.size()).
*/
unordered_set(initializer_list<value_type> __l,
size_type __n = 0,
const hasher& __hf = hasher(),
const key_equal& __eql = key_equal(),
const allocator_type& __a = allocator_type())
: _M_h(__l, __n, __hf, __eql, __a)
{ }
/// Copy assignment operator.
unordered_set&
operator=(const unordered_set&) = default;
/// Move assignment operator.
unordered_set&
operator=(unordered_set&&) = default;
/**
* @brief %Unordered_set list assignment operator.
* @param __l An initializer_list.
*
* This function fills an %unordered_set with copies of the elements in
* the initializer list @a __l.
*
* Note that the assignment completely changes the %unordered_set and
* that the resulting %unordered_set's size is the same as the number
* of elements assigned. Old data may be lost.
*/
unordered_set&
operator=(initializer_list<value_type> __l)
{
_M_h = __l;
return *this;
}
/// Returns the allocator object with which the %unordered_set was
/// constructed.
allocator_type
get_allocator() const noexcept
{ return _M_h.get_allocator(); }
// size and capacity:
/// Returns true if the %unordered_set is empty.
bool
empty() const noexcept
{ return _M_h.empty(); }
/// Returns the size of the %unordered_set.
size_type
size() const noexcept
{ return _M_h.size(); }
/// Returns the maximum size of the %unordered_set.
size_type
max_size() const noexcept
{ return _M_h.max_size(); }
// iterators.
//@{
/**
* Returns a read-only (constant) iterator that points to the first
* element in the %unordered_set.
*/
iterator
begin() noexcept
{ return _M_h.begin(); }
const_iterator
begin() const noexcept
{ return _M_h.begin(); }
//@}
//@{
/**
* Returns a read-only (constant) iterator that points one past the last
* element in the %unordered_set.
*/
iterator
end() noexcept
{ return _M_h.end(); }
const_iterator
end() const noexcept
{ return _M_h.end(); }
//@}
/**
* Returns a read-only (constant) iterator that points to the first
* element in the %unordered_set.
*/
const_iterator
cbegin() const noexcept
{ return _M_h.begin(); }
/**
* Returns a read-only (constant) iterator that points one past the last
* element in the %unordered_set.
*/
const_iterator
cend() const noexcept
{ return _M_h.end(); }
// modifiers.
/**
* @brief Attempts to build and insert an element into the
* %unordered_set.
* @param __args Arguments used to generate an element.
* @return A pair, of which the first element is an iterator that points
* to the possibly inserted element, and the second is a bool
* that is true if the element was actually inserted.
*
* This function attempts to build and insert an element into the
* %unordered_set. An %unordered_set relies on unique keys and thus an
* element is only inserted if it is not already present in the
* %unordered_set.
*
* Insertion requires amortized constant time.
*/
template<typename... _Args>
std::pair<iterator, bool>
emplace(_Args&&... __args)
{ return _M_h.emplace(std::forward<_Args>(__args)...); }
/**
* @brief Attempts to insert an element into the %unordered_set.
* @param __pos An iterator that serves as a hint as to where the
* element should be inserted.
* @param __args Arguments used to generate the element to be
* inserted.
* @return An iterator that points to the element with key equivalent to
* the one generated from @a __args (may or may not be the
* element itself).
*
* This function is not concerned about whether the insertion took place,
* and thus does not return a boolean like the single-argument emplace()
* does. Note that the first parameter is only a hint and can
* potentially improve the performance of the insertion process. A bad
* hint would cause no gains in efficiency.
*
* For more on @a hinting, see:
* http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt07ch17.html
*
* Insertion requires amortized constant time.
*/
template<typename... _Args>
iterator
emplace_hint(const_iterator __pos, _Args&&... __args)
{ return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); }
//@{
/**
* @brief Attempts to insert an element into the %unordered_set.
* @param __x Element to be inserted.
* @return A pair, of which the first element is an iterator that points
* to the possibly inserted element, and the second is a bool
* that is true if the element was actually inserted.
*
* This function attempts to insert an element into the %unordered_set.
* An %unordered_set relies on unique keys and thus an element is only
* inserted if it is not already present in the %unordered_set.
*
* Insertion requires amortized constant time.
*/
std::pair<iterator, bool>
insert(const value_type& __x)
{ return _M_h.insert(__x); }
std::pair<iterator, bool>
insert(value_type&& __x)
{ return _M_h.insert(std::move(__x)); }
//@}
//@{
/**
* @brief Attempts to insert an element into the %unordered_set.
* @param __hint An iterator that serves as a hint as to where the
* element should be inserted.
* @param __x Element to be inserted.
* @return An iterator that points to the element with key of
* @a __x (may or may not be the element passed in).
*
* This function is not concerned about whether the insertion took place,
* and thus does not return a boolean like the single-argument insert()
* does. Note that the first parameter is only a hint and can
* potentially improve the performance of the insertion process. A bad
* hint would cause no gains in efficiency.
*
* For more on @a hinting, see:
* http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt07ch17.html
*
* Insertion requires amortized constant.
*/
iterator
insert(const_iterator __hint, const value_type& __x)
{ return _M_h.insert(__hint, __x); }
iterator
insert(const_iterator __hint, value_type&& __x)
{ return _M_h.insert(__hint, std::move(__x)); }
//@}
/**
* @brief A template function that attempts to insert a range of
* elements.
* @param __first Iterator pointing to the start of the range to be
* inserted.
* @param __last Iterator pointing to the end of the range.
*
* Complexity similar to that of the range constructor.
*/
template<typename _InputIterator>
void
insert(_InputIterator __first, _InputIterator __last)
{ _M_h.insert(__first, __last); }
/**
* @brief Attempts to insert a list of elements into the %unordered_set.
* @param __l A std::initializer_list<value_type> of elements
* to be inserted.
*
* Complexity similar to that of the range constructor.
*/
void
insert(initializer_list<value_type> __l)
{ _M_h.insert(__l); }
//@{
/**
* @brief Erases an element from an %unordered_set.
* @param __position An iterator pointing to the element to be erased.
* @return An iterator pointing to the element immediately following
* @a __position prior to the element being erased. If no such
* element exists, end() is returned.
*
* This function erases an element, pointed to by the given iterator,
* from an %unordered_set. Note that this function only erases the
* element, and that if the element is itself a pointer, the pointed-to
* memory is not touched in any way. Managing the pointer is the user's
* responsibility.
*/
iterator
erase(const_iterator __position)
{ return _M_h.erase(__position); }
// LWG 2059.
iterator
erase(iterator __it)
{ return _M_h.erase(__it); }
//@}
/**
* @brief Erases elements according to the provided key.
* @param __x Key of element to be erased.
* @return The number of elements erased.
*
* This function erases all the elements located by the given key from
* an %unordered_set. For an %unordered_set the result of this function
* can only be 0 (not present) or 1 (present).
* Note that this function only erases the element, and that if
* the element is itself a pointer, the pointed-to memory is not touched
* in any way. Managing the pointer is the user's responsibility.
*/
size_type
erase(const key_type& __x)
{ return _M_h.erase(__x); }
/**
* @brief Erases a [__first,__last) range of elements from an
* %unordered_set.
* @param __first Iterator pointing to the start of the range to be
* erased.
* @param __last Iterator pointing to the end of the range to
* be erased.
* @return The iterator @a __last.
*
* This function erases a sequence of elements from an %unordered_set.
* Note that this function only erases the element, and that if
* the element is itself a pointer, the pointed-to memory is not touched
* in any way. Managing the pointer is the user's responsibility.
*/
iterator
erase(const_iterator __first, const_iterator __last)
{ return _M_h.erase(__first, __last); }
/**
* Erases all elements in an %unordered_set. Note that this function only
* erases the elements, and that if the elements themselves are pointers,
* the pointed-to memory is not touched in any way. Managing the pointer
* is the user's responsibility.
*/
void
clear() noexcept
{ _M_h.clear(); }
/**
* @brief Swaps data with another %unordered_set.
* @param __x An %unordered_set of the same element and allocator
* types.
*
* This exchanges the elements between two sets in constant time.
* Note that the global std::swap() function is specialized such that
* std::swap(s1,s2) will feed to this function.
*/
void
swap(unordered_set& __x)
{ _M_h.swap(__x._M_h); }
// observers.
/// Returns the hash functor object with which the %unordered_set was
/// constructed.
hasher
hash_function() const
{ return _M_h.hash_function(); }
/// Returns the key comparison object with which the %unordered_set was
/// constructed.
key_equal
key_eq() const
{ return _M_h.key_eq(); }
// lookup.
//@{
/**
* @brief Tries to locate an element in an %unordered_set.
* @param __x Element to be located.
* @return Iterator pointing to sought-after element, or end() if not
* found.
*
* This function takes a key and tries to locate the element with which
* the key matches. If successful the function returns an iterator
* pointing to the sought after element. If unsuccessful it returns the
* past-the-end ( @c end() ) iterator.
*/
iterator
find(const key_type& __x)
{ return _M_h.find(__x); }
const_iterator
find(const key_type& __x) const
{ return _M_h.find(__x); }
//@}
/**
* @brief Finds the number of elements.
* @param __x Element to located.
* @return Number of elements with specified key.
*
* This function only makes sense for unordered_multisets; for
* unordered_set the result will either be 0 (not present) or 1
* (present).
*/
size_type
count(const key_type& __x) const
{ return _M_h.count(__x); }
//@{
/**
* @brief Finds a subsequence matching given key.
* @param __x Key to be located.
* @return Pair of iterators that possibly points to the subsequence
* matching given key.
*
* This function probably only makes sense for multisets.
*/
std::pair<iterator, iterator>
equal_range(const key_type& __x)
{ return _M_h.equal_range(__x); }
std::pair<const_iterator, const_iterator>
equal_range(const key_type& __x) const
{ return _M_h.equal_range(__x); }
//@}
// bucket interface.
/// Returns the number of buckets of the %unordered_set.
size_type
bucket_count() const noexcept
{ return _M_h.bucket_count(); }
/// Returns the maximum number of buckets of the %unordered_set.
size_type
max_bucket_count() const noexcept
{ return _M_h.max_bucket_count(); }
/*
* @brief Returns the number of elements in a given bucket.
* @param __n A bucket index.
* @return The number of elements in the bucket.
*/
size_type
bucket_size(size_type __n) const
{ return _M_h.bucket_size(__n); }
/*
* @brief Returns the bucket index of a given element.
* @param __key A key instance.
* @return The key bucket index.
*/
size_type
bucket(const key_type& __key) const
{ return _M_h.bucket(__key); }
//@{
/**
* @brief Returns a read-only (constant) iterator pointing to the first
* bucket element.
* @param __n The bucket index.
* @return A read-only local iterator.
*/
local_iterator
begin(size_type __n)
{ return _M_h.begin(__n); }
const_local_iterator
begin(size_type __n) const
{ return _M_h.begin(__n); }
const_local_iterator
cbegin(size_type __n) const
{ return _M_h.cbegin(__n); }
//@}
//@{
/**
* @brief Returns a read-only (constant) iterator pointing to one past
* the last bucket elements.
* @param __n The bucket index.
* @return A read-only local iterator.
*/
local_iterator
end(size_type __n)
{ return _M_h.end(__n); }
const_local_iterator
end(size_type __n) const
{ return _M_h.end(__n); }
const_local_iterator
cend(size_type __n) const
{ return _M_h.cend(__n); }
//@}
// hash policy.
/// Returns the average number of elements per bucket.
float
load_factor() const noexcept
{ return _M_h.load_factor(); }
/// Returns a positive number that the %unordered_set tries to keep the
/// load factor less than or equal to.
float
max_load_factor() const noexcept
{ return _M_h.max_load_factor(); }
/**
* @brief Change the %unordered_set maximum load factor.
* @param __z The new maximum load factor.
*/
void
max_load_factor(float __z)
{ _M_h.max_load_factor(__z); }
/**
* @brief May rehash the %unordered_set.
* @param __n The new number of buckets.
*
* Rehash will occur only if the new number of buckets respect the
* %unordered_set maximum load factor.
*/
void
rehash(size_type __n)
{ _M_h.rehash(__n); }
/**
* @brief Prepare the %unordered_set for a specified number of
* elements.
* @param __n Number of elements required.
*
* Same as rehash(ceil(n / max_load_factor())).
*/
void
reserve(size_type __n)
{ _M_h.reserve(__n); }
template<typename _Value1, typename _Hash1, typename _Pred1,
typename _Alloc1>
friend bool
operator==(const unordered_set<_Value1, _Hash1, _Pred1, _Alloc1>&,
const unordered_set<_Value1, _Hash1, _Pred1, _Alloc1>&);
};
/**
* @brief A standard container composed of equivalent keys
* (possibly containing multiple of each key value) in which the
* elements' keys are the elements themselves.
*
* @ingroup unordered_associative_containers
*
* @tparam _Value Type of key objects.
* @tparam _Hash Hashing function object type, defaults to hash<_Value>.
* @tparam _Pred Predicate function object type, defaults
* to equal_to<_Value>.
* @tparam _Alloc Allocator type, defaults to allocator<_Key>.
*
* Meets the requirements of a <a href="tables.html#65">container</a>, and
* <a href="tables.html#xx">unordered associative container</a>
*
* Base is _Hashtable, dispatched at compile time via template
* alias __umset_hashtable.
*/
template<class _Value,
class _Hash = hash<_Value>,
class _Pred = std::equal_to<_Value>,
class _Alloc = std::allocator<_Value> >
class unordered_multiset : __check_copy_constructible<_Alloc>
{
typedef __umset_hashtable<_Value, _Hash, _Pred, _Alloc> _Hashtable;
_Hashtable _M_h;
public:
// typedefs:
//@{
/// Public typedefs.
typedef typename _Hashtable::key_type key_type;
typedef typename _Hashtable::value_type value_type;
typedef typename _Hashtable::hasher hasher;
typedef typename _Hashtable::key_equal key_equal;
typedef typename _Hashtable::allocator_type allocator_type;
//@}
//@{
/// Iterator-related typedefs.
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename _Hashtable::iterator iterator;
typedef typename _Hashtable::const_iterator const_iterator;
typedef typename _Hashtable::local_iterator local_iterator;
typedef typename _Hashtable::const_local_iterator const_local_iterator;
typedef typename _Hashtable::size_type size_type;
typedef typename _Hashtable::difference_type difference_type;
//@}
// construct/destroy/copy
/**
* @brief Default constructor creates no elements.
* @param __n Initial number of buckets.
* @param __hf A hash functor.
* @param __eql A key equality functor.
* @param __a An allocator object.
*/
explicit
unordered_multiset(size_type __n = 10,
const hasher& __hf = hasher(),
const key_equal& __eql = key_equal(),
const allocator_type& __a = allocator_type())
: _M_h(__n, __hf, __eql, __a)
{ }
/**
* @brief Builds an %unordered_multiset from a range.
* @param __first An input iterator.
* @param __last An input iterator.
* @param __n Minimal initial number of buckets.
* @param __hf A hash functor.
* @param __eql A key equality functor.
* @param __a An allocator object.
*
* Create an %unordered_multiset consisting of copies of the elements
* from [__first,__last). This is linear in N (where N is
* distance(__first,__last)).
*/
template<typename _InputIterator>
unordered_multiset(_InputIterator __f, _InputIterator __l,
size_type __n = 0,
const hasher& __hf = hasher(),
const key_equal& __eql = key_equal(),
const allocator_type& __a = allocator_type())
: _M_h(__f, __l, __n, __hf, __eql, __a)
{ }
/// Copy constructor.
unordered_multiset(const unordered_multiset&) = default;
/// Move constructor.
unordered_multiset(unordered_multiset&&) = default;
/**
* @brief Builds an %unordered_multiset from an initializer_list.
* @param __l An initializer_list.
* @param __n Minimal initial number of buckets.
* @param __hf A hash functor.
* @param __eql A key equality functor.
* @param __a An allocator object.
*
* Create an %unordered_multiset consisting of copies of the elements in
* the list. This is linear in N (where N is @a __l.size()).
*/
unordered_multiset(initializer_list<value_type> __l,
size_type __n = 0,
const hasher& __hf = hasher(),
const key_equal& __eql = key_equal(),
const allocator_type& __a = allocator_type())
: _M_h(__l, __n, __hf, __eql, __a)
{ }
/// Copy assignment operator.
unordered_multiset&
operator=(const unordered_multiset&) = default;
/// Move assignment operator.
unordered_multiset&
operator=(unordered_multiset&& __x) = default;
/**
* @brief %Unordered_multiset list assignment operator.
* @param __l An initializer_list.
*
* This function fills an %unordered_multiset with copies of the elements
* in the initializer list @a __l.
*
* Note that the assignment completely changes the %unordered_multiset
* and that the resulting %unordered_set's size is the same as the number
* of elements assigned. Old data may be lost.
*/
unordered_multiset&
operator=(initializer_list<value_type> __l)
{
_M_h = __l;
return *this;
}
/// Returns the allocator object with which the %unordered_multiset was
/// constructed.
allocator_type
get_allocator() const noexcept
{ return _M_h.get_allocator(); }
// size and capacity:
/// Returns true if the %unordered_multiset is empty.
bool
empty() const noexcept
{ return _M_h.empty(); }
/// Returns the size of the %unordered_multiset.
size_type
size() const noexcept
{ return _M_h.size(); }
/// Returns the maximum size of the %unordered_multiset.
size_type
max_size() const noexcept
{ return _M_h.max_size(); }
// iterators.
//@{
/**
* Returns a read-only (constant) iterator that points to the first
* element in the %unordered_multiset.
*/
iterator
begin() noexcept
{ return _M_h.begin(); }
const_iterator
begin() const noexcept
{ return _M_h.begin(); }
//@}
//@{
/**
* Returns a read-only (constant) iterator that points one past the last
* element in the %unordered_multiset.
*/
iterator
end() noexcept
{ return _M_h.end(); }
const_iterator
end() const noexcept
{ return _M_h.end(); }
//@}
/**
* Returns a read-only (constant) iterator that points to the first
* element in the %unordered_multiset.
*/
const_iterator
cbegin() const noexcept
{ return _M_h.begin(); }
/**
* Returns a read-only (constant) iterator that points one past the last
* element in the %unordered_multiset.
*/
const_iterator
cend() const noexcept
{ return _M_h.end(); }
// modifiers.
/**
* @brief Builds and insert an element into the %unordered_multiset.
* @param __args Arguments used to generate an element.
* @return An iterator that points to the inserted element.
*
* Insertion requires amortized constant time.
*/
template<typename... _Args>
iterator
emplace(_Args&&... __args)
{ return _M_h.emplace(std::forward<_Args>(__args)...); }
/**
* @brief Inserts an element into the %unordered_multiset.
* @param __pos An iterator that serves as a hint as to where the
* element should be inserted.
* @param __args Arguments used to generate the element to be
* inserted.
* @return An iterator that points to the inserted element.
*
* Note that the first parameter is only a hint and can potentially
* improve the performance of the insertion process. A bad hint would
* cause no gains in efficiency.
*
* For more on @a hinting, see:
* http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt07ch17.html
*
* Insertion requires amortized constant time.
*/
template<typename... _Args>
iterator
emplace_hint(const_iterator __pos, _Args&&... __args)
{ return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); }
//@{
/**
* @brief Inserts an element into the %unordered_multiset.
* @param __x Element to be inserted.
* @return An iterator that points to the inserted element.
*
* Insertion requires amortized constant time.
*/
iterator
insert(const value_type& __x)
{ return _M_h.insert(__x); }
iterator
insert(value_type&& __x)
{ return _M_h.insert(std::move(__x)); }
//@}
//@{
/**
* @brief Inserts an element into the %unordered_multiset.
* @param __hint An iterator that serves as a hint as to where the
* element should be inserted.
* @param __x Element to be inserted.
* @return An iterator that points to the inserted element.
*
* Note that the first parameter is only a hint and can potentially
* improve the performance of the insertion process. A bad hint would
* cause no gains in efficiency.
*
* For more on @a hinting, see:
* http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt07ch17.html
*
* Insertion requires amortized constant.
*/
iterator
insert(const_iterator __hint, const value_type& __x)
{ return _M_h.insert(__hint, __x); }
iterator
insert(const_iterator __hint, value_type&& __x)
{ return _M_h.insert(__hint, std::move(__x)); }
//@}
/**
* @brief A template function that inserts a range of elements.
* @param __first Iterator pointing to the start of the range to be
* inserted.
* @param __last Iterator pointing to the end of the range.
*
* Complexity similar to that of the range constructor.
*/
template<typename _InputIterator>
void
insert(_InputIterator __first, _InputIterator __last)
{ _M_h.insert(__first, __last); }
/**
* @brief Inserts a list of elements into the %unordered_multiset.
* @param __l A std::initializer_list<value_type> of elements to be
* inserted.
*
* Complexity similar to that of the range constructor.
*/
void
insert(initializer_list<value_type> __l)
{ _M_h.insert(__l); }
//@{
/**
* @brief Erases an element from an %unordered_multiset.
* @param __position An iterator pointing to the element to be erased.
* @return An iterator pointing to the element immediately following
* @a __position prior to the element being erased. If no such
* element exists, end() is returned.
*
* This function erases an element, pointed to by the given iterator,
* from an %unordered_multiset.
*
* Note that this function only erases the element, and that if the
* element is itself a pointer, the pointed-to memory is not touched in
* any way. Managing the pointer is the user's responsibility.
*/
iterator
erase(const_iterator __position)
{ return _M_h.erase(__position); }
// LWG 2059.
iterator
erase(iterator __it)
{ return _M_h.erase(__it); }
//@}
/**
* @brief Erases elements according to the provided key.
* @param __x Key of element to be erased.
* @return The number of elements erased.
*
* This function erases all the elements located by the given key from
* an %unordered_multiset.
*
* Note that this function only erases the element, and that if the
* element is itself a pointer, the pointed-to memory is not touched in
* any way. Managing the pointer is the user's responsibility.
*/
size_type
erase(const key_type& __x)
{ return _M_h.erase(__x); }
/**
* @brief Erases a [__first,__last) range of elements from an
* %unordered_multiset.
* @param __first Iterator pointing to the start of the range to be
* erased.
* @param __last Iterator pointing to the end of the range to
* be erased.
* @return The iterator @a __last.
*
* This function erases a sequence of elements from an
* %unordered_multiset.
*
* Note that this function only erases the element, and that if
* the element is itself a pointer, the pointed-to memory is not touched
* in any way. Managing the pointer is the user's responsibility.
*/
iterator
erase(const_iterator __first, const_iterator __last)
{ return _M_h.erase(__first, __last); }
/**
* Erases all elements in an %unordered_multiset.
*
* Note that this function only erases the elements, and that if the
* elements themselves are pointers, the pointed-to memory is not touched
* in any way. Managing the pointer is the user's responsibility.
*/
void
clear() noexcept
{ _M_h.clear(); }
/**
* @brief Swaps data with another %unordered_multiset.
* @param __x An %unordered_multiset of the same element and allocator
* types.
*
* This exchanges the elements between two sets in constant time.
* Note that the global std::swap() function is specialized such that
* std::swap(s1,s2) will feed to this function.
*/
void
swap(unordered_multiset& __x)
{ _M_h.swap(__x._M_h); }
// observers.
/// Returns the hash functor object with which the %unordered_multiset
/// was constructed.
hasher
hash_function() const
{ return _M_h.hash_function(); }
/// Returns the key comparison object with which the %unordered_multiset
/// was constructed.
key_equal
key_eq() const
{ return _M_h.key_eq(); }
// lookup.
//@{
/**
* @brief Tries to locate an element in an %unordered_multiset.
* @param __x Element to be located.
* @return Iterator pointing to sought-after element, or end() if not
* found.
*
* This function takes a key and tries to locate the element with which
* the key matches. If successful the function returns an iterator
* pointing to the sought after element. If unsuccessful it returns the
* past-the-end ( @c end() ) iterator.
*/
iterator
find(const key_type& __x)
{ return _M_h.find(__x); }
const_iterator
find(const key_type& __x) const
{ return _M_h.find(__x); }
//@}
/**
* @brief Finds the number of elements.
* @param __x Element to located.
* @return Number of elements with specified key.
*/
size_type
count(const key_type& __x) const
{ return _M_h.count(__x); }
//@{
/**
* @brief Finds a subsequence matching given key.
* @param __x Key to be located.
* @return Pair of iterators that possibly points to the subsequence
* matching given key.
*/
std::pair<iterator, iterator>
equal_range(const key_type& __x)
{ return _M_h.equal_range(__x); }
std::pair<const_iterator, const_iterator>
equal_range(const key_type& __x) const
{ return _M_h.equal_range(__x); }
//@}
// bucket interface.
/// Returns the number of buckets of the %unordered_multiset.
size_type
bucket_count() const noexcept
{ return _M_h.bucket_count(); }
/// Returns the maximum number of buckets of the %unordered_multiset.
size_type
max_bucket_count() const noexcept
{ return _M_h.max_bucket_count(); }
/*
* @brief Returns the number of elements in a given bucket.
* @param __n A bucket index.
* @return The number of elements in the bucket.
*/
size_type
bucket_size(size_type __n) const
{ return _M_h.bucket_size(__n); }
/*
* @brief Returns the bucket index of a given element.
* @param __key A key instance.
* @return The key bucket index.
*/
size_type
bucket(const key_type& __key) const
{ return _M_h.bucket(__key); }
//@{
/**
* @brief Returns a read-only (constant) iterator pointing to the first
* bucket element.
* @param __n The bucket index.
* @return A read-only local iterator.
*/
local_iterator
begin(size_type __n)
{ return _M_h.begin(__n); }
const_local_iterator
begin(size_type __n) const
{ return _M_h.begin(__n); }
const_local_iterator
cbegin(size_type __n) const
{ return _M_h.cbegin(__n); }
//@}
//@{
/**
* @brief Returns a read-only (constant) iterator pointing to one past
* the last bucket elements.
* @param __n The bucket index.
* @return A read-only local iterator.
*/
local_iterator
end(size_type __n)
{ return _M_h.end(__n); }
const_local_iterator
end(size_type __n) const
{ return _M_h.end(__n); }
const_local_iterator
cend(size_type __n) const
{ return _M_h.cend(__n); }
//@}
// hash policy.
/// Returns the average number of elements per bucket.
float
load_factor() const noexcept
{ return _M_h.load_factor(); }
/// Returns a positive number that the %unordered_multiset tries to keep the
/// load factor less than or equal to.
float
max_load_factor() const noexcept
{ return _M_h.max_load_factor(); }
/**
* @brief Change the %unordered_multiset maximum load factor.
* @param __z The new maximum load factor.
*/
void
max_load_factor(float __z)
{ _M_h.max_load_factor(__z); }
/**
* @brief May rehash the %unordered_multiset.
* @param __n The new number of buckets.
*
* Rehash will occur only if the new number of buckets respect the
* %unordered_multiset maximum load factor.
*/
void
rehash(size_type __n)
{ _M_h.rehash(__n); }
/**
* @brief Prepare the %unordered_multiset for a specified number of
* elements.
* @param __n Number of elements required.
*
* Same as rehash(ceil(n / max_load_factor())).
*/
void
reserve(size_type __n)
{ _M_h.reserve(__n); }
template<typename _Value1, typename _Hash1, typename _Pred1,
typename _Alloc1>
friend bool
operator==(const unordered_multiset<_Value1, _Hash1, _Pred1, _Alloc1>&,
const unordered_multiset<_Value1, _Hash1, _Pred1, _Alloc1>&);
};
template<class _Value, class _Hash, class _Pred, class _Alloc>
inline void
swap(unordered_set<_Value, _Hash, _Pred, _Alloc>& __x,
unordered_set<_Value, _Hash, _Pred, _Alloc>& __y)
{ __x.swap(__y); }
template<class _Value, class _Hash, class _Pred, class _Alloc>
inline void
swap(unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x,
unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y)
{ __x.swap(__y); }
template<class _Value, class _Hash, class _Pred, class _Alloc>
inline bool
operator==(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x,
const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y)
{ return __x._M_h._M_equal(__y._M_h); }
template<class _Value, class _Hash, class _Pred, class _Alloc>
inline bool
operator!=(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x,
const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y)
{ return !(__x == __y); }
template<class _Value, class _Hash, class _Pred, class _Alloc>
inline bool
operator==(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x,
const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y)
{ return __x._M_h._M_equal(__y._M_h); }
template<class _Value, class _Hash, class _Pred, class _Alloc>
inline bool
operator!=(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x,
const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y)
{ return !(__x == __y); }
_GLIBCXX_END_NAMESPACE_CONTAINER
} // namespace std
#endif /* _UNORDERED_SET_H */
| {
"pile_set_name": "Github"
} |
:local(.dropdownheader) {
padding-left: 10px;
padding-right: 10px;
padding-bottom: 5px;
margin-bottom: 5px;
font-weight: 600;
}
:local(.bottomSpacer) {
margin-bottom: 10px;
list-style: none;
}
:local(.topSpacer) {
margin-top: 10px;
}
| {
"pile_set_name": "Github"
} |
#ifndef __IRODS_NETWORK_OBJECT_HPP__
#define __IRODS_NETWORK_OBJECT_HPP__
// =-=-=-=-=-=-=-
#include "irods_first_class_object.hpp"
// =-=-=-=-=-=-=-
// irods includes
#include "rcConnect.h"
// =-=-=-=-=-=-=-
// boost includes
#include <boost/shared_ptr.hpp>
namespace irods {
// =-=-=-=-=-=-=-
// network object base class
class network_object : public first_class_object {
public:
// =-=-=-=-=-=-=-
// Constructors
network_object();
network_object( const rcComm_t& );
network_object( const rsComm_t& );
network_object( const network_object& );
// =-=-=-=-=-=-=-
// Destructors
virtual ~network_object();
// =-=-=-=-=-=-=-
// Operators
virtual network_object& operator=( const network_object& );
// =-=-=-=-=-=-=-
/// @brief Comparison operator
virtual bool operator==( const network_object& _rhs ) const;
// =-=-=-=-=-=-=-
// plugin resolution operation
virtual error resolve(
const std::string&, // plugin interface
plugin_ptr& ) = 0; // resolved plugin
// =-=-=-=-=-=-=-
// convertion to client comm ptr
virtual error to_client( rcComm_t* );
// =-=-=-=-=-=-=-
// convertion to client comm ptr
virtual error to_server( rsComm_t* );
// =-=-=-=-=-=-=-
// accessor for rule engine variables
virtual error get_re_vars( rule_engine_vars_t& );
// =-=-=-=-=-=-=-
// Accessors
virtual int socket_handle() const {
return socket_handle_;
}
// =-=-=-=-=-=-=-
// Mutators
virtual void socket_handle( int _s ) {
socket_handle_ = _s;
}
private:
// =-=-=-=-=-=-=-
// Attributes
int socket_handle_; // socket descriptor
}; // network_object
// =-=-=-=-=-=-=-
// helpful typedef for sock comm interface & factory
typedef boost::shared_ptr< network_object > network_object_ptr;
}; // namespace irods
#endif // __IRODS_NETWORK_OBJECT_HPP__
| {
"pile_set_name": "Github"
} |
/*
* YAFFS: Yet another FFS. A NAND-flash specific file system.
*
* Copyright (C) 2002-2011 Aleph One Ltd.
* for Toby Churchill Ltd and Brightstar Engineering
*
* Created by Timothy Manning <[email protected]>
*
* 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.
*/
#include "yaffsfs.h"
struct error_entry {
int code;
const char *text;
};
static const struct error_entry error_list[] = {
{ ENOMEM , "ENOMEM" },
{ EBUSY , "EBUSY"},
{ ENODEV , "ENODEV"},
{ EINVAL , "EINVAL"},
{ EBADF , "EBADF"},
{ EACCES , "EACCES"},
{ EXDEV , "EXDEV" },
{ ENOENT , "ENOENT"},
{ ENOSPC , "ENOSPC"},
{ ERANGE , "ERANGE"},
{ ENODATA, "ENODATA"},
{ ENOTEMPTY, "ENOTEMPTY"},
{ ENAMETOOLONG, "ENAMETOOLONG"},
{ ENOMEM , "ENOMEM"},
{ EEXIST , "EEXIST"},
{ ENOTDIR , "ENOTDIR"},
{ EISDIR , "EISDIR"},
{ ENFILE, "ENFILE"},
{ EROFS, "EROFS"},
{ EFAULT, "EFAULT"},
{ 0, NULL }
};
const char *yaffs_error_to_str(int err)
{
const struct error_entry *e = error_list;
if (err < 0)
err = -err;
while (e->code && e->text) {
if (err == e->code)
return e->text;
e++;
}
return "Unknown error code";
}
| {
"pile_set_name": "Github"
} |
# Sets up an HTTPS server that serves directory contents
# Generate a private key and certificate using openssl:
# openssl req -newkey rsa:2048 -nodes -keyout privkey.pem -x509 -days 36500 -out certificate.pem -subj "/C=US/ST=NRW/L=Earth/O=CompanyName/OU=IT/CN=www.example.com/[email protected]"
import sys
import ssl
listen_target = ('localhost', 4443)
certificate_file = './certificate.pem'
private_key_file = './privkey.pem'
# Python 3 version
if sys.version_info[0] == 3:
import http.server
httpd = http.server.HTTPServer(listen_target, http.server.SimpleHTTPRequestHandler)
# Python 2 version
elif sys.version_info[0] == 2:
import BaseHTTPServer, SimpleHTTPServer
httpd = BaseHTTPServer.HTTPServer(listen_target, SimpleHTTPServer.SimpleHTTPRequestHandler)
# Wrap the socket with SSL
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=certificate_file, keyfile=private_key_file, server_side=True)
# Start listening
httpd.serve_forever()
| {
"pile_set_name": "Github"
} |
/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2020 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address [email protected].
*
*/
#include <string>
#include <memory>
#include "modsecurity/actions/action.h"
#ifndef SRC_ACTIONS_SKIP_AFTER_H_
#define SRC_ACTIONS_SKIP_AFTER_H_
class Transaction;
namespace modsecurity {
class Transaction;
namespace actions {
class SkipAfter : public Action {
public:
explicit SkipAfter(const std::string &action)
: Action(action, RunTimeOnlyIfMatchKind),
m_skipName(std::make_shared<std::string>(m_parser_payload)) { }
bool evaluate(RuleWithActions *rule, Transaction *transaction) override;
private:
std::shared_ptr<std::string> m_skipName;
};
} // namespace actions
} // namespace modsecurity
#endif // SRC_ACTIONS_SKIP_AFTER_H_
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only -ast-dump=json %s | FileCheck %s
unsigned char implicitcast_0(unsigned int x) {
return x;
}
signed char implicitcast_1(unsigned int x) {
return x;
}
unsigned char implicitcast_2(signed int x) {
return x;
}
signed char implicitcast_3(signed int x) {
return x;
}
//----------------------------------------------------------------------------//
unsigned char cstylecast_0(unsigned int x) {
return (unsigned char)x;
}
signed char cstylecast_1(unsigned int x) {
return (signed char)x;
}
unsigned char cstylecast_2(signed int x) {
return (unsigned char)x;
}
signed char cstylecast_3(signed int x) {
return (signed char)x;
}
//----------------------------------------------------------------------------//
unsigned char cxxstaticcast_0(unsigned int x) {
return static_cast<unsigned char>(x);
}
signed char cxxstaticcast_1(unsigned int x) {
return static_cast<signed char>(x);
}
unsigned char cxxstaticcast_2(signed int x) {
return static_cast<unsigned char>(x);
}
signed char cxxstaticcast_3(signed int x) {
return static_cast<signed char>(x);
}
//----------------------------------------------------------------------------//
using UnsignedChar = unsigned char;
using SignedChar = signed char;
using UnsignedInt = unsigned int;
using SignedInt = signed int;
UnsignedChar cxxfunctionalcast_0(UnsignedInt x) {
return UnsignedChar(x);
}
SignedChar cxxfunctionalcast_1(UnsignedInt x) {
return SignedChar(x);
}
UnsignedChar cxxfunctionalcast_2(SignedInt x) {
return UnsignedChar(x);
}
SignedChar cxxfunctionalcast_3(SignedInt x) {
return SignedChar(x);
}
// NOTE: CHECK lines have been autogenerated by gen_ast_dump_json_test.py
// using --filters=ImplicitCastExpr,CStyleCastExpr,CXXStaticCastExpr,CXXFunctionalCastExpr
// CHECK: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 148,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 148,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 148,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 148,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 148,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 148,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 208,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 208,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 208,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 208,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 208,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 208,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 268,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 268,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 268,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 268,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 268,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 268,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 326,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 326,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 326,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 326,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 326,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 326,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CStyleCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 468,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 483,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 483,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 483,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 483,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 483,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 483,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 483,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CStyleCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 541,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 554,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 554,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 554,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 554,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 554,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 554,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 554,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CStyleCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 612,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 627,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 627,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 627,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 627,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 627,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 627,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 627,
// CHECK-NEXT: "col": 25,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CStyleCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 683,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 696,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 696,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 696,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 696,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 696,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 696,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 696,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CXXStaticCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 841,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 11
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 869,
// CHECK-NEXT: "col": 38,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 868,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 868,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 868,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 868,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 868,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 868,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CXXStaticCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 930,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 11
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 956,
// CHECK-NEXT: "col": 36,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 955,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 955,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 955,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 955,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 955,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 955,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CXXStaticCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1017,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 11
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1045,
// CHECK-NEXT: "col": 38,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1044,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1044,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "unsigned char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1044,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1044,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1044,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1044,
// CHECK-NEXT: "col": 37,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CXXStaticCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1104,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 11
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1130,
// CHECK-NEXT: "col": 36,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1129,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1129,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "signed char"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1129,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1129,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1129,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1129,
// CHECK-NEXT: "col": 35,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "qualType": "int"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CXXFunctionalCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1410,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 12
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1424,
// CHECK-NEXT: "col": 24,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned char",
// CHECK-NEXT: "qualType": "UnsignedChar",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1423,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1423,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned char",
// CHECK-NEXT: "qualType": "UnsignedChar",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1423,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1423,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned int",
// CHECK-NEXT: "qualType": "UnsignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1423,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1423,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned int",
// CHECK-NEXT: "qualType": "UnsignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned int",
// CHECK-NEXT: "qualType": "UnsignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CXXFunctionalCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1487,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 10
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1499,
// CHECK-NEXT: "col": 22,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "signed char",
// CHECK-NEXT: "qualType": "SignedChar",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1498,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1498,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "signed char",
// CHECK-NEXT: "qualType": "SignedChar",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1498,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1498,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned int",
// CHECK-NEXT: "qualType": "UnsignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1498,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1498,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned int",
// CHECK-NEXT: "qualType": "UnsignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned int",
// CHECK-NEXT: "qualType": "UnsignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CXXFunctionalCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1562,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 12
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1576,
// CHECK-NEXT: "col": 24,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned char",
// CHECK-NEXT: "qualType": "UnsignedChar",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1575,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1575,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "unsigned char",
// CHECK-NEXT: "qualType": "UnsignedChar",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1575,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1575,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "int",
// CHECK-NEXT: "qualType": "SignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1575,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1575,
// CHECK-NEXT: "col": 23,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "int",
// CHECK-NEXT: "qualType": "SignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "int",
// CHECK-NEXT: "qualType": "SignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK: "kind": "CXXFunctionalCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1637,
// CHECK-NEXT: "col": 10,
// CHECK-NEXT: "tokLen": 10
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1649,
// CHECK-NEXT: "col": 22,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "signed char",
// CHECK-NEXT: "qualType": "SignedChar",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "NoOp",
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1648,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1648,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "signed char",
// CHECK-NEXT: "qualType": "SignedChar",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "IntegralCast",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ImplicitCastExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1648,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1648,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "int",
// CHECK-NEXT: "qualType": "SignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "rvalue",
// CHECK-NEXT: "castKind": "LValueToRValue",
// CHECK-NEXT: "isPartOfExplicitCast": true,
// CHECK-NEXT: "inner": [
// CHECK-NEXT: {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "DeclRefExpr",
// CHECK-NEXT: "range": {
// CHECK-NEXT: "begin": {
// CHECK-NEXT: "offset": 1648,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: },
// CHECK-NEXT: "end": {
// CHECK-NEXT: "offset": 1648,
// CHECK-NEXT: "col": 21,
// CHECK-NEXT: "tokLen": 1
// CHECK-NEXT: }
// CHECK-NEXT: },
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "int",
// CHECK-NEXT: "qualType": "SignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: },
// CHECK-NEXT: "valueCategory": "lvalue",
// CHECK-NEXT: "referencedDecl": {
// CHECK-NEXT: "id": "0x{{.*}}",
// CHECK-NEXT: "kind": "ParmVarDecl",
// CHECK-NEXT: "name": "x",
// CHECK-NEXT: "type": {
// CHECK-NEXT: "desugaredQualType": "int",
// CHECK-NEXT: "qualType": "SignedInt",
// CHECK-NEXT: "typeAliasDeclId": "0x{{.*}}"
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
| {
"pile_set_name": "Github"
} |
% -*- Mode: LaTeX -*-
\newcounter{testpart}
\newcounter{testchapter}
\typeout{Enter "y" or "n" followed by <return> for all questions.}
\def\querypart#1{Do you want to format all or some of Part \thetestpart: #1 ?}
\def\querychapter#1{Do you want to format Chapter \thetestchapter: #1 ?}
\setcounter{testpart}{1}
\setcounter{testchapter}{1}
\typein [\doOverviewAndConventions] {\querypart{Overview and Conventions}
It includes Overview, Conventions.}
\if\doOverviewAndConventions y
\typein [\doOverview] {\querychapter{Overview}}
\addtocounter{testchapter}{1}
\typein [\doConventions] {\querychapter{Conventions}}
\addtocounter{testchapter}{1}
\else
\addtocounter{testchapter}{2}
\fi
\addtocounter{testpart}{1}
\typein [\doGeometrySubstrate] {\querypart{Geometry Substrate}
It includes Geometry, Bounding Rectangles, Transformations.}
\if\doGeometrySubstrate y
\typein [\doGeometry] {\querychapter{Geometry}}
\addtocounter{testchapter}{1}
\typein [\doBoundRect] {\querychapter{Bounding Rectangles}}
\addtocounter{testchapter}{1}
\typein [\doTransformations] {\querychapter{Transformations}}
\addtocounter{testchapter}{1}
\else
\addtocounter{testchapter}{3}
\fi
\addtocounter{testpart}{1}
\typein [\doWindowingSubstrate] {\querypart{Windowing Substrate}}
\addtocounter{testchapter}{5}
\addtocounter{testpart}{1}
\typein [\doBasicOutputFacilities] {\querypart{Basic Output Facilities}
It includes Drawing Options, Text Styles, Graphics, Drawing in Color, Patterned Designs.}
\if\doBasicOutputFacilities y
\typein [\doDrawingOptions] {\querychapter{Drawing Options}}
\addtocounter{testchapter}{1}
\typein [\doTextStyles] {\querychapter{Text Styles}}
\addtocounter{testchapter}{1}
\typein [\doGraphics] {\querychapter{Graphics}}
\addtocounter{testchapter}{1}
\typein [\doColor] {\querychapter{Drawing in Color}}
\addtocounter{testchapter}{1}
\typein [\doPatterns] {\querychapter{Patterned Designs}}
\addtocounter{testchapter}{1}
\else
\addtocounter{testchapter}{5}
\fi
\addtocounter{testpart}{1}
\typein [\doBasicInputFacilities] {\querypart{Basic Input Facilities}}
\addtocounter{testchapter}{1}
\addtocounter{testpart}{1}
\typein [\doBasicCharacterStreams] {\querypart{Basic Character Streams}}
\addtocounter{testchapter}{1}
\addtocounter{testpart}{1}
\typein [\doExtendedOutputFacilities] {\querypart{Extended Output Facilities}
It includes Extended Output, Output Recording, Table Formatting, Graph Formatting,
Bordered Output, Incremental Redisplay.}
\if\doExtendedOutputFacilities y
\typein [\doExtendedOutput] {\querychapter{Extended Output}}
\addtocounter{testchapter}{1}
\typein [\doOutputRecording] {\querychapter{Output Recording}}
\addtocounter{testchapter}{1}
\typein [\doTableFormatting] {\querychapter{Table Formatting}}
\addtocounter{testchapter}{1}
\typein [\doGraphFormatting] {\querychapter{Graph Formatting}}
\addtocounter{testchapter}{1}
\typein [\doBorderedOutput] {\querychapter{Bordered Output}}
\addtocounter{testchapter}{1}
\typein [\doIncrementalRedisplay] {\querychapter{Incremental Redisplay}}
\addtocounter{testchapter}{1}
\else
\addtocounter{testchapter}{6}
\fi
\addtocounter{testpart}{1}
\typein [\doExtendedInputFacilities] {\querypart{Extended Input Facilities}
It includes Extended Input, Presentation Types, Input Editing, Menus, Dialogs.}
\if\doExtendedInputFacilities y
\typein [\doExtendedInput] {\querychapter{Extended Input}}
\addtocounter{testchapter}{1}
\typein [\doPresentationTypes] {\querychapter{Presentation Types}}
\addtocounter{testchapter}{1}
\typein [\doInputEditing] {\querychapter{Input Editing}}
\addtocounter{testchapter}{1}
\typein [\doMenus] {\querychapter{Menus}}
\addtocounter{testchapter}{1}
\typein [\doDialogs] {\querychapter{Dialogs}}
\addtocounter{testchapter}{1}
\else
\addtocounter{testchapter}{5}
\fi
\addtocounter{testpart}{1}
\typein [\doBuildingApplications] {\querypart{Building Applications}
It includes Command Processor, Frames, Panes, Using the Host Toolkit.}
\if\doBuildingApplications y
\typein [\doCommandProcessor] {\querychapter{Command Processor}}
\addtocounter{testchapter}{1}
\typein [\doFrames] {\querychapter{Frames}}
\addtocounter{testchapter}{1}
\typein [\doPanes] {\querychapter{Panes}}
\addtocounter{testchapter}{1}
\typein [\doHostToolkit] {\querychapter{Using the Host Toolkit}}
\addtocounter{testchapter}{1}
\else
\addtocounter{testchapter}{4}
\fi
\def\blankpart#1{\addtocounter{part}{1} \typeout{Part \arabic{part} ``#1'' skipped.}}
\def\blankchapter#1{\addtocounter{chapter}{1} \typeout{ Chapter \arabic{chapter} ``#1'' skipped.}}
\documentstyle{report}
\pagestyle{headings}
\title{Common Lisp Interface Manager \\
Release 1 Specification}
\author{Working Draft \\
\\
Ramana Rao ([email protected]) \\
Bill York ([email protected]) \\
John Aspinall ([email protected]) \\
Scott McKay ([email protected]) \\
Dave Moon ([email protected]) \\
\\
{\bf **Draft -- Do not distribute**}}
\date{\today}
\markright{CLIM Specification -- **Do not distribute**}
\input psfig+
\include{spec-macros}
\addtolength{\oddsidemargin}{-.5in}
\addtolength{\evensidemargin}{-.5in}
\addtolength{\textwidth}{1in}
\addtolength{\topmargin}{-.5in}
\addtolength{\textheight}{1.0in}
\begin{document}
\maketitle
\parindent 0pc
\parskip 1pc
\pagebreak
\tableofcontents
\if\doOverviewAndConventions y
\part{Overview and Conventions}
\if\doOverview y \input{overview.tex} \else \blankchapter{Overview} \fi
\if\doConventions y \input{conventions.tex} \else \blankchapter{Conventions} \fi
\else
\blankpart{Overview and Conventions}
\addtocounter{chapter}{2}
\fi
\if\doGeometrySubstrate y
\part{Geometry Substrate}
\if\doGeometry y \input{geometry.tex} \else \blankchapter{Geometry} \fi
\if\doBoundRect y \input{bounding-rectangles.tex} \else \blankchapter{Bounding Rectangles} \fi
\if\doTransformations y \input{transformations.tex} \else \blankchapter{Transformations} \fi
\else
\blankpart{Geometry Substrate}
\addtocounter{chapter}{3}
\fi
\if\doWindowingSubstrate y
\part{Windowing Substrate}
\input{silica.tex}
\else
\blankpart{Windowing Substrate}
\addtocounter{chapter}{5}
\fi
\if\doBasicOutputFacilities y
\part{Basic Output Facilities}
\if\doDrawingOptions y \input{drawing-options.tex} \else \blankchapter{Drawing Options} \fi
\if\doTextStyles y \input{text-styles.tex} \else \blankchapter{Text Styles} \fi
\if\doGraphics y \input{graphics.tex} \else \blankchapter{Graphics} \fi
\if\doColor y \input{color.tex} \else \blankchapter{Drawing in Color} \fi
\if\doPatterns y \input{patterns.tex} \else \blankchapter{Patterned Designs} \fi
\else
\blankpart{Basic Output Facilities}
\addtocounter{chapter}{5}
\fi
\if\doBasicInputFacilities y
\part{Basic Input Facilities}
\input{input.tex}
\else
\blankpart{Basic Input Facilities}
\addtocounter{chapter}{1}
\fi
\if\doBasicCharacterStreams y
\part{Basic Character Streams}
\input{gray-streams.tex}
\else
\blankpart{Basic Character Streams}
\addtocounter{chapter}{1}
\fi
\if\doExtendedOutputFacilities y
\part{Extended Output Facilities}
\if\doExtendedOutput y \input{extended-output.tex} \else \blankchapter{Extended Output} \fi
\if\doOutputRecording y \input{output-recording.tex} \else \blankchapter{Output Recording} \fi
\if\doTableFormatting y \input{table-formatting.tex} \else \blankchapter{Table Formatting} \fi
\if\doGraphFormatting y \input{graph-formatting.tex} \else \blankchapter{Graph Formatting} \fi
\if\doBorderedOutput y \input{bordered-output.tex} \else \blankchapter{Bordered Output} \fi
\if\doIncrementalRedisplay y \input{incremental-redisplay.tex} \else \blankchapter{Incremental Redisplay} \fi
\else
\blankpart{Extended Output Facilities}
\addtocounter{chapter}{6}
\fi
\if\doExtendedInputFacilities y
\part{Extended Input Facilities}
\if\doExtendedInput y \input{extended-input.tex} \else \blankchapter{Extended Input} \fi
\if\doPresentationTypes y \input{presentation-types.tex} \else \blankchapter{Presentation Types} \fi
\if\doInputEditing y \input{input-editing.tex} \else \blankchapter{Input Editing} \fi
\if\doMenus y \input{menus.tex} \else \blankchapter{Menus} \fi
\if\doDialogs y \input{dialogs.tex} \else \blankchapter{Dialogs} \fi
\else
\blankpart{Extended Input Facilities}
\addtocounter{chapter}{5}
\fi
\if\doBuildingApplications y
\part{Building Applications}
\if\doCommandProcessor y \input{command-processor.tex} \else \blankchapter{Command Processor} \fi
\if\doFrames y \input{frame.tex} \else \blankchapter{Frames} \fi
\if\doPanes y \input{panes.tex} \else \blankchapter{Panes} \fi
\if\doHostToolkit y \input{host-tk.tex} \else \blankchapter{Using the Host Toolkit} \fi
\else
\blankpart{Building Applications}
\addtocounter{chapter}{4}
\fi
\end{document}
| {
"pile_set_name": "Github"
} |
import sys
import pytest
from hypothesis import strategies as st
from hypothesis import given, settings, example
from unicodedata import normalize
# For every (n1, n2, n3) triple, applying n1 then n2 must be the same
# as applying n3.
# Reference: http://unicode.org/reports/tr15/#Design_Goals
compositions = [
('NFC', 'NFC', 'NFC'),
('NFC', 'NFD', 'NFD'),
('NFC', 'NFKC', 'NFKC'),
('NFC', 'NFKD', 'NFKD'),
('NFD', 'NFC', 'NFC'),
('NFD', 'NFD', 'NFD'),
('NFD', 'NFKC', 'NFKC'),
('NFD', 'NFKD', 'NFKD'),
('NFKC', 'NFC', 'NFKC'),
('NFKC', 'NFD', 'NFKD'),
('NFKC', 'NFKC', 'NFKC'),
('NFKC', 'NFKD', 'NFKD'),
('NFKD', 'NFC', 'NFKC'),
('NFKD', 'NFD', 'NFKD'),
('NFKD', 'NFKC', 'NFKC'),
('NFKD', 'NFKD', 'NFKD'),
]
@pytest.mark.parametrize('norm1, norm2, norm3', compositions)
@settings(max_examples=1000)
@example(s=u'---\uafb8\u11a7---') # issue 2289
@given(s=st.text())
def test_composition(s, norm1, norm2, norm3):
assert normalize(norm2, normalize(norm1, s)) == normalize(norm3, s)
@given(st.text(), st.text(), st.text())
def test_find(u, prefix, suffix):
s = prefix + u + suffix
assert 0 <= s.find(u) <= len(prefix)
assert s.find(u, len(prefix), len(s) - len(suffix)) == len(prefix)
@given(st.text(), st.text(), st.text())
def test_index(u, prefix, suffix):
s = prefix + u + suffix
assert 0 <= s.index(u) <= len(prefix)
assert s.index(u, len(prefix), len(s) - len(suffix)) == len(prefix)
@given(st.text(), st.text(), st.text())
def test_rfind(u, prefix, suffix):
s = prefix + u + suffix
assert s.rfind(u) >= len(prefix)
assert s.rfind(u, len(prefix), len(s) - len(suffix)) == len(prefix)
@given(st.text(), st.text(), st.text())
def test_rindex(u, prefix, suffix):
s = prefix + u + suffix
assert s.rindex(u) >= len(prefix)
assert s.rindex(u, len(prefix), len(s) - len(suffix)) == len(prefix)
def adjust_indices(u, start, end):
if end < 0:
end = max(end + len(u), 0)
else:
end = min(end, len(u))
if start < 0:
start = max(start + len(u), 0)
return start, end
@given(st.text(), st.text())
def test_startswith_basic(u, v):
assert u.startswith(v) is (u[:len(v)] == v)
@example(u'x', u'', 1)
@example(u'x', u'', 2)
@given(st.text(), st.text(), st.integers())
def test_startswith_2(u, v, start):
if v or sys.version_info[0] == 2:
expected = u[start:].startswith(v)
else: # CPython leaks implementation details in this case
expected = start <= len(u)
assert u.startswith(v, start) is expected
@example(u'x', u'', 1, 0)
@example(u'xx', u'', -1, 0)
@given(st.text(), st.text(), st.integers(), st.integers())
def test_startswith_3(u, v, start, end):
if v or sys.version_info[0] == 2:
expected = u[start:end].startswith(v)
else: # CPython leaks implementation details in this case
start0, end0 = adjust_indices(u, start, end)
expected = start0 <= len(u) and start0 <= end0
assert u.startswith(v, start, end) is expected
@given(st.text(), st.text())
def test_endswith_basic(u, v):
if len(v) > len(u):
assert u.endswith(v) is False
else:
assert u.endswith(v) is (u[len(u) - len(v):] == v)
@example(u'x', u'', 1)
@example(u'x', u'', 2)
@given(st.text(), st.text(), st.integers())
def test_endswith_2(u, v, start):
if v or sys.version_info[0] == 2:
expected = u[start:].endswith(v)
else: # CPython leaks implementation details in this case
expected = start <= len(u)
assert u.endswith(v, start) is expected
@example(u'x', u'', 1, 0)
@example(u'xx', u'', -1, 0)
@given(st.text(), st.text(), st.integers(), st.integers())
def test_endswith_3(u, v, start, end):
if v or sys.version_info[0] == 2:
expected = u[start:end].endswith(v)
else: # CPython leaks implementation details in this case
start0, end0 = adjust_indices(u, start, end)
expected = start0 <= len(u) and start0 <= end0
assert u.endswith(v, start, end) is expected
| {
"pile_set_name": "Github"
} |
{
"name": "simple-line-icons",
"version": "2.4.1",
"authors": [
"Sabbir Ahmed <[email protected]>"
],
"description": "Simple Line Icons Bower Package",
"keywords": [
"fonts",
"simple",
"simple-line",
"icon"
],
"main": [
"css/simple-line-icons.css",
"scss/simple-line-icons.scss",
"less/simple-line-icons.less"
],
"license": "MIT",
"homepage": "https://github.com/thesabbir/simple-line-icons",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}
| {
"pile_set_name": "Github"
} |
{$, $$, View, TextEditorView} = require 'atom-space-pen-views'
{CompositeDisposable} = require 'atom'
module.exports =
class Dialog extends View
@content: ({prompt} = {}) ->
@div class: 'dialog', =>
@label prompt, class: 'icon', outlet: 'promptText'
@subview 'miniEditor', new TextEditorView(mini: true)
@div class: 'error-message', outlet: 'errorMessage'
initialize: ({iconClass} = {}) ->
@promptText.addClass(iconClass) if iconClass
@disposables = new CompositeDisposable
@disposables.add atom.commands.add 'atom-workspace',
'core:confirm': => @onConfirm(@miniEditor.getText())
'core:cancel': (event) =>
@cancel()
event.stopPropagation()
@miniEditor.getModel().onDidChange => @showError()
@miniEditor.on 'blur', => @cancel()
onConfirm: (value) ->
@callback?(undefined, value)
@cancel()
value
showError: (message='') ->
@errorMessage.text(message)
@flashError() if message
destroy: ->
@disposables.dispose()
cancel: ->
@cancelled()
@restoreFocus()
@destroy()
cancelled: ->
@hide()
toggle: (@callback) ->
if @panel?.isVisible()
@cancel()
else
@show()
show: () ->
@panel ?= atom.workspace.addModalPanel(item: this)
@panel.show()
@storeFocusedElement()
@miniEditor.focus()
hide: ->
@panel?.hide()
storeFocusedElement: ->
@previouslyFocusedElement = $(document.activeElement)
restoreFocus: ->
@previouslyFocusedElement?.focus()
| {
"pile_set_name": "Github"
} |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd netbsd openbsd
// BSD system call wrappers shared by *BSD based systems
// including OS X (Darwin) and FreeBSD. Like the other
// syscall_*.go files it is compiled as Go code but also
// used as input to mksyscall which parses the //sys
// lines and generates system call stubs.
package unix
import (
"runtime"
"syscall"
"unsafe"
)
/*
* Wrapped
*/
//sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error)
//sysnb setgroups(ngid int, gid *_Gid_t) (err error)
func Getgroups() (gids []int, err error) {
n, err := getgroups(0, nil)
if err != nil {
return nil, err
}
if n == 0 {
return nil, nil
}
// Sanity check group count. Max is 16 on BSD.
if n < 0 || n > 1000 {
return nil, EINVAL
}
a := make([]_Gid_t, n)
n, err = getgroups(n, &a[0])
if err != nil {
return nil, err
}
gids = make([]int, n)
for i, v := range a[0:n] {
gids[i] = int(v)
}
return
}
func Setgroups(gids []int) (err error) {
if len(gids) == 0 {
return setgroups(0, nil)
}
a := make([]_Gid_t, len(gids))
for i, v := range gids {
a[i] = _Gid_t(v)
}
return setgroups(len(a), &a[0])
}
func ReadDirent(fd int, buf []byte) (n int, err error) {
// Final argument is (basep *uintptr) and the syscall doesn't take nil.
// 64 bits should be enough. (32 bits isn't even on 386). Since the
// actual system call is getdirentries64, 64 is a good guess.
// TODO(rsc): Can we use a single global basep for all calls?
var base = (*uintptr)(unsafe.Pointer(new(uint64)))
return Getdirentries(fd, buf, base)
}
// Wait status is 7 bits at bottom, either 0 (exited),
// 0x7F (stopped), or a signal number that caused an exit.
// The 0x80 bit is whether there was a core dump.
// An extra number (exit code, signal causing a stop)
// is in the high bits.
type WaitStatus uint32
const (
mask = 0x7F
core = 0x80
shift = 8
exited = 0
stopped = 0x7F
)
func (w WaitStatus) Exited() bool { return w&mask == exited }
func (w WaitStatus) ExitStatus() int {
if w&mask != exited {
return -1
}
return int(w >> shift)
}
func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 }
func (w WaitStatus) Signal() syscall.Signal {
sig := syscall.Signal(w & mask)
if sig == stopped || sig == 0 {
return -1
}
return sig
}
func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP }
func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP }
func (w WaitStatus) StopSignal() syscall.Signal {
if !w.Stopped() {
return -1
}
return syscall.Signal(w>>shift) & 0xFF
}
func (w WaitStatus) TrapCause() int { return -1 }
//sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
var status _C_int
wpid, err = wait4(pid, &status, options, rusage)
if wstatus != nil {
*wstatus = WaitStatus(status)
}
return
}
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys Shutdown(s int, how int) (err error)
func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, EINVAL
}
sa.raw.Len = SizeofSockaddrInet4
sa.raw.Family = AF_INET
p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Addr[i] = sa.Addr[i]
}
return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
}
func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, EINVAL
}
sa.raw.Len = SizeofSockaddrInet6
sa.raw.Family = AF_INET6
p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
sa.raw.Scope_id = sa.ZoneId
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Addr[i] = sa.Addr[i]
}
return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
}
func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
name := sa.Name
n := len(name)
if n >= len(sa.raw.Path) || n == 0 {
return nil, 0, EINVAL
}
sa.raw.Len = byte(3 + n) // 2 for Family, Len; 1 for NUL
sa.raw.Family = AF_UNIX
for i := 0; i < n; i++ {
sa.raw.Path[i] = int8(name[i])
}
return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
}
func (sa *SockaddrDatalink) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Index == 0 {
return nil, 0, EINVAL
}
sa.raw.Len = sa.Len
sa.raw.Family = AF_LINK
sa.raw.Index = sa.Index
sa.raw.Type = sa.Type
sa.raw.Nlen = sa.Nlen
sa.raw.Alen = sa.Alen
sa.raw.Slen = sa.Slen
for i := 0; i < len(sa.raw.Data); i++ {
sa.raw.Data[i] = sa.Data[i]
}
return unsafe.Pointer(&sa.raw), SizeofSockaddrDatalink, nil
}
func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
switch rsa.Addr.Family {
case AF_LINK:
pp := (*RawSockaddrDatalink)(unsafe.Pointer(rsa))
sa := new(SockaddrDatalink)
sa.Len = pp.Len
sa.Family = pp.Family
sa.Index = pp.Index
sa.Type = pp.Type
sa.Nlen = pp.Nlen
sa.Alen = pp.Alen
sa.Slen = pp.Slen
for i := 0; i < len(sa.Data); i++ {
sa.Data[i] = pp.Data[i]
}
return sa, nil
case AF_UNIX:
pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
if pp.Len < 2 || pp.Len > SizeofSockaddrUnix {
return nil, EINVAL
}
sa := new(SockaddrUnix)
// Some BSDs include the trailing NUL in the length, whereas
// others do not. Work around this by subtracting the leading
// family and len. The path is then scanned to see if a NUL
// terminator still exists within the length.
n := int(pp.Len) - 2 // subtract leading Family, Len
for i := 0; i < n; i++ {
if pp.Path[i] == 0 {
// found early NUL; assume Len included the NUL
// or was overestimating.
n = i
break
}
}
bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
sa.Name = string(bytes)
return sa, nil
case AF_INET:
pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
sa := new(SockaddrInet4)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
case AF_INET6:
pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
sa := new(SockaddrInet6)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
sa.ZoneId = pp.Scope_id
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
}
return nil, EAFNOSUPPORT
}
func Accept(fd int) (nfd int, sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
nfd, err = accept(fd, &rsa, &len)
if err != nil {
return
}
if runtime.GOOS == "darwin" && len == 0 {
// Accepted socket has no address.
// This is likely due to a bug in xnu kernels,
// where instead of ECONNABORTED error socket
// is accepted, but has no address.
Close(nfd)
return 0, nil, ECONNABORTED
}
sa, err = anyToSockaddr(&rsa)
if err != nil {
Close(nfd)
nfd = 0
}
return
}
func Getsockname(fd int) (sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
if err = getsockname(fd, &rsa, &len); err != nil {
return
}
// TODO(jsing): DragonFly has a "bug" (see issue 3349), which should be
// reported upstream.
if runtime.GOOS == "dragonfly" && rsa.Addr.Family == AF_UNSPEC && rsa.Addr.Len == 0 {
rsa.Addr.Family = AF_UNIX
rsa.Addr.Len = SizeofSockaddrUnix
}
return anyToSockaddr(&rsa)
}
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
// GetsockoptString returns the string value of the socket option opt for the
// socket associated with fd at the given socket level.
func GetsockoptString(fd, level, opt int) (string, error) {
buf := make([]byte, 256)
vallen := _Socklen(len(buf))
err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
if err != nil {
return "", err
}
return string(buf[:vallen-1]), nil
}
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
var msg Msghdr
var rsa RawSockaddrAny
msg.Name = (*byte)(unsafe.Pointer(&rsa))
msg.Namelen = uint32(SizeofSockaddrAny)
var iov Iovec
if len(p) > 0 {
iov.Base = (*byte)(unsafe.Pointer(&p[0]))
iov.SetLen(len(p))
}
var dummy byte
if len(oob) > 0 {
// receive at least one normal byte
if len(p) == 0 {
iov.Base = &dummy
iov.SetLen(1)
}
msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
msg.SetControllen(len(oob))
}
msg.Iov = &iov
msg.Iovlen = 1
if n, err = recvmsg(fd, &msg, flags); err != nil {
return
}
oobn = int(msg.Controllen)
recvflags = int(msg.Flags)
// source address is only specified if the socket is unconnected
if rsa.Addr.Family != AF_UNSPEC {
from, err = anyToSockaddr(&rsa)
}
return
}
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
_, err = SendmsgN(fd, p, oob, to, flags)
return
}
func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
var ptr unsafe.Pointer
var salen _Socklen
if to != nil {
ptr, salen, err = to.sockaddr()
if err != nil {
return 0, err
}
}
var msg Msghdr
msg.Name = (*byte)(unsafe.Pointer(ptr))
msg.Namelen = uint32(salen)
var iov Iovec
if len(p) > 0 {
iov.Base = (*byte)(unsafe.Pointer(&p[0]))
iov.SetLen(len(p))
}
var dummy byte
if len(oob) > 0 {
// send at least one normal byte
if len(p) == 0 {
iov.Base = &dummy
iov.SetLen(1)
}
msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
msg.SetControllen(len(oob))
}
msg.Iov = &iov
msg.Iovlen = 1
if n, err = sendmsg(fd, &msg, flags); err != nil {
return 0, err
}
if len(oob) > 0 && len(p) == 0 {
n = 0
}
return n, nil
}
//sys kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error)
func Kevent(kq int, changes, events []Kevent_t, timeout *Timespec) (n int, err error) {
var change, event unsafe.Pointer
if len(changes) > 0 {
change = unsafe.Pointer(&changes[0])
}
if len(events) > 0 {
event = unsafe.Pointer(&events[0])
}
return kevent(kq, change, len(changes), event, len(events), timeout)
}
//sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL
// sysctlmib translates name to mib number and appends any additional args.
func sysctlmib(name string, args ...int) ([]_C_int, error) {
// Translate name to mib number.
mib, err := nametomib(name)
if err != nil {
return nil, err
}
for _, a := range args {
mib = append(mib, _C_int(a))
}
return mib, nil
}
func Sysctl(name string) (string, error) {
return SysctlArgs(name)
}
func SysctlArgs(name string, args ...int) (string, error) {
buf, err := SysctlRaw(name, args...)
if err != nil {
return "", err
}
n := len(buf)
// Throw away terminating NUL.
if n > 0 && buf[n-1] == '\x00' {
n--
}
return string(buf[0:n]), nil
}
func SysctlUint32(name string) (uint32, error) {
return SysctlUint32Args(name)
}
func SysctlUint32Args(name string, args ...int) (uint32, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return 0, err
}
n := uintptr(4)
buf := make([]byte, 4)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return 0, err
}
if n != 4 {
return 0, EIO
}
return *(*uint32)(unsafe.Pointer(&buf[0])), nil
}
func SysctlUint64(name string, args ...int) (uint64, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return 0, err
}
n := uintptr(8)
buf := make([]byte, 8)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return 0, err
}
if n != 8 {
return 0, EIO
}
return *(*uint64)(unsafe.Pointer(&buf[0])), nil
}
func SysctlRaw(name string, args ...int) ([]byte, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return nil, err
}
// Find size.
n := uintptr(0)
if err := sysctl(mib, nil, &n, nil, 0); err != nil {
return nil, err
}
if n == 0 {
return nil, nil
}
// Read into buffer of that size.
buf := make([]byte, n)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return nil, err
}
// The actual call may return less than the original reported required
// size so ensure we deal with that.
return buf[:n], nil
}
//sys utimes(path string, timeval *[2]Timeval) (err error)
func Utimes(path string, tv []Timeval) error {
if tv == nil {
return utimes(path, nil)
}
if len(tv) != 2 {
return EINVAL
}
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
func UtimesNano(path string, ts []Timespec) error {
if ts == nil {
err := utimensat(AT_FDCWD, path, nil, 0)
if err != ENOSYS {
return err
}
return utimes(path, nil)
}
if len(ts) != 2 {
return EINVAL
}
// Darwin setattrlist can set nanosecond timestamps
err := setattrlistTimes(path, ts, 0)
if err != ENOSYS {
return err
}
err = utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
if err != ENOSYS {
return err
}
// Not as efficient as it could be because Timespec and
// Timeval have different types in the different OSes
tv := [2]Timeval{
NsecToTimeval(TimespecToNsec(ts[0])),
NsecToTimeval(TimespecToNsec(ts[1])),
}
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
if ts == nil {
return utimensat(dirfd, path, nil, flags)
}
if len(ts) != 2 {
return EINVAL
}
err := setattrlistTimes(path, ts, flags)
if err != ENOSYS {
return err
}
return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
}
//sys futimes(fd int, timeval *[2]Timeval) (err error)
func Futimes(fd int, tv []Timeval) error {
if tv == nil {
return futimes(fd, nil)
}
if len(tv) != 2 {
return EINVAL
}
return futimes(fd, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
//sys fcntl(fd int, cmd int, arg int) (val int, err error)
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
func Poll(fds []PollFd, timeout int) (n int, err error) {
if len(fds) == 0 {
return poll(nil, 0, timeout)
}
return poll(&fds[0], len(fds), timeout)
}
// TODO: wrap
// Acct(name nil-string) (err error)
// Gethostuuid(uuid *byte, timeout *Timespec) (err error)
// Ptrace(req int, pid int, addr uintptr, data int) (ret uintptr, err error)
var mapper = &mmapper{
active: make(map[*byte][]byte),
mmap: mmap,
munmap: munmap,
}
func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
return mapper.Mmap(fd, offset, length, prot, flags)
}
func Munmap(b []byte) (err error) {
return mapper.Munmap(b)
}
//sys Madvise(b []byte, behav int) (err error)
//sys Mlock(b []byte) (err error)
//sys Mlockall(flags int) (err error)
//sys Mprotect(b []byte, prot int) (err error)
//sys Msync(b []byte, flags int) (err error)
//sys Munlock(b []byte) (err error)
//sys Munlockall() (err error)
| {
"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 fake
import (
"context"
"k8s.io/api/core/v1"
policy "k8s.io/api/policy/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
restclient "k8s.io/client-go/rest"
core "k8s.io/client-go/testing"
)
func (c *FakePods) Bind(ctx context.Context, binding *v1.Binding, opts metav1.CreateOptions) error {
action := core.CreateActionImpl{}
action.Verb = "create"
action.Namespace = binding.Namespace
action.Resource = podsResource
action.Subresource = "binding"
action.Object = binding
_, err := c.Fake.Invokes(action, binding)
return err
}
func (c *FakePods) GetBinding(name string) (result *v1.Binding, err error) {
obj, err := c.Fake.
Invokes(core.NewGetSubresourceAction(podsResource, c.ns, "binding", name), &v1.Binding{})
if obj == nil {
return nil, err
}
return obj.(*v1.Binding), err
}
func (c *FakePods) GetLogs(name string, opts *v1.PodLogOptions) *restclient.Request {
action := core.GenericActionImpl{}
action.Verb = "get"
action.Namespace = c.ns
action.Resource = podsResource
action.Subresource = "log"
action.Value = opts
_, _ = c.Fake.Invokes(action, &v1.Pod{})
return &restclient.Request{}
}
func (c *FakePods) Evict(ctx context.Context, eviction *policy.Eviction) error {
action := core.CreateActionImpl{}
action.Verb = "create"
action.Namespace = c.ns
action.Resource = podsResource
action.Subresource = "eviction"
action.Object = eviction
_, err := c.Fake.Invokes(action, eviction)
return err
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2015-2019, Intel Corporation
#
# src/test/obj_recovery/TEST5 -- unit test for pool recovery
#
. ../unittest/unittest.sh
require_test_type medium
require_no_asan
configure_valgrind pmemcheck force-disable
setup
# exits in the middle of transaction, so pool cannot be closed
export MEMCHECK_DONT_CHECK_LEAKS=1
create_poolset $DIR/testset 16M:$DIR/testfile1 R 16M:$DIR/testfile2
expect_normal_exit ./obj_recovery$EXESUFFIX $DIR/testset n c f
compare_replicas "-soOaAbd -l -Z -H -C" \
$DIR/testfile1 $DIR/testfile2 > diff_pre$UNITTEST_NUM.log
expect_normal_exit ./obj_recovery$EXESUFFIX $DIR/testset n o f
compare_replicas "-soOaAbd -l -Z -H -C" \
$DIR/testfile1 $DIR/testfile2 > diff_post$UNITTEST_NUM.log
check
pass
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015-2020 Ole André Vadla Ravnås <[email protected]>
*
* Licence: wxWindows Library Licence, Version 3.1
*/
#include "gumthumbreader.h"
#include <capstone.h>
static cs_insn * disassemble_instruction_at (gconstpointer address);
gpointer
gum_thumb_reader_try_get_relative_jump_target (gconstpointer address)
{
gpointer result = NULL;
cs_insn * insn;
cs_arm_op * op;
insn = disassemble_instruction_at (address);
if (insn == NULL)
return NULL;
op = &insn->detail->arm.operands[0];
if (insn->id == ARM_INS_B && op->type == ARM_OP_IMM)
result = GSIZE_TO_POINTER (op->imm | 1);
else if (insn->id == ARM_INS_BX && op->type == ARM_OP_IMM)
result = GSIZE_TO_POINTER (op->imm);
cs_free (insn, 1);
return result;
}
static cs_insn *
disassemble_instruction_at (gconstpointer address)
{
gconstpointer code = GSIZE_TO_POINTER (GPOINTER_TO_SIZE (address) & ~1);
csh capstone;
cs_err err;
cs_insn * insn = NULL;
err = cs_open (CS_ARCH_ARM, CS_MODE_THUMB | CS_MODE_V8, &capstone);
g_assert (err == CS_ERR_OK);
err = cs_option (capstone, CS_OPT_DETAIL, CS_OPT_ON);
g_assert (err == CS_ERR_OK);
cs_disasm (capstone, code, 16, GPOINTER_TO_SIZE (code), 1, &insn);
cs_close (&capstone);
return insn;
}
| {
"pile_set_name": "Github"
} |
import { BufferWhenSignature } from '../../operator/bufferWhen';
declare module '../../Observable' {
interface Observable<T> {
bufferWhen: BufferWhenSignature<T>;
}
}
| {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <[email protected]>
// Copyright (C) 2010 Jitse Niesen <[email protected]>
//
// 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/.
#ifndef EIGEN_SELFADJOINTEIGENSOLVER_H
#define EIGEN_SELFADJOINTEIGENSOLVER_H
#include "./Tridiagonalization.h"
namespace Eigen {
template<typename _MatrixType>
class GeneralizedSelfAdjointEigenSolver;
namespace internal {
template<typename SolverType,int Size,bool IsComplex> struct direct_selfadjoint_eigenvalues;
template<typename MatrixType, typename DiagType, typename SubDiagType>
ComputationInfo computeFromTridiagonal_impl(DiagType& diag, SubDiagType& subdiag, const Index maxIterations, bool computeEigenvectors, MatrixType& eivec);
}
/** \eigenvalues_module \ingroup Eigenvalues_Module
*
*
* \class SelfAdjointEigenSolver
*
* \brief Computes eigenvalues and eigenvectors of selfadjoint matrices
*
* \tparam _MatrixType the type of the matrix of which we are computing the
* eigendecomposition; this is expected to be an instantiation of the Matrix
* class template.
*
* A matrix \f$ A \f$ is selfadjoint if it equals its adjoint. For real
* matrices, this means that the matrix is symmetric: it equals its
* transpose. This class computes the eigenvalues and eigenvectors of a
* selfadjoint matrix. These are the scalars \f$ \lambda \f$ and vectors
* \f$ v \f$ such that \f$ Av = \lambda v \f$. The eigenvalues of a
* selfadjoint matrix are always real. If \f$ D \f$ is a diagonal matrix with
* the eigenvalues on the diagonal, and \f$ V \f$ is a matrix with the
* eigenvectors as its columns, then \f$ A = V D V^{-1} \f$ (for selfadjoint
* matrices, the matrix \f$ V \f$ is always invertible). This is called the
* eigendecomposition.
*
* The algorithm exploits the fact that the matrix is selfadjoint, making it
* faster and more accurate than the general purpose eigenvalue algorithms
* implemented in EigenSolver and ComplexEigenSolver.
*
* Only the \b lower \b triangular \b part of the input matrix is referenced.
*
* Call the function compute() to compute the eigenvalues and eigenvectors of
* a given matrix. Alternatively, you can use the
* SelfAdjointEigenSolver(const MatrixType&, int) constructor which computes
* the eigenvalues and eigenvectors at construction time. Once the eigenvalue
* and eigenvectors are computed, they can be retrieved with the eigenvalues()
* and eigenvectors() functions.
*
* The documentation for SelfAdjointEigenSolver(const MatrixType&, int)
* contains an example of the typical use of this class.
*
* To solve the \em generalized eigenvalue problem \f$ Av = \lambda Bv \f$ and
* the likes, see the class GeneralizedSelfAdjointEigenSolver.
*
* \sa MatrixBase::eigenvalues(), class EigenSolver, class ComplexEigenSolver
*/
template<typename _MatrixType> class SelfAdjointEigenSolver
{
public:
typedef _MatrixType MatrixType;
enum {
Size = MatrixType::RowsAtCompileTime,
ColsAtCompileTime = MatrixType::ColsAtCompileTime,
Options = MatrixType::Options,
MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
};
/** \brief Scalar type for matrices of type \p _MatrixType. */
typedef typename MatrixType::Scalar Scalar;
typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3
typedef Matrix<Scalar,Size,Size,ColMajor,MaxColsAtCompileTime,MaxColsAtCompileTime> EigenvectorsType;
/** \brief Real scalar type for \p _MatrixType.
*
* This is just \c Scalar if #Scalar is real (e.g., \c float or
* \c double), and the type of the real part of \c Scalar if #Scalar is
* complex.
*/
typedef typename NumTraits<Scalar>::Real RealScalar;
friend struct internal::direct_selfadjoint_eigenvalues<SelfAdjointEigenSolver,Size,NumTraits<Scalar>::IsComplex>;
/** \brief Type for vector of eigenvalues as returned by eigenvalues().
*
* This is a column vector with entries of type #RealScalar.
* The length of the vector is the size of \p _MatrixType.
*/
typedef typename internal::plain_col_type<MatrixType, RealScalar>::type RealVectorType;
typedef Tridiagonalization<MatrixType> TridiagonalizationType;
typedef typename TridiagonalizationType::SubDiagonalType SubDiagonalType;
/** \brief Default constructor for fixed-size matrices.
*
* The default constructor is useful in cases in which the user intends to
* perform decompositions via compute(). This constructor
* can only be used if \p _MatrixType is a fixed-size matrix; use
* SelfAdjointEigenSolver(Index) for dynamic-size matrices.
*
* Example: \include SelfAdjointEigenSolver_SelfAdjointEigenSolver.cpp
* Output: \verbinclude SelfAdjointEigenSolver_SelfAdjointEigenSolver.out
*/
EIGEN_DEVICE_FUNC
SelfAdjointEigenSolver()
: m_eivec(),
m_eivalues(),
m_subdiag(),
m_isInitialized(false)
{ }
/** \brief Constructor, pre-allocates memory for dynamic-size matrices.
*
* \param [in] size Positive integer, size of the matrix whose
* eigenvalues and eigenvectors will be computed.
*
* This constructor is useful for dynamic-size matrices, when the user
* intends to perform decompositions via compute(). The \p size
* parameter is only used as a hint. It is not an error to give a wrong
* \p size, but it may impair performance.
*
* \sa compute() for an example
*/
EIGEN_DEVICE_FUNC
explicit SelfAdjointEigenSolver(Index size)
: m_eivec(size, size),
m_eivalues(size),
m_subdiag(size > 1 ? size - 1 : 1),
m_isInitialized(false)
{}
/** \brief Constructor; computes eigendecomposition of given matrix.
*
* \param[in] matrix Selfadjoint matrix whose eigendecomposition is to
* be computed. Only the lower triangular part of the matrix is referenced.
* \param[in] options Can be #ComputeEigenvectors (default) or #EigenvaluesOnly.
*
* This constructor calls compute(const MatrixType&, int) to compute the
* eigenvalues of the matrix \p matrix. The eigenvectors are computed if
* \p options equals #ComputeEigenvectors.
*
* Example: \include SelfAdjointEigenSolver_SelfAdjointEigenSolver_MatrixType.cpp
* Output: \verbinclude SelfAdjointEigenSolver_SelfAdjointEigenSolver_MatrixType.out
*
* \sa compute(const MatrixType&, int)
*/
template<typename InputType>
EIGEN_DEVICE_FUNC
explicit SelfAdjointEigenSolver(const EigenBase<InputType>& matrix, int options = ComputeEigenvectors)
: m_eivec(matrix.rows(), matrix.cols()),
m_eivalues(matrix.cols()),
m_subdiag(matrix.rows() > 1 ? matrix.rows() - 1 : 1),
m_isInitialized(false)
{
compute(matrix.derived(), options);
}
/** \brief Computes eigendecomposition of given matrix.
*
* \param[in] matrix Selfadjoint matrix whose eigendecomposition is to
* be computed. Only the lower triangular part of the matrix is referenced.
* \param[in] options Can be #ComputeEigenvectors (default) or #EigenvaluesOnly.
* \returns Reference to \c *this
*
* This function computes the eigenvalues of \p matrix. The eigenvalues()
* function can be used to retrieve them. If \p options equals #ComputeEigenvectors,
* then the eigenvectors are also computed and can be retrieved by
* calling eigenvectors().
*
* This implementation uses a symmetric QR algorithm. The matrix is first
* reduced to tridiagonal form using the Tridiagonalization class. The
* tridiagonal matrix is then brought to diagonal form with implicit
* symmetric QR steps with Wilkinson shift. Details can be found in
* Section 8.3 of Golub \& Van Loan, <i>%Matrix Computations</i>.
*
* The cost of the computation is about \f$ 9n^3 \f$ if the eigenvectors
* are required and \f$ 4n^3/3 \f$ if they are not required.
*
* This method reuses the memory in the SelfAdjointEigenSolver object that
* was allocated when the object was constructed, if the size of the
* matrix does not change.
*
* Example: \include SelfAdjointEigenSolver_compute_MatrixType.cpp
* Output: \verbinclude SelfAdjointEigenSolver_compute_MatrixType.out
*
* \sa SelfAdjointEigenSolver(const MatrixType&, int)
*/
template<typename InputType>
EIGEN_DEVICE_FUNC
SelfAdjointEigenSolver& compute(const EigenBase<InputType>& matrix, int options = ComputeEigenvectors);
/** \brief Computes eigendecomposition of given matrix using a closed-form algorithm
*
* This is a variant of compute(const MatrixType&, int options) which
* directly solves the underlying polynomial equation.
*
* Currently only 2x2 and 3x3 matrices for which the sizes are known at compile time are supported (e.g., Matrix3d).
*
* This method is usually significantly faster than the QR iterative algorithm
* but it might also be less accurate. It is also worth noting that
* for 3x3 matrices it involves trigonometric operations which are
* not necessarily available for all scalar types.
*
* For the 3x3 case, we observed the following worst case relative error regarding the eigenvalues:
* - double: 1e-8
* - float: 1e-3
*
* \sa compute(const MatrixType&, int options)
*/
EIGEN_DEVICE_FUNC
SelfAdjointEigenSolver& computeDirect(const MatrixType& matrix, int options = ComputeEigenvectors);
/**
*\brief Computes the eigen decomposition from a tridiagonal symmetric matrix
*
* \param[in] diag The vector containing the diagonal of the matrix.
* \param[in] subdiag The subdiagonal of the matrix.
* \param[in] options Can be #ComputeEigenvectors (default) or #EigenvaluesOnly.
* \returns Reference to \c *this
*
* This function assumes that the matrix has been reduced to tridiagonal form.
*
* \sa compute(const MatrixType&, int) for more information
*/
SelfAdjointEigenSolver& computeFromTridiagonal(const RealVectorType& diag, const SubDiagonalType& subdiag , int options=ComputeEigenvectors);
/** \brief Returns the eigenvectors of given matrix.
*
* \returns A const reference to the matrix whose columns are the eigenvectors.
*
* \pre The eigenvectors have been computed before.
*
* Column \f$ k \f$ of the returned matrix is an eigenvector corresponding
* to eigenvalue number \f$ k \f$ as returned by eigenvalues(). The
* eigenvectors are normalized to have (Euclidean) norm equal to one. If
* this object was used to solve the eigenproblem for the selfadjoint
* matrix \f$ A \f$, then the matrix returned by this function is the
* matrix \f$ V \f$ in the eigendecomposition \f$ A = V D V^{-1} \f$.
*
* Example: \include SelfAdjointEigenSolver_eigenvectors.cpp
* Output: \verbinclude SelfAdjointEigenSolver_eigenvectors.out
*
* \sa eigenvalues()
*/
EIGEN_DEVICE_FUNC
const EigenvectorsType& eigenvectors() const
{
eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
return m_eivec;
}
/** \brief Returns the eigenvalues of given matrix.
*
* \returns A const reference to the column vector containing the eigenvalues.
*
* \pre The eigenvalues have been computed before.
*
* The eigenvalues are repeated according to their algebraic multiplicity,
* so there are as many eigenvalues as rows in the matrix. The eigenvalues
* are sorted in increasing order.
*
* Example: \include SelfAdjointEigenSolver_eigenvalues.cpp
* Output: \verbinclude SelfAdjointEigenSolver_eigenvalues.out
*
* \sa eigenvectors(), MatrixBase::eigenvalues()
*/
EIGEN_DEVICE_FUNC
const RealVectorType& eigenvalues() const
{
eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
return m_eivalues;
}
/** \brief Computes the positive-definite square root of the matrix.
*
* \returns the positive-definite square root of the matrix
*
* \pre The eigenvalues and eigenvectors of a positive-definite matrix
* have been computed before.
*
* The square root of a positive-definite matrix \f$ A \f$ is the
* positive-definite matrix whose square equals \f$ A \f$. This function
* uses the eigendecomposition \f$ A = V D V^{-1} \f$ to compute the
* square root as \f$ A^{1/2} = V D^{1/2} V^{-1} \f$.
*
* Example: \include SelfAdjointEigenSolver_operatorSqrt.cpp
* Output: \verbinclude SelfAdjointEigenSolver_operatorSqrt.out
*
* \sa operatorInverseSqrt(), <a href="unsupported/group__MatrixFunctions__Module.html">MatrixFunctions Module</a>
*/
EIGEN_DEVICE_FUNC
MatrixType operatorSqrt() const
{
eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
return m_eivec * m_eivalues.cwiseSqrt().asDiagonal() * m_eivec.adjoint();
}
/** \brief Computes the inverse square root of the matrix.
*
* \returns the inverse positive-definite square root of the matrix
*
* \pre The eigenvalues and eigenvectors of a positive-definite matrix
* have been computed before.
*
* This function uses the eigendecomposition \f$ A = V D V^{-1} \f$ to
* compute the inverse square root as \f$ V D^{-1/2} V^{-1} \f$. This is
* cheaper than first computing the square root with operatorSqrt() and
* then its inverse with MatrixBase::inverse().
*
* Example: \include SelfAdjointEigenSolver_operatorInverseSqrt.cpp
* Output: \verbinclude SelfAdjointEigenSolver_operatorInverseSqrt.out
*
* \sa operatorSqrt(), MatrixBase::inverse(), <a href="unsupported/group__MatrixFunctions__Module.html">MatrixFunctions Module</a>
*/
EIGEN_DEVICE_FUNC
MatrixType operatorInverseSqrt() const
{
eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
return m_eivec * m_eivalues.cwiseInverse().cwiseSqrt().asDiagonal() * m_eivec.adjoint();
}
/** \brief Reports whether previous computation was successful.
*
* \returns \c Success if computation was succesful, \c NoConvergence otherwise.
*/
EIGEN_DEVICE_FUNC
ComputationInfo info() const
{
eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
return m_info;
}
/** \brief Maximum number of iterations.
*
* The algorithm terminates if it does not converge within m_maxIterations * n iterations, where n
* denotes the size of the matrix. This value is currently set to 30 (copied from LAPACK).
*/
static const int m_maxIterations = 30;
protected:
static void check_template_parameters()
{
EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar);
}
EigenvectorsType m_eivec;
RealVectorType m_eivalues;
typename TridiagonalizationType::SubDiagonalType m_subdiag;
ComputationInfo m_info;
bool m_isInitialized;
bool m_eigenvectorsOk;
};
namespace internal {
/** \internal
*
* \eigenvalues_module \ingroup Eigenvalues_Module
*
* Performs a QR step on a tridiagonal symmetric matrix represented as a
* pair of two vectors \a diag and \a subdiag.
*
* \param diag the diagonal part of the input selfadjoint tridiagonal matrix
* \param subdiag the sub-diagonal part of the input selfadjoint tridiagonal matrix
* \param start starting index of the submatrix to work on
* \param end last+1 index of the submatrix to work on
* \param matrixQ pointer to the column-major matrix holding the eigenvectors, can be 0
* \param n size of the input matrix
*
* For compilation efficiency reasons, this procedure does not use eigen expression
* for its arguments.
*
* Implemented from Golub's "Matrix Computations", algorithm 8.3.2:
* "implicit symmetric QR step with Wilkinson shift"
*/
template<int StorageOrder,typename RealScalar, typename Scalar, typename Index>
EIGEN_DEVICE_FUNC
static void tridiagonal_qr_step(RealScalar* diag, RealScalar* subdiag, Index start, Index end, Scalar* matrixQ, Index n);
}
template<typename MatrixType>
template<typename InputType>
EIGEN_DEVICE_FUNC
SelfAdjointEigenSolver<MatrixType>& SelfAdjointEigenSolver<MatrixType>
::compute(const EigenBase<InputType>& a_matrix, int options)
{
check_template_parameters();
const InputType &matrix(a_matrix.derived());
using std::abs;
eigen_assert(matrix.cols() == matrix.rows());
eigen_assert((options&~(EigVecMask|GenEigMask))==0
&& (options&EigVecMask)!=EigVecMask
&& "invalid option parameter");
bool computeEigenvectors = (options&ComputeEigenvectors)==ComputeEigenvectors;
Index n = matrix.cols();
m_eivalues.resize(n,1);
if(n==1)
{
m_eivec = matrix;
m_eivalues.coeffRef(0,0) = numext::real(m_eivec.coeff(0,0));
if(computeEigenvectors)
m_eivec.setOnes(n,n);
m_info = Success;
m_isInitialized = true;
m_eigenvectorsOk = computeEigenvectors;
return *this;
}
// declare some aliases
RealVectorType& diag = m_eivalues;
EigenvectorsType& mat = m_eivec;
// map the matrix coefficients to [-1:1] to avoid over- and underflow.
mat = matrix.template triangularView<Lower>();
RealScalar scale = mat.cwiseAbs().maxCoeff();
if(scale==RealScalar(0)) scale = RealScalar(1);
mat.template triangularView<Lower>() /= scale;
m_subdiag.resize(n-1);
internal::tridiagonalization_inplace(mat, diag, m_subdiag, computeEigenvectors);
m_info = internal::computeFromTridiagonal_impl(diag, m_subdiag, m_maxIterations, computeEigenvectors, m_eivec);
// scale back the eigen values
m_eivalues *= scale;
m_isInitialized = true;
m_eigenvectorsOk = computeEigenvectors;
return *this;
}
template<typename MatrixType>
SelfAdjointEigenSolver<MatrixType>& SelfAdjointEigenSolver<MatrixType>
::computeFromTridiagonal(const RealVectorType& diag, const SubDiagonalType& subdiag , int options)
{
//TODO : Add an option to scale the values beforehand
bool computeEigenvectors = (options&ComputeEigenvectors)==ComputeEigenvectors;
m_eivalues = diag;
m_subdiag = subdiag;
if (computeEigenvectors)
{
m_eivec.setIdentity(diag.size(), diag.size());
}
m_info = internal::computeFromTridiagonal_impl(m_eivalues, m_subdiag, m_maxIterations, computeEigenvectors, m_eivec);
m_isInitialized = true;
m_eigenvectorsOk = computeEigenvectors;
return *this;
}
namespace internal {
/**
* \internal
* \brief Compute the eigendecomposition from a tridiagonal matrix
*
* \param[in,out] diag : On input, the diagonal of the matrix, on output the eigenvalues
* \param[in,out] subdiag : The subdiagonal part of the matrix (entries are modified during the decomposition)
* \param[in] maxIterations : the maximum number of iterations
* \param[in] computeEigenvectors : whether the eigenvectors have to be computed or not
* \param[out] eivec : The matrix to store the eigenvectors if computeEigenvectors==true. Must be allocated on input.
* \returns \c Success or \c NoConvergence
*/
template<typename MatrixType, typename DiagType, typename SubDiagType>
ComputationInfo computeFromTridiagonal_impl(DiagType& diag, SubDiagType& subdiag, const Index maxIterations, bool computeEigenvectors, MatrixType& eivec)
{
using std::abs;
ComputationInfo info;
typedef typename MatrixType::Scalar Scalar;
Index n = diag.size();
Index end = n-1;
Index start = 0;
Index iter = 0; // total number of iterations
typedef typename DiagType::RealScalar RealScalar;
const RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();
const RealScalar precision = RealScalar(2)*NumTraits<RealScalar>::epsilon();
while (end>0)
{
for (Index i = start; i<end; ++i)
if (internal::isMuchSmallerThan(abs(subdiag[i]),(abs(diag[i])+abs(diag[i+1])),precision) || abs(subdiag[i]) <= considerAsZero)
subdiag[i] = 0;
// find the largest unreduced block
while (end>0 && subdiag[end-1]==RealScalar(0))
{
end--;
}
if (end<=0)
break;
// if we spent too many iterations, we give up
iter++;
if(iter > maxIterations * n) break;
start = end - 1;
while (start>0 && subdiag[start-1]!=0)
start--;
internal::tridiagonal_qr_step<MatrixType::Flags&RowMajorBit ? RowMajor : ColMajor>(diag.data(), subdiag.data(), start, end, computeEigenvectors ? eivec.data() : (Scalar*)0, n);
}
if (iter <= maxIterations * n)
info = Success;
else
info = NoConvergence;
// Sort eigenvalues and corresponding vectors.
// TODO make the sort optional ?
// TODO use a better sort algorithm !!
if (info == Success)
{
for (Index i = 0; i < n-1; ++i)
{
Index k;
diag.segment(i,n-i).minCoeff(&k);
if (k > 0)
{
std::swap(diag[i], diag[k+i]);
if(computeEigenvectors)
eivec.col(i).swap(eivec.col(k+i));
}
}
}
return info;
}
template<typename SolverType,int Size,bool IsComplex> struct direct_selfadjoint_eigenvalues
{
EIGEN_DEVICE_FUNC
static inline void run(SolverType& eig, const typename SolverType::MatrixType& A, int options)
{ eig.compute(A,options); }
};
template<typename SolverType> struct direct_selfadjoint_eigenvalues<SolverType,3,false>
{
typedef typename SolverType::MatrixType MatrixType;
typedef typename SolverType::RealVectorType VectorType;
typedef typename SolverType::Scalar Scalar;
typedef typename SolverType::EigenvectorsType EigenvectorsType;
/** \internal
* Computes the roots of the characteristic polynomial of \a m.
* For numerical stability m.trace() should be near zero and to avoid over- or underflow m should be normalized.
*/
EIGEN_DEVICE_FUNC
static inline void computeRoots(const MatrixType& m, VectorType& roots)
{
EIGEN_USING_STD_MATH(sqrt)
EIGEN_USING_STD_MATH(atan2)
EIGEN_USING_STD_MATH(cos)
EIGEN_USING_STD_MATH(sin)
const Scalar s_inv3 = Scalar(1)/Scalar(3);
const Scalar s_sqrt3 = sqrt(Scalar(3));
// The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0. The
// eigenvalues are the roots to this equation, all guaranteed to be
// real-valued, because the matrix is symmetric.
Scalar c0 = m(0,0)*m(1,1)*m(2,2) + Scalar(2)*m(1,0)*m(2,0)*m(2,1) - m(0,0)*m(2,1)*m(2,1) - m(1,1)*m(2,0)*m(2,0) - m(2,2)*m(1,0)*m(1,0);
Scalar c1 = m(0,0)*m(1,1) - m(1,0)*m(1,0) + m(0,0)*m(2,2) - m(2,0)*m(2,0) + m(1,1)*m(2,2) - m(2,1)*m(2,1);
Scalar c2 = m(0,0) + m(1,1) + m(2,2);
// Construct the parameters used in classifying the roots of the equation
// and in solving the equation for the roots in closed form.
Scalar c2_over_3 = c2*s_inv3;
Scalar a_over_3 = (c2*c2_over_3 - c1)*s_inv3;
a_over_3 = numext::maxi(a_over_3, Scalar(0));
Scalar half_b = Scalar(0.5)*(c0 + c2_over_3*(Scalar(2)*c2_over_3*c2_over_3 - c1));
Scalar q = a_over_3*a_over_3*a_over_3 - half_b*half_b;
q = numext::maxi(q, Scalar(0));
// Compute the eigenvalues by solving for the roots of the polynomial.
Scalar rho = sqrt(a_over_3);
Scalar theta = atan2(sqrt(q),half_b)*s_inv3; // since sqrt(q) > 0, atan2 is in [0, pi] and theta is in [0, pi/3]
Scalar cos_theta = cos(theta);
Scalar sin_theta = sin(theta);
// roots are already sorted, since cos is monotonically decreasing on [0, pi]
roots(0) = c2_over_3 - rho*(cos_theta + s_sqrt3*sin_theta); // == 2*rho*cos(theta+2pi/3)
roots(1) = c2_over_3 - rho*(cos_theta - s_sqrt3*sin_theta); // == 2*rho*cos(theta+ pi/3)
roots(2) = c2_over_3 + Scalar(2)*rho*cos_theta;
}
EIGEN_DEVICE_FUNC
static inline bool extract_kernel(MatrixType& mat, Ref<VectorType> res, Ref<VectorType> representative)
{
using std::abs;
Index i0;
// Find non-zero column i0 (by construction, there must exist a non zero coefficient on the diagonal):
mat.diagonal().cwiseAbs().maxCoeff(&i0);
// mat.col(i0) is a good candidate for an orthogonal vector to the current eigenvector,
// so let's save it:
representative = mat.col(i0);
Scalar n0, n1;
VectorType c0, c1;
n0 = (c0 = representative.cross(mat.col((i0+1)%3))).squaredNorm();
n1 = (c1 = representative.cross(mat.col((i0+2)%3))).squaredNorm();
if(n0>n1) res = c0/std::sqrt(n0);
else res = c1/std::sqrt(n1);
return true;
}
EIGEN_DEVICE_FUNC
static inline void run(SolverType& solver, const MatrixType& mat, int options)
{
eigen_assert(mat.cols() == 3 && mat.cols() == mat.rows());
eigen_assert((options&~(EigVecMask|GenEigMask))==0
&& (options&EigVecMask)!=EigVecMask
&& "invalid option parameter");
bool computeEigenvectors = (options&ComputeEigenvectors)==ComputeEigenvectors;
EigenvectorsType& eivecs = solver.m_eivec;
VectorType& eivals = solver.m_eivalues;
// Shift the matrix to the mean eigenvalue and map the matrix coefficients to [-1:1] to avoid over- and underflow.
Scalar shift = mat.trace() / Scalar(3);
// TODO Avoid this copy. Currently it is necessary to suppress bogus values when determining maxCoeff and for computing the eigenvectors later
MatrixType scaledMat = mat.template selfadjointView<Lower>();
scaledMat.diagonal().array() -= shift;
Scalar scale = scaledMat.cwiseAbs().maxCoeff();
if(scale > 0) scaledMat /= scale; // TODO for scale==0 we could save the remaining operations
// compute the eigenvalues
computeRoots(scaledMat,eivals);
// compute the eigenvectors
if(computeEigenvectors)
{
if((eivals(2)-eivals(0))<=Eigen::NumTraits<Scalar>::epsilon())
{
// All three eigenvalues are numerically the same
eivecs.setIdentity();
}
else
{
MatrixType tmp;
tmp = scaledMat;
// Compute the eigenvector of the most distinct eigenvalue
Scalar d0 = eivals(2) - eivals(1);
Scalar d1 = eivals(1) - eivals(0);
Index k(0), l(2);
if(d0 > d1)
{
numext::swap(k,l);
d0 = d1;
}
// Compute the eigenvector of index k
{
tmp.diagonal().array () -= eivals(k);
// By construction, 'tmp' is of rank 2, and its kernel corresponds to the respective eigenvector.
extract_kernel(tmp, eivecs.col(k), eivecs.col(l));
}
// Compute eigenvector of index l
if(d0<=2*Eigen::NumTraits<Scalar>::epsilon()*d1)
{
// If d0 is too small, then the two other eigenvalues are numerically the same,
// and thus we only have to ortho-normalize the near orthogonal vector we saved above.
eivecs.col(l) -= eivecs.col(k).dot(eivecs.col(l))*eivecs.col(l);
eivecs.col(l).normalize();
}
else
{
tmp = scaledMat;
tmp.diagonal().array () -= eivals(l);
VectorType dummy;
extract_kernel(tmp, eivecs.col(l), dummy);
}
// Compute last eigenvector from the other two
eivecs.col(1) = eivecs.col(2).cross(eivecs.col(0)).normalized();
}
}
// Rescale back to the original size.
eivals *= scale;
eivals.array() += shift;
solver.m_info = Success;
solver.m_isInitialized = true;
solver.m_eigenvectorsOk = computeEigenvectors;
}
};
// 2x2 direct eigenvalues decomposition, code from Hauke Heibel
template<typename SolverType>
struct direct_selfadjoint_eigenvalues<SolverType,2,false>
{
typedef typename SolverType::MatrixType MatrixType;
typedef typename SolverType::RealVectorType VectorType;
typedef typename SolverType::Scalar Scalar;
typedef typename SolverType::EigenvectorsType EigenvectorsType;
EIGEN_DEVICE_FUNC
static inline void computeRoots(const MatrixType& m, VectorType& roots)
{
using std::sqrt;
const Scalar t0 = Scalar(0.5) * sqrt( numext::abs2(m(0,0)-m(1,1)) + Scalar(4)*numext::abs2(m(1,0)));
const Scalar t1 = Scalar(0.5) * (m(0,0) + m(1,1));
roots(0) = t1 - t0;
roots(1) = t1 + t0;
}
EIGEN_DEVICE_FUNC
static inline void run(SolverType& solver, const MatrixType& mat, int options)
{
EIGEN_USING_STD_MATH(sqrt);
EIGEN_USING_STD_MATH(abs);
eigen_assert(mat.cols() == 2 && mat.cols() == mat.rows());
eigen_assert((options&~(EigVecMask|GenEigMask))==0
&& (options&EigVecMask)!=EigVecMask
&& "invalid option parameter");
bool computeEigenvectors = (options&ComputeEigenvectors)==ComputeEigenvectors;
EigenvectorsType& eivecs = solver.m_eivec;
VectorType& eivals = solver.m_eivalues;
// Shift the matrix to the mean eigenvalue and map the matrix coefficients to [-1:1] to avoid over- and underflow.
Scalar shift = mat.trace() / Scalar(2);
MatrixType scaledMat = mat;
scaledMat.coeffRef(0,1) = mat.coeff(1,0);
scaledMat.diagonal().array() -= shift;
Scalar scale = scaledMat.cwiseAbs().maxCoeff();
if(scale > Scalar(0))
scaledMat /= scale;
// Compute the eigenvalues
computeRoots(scaledMat,eivals);
// compute the eigen vectors
if(computeEigenvectors)
{
if((eivals(1)-eivals(0))<=abs(eivals(1))*Eigen::NumTraits<Scalar>::epsilon())
{
eivecs.setIdentity();
}
else
{
scaledMat.diagonal().array () -= eivals(1);
Scalar a2 = numext::abs2(scaledMat(0,0));
Scalar c2 = numext::abs2(scaledMat(1,1));
Scalar b2 = numext::abs2(scaledMat(1,0));
if(a2>c2)
{
eivecs.col(1) << -scaledMat(1,0), scaledMat(0,0);
eivecs.col(1) /= sqrt(a2+b2);
}
else
{
eivecs.col(1) << -scaledMat(1,1), scaledMat(1,0);
eivecs.col(1) /= sqrt(c2+b2);
}
eivecs.col(0) << eivecs.col(1).unitOrthogonal();
}
}
// Rescale back to the original size.
eivals *= scale;
eivals.array() += shift;
solver.m_info = Success;
solver.m_isInitialized = true;
solver.m_eigenvectorsOk = computeEigenvectors;
}
};
}
template<typename MatrixType>
EIGEN_DEVICE_FUNC
SelfAdjointEigenSolver<MatrixType>& SelfAdjointEigenSolver<MatrixType>
::computeDirect(const MatrixType& matrix, int options)
{
internal::direct_selfadjoint_eigenvalues<SelfAdjointEigenSolver,Size,NumTraits<Scalar>::IsComplex>::run(*this,matrix,options);
return *this;
}
namespace internal {
template<int StorageOrder,typename RealScalar, typename Scalar, typename Index>
EIGEN_DEVICE_FUNC
static void tridiagonal_qr_step(RealScalar* diag, RealScalar* subdiag, Index start, Index end, Scalar* matrixQ, Index n)
{
using std::abs;
RealScalar td = (diag[end-1] - diag[end])*RealScalar(0.5);
RealScalar e = subdiag[end-1];
// Note that thanks to scaling, e^2 or td^2 cannot overflow, however they can still
// underflow thus leading to inf/NaN values when using the following commented code:
// RealScalar e2 = numext::abs2(subdiag[end-1]);
// RealScalar mu = diag[end] - e2 / (td + (td>0 ? 1 : -1) * sqrt(td*td + e2));
// This explain the following, somewhat more complicated, version:
RealScalar mu = diag[end];
if(td==RealScalar(0))
mu -= abs(e);
else
{
RealScalar e2 = numext::abs2(subdiag[end-1]);
RealScalar h = numext::hypot(td,e);
if(e2==RealScalar(0)) mu -= (e / (td + (td>RealScalar(0) ? RealScalar(1) : RealScalar(-1)))) * (e / h);
else mu -= e2 / (td + (td>RealScalar(0) ? h : -h));
}
RealScalar x = diag[start] - mu;
RealScalar z = subdiag[start];
for (Index k = start; k < end; ++k)
{
JacobiRotation<RealScalar> rot;
rot.makeGivens(x, z);
// do T = G' T G
RealScalar sdk = rot.s() * diag[k] + rot.c() * subdiag[k];
RealScalar dkp1 = rot.s() * subdiag[k] + rot.c() * diag[k+1];
diag[k] = rot.c() * (rot.c() * diag[k] - rot.s() * subdiag[k]) - rot.s() * (rot.c() * subdiag[k] - rot.s() * diag[k+1]);
diag[k+1] = rot.s() * sdk + rot.c() * dkp1;
subdiag[k] = rot.c() * sdk - rot.s() * dkp1;
if (k > start)
subdiag[k - 1] = rot.c() * subdiag[k-1] - rot.s() * z;
x = subdiag[k];
if (k < end - 1)
{
z = -rot.s() * subdiag[k+1];
subdiag[k + 1] = rot.c() * subdiag[k+1];
}
// apply the givens rotation to the unit matrix Q = Q * G
if (matrixQ)
{
// FIXME if StorageOrder == RowMajor this operation is not very efficient
Map<Matrix<Scalar,Dynamic,Dynamic,StorageOrder> > q(matrixQ,n,n);
q.applyOnTheRight(k,k+1,rot);
}
}
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_SELFADJOINTEIGENSOLVER_H
| {
"pile_set_name": "Github"
} |
---
title: Introduction to Framework Objects
description: Introduction to Framework Objects
ms.assetid: 1314501a-bff1-4aac-a391-a72acca9cc26
keywords:
- framework objects WDK KMDF , about framework objects
- reference counts WDK KMDF
- deletion callback functions WDK KMDF
- callback functions WDK KMDF
- parent objects WDK KMDF
ms.date: 04/20/2017
ms.localizationpriority: medium
---
# Introduction to Framework Objects
The interfaces that Windows Driver Frameworks (WDF) provides to drivers are object-based. The framework defines several objects. These objects export [methods](framework-object-methods.md) (functions) and [properties](framework-object-properties.md) (data) that drivers can access. Framework objects also initiate [events](framework-object-events.md), which drivers can support by providing event callback functions.
Framework-based drivers never directly access framework objects. Instead, drivers reference the objects by *handles*, which the driver passes as input to object methods.
All framework objects have the following characteristics:
<a href="" id="reference-count"></a>*Reference count*
The framework maintains a count of the number of references to each object. When the framework creates an object, it sets the object's reference count to one. When the framework has finished using an object, it decrements the reference count. The framework cannot delete the object until the reference count is decremented to zero, so drivers can prevent the deletion of an object by incrementing its reference count.
<a href="" id="context-space"></a>*Context space*
Framework-based drivers can create object-specific context space for every framework object that the driver receives or creates. Drivers should store all object-specific data in an object's context space. For more information about context space, see [Framework Object Context Space](framework-object-context-space.md).
<a href="" id="deletion-callback-functions"></a>*Deletion callback functions*
Drivers can register callback functions that the framework calls when it is deleting an object. The callback functions can remove driver-assigned resources, such as object-specific memory allocations. For more information about these callback functions, see [Framework Object Life Cycle](framework-object-life-cycle.md).
<a href="" id="parent-object"></a>*Parent object*
All framework objects can have a parent object. The framework designates a default parent object for most objects. When a driver creates an object, it can designate a parent object that overrides the object's default parent object. To designate an object's parent object, drivers set the **ParentObject** member of the object's [**WDF\_OBJECT\_ATTRIBUTES**](/windows-hardware/drivers/ddi/wdfobject/ns-wdfobject-_wdf_object_attributes) structure. (For a few object types, drivers cannot override the default parent object.) When the framework or a driver deletes a parent object, the framework also deletes the parent object's children.
For an overview of all of the objects that are defined by WDF, see [Summary of Framework Objects](summary-of-framework-objects.md).
| {
"pile_set_name": "Github"
} |
To update exchange rates, run the following command
```
curl https://api.exchangeratesapi.io/latest > exchange_rates.json
``` | {
"pile_set_name": "Github"
} |
/*
* Driver for the National Semiconductor DP83640 PHYTER
*
* Copyright (C) 2010 OMICRON electronics GmbH
*
* 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/crc32.h>
#include <linux/ethtool.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/mii.h>
#include <linux/module.h>
#include <linux/net_tstamp.h>
#include <linux/netdevice.h>
#include <linux/if_vlan.h>
#include <linux/phy.h>
#include <linux/ptp_classify.h>
#include <linux/ptp_clock_kernel.h>
#include "dp83640_reg.h"
#define DP83640_PHY_ID 0x20005ce1
#define PAGESEL 0x13
#define MAX_RXTS 64
#define N_EXT_TS 6
#define N_PER_OUT 7
#define PSF_PTPVER 2
#define PSF_EVNT 0x4000
#define PSF_RX 0x2000
#define PSF_TX 0x1000
#define EXT_EVENT 1
#define CAL_EVENT 7
#define CAL_TRIGGER 1
#define DP83640_N_PINS 12
#define MII_DP83640_MICR 0x11
#define MII_DP83640_MISR 0x12
#define MII_DP83640_MICR_OE 0x1
#define MII_DP83640_MICR_IE 0x2
#define MII_DP83640_MISR_RHF_INT_EN 0x01
#define MII_DP83640_MISR_FHF_INT_EN 0x02
#define MII_DP83640_MISR_ANC_INT_EN 0x04
#define MII_DP83640_MISR_DUP_INT_EN 0x08
#define MII_DP83640_MISR_SPD_INT_EN 0x10
#define MII_DP83640_MISR_LINK_INT_EN 0x20
#define MII_DP83640_MISR_ED_INT_EN 0x40
#define MII_DP83640_MISR_LQ_INT_EN 0x80
/* phyter seems to miss the mark by 16 ns */
#define ADJTIME_FIX 16
#define SKB_TIMESTAMP_TIMEOUT 2 /* jiffies */
#if defined(__BIG_ENDIAN)
#define ENDIAN_FLAG 0
#elif defined(__LITTLE_ENDIAN)
#define ENDIAN_FLAG PSF_ENDIAN
#endif
struct dp83640_skb_info {
int ptp_type;
unsigned long tmo;
};
struct phy_rxts {
u16 ns_lo; /* ns[15:0] */
u16 ns_hi; /* overflow[1:0], ns[29:16] */
u16 sec_lo; /* sec[15:0] */
u16 sec_hi; /* sec[31:16] */
u16 seqid; /* sequenceId[15:0] */
u16 msgtype; /* messageType[3:0], hash[11:0] */
};
struct phy_txts {
u16 ns_lo; /* ns[15:0] */
u16 ns_hi; /* overflow[1:0], ns[29:16] */
u16 sec_lo; /* sec[15:0] */
u16 sec_hi; /* sec[31:16] */
};
struct rxts {
struct list_head list;
unsigned long tmo;
u64 ns;
u16 seqid;
u8 msgtype;
u16 hash;
};
struct dp83640_clock;
struct dp83640_private {
struct list_head list;
struct dp83640_clock *clock;
struct phy_device *phydev;
struct delayed_work ts_work;
int hwts_tx_en;
int hwts_rx_en;
int layer;
int version;
/* remember state of cfg0 during calibration */
int cfg0;
/* remember the last event time stamp */
struct phy_txts edata;
/* list of rx timestamps */
struct list_head rxts;
struct list_head rxpool;
struct rxts rx_pool_data[MAX_RXTS];
/* protects above three fields from concurrent access */
spinlock_t rx_lock;
/* queues of incoming and outgoing packets */
struct sk_buff_head rx_queue;
struct sk_buff_head tx_queue;
};
struct dp83640_clock {
/* keeps the instance in the 'phyter_clocks' list */
struct list_head list;
/* we create one clock instance per MII bus */
struct mii_bus *bus;
/* protects extended registers from concurrent access */
struct mutex extreg_lock;
/* remembers which page was last selected */
int page;
/* our advertised capabilities */
struct ptp_clock_info caps;
/* protects the three fields below from concurrent access */
struct mutex clock_lock;
/* the one phyter from which we shall read */
struct dp83640_private *chosen;
/* list of the other attached phyters, not chosen */
struct list_head phylist;
/* reference to our PTP hardware clock */
struct ptp_clock *ptp_clock;
};
/* globals */
enum {
CALIBRATE_GPIO,
PEROUT_GPIO,
EXTTS0_GPIO,
EXTTS1_GPIO,
EXTTS2_GPIO,
EXTTS3_GPIO,
EXTTS4_GPIO,
EXTTS5_GPIO,
GPIO_TABLE_SIZE
};
static int chosen_phy = -1;
static ushort gpio_tab[GPIO_TABLE_SIZE] = {
1, 2, 3, 4, 8, 9, 10, 11
};
module_param(chosen_phy, int, 0444);
module_param_array(gpio_tab, ushort, NULL, 0444);
MODULE_PARM_DESC(chosen_phy, \
"The address of the PHY to use for the ancillary clock features");
MODULE_PARM_DESC(gpio_tab, \
"Which GPIO line to use for which purpose: cal,perout,extts1,...,extts6");
static void dp83640_gpio_defaults(struct ptp_pin_desc *pd)
{
int i, index;
for (i = 0; i < DP83640_N_PINS; i++) {
snprintf(pd[i].name, sizeof(pd[i].name), "GPIO%d", 1 + i);
pd[i].index = i;
}
for (i = 0; i < GPIO_TABLE_SIZE; i++) {
if (gpio_tab[i] < 1 || gpio_tab[i] > DP83640_N_PINS) {
pr_err("gpio_tab[%d]=%hu out of range", i, gpio_tab[i]);
return;
}
}
index = gpio_tab[CALIBRATE_GPIO] - 1;
pd[index].func = PTP_PF_PHYSYNC;
pd[index].chan = 0;
index = gpio_tab[PEROUT_GPIO] - 1;
pd[index].func = PTP_PF_PEROUT;
pd[index].chan = 0;
for (i = EXTTS0_GPIO; i < GPIO_TABLE_SIZE; i++) {
index = gpio_tab[i] - 1;
pd[index].func = PTP_PF_EXTTS;
pd[index].chan = i - EXTTS0_GPIO;
}
}
/* a list of clocks and a mutex to protect it */
static LIST_HEAD(phyter_clocks);
static DEFINE_MUTEX(phyter_clocks_lock);
static void rx_timestamp_work(struct work_struct *work);
/* extended register access functions */
#define BROADCAST_ADDR 31
static inline int broadcast_write(struct phy_device *phydev, u32 regnum,
u16 val)
{
return mdiobus_write(phydev->mdio.bus, BROADCAST_ADDR, regnum, val);
}
/* Caller must hold extreg_lock. */
static int ext_read(struct phy_device *phydev, int page, u32 regnum)
{
struct dp83640_private *dp83640 = phydev->priv;
int val;
if (dp83640->clock->page != page) {
broadcast_write(phydev, PAGESEL, page);
dp83640->clock->page = page;
}
val = phy_read(phydev, regnum);
return val;
}
/* Caller must hold extreg_lock. */
static void ext_write(int broadcast, struct phy_device *phydev,
int page, u32 regnum, u16 val)
{
struct dp83640_private *dp83640 = phydev->priv;
if (dp83640->clock->page != page) {
broadcast_write(phydev, PAGESEL, page);
dp83640->clock->page = page;
}
if (broadcast)
broadcast_write(phydev, regnum, val);
else
phy_write(phydev, regnum, val);
}
/* Caller must hold extreg_lock. */
static int tdr_write(int bc, struct phy_device *dev,
const struct timespec64 *ts, u16 cmd)
{
ext_write(bc, dev, PAGE4, PTP_TDR, ts->tv_nsec & 0xffff);/* ns[15:0] */
ext_write(bc, dev, PAGE4, PTP_TDR, ts->tv_nsec >> 16); /* ns[31:16] */
ext_write(bc, dev, PAGE4, PTP_TDR, ts->tv_sec & 0xffff); /* sec[15:0] */
ext_write(bc, dev, PAGE4, PTP_TDR, ts->tv_sec >> 16); /* sec[31:16]*/
ext_write(bc, dev, PAGE4, PTP_CTL, cmd);
return 0;
}
/* convert phy timestamps into driver timestamps */
static void phy2rxts(struct phy_rxts *p, struct rxts *rxts)
{
u32 sec;
sec = p->sec_lo;
sec |= p->sec_hi << 16;
rxts->ns = p->ns_lo;
rxts->ns |= (p->ns_hi & 0x3fff) << 16;
rxts->ns += ((u64)sec) * 1000000000ULL;
rxts->seqid = p->seqid;
rxts->msgtype = (p->msgtype >> 12) & 0xf;
rxts->hash = p->msgtype & 0x0fff;
rxts->tmo = jiffies + SKB_TIMESTAMP_TIMEOUT;
}
static u64 phy2txts(struct phy_txts *p)
{
u64 ns;
u32 sec;
sec = p->sec_lo;
sec |= p->sec_hi << 16;
ns = p->ns_lo;
ns |= (p->ns_hi & 0x3fff) << 16;
ns += ((u64)sec) * 1000000000ULL;
return ns;
}
static int periodic_output(struct dp83640_clock *clock,
struct ptp_clock_request *clkreq, bool on,
int trigger)
{
struct dp83640_private *dp83640 = clock->chosen;
struct phy_device *phydev = dp83640->phydev;
u32 sec, nsec, pwidth;
u16 gpio, ptp_trig, val;
if (on) {
gpio = 1 + ptp_find_pin(clock->ptp_clock, PTP_PF_PEROUT,
trigger);
if (gpio < 1)
return -EINVAL;
} else {
gpio = 0;
}
ptp_trig = TRIG_WR |
(trigger & TRIG_CSEL_MASK) << TRIG_CSEL_SHIFT |
(gpio & TRIG_GPIO_MASK) << TRIG_GPIO_SHIFT |
TRIG_PER |
TRIG_PULSE;
val = (trigger & TRIG_SEL_MASK) << TRIG_SEL_SHIFT;
if (!on) {
val |= TRIG_DIS;
mutex_lock(&clock->extreg_lock);
ext_write(0, phydev, PAGE5, PTP_TRIG, ptp_trig);
ext_write(0, phydev, PAGE4, PTP_CTL, val);
mutex_unlock(&clock->extreg_lock);
return 0;
}
sec = clkreq->perout.start.sec;
nsec = clkreq->perout.start.nsec;
pwidth = clkreq->perout.period.sec * 1000000000UL;
pwidth += clkreq->perout.period.nsec;
pwidth /= 2;
mutex_lock(&clock->extreg_lock);
ext_write(0, phydev, PAGE5, PTP_TRIG, ptp_trig);
/*load trigger*/
val |= TRIG_LOAD;
ext_write(0, phydev, PAGE4, PTP_CTL, val);
ext_write(0, phydev, PAGE4, PTP_TDR, nsec & 0xffff); /* ns[15:0] */
ext_write(0, phydev, PAGE4, PTP_TDR, nsec >> 16); /* ns[31:16] */
ext_write(0, phydev, PAGE4, PTP_TDR, sec & 0xffff); /* sec[15:0] */
ext_write(0, phydev, PAGE4, PTP_TDR, sec >> 16); /* sec[31:16] */
ext_write(0, phydev, PAGE4, PTP_TDR, pwidth & 0xffff); /* ns[15:0] */
ext_write(0, phydev, PAGE4, PTP_TDR, pwidth >> 16); /* ns[31:16] */
/* Triggers 0 and 1 has programmable pulsewidth2 */
if (trigger < 2) {
ext_write(0, phydev, PAGE4, PTP_TDR, pwidth & 0xffff);
ext_write(0, phydev, PAGE4, PTP_TDR, pwidth >> 16);
}
/*enable trigger*/
val &= ~TRIG_LOAD;
val |= TRIG_EN;
ext_write(0, phydev, PAGE4, PTP_CTL, val);
mutex_unlock(&clock->extreg_lock);
return 0;
}
/* ptp clock methods */
static int ptp_dp83640_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)
{
struct dp83640_clock *clock =
container_of(ptp, struct dp83640_clock, caps);
struct phy_device *phydev = clock->chosen->phydev;
u64 rate;
int neg_adj = 0;
u16 hi, lo;
if (scaled_ppm < 0) {
neg_adj = 1;
scaled_ppm = -scaled_ppm;
}
rate = scaled_ppm;
rate <<= 13;
rate = div_u64(rate, 15625);
hi = (rate >> 16) & PTP_RATE_HI_MASK;
if (neg_adj)
hi |= PTP_RATE_DIR;
lo = rate & 0xffff;
mutex_lock(&clock->extreg_lock);
ext_write(1, phydev, PAGE4, PTP_RATEH, hi);
ext_write(1, phydev, PAGE4, PTP_RATEL, lo);
mutex_unlock(&clock->extreg_lock);
return 0;
}
static int ptp_dp83640_adjtime(struct ptp_clock_info *ptp, s64 delta)
{
struct dp83640_clock *clock =
container_of(ptp, struct dp83640_clock, caps);
struct phy_device *phydev = clock->chosen->phydev;
struct timespec64 ts;
int err;
delta += ADJTIME_FIX;
ts = ns_to_timespec64(delta);
mutex_lock(&clock->extreg_lock);
err = tdr_write(1, phydev, &ts, PTP_STEP_CLK);
mutex_unlock(&clock->extreg_lock);
return err;
}
static int ptp_dp83640_gettime(struct ptp_clock_info *ptp,
struct timespec64 *ts)
{
struct dp83640_clock *clock =
container_of(ptp, struct dp83640_clock, caps);
struct phy_device *phydev = clock->chosen->phydev;
unsigned int val[4];
mutex_lock(&clock->extreg_lock);
ext_write(0, phydev, PAGE4, PTP_CTL, PTP_RD_CLK);
val[0] = ext_read(phydev, PAGE4, PTP_TDR); /* ns[15:0] */
val[1] = ext_read(phydev, PAGE4, PTP_TDR); /* ns[31:16] */
val[2] = ext_read(phydev, PAGE4, PTP_TDR); /* sec[15:0] */
val[3] = ext_read(phydev, PAGE4, PTP_TDR); /* sec[31:16] */
mutex_unlock(&clock->extreg_lock);
ts->tv_nsec = val[0] | (val[1] << 16);
ts->tv_sec = val[2] | (val[3] << 16);
return 0;
}
static int ptp_dp83640_settime(struct ptp_clock_info *ptp,
const struct timespec64 *ts)
{
struct dp83640_clock *clock =
container_of(ptp, struct dp83640_clock, caps);
struct phy_device *phydev = clock->chosen->phydev;
int err;
mutex_lock(&clock->extreg_lock);
err = tdr_write(1, phydev, ts, PTP_LOAD_CLK);
mutex_unlock(&clock->extreg_lock);
return err;
}
static int ptp_dp83640_enable(struct ptp_clock_info *ptp,
struct ptp_clock_request *rq, int on)
{
struct dp83640_clock *clock =
container_of(ptp, struct dp83640_clock, caps);
struct phy_device *phydev = clock->chosen->phydev;
unsigned int index;
u16 evnt, event_num, gpio_num;
switch (rq->type) {
case PTP_CLK_REQ_EXTTS:
index = rq->extts.index;
if (index >= N_EXT_TS)
return -EINVAL;
event_num = EXT_EVENT + index;
evnt = EVNT_WR | (event_num & EVNT_SEL_MASK) << EVNT_SEL_SHIFT;
if (on) {
gpio_num = 1 + ptp_find_pin(clock->ptp_clock,
PTP_PF_EXTTS, index);
if (gpio_num < 1)
return -EINVAL;
evnt |= (gpio_num & EVNT_GPIO_MASK) << EVNT_GPIO_SHIFT;
if (rq->extts.flags & PTP_FALLING_EDGE)
evnt |= EVNT_FALL;
else
evnt |= EVNT_RISE;
}
mutex_lock(&clock->extreg_lock);
ext_write(0, phydev, PAGE5, PTP_EVNT, evnt);
mutex_unlock(&clock->extreg_lock);
return 0;
case PTP_CLK_REQ_PEROUT:
if (rq->perout.index >= N_PER_OUT)
return -EINVAL;
return periodic_output(clock, rq, on, rq->perout.index);
default:
break;
}
return -EOPNOTSUPP;
}
static int ptp_dp83640_verify(struct ptp_clock_info *ptp, unsigned int pin,
enum ptp_pin_function func, unsigned int chan)
{
struct dp83640_clock *clock =
container_of(ptp, struct dp83640_clock, caps);
if (clock->caps.pin_config[pin].func == PTP_PF_PHYSYNC &&
!list_empty(&clock->phylist))
return 1;
if (func == PTP_PF_PHYSYNC)
return 1;
return 0;
}
static u8 status_frame_dst[6] = { 0x01, 0x1B, 0x19, 0x00, 0x00, 0x00 };
static u8 status_frame_src[6] = { 0x08, 0x00, 0x17, 0x0B, 0x6B, 0x0F };
static void enable_status_frames(struct phy_device *phydev, bool on)
{
struct dp83640_private *dp83640 = phydev->priv;
struct dp83640_clock *clock = dp83640->clock;
u16 cfg0 = 0, ver;
if (on)
cfg0 = PSF_EVNT_EN | PSF_RXTS_EN | PSF_TXTS_EN | ENDIAN_FLAG;
ver = (PSF_PTPVER & VERSIONPTP_MASK) << VERSIONPTP_SHIFT;
mutex_lock(&clock->extreg_lock);
ext_write(0, phydev, PAGE5, PSF_CFG0, cfg0);
ext_write(0, phydev, PAGE6, PSF_CFG1, ver);
mutex_unlock(&clock->extreg_lock);
if (!phydev->attached_dev) {
pr_warn("expected to find an attached netdevice\n");
return;
}
if (on) {
if (dev_mc_add(phydev->attached_dev, status_frame_dst))
pr_warn("failed to add mc address\n");
} else {
if (dev_mc_del(phydev->attached_dev, status_frame_dst))
pr_warn("failed to delete mc address\n");
}
}
static bool is_status_frame(struct sk_buff *skb, int type)
{
struct ethhdr *h = eth_hdr(skb);
if (PTP_CLASS_V2_L2 == type &&
!memcmp(h->h_source, status_frame_src, sizeof(status_frame_src)))
return true;
else
return false;
}
static int expired(struct rxts *rxts)
{
return time_after(jiffies, rxts->tmo);
}
/* Caller must hold rx_lock. */
static void prune_rx_ts(struct dp83640_private *dp83640)
{
struct list_head *this, *next;
struct rxts *rxts;
list_for_each_safe(this, next, &dp83640->rxts) {
rxts = list_entry(this, struct rxts, list);
if (expired(rxts)) {
list_del_init(&rxts->list);
list_add(&rxts->list, &dp83640->rxpool);
}
}
}
/* synchronize the phyters so they act as one clock */
static void enable_broadcast(struct phy_device *phydev, int init_page, int on)
{
int val;
phy_write(phydev, PAGESEL, 0);
val = phy_read(phydev, PHYCR2);
if (on)
val |= BC_WRITE;
else
val &= ~BC_WRITE;
phy_write(phydev, PHYCR2, val);
phy_write(phydev, PAGESEL, init_page);
}
static void recalibrate(struct dp83640_clock *clock)
{
s64 now, diff;
struct phy_txts event_ts;
struct timespec64 ts;
struct list_head *this;
struct dp83640_private *tmp;
struct phy_device *master = clock->chosen->phydev;
u16 cal_gpio, cfg0, evnt, ptp_trig, trigger, val;
trigger = CAL_TRIGGER;
cal_gpio = 1 + ptp_find_pin(clock->ptp_clock, PTP_PF_PHYSYNC, 0);
if (cal_gpio < 1) {
pr_err("PHY calibration pin not available - PHY is not calibrated.");
return;
}
mutex_lock(&clock->extreg_lock);
/*
* enable broadcast, disable status frames, enable ptp clock
*/
list_for_each(this, &clock->phylist) {
tmp = list_entry(this, struct dp83640_private, list);
enable_broadcast(tmp->phydev, clock->page, 1);
tmp->cfg0 = ext_read(tmp->phydev, PAGE5, PSF_CFG0);
ext_write(0, tmp->phydev, PAGE5, PSF_CFG0, 0);
ext_write(0, tmp->phydev, PAGE4, PTP_CTL, PTP_ENABLE);
}
enable_broadcast(master, clock->page, 1);
cfg0 = ext_read(master, PAGE5, PSF_CFG0);
ext_write(0, master, PAGE5, PSF_CFG0, 0);
ext_write(0, master, PAGE4, PTP_CTL, PTP_ENABLE);
/*
* enable an event timestamp
*/
evnt = EVNT_WR | EVNT_RISE | EVNT_SINGLE;
evnt |= (CAL_EVENT & EVNT_SEL_MASK) << EVNT_SEL_SHIFT;
evnt |= (cal_gpio & EVNT_GPIO_MASK) << EVNT_GPIO_SHIFT;
list_for_each(this, &clock->phylist) {
tmp = list_entry(this, struct dp83640_private, list);
ext_write(0, tmp->phydev, PAGE5, PTP_EVNT, evnt);
}
ext_write(0, master, PAGE5, PTP_EVNT, evnt);
/*
* configure a trigger
*/
ptp_trig = TRIG_WR | TRIG_IF_LATE | TRIG_PULSE;
ptp_trig |= (trigger & TRIG_CSEL_MASK) << TRIG_CSEL_SHIFT;
ptp_trig |= (cal_gpio & TRIG_GPIO_MASK) << TRIG_GPIO_SHIFT;
ext_write(0, master, PAGE5, PTP_TRIG, ptp_trig);
/* load trigger */
val = (trigger & TRIG_SEL_MASK) << TRIG_SEL_SHIFT;
val |= TRIG_LOAD;
ext_write(0, master, PAGE4, PTP_CTL, val);
/* enable trigger */
val &= ~TRIG_LOAD;
val |= TRIG_EN;
ext_write(0, master, PAGE4, PTP_CTL, val);
/* disable trigger */
val = (trigger & TRIG_SEL_MASK) << TRIG_SEL_SHIFT;
val |= TRIG_DIS;
ext_write(0, master, PAGE4, PTP_CTL, val);
/*
* read out and correct offsets
*/
val = ext_read(master, PAGE4, PTP_STS);
pr_info("master PTP_STS 0x%04hx\n", val);
val = ext_read(master, PAGE4, PTP_ESTS);
pr_info("master PTP_ESTS 0x%04hx\n", val);
event_ts.ns_lo = ext_read(master, PAGE4, PTP_EDATA);
event_ts.ns_hi = ext_read(master, PAGE4, PTP_EDATA);
event_ts.sec_lo = ext_read(master, PAGE4, PTP_EDATA);
event_ts.sec_hi = ext_read(master, PAGE4, PTP_EDATA);
now = phy2txts(&event_ts);
list_for_each(this, &clock->phylist) {
tmp = list_entry(this, struct dp83640_private, list);
val = ext_read(tmp->phydev, PAGE4, PTP_STS);
pr_info("slave PTP_STS 0x%04hx\n", val);
val = ext_read(tmp->phydev, PAGE4, PTP_ESTS);
pr_info("slave PTP_ESTS 0x%04hx\n", val);
event_ts.ns_lo = ext_read(tmp->phydev, PAGE4, PTP_EDATA);
event_ts.ns_hi = ext_read(tmp->phydev, PAGE4, PTP_EDATA);
event_ts.sec_lo = ext_read(tmp->phydev, PAGE4, PTP_EDATA);
event_ts.sec_hi = ext_read(tmp->phydev, PAGE4, PTP_EDATA);
diff = now - (s64) phy2txts(&event_ts);
pr_info("slave offset %lld nanoseconds\n", diff);
diff += ADJTIME_FIX;
ts = ns_to_timespec64(diff);
tdr_write(0, tmp->phydev, &ts, PTP_STEP_CLK);
}
/*
* restore status frames
*/
list_for_each(this, &clock->phylist) {
tmp = list_entry(this, struct dp83640_private, list);
ext_write(0, tmp->phydev, PAGE5, PSF_CFG0, tmp->cfg0);
}
ext_write(0, master, PAGE5, PSF_CFG0, cfg0);
mutex_unlock(&clock->extreg_lock);
}
/* time stamping methods */
static inline u16 exts_chan_to_edata(int ch)
{
return 1 << ((ch + EXT_EVENT) * 2);
}
static int decode_evnt(struct dp83640_private *dp83640,
void *data, int len, u16 ests)
{
struct phy_txts *phy_txts;
struct ptp_clock_event event;
int i, parsed;
int words = (ests >> EVNT_TS_LEN_SHIFT) & EVNT_TS_LEN_MASK;
u16 ext_status = 0;
/* calculate length of the event timestamp status message */
if (ests & MULT_EVNT)
parsed = (words + 2) * sizeof(u16);
else
parsed = (words + 1) * sizeof(u16);
/* check if enough data is available */
if (len < parsed)
return len;
if (ests & MULT_EVNT) {
ext_status = *(u16 *) data;
data += sizeof(ext_status);
}
phy_txts = data;
switch (words) { /* fall through in every case */
case 3:
dp83640->edata.sec_hi = phy_txts->sec_hi;
case 2:
dp83640->edata.sec_lo = phy_txts->sec_lo;
case 1:
dp83640->edata.ns_hi = phy_txts->ns_hi;
case 0:
dp83640->edata.ns_lo = phy_txts->ns_lo;
}
if (!ext_status) {
i = ((ests >> EVNT_NUM_SHIFT) & EVNT_NUM_MASK) - EXT_EVENT;
ext_status = exts_chan_to_edata(i);
}
event.type = PTP_CLOCK_EXTTS;
event.timestamp = phy2txts(&dp83640->edata);
/* Compensate for input path and synchronization delays */
event.timestamp -= 35;
for (i = 0; i < N_EXT_TS; i++) {
if (ext_status & exts_chan_to_edata(i)) {
event.index = i;
ptp_clock_event(dp83640->clock->ptp_clock, &event);
}
}
return parsed;
}
#define DP83640_PACKET_HASH_OFFSET 20
#define DP83640_PACKET_HASH_LEN 10
static int match(struct sk_buff *skb, unsigned int type, struct rxts *rxts)
{
u16 *seqid, hash;
unsigned int offset = 0;
u8 *msgtype, *data = skb_mac_header(skb);
/* check sequenceID, messageType, 12 bit hash of offset 20-29 */
if (type & PTP_CLASS_VLAN)
offset += VLAN_HLEN;
switch (type & PTP_CLASS_PMASK) {
case PTP_CLASS_IPV4:
offset += ETH_HLEN + IPV4_HLEN(data + offset) + UDP_HLEN;
break;
case PTP_CLASS_IPV6:
offset += ETH_HLEN + IP6_HLEN + UDP_HLEN;
break;
case PTP_CLASS_L2:
offset += ETH_HLEN;
break;
default:
return 0;
}
if (skb->len + ETH_HLEN < offset + OFF_PTP_SEQUENCE_ID + sizeof(*seqid))
return 0;
if (unlikely(type & PTP_CLASS_V1))
msgtype = data + offset + OFF_PTP_CONTROL;
else
msgtype = data + offset;
if (rxts->msgtype != (*msgtype & 0xf))
return 0;
seqid = (u16 *)(data + offset + OFF_PTP_SEQUENCE_ID);
if (rxts->seqid != ntohs(*seqid))
return 0;
hash = ether_crc(DP83640_PACKET_HASH_LEN,
data + offset + DP83640_PACKET_HASH_OFFSET) >> 20;
if (rxts->hash != hash)
return 0;
return 1;
}
static void decode_rxts(struct dp83640_private *dp83640,
struct phy_rxts *phy_rxts)
{
struct rxts *rxts;
struct skb_shared_hwtstamps *shhwtstamps = NULL;
struct sk_buff *skb;
unsigned long flags;
u8 overflow;
overflow = (phy_rxts->ns_hi >> 14) & 0x3;
if (overflow)
pr_debug("rx timestamp queue overflow, count %d\n", overflow);
spin_lock_irqsave(&dp83640->rx_lock, flags);
prune_rx_ts(dp83640);
if (list_empty(&dp83640->rxpool)) {
pr_debug("rx timestamp pool is empty\n");
goto out;
}
rxts = list_first_entry(&dp83640->rxpool, struct rxts, list);
list_del_init(&rxts->list);
phy2rxts(phy_rxts, rxts);
spin_lock(&dp83640->rx_queue.lock);
skb_queue_walk(&dp83640->rx_queue, skb) {
struct dp83640_skb_info *skb_info;
skb_info = (struct dp83640_skb_info *)skb->cb;
if (match(skb, skb_info->ptp_type, rxts)) {
__skb_unlink(skb, &dp83640->rx_queue);
shhwtstamps = skb_hwtstamps(skb);
memset(shhwtstamps, 0, sizeof(*shhwtstamps));
shhwtstamps->hwtstamp = ns_to_ktime(rxts->ns);
list_add(&rxts->list, &dp83640->rxpool);
break;
}
}
spin_unlock(&dp83640->rx_queue.lock);
if (!shhwtstamps)
list_add_tail(&rxts->list, &dp83640->rxts);
out:
spin_unlock_irqrestore(&dp83640->rx_lock, flags);
if (shhwtstamps)
netif_rx_ni(skb);
}
static void decode_txts(struct dp83640_private *dp83640,
struct phy_txts *phy_txts)
{
struct skb_shared_hwtstamps shhwtstamps;
struct sk_buff *skb;
u64 ns;
u8 overflow;
/* We must already have the skb that triggered this. */
skb = skb_dequeue(&dp83640->tx_queue);
if (!skb) {
pr_debug("have timestamp but tx_queue empty\n");
return;
}
overflow = (phy_txts->ns_hi >> 14) & 0x3;
if (overflow) {
pr_debug("tx timestamp queue overflow, count %d\n", overflow);
while (skb) {
kfree_skb(skb);
skb = skb_dequeue(&dp83640->tx_queue);
}
return;
}
ns = phy2txts(phy_txts);
memset(&shhwtstamps, 0, sizeof(shhwtstamps));
shhwtstamps.hwtstamp = ns_to_ktime(ns);
skb_complete_tx_timestamp(skb, &shhwtstamps);
}
static void decode_status_frame(struct dp83640_private *dp83640,
struct sk_buff *skb)
{
struct phy_rxts *phy_rxts;
struct phy_txts *phy_txts;
u8 *ptr;
int len, size;
u16 ests, type;
ptr = skb->data + 2;
for (len = skb_headlen(skb) - 2; len > sizeof(type); len -= size) {
type = *(u16 *)ptr;
ests = type & 0x0fff;
type = type & 0xf000;
len -= sizeof(type);
ptr += sizeof(type);
if (PSF_RX == type && len >= sizeof(*phy_rxts)) {
phy_rxts = (struct phy_rxts *) ptr;
decode_rxts(dp83640, phy_rxts);
size = sizeof(*phy_rxts);
} else if (PSF_TX == type && len >= sizeof(*phy_txts)) {
phy_txts = (struct phy_txts *) ptr;
decode_txts(dp83640, phy_txts);
size = sizeof(*phy_txts);
} else if (PSF_EVNT == type) {
size = decode_evnt(dp83640, ptr, len, ests);
} else {
size = 0;
break;
}
ptr += size;
}
}
static int is_sync(struct sk_buff *skb, int type)
{
u8 *data = skb->data, *msgtype;
unsigned int offset = 0;
if (type & PTP_CLASS_VLAN)
offset += VLAN_HLEN;
switch (type & PTP_CLASS_PMASK) {
case PTP_CLASS_IPV4:
offset += ETH_HLEN + IPV4_HLEN(data + offset) + UDP_HLEN;
break;
case PTP_CLASS_IPV6:
offset += ETH_HLEN + IP6_HLEN + UDP_HLEN;
break;
case PTP_CLASS_L2:
offset += ETH_HLEN;
break;
default:
return 0;
}
if (type & PTP_CLASS_V1)
offset += OFF_PTP_CONTROL;
if (skb->len < offset + 1)
return 0;
msgtype = data + offset;
return (*msgtype & 0xf) == 0;
}
static void dp83640_free_clocks(void)
{
struct dp83640_clock *clock;
struct list_head *this, *next;
mutex_lock(&phyter_clocks_lock);
list_for_each_safe(this, next, &phyter_clocks) {
clock = list_entry(this, struct dp83640_clock, list);
if (!list_empty(&clock->phylist)) {
pr_warn("phy list non-empty while unloading\n");
BUG();
}
list_del(&clock->list);
mutex_destroy(&clock->extreg_lock);
mutex_destroy(&clock->clock_lock);
put_device(&clock->bus->dev);
kfree(clock->caps.pin_config);
kfree(clock);
}
mutex_unlock(&phyter_clocks_lock);
}
static void dp83640_clock_init(struct dp83640_clock *clock, struct mii_bus *bus)
{
INIT_LIST_HEAD(&clock->list);
clock->bus = bus;
mutex_init(&clock->extreg_lock);
mutex_init(&clock->clock_lock);
INIT_LIST_HEAD(&clock->phylist);
clock->caps.owner = THIS_MODULE;
sprintf(clock->caps.name, "dp83640 timer");
clock->caps.max_adj = 1953124;
clock->caps.n_alarm = 0;
clock->caps.n_ext_ts = N_EXT_TS;
clock->caps.n_per_out = N_PER_OUT;
clock->caps.n_pins = DP83640_N_PINS;
clock->caps.pps = 0;
clock->caps.adjfine = ptp_dp83640_adjfine;
clock->caps.adjtime = ptp_dp83640_adjtime;
clock->caps.gettime64 = ptp_dp83640_gettime;
clock->caps.settime64 = ptp_dp83640_settime;
clock->caps.enable = ptp_dp83640_enable;
clock->caps.verify = ptp_dp83640_verify;
/*
* Convert the module param defaults into a dynamic pin configuration.
*/
dp83640_gpio_defaults(clock->caps.pin_config);
/*
* Get a reference to this bus instance.
*/
get_device(&bus->dev);
}
static int choose_this_phy(struct dp83640_clock *clock,
struct phy_device *phydev)
{
if (chosen_phy == -1 && !clock->chosen)
return 1;
if (chosen_phy == phydev->mdio.addr)
return 1;
return 0;
}
static struct dp83640_clock *dp83640_clock_get(struct dp83640_clock *clock)
{
if (clock)
mutex_lock(&clock->clock_lock);
return clock;
}
/*
* Look up and lock a clock by bus instance.
* If there is no clock for this bus, then create it first.
*/
static struct dp83640_clock *dp83640_clock_get_bus(struct mii_bus *bus)
{
struct dp83640_clock *clock = NULL, *tmp;
struct list_head *this;
mutex_lock(&phyter_clocks_lock);
list_for_each(this, &phyter_clocks) {
tmp = list_entry(this, struct dp83640_clock, list);
if (tmp->bus == bus) {
clock = tmp;
break;
}
}
if (clock)
goto out;
clock = kzalloc(sizeof(struct dp83640_clock), GFP_KERNEL);
if (!clock)
goto out;
clock->caps.pin_config = kzalloc(sizeof(struct ptp_pin_desc) *
DP83640_N_PINS, GFP_KERNEL);
if (!clock->caps.pin_config) {
kfree(clock);
clock = NULL;
goto out;
}
dp83640_clock_init(clock, bus);
list_add_tail(&phyter_clocks, &clock->list);
out:
mutex_unlock(&phyter_clocks_lock);
return dp83640_clock_get(clock);
}
static void dp83640_clock_put(struct dp83640_clock *clock)
{
mutex_unlock(&clock->clock_lock);
}
static int dp83640_probe(struct phy_device *phydev)
{
struct dp83640_clock *clock;
struct dp83640_private *dp83640;
int err = -ENOMEM, i;
if (phydev->mdio.addr == BROADCAST_ADDR)
return 0;
clock = dp83640_clock_get_bus(phydev->mdio.bus);
if (!clock)
goto no_clock;
dp83640 = kzalloc(sizeof(struct dp83640_private), GFP_KERNEL);
if (!dp83640)
goto no_memory;
dp83640->phydev = phydev;
INIT_DELAYED_WORK(&dp83640->ts_work, rx_timestamp_work);
INIT_LIST_HEAD(&dp83640->rxts);
INIT_LIST_HEAD(&dp83640->rxpool);
for (i = 0; i < MAX_RXTS; i++)
list_add(&dp83640->rx_pool_data[i].list, &dp83640->rxpool);
phydev->priv = dp83640;
spin_lock_init(&dp83640->rx_lock);
skb_queue_head_init(&dp83640->rx_queue);
skb_queue_head_init(&dp83640->tx_queue);
dp83640->clock = clock;
if (choose_this_phy(clock, phydev)) {
clock->chosen = dp83640;
clock->ptp_clock = ptp_clock_register(&clock->caps,
&phydev->mdio.dev);
if (IS_ERR(clock->ptp_clock)) {
err = PTR_ERR(clock->ptp_clock);
goto no_register;
}
} else
list_add_tail(&dp83640->list, &clock->phylist);
dp83640_clock_put(clock);
return 0;
no_register:
clock->chosen = NULL;
kfree(dp83640);
no_memory:
dp83640_clock_put(clock);
no_clock:
return err;
}
static void dp83640_remove(struct phy_device *phydev)
{
struct dp83640_clock *clock;
struct list_head *this, *next;
struct dp83640_private *tmp, *dp83640 = phydev->priv;
if (phydev->mdio.addr == BROADCAST_ADDR)
return;
enable_status_frames(phydev, false);
cancel_delayed_work_sync(&dp83640->ts_work);
skb_queue_purge(&dp83640->rx_queue);
skb_queue_purge(&dp83640->tx_queue);
clock = dp83640_clock_get(dp83640->clock);
if (dp83640 == clock->chosen) {
ptp_clock_unregister(clock->ptp_clock);
clock->chosen = NULL;
} else {
list_for_each_safe(this, next, &clock->phylist) {
tmp = list_entry(this, struct dp83640_private, list);
if (tmp == dp83640) {
list_del_init(&tmp->list);
break;
}
}
}
dp83640_clock_put(clock);
kfree(dp83640);
}
static int dp83640_soft_reset(struct phy_device *phydev)
{
int ret;
ret = genphy_soft_reset(phydev);
if (ret < 0)
return ret;
/* From DP83640 datasheet: "Software driver code must wait 3 us
* following a software reset before allowing further serial MII
* operations with the DP83640."
*/
udelay(10); /* Taking udelay inaccuracy into account */
return 0;
}
static int dp83640_config_init(struct phy_device *phydev)
{
struct dp83640_private *dp83640 = phydev->priv;
struct dp83640_clock *clock = dp83640->clock;
if (clock->chosen && !list_empty(&clock->phylist))
recalibrate(clock);
else {
mutex_lock(&clock->extreg_lock);
enable_broadcast(phydev, clock->page, 1);
mutex_unlock(&clock->extreg_lock);
}
enable_status_frames(phydev, true);
mutex_lock(&clock->extreg_lock);
ext_write(0, phydev, PAGE4, PTP_CTL, PTP_ENABLE);
mutex_unlock(&clock->extreg_lock);
return 0;
}
static int dp83640_ack_interrupt(struct phy_device *phydev)
{
int err = phy_read(phydev, MII_DP83640_MISR);
if (err < 0)
return err;
return 0;
}
static int dp83640_config_intr(struct phy_device *phydev)
{
int micr;
int misr;
int err;
if (phydev->interrupts == PHY_INTERRUPT_ENABLED) {
misr = phy_read(phydev, MII_DP83640_MISR);
if (misr < 0)
return misr;
misr |=
(MII_DP83640_MISR_ANC_INT_EN |
MII_DP83640_MISR_DUP_INT_EN |
MII_DP83640_MISR_SPD_INT_EN |
MII_DP83640_MISR_LINK_INT_EN);
err = phy_write(phydev, MII_DP83640_MISR, misr);
if (err < 0)
return err;
micr = phy_read(phydev, MII_DP83640_MICR);
if (micr < 0)
return micr;
micr |=
(MII_DP83640_MICR_OE |
MII_DP83640_MICR_IE);
return phy_write(phydev, MII_DP83640_MICR, micr);
} else {
micr = phy_read(phydev, MII_DP83640_MICR);
if (micr < 0)
return micr;
micr &=
~(MII_DP83640_MICR_OE |
MII_DP83640_MICR_IE);
err = phy_write(phydev, MII_DP83640_MICR, micr);
if (err < 0)
return err;
misr = phy_read(phydev, MII_DP83640_MISR);
if (misr < 0)
return misr;
misr &=
~(MII_DP83640_MISR_ANC_INT_EN |
MII_DP83640_MISR_DUP_INT_EN |
MII_DP83640_MISR_SPD_INT_EN |
MII_DP83640_MISR_LINK_INT_EN);
return phy_write(phydev, MII_DP83640_MISR, misr);
}
}
static int dp83640_hwtstamp(struct phy_device *phydev, struct ifreq *ifr)
{
struct dp83640_private *dp83640 = phydev->priv;
struct hwtstamp_config cfg;
u16 txcfg0, rxcfg0;
if (copy_from_user(&cfg, ifr->ifr_data, sizeof(cfg)))
return -EFAULT;
if (cfg.flags) /* reserved for future extensions */
return -EINVAL;
if (cfg.tx_type < 0 || cfg.tx_type > HWTSTAMP_TX_ONESTEP_SYNC)
return -ERANGE;
dp83640->hwts_tx_en = cfg.tx_type;
switch (cfg.rx_filter) {
case HWTSTAMP_FILTER_NONE:
dp83640->hwts_rx_en = 0;
dp83640->layer = 0;
dp83640->version = 0;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
dp83640->hwts_rx_en = 1;
dp83640->layer = PTP_CLASS_L4;
dp83640->version = PTP_CLASS_V1;
break;
case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
dp83640->hwts_rx_en = 1;
dp83640->layer = PTP_CLASS_L4;
dp83640->version = PTP_CLASS_V2;
break;
case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
dp83640->hwts_rx_en = 1;
dp83640->layer = PTP_CLASS_L2;
dp83640->version = PTP_CLASS_V2;
break;
case HWTSTAMP_FILTER_PTP_V2_EVENT:
case HWTSTAMP_FILTER_PTP_V2_SYNC:
case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
dp83640->hwts_rx_en = 1;
dp83640->layer = PTP_CLASS_L4 | PTP_CLASS_L2;
dp83640->version = PTP_CLASS_V2;
break;
default:
return -ERANGE;
}
txcfg0 = (dp83640->version & TX_PTP_VER_MASK) << TX_PTP_VER_SHIFT;
rxcfg0 = (dp83640->version & TX_PTP_VER_MASK) << TX_PTP_VER_SHIFT;
if (dp83640->layer & PTP_CLASS_L2) {
txcfg0 |= TX_L2_EN;
rxcfg0 |= RX_L2_EN;
}
if (dp83640->layer & PTP_CLASS_L4) {
txcfg0 |= TX_IPV6_EN | TX_IPV4_EN;
rxcfg0 |= RX_IPV6_EN | RX_IPV4_EN;
}
if (dp83640->hwts_tx_en)
txcfg0 |= TX_TS_EN;
if (dp83640->hwts_tx_en == HWTSTAMP_TX_ONESTEP_SYNC)
txcfg0 |= SYNC_1STEP | CHK_1STEP;
if (dp83640->hwts_rx_en)
rxcfg0 |= RX_TS_EN;
mutex_lock(&dp83640->clock->extreg_lock);
ext_write(0, phydev, PAGE5, PTP_TXCFG0, txcfg0);
ext_write(0, phydev, PAGE5, PTP_RXCFG0, rxcfg0);
mutex_unlock(&dp83640->clock->extreg_lock);
return copy_to_user(ifr->ifr_data, &cfg, sizeof(cfg)) ? -EFAULT : 0;
}
static void rx_timestamp_work(struct work_struct *work)
{
struct dp83640_private *dp83640 =
container_of(work, struct dp83640_private, ts_work.work);
struct sk_buff *skb;
/* Deliver expired packets. */
while ((skb = skb_dequeue(&dp83640->rx_queue))) {
struct dp83640_skb_info *skb_info;
skb_info = (struct dp83640_skb_info *)skb->cb;
if (!time_after(jiffies, skb_info->tmo)) {
skb_queue_head(&dp83640->rx_queue, skb);
break;
}
netif_rx_ni(skb);
}
if (!skb_queue_empty(&dp83640->rx_queue))
schedule_delayed_work(&dp83640->ts_work, SKB_TIMESTAMP_TIMEOUT);
}
static bool dp83640_rxtstamp(struct phy_device *phydev,
struct sk_buff *skb, int type)
{
struct dp83640_private *dp83640 = phydev->priv;
struct dp83640_skb_info *skb_info = (struct dp83640_skb_info *)skb->cb;
struct list_head *this, *next;
struct rxts *rxts;
struct skb_shared_hwtstamps *shhwtstamps = NULL;
unsigned long flags;
if (is_status_frame(skb, type)) {
decode_status_frame(dp83640, skb);
kfree_skb(skb);
return true;
}
if (!dp83640->hwts_rx_en)
return false;
if ((type & dp83640->version) == 0 || (type & dp83640->layer) == 0)
return false;
spin_lock_irqsave(&dp83640->rx_lock, flags);
prune_rx_ts(dp83640);
list_for_each_safe(this, next, &dp83640->rxts) {
rxts = list_entry(this, struct rxts, list);
if (match(skb, type, rxts)) {
shhwtstamps = skb_hwtstamps(skb);
memset(shhwtstamps, 0, sizeof(*shhwtstamps));
shhwtstamps->hwtstamp = ns_to_ktime(rxts->ns);
list_del_init(&rxts->list);
list_add(&rxts->list, &dp83640->rxpool);
break;
}
}
spin_unlock_irqrestore(&dp83640->rx_lock, flags);
if (!shhwtstamps) {
skb_info->ptp_type = type;
skb_info->tmo = jiffies + SKB_TIMESTAMP_TIMEOUT;
skb_queue_tail(&dp83640->rx_queue, skb);
schedule_delayed_work(&dp83640->ts_work, SKB_TIMESTAMP_TIMEOUT);
} else {
netif_rx_ni(skb);
}
return true;
}
static void dp83640_txtstamp(struct phy_device *phydev,
struct sk_buff *skb, int type)
{
struct dp83640_private *dp83640 = phydev->priv;
switch (dp83640->hwts_tx_en) {
case HWTSTAMP_TX_ONESTEP_SYNC:
if (is_sync(skb, type)) {
kfree_skb(skb);
return;
}
/* fall through */
case HWTSTAMP_TX_ON:
skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
skb_queue_tail(&dp83640->tx_queue, skb);
break;
case HWTSTAMP_TX_OFF:
default:
kfree_skb(skb);
break;
}
}
static int dp83640_ts_info(struct phy_device *dev, struct ethtool_ts_info *info)
{
struct dp83640_private *dp83640 = dev->priv;
info->so_timestamping =
SOF_TIMESTAMPING_TX_HARDWARE |
SOF_TIMESTAMPING_RX_HARDWARE |
SOF_TIMESTAMPING_RAW_HARDWARE;
info->phc_index = ptp_clock_index(dp83640->clock->ptp_clock);
info->tx_types =
(1 << HWTSTAMP_TX_OFF) |
(1 << HWTSTAMP_TX_ON) |
(1 << HWTSTAMP_TX_ONESTEP_SYNC);
info->rx_filters =
(1 << HWTSTAMP_FILTER_NONE) |
(1 << HWTSTAMP_FILTER_PTP_V1_L4_EVENT) |
(1 << HWTSTAMP_FILTER_PTP_V2_L4_EVENT) |
(1 << HWTSTAMP_FILTER_PTP_V2_L2_EVENT) |
(1 << HWTSTAMP_FILTER_PTP_V2_EVENT);
return 0;
}
static struct phy_driver dp83640_driver = {
.phy_id = DP83640_PHY_ID,
.phy_id_mask = 0xfffffff0,
.name = "NatSemi DP83640",
.features = PHY_BASIC_FEATURES,
.flags = PHY_HAS_INTERRUPT,
.probe = dp83640_probe,
.remove = dp83640_remove,
.soft_reset = dp83640_soft_reset,
.config_init = dp83640_config_init,
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.ack_interrupt = dp83640_ack_interrupt,
.config_intr = dp83640_config_intr,
.ts_info = dp83640_ts_info,
.hwtstamp = dp83640_hwtstamp,
.rxtstamp = dp83640_rxtstamp,
.txtstamp = dp83640_txtstamp,
};
static int __init dp83640_init(void)
{
return phy_driver_register(&dp83640_driver, THIS_MODULE);
}
static void __exit dp83640_exit(void)
{
dp83640_free_clocks();
phy_driver_unregister(&dp83640_driver);
}
MODULE_DESCRIPTION("National Semiconductor DP83640 PHY driver");
MODULE_AUTHOR("Richard Cochran <[email protected]>");
MODULE_LICENSE("GPL");
module_init(dp83640_init);
module_exit(dp83640_exit);
static struct mdio_device_id __maybe_unused dp83640_tbl[] = {
{ DP83640_PHY_ID, 0xfffffff0 },
{ }
};
MODULE_DEVICE_TABLE(mdio, dp83640_tbl);
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/sagemaker/model/ImageConfig.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SageMaker
{
namespace Model
{
ImageConfig::ImageConfig() :
m_repositoryAccessMode(RepositoryAccessMode::NOT_SET),
m_repositoryAccessModeHasBeenSet(false)
{
}
ImageConfig::ImageConfig(JsonView jsonValue) :
m_repositoryAccessMode(RepositoryAccessMode::NOT_SET),
m_repositoryAccessModeHasBeenSet(false)
{
*this = jsonValue;
}
ImageConfig& ImageConfig::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("RepositoryAccessMode"))
{
m_repositoryAccessMode = RepositoryAccessModeMapper::GetRepositoryAccessModeForName(jsonValue.GetString("RepositoryAccessMode"));
m_repositoryAccessModeHasBeenSet = true;
}
return *this;
}
JsonValue ImageConfig::Jsonize() const
{
JsonValue payload;
if(m_repositoryAccessModeHasBeenSet)
{
payload.WithString("RepositoryAccessMode", RepositoryAccessModeMapper::GetNameForRepositoryAccessMode(m_repositoryAccessMode));
}
return payload;
}
} // namespace Model
} // namespace SageMaker
} // namespace Aws
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2000-2006 Silicon Graphics, Inc.
* All Rights Reserved.
*
* 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.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_inode_item.h"
#include "xfs_bmap.h"
#include "xfs_itable.h"
#include "xfs_dfrag.h"
#include "xfs_error.h"
#include "xfs_vnodeops.h"
#include "xfs_trace.h"
static int xfs_swap_extents(
xfs_inode_t *ip, /* target inode */
xfs_inode_t *tip, /* tmp inode */
xfs_swapext_t *sxp);
/*
* ioctl interface for swapext
*/
int
xfs_swapext(
xfs_swapext_t *sxp)
{
xfs_inode_t *ip, *tip;
struct file *file, *tmp_file;
int error = 0;
/* Pull information for the target fd */
file = fget((int)sxp->sx_fdtarget);
if (!file) {
error = XFS_ERROR(EINVAL);
goto out;
}
if (!(file->f_mode & FMODE_WRITE) ||
!(file->f_mode & FMODE_READ) ||
(file->f_flags & O_APPEND)) {
error = XFS_ERROR(EBADF);
goto out_put_file;
}
tmp_file = fget((int)sxp->sx_fdtmp);
if (!tmp_file) {
error = XFS_ERROR(EINVAL);
goto out_put_file;
}
if (!(tmp_file->f_mode & FMODE_WRITE) ||
!(tmp_file->f_mode & FMODE_READ) ||
(tmp_file->f_flags & O_APPEND)) {
error = XFS_ERROR(EBADF);
goto out_put_tmp_file;
}
if (IS_SWAPFILE(file->f_path.dentry->d_inode) ||
IS_SWAPFILE(tmp_file->f_path.dentry->d_inode)) {
error = XFS_ERROR(EINVAL);
goto out_put_tmp_file;
}
ip = XFS_I(file->f_path.dentry->d_inode);
tip = XFS_I(tmp_file->f_path.dentry->d_inode);
if (ip->i_mount != tip->i_mount) {
error = XFS_ERROR(EINVAL);
goto out_put_tmp_file;
}
if (ip->i_ino == tip->i_ino) {
error = XFS_ERROR(EINVAL);
goto out_put_tmp_file;
}
if (XFS_FORCED_SHUTDOWN(ip->i_mount)) {
error = XFS_ERROR(EIO);
goto out_put_tmp_file;
}
error = xfs_swap_extents(ip, tip, sxp);
out_put_tmp_file:
fput(tmp_file);
out_put_file:
fput(file);
out:
return error;
}
/*
* We need to check that the format of the data fork in the temporary inode is
* valid for the target inode before doing the swap. This is not a problem with
* attr1 because of the fixed fork offset, but attr2 has a dynamically sized
* data fork depending on the space the attribute fork is taking so we can get
* invalid formats on the target inode.
*
* E.g. target has space for 7 extents in extent format, temp inode only has
* space for 6. If we defragment down to 7 extents, then the tmp format is a
* btree, but when swapped it needs to be in extent format. Hence we can't just
* blindly swap data forks on attr2 filesystems.
*
* Note that we check the swap in both directions so that we don't end up with
* a corrupt temporary inode, either.
*
* Note that fixing the way xfs_fsr sets up the attribute fork in the source
* inode will prevent this situation from occurring, so all we do here is
* reject and log the attempt. basically we are putting the responsibility on
* userspace to get this right.
*/
static int
xfs_swap_extents_check_format(
xfs_inode_t *ip, /* target inode */
xfs_inode_t *tip) /* tmp inode */
{
/* Should never get a local format */
if (ip->i_d.di_format == XFS_DINODE_FMT_LOCAL ||
tip->i_d.di_format == XFS_DINODE_FMT_LOCAL)
return EINVAL;
/*
* if the target inode has less extents that then temporary inode then
* why did userspace call us?
*/
if (ip->i_d.di_nextents < tip->i_d.di_nextents)
return EINVAL;
/*
* if the target inode is in extent form and the temp inode is in btree
* form then we will end up with the target inode in the wrong format
* as we already know there are less extents in the temp inode.
*/
if (ip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
tip->i_d.di_format == XFS_DINODE_FMT_BTREE)
return EINVAL;
/* Check temp in extent form to max in target */
if (tip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_NEXTENTS(tip, XFS_DATA_FORK) >
XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
return EINVAL;
/* Check target in extent form to max in temp */
if (ip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_NEXTENTS(ip, XFS_DATA_FORK) >
XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
return EINVAL;
/*
* If we are in a btree format, check that the temp root block will fit
* in the target and that it has enough extents to be in btree format
* in the target.
*
* Note that we have to be careful to allow btree->extent conversions
* (a common defrag case) which will occur when the temp inode is in
* extent format...
*/
if (tip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
if (XFS_IFORK_BOFF(ip) &&
tip->i_df.if_broot_bytes > XFS_IFORK_BOFF(ip))
return EINVAL;
if (XFS_IFORK_NEXTENTS(tip, XFS_DATA_FORK) <=
XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
return EINVAL;
}
/* Reciprocal target->temp btree format checks */
if (ip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
if (XFS_IFORK_BOFF(tip) &&
ip->i_df.if_broot_bytes > XFS_IFORK_BOFF(tip))
return EINVAL;
if (XFS_IFORK_NEXTENTS(ip, XFS_DATA_FORK) <=
XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
return EINVAL;
}
return 0;
}
static int
xfs_swap_extents(
xfs_inode_t *ip, /* target inode */
xfs_inode_t *tip, /* tmp inode */
xfs_swapext_t *sxp)
{
xfs_mount_t *mp = ip->i_mount;
xfs_trans_t *tp;
xfs_bstat_t *sbp = &sxp->sx_stat;
xfs_ifork_t *tempifp, *ifp, *tifp;
int src_log_flags, target_log_flags;
int error = 0;
int aforkblks = 0;
int taforkblks = 0;
__uint64_t tmp;
tempifp = kmem_alloc(sizeof(xfs_ifork_t), KM_MAYFAIL);
if (!tempifp) {
error = XFS_ERROR(ENOMEM);
goto out;
}
/*
* we have to do two separate lock calls here to keep lockdep
* happy. If we try to get all the locks in one call, lock will
* report false positives when we drop the ILOCK and regain them
* below.
*/
xfs_lock_two_inodes(ip, tip, XFS_IOLOCK_EXCL);
xfs_lock_two_inodes(ip, tip, XFS_ILOCK_EXCL);
/* Verify that both files have the same format */
if ((ip->i_d.di_mode & S_IFMT) != (tip->i_d.di_mode & S_IFMT)) {
error = XFS_ERROR(EINVAL);
goto out_unlock;
}
/* Verify both files are either real-time or non-realtime */
if (XFS_IS_REALTIME_INODE(ip) != XFS_IS_REALTIME_INODE(tip)) {
error = XFS_ERROR(EINVAL);
goto out_unlock;
}
if (VN_CACHED(VFS_I(tip)) != 0) {
error = xfs_flushinval_pages(tip, 0, -1,
FI_REMAPF_LOCKED);
if (error)
goto out_unlock;
}
/* Verify O_DIRECT for ftmp */
if (VN_CACHED(VFS_I(tip)) != 0) {
error = XFS_ERROR(EINVAL);
goto out_unlock;
}
/* Verify all data are being swapped */
if (sxp->sx_offset != 0 ||
sxp->sx_length != ip->i_d.di_size ||
sxp->sx_length != tip->i_d.di_size) {
error = XFS_ERROR(EFAULT);
goto out_unlock;
}
trace_xfs_swap_extent_before(ip, 0);
trace_xfs_swap_extent_before(tip, 1);
/* check inode formats now that data is flushed */
error = xfs_swap_extents_check_format(ip, tip);
if (error) {
xfs_notice(mp,
"%s: inode 0x%llx format is incompatible for exchanging.",
__func__, ip->i_ino);
goto out_unlock;
}
/*
* Compare the current change & modify times with that
* passed in. If they differ, we abort this swap.
* This is the mechanism used to ensure the calling
* process that the file was not changed out from
* under it.
*/
if ((sbp->bs_ctime.tv_sec != VFS_I(ip)->i_ctime.tv_sec) ||
(sbp->bs_ctime.tv_nsec != VFS_I(ip)->i_ctime.tv_nsec) ||
(sbp->bs_mtime.tv_sec != VFS_I(ip)->i_mtime.tv_sec) ||
(sbp->bs_mtime.tv_nsec != VFS_I(ip)->i_mtime.tv_nsec)) {
error = XFS_ERROR(EBUSY);
goto out_unlock;
}
/* We need to fail if the file is memory mapped. Once we have tossed
* all existing pages, the page fault will have no option
* but to go to the filesystem for pages. By making the page fault call
* vop_read (or write in the case of autogrow) they block on the iolock
* until we have switched the extents.
*/
if (VN_MAPPED(VFS_I(ip))) {
error = XFS_ERROR(EBUSY);
goto out_unlock;
}
xfs_iunlock(ip, XFS_ILOCK_EXCL);
xfs_iunlock(tip, XFS_ILOCK_EXCL);
/*
* There is a race condition here since we gave up the
* ilock. However, the data fork will not change since
* we have the iolock (locked for truncation too) so we
* are safe. We don't really care if non-io related
* fields change.
*/
xfs_tosspages(ip, 0, -1, FI_REMAPF);
tp = xfs_trans_alloc(mp, XFS_TRANS_SWAPEXT);
if ((error = xfs_trans_reserve(tp, 0,
XFS_ICHANGE_LOG_RES(mp), 0,
0, 0))) {
xfs_iunlock(ip, XFS_IOLOCK_EXCL);
xfs_iunlock(tip, XFS_IOLOCK_EXCL);
xfs_trans_cancel(tp, 0);
goto out;
}
xfs_lock_two_inodes(ip, tip, XFS_ILOCK_EXCL);
/*
* Count the number of extended attribute blocks
*/
if ( ((XFS_IFORK_Q(ip) != 0) && (ip->i_d.di_anextents > 0)) &&
(ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)) {
error = xfs_bmap_count_blocks(tp, ip, XFS_ATTR_FORK, &aforkblks);
if (error)
goto out_trans_cancel;
}
if ( ((XFS_IFORK_Q(tip) != 0) && (tip->i_d.di_anextents > 0)) &&
(tip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)) {
error = xfs_bmap_count_blocks(tp, tip, XFS_ATTR_FORK,
&taforkblks);
if (error)
goto out_trans_cancel;
}
/*
* Swap the data forks of the inodes
*/
ifp = &ip->i_df;
tifp = &tip->i_df;
*tempifp = *ifp; /* struct copy */
*ifp = *tifp; /* struct copy */
*tifp = *tempifp; /* struct copy */
/*
* Fix the on-disk inode values
*/
tmp = (__uint64_t)ip->i_d.di_nblocks;
ip->i_d.di_nblocks = tip->i_d.di_nblocks - taforkblks + aforkblks;
tip->i_d.di_nblocks = tmp + taforkblks - aforkblks;
tmp = (__uint64_t) ip->i_d.di_nextents;
ip->i_d.di_nextents = tip->i_d.di_nextents;
tip->i_d.di_nextents = tmp;
tmp = (__uint64_t) ip->i_d.di_format;
ip->i_d.di_format = tip->i_d.di_format;
tip->i_d.di_format = tmp;
/*
* The extents in the source inode could still contain speculative
* preallocation beyond EOF (e.g. the file is open but not modified
* while defrag is in progress). In that case, we need to copy over the
* number of delalloc blocks the data fork in the source inode is
* tracking beyond EOF so that when the fork is truncated away when the
* temporary inode is unlinked we don't underrun the i_delayed_blks
* counter on that inode.
*/
ASSERT(tip->i_delayed_blks == 0);
tip->i_delayed_blks = ip->i_delayed_blks;
ip->i_delayed_blks = 0;
src_log_flags = XFS_ILOG_CORE;
switch (ip->i_d.di_format) {
case XFS_DINODE_FMT_EXTENTS:
/* If the extents fit in the inode, fix the
* pointer. Otherwise it's already NULL or
* pointing to the extent.
*/
if (ip->i_d.di_nextents <= XFS_INLINE_EXTS) {
ifp->if_u1.if_extents =
ifp->if_u2.if_inline_ext;
}
src_log_flags |= XFS_ILOG_DEXT;
break;
case XFS_DINODE_FMT_BTREE:
src_log_flags |= XFS_ILOG_DBROOT;
break;
}
target_log_flags = XFS_ILOG_CORE;
switch (tip->i_d.di_format) {
case XFS_DINODE_FMT_EXTENTS:
/* If the extents fit in the inode, fix the
* pointer. Otherwise it's already NULL or
* pointing to the extent.
*/
if (tip->i_d.di_nextents <= XFS_INLINE_EXTS) {
tifp->if_u1.if_extents =
tifp->if_u2.if_inline_ext;
}
target_log_flags |= XFS_ILOG_DEXT;
break;
case XFS_DINODE_FMT_BTREE:
target_log_flags |= XFS_ILOG_DBROOT;
break;
}
xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
xfs_trans_ijoin(tp, tip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
xfs_trans_log_inode(tp, ip, src_log_flags);
xfs_trans_log_inode(tp, tip, target_log_flags);
/*
* If this is a synchronous mount, make sure that the
* transaction goes to disk before returning to the user.
*/
if (mp->m_flags & XFS_MOUNT_WSYNC)
xfs_trans_set_sync(tp);
error = xfs_trans_commit(tp, 0);
trace_xfs_swap_extent_after(ip, 0);
trace_xfs_swap_extent_after(tip, 1);
out:
kmem_free(tempifp);
return error;
out_unlock:
xfs_iunlock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
xfs_iunlock(tip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
goto out;
out_trans_cancel:
xfs_trans_cancel(tp, 0);
goto out_unlock;
}
| {
"pile_set_name": "Github"
} |
[libui](README.md) / [uiMainStep](ui-main-step.md)
# uiMainStep
`fun uiMainStep(wait: Int): Int` | {
"pile_set_name": "Github"
} |
{-# OPTIONS_GHC -Wno-orphans #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Apecs.Components where
import Data.Functor.Identity
import Apecs.Core
import qualified Apecs.THTuples as T
-- | Identity component. @Identity c@ is equivalent to @c@, so mostly useless.
instance Component c => Component (Identity c) where
type Storage (Identity c) = Identity (Storage c)
instance Has w m c => Has w m (Identity c) where
{-# INLINE getStore #-}
getStore = Identity <$> getStore
type instance Elem (Identity s) = Identity (Elem s)
instance ExplGet m s => ExplGet m (Identity s) where
{-# INLINE explGet #-}
explGet (Identity s) e = Identity <$> explGet s e
{-# INLINE explExists #-}
explExists (Identity s) = explExists s
instance ExplSet m s => ExplSet m (Identity s) where
{-# INLINE explSet #-}
explSet (Identity s) e (Identity x) = explSet s e x
instance ExplMembers m s => ExplMembers m (Identity s) where
{-# INLINE explMembers #-}
explMembers (Identity s) = explMembers s
instance ExplDestroy m s => ExplDestroy m (Identity s) where
{-# INLINE explDestroy #-}
explDestroy (Identity s) = explDestroy s
T.makeInstances [2..8]
-- | Pseudocomponent indicating the absence of @a@.
-- Mainly used as e.g. @cmap $ \(a, Not b) -> c@ to iterate over entities with an @a@ but no @b@.
-- Can also be used to delete components, like @cmap $ \a -> (Not :: Not a)@ to delete every @a@ component.
data Not a = Not
-- | Pseudostore used to produce values of type @Not a@, inverts @explExists@, and destroys instead of @explSet@.
newtype NotStore s = NotStore s
instance Component c => Component (Not c) where
type Storage (Not c) = NotStore (Storage c)
instance (Has w m c) => Has w m (Not c) where
{-# INLINE getStore #-}
getStore = NotStore <$> getStore
type instance Elem (NotStore s) = Not (Elem s)
instance ExplGet m s => ExplGet m (NotStore s) where
{-# INLINE explGet #-}
explGet _ _ = return Not
{-# INLINE explExists #-}
explExists (NotStore sa) ety = not <$> explExists sa ety
instance ExplDestroy m s => ExplSet m (NotStore s) where
{-# INLINE explSet #-}
explSet (NotStore sa) ety _ = explDestroy sa ety
-- | Pseudostore used to produce values of type @Maybe a@.
-- Will always return @True@ for @explExists@.
-- Writing can both set and delete a component using @Just@ and @Nothing@ respectively.
newtype MaybeStore s = MaybeStore s
instance Component c => Component (Maybe c) where
type Storage (Maybe c) = MaybeStore (Storage c)
instance (Has w m c) => Has w m (Maybe c) where
{-# INLINE getStore #-}
getStore = MaybeStore <$> getStore
type instance Elem (MaybeStore s) = Maybe (Elem s)
instance ExplGet m s => ExplGet m (MaybeStore s) where
{-# INLINE explGet #-}
explGet (MaybeStore sa) ety = do
e <- explExists sa ety
if e then Just <$> explGet sa ety
else return Nothing
explExists _ _ = return True
instance (ExplDestroy m s, ExplSet m s) => ExplSet m (MaybeStore s) where
{-# INLINE explSet #-}
explSet (MaybeStore sa) ety Nothing = explDestroy sa ety
explSet (MaybeStore sa) ety (Just x) = explSet sa ety x
-- | Used for 'Either', a logical disjunction between two components.
-- As expected, Either is used to model error values.
-- Getting an @Either a b@ will first attempt to get a @b@ and return it as @Right b@, or if it does not exist, get an @a@ as @Left a@.
-- Can also be used to set one of two things.
data EitherStore sa sb = EitherStore sa sb
instance (Component ca, Component cb) => Component (Either ca cb) where
type Storage (Either ca cb) = EitherStore (Storage ca) (Storage cb)
instance (Has w m ca, Has w m cb) => Has w m (Either ca cb) where
{-# INLINE getStore #-}
getStore = EitherStore <$> getStore <*> getStore
type instance Elem (EitherStore sa sb) = Either (Elem sa) (Elem sb)
instance (ExplGet m sa, ExplGet m sb) => ExplGet m (EitherStore sa sb) where
{-# INLINE explGet #-}
explGet (EitherStore sa sb) ety = do
e <- explExists sb ety
if e then Right <$> explGet sb ety
else Left <$> explGet sa ety
{-# INLINE explExists #-}
explExists (EitherStore sa sb) ety = do
e <- explExists sb ety
if e then return True
else explExists sa ety
instance (ExplSet m sa, ExplSet m sb) => ExplSet m (EitherStore sa sb) where
{-# INLINE explSet #-}
explSet (EitherStore _ sb) ety (Right b) = explSet sb ety b
explSet (EitherStore sa _) ety (Left a) = explSet sa ety a
instance (ExplDestroy m sa, ExplDestroy m sb)
=> ExplDestroy m (EitherStore sa sb) where
{-# INLINE explDestroy #-}
explDestroy (EitherStore sa sb) ety =
explDestroy sa ety >> explDestroy sb ety
-- Unit instances ()
instance Monad m => Has w m () where
{-# INLINE getStore #-}
getStore = return ()
instance Component () where
type Storage () = ()
type instance Elem () = ()
instance Monad m => ExplGet m () where
{-# INLINE explExists #-}
explExists _ _ = return True
{-# INLINE explGet #-}
explGet _ _ = return ()
instance Monad m => ExplSet m () where
{-# INLINE explSet #-}
explSet _ _ _ = return ()
instance Monad m => ExplDestroy m () where
{-# INLINE explDestroy #-}
explDestroy _ _ = return ()
-- | Pseudocomponent that functions normally for @explExists@ and @explMembers@, but always return @Filter@ for @explGet@.
-- Can be used in cmap as @cmap $ \(Filter :: Filter a) -> b@.
-- Since the above can be written more consicely as @cmap $ \(_ :: a) -> b@, it is rarely directly.
-- More interestingly, we can define reusable filters like @movables = Filter :: Filter (Position, Velocity)@.
-- Note that 'Filter c' is equivalent to 'Not (Not c)'.
data Filter c = Filter deriving (Eq, Show)
-- Pseudostore for 'Filter'.
newtype FilterStore s = FilterStore s
instance Component c => Component (Filter c) where
type Storage (Filter c) = FilterStore (Storage c)
instance Has w m c => Has w m (Filter c) where
{-# INLINE getStore #-}
getStore = FilterStore <$> getStore
type instance Elem (FilterStore s) = Filter (Elem s)
instance ExplGet m s => ExplGet m (FilterStore s) where
{-# INLINE explGet #-}
explGet _ _ = return Filter
{-# INLINE explExists #-}
explExists (FilterStore s) ety = explExists s ety
instance ExplMembers m s => ExplMembers m (FilterStore s) where
{-# INLINE explMembers #-}
explMembers (FilterStore s) = explMembers s
-- | Pseudostore used to produce components of type 'Entity'.
-- Always returns @True@ for @explExists@, and echoes back the entity argument for @explGet@.
-- Used in e.g. @cmap $ \(a, ety :: Entity) -> b@ to access the current entity.
data EntityStore = EntityStore
instance Component Entity where
type Storage Entity = EntityStore
instance Monad m => Has w m Entity where
{-# INLINE getStore #-}
getStore = return EntityStore
type instance Elem EntityStore = Entity
instance Monad m => ExplGet m EntityStore where
{-# INLINE explGet #-}
explGet _ ety = return $ Entity ety
{-# INLINE explExists #-}
explExists _ _ = return True
| {
"pile_set_name": "Github"
} |
[Desktop Entry]
Encoding=UTF-8
Type=Directory
Name=Card Games
Icon=applications-games-card
#TRANSLATIONS_DIR=translations
# Translations
Name[uz@cyrillic]=Қарта ўйинлари
| {
"pile_set_name": "Github"
} |
<!--
~ Changes to this file committed after and not including commit-id: ccc0d2c5f9a5ac661e60e6eaf138de7889928b8b
~ are released under the following license:
~
~ This file is part of Hopsworks
~ Copyright (C) 2018, Logical Clocks AB. All rights reserved
~
~ Hopsworks is free software: you can redistribute it and/or modify it under the terms of
~ the GNU Affero General Public License as published by the Free Software Foundation,
~ either version 3 of the License, or (at your option) any later version.
~
~ Hopsworks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
~ without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
~ PURPOSE. See the GNU Affero General Public License for more details.
~
~ You should have received a copy of the GNU Affero General Public License along with this program.
~ If not, see <https://www.gnu.org/licenses/>.
~
~ Changes to this file committed before and including commit-id: ccc0d2c5f9a5ac661e60e6eaf138de7889928b8b
~ are released under the following license:
~
~ Copyright (C) 2013 - 2018, Logical Clocks AB and RISE SICS AB. All rights reserved
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy of this
~ software and associated documentation files (the "Software"), to deal in the Software
~ without restriction, including without limitation the rights to use, copy, modify, merge,
~ publish, distribute, sublicense, and/or sell copies of the Software, and to permit
~ persons to whom the Software is furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in all copies or
~ substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
~ BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
~ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
~ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<div class="modal-header">
<button class="close" ng-click="projectCreatorCtrl.close()" data-dismiss="modal" aria-hidden="true"
type="button">×</button>
<h2 class="modal-title">New project</h2>
</div>
<div class="modal-body">
<div growl reference="1" class="pull-right" ></div>
<form role="form" name="projectForm" ng-submit="projectCreatorCtrl.createProject()" novalidate class="form-validate">
<div class="row">
<div class="col-md-8">
<fieldset>
<div class="control-group" flex>
<label for="projectname" style="color: black;">Name</label>
<md-input-container style="height: 50px" class="md-block">
<input name="project_name" type="text" id="projectname"
ng-model="projectCreatorCtrl.projectName" tabindex="1"
ng-pattern="projectCreatorCtrl.projectNameValidator.regex"
autofocus="autofocus"
ng-maxlength="88"
required >
</md-input-container>
<span ng-show="(projectForm.$submitted || projectForm.project_name.$dirty) && projectForm.project_name.$error.required"
class="text-danger ng-hide">This field is required</span>
<span ng-show="(projectForm.project_name.$dirty) && projectForm.project_name.$error.pattern"
class="text-danger ng-hide">Invalid project name. Project name can only contain characters a-z,
A-Z, 0-9 and special characters '_, .' but not '__' (double underscore). Go to
<a target="_blank" rel="noopener noreferrer"
href="https://hopsworks.readthedocs.io/en/{{hopsworksDocVersion}}/user_guide/hopsworks/newProject.html">
Documentation</a> to see additional reserved words.</span>
<span ng-show="(projectForm.project_name.$dirty) && projectForm.project_name.$error.maxlength"
class="text-danger ng-hide">Project name shouldn't be longer than 88 characters.</span>
<p></p>
<label for="projectname" class="control-label">Description</label>
<div class="controls">
<textarea class="form-control" style="resize:none;" ng-model="projectCreatorCtrl.projectDesc"
rows="3" tabindex="2"></textarea>
</div>
</div>
</fieldset>
</div>
<div class="col-md-4">
<h3>Services</h3>
<fieldset class="standard">
<div class="control-group col-md-offset-2" flex>
<div class="row" ng-repeat="projectType in projectCreatorCtrl.projectTypes">
<md-checkbox class="md-primary"
ng-checked="projectCreatorCtrl.exists(projectType)"
ng-click="projectCreatorCtrl.addSelected(projectType)"
aria-label="projectType"
tabindex="{{$index}}"
id="{{projectType}}">
{{ projectType}}
</md-checkbox>
</div>
</div>
</fieldset>
</div>
</div>
<div>
<label class="text-muted">
You can still create {{projectCreatorCtrl.user.maxNumProjects - projectCreatorCtrl.user.numCreatedProjects}}
project (s)
</label>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" ng-click="projectCreatorCtrl.close()" tabindex="5">Cancel</button>
<button class="btn btn-primary" type="submit"
ng-disabled="projectForm.project_name.$error.required
|| projectCreatorCtrl.working
|| projectForm.project_name.$error.pattern
|| projectForm.project_name.$error.maxlength" tabindex="6">
<i ng-if="projectCreatorCtrl.working" style="margin-top: 2px" class="fa fa-spinner fa-spin pull-right" ></i>
Create
</button>
</div>
</form>
</div>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
#include <types.h>
#include <unistd.h>
#include <ulib.h>
#include <spipe.h>
#define SPIPE_SIZE 4096
#define SPIPE_BUFSIZE (SPIPE_SIZE - sizeof(__spipe_state_t))
static bool __spipeisclosed_nolock(spipe_t * p, bool read);
int spipe(spipe_t * p)
{
static_assert(SPIPE_SIZE > SPIPE_BUFSIZE);
int ret;
sem_t spipe_sem;
uintptr_t addr = 0;
if ((ret = shmem(&addr, SPIPE_SIZE, MMAP_WRITE)) != 0) {
goto failed;
}
if ((spipe_sem = sem_init(1)) < 0) {
goto failed_cleanup_mem;
}
p->isclosed = 0;
p->spipe_sem = spipe_sem;
p->addr = addr;
p->state = (__spipe_state_t *) addr;
p->buf = (uint8_t *) (p->state + 1);
p->state->p_rpos = p->state->p_wpos = 0;
p->state->isclosed = 0;
out:
return ret;
failed_cleanup_mem:
munmap(addr, SPIPE_BUFSIZE);
failed:
goto out;
}
size_t spiperead(spipe_t * p, void *buf, size_t n)
{
size_t ret = 0;
__spipe_state_t *state = p->state;
try_again:
if (p->isclosed || sem_wait(p->spipe_sem) != 0) {
goto out;
}
if (__spipeisclosed_nolock(p, 1)) {
goto out_unlock;
}
if (state->p_rpos == state->p_wpos) {
sem_post(p->spipe_sem);
yield();
goto try_again;
}
for (; ret < n; ret++, state->p_rpos++) {
if (state->p_rpos == state->p_wpos) {
break;
}
*(uint8_t *) (buf + ret) =
p->buf[state->p_rpos % SPIPE_BUFSIZE];
}
out_unlock:
sem_post(p->spipe_sem);
out:
return ret;
}
size_t spipewrite(spipe_t * p, void *buf, size_t n)
{
size_t ret = 0;
__spipe_state_t *state = p->state;
try_again:
if (p->isclosed || sem_wait(p->spipe_sem) != 0) {
goto out;
}
if (__spipeisclosed_nolock(p, 0)) {
goto out_unlock;
}
for (; ret < n; ret++, state->p_wpos++) {
if (state->p_wpos - state->p_rpos >= SPIPE_BUFSIZE) {
sem_post(p->spipe_sem);
yield();
goto try_again;
}
p->buf[state->p_wpos % SPIPE_BUFSIZE] =
*(uint8_t *) (buf + ret);
}
out_unlock:
sem_post(p->spipe_sem);
out:
return ret;
}
static int __spipeclose_nolock(spipe_t * p)
{
if (!p->isclosed) {
p->isclosed = p->state->isclosed = 1;
munmap(p->addr, SPIPE_BUFSIZE);
return 0;
}
return -1;
}
int spipeclose(spipe_t * p)
{
if (!p->isclosed) {
int ret;
sem_wait(p->spipe_sem);
ret = __spipeclose_nolock(p);
sem_post(p->spipe_sem);
return ret;
}
return -1;
}
static bool __spipeisclosed_nolock(spipe_t * p, bool read)
{
if (!p->isclosed) {
if (!p->state->isclosed) {
return 0;
}
if (p->state->p_rpos < p->state->p_wpos) {
return !read;
}
__spipeclose_nolock(p);
}
return 1;
}
bool spipeisclosed(spipe_t * p)
{
if (!p->isclosed) {
bool isclosed;
sem_wait(p->spipe_sem);
isclosed = __spipeisclosed_nolock(p, 0);
sem_post(p->spipe_sem);
return isclosed;
}
return 1;
}
| {
"pile_set_name": "Github"
} |
/*
* HDMI Channel map support helpers
*/
#include <linux/module.h>
#include <sound/control.h>
#include <sound/tlv.h>
#include <sound/hda_chmap.h>
/*
* CEA speaker placement:
*
* FLH FCH FRH
* FLW FL FLC FC FRC FR FRW
*
* LFE
* TC
*
* RL RLC RC RRC RR
*
* The Left/Right Surround channel _notions_ LS/RS in SMPTE 320M corresponds to
* CEA RL/RR; The SMPTE channel _assignment_ C/LFE is swapped to CEA LFE/FC.
*/
enum cea_speaker_placement {
FL = (1 << 0), /* Front Left */
FC = (1 << 1), /* Front Center */
FR = (1 << 2), /* Front Right */
FLC = (1 << 3), /* Front Left Center */
FRC = (1 << 4), /* Front Right Center */
RL = (1 << 5), /* Rear Left */
RC = (1 << 6), /* Rear Center */
RR = (1 << 7), /* Rear Right */
RLC = (1 << 8), /* Rear Left Center */
RRC = (1 << 9), /* Rear Right Center */
LFE = (1 << 10), /* Low Frequency Effect */
FLW = (1 << 11), /* Front Left Wide */
FRW = (1 << 12), /* Front Right Wide */
FLH = (1 << 13), /* Front Left High */
FCH = (1 << 14), /* Front Center High */
FRH = (1 << 15), /* Front Right High */
TC = (1 << 16), /* Top Center */
};
static const char * const cea_speaker_allocation_names[] = {
/* 0 */ "FL/FR",
/* 1 */ "LFE",
/* 2 */ "FC",
/* 3 */ "RL/RR",
/* 4 */ "RC",
/* 5 */ "FLC/FRC",
/* 6 */ "RLC/RRC",
/* 7 */ "FLW/FRW",
/* 8 */ "FLH/FRH",
/* 9 */ "TC",
/* 10 */ "FCH",
};
/*
* ELD SA bits in the CEA Speaker Allocation data block
*/
static int eld_speaker_allocation_bits[] = {
[0] = FL | FR,
[1] = LFE,
[2] = FC,
[3] = RL | RR,
[4] = RC,
[5] = FLC | FRC,
[6] = RLC | RRC,
/* the following are not defined in ELD yet */
[7] = FLW | FRW,
[8] = FLH | FRH,
[9] = TC,
[10] = FCH,
};
/*
* ALSA sequence is:
*
* surround40 surround41 surround50 surround51 surround71
* ch0 front left = = = =
* ch1 front right = = = =
* ch2 rear left = = = =
* ch3 rear right = = = =
* ch4 LFE center center center
* ch5 LFE LFE
* ch6 side left
* ch7 side right
*
* surround71 = {FL, FR, RLC, RRC, FC, LFE, RL, RR}
*/
static int hdmi_channel_mapping[0x32][8] = {
/* stereo */
[0x00] = { 0x00, 0x11, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7 },
/* 2.1 */
[0x01] = { 0x00, 0x11, 0x22, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7 },
/* Dolby Surround */
[0x02] = { 0x00, 0x11, 0x23, 0xf2, 0xf4, 0xf5, 0xf6, 0xf7 },
/* surround40 */
[0x08] = { 0x00, 0x11, 0x24, 0x35, 0xf3, 0xf2, 0xf6, 0xf7 },
/* 4ch */
[0x03] = { 0x00, 0x11, 0x23, 0x32, 0x44, 0xf5, 0xf6, 0xf7 },
/* surround41 */
[0x09] = { 0x00, 0x11, 0x24, 0x35, 0x42, 0xf3, 0xf6, 0xf7 },
/* surround50 */
[0x0a] = { 0x00, 0x11, 0x24, 0x35, 0x43, 0xf2, 0xf6, 0xf7 },
/* surround51 */
[0x0b] = { 0x00, 0x11, 0x24, 0x35, 0x43, 0x52, 0xf6, 0xf7 },
/* 7.1 */
[0x13] = { 0x00, 0x11, 0x26, 0x37, 0x43, 0x52, 0x64, 0x75 },
};
/*
* This is an ordered list!
*
* The preceding ones have better chances to be selected by
* hdmi_channel_allocation().
*/
static struct hdac_cea_channel_speaker_allocation channel_allocations[] = {
/* channel: 7 6 5 4 3 2 1 0 */
{ .ca_index = 0x00, .speakers = { 0, 0, 0, 0, 0, 0, FR, FL } },
/* 2.1 */
{ .ca_index = 0x01, .speakers = { 0, 0, 0, 0, 0, LFE, FR, FL } },
/* Dolby Surround */
{ .ca_index = 0x02, .speakers = { 0, 0, 0, 0, FC, 0, FR, FL } },
/* surround40 */
{ .ca_index = 0x08, .speakers = { 0, 0, RR, RL, 0, 0, FR, FL } },
/* surround41 */
{ .ca_index = 0x09, .speakers = { 0, 0, RR, RL, 0, LFE, FR, FL } },
/* surround50 */
{ .ca_index = 0x0a, .speakers = { 0, 0, RR, RL, FC, 0, FR, FL } },
/* surround51 */
{ .ca_index = 0x0b, .speakers = { 0, 0, RR, RL, FC, LFE, FR, FL } },
/* 6.1 */
{ .ca_index = 0x0f, .speakers = { 0, RC, RR, RL, FC, LFE, FR, FL } },
/* surround71 */
{ .ca_index = 0x13, .speakers = { RRC, RLC, RR, RL, FC, LFE, FR, FL } },
{ .ca_index = 0x03, .speakers = { 0, 0, 0, 0, FC, LFE, FR, FL } },
{ .ca_index = 0x04, .speakers = { 0, 0, 0, RC, 0, 0, FR, FL } },
{ .ca_index = 0x05, .speakers = { 0, 0, 0, RC, 0, LFE, FR, FL } },
{ .ca_index = 0x06, .speakers = { 0, 0, 0, RC, FC, 0, FR, FL } },
{ .ca_index = 0x07, .speakers = { 0, 0, 0, RC, FC, LFE, FR, FL } },
{ .ca_index = 0x0c, .speakers = { 0, RC, RR, RL, 0, 0, FR, FL } },
{ .ca_index = 0x0d, .speakers = { 0, RC, RR, RL, 0, LFE, FR, FL } },
{ .ca_index = 0x0e, .speakers = { 0, RC, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x10, .speakers = { RRC, RLC, RR, RL, 0, 0, FR, FL } },
{ .ca_index = 0x11, .speakers = { RRC, RLC, RR, RL, 0, LFE, FR, FL } },
{ .ca_index = 0x12, .speakers = { RRC, RLC, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x14, .speakers = { FRC, FLC, 0, 0, 0, 0, FR, FL } },
{ .ca_index = 0x15, .speakers = { FRC, FLC, 0, 0, 0, LFE, FR, FL } },
{ .ca_index = 0x16, .speakers = { FRC, FLC, 0, 0, FC, 0, FR, FL } },
{ .ca_index = 0x17, .speakers = { FRC, FLC, 0, 0, FC, LFE, FR, FL } },
{ .ca_index = 0x18, .speakers = { FRC, FLC, 0, RC, 0, 0, FR, FL } },
{ .ca_index = 0x19, .speakers = { FRC, FLC, 0, RC, 0, LFE, FR, FL } },
{ .ca_index = 0x1a, .speakers = { FRC, FLC, 0, RC, FC, 0, FR, FL } },
{ .ca_index = 0x1b, .speakers = { FRC, FLC, 0, RC, FC, LFE, FR, FL } },
{ .ca_index = 0x1c, .speakers = { FRC, FLC, RR, RL, 0, 0, FR, FL } },
{ .ca_index = 0x1d, .speakers = { FRC, FLC, RR, RL, 0, LFE, FR, FL } },
{ .ca_index = 0x1e, .speakers = { FRC, FLC, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x1f, .speakers = { FRC, FLC, RR, RL, FC, LFE, FR, FL } },
{ .ca_index = 0x20, .speakers = { 0, FCH, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x21, .speakers = { 0, FCH, RR, RL, FC, LFE, FR, FL } },
{ .ca_index = 0x22, .speakers = { TC, 0, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x23, .speakers = { TC, 0, RR, RL, FC, LFE, FR, FL } },
{ .ca_index = 0x24, .speakers = { FRH, FLH, RR, RL, 0, 0, FR, FL } },
{ .ca_index = 0x25, .speakers = { FRH, FLH, RR, RL, 0, LFE, FR, FL } },
{ .ca_index = 0x26, .speakers = { FRW, FLW, RR, RL, 0, 0, FR, FL } },
{ .ca_index = 0x27, .speakers = { FRW, FLW, RR, RL, 0, LFE, FR, FL } },
{ .ca_index = 0x28, .speakers = { TC, RC, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x29, .speakers = { TC, RC, RR, RL, FC, LFE, FR, FL } },
{ .ca_index = 0x2a, .speakers = { FCH, RC, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x2b, .speakers = { FCH, RC, RR, RL, FC, LFE, FR, FL } },
{ .ca_index = 0x2c, .speakers = { TC, FCH, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x2d, .speakers = { TC, FCH, RR, RL, FC, LFE, FR, FL } },
{ .ca_index = 0x2e, .speakers = { FRH, FLH, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x2f, .speakers = { FRH, FLH, RR, RL, FC, LFE, FR, FL } },
{ .ca_index = 0x30, .speakers = { FRW, FLW, RR, RL, FC, 0, FR, FL } },
{ .ca_index = 0x31, .speakers = { FRW, FLW, RR, RL, FC, LFE, FR, FL } },
};
static int hdmi_pin_set_slot_channel(struct hdac_device *codec,
hda_nid_t pin_nid, int asp_slot, int channel)
{
return snd_hdac_codec_write(codec, pin_nid, 0,
AC_VERB_SET_HDMI_CHAN_SLOT,
(channel << 4) | asp_slot);
}
static int hdmi_pin_get_slot_channel(struct hdac_device *codec,
hda_nid_t pin_nid, int asp_slot)
{
return (snd_hdac_codec_read(codec, pin_nid, 0,
AC_VERB_GET_HDMI_CHAN_SLOT,
asp_slot) & 0xf0) >> 4;
}
static int hdmi_get_channel_count(struct hdac_device *codec, hda_nid_t cvt_nid)
{
return 1 + snd_hdac_codec_read(codec, cvt_nid, 0,
AC_VERB_GET_CVT_CHAN_COUNT, 0);
}
static void hdmi_set_channel_count(struct hdac_device *codec,
hda_nid_t cvt_nid, int chs)
{
if (chs != hdmi_get_channel_count(codec, cvt_nid))
snd_hdac_codec_write(codec, cvt_nid, 0,
AC_VERB_SET_CVT_CHAN_COUNT, chs - 1);
}
/*
* Channel mapping routines
*/
/*
* Compute derived values in channel_allocations[].
*/
static void init_channel_allocations(void)
{
int i, j;
struct hdac_cea_channel_speaker_allocation *p;
for (i = 0; i < ARRAY_SIZE(channel_allocations); i++) {
p = channel_allocations + i;
p->channels = 0;
p->spk_mask = 0;
for (j = 0; j < ARRAY_SIZE(p->speakers); j++)
if (p->speakers[j]) {
p->channels++;
p->spk_mask |= p->speakers[j];
}
}
}
static int get_channel_allocation_order(int ca)
{
int i;
for (i = 0; i < ARRAY_SIZE(channel_allocations); i++) {
if (channel_allocations[i].ca_index == ca)
break;
}
return i;
}
void snd_hdac_print_channel_allocation(int spk_alloc, char *buf, int buflen)
{
int i, j;
for (i = 0, j = 0; i < ARRAY_SIZE(cea_speaker_allocation_names); i++) {
if (spk_alloc & (1 << i))
j += snprintf(buf + j, buflen - j, " %s",
cea_speaker_allocation_names[i]);
}
buf[j] = '\0'; /* necessary when j == 0 */
}
EXPORT_SYMBOL_GPL(snd_hdac_print_channel_allocation);
/*
* The transformation takes two steps:
*
* eld->spk_alloc => (eld_speaker_allocation_bits[]) => spk_mask
* spk_mask => (channel_allocations[]) => ai->CA
*
* TODO: it could select the wrong CA from multiple candidates.
*/
static int hdmi_channel_allocation_spk_alloc_blk(struct hdac_device *codec,
int spk_alloc, int channels)
{
int i;
int ca = 0;
int spk_mask = 0;
char buf[SND_PRINT_CHANNEL_ALLOCATION_ADVISED_BUFSIZE];
/*
* CA defaults to 0 for basic stereo audio
*/
if (channels <= 2)
return 0;
/*
* expand ELD's speaker allocation mask
*
* ELD tells the speaker mask in a compact(paired) form,
* expand ELD's notions to match the ones used by Audio InfoFrame.
*/
for (i = 0; i < ARRAY_SIZE(eld_speaker_allocation_bits); i++) {
if (spk_alloc & (1 << i))
spk_mask |= eld_speaker_allocation_bits[i];
}
/* search for the first working match in the CA table */
for (i = 0; i < ARRAY_SIZE(channel_allocations); i++) {
if (channels == channel_allocations[i].channels &&
(spk_mask & channel_allocations[i].spk_mask) ==
channel_allocations[i].spk_mask) {
ca = channel_allocations[i].ca_index;
break;
}
}
if (!ca) {
/*
* if there was no match, select the regular ALSA channel
* allocation with the matching number of channels
*/
for (i = 0; i < ARRAY_SIZE(channel_allocations); i++) {
if (channels == channel_allocations[i].channels) {
ca = channel_allocations[i].ca_index;
break;
}
}
}
snd_hdac_print_channel_allocation(spk_alloc, buf, sizeof(buf));
dev_dbg(&codec->dev, "HDMI: select CA 0x%x for %d-channel allocation: %s\n",
ca, channels, buf);
return ca;
}
static void hdmi_debug_channel_mapping(struct hdac_chmap *chmap,
hda_nid_t pin_nid)
{
#ifdef CONFIG_SND_DEBUG_VERBOSE
int i;
int channel;
for (i = 0; i < 8; i++) {
channel = chmap->ops.pin_get_slot_channel(
chmap->hdac, pin_nid, i);
dev_dbg(&chmap->hdac->dev, "HDMI: ASP channel %d => slot %d\n",
channel, i);
}
#endif
}
static void hdmi_std_setup_channel_mapping(struct hdac_chmap *chmap,
hda_nid_t pin_nid,
bool non_pcm,
int ca)
{
struct hdac_cea_channel_speaker_allocation *ch_alloc;
int i;
int err;
int order;
int non_pcm_mapping[8];
order = get_channel_allocation_order(ca);
ch_alloc = &channel_allocations[order];
if (hdmi_channel_mapping[ca][1] == 0) {
int hdmi_slot = 0;
/* fill actual channel mappings in ALSA channel (i) order */
for (i = 0; i < ch_alloc->channels; i++) {
while (!ch_alloc->speakers[7 - hdmi_slot] && !WARN_ON(hdmi_slot >= 8))
hdmi_slot++; /* skip zero slots */
hdmi_channel_mapping[ca][i] = (i << 4) | hdmi_slot++;
}
/* fill the rest of the slots with ALSA channel 0xf */
for (hdmi_slot = 0; hdmi_slot < 8; hdmi_slot++)
if (!ch_alloc->speakers[7 - hdmi_slot])
hdmi_channel_mapping[ca][i++] = (0xf << 4) | hdmi_slot;
}
if (non_pcm) {
for (i = 0; i < ch_alloc->channels; i++)
non_pcm_mapping[i] = (i << 4) | i;
for (; i < 8; i++)
non_pcm_mapping[i] = (0xf << 4) | i;
}
for (i = 0; i < 8; i++) {
int slotsetup = non_pcm ? non_pcm_mapping[i] : hdmi_channel_mapping[ca][i];
int hdmi_slot = slotsetup & 0x0f;
int channel = (slotsetup & 0xf0) >> 4;
err = chmap->ops.pin_set_slot_channel(chmap->hdac,
pin_nid, hdmi_slot, channel);
if (err) {
dev_dbg(&chmap->hdac->dev, "HDMI: channel mapping failed\n");
break;
}
}
}
struct channel_map_table {
unsigned char map; /* ALSA API channel map position */
int spk_mask; /* speaker position bit mask */
};
static struct channel_map_table map_tables[] = {
{ SNDRV_CHMAP_FL, FL },
{ SNDRV_CHMAP_FR, FR },
{ SNDRV_CHMAP_RL, RL },
{ SNDRV_CHMAP_RR, RR },
{ SNDRV_CHMAP_LFE, LFE },
{ SNDRV_CHMAP_FC, FC },
{ SNDRV_CHMAP_RLC, RLC },
{ SNDRV_CHMAP_RRC, RRC },
{ SNDRV_CHMAP_RC, RC },
{ SNDRV_CHMAP_FLC, FLC },
{ SNDRV_CHMAP_FRC, FRC },
{ SNDRV_CHMAP_TFL, FLH },
{ SNDRV_CHMAP_TFR, FRH },
{ SNDRV_CHMAP_FLW, FLW },
{ SNDRV_CHMAP_FRW, FRW },
{ SNDRV_CHMAP_TC, TC },
{ SNDRV_CHMAP_TFC, FCH },
{} /* terminator */
};
/* from ALSA API channel position to speaker bit mask */
int snd_hdac_chmap_to_spk_mask(unsigned char c)
{
struct channel_map_table *t = map_tables;
for (; t->map; t++) {
if (t->map == c)
return t->spk_mask;
}
return 0;
}
EXPORT_SYMBOL_GPL(snd_hdac_chmap_to_spk_mask);
/* from ALSA API channel position to CEA slot */
static int to_cea_slot(int ordered_ca, unsigned char pos)
{
int mask = snd_hdac_chmap_to_spk_mask(pos);
int i;
if (mask) {
for (i = 0; i < 8; i++) {
if (channel_allocations[ordered_ca].speakers[7 - i] == mask)
return i;
}
}
return -1;
}
/* from speaker bit mask to ALSA API channel position */
int snd_hdac_spk_to_chmap(int spk)
{
struct channel_map_table *t = map_tables;
for (; t->map; t++) {
if (t->spk_mask == spk)
return t->map;
}
return 0;
}
EXPORT_SYMBOL_GPL(snd_hdac_spk_to_chmap);
/* from CEA slot to ALSA API channel position */
static int from_cea_slot(int ordered_ca, unsigned char slot)
{
int mask = channel_allocations[ordered_ca].speakers[7 - slot];
return snd_hdac_spk_to_chmap(mask);
}
/* get the CA index corresponding to the given ALSA API channel map */
static int hdmi_manual_channel_allocation(int chs, unsigned char *map)
{
int i, spks = 0, spk_mask = 0;
for (i = 0; i < chs; i++) {
int mask = snd_hdac_chmap_to_spk_mask(map[i]);
if (mask) {
spk_mask |= mask;
spks++;
}
}
for (i = 0; i < ARRAY_SIZE(channel_allocations); i++) {
if ((chs == channel_allocations[i].channels ||
spks == channel_allocations[i].channels) &&
(spk_mask & channel_allocations[i].spk_mask) ==
channel_allocations[i].spk_mask)
return channel_allocations[i].ca_index;
}
return -1;
}
/* set up the channel slots for the given ALSA API channel map */
static int hdmi_manual_setup_channel_mapping(struct hdac_chmap *chmap,
hda_nid_t pin_nid,
int chs, unsigned char *map,
int ca)
{
int ordered_ca = get_channel_allocation_order(ca);
int alsa_pos, hdmi_slot;
int assignments[8] = {[0 ... 7] = 0xf};
for (alsa_pos = 0; alsa_pos < chs; alsa_pos++) {
hdmi_slot = to_cea_slot(ordered_ca, map[alsa_pos]);
if (hdmi_slot < 0)
continue; /* unassigned channel */
assignments[hdmi_slot] = alsa_pos;
}
for (hdmi_slot = 0; hdmi_slot < 8; hdmi_slot++) {
int err;
err = chmap->ops.pin_set_slot_channel(chmap->hdac,
pin_nid, hdmi_slot, assignments[hdmi_slot]);
if (err)
return -EINVAL;
}
return 0;
}
/* store ALSA API channel map from the current default map */
static void hdmi_setup_fake_chmap(unsigned char *map, int ca)
{
int i;
int ordered_ca = get_channel_allocation_order(ca);
for (i = 0; i < 8; i++) {
if (i < channel_allocations[ordered_ca].channels)
map[i] = from_cea_slot(ordered_ca, hdmi_channel_mapping[ca][i] & 0x0f);
else
map[i] = 0;
}
}
void snd_hdac_setup_channel_mapping(struct hdac_chmap *chmap,
hda_nid_t pin_nid, bool non_pcm, int ca,
int channels, unsigned char *map,
bool chmap_set)
{
if (!non_pcm && chmap_set) {
hdmi_manual_setup_channel_mapping(chmap, pin_nid,
channels, map, ca);
} else {
hdmi_std_setup_channel_mapping(chmap, pin_nid, non_pcm, ca);
hdmi_setup_fake_chmap(map, ca);
}
hdmi_debug_channel_mapping(chmap, pin_nid);
}
EXPORT_SYMBOL_GPL(snd_hdac_setup_channel_mapping);
int snd_hdac_get_active_channels(int ca)
{
int ordered_ca = get_channel_allocation_order(ca);
return channel_allocations[ordered_ca].channels;
}
EXPORT_SYMBOL_GPL(snd_hdac_get_active_channels);
struct hdac_cea_channel_speaker_allocation *snd_hdac_get_ch_alloc_from_ca(int ca)
{
return &channel_allocations[get_channel_allocation_order(ca)];
}
EXPORT_SYMBOL_GPL(snd_hdac_get_ch_alloc_from_ca);
int snd_hdac_channel_allocation(struct hdac_device *hdac, int spk_alloc,
int channels, bool chmap_set, bool non_pcm, unsigned char *map)
{
int ca;
if (!non_pcm && chmap_set)
ca = hdmi_manual_channel_allocation(channels, map);
else
ca = hdmi_channel_allocation_spk_alloc_blk(hdac,
spk_alloc, channels);
if (ca < 0)
ca = 0;
return ca;
}
EXPORT_SYMBOL_GPL(snd_hdac_channel_allocation);
/*
* ALSA API channel-map control callbacks
*/
static int hdmi_chmap_ctl_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
struct hdac_chmap *chmap = info->private_data;
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = chmap->channels_max;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = SNDRV_CHMAP_LAST;
return 0;
}
static int hdmi_chmap_cea_alloc_validate_get_type(struct hdac_chmap *chmap,
struct hdac_cea_channel_speaker_allocation *cap, int channels)
{
/* If the speaker allocation matches the channel count, it is OK.*/
if (cap->channels != channels)
return -1;
/* all channels are remappable freely */
return SNDRV_CTL_TLVT_CHMAP_VAR;
}
static void hdmi_cea_alloc_to_tlv_chmap(struct hdac_chmap *hchmap,
struct hdac_cea_channel_speaker_allocation *cap,
unsigned int *chmap, int channels)
{
int count = 0;
int c;
for (c = 7; c >= 0; c--) {
int spk = cap->speakers[c];
if (!spk)
continue;
chmap[count++] = snd_hdac_spk_to_chmap(spk);
}
WARN_ON(count != channels);
}
static int spk_mask_from_spk_alloc(int spk_alloc)
{
int i;
int spk_mask = eld_speaker_allocation_bits[0];
for (i = 0; i < ARRAY_SIZE(eld_speaker_allocation_bits); i++) {
if (spk_alloc & (1 << i))
spk_mask |= eld_speaker_allocation_bits[i];
}
return spk_mask;
}
static int hdmi_chmap_ctl_tlv(struct snd_kcontrol *kcontrol, int op_flag,
unsigned int size, unsigned int __user *tlv)
{
struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
struct hdac_chmap *chmap = info->private_data;
int pcm_idx = kcontrol->private_value;
unsigned int __user *dst;
int chs, count = 0;
unsigned long max_chs;
int type;
int spk_alloc, spk_mask;
if (size < 8)
return -ENOMEM;
if (put_user(SNDRV_CTL_TLVT_CONTAINER, tlv))
return -EFAULT;
size -= 8;
dst = tlv + 2;
spk_alloc = chmap->ops.get_spk_alloc(chmap->hdac, pcm_idx);
spk_mask = spk_mask_from_spk_alloc(spk_alloc);
max_chs = hweight_long(spk_mask);
for (chs = 2; chs <= max_chs; chs++) {
int i;
struct hdac_cea_channel_speaker_allocation *cap;
cap = channel_allocations;
for (i = 0; i < ARRAY_SIZE(channel_allocations); i++, cap++) {
int chs_bytes = chs * 4;
unsigned int tlv_chmap[8];
if (cap->channels != chs)
continue;
if (!(cap->spk_mask == (spk_mask & cap->spk_mask)))
continue;
type = chmap->ops.chmap_cea_alloc_validate_get_type(
chmap, cap, chs);
if (type < 0)
return -ENODEV;
if (size < 8)
return -ENOMEM;
if (put_user(type, dst) ||
put_user(chs_bytes, dst + 1))
return -EFAULT;
dst += 2;
size -= 8;
count += 8;
if (size < chs_bytes)
return -ENOMEM;
size -= chs_bytes;
count += chs_bytes;
chmap->ops.cea_alloc_to_tlv_chmap(chmap, cap,
tlv_chmap, chs);
if (copy_to_user(dst, tlv_chmap, chs_bytes))
return -EFAULT;
dst += chs;
}
}
if (put_user(count, tlv + 1))
return -EFAULT;
return 0;
}
static int hdmi_chmap_ctl_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
struct hdac_chmap *chmap = info->private_data;
int pcm_idx = kcontrol->private_value;
unsigned char pcm_chmap[8];
int i;
memset(pcm_chmap, 0, sizeof(pcm_chmap));
chmap->ops.get_chmap(chmap->hdac, pcm_idx, pcm_chmap);
for (i = 0; i < sizeof(chmap); i++)
ucontrol->value.integer.value[i] = pcm_chmap[i];
return 0;
}
static int hdmi_chmap_ctl_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
struct hdac_chmap *hchmap = info->private_data;
int pcm_idx = kcontrol->private_value;
unsigned int ctl_idx;
struct snd_pcm_substream *substream;
unsigned char chmap[8], per_pin_chmap[8];
int i, err, ca, prepared = 0;
/* No monitor is connected in dyn_pcm_assign.
* It's invalid to setup the chmap
*/
if (!hchmap->ops.is_pcm_attached(hchmap->hdac, pcm_idx))
return 0;
ctl_idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id);
substream = snd_pcm_chmap_substream(info, ctl_idx);
if (!substream || !substream->runtime)
return 0; /* just for avoiding error from alsactl restore */
switch (substream->runtime->status->state) {
case SNDRV_PCM_STATE_OPEN:
case SNDRV_PCM_STATE_SETUP:
break;
case SNDRV_PCM_STATE_PREPARED:
prepared = 1;
break;
default:
return -EBUSY;
}
memset(chmap, 0, sizeof(chmap));
for (i = 0; i < ARRAY_SIZE(chmap); i++)
chmap[i] = ucontrol->value.integer.value[i];
hchmap->ops.get_chmap(hchmap->hdac, pcm_idx, per_pin_chmap);
if (!memcmp(chmap, per_pin_chmap, sizeof(chmap)))
return 0;
ca = hdmi_manual_channel_allocation(ARRAY_SIZE(chmap), chmap);
if (ca < 0)
return -EINVAL;
if (hchmap->ops.chmap_validate) {
err = hchmap->ops.chmap_validate(hchmap, ca,
ARRAY_SIZE(chmap), chmap);
if (err)
return err;
}
hchmap->ops.set_chmap(hchmap->hdac, pcm_idx, chmap, prepared);
return 0;
}
static const struct hdac_chmap_ops chmap_ops = {
.chmap_cea_alloc_validate_get_type = hdmi_chmap_cea_alloc_validate_get_type,
.cea_alloc_to_tlv_chmap = hdmi_cea_alloc_to_tlv_chmap,
.pin_get_slot_channel = hdmi_pin_get_slot_channel,
.pin_set_slot_channel = hdmi_pin_set_slot_channel,
.set_channel_count = hdmi_set_channel_count,
};
void snd_hdac_register_chmap_ops(struct hdac_device *hdac,
struct hdac_chmap *chmap)
{
chmap->ops = chmap_ops;
chmap->hdac = hdac;
init_channel_allocations();
}
EXPORT_SYMBOL_GPL(snd_hdac_register_chmap_ops);
int snd_hdac_add_chmap_ctls(struct snd_pcm *pcm, int pcm_idx,
struct hdac_chmap *hchmap)
{
struct snd_pcm_chmap *chmap;
struct snd_kcontrol *kctl;
int err, i;
err = snd_pcm_add_chmap_ctls(pcm,
SNDRV_PCM_STREAM_PLAYBACK,
NULL, 0, pcm_idx, &chmap);
if (err < 0)
return err;
/* override handlers */
chmap->private_data = hchmap;
kctl = chmap->kctl;
for (i = 0; i < kctl->count; i++)
kctl->vd[i].access |= SNDRV_CTL_ELEM_ACCESS_WRITE;
kctl->info = hdmi_chmap_ctl_info;
kctl->get = hdmi_chmap_ctl_get;
kctl->put = hdmi_chmap_ctl_put;
kctl->tlv.c = hdmi_chmap_ctl_tlv;
return 0;
}
EXPORT_SYMBOL_GPL(snd_hdac_add_chmap_ctls);
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2016-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <io/MslObject.h>
#include <io/MslArray.h>
#include <io/DefaultMslEncoderFactory.h>
#include <io/MslEncoderFormat.h>
#include <msg/MessageCapabilities.h>
#include <MslConstants.h>
#include <MslEncodingException.h>
#include <algorithm>
using namespace std;
using namespace netflix::msl::io;
namespace netflix {
namespace msl {
namespace msg {
namespace {
const std::string KEY_COMPRESSION_ALGOS = "compressionalgos";
const std::string KEY_LANGUAGES = "languages";
const std::string KEY_ENCODER_FORMATS = "encoderformats";
template <typename T> string op(const T& x) { return x.toString(); }
//string toString(MessageCapabilities mc) {
// MslEncoderFactory mef;
// const ByteArray ba = mc.toMslEncoding(mef, MslEncoderFormat::JSON);
// return string(ba.begin(), ba.end());
//}
}
class MessageCapabilitiesTest : public ::testing::Test
{
protected:
MessageCapabilitiesTest() {
compressionAlgos_.insert(MslConstants::CompressionAlgorithm::NOCOMPRESSION);
compressionAlgos_.insert(MslConstants::CompressionAlgorithm::LZW);
compressionAlgos_.insert(MslConstants::CompressionAlgorithm::GZIP);
languages_.push_back("aa");
languages_.push_back("cc");
languages_.push_back("bb");
encoderFormats_.insert(MslEncoderFormat::JSON);
}
set<MslConstants::CompressionAlgorithm> compressionAlgos_;
vector<string> languages_;
set<MslEncoderFormat> encoderFormats_;
};
TEST_F(MessageCapabilitiesTest, simpleCtor)
{
MessageCapabilities mc(compressionAlgos_, languages_, encoderFormats_);
EXPECT_EQ(compressionAlgos_, mc.getCompressionAlgorithms());
EXPECT_EQ(languages_, mc.getLanguages());
EXPECT_EQ(encoderFormats_, mc.getEncoderFormats());
}
TEST_F(MessageCapabilitiesTest, mslObjectCtor)
{
// happy path
shared_ptr<MslObject> mo = make_shared<MslObject>();
vector<string> ca(compressionAlgos_.size());
transform(compressionAlgos_.begin(), compressionAlgos_.end(), ca.begin(), op<MslConstants::CompressionAlgorithm>);
shared_ptr<MslArray> cama = make_shared<MslArray>(ca);
mo->put(KEY_COMPRESSION_ALGOS, cama);
shared_ptr<MslArray> lma = make_shared<MslArray>(languages_);
mo->put(KEY_LANGUAGES, lma);
vector<string> ef(encoderFormats_.size());
transform(encoderFormats_.begin(), encoderFormats_.end(), ef.begin(), op<MslEncoderFormat>);
shared_ptr<MslArray> efma = make_shared<MslArray>(ef);
mo->put(KEY_ENCODER_FORMATS, efma);
shared_ptr<MessageCapabilities> mc1 = make_shared<MessageCapabilities>(mo);
EXPECT_EQ(compressionAlgos_, mc1->getCompressionAlgorithms());
EXPECT_EQ(languages_, mc1->getLanguages());
EXPECT_EQ(encoderFormats_, mc1->getEncoderFormats());
// missing compression algos field
mo->remove(KEY_COMPRESSION_ALGOS);
shared_ptr<MessageCapabilities> mc2 = make_shared<MessageCapabilities>(mo);
EXPECT_TRUE(mc2->getCompressionAlgorithms().empty());
mo->put(KEY_COMPRESSION_ALGOS, cama);
// unsupported compression algorithm
cama->put<string>(-1, "invalidCompressionAlgoName");
mo->put(KEY_COMPRESSION_ALGOS, cama);
shared_ptr<MessageCapabilities> mc3 = make_shared<MessageCapabilities>(mo);
EXPECT_EQ(compressionAlgos_, mc3->getCompressionAlgorithms());
// missing languages
mo->remove(KEY_LANGUAGES);
shared_ptr<MessageCapabilities> mc4 = make_shared<MessageCapabilities>(mo);
EXPECT_TRUE(mc4->getLanguages().empty());
mo->put(KEY_LANGUAGES, lma);
// missing encoder formats
mo->remove(KEY_ENCODER_FORMATS);
shared_ptr<MessageCapabilities> mc5 = make_shared<MessageCapabilities>(mo);
EXPECT_TRUE(mc5->getEncoderFormats().empty());
mo->put(KEY_ENCODER_FORMATS, efma);
// unsupported encoder formats
efma->put<string>(-1, "invalidEncoderFormat");
mo->put(KEY_ENCODER_FORMATS, efma);
shared_ptr<MessageCapabilities> mc6 = make_shared<MessageCapabilities>(mo);
EXPECT_EQ(encoderFormats_, mc6->getEncoderFormats());
}
TEST_F(MessageCapabilitiesTest, toMslEncoding)
{
// FIXME: This is an error-prone test because there is no guarantee of how
// a JSON encoding might be constructed or formatted.
shared_ptr<MessageCapabilities> mc1 = make_shared<MessageCapabilities>(compressionAlgos_, languages_, encoderFormats_);
shared_ptr<MslEncoderFactory> mef = make_shared<DefaultMslEncoderFactory>();
shared_ptr<ByteArray> ba1 = mc1->toMslEncoding(mef, MslEncoderFormat::JSON);
EXPECT_EQ(
"{\"compressionalgos\":[\"GZIP\",\"LZW\",\"NOCOMPRESSION\"],\"encoderformats\":[\"JSON\"],\"languages\":[\"aa\",\"cc\",\"bb\"]}",
string(ba1->begin(), ba1->end()));
shared_ptr<MslObject> mo = make_shared<MslObject>();
shared_ptr<MessageCapabilities> mc2 = make_shared<MessageCapabilities>(mo);
shared_ptr<ByteArray> ba2 = mc2->toMslEncoding(mef, MslEncoderFormat::JSON);
EXPECT_EQ(
"{\"compressionalgos\":[],\"encoderformats\":[],\"languages\":[]}",
string(ba2->begin(), ba2->end()));
}
TEST_F(MessageCapabilitiesTest, equality)
{
set<MslConstants::CompressionAlgorithm> compressionAlgos = compressionAlgos_;
vector<string> languages = languages_;
set<MslEncoderFormat> encoderFormats = encoderFormats_;
shared_ptr<MessageCapabilities> mc1 = make_shared<MessageCapabilities>(compressionAlgos_, languages_, encoderFormats_);
shared_ptr<MessageCapabilities> mc2 = make_shared<MessageCapabilities>(compressionAlgos, languages, encoderFormats);
EXPECT_TRUE(*mc1 == *mc2);
EXPECT_FALSE(*mc1 != *mc2);
EXPECT_EQ(*mc1, *mc2);
compressionAlgos.erase(MslConstants::CompressionAlgorithm::LZW);
shared_ptr<MessageCapabilities> mc3 = make_shared<MessageCapabilities>(compressionAlgos, languages, encoderFormats);
EXPECT_FALSE(*mc2 == *mc3);
EXPECT_TRUE(*mc2 != *mc3);
EXPECT_NE(*mc1, *mc3);
}
TEST_F(MessageCapabilitiesTest, intersection)
{
// empty intersection with empty should be empty
const set<MslConstants::CompressionAlgorithm> emptyCompressionAlgos;
const vector<string> emptyLanguages;
const set<MslEncoderFormat> emptyEncoderFormats;
shared_ptr<MessageCapabilities> mc1 = make_shared<MessageCapabilities>(emptyCompressionAlgos, emptyLanguages, emptyEncoderFormats);
shared_ptr<MessageCapabilities> mc2 = make_shared<MessageCapabilities>(emptyCompressionAlgos, emptyLanguages, emptyEncoderFormats);
shared_ptr<MessageCapabilities> result = MessageCapabilities::intersection(mc1, mc2);
EXPECT_TRUE(result->getCompressionAlgorithms().empty());
EXPECT_TRUE(result->getEncoderFormats().empty());
EXPECT_TRUE(result->getLanguages().empty());
// empty intersection with non-empty object should kill the object x3
shared_ptr<MessageCapabilities> mc3 = make_shared<MessageCapabilities>(compressionAlgos_, languages_, encoderFormats_);
shared_ptr<MessageCapabilities> emptyMc1 = make_shared<MessageCapabilities>(emptyCompressionAlgos, languages_, encoderFormats_);
shared_ptr<MessageCapabilities> emptyMc2 = make_shared<MessageCapabilities>(compressionAlgos_, emptyLanguages, encoderFormats_);
shared_ptr<MessageCapabilities> emptyMc3 = make_shared<MessageCapabilities>(compressionAlgos_, languages_, emptyEncoderFormats);
result = MessageCapabilities::intersection(mc3, emptyMc1);
EXPECT_TRUE(result->getCompressionAlgorithms().empty());
EXPECT_NE(compressionAlgos_, result->getCompressionAlgorithms());
EXPECT_EQ(languages_, result->getLanguages());
EXPECT_EQ(encoderFormats_, result->getEncoderFormats());
result = MessageCapabilities::intersection(mc3, emptyMc2);
EXPECT_TRUE(result->getLanguages().empty());
EXPECT_EQ(compressionAlgos_, result->getCompressionAlgorithms());
EXPECT_NE(languages_, result->getLanguages());
EXPECT_EQ(encoderFormats_, result->getEncoderFormats());
result = MessageCapabilities::intersection(mc3, emptyMc3);
EXPECT_TRUE(result->getEncoderFormats().empty());
EXPECT_EQ(compressionAlgos_, result->getCompressionAlgorithms());
EXPECT_EQ(languages_, result->getLanguages());
EXPECT_NE(encoderFormats_, result->getEncoderFormats());
// intersection between two non-empty objects should be the lesser object
set<MslConstants::CompressionAlgorithm> compressionAlgos = compressionAlgos_;
vector<string> languages = languages_;
set<MslEncoderFormat> encoderFormats = encoderFormats_;
compressionAlgos.erase(MslConstants::CompressionAlgorithm::LZW);
languages.erase(remove(languages.begin(), languages.end(), "bb"), languages.end());
encoderFormats.erase(MslEncoderFormat::JSON);
shared_ptr<MessageCapabilities> mc4 = make_shared<MessageCapabilities>(compressionAlgos, languages, encoderFormats);
result = MessageCapabilities::intersection(mc3, mc4);
EXPECT_EQ(compressionAlgos, result->getCompressionAlgorithms());
EXPECT_EQ(languages, result->getLanguages());
EXPECT_EQ(encoderFormats, result->getEncoderFormats());
// intersection order should not matter
shared_ptr<MessageCapabilities> result1 = MessageCapabilities::intersection(mc4, mc3);
EXPECT_EQ(*result, *result1);
}
}}} // namespace netflix::msl::msg
| {
"pile_set_name": "Github"
} |
gcr.io/google_containers/kube-proxy:v1.11.10
| {
"pile_set_name": "Github"
} |
// ***************************************************************************
// *
// * Copyright (C) 2014 International Business Machines
// * Corporation and others. All Rights Reserved.
// * Tool: org.unicode.cldr.icu.NewLdml2IcuConverter
// * Source File: <path>/common/main/mgo.xml
// *
// ***************************************************************************
/**
* ICU <specials> source: <path>/common/main/mgo.xml
*/
mgo{
Version{"2.1.6.69"}
units{
duration{
day{
one{"{0} d"}
other{"{0} d"}
}
hour{
one{"{0} h"}
other{"{0} h"}
}
minute{
one{"{0} min"}
other{"{0} min"}
}
month{
one{"{0} m"}
other{"{0} m"}
}
second{
one{"{0} s"}
other{"{0} s"}
}
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{4C55E602-1C6C-4396-A118-70BA9A93FD97}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TikaOnDotNet.TextExtraction</RootNamespace>
<AssemblyName>TikaOnDotNet.TextExtraction</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="TikaOnDotNet">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\TikaOnDotNet.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\SolutionInfo.cs">
<Link>Properties\SolutionInfo.cs</Link>
</Compile>
<Compile Include="Stream\DotNetOutputStreamAdapter.cs" />
<Compile Include="Stream\ExtractionResult.cs" />
<Compile Include="Stream\StreamContentHandler.cs" />
<Compile Include="Stream\StreamTextExtractor.cs" />
<Compile Include="ITextExtractor.cs" />
<Compile Include="MySystemClassLoader.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StringExtensions.cs" />
<Compile Include="TextExtractionException.cs" />
<Compile Include="TextExtractionResult.cs" />
<Compile Include="TextExtractor.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ItemGroup>
<None Include="paket.references" />
<None Include="paket.template" />
</ItemGroup>
<ItemGroup>
<Reference Include="IKVM.AWT.WinForms">
<HintPath>..\..\packages\IKVM\lib\IKVM.AWT.WinForms.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Beans">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Beans.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Charsets">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Charsets.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Cldrdata">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Cldrdata.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Corba">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Corba.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Core">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Core.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Jdbc">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Jdbc.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Localedata">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Localedata.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Management">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Management.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Media">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Media.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Misc">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Misc.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Naming">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Naming.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Nashorn">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Nashorn.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Remoting">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Remoting.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Security">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Security.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.SwingAWT">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.SwingAWT.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Text">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Text.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Tools">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Tools.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.Util">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.Util.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.XML.API">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.XML.API.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.XML.Bind">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.XML.Bind.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.XML.Crypto">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.XML.Crypto.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.XML.Parse">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.XML.Parse.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.XML.Transform">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.XML.Transform.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.XML.WebServices">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.XML.WebServices.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.OpenJDK.XML.XPath">
<HintPath>..\..\packages\IKVM\lib\IKVM.OpenJDK.XML.XPath.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.Runtime">
<HintPath>..\..\packages\IKVM\lib\IKVM.Runtime.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
<Reference Include="IKVM.Runtime.JNI">
<HintPath>..\..\packages\IKVM\lib\IKVM.Runtime.JNI.dll</HintPath>
<Private>True</Private>
<Paket>True</Paket>
</Reference>
</ItemGroup>
</Project> | {
"pile_set_name": "Github"
} |
--------------ofCamera parameters--------------
transformMatrix
0.995621, 0.0225893, -0.0907183, 0
-0.0607166, 0.894107, -0.443719, 0
0.0710885, 0.447283, 0.891562, 0
52.9581, 333.196, 664.16, 1
fov
60
near
6.65107
far
6651.07
lensOffset
0, 0
isOrtho
0
--------------ofEasyCam parameters--------------
target
0, 0, 0
bEnableMouseMiddleButton
1
bMouseInputEnabled
0
drag
0.9
doTranslationKey
m
| {
"pile_set_name": "Github"
} |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import React, {Component} from 'react';
import FormControl from './form-control';
// Styles
import styles from './param-selector.css';
import formField from '../styles/form-field.css';
/**
* A component for choosing the params to use in the trend report.
*/
export default class ParamSelector extends Component {
/**
* React lifecycyle methods below:
* http://facebook.github.io/react/docs/component-specs.html
* ---------------------------------------------------------
*/
/** @return {Object} The React component. */
render() {
const {onChange, options, params} = this.props;
const metrics = (
<FormControl full label="Metric">
{!options.metrics ? null : (
<select
className={formField.root}
name="metric"
value={params.metric}
onChange={onChange}>{
Object.keys(options.metrics).map((group) => (
<optgroup key={group} label={group}>{
options.metrics[group].map((metric) => (
<option key={metric.id} value={metric.id}>
{metric.attributes.uiName}
</option>
))
}</optgroup>
))
}</select>
)}
</FormControl>
);
const dimensions = (
<FormControl full label="Dimension">
{!options.dimensions ? null : (
<select
className={formField.root}
name="dimension"
value={params.dimension}
onChange={onChange}>{
Object.keys(options.dimensions).map((group) => (
<optgroup key={group} label={group}>{
options.dimensions[group].map((dimension) => (
<option key={dimension.id} value={dimension.id}>
{dimension.attributes.uiName}
</option>
))
}</optgroup>
))
}</select>
)}
</FormControl>
);
const dateRange = (
<FormControl full label="Time Frame">
<select
className={formField.root}
name="dateRange"
value={params.dateRange}
onChange={onChange}>
<option value="180">Past 6 months</option>
<option value="365">Past year</option>
<option value="730">Past 2 years</option>
<option value="1095">Past 3 years</option>
</select>
</FormControl>
);
const maxResults = (
<FormControl full label="Max Results">
<select
className={formField.root}
name="maxResults"
value={params.maxResults}
onChange={onChange}>
{[2, 3, 4, 5, 6, 7, 8, 9, 10].map((i) => (
<option key={i} value={i}>{i}</option>)
)}
</select>
</FormControl>
);
return (
<div className={styles.root}>
<div className={styles.item}>{metrics}</div>
<div className={styles.item}>{dimensions}</div>
<div className={styles.item}>
<div className={styles.dateRange}>{dateRange}</div>
<div className={styles.maxResults}>{maxResults}</div>
</div>
</div>
);
}
}
| {
"pile_set_name": "Github"
} |
{
"name" : "Wizzard",
"level" : 17,
"sanity" : null,
"inventory" : [
{
"name" : "Hat",
"features" : [ "magic", "pointed" ],
"traits" : {}
},
{
"name" : "Staff",
"features" : [],
"traits" : { "damage" : 10 }
},
{
"name" : "Cloak",
"features" : [ "old" ],
"traits" : { "defence" : 0, "comfort" : 3 }
}
]
}
| {
"pile_set_name": "Github"
} |
from .flops_counter import get_model_complexity_info
from .registry import Registry, build_from_cfg
__all__ = ["Registry", "build_from_cfg", "get_model_complexity_info"]
| {
"pile_set_name": "Github"
} |
MIT License
Copyright (c) Sindre Sorhus <[email protected]> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| {
"pile_set_name": "Github"
} |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
public class btStaticPlaneShape extends btConcaveShape {
private long swigCPtr;
protected btStaticPlaneShape(final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btStaticPlaneShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btStaticPlaneShape, normally you should not need this constructor it's intended for low-level usage. */
public btStaticPlaneShape(long cPtr, boolean cMemoryOwn) {
this("btStaticPlaneShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset(long cPtr, boolean cMemoryOwn) {
if (!destroyed)
destroy();
super.reset(CollisionJNI.btStaticPlaneShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr(btStaticPlaneShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize() throws Throwable {
if (!destroyed)
destroy();
super.finalize();
}
@Override protected synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btStaticPlaneShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew(long sizeInBytes) {
return CollisionJNI.btStaticPlaneShape_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete(long ptr) {
CollisionJNI.btStaticPlaneShape_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew(long arg0, long ptr) {
return CollisionJNI.btStaticPlaneShape_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete(long arg0, long arg1) {
CollisionJNI.btStaticPlaneShape_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray(long sizeInBytes) {
return CollisionJNI.btStaticPlaneShape_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray(long ptr) {
CollisionJNI.btStaticPlaneShape_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray(long arg0, long ptr) {
return CollisionJNI.btStaticPlaneShape_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray(long arg0, long arg1) {
CollisionJNI.btStaticPlaneShape_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btStaticPlaneShape(Vector3 planeNormal, float planeConstant) {
this(CollisionJNI.new_btStaticPlaneShape(planeNormal, planeConstant), true);
}
public Vector3 getPlaneNormal() {
return CollisionJNI.btStaticPlaneShape_getPlaneNormal(swigCPtr, this);
}
public float getPlaneConstant() {
return CollisionJNI.btStaticPlaneShape_getPlaneConstant(swigCPtr, this);
}
}
| {
"pile_set_name": "Github"
} |
#
# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code 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
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
# (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved
#
# The original version of this source code and documentation
# is copyrighted and owned by Taligent, Inc., a wholly-owned
# subsidiary of IBM. These materials are provided under terms
# of a License Agreement between Taligent and Sun. This technology
# is protected by multiple US and International patents.
#
# This notice and attribution to Taligent may not be removed.
# Taligent is a registered trademark of Taligent, Inc.
SYP=\u0644.\u0633.\u200f
| {
"pile_set_name": "Github"
} |
package com.simplecity.amp_library.model;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import com.simplecity.amp_library.R;
import com.simplecity.amp_library.utils.playlists.FavoritesPlaylistManager;
import com.simplecity.amp_library.utils.playlists.PlaylistManager;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;
import java.io.Serializable;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
public class Playlist implements Serializable {
private static final String TAG = "Playlist";
public @interface Type {
int PODCAST = 0;
int RECENTLY_ADDED = 1;
int MOST_PLAYED = 2;
int RECENTLY_PLAYED = 3;
int FAVORITES = 4;
int USER_CREATED = 5;
}
@Type
public int type;
public long id;
public String name;
public boolean canEdit = true;
public boolean canClear = false;
public boolean canDelete = true;
public boolean canRename = true;
public boolean canSort = true;
// These are the Playlist rows that we will retrieve.
public static final String[] PROJECTION = new String[] {
MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME
};
public static Query getQuery() {
return new Query.Builder()
.uri(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI)
.projection(PROJECTION)
.selection(null)
.sort(null)
.build();
}
public Playlist(@Type int type, long id, String name, boolean canEdit, boolean canClear, boolean canDelete, boolean canRename, boolean canSort) {
this.type = type;
this.id = id;
this.name = name;
this.canEdit = canEdit;
this.canClear = canClear;
this.canDelete = canDelete;
this.canRename = canRename;
this.canSort = canSort;
}
public Playlist(Context context, Cursor cursor) {
id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Playlists._ID));
name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.NAME));
type = Type.USER_CREATED;
canClear = true;
if (context.getString(R.string.fav_title).equals(name)) {
type = Type.FAVORITES;
canDelete = false;
canRename = false;
}
}
public void clear(PlaylistManager playlistManager, FavoritesPlaylistManager favoritesPlaylistManager) {
switch (type) {
case Playlist.Type.FAVORITES:
favoritesPlaylistManager.clearFavorites();
break;
case Playlist.Type.MOST_PLAYED:
playlistManager.clearMostPlayed();
break;
case Playlist.Type.USER_CREATED:
playlistManager.clearPlaylist(id);
break;
}
}
public void removeSong(@NonNull Song song, PlaylistManager playlistManager, @Nullable Function1<Boolean, Unit> success) {
playlistManager.removeFromPlaylist(this, song, success);
}
public boolean moveSong(Context context, int from, int to) {
return MediaStore.Audio.Playlists.Members.moveItem(context.getContentResolver(), id, from, to);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Playlist playlist = (Playlist) o;
if (id != playlist.id) return false;
return name != null ? name.equals(playlist.name) : playlist.name == null;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Playlist{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public static Song createSongFromPlaylistCursor(Cursor cursor) {
Song song = new Song(cursor);
song.id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID));
song.playlistSongId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members._ID));
song.playlistSongPlayOrder = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.PLAY_ORDER));
return song;
}
}
| {
"pile_set_name": "Github"
} |
#ifndef BOOST_CHECKED_DELETE_HPP_INCLUDED
#define BOOST_CHECKED_DELETE_HPP_INCLUDED
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
//
// boost/checked_delete.hpp
//
// Copyright (c) 2002, 2003 Peter Dimov
// Copyright (c) 2003 Daniel Frey
// Copyright (c) 2003 Howard Hinnant
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/utility/checked_delete.html for documentation.
//
namespace boost
{
// verify that types are complete for increased safety
template<class T> inline void checked_delete(T * x)
{
// intentionally complex - simplification causes regressions
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete x;
}
template<class T> inline void checked_array_delete(T * x)
{
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete [] x;
}
template<class T> struct checked_deleter
{
typedef void result_type;
typedef T * argument_type;
void operator()(T * x) const
{
// boost:: disables ADL
boost::checked_delete(x);
}
};
template<class T> struct checked_array_deleter
{
typedef void result_type;
typedef T * argument_type;
void operator()(T * x) const
{
boost::checked_array_delete(x);
}
};
} // namespace boost
#endif // #ifndef BOOST_CHECKED_DELETE_HPP_INCLUDED
| {
"pile_set_name": "Github"
} |
#%RAML 1.0
title: simple object
types:
root:
properties:
name: string
friend:
type: object
properties:
name: string
/res:
get:
body:
application/xml:
type: root
example: |
<root>
<name>robert</name>
<friend>
<name>eddard</name>
</friend>
<my-custom-xml>with-custom-value</my-custom-xml>
</root> | {
"pile_set_name": "Github"
} |
/**
* Provides a taint-tracking configuration for reasoning about command-injection
* vulnerabilities (CWE-078).
*/
import javascript
module IndirectCommandInjection {
import IndirectCommandInjectionCustomizations::IndirectCommandInjection
private import IndirectCommandArgument
/**
* A taint-tracking configuration for reasoning about command-injection vulnerabilities.
*/
class Configuration extends TaintTracking::Configuration {
Configuration() { this = "IndirectCommandInjection" }
override predicate isSource(DataFlow::Node source) { source instanceof Source }
/**
* Holds if `sink` is a data-flow sink for command-injection vulnerabilities, and
* the alert should be placed at the node `highlight`.
*/
predicate isSinkWithHighlight(DataFlow::Node sink, DataFlow::Node highlight) {
sink instanceof Sink and highlight = sink
or
isIndirectCommandArgument(sink, highlight)
}
override predicate isSink(DataFlow::Node sink) { isSinkWithHighlight(sink, _) }
override predicate isSanitizer(DataFlow::Node node) { node instanceof Sanitizer }
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
-->
<component loader="com.sun.star.loader.SharedLibrary" environment="@CPPU_ENV@"
xmlns="http://openoffice.org/2010/uno-components">
<implementation name="com.sun.star.accessibility.my_sc_implementation.MSAAService"
constructor="winaccessibility_MSAAServiceImpl_get_implementation">
<service name="com.sun.star.accessibility.MSAAService"/>
</implementation>
</component>
| {
"pile_set_name": "Github"
} |
name: "LeNet"
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 64 dim: 1 dim: 28 dim: 28 } }
}
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 20
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool1"
type: "Pooling"
bottom: "conv1"
top: "pool1"
pooling_param {
pool: MAX
kernel_size: 2
stride: 2
}
}
layer {
name: "conv2"
type: "Convolution"
bottom: "pool1"
top: "conv2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 50
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool2"
type: "Pooling"
bottom: "conv2"
top: "pool2"
pooling_param {
pool: MAX
kernel_size: 2
stride: 2
}
}
layer {
name: "ip1"
type: "InnerProduct"
bottom: "pool2"
top: "ip1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 500
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "relu1"
type: "ReLU"
bottom: "ip1"
top: "ip1"
}
layer {
name: "ip2"
type: "InnerProduct"
bottom: "ip1"
top: "ip2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 10
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "prob"
type: "Softmax"
bottom: "ip2"
top: "prob"
}
| {
"pile_set_name": "Github"
} |
//===- PtrUseVisitor.cpp - InstVisitors over a pointers uses --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file
/// Implementation of the pointer use visitors.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/PtrUseVisitor.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include <algorithm>
using namespace llvm;
void detail::PtrUseVisitorBase::enqueueUsers(Instruction &I) {
for (Use &U : I.uses()) {
if (VisitedUses.insert(&U).second) {
UseToVisit NewU = {
UseToVisit::UseAndIsOffsetKnownPair(&U, IsOffsetKnown),
Offset
};
Worklist.push_back(std::move(NewU));
}
}
}
bool detail::PtrUseVisitorBase::adjustOffsetForGEP(GetElementPtrInst &GEPI) {
if (!IsOffsetKnown)
return false;
APInt TmpOffset(DL.getIndexTypeSizeInBits(GEPI.getType()), 0);
if (GEPI.accumulateConstantOffset(DL, TmpOffset)) {
Offset += TmpOffset.sextOrTrunc(Offset.getBitWidth());
return true;
}
return false;
}
| {
"pile_set_name": "Github"
} |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2015 The ZAP Development Team
*
* 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.zaproxy.zap.extension.fuzz.payloads;
import java.util.Collection;
import java.util.Iterator;
import org.zaproxy.zap.utils.ResettableAutoCloseableIterator;
public class PayloadCollectionIterator<E extends Payload>
implements ResettableAutoCloseableIterator<E> {
private final Collection<E> payloads;
private Iterator<E> payloadIterator;
public PayloadCollectionIterator(Collection<E> payloads) {
this.payloads = payloads;
initIterator();
}
private void initIterator() {
payloadIterator = payloads.iterator();
}
@Override
public boolean hasNext() {
return payloadIterator.hasNext();
}
@Override
public E next() {
return payloadIterator.next();
}
@Override
public void remove() {}
@Override
public void reset() {
initIterator();
}
@Override
public void close() {}
}
| {
"pile_set_name": "Github"
} |
(function($) {
$.extend($.summernote.lang, {
'fi-FI': {
font: {
bold: 'Lihavointi',
italic: 'Kursivointi',
underline: 'Alleviivaus',
clear: 'Tyhjennä muotoilu',
height: 'Riviväli',
name: 'Kirjasintyyppi',
strikethrough: 'Yliviivaus',
subscript: 'Alaindeksi',
superscript: 'Yläindeksi',
size: 'Kirjasinkoko'
},
image: {
image: 'Kuva',
insert: 'Lisää kuva',
resizeFull: 'Koko leveys',
resizeHalf: 'Puolikas leveys',
resizeQuarter: 'Neljäsosa leveys',
floatLeft: 'Sijoita vasemmalle',
floatRight: 'Sijoita oikealle',
floatNone: 'Ei sijoitusta',
shapeRounded: 'Muoto: Pyöristetty',
shapeCircle: 'Muoto: Ympyrä',
shapeThumbnail: 'Muoto: Esikatselukuva',
shapeNone: 'Muoto: Ei muotoilua',
dragImageHere: 'Vedä kuva tähän',
selectFromFiles: 'Valitse tiedostoista',
maximumFileSize: 'Maksimi tiedosto koko',
maximumFileSizeError: 'Maksimi tiedosto koko ylitetty.',
url: 'URL-osoitteen mukaan',
remove: 'Poista kuva',
original: 'Alkuperäinen'
},
video: {
video: 'Video',
videoLink: 'Linkki videoon',
insert: 'Lisää video',
url: 'Videon URL-osoite',
providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion tai Youku)'
},
link: {
link: 'Linkki',
insert: 'Lisää linkki',
unlink: 'Poista linkki',
edit: 'Muokkaa',
textToDisplay: 'Näytettävä teksti',
url: 'Linkin URL-osoite',
openInNewWindow: 'Avaa uudessa ikkunassa'
},
table: {
table: 'Taulukko',
addRowAbove: 'Lisää rivi yläpuolelle',
addRowBelow: 'Lisää rivi alapuolelle',
addColLeft: 'Lisää sarake vasemmalle puolelle',
addColRight: 'Lisää sarake oikealle puolelle',
delRow: 'Poista rivi',
delCol: 'Poista sarake',
delTable: 'Poista taulukko'
},
hr: {
insert: 'Lisää vaakaviiva'
},
style: {
style: 'Tyyli',
p: 'Normaali',
blockquote: 'Lainaus',
pre: 'Koodi',
h1: 'Otsikko 1',
h2: 'Otsikko 2',
h3: 'Otsikko 3',
h4: 'Otsikko 4',
h5: 'Otsikko 5',
h6: 'Otsikko 6'
},
lists: {
unordered: 'Luettelomerkitty luettelo',
ordered: 'Numeroitu luettelo'
},
options: {
help: 'Ohje',
fullscreen: 'Koko näyttö',
codeview: 'HTML-näkymä'
},
paragraph: {
paragraph: 'Kappale',
outdent: 'Pienennä sisennystä',
indent: 'Suurenna sisennystä',
left: 'Tasaa vasemmalle',
center: 'Keskitä',
right: 'Tasaa oikealle',
justify: 'Tasaa'
},
color: {
recent: 'Viimeisin väri',
more: 'Lisää värejä',
background: 'Korostusväri',
foreground: 'Tekstin väri',
transparent: 'Läpinäkyvä',
setTransparent: 'Aseta läpinäkyväksi',
reset: 'Palauta',
resetToDefault: 'Palauta oletusarvoksi'
},
shortcut: {
shortcuts: 'Pikanäppäimet',
close: 'Sulje',
textFormatting: 'Tekstin muotoilu',
action: 'Toiminto',
paragraphFormatting: 'Kappaleen muotoilu',
documentStyle: 'Asiakirjan tyyli'
},
help: {
'insertParagraph': 'Lisää kappale',
'undo': 'Kumoa viimeisin komento',
'redo': 'Tee uudelleen kumottu komento',
'tab': 'Sarkain',
'untab': 'Sarkainmerkin poisto',
'bold': 'Lihavointi',
'italic': 'Kursiivi',
'underline': 'Alleviivaus',
'strikethrough': 'Yliviivaus',
'removeFormat': 'Poista asetetut tyylit',
'justifyLeft': 'Tasaa vasemmalle',
'justifyCenter': 'Keskitä',
'justifyRight': 'Tasaa oikealle',
'justifyFull': 'Tasaa',
'insertUnorderedList': 'Luettelomerkillä varustettu lista',
'insertOrderedList': 'Numeroitu lista',
'outdent': 'Pienennä sisennystä',
'indent': 'Suurenna sisennystä',
'formatPara': 'Muuta kappaleen formaatti p',
'formatH1': 'Muuta kappaleen formaatti H1',
'formatH2': 'Muuta kappaleen formaatti H2',
'formatH3': 'Muuta kappaleen formaatti H3',
'formatH4': 'Muuta kappaleen formaatti H4',
'formatH5': 'Muuta kappaleen formaatti H5',
'formatH6': 'Muuta kappaleen formaatti H6',
'insertHorizontalRule': 'Lisää vaakaviiva',
'linkDialog.show': 'Lisää linkki'
},
history: {
undo: 'Kumoa',
redo: 'Toista'
},
specialChar: {
specialChar: 'ERIKOISMERKIT',
select: 'Valitse erikoismerkit'
}
}
});
})(jQuery);
| {
"pile_set_name": "Github"
} |
import React from "react";
import { MediaGrid, ImageMediaGridItem } from "./MediaGrid";
import defaultThumbnailUrl from "../../assets/default-thumbnail.png";
import { VerticalScrollContainer } from "./Flex";
export default {
title: "MediaGrid",
component: MediaGrid
};
export const mediaGrid = () => (
<VerticalScrollContainer height={320}>
<MediaGrid>
{new Array(25).fill(0).map((_, index) => (
<ImageMediaGridItem
key={index}
tabIndex={index}
selected={index === 3}
src={defaultThumbnailUrl}
label={`Item ${index}`}
/>
))}
</MediaGrid>
</VerticalScrollContainer>
);
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* 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.drools.examples.troubleticket;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
/**
* This shows off a decision table.
*/
public class TroubleTicketExampleWithDT {
public static void main(final String[] args) {
KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();
execute( kc );
}
public static void execute( KieContainer kc ) {
KieSession ksession = kc.newKieSession( "TroubleTicketWithDTKS" );
final Customer a = new Customer( "A",
"Drools",
"Gold" );
final Customer b = new Customer( "B",
"Drools",
"Platinum" );
final Customer c = new Customer( "C",
"Drools",
"Silver" );
final Customer d = new Customer( "D",
"Drools",
"Silver" );
final Ticket t1 = new Ticket( a );
final Ticket t2 = new Ticket( b );
final Ticket t3 = new Ticket( c );
final Ticket t4 = new Ticket( d );
ksession.insert( a );
ksession.insert( b );
ksession.insert( c );
ksession.insert( d );
ksession.insert( t1 );
ksession.insert( t2 );
final FactHandle ft3 = ksession.insert( t3 );
ksession.insert( t4 );
ksession.fireAllRules();
t3.setStatus( "Done" );
ksession.update( ft3,
t3 );
try {
System.err.println( "[[ Sleeping 5 seconds ]]" );
Thread.sleep( 5000 );
} catch ( final InterruptedException e ) {
e.printStackTrace();
}
System.err.println( "[[ awake ]]" );
ksession.dispose();
}
}
| {
"pile_set_name": "Github"
} |
# Copyright (C) 2019 Automattic
# This file is distributed under the GNU General Public License v2 or later.
msgid ""
msgstr ""
"Project-Id-Version: Maywood 1.4.2\n"
"Report-Msgid-Bugs-To: http://wordpress.org/support/theme/maywood\n"
"POT-Creation-Date: 2019-08-28 16:20:11+00:00\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"PO-Revision-Date: 2019-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
#: functions.php:30
msgid "Small"
msgstr ""
#: functions.php:31
msgid "S"
msgstr ""
#: functions.php:36
msgid "Normal"
msgstr ""
#: functions.php:37
msgid "M"
msgstr ""
#: functions.php:42
msgid "Large"
msgstr ""
#: functions.php:43
msgid "L"
msgstr ""
#: functions.php:48
msgid "Huge"
msgstr ""
#: functions.php:49
msgid "XL"
msgstr ""
#: functions.php:61
msgid "Primary"
msgstr ""
#: functions.php:66
msgid "Secondary"
msgstr ""
#: functions.php:71
msgid "Black"
msgstr ""
#: functions.php:76
msgid "Dark Gray"
msgstr ""
#: functions.php:81
msgid "Gray"
msgstr ""
#: functions.php:86
msgid "Light Gray"
msgstr ""
#: functions.php:91
msgid "Subtle Gray"
msgstr ""
#: functions.php:96
msgid "White"
msgstr ""
#. Translators: If there are characters in your language that are not supported
#. by IBM Plex Sans, translate this to 'off'. Do not translate into your own
#. language.
#: functions.php:127
msgctxt "IBM Plex Sans font: on or off"
msgid "on"
msgstr ""
#. Theme Name of the plugin/theme
#: wp-content/themes/pub/maywood/style.css
msgid "Maywood"
msgstr ""
#. Theme URI of the plugin/theme
#: wp-content/themes/pub/maywood/style.css
msgid "https://github.com/Automattic/themes/tree/master/maywood"
msgstr ""
#. Description of the plugin/theme
#: wp-content/themes/pub/maywood/style.css
msgid ""
"Maywood is a refined theme designed for restaurants and food-related "
"businesses seeking a modern look."
msgstr ""
#. Author of the plugin/theme
#: wp-content/themes/pub/maywood/style.css
msgid "Automattic"
msgstr ""
#. Author URI of the plugin/theme
#: wp-content/themes/pub/maywood/style.css
msgid "https://automattic.com/"
msgstr ""
| {
"pile_set_name": "Github"
} |
package sqlmock
import (
"database/sql/driver"
"fmt"
"reflect"
"regexp"
"strings"
"sync"
)
// Argument interface allows to match
// any argument in specific way when used with
// ExpectedQuery and ExpectedExec expectations.
type Argument interface {
Match(driver.Value) bool
}
// an expectation interface
type expectation interface {
fulfilled() bool
Lock()
Unlock()
String() string
}
// common expectation struct
// satisfies the expectation interface
type commonExpectation struct {
sync.Mutex
triggered bool
err error
}
func (e *commonExpectation) fulfilled() bool {
return e.triggered
}
// ExpectedClose is used to manage *sql.DB.Close expectation
// returned by *Sqlmock.ExpectClose.
type ExpectedClose struct {
commonExpectation
}
// WillReturnError allows to set an error for *sql.DB.Close action
func (e *ExpectedClose) WillReturnError(err error) *ExpectedClose {
e.err = err
return e
}
// String returns string representation
func (e *ExpectedClose) String() string {
msg := "ExpectedClose => expecting database Close"
if e.err != nil {
msg += fmt.Sprintf(", which should return error: %s", e.err)
}
return msg
}
// ExpectedBegin is used to manage *sql.DB.Begin expectation
// returned by *Sqlmock.ExpectBegin.
type ExpectedBegin struct {
commonExpectation
}
// WillReturnError allows to set an error for *sql.DB.Begin action
func (e *ExpectedBegin) WillReturnError(err error) *ExpectedBegin {
e.err = err
return e
}
// String returns string representation
func (e *ExpectedBegin) String() string {
msg := "ExpectedBegin => expecting database transaction Begin"
if e.err != nil {
msg += fmt.Sprintf(", which should return error: %s", e.err)
}
return msg
}
// ExpectedCommit is used to manage *sql.Tx.Commit expectation
// returned by *Sqlmock.ExpectCommit.
type ExpectedCommit struct {
commonExpectation
}
// WillReturnError allows to set an error for *sql.Tx.Close action
func (e *ExpectedCommit) WillReturnError(err error) *ExpectedCommit {
e.err = err
return e
}
// String returns string representation
func (e *ExpectedCommit) String() string {
msg := "ExpectedCommit => expecting transaction Commit"
if e.err != nil {
msg += fmt.Sprintf(", which should return error: %s", e.err)
}
return msg
}
// ExpectedRollback is used to manage *sql.Tx.Rollback expectation
// returned by *Sqlmock.ExpectRollback.
type ExpectedRollback struct {
commonExpectation
}
// WillReturnError allows to set an error for *sql.Tx.Rollback action
func (e *ExpectedRollback) WillReturnError(err error) *ExpectedRollback {
e.err = err
return e
}
// String returns string representation
func (e *ExpectedRollback) String() string {
msg := "ExpectedRollback => expecting transaction Rollback"
if e.err != nil {
msg += fmt.Sprintf(", which should return error: %s", e.err)
}
return msg
}
// ExpectedQuery is used to manage *sql.DB.Query, *dql.DB.QueryRow, *sql.Tx.Query,
// *sql.Tx.QueryRow, *sql.Stmt.Query or *sql.Stmt.QueryRow expectations.
// Returned by *Sqlmock.ExpectQuery.
type ExpectedQuery struct {
queryBasedExpectation
rows driver.Rows
}
// WithArgs will match given expected args to actual database query arguments.
// if at least one argument does not match, it will return an error. For specific
// arguments an sqlmock.Argument interface can be used to match an argument.
func (e *ExpectedQuery) WithArgs(args ...driver.Value) *ExpectedQuery {
e.args = args
return e
}
// WillReturnError allows to set an error for expected database query
func (e *ExpectedQuery) WillReturnError(err error) *ExpectedQuery {
e.err = err
return e
}
// WillReturnRows specifies the set of resulting rows that will be returned
// by the triggered query
func (e *ExpectedQuery) WillReturnRows(rows driver.Rows) *ExpectedQuery {
e.rows = rows
return e
}
// String returns string representation
func (e *ExpectedQuery) String() string {
msg := "ExpectedQuery => expecting Query or QueryRow which:"
msg += "\n - matches sql: '" + e.sqlRegex.String() + "'"
if len(e.args) == 0 {
msg += "\n - is without arguments"
} else {
msg += "\n - is with arguments:\n"
for i, arg := range e.args {
msg += fmt.Sprintf(" %d - %+v\n", i, arg)
}
msg = strings.TrimSpace(msg)
}
if e.rows != nil {
msg += "\n - should return rows:\n"
rs, _ := e.rows.(*rows)
for i, row := range rs.rows {
msg += fmt.Sprintf(" %d - %+v\n", i, row)
}
msg = strings.TrimSpace(msg)
}
if e.err != nil {
msg += fmt.Sprintf("\n - should return error: %s", e.err)
}
return msg
}
// ExpectedExec is used to manage *sql.DB.Exec, *sql.Tx.Exec or *sql.Stmt.Exec expectations.
// Returned by *Sqlmock.ExpectExec.
type ExpectedExec struct {
queryBasedExpectation
result driver.Result
}
// WithArgs will match given expected args to actual database exec operation arguments.
// if at least one argument does not match, it will return an error. For specific
// arguments an sqlmock.Argument interface can be used to match an argument.
func (e *ExpectedExec) WithArgs(args ...driver.Value) *ExpectedExec {
e.args = args
return e
}
// WillReturnError allows to set an error for expected database exec action
func (e *ExpectedExec) WillReturnError(err error) *ExpectedExec {
e.err = err
return e
}
// String returns string representation
func (e *ExpectedExec) String() string {
msg := "ExpectedExec => expecting Exec which:"
msg += "\n - matches sql: '" + e.sqlRegex.String() + "'"
if len(e.args) == 0 {
msg += "\n - is without arguments"
} else {
msg += "\n - is with arguments:\n"
var margs []string
for i, arg := range e.args {
margs = append(margs, fmt.Sprintf(" %d - %+v", i, arg))
}
msg += strings.Join(margs, "\n")
}
if e.result != nil {
res, _ := e.result.(*result)
msg += "\n - should return Result having:"
msg += fmt.Sprintf("\n LastInsertId: %d", res.insertID)
msg += fmt.Sprintf("\n RowsAffected: %d", res.rowsAffected)
if res.err != nil {
msg += fmt.Sprintf("\n Error: %s", res.err)
}
}
if e.err != nil {
msg += fmt.Sprintf("\n - should return error: %s", e.err)
}
return msg
}
// WillReturnResult arranges for an expected Exec() to return a particular
// result, there is sqlmock.NewResult(lastInsertID int64, affectedRows int64) method
// to build a corresponding result. Or if actions needs to be tested against errors
// sqlmock.NewErrorResult(err error) to return a given error.
func (e *ExpectedExec) WillReturnResult(result driver.Result) *ExpectedExec {
e.result = result
return e
}
// ExpectedPrepare is used to manage *sql.DB.Prepare or *sql.Tx.Prepare expectations.
// Returned by *Sqlmock.ExpectPrepare.
type ExpectedPrepare struct {
commonExpectation
mock *sqlmock
sqlRegex *regexp.Regexp
statement driver.Stmt
closeErr error
}
// WillReturnError allows to set an error for the expected *sql.DB.Prepare or *sql.Tx.Prepare action.
func (e *ExpectedPrepare) WillReturnError(err error) *ExpectedPrepare {
e.err = err
return e
}
// WillReturnCloseError allows to set an error for this prapared statement Close action
func (e *ExpectedPrepare) WillReturnCloseError(err error) *ExpectedPrepare {
e.closeErr = err
return e
}
// ExpectQuery allows to expect Query() or QueryRow() on this prepared statement.
// this method is convenient in order to prevent duplicating sql query string matching.
func (e *ExpectedPrepare) ExpectQuery() *ExpectedQuery {
eq := &ExpectedQuery{}
eq.sqlRegex = e.sqlRegex
e.mock.expected = append(e.mock.expected, eq)
return eq
}
// ExpectExec allows to expect Exec() on this prepared statement.
// this method is convenient in order to prevent duplicating sql query string matching.
func (e *ExpectedPrepare) ExpectExec() *ExpectedExec {
eq := &ExpectedExec{}
eq.sqlRegex = e.sqlRegex
e.mock.expected = append(e.mock.expected, eq)
return eq
}
// String returns string representation
func (e *ExpectedPrepare) String() string {
msg := "ExpectedPrepare => expecting Prepare statement which:"
msg += "\n - matches sql: '" + e.sqlRegex.String() + "'"
if e.err != nil {
msg += fmt.Sprintf("\n - should return error: %s", e.err)
}
if e.closeErr != nil {
msg += fmt.Sprintf("\n - should return error on Close: %s", e.closeErr)
}
return msg
}
// query based expectation
// adds a query matching logic
type queryBasedExpectation struct {
commonExpectation
sqlRegex *regexp.Regexp
args []driver.Value
}
func (e *queryBasedExpectation) attemptMatch(sql string, args []driver.Value) (ret bool) {
if !e.queryMatches(sql) {
return
}
defer recover() // ignore panic since we attempt a match
if e.argsMatches(args) {
return true
}
return
}
func (e *queryBasedExpectation) queryMatches(sql string) bool {
return e.sqlRegex.MatchString(sql)
}
func (e *queryBasedExpectation) argsMatches(args []driver.Value) bool {
if nil == e.args {
return true
}
if len(args) != len(e.args) {
return false
}
for k, v := range args {
matcher, ok := e.args[k].(Argument)
if ok {
if !matcher.Match(v) {
return false
}
continue
}
vi := reflect.ValueOf(v)
ai := reflect.ValueOf(e.args[k])
switch vi.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if vi.Int() != ai.Int() {
return false
}
case reflect.Float32, reflect.Float64:
if vi.Float() != ai.Float() {
return false
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if vi.Uint() != ai.Uint() {
return false
}
case reflect.String:
if vi.String() != ai.String() {
return false
}
case reflect.Bool:
if vi.Bool() != ai.Bool() {
return false
}
default:
// compare types like time.Time based on type only
if vi.Kind() != ai.Kind() {
return false
}
}
}
return true
}
| {
"pile_set_name": "Github"
} |
using FSO.Client;
using FSO.Common.Rendering.Framework;
using FSO.Common.Rendering.Framework.Camera;
using FSO.Content;
using FSO.SimAntics;
using FSO.SimAntics.Model;
using FSO.Vitaboy;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FSO.Client.UI.Model
{
/// <summary>
/// Caches icons for objects missing them, eg. heads, some catalog objects..
/// </summary>
public static class UIIconCache
{
//indexed as mesh:texture
private static Dictionary<ulong, Texture2D> AvatarHeadCache = new Dictionary<ulong, Texture2D>();
/*
public static Texture2D GetObject(VMEntity obj)
{
if (obj is VMAvatar)
{
var ava = (VMAvatar)obj;
var headname = ava.HeadOutfit.Name;
if (headname == "") headname = ava.BodyOutfit.OftData.TS1TextureID;
var id = headname +":"+ ava.HeadOutfit.OftData.TS1TextureID;
Texture2D result = null;
if (!AvatarHeadCache.TryGetValue(id, out result))
{
result = GenHeadTex(ava);
AvatarHeadCache[id] = result;
}
return result;
}
else if (obj is VMGameObject)
{
if (obj.Object.OBJ.GUID == 0x000007C4) return Content.Get().CustomUI.Get("int_gohere.png").Get(GameFacade.GraphicsDevice);
else return obj.GetIcon(GameFacade.GraphicsDevice, 0);
}
return null;
}*/
public static Texture2D GetObject(VMEntity obj)
{
if (obj is VMAvatar)
{
var ava = (VMAvatar)obj;
return GenHeadTex(ava.HeadOutfit?.ID ?? 0, ava.BodyOutfit.ID);
}
return null;
}
public static Texture2D GenHeadTex(ulong headOft, ulong bodyOft)
{
if (headOft == 0) headOft = bodyOft;
Texture2D result = null;
if (!AvatarHeadCache.TryGetValue(headOft, out result))
{
var ofts = Content.Content.Get().AvatarOutfits;
var oft = ofts.Get(headOft);
if (oft == null) return null;
else
{
result = GenHeadTex(oft, ofts.GetNameByID(headOft));
}
AvatarHeadCache[headOft] = result;
}
return result;
}
public static Texture2D GenHeadTex(Outfit headOft, string name)
{
var skels = Content.Content.Get().AvatarSkeletons;
Skeleton skel = null;
bool pet = false;
if (name.StartsWith("uaa"))
{
//pet
if (name.Contains("cat")) skel = skels.Get("cat.skel");
else skel = skels.Get("dog.skel");
pet = true;
} else
{
skel = skels.Get("adult.skel");
}
var m_Head = new SimAvatar(skel);
m_Head.Head = headOft;
m_Head.ReloadSkeleton();
m_Head.StripAllButHead();
var HeadCamera = new BasicCamera(GameFacade.GraphicsDevice, new Vector3(0.0f, 7.0f, -17.0f), Vector3.Zero, Vector3.Up);
var pos2 = m_Head.Skeleton.GetBone("HEAD").AbsolutePosition;
pos2.Y += (pet)?((name.Contains("dog"))?0.16f:0.1f):0.12f;
HeadCamera.Position = new Vector3(0, pos2.Y, 12.5f);
HeadCamera.FOV = (float)Math.PI / 3f;
HeadCamera.Target = pos2;
HeadCamera.ProjectionOrigin = new Vector2(66/2, 66/2);
var HeadScene = new _3DTargetScene(GameFacade.GraphicsDevice, HeadCamera, new Point(66, 66), 0);// (GlobalSettings.Default.AntiAlias) ? 8 : 0);
HeadScene.ID = "UIPieMenuHead";
HeadScene.ClearColor = new Color(49, 65, 88);
m_Head.Scene = HeadScene;
m_Head.Scale = new Vector3(1f);
HeadCamera.Zoom = 19.5f;
//rotate camera, similar to pie menu
double xdir = 0;//Math.Atan(0);
double ydir = 0;//Math.Atan(0);
Vector3 off = new Vector3(0, 0, 13.5f);
Matrix mat = Microsoft.Xna.Framework.Matrix.CreateRotationY((float)xdir) * Microsoft.Xna.Framework.Matrix.CreateRotationX((float)ydir);
HeadCamera.Position = new Vector3(0, pos2.Y, 0) + Vector3.Transform(off, mat);
if (pet)
{
HeadCamera.Zoom *= 1.3f;
}
//end rotate camera
HeadScene.Initialize(GameFacade.Scenes);
HeadScene.Add(m_Head);
HeadScene.Draw(GameFacade.GraphicsDevice);
return Common.Utils.TextureUtils.Decimate(HeadScene.Target, GameFacade.GraphicsDevice, 2, true);
}
}
}
| {
"pile_set_name": "Github"
} |
{
"name": "kill",
"displayName": "Kill",
"description": "Kill an app",
"examples": ["kill atom", "kill safari"],
"categories": ["Utilities"],
"creator_name": "Jeff Shaver",
"creator_url": "https://twitter.com/jeffshaver_"
}
| {
"pile_set_name": "Github"
} |
var gqlwx = require('../graphql/wxgql');
var GraphQL = gqlwx.GraphQL;
var gql = GraphQL(
{
//设置全局url
url: 'https://users.authing.cn/graphql', // url必填
//设置全居动态header
header: function () {
return {
// something....
'X-Test-Header': 'test header content'
}
},
//设置全居错误拦截
errorHandler: function (res) {
//do something
}
}, true
);
module.exports = gql;
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_08_01;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for ProcessorArchitecture.
*/
public final class ProcessorArchitecture extends ExpandableStringEnum<ProcessorArchitecture> {
/** Static value Amd64 for ProcessorArchitecture. */
public static final ProcessorArchitecture AMD64 = fromString("Amd64");
/** Static value X86 for ProcessorArchitecture. */
public static final ProcessorArchitecture X86 = fromString("X86");
/**
* Creates or finds a ProcessorArchitecture from its string representation.
* @param name a name to look for
* @return the corresponding ProcessorArchitecture
*/
@JsonCreator
public static ProcessorArchitecture fromString(String name) {
return fromString(name, ProcessorArchitecture.class);
}
/**
* @return known ProcessorArchitecture values
*/
public static Collection<ProcessorArchitecture> values() {
return values(ProcessorArchitecture.class);
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2017 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 !gccgo
#include "textflag.h"
//
// System call support for ARM, OpenBSD
//
// Just jump to package syscall's implementation for all these functions.
// The runtime may know about them.
TEXT ·Syscall(SB),NOSPLIT,$0-28
B syscall·Syscall(SB)
TEXT ·Syscall6(SB),NOSPLIT,$0-40
B syscall·Syscall6(SB)
TEXT ·Syscall9(SB),NOSPLIT,$0-52
B syscall·Syscall9(SB)
TEXT ·RawSyscall(SB),NOSPLIT,$0-28
B syscall·RawSyscall(SB)
TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
B syscall·RawSyscall6(SB)
| {
"pile_set_name": "Github"
} |
// MARK: JSON
public enum JSON
{
case string(Swift.String)
case number(Double)
case bool(Swift.Bool)
case null
case array([JSON])
case object([Swift.String : JSON])
}
// MARK: RawRepresentable
extension JSON: RawRepresentable
{
public init?(rawValue: Any)
{
switch rawValue {
case let v as Swift.String:
self = .string(v)
case let v as DoubleType:
self = .number(v.double)
case let v as Swift.Bool:
self = .bool(v)
case is ():
self = .null
case let v as [JSON]:
self = .array(v)
case let v as [Swift.String : JSON]:
self = .object(v)
default:
return nil
}
}
public var rawValue: Any
{
switch self {
case let .string(v): return v
case let .number(v): return v
case let .bool(v): return v
case .null: return ()
case let .array(v): return v
case let .object(v): return v
}
}
}
// MARK: Equatable
extension JSON: Equatable {}
public func == (lhs: JSON, rhs: JSON) -> Bool
{
switch (lhs, rhs) {
case let (.string(l), .string(r)):
return l == r
case let (.number(l), .number(r)):
return l == r
case let (.bool(l), .bool(r)):
return l == r
case (.null, .null):
return true
case let (.array(l), .array(r)):
return l == r
case let (.object(l), .object(r)):
return l == r
default:
return false
}
}
// MARK: CustomStringConvertible
extension JSON: CustomStringConvertible
{
public var description: Swift.String
{
switch self {
case let .string(v): return ".string(\(v))"
case let .number(v): return ".number(\(v))"
case let .bool(v): return ".bool(\(v))"
case .null: return ".null"
case let .array(v): return ".array(\(v.description))"
case let .object(v): return ".object(\(v.description))"
}
}
}
// MARK: Accessors
extension JSON
{
public subscript(index: Int) -> JSON?
{
return self.rawArray?[index]
}
public subscript(key: Swift.String) -> JSON?
{
return self.rawObject?[key]
}
public var rawString: Swift.String?
{
switch self {
case let .string(v): return v
default: return nil
}
}
public var rawNumber: Double?
{
switch self {
case let .number(v): return v
default: return nil
}
}
public var rawBool: Swift.Bool?
{
switch self {
case let .bool(v): return v
default: return nil
}
}
public var rawNull: ()?
{
switch self {
case .null: return ()
default: return nil
}
}
public var rawArray: [JSON]?
{
switch self {
case let .array(v): return v
default: return nil
}
}
public var rawObject: [Swift.String : JSON]?
{
switch self {
case let .object(v): return v
default: return nil
}
}
public var jsonString: Swift.String
{
switch self {
case let .string(v): return "\"\(v)\""
case let .number(v): return "\(v)"
case let .bool(v): return "\(v)"
case .null: return "null"
case let .array(v):
let valuesString = v.reduce("") {
($0 == "" ? "" : $0 + ", ") + $1.jsonString
}
return "[ " + valuesString + " ]"
case let .object(v):
let keyValuesString = v.reduce("") {
($0 == "" ? "\"" : $0 + ", \"") + $1.0 + "\" : " + $1.1.jsonString
}
return "{ " + keyValuesString + " }"
}
}
}
// MARK: JSON.ParseError
extension JSON
{
public enum ParseError: Error
{
case invalidJSONFormat
case typeMismatched(expected: Swift.String, actual: Swift.String)
case keyNotFound(Swift.String)
}
}
| {
"pile_set_name": "Github"
} |
form=未知
tags=
美女妖且闲,
采桑歧路间。
柔条纷冉冉,
落叶何翩翩。
攘袖见素手,
皓腕约金环。
头上金爵钗,
腰佩翠琅玕。
明珠交玉体,
珊瑚间木难。
罗衣何飘摇,
轻裾随风还。
顾盼遗光彩,
长啸气若兰。
行徒用息驾,
休者以忘餐。
借问女安居,
乃在城南端。
青楼临大路,
高门结重关。
容华耀朝日,
谁不希令颜?
媒氏何所营?
玉帛不时安。
佳人慕高义,
求贤良独难。
众人徒嗷嗷,
安知彼所观?
盛年处房室,
中夜起长叹。
| {
"pile_set_name": "Github"
} |
name = 'HDF5'
version = '1.10.2'
homepage = 'https://portal.hdfgroup.org/display/support'
description = """HDF5 is a data model, library, and file format for storing and managing data.
It supports an unlimited variety of datatypes, and is designed for flexible
and efficient I/O and for high volume and complex data."""
toolchain = {'name': 'PGI', 'version': '18.4-GCC-6.4.0-2.28'}
toolchainopts = {'pic': True}
source_urls = ['https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-%(version_major_minor)s/hdf5-%(version)s/src']
sources = [SOURCELOWER_TAR_GZ]
checksums = [
'bfec1be8c366965a99812cf02ddc97e4b708c1754fccba5414d4adccdc073866', # hdf5-1.10.2.tar.gz
]
# Add -noswitcherror to make PGI compiler ignore the unknown compiler option -pthread
preconfigopts = 'export CXX="$CXX -noswitcherror" && '
dependencies = [
('zlib', '1.2.11'),
('Szip', '2.1.1'),
]
moduleclass = 'data'
| {
"pile_set_name": "Github"
} |
/* Auto-generated from php/php-langspec tests */
<?php
/*
+-------------------------------------------------------------+
| Copyright (c) 2014 Facebook, Inc. (http://www.facebook.com) |
+-------------------------------------------------------------+
*/
error_reporting(-1);
include_once 'MathLibrary.inc';
// $m = new MathLibrary; // can't instantiate a final class
MathLibrary::sin(2.34);
MathLibrary::cos(2.34);
MathLibrary::tan(2.34);
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>MathJax Example Page</title>
<!-- Copyright (c) 2012-2017 The MathJax Consortium -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
li {margin-top: .2em}
</style>
</head>
<body>
<h1>MathJax Example Pages</h1>
View the page source for any of these examples to see how they work.
<ul>
<li><a href="sample-tex.html">Page using TeX notation</a></li>
<li><a href="sample-mml.html">Page using MathML notation</a></li>
<li><a href="sample-asciimath.html">Page using AsciiMath notation</a></li>
<li><a href="sample.html">Page included several examples TeX equations</a></li>
<li><a href="sample-eqnum.html">Page of TeX equations with automatic numbering</a></li>
<li><a href="sample-eqrefs.html">Page of TeX equations with equation references</a></li>
<p>
<li><a href="sample-macros.html">Example of defining TeX macros</a></li>
<li><a href="sample-autoload.html">Defining macros to autoload the extensions in
which they are implemented</a></li>
<p>
<li><a href="sample-all-at-once.html">Example of waiting until all the
math is typeset before displaying the page (avoids "flicker")</a></li>
<p>
<li><a href="sample-dynamic-steps.html">Showing an equation one step at a time</a></li>
<li><a href="sample-dynamic.html">Display an equation typed in by a user</a></li>
<li><a href="sample-dynamic-2.html">Preview text containing math typed in by a user</a></li>
<p>
<li><a href="sample-loader.html">Loading MathJax into a page after it is loaded</a></li>
<li><a href="sample-loader-config.html">Loading MathJax dynamically with in-line configuration</a></li>
<p>
<li><a href="sample-signals.html">Page showing MathJax signals during page processing</a></li>
</ul>
</body>
</html>
| {
"pile_set_name": "Github"
} |
import flat from "array.prototype.flat";
import { fromEntries } from "./object-entries";
type LineIndex = number;
type ColumnIndex = number;
export function parseFocus(focus: string) {
if (!focus) {
throw new Error("Focus cannot be empty");
}
try {
const parts = focus.split(/,(?![^\[]*\])/g).map(parsePart);
return fromEntries(flat(parts));
} catch (error) {
// TODO enhance error
throw error;
}
}
type Part = [LineIndex, true | ColumnIndex[]];
function parsePart(part: string): Part[] {
// a part could be
// - a line number: "2"
// - a line range: "5:9"
// - a line number with a column selector: "2[1,3:5,9]"
const columnsMatch = part.match(/(\d+)\[(.+)\]/);
if (columnsMatch) {
const [, line, columns] = columnsMatch;
const columnsList = columns.split(",").map(expandString);
const lineIndex = Number(line) - 1;
const columnIndexes = flat(columnsList).map(c => c - 1);
return [[lineIndex, columnIndexes]];
} else {
return expandString(part).map(lineNumber => [lineNumber - 1, true]);
}
}
function expandString(part: string) {
// Transforms something like
// - "1:3" to [1,2,3]
// - "4" to [4]
const [start, end] = part.split(":");
if (!isNaturalNumber(start)) {
throw new FocusNumberError(start);
}
const startNumber = Number(start);
if (startNumber < 1) {
throw new LineOrColumnNumberError();
}
if (!end) {
return [startNumber];
} else {
if (!isNaturalNumber(end)) {
throw new FocusNumberError(end);
}
const list: number[] = [];
for (let i = startNumber; i <= +end; i++) {
list.push(i);
}
return list;
}
}
function isNaturalNumber(n: any) {
n = n.toString(); // force the value in case it is not
var n1 = Math.abs(n),
n2 = parseInt(n, 10);
return !isNaN(n1) && n2 === n1 && n1.toString() === n;
}
export function getFocusSize(focus: Record<LineIndex, true | ColumnIndex[]>) {
const lineIndexList = Object.keys(focus).map(k => +k);
const focusStart = Math.min.apply(Math, lineIndexList);
const focusEnd = Math.max.apply(Math, lineIndexList);
return {
focusCenter: (focusStart + focusEnd + 1) / 2,
focusCount: focusEnd - focusStart + 1
};
}
export class LineOrColumnNumberError extends Error {
constructor() {
super(`Invalid line or column number in focus string`);
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class FocusNumberError extends Error {
number: string;
constructor(number: string) {
super(`Invalid number "${number}" in focus string`);
this.number = number;
Object.setPrototypeOf(this, new.target.prototype);
}
}
| {
"pile_set_name": "Github"
} |
using UnityEngine;
using System.Collections;
public class Shell : MonoBehaviour {
public Rigidbody myRigidbody;
public float forceMin;
public float forceMax;
float lifetime = 4;
float fadetime = 2;
void Start () {
float force = Random.Range (forceMin, forceMax);
myRigidbody.AddForce (transform.right * force);
myRigidbody.AddTorque (Random.insideUnitSphere * force);
StartCoroutine (Fade ());
}
IEnumerator Fade() {
yield return new WaitForSeconds(lifetime);
float percent = 0;
float fadeSpeed = 1 / fadetime;
Material mat = GetComponent<Renderer> ().material;
Color initialColour = mat.color;
while (percent < 1) {
percent += Time.deltaTime * fadeSpeed;
mat.color = Color.Lerp(initialColour, Color.clear, percent);
yield return null;
}
Destroy (gameObject);
}
}
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
"""Specific data provider for Russia (ru)."""
from mimesis.builtins.base import BaseSpecProvider
from mimesis.enums import Gender
from mimesis.typing import Seed
__all__ = ['RussiaSpecProvider']
class RussiaSpecProvider(BaseSpecProvider):
"""Class that provides special data for Russia (ru)."""
def __init__(self, seed: Seed = None):
"""Initialize attributes."""
super().__init__(locale='ru', seed=seed)
self._pull(self._datafile)
class Meta:
"""The name of the provider."""
name = 'russia_provider'
def generate_sentence(self) -> str:
"""Generate sentence from the parts.
:return: Sentence.
"""
sentences = self._data['sentence']
sentence = [
self.random.choice(sentences[k]) for k
in ('head', 'p1', 'p2', 'tail')
]
return '{0} {1} {2} {3}'.format(*sentence)
def patronymic(self, gender: Gender = None) -> str:
"""Generate random patronymic name.
:param gender: Gender of person.
:return: Patronymic name.
:Example:
Алексеевна.
"""
gender = self._validate_enum(gender, Gender)
patronymics = self._data['patronymic'][gender]
return self.random.choice(patronymics)
def passport_series(self, year: int = None) -> str:
"""Generate random series of passport.
:param year: Year of manufacture.
:type year: int or None
:return: Series.
:Example:
02 15.
"""
if not year:
year = self.random.randint(10, 18)
region = self.random.randint(1, 99)
return '{:02d} {}'.format(region, year)
def passport_number(self) -> int:
"""Generate random passport number.
:return: Number.
:Example:
560430
"""
return self.random.randint(
100000, 999999)
def series_and_number(self) -> str:
"""Generate a random passport number and series.
:return: Series and number.
:Example:
57 16 805199.
"""
return '{}{}'.format(
self.passport_series(),
self.passport_number(),
)
def snils(self) -> str:
"""Generate snils with special algorithm.
:return: SNILS.
:Example:
41917492600.
"""
numbers = []
control_codes = []
for i in range(0, 9):
numbers.append(self.random.randint(0, 9))
for i in range(9, 0, -1):
control_codes.append(numbers[9 - i] * i)
control_code = sum(control_codes)
code = ''.join(str(number) for number in numbers)
if control_code in (100, 101):
snils = code + '00'
return snils
if control_code < 100:
snils = code + str(control_code)
return snils
if control_code > 101:
control_code = control_code % 101
if control_code == 100:
control_code = 0
snils = code + '{:02}'.format(control_code)
return snils
def inn(self) -> str:
"""Generate random, but valid ``INN``.
:return: INN.
"""
def control_sum(nums: list, t: str) -> int:
digits_dict = {
'n2': [7, 2, 4, 10, 3, 5, 9, 4, 6, 8],
'n1': [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8],
}
number = 0
digits = digits_dict[t]
for i in range(0, len(digits)):
number += nums[i] * digits[i]
return number % 11 % 10
numbers = []
for x in range(0, 10):
numbers.append(self.random.randint(1 if x == 0 else 0, 9))
n2 = control_sum(numbers, 'n2')
numbers.append(n2)
n1 = control_sum(numbers, 'n1')
numbers.append(n1)
return ''.join([str(x) for x in numbers])
def ogrn(self) -> str:
"""Generate random valid ``OGRN``.
:return: OGRN.
:Example:
4715113303725.
"""
numbers = []
for _ in range(0, 12):
numbers.append(self.random.randint(1 if _ == 0 else 0, 9))
ogrn = ''.join([str(x) for x in numbers])
check_sum = str(int(ogrn) % 11 % 10)
return '{}{}'.format(ogrn, check_sum)
def bic(self) -> str:
"""Generate random ``BIC`` (Bank ID Code).
:return: BIC.
:Example:
044025575.
"""
country_code = '04'
code = '{:02}'.format(self.random.randint(1, 10))
bank_number = '{:02}'.format(self.random.randint(0, 99))
bank_office = '{:03}'.format(self.random.randint(50, 999))
bic = country_code + code + bank_number + bank_office
return bic
def kpp(self) -> str:
"""Generate random ``KPP``.
:return: 'KPP'.
:Example:
560058652.
"""
tax_codes = [
'7700', '7800', '5000', '0100',
'0200', '0300', '0500', '0600',
'0700', '0800', '0900', '1000',
'1100', '1200', '1300', '1400',
'1500', '1600', '1700', '1800',
'1900', '2000', '2100', '2200',
'2300', '2400', '2500', '2600',
'2700', '2800', '2900', '3000',
'3100', '3200', '3300', '3400',
'3500', '3600', '3700', '3800',
'3900', '4000', '4100', '4900',
'5100', '5200', '5300', '5400',
'5500', '5600', '5700', '5800',
'5900', '6000', '6100', '6200',
'6300', '6400', '6500', '6600',
'6700', '6800', '6900', '7000',
'7100', '7200', '7300', '7400',
'7500', '7600', '7900', '8600',
'8700', '8900', '9100', '9200',
'9800', '9900', '9901', '9951',
'9952', '9953', '9954', '9955',
'9956', '9957', '9958', '9959',
'9961', '9962', '9965', '9966',
'9971', '9972', '9973', '9974',
'9975', '9976', '9977', '9979',
'9998',
]
tax_code = tax_codes[self.random.randint(0, len(tax_codes) - 1)]
reg_code = '{:02}'.format(self.random.randint(1, 99))
reg_number = '{:03}'.format(self.random.randint(1, 999))
kpp = tax_code + reg_code + reg_number
return kpp
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.
"""
VMware player/workstation server module.
"""
import os
import sys
import re
import shutil
import asyncio
import subprocess
import logging
import codecs
from collections import OrderedDict
from gns3server.utils.interfaces import interfaces
from gns3server.utils.asyncio import subprocess_check_output
from gns3server.utils import parse_version, shlex_quote
log = logging.getLogger(__name__)
from gns3server.compute.base_manager import BaseManager
from gns3server.compute.vmware.vmware_vm import VMwareVM
from gns3server.compute.vmware.vmware_error import VMwareError
class VMware(BaseManager):
_NODE_CLASS = VMwareVM
def __init__(self):
super().__init__()
self._vmware_inventory_lock = asyncio.Lock()
self._vmrun_path = None
self._host_type = None
self._vmnets = []
self._vmnet_start_range = 2
if sys.platform.startswith("win"):
self._vmnet_end_range = 19
else:
self._vmnet_end_range = 255
@property
def vmrun_path(self):
"""
Returns the path vmrun utility.
:returns: path
"""
return self._vmrun_path
@staticmethod
def _find_vmrun_registry(regkey):
import winreg
try:
# default path not used, let's look in the registry
hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, regkey)
install_path, _ = winreg.QueryValueEx(hkey, "InstallPath")
vmrun_path = os.path.join(install_path, "vmrun.exe")
winreg.CloseKey(hkey)
if os.path.exists(vmrun_path):
return vmrun_path
except OSError:
pass
return None
def find_vmrun(self):
"""
Searches for vmrun.
:returns: path to vmrun
"""
# look for vmrun
vmrun_path = self.config.get_section_config("VMware").get("vmrun_path")
if not vmrun_path:
if sys.platform.startswith("win"):
vmrun_path = shutil.which("vmrun")
if vmrun_path is None:
# look for vmrun.exe using the VMware Workstation directory listed in the registry
vmrun_path = self._find_vmrun_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation")
if vmrun_path is None:
# look for vmrun.exe using the VIX directory listed in the registry
vmrun_path = self._find_vmrun_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware VIX")
elif sys.platform.startswith("darwin"):
vmrun_path = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
else:
vmrun_path = "vmrun"
if vmrun_path and not os.path.isabs(vmrun_path):
vmrun_path = shutil.which(vmrun_path)
if not vmrun_path:
raise VMwareError("Could not find VMware vmrun, please make sure it is installed")
if not os.path.isfile(vmrun_path):
raise VMwareError("vmrun {} is not accessible".format(vmrun_path))
if not os.access(vmrun_path, os.X_OK):
raise VMwareError("vmrun is not executable")
if os.path.basename(vmrun_path).lower() not in ["vmrun", "vmrun.exe"]:
raise VMwareError("Invalid vmrun executable name {}".format(os.path.basename(vmrun_path)))
self._vmrun_path = vmrun_path
return vmrun_path
@staticmethod
def _find_vmware_version_registry(regkey):
import winreg
version = None
try:
# default path not used, let's look in the registry
hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, regkey)
version, _ = winreg.QueryValueEx(hkey, "ProductVersion")
winreg.CloseKey(hkey)
except OSError:
pass
if version is not None:
match = re.search(r"([0-9]+)\.", version)
if match:
version = match.group(1)
return version
async def _check_vmware_player_requirements(self, player_version):
"""
Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
VIX 1.17 was the release for Workstation Player 14.
:param player_version: VMware Player major version.
"""
player_version = int(player_version)
if player_version < 6:
raise VMwareError("Using VMware Player requires version 6 or above")
elif player_version == 6:
await self.check_vmrun_version(minimum_required_version="1.13.0")
elif player_version == 7:
await self.check_vmrun_version(minimum_required_version="1.14.0")
elif player_version >= 12:
await self.check_vmrun_version(minimum_required_version="1.15.0")
elif player_version >= 14:
await self.check_vmrun_version(minimum_required_version="1.17.0")
self._host_type = "player"
async def _check_vmware_workstation_requirements(self, ws_version):
"""
Check minimum requirements to use VMware Workstation.
VIX 1.13 was the release for Workstation 10.
VIX 1.14 was the release for Workstation 11.
VIX 1.15 was the release for Workstation Pro 12.
VIX 1.17 was the release for Workstation Pro 14.
:param ws_version: VMware Workstation major version.
"""
ws_version = int(ws_version)
if ws_version < 10:
raise VMwareError("Using VMware Workstation requires version 10 or above")
elif ws_version == 10:
await self.check_vmrun_version(minimum_required_version="1.13.0")
elif ws_version == 11:
await self.check_vmrun_version(minimum_required_version="1.14.0")
elif ws_version >= 12:
await self.check_vmrun_version(minimum_required_version="1.15.0")
elif ws_version >= 14:
await self.check_vmrun_version(minimum_required_version="1.17.0")
self._host_type = "ws"
async def check_vmware_version(self):
"""
Check VMware version
"""
if sys.platform.startswith("win"):
# look for vmrun.exe using the directory listed in the registry
ws_version = self._find_vmware_version_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation")
if ws_version is None:
player_version = self._find_vmware_version_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Player")
if player_version:
log.debug("VMware Player version {} detected".format(player_version))
await self._check_vmware_player_requirements(player_version)
else:
log.warning("Could not find VMware version")
self._host_type = "ws"
else:
log.debug("VMware Workstation version {} detected".format(ws_version))
await self._check_vmware_workstation_requirements(ws_version)
else:
if sys.platform.startswith("darwin"):
if not os.path.isdir("/Applications/VMware Fusion.app"):
raise VMwareError("VMware Fusion is not installed in the standard location /Applications/VMware Fusion.app")
self._host_type = "fusion"
return # FIXME: no version checking on Mac OS X but we support all versions of fusion
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path is None:
raise VMwareError("VMware is not installed (vmware or vmplayer executable could not be found in $PATH)")
try:
output = await subprocess_check_output(vmware_path, "-v")
match = re.search(r"VMware Workstation ([0-9]+)\.", output)
version = None
if match:
# VMware Workstation has been detected
version = match.group(1)
log.debug("VMware Workstation version {} detected".format(version))
await self._check_vmware_workstation_requirements(version)
match = re.search(r"VMware Player ([0-9]+)\.", output)
if match:
# VMware Player has been detected
version = match.group(1)
log.debug("VMware Player version {} detected".format(version))
await self._check_vmware_player_requirements(version)
if version is None:
log.warning("Could not find VMware version. Output of VMware: {}".format(output))
raise VMwareError("Could not find VMware version. Output of VMware: {}".format(output))
except (OSError, subprocess.SubprocessError) as e:
log.error("Error while looking for the VMware version: {}".format(e))
raise VMwareError("Error while looking for the VMware version: {}".format(e))
@staticmethod
def _get_vmnet_interfaces_registry():
import winreg
vmnet_interfaces = []
regkey = r"SOFTWARE\Wow6432Node\VMware, Inc.\VMnetLib\VMnetConfig"
try:
hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, regkey)
for index in range(winreg.QueryInfoKey(hkey)[0]):
vmnet = winreg.EnumKey(hkey, index)
hkeyvmnet = winreg.OpenKey(hkey, vmnet)
if winreg.QueryInfoKey(hkeyvmnet)[1]:
# the vmnet has not been configure if the key has no values
vmnet = vmnet.replace("vm", "VM")
if vmnet not in ("VMnet0", "VMnet1", "VMnet8"):
vmnet_interfaces.append(vmnet)
winreg.CloseKey(hkeyvmnet)
winreg.CloseKey(hkey)
except OSError as e:
raise VMwareError("Could not read registry key {}: {}".format(regkey, e))
return vmnet_interfaces
@staticmethod
def _get_vmnet_interfaces():
if sys.platform.startswith("win"):
return VMware._get_vmnet_interfaces_registry()
elif sys.platform.startswith("darwin"):
vmware_networking_file = "/Library/Preferences/VMware Fusion/networking"
else:
# location on Linux
vmware_networking_file = "/etc/vmware/networking"
vmnet_interfaces = []
try:
with open(vmware_networking_file, "r", encoding="utf-8") as f:
for line in f.read().splitlines():
match = re.search(r"VNET_([0-9]+)_VIRTUAL_ADAPTER", line)
if match:
vmnet = "vmnet{}".format(match.group(1))
if vmnet not in ("vmnet0", "vmnet1", "vmnet8"):
vmnet_interfaces.append(vmnet)
except OSError as e:
raise VMwareError("Cannot open {}: {}".format(vmware_networking_file, e))
return vmnet_interfaces
@staticmethod
def _get_vmnet_interfaces_ubridge():
vmnet_interfaces = []
for interface in interfaces():
if sys.platform.startswith("win"):
if "netcard" in interface:
windows_name = interface["netcard"]
else:
windows_name = interface["name"]
match = re.search(r"(VMnet[0-9]+)", windows_name)
if match:
vmnet = match.group(1)
if vmnet not in ("VMnet0", "VMnet1", "VMnet8"):
vmnet_interfaces.append(vmnet)
elif interface["name"].startswith("vmnet"):
vmnet = interface["name"]
if vmnet not in ("vmnet0", "vmnet1", "vmnet8"):
vmnet_interfaces.append(interface["name"])
return vmnet_interfaces
def is_managed_vmnet(self, vmnet):
self._vmnet_start_range = self.config.get_section_config("VMware").getint("vmnet_start_range", self._vmnet_start_range)
self._vmnet_end_range = self.config.get_section_config("VMware").getint("vmnet_end_range", self._vmnet_end_range)
match = re.search(r"vmnet([0-9]+)$", vmnet, re.IGNORECASE)
if match:
vmnet_number = match.group(1)
if self._vmnet_start_range <= int(vmnet_number) <= self._vmnet_end_range:
return True
return False
def allocate_vmnet(self):
if not self._vmnets:
raise VMwareError("No VMnet interface available between vmnet{} and vmnet{}. Go to preferences VMware / Network / Configure to add more interfaces.".format(self._vmnet_start_range, self._vmnet_end_range))
return self._vmnets.pop(0)
def refresh_vmnet_list(self, ubridge=True):
if ubridge:
# VMnet host adapters must be present when uBridge is used
vmnet_interfaces = self._get_vmnet_interfaces_ubridge()
else:
vmnet_interfaces = self._get_vmnet_interfaces()
# remove vmnets already in use
for vmware_vm in self._nodes.values():
for used_vmnet in vmware_vm.vmnets:
if used_vmnet in vmnet_interfaces:
log.debug("{} is already in use".format(used_vmnet))
vmnet_interfaces.remove(used_vmnet)
# remove vmnets that are not managed
for vmnet in vmnet_interfaces.copy():
if vmnet in vmnet_interfaces and self.is_managed_vmnet(vmnet) is False:
vmnet_interfaces.remove(vmnet)
self._vmnets = vmnet_interfaces
@property
def host_type(self):
"""
Returns the VMware host type.
player = VMware player
ws = VMware Workstation
fusion = VMware Fusion
:returns: host type (string)
"""
return self._host_type
async def execute(self, subcommand, args, timeout=120, log_level=logging.INFO):
trial = 2
while True:
try:
return (await self._execute(subcommand, args, timeout=timeout, log_level=log_level))
except VMwareError as e:
# We can fail to detect that it's VMware player instead of Workstation (due to marketing change Player is now Player Workstation)
if self.host_type == "ws" and "VIX_SERVICEPROVIDER_VMWARE_WORKSTATION" in str(e):
self._host_type = "player"
return (await self._execute(subcommand, args, timeout=timeout, log_level=log_level))
else:
if trial <= 0:
raise e
trial -= 1
await asyncio.sleep(0.5)
async def _execute(self, subcommand, args, timeout=120, log_level=logging.INFO):
if self.host_type is None:
await self.check_vmware_version()
vmrun_path = self.vmrun_path
if not vmrun_path:
vmrun_path = self.find_vmrun()
command = [vmrun_path, "-T", self.host_type, subcommand]
command.extend(args)
command_string = " ".join([shlex_quote(c) for c in command])
log.log(log_level, "Executing vmrun with command: {}".format(command_string))
try:
process = await asyncio.create_subprocess_exec(*command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
except (OSError, subprocess.SubprocessError) as e:
raise VMwareError("Could not execute vmrun: {}".format(e))
try:
stdout_data, _ = await asyncio.wait_for(process.communicate(), timeout=timeout)
except asyncio.TimeoutError:
raise VMwareError("vmrun has timed out after {} seconds!\nTry to run {} in a terminal to see more details.\n\nMake sure GNS3 and VMware run under the same user and whitelist vmrun.exe in your antivirus.".format(timeout, command_string))
if process.returncode:
# vmrun print errors on stdout
vmrun_error = stdout_data.decode("utf-8", errors="ignore")
raise VMwareError("vmrun has returned an error: {}\nTry to run {} in a terminal to see more details.\nAnd make sure GNS3 and VMware run under the same user.".format(vmrun_error, command_string))
return stdout_data.decode("utf-8", errors="ignore").splitlines()
async def check_vmrun_version(self, minimum_required_version="1.13.0"):
"""
Checks the vmrun version.
VMware VIX library version must be at least >= 1.13 by default
VIX 1.13 was the release for VMware Fusion 6, Workstation 10, and Player 6.
VIX 1.14 was the release for VMware Fusion 7, Workstation 11 and Player 7.
VIX 1.15 was the release for VMware Fusion 8, Workstation Pro 12 and Workstation Player 12.
:param required_version: required vmrun version number
"""
vmrun_path = self.vmrun_path
if not vmrun_path:
vmrun_path = self.find_vmrun()
try:
output = await subprocess_check_output(vmrun_path)
match = re.search(r"vmrun version ([0-9\.]+)", output)
version = None
if match:
version = match.group(1)
log.debug("VMware vmrun version {} detected, minimum required: {}".format(version, minimum_required_version))
if parse_version(version) < parse_version(minimum_required_version):
raise VMwareError("VMware vmrun executable version must be >= version {}".format(minimum_required_version))
if version is None:
log.warning("Could not find VMware vmrun version. Output: {}".format(output))
raise VMwareError("Could not find VMware vmrun version. Output: {}".format(output))
except (OSError, subprocess.SubprocessError) as e:
log.error("Error while looking for the VMware vmrun version: {}".format(e))
raise VMwareError("Error while looking for the VMware vmrun version: {}".format(e))
async def remove_from_vmware_inventory(self, vmx_path):
"""
Removes a linked clone from the VMware inventory file.
:param vmx_path: path of the linked clone VMX file
"""
async with self._vmware_inventory_lock:
inventory_path = self.get_vmware_inventory_path()
if os.path.exists(inventory_path):
try:
inventory_pairs = self.parse_vmware_file(inventory_path)
except OSError as e:
log.warning('Could not read VMware inventory file "{}": {}'.format(inventory_path, e))
return
vmlist_entry = None
for name, value in inventory_pairs.items():
if value == vmx_path:
vmlist_entry = name.split(".", 1)[0]
break
if vmlist_entry is not None:
for name in inventory_pairs.copy().keys():
if name.startswith(vmlist_entry):
del inventory_pairs[name]
try:
self.write_vmware_file(inventory_path, inventory_pairs)
except OSError as e:
raise VMwareError('Could not write VMware inventory file "{}": {}'.format(inventory_path, e))
@staticmethod
def parse_vmware_file(path):
"""
Parses a VMware file (VMX, preferences or inventory).
:param path: path to the VMware file
:returns: dict
"""
pairs = OrderedDict()
encoding = "utf-8"
# get the first line to read the .encoding value
with open(path, "rb") as f:
line = f.readline().decode(encoding, errors="ignore")
if line.startswith("#!"):
# skip the shebang
line = f.readline().decode(encoding, errors="ignore")
try:
key, value = line.split('=', 1)
if key.strip().lower() == ".encoding":
file_encoding = value.strip('" ')
try:
codecs.lookup(file_encoding)
encoding = file_encoding
except LookupError:
log.warning("Invalid file encoding detected in '{}': {}".format(path, file_encoding))
except ValueError:
log.warning("Couldn't find file encoding in {}, using {}...".format(path, encoding))
# read the file with the correct encoding
with open(path, encoding=encoding, errors="ignore") as f:
for line in f.read().splitlines():
try:
key, value = line.split('=', 1)
pairs[key.strip().lower()] = value.strip('" ')
except ValueError:
continue
return pairs
@staticmethod
def write_vmware_file(path, pairs):
"""
Write a VMware file (excepting VMX file).
:param path: path to the VMware file
:param pairs: settings to write
"""
encoding = "utf-8"
if ".encoding" in pairs:
file_encoding = pairs[".encoding"]
try:
codecs.lookup(file_encoding)
encoding = file_encoding
except LookupError:
log.warning("Invalid file encoding detected in '{}': {}".format(path, file_encoding))
with open(path, "w", encoding=encoding, errors="ignore") as f:
for key, value in pairs.items():
entry = '{} = "{}"\n'.format(key, value)
f.write(entry)
@staticmethod
def write_vmx_file(path, pairs):
"""
Write a VMware VMX file.
:param path: path to the VMX file
:param pairs: settings to write
"""
encoding = "utf-8"
if ".encoding" in pairs:
file_encoding = pairs[".encoding"]
try:
codecs.lookup(file_encoding)
encoding = file_encoding
except LookupError:
log.warning("Invalid file encoding detected in '{}': {}".format(path, file_encoding))
with open(path, "w", encoding=encoding, errors="ignore") as f:
if sys.platform.startswith("linux"):
# write the shebang on the first line on Linux
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path:
f.write("#!{}\n".format(vmware_path))
for key, value in pairs.items():
entry = '{} = "{}"\n'.format(key, value)
f.write(entry)
def _get_vms_from_inventory(self, inventory_path):
"""
Searches for VMs by parsing a VMware inventory file.
:param inventory_path: path to the inventory file
:returns: list of VMs
"""
vm_entries = {}
vmware_vms = []
log.info('Searching for VMware VMs in inventory file "{}"'.format(inventory_path))
try:
pairs = self.parse_vmware_file(inventory_path)
for key, value in pairs.items():
if key.startswith("vmlist"):
try:
vm_entry, variable_name = key.split('.', 1)
except ValueError:
continue
if vm_entry not in vm_entries:
vm_entries[vm_entry] = {}
vm_entries[vm_entry][variable_name.strip()] = value
except OSError as e:
log.warning("Could not read VMware inventory file {}: {}".format(inventory_path, e))
for vm_settings in vm_entries.values():
if "displayname" in vm_settings and "config" in vm_settings:
if os.path.exists(vm_settings["config"]):
log.debug('Found VM named "{}" with VMX file "{}"'.format(vm_settings["displayname"], vm_settings["config"]))
vmware_vms.append({"vmname": vm_settings["displayname"], "vmx_path": vm_settings["config"]})
return vmware_vms
def _get_vms_from_directory(self, directory):
"""
Searches for VMs in a given directory.
:param directory: path to the directory
:returns: list of VMs
"""
vmware_vms = []
log.info('Searching for VMware VMs in directory "{}"'.format(directory))
for path, _, filenames in os.walk(directory):
for filename in filenames:
if os.path.splitext(filename)[1] == ".vmx":
vmx_path = os.path.join(path, filename)
log.debug('Reading VMware VMX file "{}"'.format(vmx_path))
try:
pairs = self.parse_vmware_file(vmx_path)
if "displayname" in pairs:
log.debug('Found VM named "{}"'.format(pairs["displayname"]))
vmware_vms.append({"vmname": pairs["displayname"], "vmx_path": vmx_path})
except OSError as e:
log.warning('Could not read VMware VMX file "{}": {}'.format(vmx_path, e))
continue
return vmware_vms
@staticmethod
def get_vmware_inventory_path():
"""
Returns VMware inventory file path.
:returns: path to the inventory file
"""
if sys.platform.startswith("win"):
return os.path.expandvars(r"%APPDATA%\Vmware\Inventory.vmls")
elif sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Application Support/VMware Fusion/vmInventory")
else:
return os.path.expanduser("~/.vmware/inventory.vmls")
@staticmethod
def get_vmware_preferences_path():
"""
Returns VMware preferences file path.
:returns: path to the preferences file
"""
if sys.platform.startswith("win"):
return os.path.expandvars(r"%APPDATA%\VMware\preferences.ini")
elif sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Preferences/VMware Fusion/preferences")
else:
return os.path.expanduser("~/.vmware/preferences")
@staticmethod
def get_vmware_default_vm_paths():
"""
Returns VMware default VM directory paths.
:returns: path to the default VM directory
"""
if sys.platform.startswith("win"):
import ctypes
import ctypes.wintypes
path = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(None, 5, None, 0, path)
documents_folder = path.value
return ['{}\My Virtual Machines'.format(documents_folder), '{}\Virtual Machines'.format(documents_folder)]
elif sys.platform.startswith("darwin"):
return [os.path.expanduser("~/Documents/Virtual Machines.localized")]
else:
return [os.path.expanduser("~/vmware")]
async def list_vms(self):
"""
Gets VMware VM list.
"""
# check for the right VMware version
await self.check_vmware_version()
vmware_vms = []
inventory_path = self.get_vmware_inventory_path()
if os.path.exists(inventory_path) and self.host_type != "player":
# inventory may exist for VMware player if VMware workstation has been previously installed
vmware_vms = self._get_vms_from_inventory(inventory_path)
if not vmware_vms:
# backup methods when no VMware inventory file exists or for VMware player which has no inventory file
vmware_preferences_path = self.get_vmware_preferences_path()
pairs = {}
if os.path.exists(vmware_preferences_path):
# the default vm path may be present in VMware preferences file.
try:
pairs = self.parse_vmware_file(vmware_preferences_path)
except OSError as e:
log.warning('Could not read VMware preferences file "{}": {}'.format(vmware_preferences_path, e))
if "prefvmx.defaultvmpath" in pairs:
default_vm_path = pairs["prefvmx.defaultvmpath"]
if not os.path.isdir(default_vm_path):
raise VMwareError('Could not find or access the default VM directory: "{default_vm_path}". Please change "prefvmx.defaultvmpath={default_vm_path}" in "{vmware_preferences_path}"'.format(default_vm_path=default_vm_path,
vmware_preferences_path=vmware_preferences_path))
vmware_vms = self._get_vms_from_directory(default_vm_path)
if not vmware_vms:
# the default vm path is not in the VMware preferences file or that directory is empty
# let's search the default locations for VMs
for default_vm_path in self.get_vmware_default_vm_paths():
if os.path.isdir(default_vm_path):
vmware_vms.extend(self._get_vms_from_directory(default_vm_path))
if not vmware_vms:
log.warning("Could not find any VMware VM in default locations")
# look for VMX paths in the preferences file in case not all VMs are in a default directory
for key, value in pairs.items():
m = re.match(r'pref.mruVM(\d+)\.filename', key)
if m:
display_name = "pref.mruVM{}.displayName".format(m.group(1))
if display_name in pairs:
found = False
for vmware_vm in vmware_vms:
if vmware_vm["vmname"] == display_name:
found = True
if found is False:
vmware_vms.append({"vmname": pairs[display_name], "vmx_path": value})
return vmware_vms
@staticmethod
def _get_linux_vmware_binary():
"""
Return the path of the vmware binary on Linux or None
"""
path = shutil.which("vmware")
if path is None:
path = shutil.which("vmplayer")
return path
if __name__ == '__main__':
loop = asyncio.get_event_loop()
vmware = VMware.instance()
print("=> Check version")
loop.run_until_complete(asyncio.ensure_future(vmware.check_vmware_version()))
| {
"pile_set_name": "Github"
} |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <forward_list>
// forward_list()
// noexcept(is_nothrow_default_constructible<allocator_type>::value);
// This tests a conforming extension
// UNSUPPORTED: c++98, c++03
#include <forward_list>
#include <cassert>
#include "test_macros.h"
#include "MoveOnly.h"
#include "test_allocator.h"
template <class T>
struct some_alloc
{
typedef T value_type;
some_alloc(const some_alloc&);
};
int main(int, char**)
{
#if defined(_LIBCPP_VERSION)
{
typedef std::forward_list<MoveOnly> C;
static_assert(std::is_nothrow_default_constructible<C>::value, "");
}
{
typedef std::forward_list<MoveOnly, test_allocator<MoveOnly>> C;
static_assert(std::is_nothrow_default_constructible<C>::value, "");
}
#endif // _LIBCPP_VERSION
{
typedef std::forward_list<MoveOnly, other_allocator<MoveOnly>> C;
static_assert(!std::is_nothrow_default_constructible<C>::value, "");
}
{
typedef std::forward_list<MoveOnly, some_alloc<MoveOnly>> C;
static_assert(!std::is_nothrow_default_constructible<C>::value, "");
}
return 0;
}
| {
"pile_set_name": "Github"
} |
/** @file
Register names for PCH Serial IO Controllers
Copyright (c) 2018 - 2019, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _PCH_REGS_SERIAL_IO_
#define _PCH_REGS_SERIAL_IO_
#define R_SERIAL_IO_CFG_BAR0_LOW 0x10
#define R_SERIAL_IO_CFG_BAR0_HIGH 0x14
#define R_SERIAL_IO_CFG_BAR1_LOW 0x18
#define R_SERIAL_IO_CFG_BAR1_HIGH 0x1C
#define R_SERIAL_IO_CFG_PME_CTRL_STS 0x84
#define R_SERIAL_IO_CFG_D0I3MAXDEVPG 0xA0
#define R_SERIAL_IO_MEM_PPR_CLK 0x200
#define B_SERIAL_IO_MEM_PPR_CLK_EN BIT0
#define B_SERIAL_IO_MEM_PPR_CLK_UPDATE BIT31
#define V_SERIAL_IO_MEM_PPR_CLK_M_DIV 0x30
#define V_SERIAL_IO_MEM_PPR_CLK_N_DIV 0xC35
#define R_SERIAL_IO_MEM_PPR_RESETS 0x204
#define B_SERIAL_IO_MEM_PPR_RESETS_FUNC BIT0
#define B_SERIAL_IO_MEM_PPR_RESETS_APB BIT1
#define B_SERIAL_IO_MEM_PPR_RESETS_IDMA BIT2
#endif
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.google.android.exoplayer2.util;
/**
* Wraps a byte array, providing methods that allow it to be read as a NAL unit bitstream.
* <p>
* Whenever the byte sequence [0, 0, 3] appears in the wrapped byte array, it is treated as [0, 0]
* for all reading/skipping operations, which makes the bitstream appear to be unescaped.
*/
public final class ParsableNalUnitBitArray {
private byte[] data;
private int byteLimit;
// The byte offset is never equal to the offset of the 3rd byte in a subsequence [0, 0, 3].
private int byteOffset;
private int bitOffset;
/**
* @param data The data to wrap.
* @param offset The byte offset in {@code data} to start reading from.
* @param limit The byte offset of the end of the bitstream in {@code data}.
*/
@SuppressWarnings({"initialization.fields.uninitialized", "method.invocation.invalid"})
public ParsableNalUnitBitArray(byte[] data, int offset, int limit) {
reset(data, offset, limit);
}
/**
* Resets the wrapped data, limit and offset.
*
* @param data The data to wrap.
* @param offset The byte offset in {@code data} to start reading from.
* @param limit The byte offset of the end of the bitstream in {@code data}.
*/
public void reset(byte[] data, int offset, int limit) {
this.data = data;
byteOffset = offset;
byteLimit = limit;
bitOffset = 0;
assertValidOffset();
}
/**
* Skips a single bit.
*/
public void skipBit() {
if (++bitOffset == 8) {
bitOffset = 0;
byteOffset += shouldSkipByte(byteOffset + 1) ? 2 : 1;
}
assertValidOffset();
}
/**
* Skips bits and moves current reading position forward.
*
* @param numBits The number of bits to skip.
*/
public void skipBits(int numBits) {
int oldByteOffset = byteOffset;
int numBytes = numBits / 8;
byteOffset += numBytes;
bitOffset += numBits - (numBytes * 8);
if (bitOffset > 7) {
byteOffset++;
bitOffset -= 8;
}
for (int i = oldByteOffset + 1; i <= byteOffset; i++) {
if (shouldSkipByte(i)) {
// Skip the byte and move forward to check three bytes ahead.
byteOffset++;
i += 2;
}
}
assertValidOffset();
}
/**
* Returns whether it's possible to read {@code n} bits starting from the current offset. The
* offset is not modified.
*
* @param numBits The number of bits.
* @return Whether it is possible to read {@code n} bits.
*/
public boolean canReadBits(int numBits) {
int oldByteOffset = byteOffset;
int numBytes = numBits / 8;
int newByteOffset = byteOffset + numBytes;
int newBitOffset = bitOffset + numBits - (numBytes * 8);
if (newBitOffset > 7) {
newByteOffset++;
newBitOffset -= 8;
}
for (int i = oldByteOffset + 1; i <= newByteOffset && newByteOffset < byteLimit; i++) {
if (shouldSkipByte(i)) {
// Skip the byte and move forward to check three bytes ahead.
newByteOffset++;
i += 2;
}
}
return newByteOffset < byteLimit || (newByteOffset == byteLimit && newBitOffset == 0);
}
/**
* Reads a single bit.
*
* @return Whether the bit is set.
*/
public boolean readBit() {
boolean returnValue = (data[byteOffset] & (0x80 >> bitOffset)) != 0;
skipBit();
return returnValue;
}
/**
* Reads up to 32 bits.
*
* @param numBits The number of bits to read.
* @return An integer whose bottom n bits hold the read data.
*/
public int readBits(int numBits) {
int returnValue = 0;
bitOffset += numBits;
while (bitOffset > 8) {
bitOffset -= 8;
returnValue |= (data[byteOffset] & 0xFF) << bitOffset;
byteOffset += shouldSkipByte(byteOffset + 1) ? 2 : 1;
}
returnValue |= (data[byteOffset] & 0xFF) >> (8 - bitOffset);
returnValue &= 0xFFFFFFFF >>> (32 - numBits);
if (bitOffset == 8) {
bitOffset = 0;
byteOffset += shouldSkipByte(byteOffset + 1) ? 2 : 1;
}
assertValidOffset();
return returnValue;
}
/**
* Returns whether it is possible to read an Exp-Golomb-coded integer starting from the current
* offset. The offset is not modified.
*
* @return Whether it is possible to read an Exp-Golomb-coded integer.
*/
public boolean canReadExpGolombCodedNum() {
int initialByteOffset = byteOffset;
int initialBitOffset = bitOffset;
int leadingZeros = 0;
while (byteOffset < byteLimit && !readBit()) {
leadingZeros++;
}
boolean hitLimit = byteOffset == byteLimit;
byteOffset = initialByteOffset;
bitOffset = initialBitOffset;
return !hitLimit && canReadBits(leadingZeros * 2 + 1);
}
/**
* Reads an unsigned Exp-Golomb-coded format integer.
*
* @return The value of the parsed Exp-Golomb-coded integer.
*/
public int readUnsignedExpGolombCodedInt() {
return readExpGolombCodeNum();
}
/**
* Reads an signed Exp-Golomb-coded format integer.
*
* @return The value of the parsed Exp-Golomb-coded integer.
*/
public int readSignedExpGolombCodedInt() {
int codeNum = readExpGolombCodeNum();
return ((codeNum % 2) == 0 ? -1 : 1) * ((codeNum + 1) / 2);
}
private int readExpGolombCodeNum() {
int leadingZeros = 0;
while (!readBit()) {
leadingZeros++;
}
return (1 << leadingZeros) - 1 + (leadingZeros > 0 ? readBits(leadingZeros) : 0);
}
private boolean shouldSkipByte(int offset) {
return 2 <= offset && offset < byteLimit && data[offset] == (byte) 0x03
&& data[offset - 2] == (byte) 0x00 && data[offset - 1] == (byte) 0x00;
}
private void assertValidOffset() {
// It is fine for position to be at the end of the array, but no further.
Assertions.checkState(byteOffset >= 0
&& (byteOffset < byteLimit || (byteOffset == byteLimit && bitOffset == 0)));
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 51d34008285243768f59a545839dc097
timeCreated: 1539108536 | {
"pile_set_name": "Github"
} |
..\nothing.com
del osask_at.exe
del osask_qe.exe
ren OSASK.EXE osask_at.exe
..\osalink1.exe
ren osask.exe osask_qe.exe
ren osask_at.exe OSASK.EXE
..\imgtol.com s osask_qe.exe osask_qe.sys 2048
..\edimg.exe @edimgopt.txt | {
"pile_set_name": "Github"
} |
"use strict";
/**
* @fileOverview
* Core operations on curve 25519 required for the higher level modules.
*/
/*
* Copyright (c) 2007, 2013, 2014 Michele Bini
* Copyright (c) 2014 Mega Limited
* under the MIT License.
*
* Authors: Guy K. Kloss, Michele Bini
*
* You should have received a copy of the license along with this program.
*/
var core = require('./core');
var utils = require('./utils');
/**
* @exports jodid25519/curve255
* Legacy compatibility module for Michele Bini's previous curve255.js.
*
* @description
* Legacy compatibility module for Michele Bini's previous curve255.js.
*
* <p>
* This code presents an API with all key formats as previously available
* from Michele Bini's curve255.js implementation.
* </p>
*/
var ns = {};
function curve25519_raw(f, c) {
var a, x_1, q;
x_1 = c;
a = core.dbl(x_1, core.ONE());
q = [x_1, core.ONE()];
var n = 255;
while (core.getbit(f, n) == 0) {
n--;
// For correct constant-time operation, bit 255 should always be
// set to 1 so the following 'while' loop is never entered.
if (n < 0) {
return core.ZERO();
}
}
n--;
var aq = [a, q];
while (n >= 0) {
var r, s;
var b = core.getbit(f, n);
r = core.sum(aq[0][0], aq[0][1], aq[1][0], aq[1][1], x_1);
s = core.dbl(aq[1 - b][0], aq[1 - b][1]);
aq[1 - b] = s;
aq[b] = r;
n--;
}
q = aq[1];
q[1] = core.invmodp(q[1]);
q[0] = core.mulmodp(q[0], q[1]);
core.reduce(q[0]);
return q[0];
}
function curve25519b32(a, b) {
return _base32encode(curve25519(_base32decode(a),
_base32decode(b)));
}
function curve25519(f, c) {
if (!c) {
c = core.BASE();
}
f[0] &= 0xFFF8;
f[15] = (f[15] & 0x7FFF) | 0x4000;
return curve25519_raw(f, c);
}
function _hexEncodeVector(k) {
var hexKey = utils.hexEncode(k);
// Pad with '0' at the front.
hexKey = new Array(64 + 1 - hexKey.length).join('0') + hexKey;
// Invert bytes.
return hexKey.split(/(..)/).reverse().join('');
}
function _hexDecodeVector(v) {
// assert(length(x) == 64);
// Invert bytes.
var hexKey = v.split(/(..)/).reverse().join('');
return utils.hexDecode(hexKey);
}
// Expose some functions to the outside through this name space.
/**
* Computes the scalar product of a point on the curve 25519.
*
* This function is used for the DH key-exchange protocol.
*
* Before multiplication, some bit operations are applied to the
* private key to ensure it is a valid Curve25519 secret key.
* It is the user's responsibility to make sure that the private
* key is a uniformly random, secret value.
*
* @function
* @param f {array}
* Private key.
* @param c {array}
* Public point on the curve. If not given, the curve's base point is used.
* @returns {array}
* Key point resulting from scalar product.
*/
ns.curve25519 = curve25519;
/**
* Computes the scalar product of a point on the curve 25519.
*
* This variant does not make sure that the private key is valid.
* The user has the responsibility to ensure the private key is
* valid or that this results in a safe protocol. Unless you know
* exactly what you are doing, you should not use this variant,
* please use 'curve25519' instead.
*
* @function
* @param f {array}
* Private key.
* @param c {array}
* Public point on the curve. If not given, the curve's base point is used.
* @returns {array}
* Key point resulting from scalar product.
*/
ns.curve25519_raw = curve25519_raw;
/**
* Encodes the internal representation of a key to a canonical hex
* representation.
*
* This is the format commonly used in other libraries and for
* test vectors, and is equivalent to the hex dump of the key in
* little-endian binary format.
*
* @function
* @param n {array}
* Array representation of key.
* @returns {string}
* Hexadecimal string representation of key.
*/
ns.hexEncodeVector = _hexEncodeVector;
/**
* Decodes a canonical hex representation of a key
* to an internally compatible array representation.
*
* @function
* @param n {string}
* Hexadecimal string representation of key.
* @returns {array}
* Array representation of key.
*/
ns.hexDecodeVector = _hexDecodeVector;
/**
* Encodes the internal representation of a key into a
* hexadecimal representation.
*
* This is a strict positional notation, most significant digit first.
*
* @function
* @param n {array}
* Array representation of key.
* @returns {string}
* Hexadecimal string representation of key.
*/
ns.hexencode = utils.hexEncode;
/**
* Decodes a hex representation of a key to an internally
* compatible array representation.
*
* @function
* @param n {string}
* Hexadecimal string representation of key.
* @returns {array}
* Array representation of key.
*/
ns.hexdecode = utils.hexDecode;
/**
* Encodes the internal representation of a key to a base32
* representation.
*
* @function
* @param n {array}
* Array representation of key.
* @returns {string}
* Base32 string representation of key.
*/
ns.base32encode = utils.base32encode;
/**
* Decodes a base32 representation of a key to an internally
* compatible array representation.
*
* @function
* @param n {string}
* Base32 string representation of key.
* @returns {array}
* Array representation of key.
*/
ns.base32decode = utils.base32decode;
module.exports = ns;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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 io.siddhi.core.query.function;
import io.siddhi.core.SiddhiAppRuntime;
import io.siddhi.core.SiddhiManager;
import io.siddhi.core.event.Event;
import io.siddhi.core.query.output.callback.QueryCallback;
import io.siddhi.core.stream.input.InputHandler;
import io.siddhi.core.util.EventPrinter;
import org.apache.log4j.Logger;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class UUIDFunctionTestCase {
private static final Logger log = Logger.getLogger(UUIDFunctionTestCase.class);
private int count;
private boolean eventArrived;
@BeforeMethod
public void init() {
count = 0;
eventArrived = false;
}
@Test
public void testFunctionQuery1() throws InterruptedException {
log.info("UUIDFunction test1");
SiddhiManager siddhiManager = new SiddhiManager();
String planName = "@app:name('UUIDFunction') ";
String cseEventStream = "define stream cseEventStream (symbol string, price double, volume long , quantity " +
"int);";
String query = "@info(name = 'query1') " +
"from cseEventStream " +
"select symbol, price as price, quantity, UUID() as uniqueValue " +
"insert into outputStream;";
SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(planName +
cseEventStream + query);
siddhiAppRuntime.addCallback("query1", new QueryCallback() {
@Override
public void receive(long timestamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timestamp, inEvents, removeEvents);
AssertJUnit.assertEquals(1.56, inEvents[0].getData()[1]);
AssertJUnit.assertNotNull("UUID is expected", inEvents[0].getData()[3]);
AssertJUnit.assertTrue("String UUID is expected", inEvents[0].getData()[3] instanceof String);
count = count + inEvents.length;
}
});
InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream");
siddhiAppRuntime.start();
inputHandler.send(new Object[]{"WSO2", 1.56d, 60L, 6});
Thread.sleep(200);
org.testng.AssertJUnit.assertEquals(1, count);
siddhiAppRuntime.shutdown();
}
}
| {
"pile_set_name": "Github"
} |
[egg_info]
tag_build = dev
tag_svn_revision = true
| {
"pile_set_name": "Github"
} |
/*
* Open Source Software published under the Apache Licence, Version 2.0.
*/
package io.github.vocabhunter.gui.common;
import org.junit.jupiter.api.Test;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class WordUseToolTest {
@Test
public void testEmpty() {
validate("", "");
}
@Test
public void testSingleWord() {
validate("and", "and");
}
@Test
public void testWordAtStart() {
validate("And then there were none.", "And", " then there were none.");
}
@Test
public void testWordInMiddle() {
validate("Chalk and cheese.", "Chalk ", "and", " cheese.");
}
@Test
public void testWordAtEnd() {
validate("Try ending with and", "Try ending with ", "and");
}
@Test
public void testPrefix() {
validate("Andian", "Andian");
}
@Test
public void testSuffix() {
validate("Sand", "Sand");
}
@Test
public void testInfix() {
validate("Sandy", "Sandy");
}
@Test
public void testVaried() {
validate("And then the sandy and andian and and", "And", " then the sandy ", "and", " andian ", "and", " ", "and");
}
private void validate(final String use, final String... expected) {
WordUseTool tool = new WordUseTool("and", use);
List<String> actual = tool.stream()
.collect(toList());
assertEquals(List.of(expected), actual, "Use: " + use);
}
}
| {
"pile_set_name": "Github"
} |
import React from 'react';
import demand from 'must';
import { shallow } from 'enzyme';
import { Lists } from '../Lists';
import ListTile from '../ListTile';
describe('<Lists />', () => {
it('should render the lists', () => {
const lists = [{}, {}];
const component = shallow(<Lists lists={lists} listsData={{}} counts={{}} />);
demand(component.find(ListTile).length).eql(lists.length);
});
it('should not prefix the admin url for external lists', () => {
const externalPath = 'http://someurl.com/some/path';
const internalPath = 'some/path';
const lists = [{
external: true,
path: externalPath,
}, {
path: internalPath,
}];
const component = shallow(<Lists lists={lists} listsData={{}} counts={{}} />);
demand(component.find(ListTile).at(0).prop('href')).eql(externalPath);
});
it('should render counts', () => {
const lists = [
{
key: 'somekey',
path: 'some/path',
},
];
const counts = {
somekey: 50,
};
const component = shallow(<Lists lists={lists} listsData={{}} counts={counts} />);
demand(component.find(ListTile).at(0).prop('count')).eql('50 Items');
});
it('should change the pluralization of the counts', () => {
const lists = [
{
key: 'somekey',
path: 'some/path',
}, {
key: 'someotherkey',
path: 'some/other/path',
},
];
const counts = {
somekey: 1,
someotherkey: 100,
};
const component = shallow(<Lists lists={lists} listsData={{}} counts={counts} />);
demand(component.find(ListTile).at(0).prop('count')).eql('1 Item');
demand(component.find(ListTile).at(1).prop('count')).eql('100 Items');
});
it('should hide the create button if it\'s a nocreate list', () => {
const internalPath = 'some/path';
const lists = [{
path: internalPath,
}];
const listData = {
[internalPath]: {
nocreate: true,
},
};
const component = shallow(<Lists lists={lists} listsData={listData} counts={{}} />);
demand(component.find(ListTile).at(0).prop('hideCreateButton')).true();
});
describe('lists object', () => {
it('should allow lists to be an object', () => {
const lists = {
somekey: {
path: 'some/path',
},
someotherkey: {
path: 'some/other/path',
},
};
const component = shallow(<Lists lists={lists} listsData={{}} counts={{}} />);
demand(component.find(ListTile).length).eql(Object.keys(lists).length);
});
it('should render counts', () => {
const lists = {
somekey: {
path: 'some/path',
},
};
const counts = {
somekey: 50,
};
const component = shallow(<Lists lists={lists} listsData={{}} counts={counts} />);
demand(component.find(ListTile).at(0).prop('count')).eql('50 Items');
});
it('should change the pluralization of the counts', () => {
const lists = {
somekey: {
path: 'some/path',
},
someotherkey: {
path: 'some/other/path',
},
};
const counts = {
somekey: 1,
someotherkey: 100,
};
const component = shallow(<Lists lists={lists} listsData={{}} counts={counts} />);
demand(component.find(ListTile).at(0).prop('count')).eql('1 Item');
demand(component.find(ListTile).at(1).prop('count')).eql('100 Items');
});
});
});
| {
"pile_set_name": "Github"
} |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace StepSliderDemo.Droid
{
[Activity(Label = "StepSliderDemo", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
Xamarin.FormsBook.Platform.Android.Toolkit.Init(this, bundle);
LoadApplication(new App());
}
}
}
| {
"pile_set_name": "Github"
} |
Vertical Kuijken & Gilmore potential
====================================
.. autoclass:: galpy.potential.KGPotential
:members: __init__ | {
"pile_set_name": "Github"
} |
config BOARD_PURISM_BASEBOARD_LIBREM_BDW
def_bool n
select SYSTEM_TYPE_LAPTOP
select BOARD_ROMSIZE_KB_8192
select HAVE_ACPI_RESUME
select HAVE_ACPI_TABLES
select INTEL_GMA_HAVE_VBT
select INTEL_INT15
select MAINBOARD_HAS_LIBGFXINIT
select MAINBOARD_HAS_TPM1
select SOC_INTEL_BROADWELL
if BOARD_PURISM_BASEBOARD_LIBREM_BDW
config VARIANT_DIR
string
default "librem13v1" if BOARD_PURISM_LIBREM13_V1
default "librem15v2" if BOARD_PURISM_LIBREM15_V2
config OVERRIDE_DEVICETREE
string
default "variants/\$(CONFIG_VARIANT_DIR)/overridetree.cb"
config DRIVERS_UART_8250IO
def_bool n
help
This platform does not have any way to get standard
serial output so disable it by default.
config PCIEXP_L1_SUB_STATE
def_bool n
config PCIEXP_AER
def_bool n
config MAINBOARD_DIR
string
default "purism/librem_bdw"
config MAINBOARD_PART_NUMBER
string
default "Librem 13 v1" if BOARD_PURISM_LIBREM13_V1
default "Librem 15 v2" if BOARD_PURISM_LIBREM15_V2
config MAINBOARD_FAMILY
string
default "Librem 13" if BOARD_PURISM_LIBREM13_V1
default "Librem 15" if BOARD_PURISM_LIBREM15_V2
config MAINBOARD_VERSION
string
default "1.0" if BOARD_PURISM_LIBREM13_V1
default "2.0" if BOARD_PURISM_LIBREM15_V2
config MAX_CPUS
int
default 8
config PRE_GRAPHICS_DELAY
int
default 50
config VGA_BIOS_ID
string
default "8086,1616" if BOARD_PURISM_LIBREM13_V1
default "8086,162b" if BOARD_PURISM_LIBREM15_V2
# Override the default variant behavior, since the data.vbt is the same
# for both variants.
config INTEL_GMA_VBT_FILE
default "src/mainboard/\$(MAINBOARDDIR)/data.vbt"
# This platform has limited means to display POST codes
config NO_POST
default y
endif
| {
"pile_set_name": "Github"
} |
package org.zstack.header.identity
import org.zstack.header.errorcode.ErrorCode
doc {
title "配额清单"
ref {
name "error"
path "org.zstack.header.identity.APIUpdateQuotaEvent.error"
desc "错误码,若不为null,则表示操作失败, 操作成功时该字段为null", false
type "ErrorCode"
since "0.6"
clz ErrorCode.class
}
ref {
name "inventory"
path "org.zstack.header.identity.APIUpdateQuotaEvent.inventory"
desc "配额清单"
type "QuotaInventory"
since "0.6"
clz QuotaInventory.class
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("devtools","en",{title:"Element Information",dialogName:"Dialog window name",tabName:"Tab name",elementId:"Element ID",elementType:"Element type"}); | {
"pile_set_name": "Github"
} |
# Copyright (c) 2020 The Orbit Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
set(DIR third_party/multicore/common)
add_library(
multicore OBJECT
${DIR}/inmemorylogger.cpp
${DIR}/autoresetevent.h
${DIR}/autoreseteventcondvar.h
${DIR}/benaphore.h
${DIR}/bitfield.h
${DIR}/diningphilosophers.h
${DIR}/inmemorylogger.h
${DIR}/rwlock.h
${DIR}/sema.h)
target_include_directories(multicore SYSTEM PUBLIC ${DIR})
target_compile_features(multicore PUBLIC cxx_std_11)
target_link_libraries(multicore PUBLIC Threads::Threads)
add_library(multicore::multicore ALIAS multicore)
| {
"pile_set_name": "Github"
} |
---
title: DocDB performance enhancements to RocksDB
headerTitle: Performance
linkTitle: Performance
description: Learn how DocDB enhances RocksDB for scale and performance.
aliases:
- /latest/architecture/concepts/docdb/performance/
menu:
latest:
identifier: docdb-performance
parent: docdb
weight: 1148
isTocNested: true
showAsideToc: true
---
DocDB uses a highly customized version of [RocksDB](http://rocksdb.org/), a log-structured merge tree (LSM) based key-value store.

A number of enhancements or customizations were done to RocksDB in order to achieve scalability and performance. These are described below.
## Enhancements to RocksDB
### Efficiently model documents
To implement a flexible data
model—such as a row (comprising of columns), or collections types (such as list, map, set) with
arbitrary nesting—on top of a key-value store, but, more importantly, to implement efficient
operations on this data model such as:
* fine-grained updates to a part of the row or collection without incurring a read-modify-write penalty of the entire row or collection
* deleting/overwriting a row or collection/object at an arbitrary nesting level without incurring a read penalty to determine what specific set of KVs need to be deleted
* enforcing row/object level TTL based expiration
A tighter coupling into the “read/compaction” layers of the underlying RocksDB key-value store is needed. Yugabyte uses RocksDB as an append-only store and operations, such as row or collection delete, are modeled as an insert of a special “delete marker”. This allows deleting an entire subdocument efficiently by just adding one key-value pair to RocksDB. Read hooks automatically recognize these markers and
suppress expired data. Expired values within the subdocument are cleaned up/garbage collected by our customized compaction hooks.
### Raft vs RocksDB WAL logs
DocDB uses Raft for replication. Changes to the distributed system are already recorded or journaled as part of Raft logs. When a change is accepted by a majority of peers, it is applied to each tablet peer’s DocDB, but the additional WAL mechanism in RocksDB (under DocDB) is unnecessary and adds overhead. For correctness, in addition to disabling the WAL mechanism in RocksDB, YugabyteDB tracks the Raft “sequence id” up to which data has been flushed from RocksDB’s memtables to SSTable files. This ensures that we can correctly garbage collect the Raft WAL logs as well as replay the minimal number of records from Raft WAL logs on a server crash or restart.
### MVCC at a higher layer
Multi-version concurrency control (MVCC) in DocDB is done at a higher layer, and does not use the MVCC mechanism of RocksDB.
The mutations to records in the system are versioned using hybrid-timestamps maintained at the YBase layer. As a result, the notion of MVCC as implemented in a vanilla RocksDB (using sequence IDs) is not necessary and only adds overhead. YugabyteDB does not use RocksDB’s sequence IDs, and instead uses hybrid-timestamps that are part of the encoded key to implement MVCC.
### Backups and snapshots
These need to be higher level operations that take into consideration data in DocDB as well as in the Raft logs to get a consistent cut of the state of the system.
## Data model aware Bloom filters
The keys stored by DocDB in RocksDB consist of a number of components, where the first component is a "document key", followed by a few scalar components, and finally followed by a timestamp (sorted in reverse order).
The bloom filter needs to be aware of what components of the key need be added to the bloom so that only the relevant SSTable files in the LSM store are looked up during a read operation.
In a traditional KV store, range scans do not make use of bloom filters because exact keys that fall in the range are unknown. However, we have implemented a data-model aware bloom filter, where range scans within keys that share the same hash component can also benefit from Bloom filters. For example, a scan to get all the columns within row or all the elements of a collection can also benefit from bloom filters.
## Range query optimizations
The ordered (or range) components of the compound-keys in DocDB frequently have a natural order. For example, it may be an int that represents a message ID (for a messaging application) or a timestamp (for a IoT/time series use case). See example below. By keeping hints with each SSTable file in the LSM store about the minimum and maximum values for these components of the “key”, range queries can intelligently prune away the lookup of irrelevant SSTable files during the read operation.
```sql
SELECT message_txt
FROM messages
WHERE user_id = 17
AND message_id > 50
AND message_id < 100;
```
Or, in the context of a time-series application:
```sql
SELECT metric_value
FROM metrics
WHERE metric_name = ’system.cpu’
AND metric_timestamp < ?
AND metric_timestamp > ?
```
## Efficient memory usage
There are two instances where memory usage across components in a manner that is global to the server yields benefits, as described below.
### Server-global block cache
A shared block cache is used across the DocDB/RocksDB instances of all the tablets hosted by a YB-TServer. This maximizes the use of memory resources, and avoids creating silos of cache that each need to be sized accurately for different user tables.
### Server-global memstore limits
While per-memstore flush sizes can be configured, in practice, because the number of memstores may change over time as users create new tables, or tablets of a table move between servers, we have enhanced the storage engine to enforce a global memstore threshold. When such a threshold is reached, selection of which memstore to flush takes into account what memstores carry the oldest records (determined using hybrid timestamps) and therefore are holding up Raft logs and preventing them from being garbage collected.
## Scan-resistant block cache
We have enhanced RocksDB’s block cache to be scan resistant. The motivation was to prevent operations such as long-running scans (e.g., due to an occasional large query or background Spark jobs) from polluting the entire cache with poor quality data and wiping out useful/hot data.
| {
"pile_set_name": "Github"
} |
# Vultr+SS+Firewall(fail2ban+iptables)+ss-bash
网络加速教程,适用于Linux0基础的同学
**教程见**
https://github.com/ugukkylbklaom/Vultr-SS-Firewall/wiki
| {
"pile_set_name": "Github"
} |
using System;
using Robust.Client.Animations;
using Robust.Client.GameObjects.Components.Animations;
using Robust.Client.Interfaces.GameObjects.Components;
using Robust.Shared.Animations;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects.Components;
using Robust.Shared.Maths;
namespace Content.Client.GameObjects.Components
{
[RegisterComponent]
public sealed class AnimationsTestComponent : Component
{
public override string Name => "AnimationsTest";
public override void Initialize()
{
base.Initialize();
var animations = Owner.GetComponent<AnimationPlayerComponent>();
animations.Play(new Animation
{
Length = TimeSpan.FromSeconds(20),
AnimationTracks =
{
new AnimationTrackComponentProperty
{
ComponentType = typeof(ITransformComponent),
Property = nameof(ITransformComponent.LocalRotation),
InterpolationMode = AnimationInterpolationMode.Linear,
KeyFrames =
{
new AnimationTrackProperty.KeyFrame(Angle.Zero, 0),
new AnimationTrackProperty.KeyFrame(Angle.FromDegrees(1440), 20)
}
},
new AnimationTrackComponentProperty
{
ComponentType = typeof(ISpriteComponent),
Property = "layer/0/texture",
KeyFrames =
{
new AnimationTrackProperty.KeyFrame("Objects/toolbox_r.png", 0),
new AnimationTrackProperty.KeyFrame("Objects/Toolbox_b.png", 5),
new AnimationTrackProperty.KeyFrame("Objects/Toolbox_y.png", 5),
new AnimationTrackProperty.KeyFrame("Objects/toolbox_r.png", 5),
}
}
}
}, "yes");
}
}
}
| {
"pile_set_name": "Github"
} |
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* Copyright (c) Faruk Ates, Paul Irish, Alex Sexton; http://www.modernizr.com/license/
*
* Includes matchMedia polyfill; Copyright (c) 2010 Filament Group, Inc; http://opensource.org/licenses/MIT
*
* Includes material adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js; Copyright 2009-2012 by contributors; http://opensource.org/licenses/MIT
*
* Includes material from css-support; Copyright (c) 2005-2012 Diego Perini; https://github.com/dperini/css-support/blob/master/LICENSE
*
* NUGET: END LICENSE TEXT */
/*!
* Modernizr v2.6.2
* www.modernizr.com
*
* Copyright (c) Faruk Ates, Paul Irish, Alex Sexton
* Available under the BSD and MIT licenses: www.modernizr.com/license/
*/
/*
* Modernizr tests which native CSS3 and HTML5 features are available in
* the current UA and makes the results available to you in two ways:
* as properties on a global Modernizr object, and as classes on the
* <html> element. This information allows you to progressively enhance
* your pages with a granular level of control over the experience.
*
* Modernizr has an optional (not included) conditional resource loader
* called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
* To get a build that includes Modernizr.load(), as well as choosing
* which tests to include, go to www.modernizr.com/download/
*
* Authors Faruk Ates, Paul Irish, Alex Sexton
* Contributors Ryan Seddon, Ben Alman
*/
window.Modernizr = (function( window, document, undefined ) {
var version = '2.6.2',
Modernizr = {},
/*>>cssclasses*/
// option for enabling the HTML classes to be added
enableClasses = true,
/*>>cssclasses*/
docElement = document.documentElement,
/**
* Create our "modernizr" element that we do most feature tests on.
*/
mod = 'modernizr',
modElem = document.createElement(mod),
mStyle = modElem.style,
/**
* Create the input element for various Web Forms feature tests.
*/
inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ ,
/*>>smile*/
smile = ':)',
/*>>smile*/
toString = {}.toString,
// TODO :: make the prefixes more granular
/*>>prefixes*/
// List of property values to set for css tests. See ticket #21
prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
/*>>prefixes*/
/*>>domprefixes*/
// Following spec is to expose vendor-specific style properties as:
// elem.style.WebkitBorderRadius
// and the following would be incorrect:
// elem.style.webkitBorderRadius
// Webkit ghosts their properties in lowercase but Opera & Moz do not.
// Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+
// erik.eae.net/archives/2008/03/10/21.48.10/
// More here: github.com/Modernizr/Modernizr/issues/issue/21
omPrefixes = 'Webkit Moz O ms',
cssomPrefixes = omPrefixes.split(' '),
domPrefixes = omPrefixes.toLowerCase().split(' '),
/*>>domprefixes*/
/*>>ns*/
ns = {'svg': 'http://www.w3.org/2000/svg'},
/*>>ns*/
tests = {},
inputs = {},
attrs = {},
classes = [],
slice = classes.slice,
featureName, // used in testing loop
/*>>teststyles*/
// Inject element with style element and some CSS rules
injectElementWithStyles = function( rule, callback, nodes, testnames ) {
var style, ret, node, docOverflow,
div = document.createElement('div'),
// After page load injecting a fake body doesn't work so check if body exists
body = document.body,
// IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it.
fakeBody = body || document.createElement('body');
if ( parseInt(nodes, 10) ) {
// In order not to give false positives we create a node for each test
// This also allows the method to scale for unspecified uses
while ( nodes-- ) {
node = document.createElement('div');
node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
div.appendChild(node);
}
}
// <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
// when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
// with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
// msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
// Documents served as xml will throw if using ­ so use xml friendly encoded version. See issue #277
style = ['­','<style id="s', mod, '">', rule, '</style>'].join('');
div.id = mod;
// IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody.
// Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270
(body ? div : fakeBody).innerHTML += style;
fakeBody.appendChild(div);
if ( !body ) {
//avoid crashing IE8, if background image is used
fakeBody.style.background = '';
//Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
fakeBody.style.overflow = 'hidden';
docOverflow = docElement.style.overflow;
docElement.style.overflow = 'hidden';
docElement.appendChild(fakeBody);
}
ret = callback(div, rule);
// If this is done after page load we don't want to remove the body so check if body exists
if ( !body ) {
fakeBody.parentNode.removeChild(fakeBody);
docElement.style.overflow = docOverflow;
} else {
div.parentNode.removeChild(div);
}
return !!ret;
},
/*>>teststyles*/
/*>>mq*/
// adapted from matchMedia polyfill
// by Scott Jehl and Paul Irish
// gist.github.com/786768
testMediaQuery = function( mq ) {
var matchMedia = window.matchMedia || window.msMatchMedia;
if ( matchMedia ) {
return matchMedia(mq).matches;
}
var bool;
injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
bool = (window.getComputedStyle ?
getComputedStyle(node, null) :
node.currentStyle)['position'] == 'absolute';
});
return bool;
},
/*>>mq*/
/*>>hasevent*/
//
// isEventSupported determines if a given element supports the given event
// kangax.github.com/iseventsupported/
//
// The following results are known incorrects:
// Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative
// Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333
// ...
isEventSupported = (function() {
var TAGNAMES = {
'select': 'input', 'change': 'input',
'submit': 'form', 'reset': 'form',
'error': 'img', 'load': 'img', 'abort': 'img'
};
function isEventSupported( eventName, element ) {
element = element || document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
// When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
var isSupported = eventName in element;
if ( !isSupported ) {
// If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
if ( !element.setAttribute ) {
element = document.createElement('div');
}
if ( element.setAttribute && element.removeAttribute ) {
element.setAttribute(eventName, '');
isSupported = is(element[eventName], 'function');
// If property was created, "remove it" (by setting value to `undefined`)
if ( !is(element[eventName], 'undefined') ) {
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
}
element = null;
return isSupported;
}
return isEventSupported;
})(),
/*>>hasevent*/
// TODO :: Add flag for hasownprop ? didn't last time
// hasOwnProperty shim by kangax needed for Safari 2.0 support
_hasOwnProperty = ({}).hasOwnProperty, hasOwnProp;
if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) {
hasOwnProp = function (object, property) {
return _hasOwnProperty.call(object, property);
};
}
else {
hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
};
}
// Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js
// es5.github.com/#x15.3.4.5
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) {
var target = this;
if (typeof target != "function") {
throw new TypeError();
}
var args = slice.call(arguments, 1),
bound = function () {
if (this instanceof bound) {
var F = function(){};
F.prototype = target.prototype;
var self = new F();
var result = target.apply(
self,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
return bound;
};
}
/**
* setCss applies given styles to the Modernizr DOM node.
*/
function setCss( str ) {
mStyle.cssText = str;
}
/**
* setCssAll extrapolates all vendor-specific css strings.
*/
function setCssAll( str1, str2 ) {
return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
}
/**
* is returns a boolean for if typeof obj is exactly type.
*/
function is( obj, type ) {
return typeof obj === type;
}
/**
* contains returns a boolean for if substr is found within str.
*/
function contains( str, substr ) {
return !!~('' + str).indexOf(substr);
}
/*>>testprop*/
// testProps is a generic CSS / DOM property test.
// In testing support for a given CSS property, it's legit to test:
// `elem.style[styleName] !== undefined`
// If the property is supported it will return an empty string,
// if unsupported it will return undefined.
// We'll take advantage of this quick test and skip setting a style
// on our modernizr element, but instead just testing undefined vs
// empty string.
// Because the testing of the CSS property names (with "-", as
// opposed to the camelCase DOM properties) is non-portable and
// non-standard but works in WebKit and IE (but not Gecko or Opera),
// we explicitly reject properties with dashes so that authors
// developing in WebKit or IE first don't end up with
// browser-specific content by accident.
function testProps( props, prefixed ) {
for ( var i in props ) {
var prop = props[i];
if ( !contains(prop, "-") && mStyle[prop] !== undefined ) {
return prefixed == 'pfx' ? prop : true;
}
}
return false;
}
/*>>testprop*/
// TODO :: add testDOMProps
/**
* testDOMProps is a generic DOM property test; if a browser supports
* a certain property, it won't return undefined for it.
*/
function testDOMProps( props, obj, elem ) {
for ( var i in props ) {
var item = obj[props[i]];
if ( item !== undefined) {
// return the property name as a string
if (elem === false) return props[i];
// let's bind a function
if (is(item, 'function')){
// default to autobind unless override
return item.bind(elem || obj);
}
// return the unbound function or obj or value
return item;
}
}
return false;
}
/*>>testallprops*/
/**
* testPropsAll tests a list of DOM properties we want to check against.
* We specify literally ALL possible (known and/or likely) properties on
* the element including the non-vendor prefixed one, for forward-
* compatibility.
*/
function testPropsAll( prop, prefixed, elem ) {
var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' ');
// did they call .prefixed('boxSizing') or are we just testing a prop?
if(is(prefixed, "string") || is(prefixed, "undefined")) {
return testProps(props, prefixed);
// otherwise, they called .prefixed('requestAnimationFrame', window[, elem])
} else {
props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' ');
return testDOMProps(props, prefixed, elem);
}
}
/*>>testallprops*/
/**
* Tests
* -----
*/
// The *new* flexbox
// dev.w3.org/csswg/css3-flexbox
tests['flexbox'] = function() {
return testPropsAll('flexWrap');
};
// The *old* flexbox
// www.w3.org/TR/2009/WD-css3-flexbox-20090723/
tests['flexboxlegacy'] = function() {
return testPropsAll('boxDirection');
};
// On the S60 and BB Storm, getContext exists, but always returns undefined
// so we actually have to call getContext() to verify
// github.com/Modernizr/Modernizr/issues/issue/97/
tests['canvas'] = function() {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
tests['canvastext'] = function() {
return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
};
// webk.it/70117 is tracking a legit WebGL feature detect proposal
// We do a soft detect which may false positive in order to avoid
// an expensive context creation: bugzil.la/732441
tests['webgl'] = function() {
return !!window.WebGLRenderingContext;
};
/*
* The Modernizr.touch test only indicates if the browser supports
* touch events, which does not necessarily reflect a touchscreen
* device, as evidenced by tablets running Windows 7 or, alas,
* the Palm Pre / WebOS (touch) phones.
*
* Additionally, Chrome (desktop) used to lie about its support on this,
* but that has since been rectified: crbug.com/36415
*
* We also test for Firefox 4 Multitouch Support.
*
* For more info, see: modernizr.github.com/Modernizr/touch.html
*/
tests['touch'] = function() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) {
bool = node.offsetTop === 9;
});
}
return bool;
};
// geolocation is often considered a trivial feature detect...
// Turns out, it's quite tricky to get right:
//
// Using !!navigator.geolocation does two things we don't want. It:
// 1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513
// 2. Disables page caching in WebKit: webk.it/43956
//
// Meanwhile, in Firefox < 8, an about:config setting could expose
// a false positive that would throw an exception: bugzil.la/688158
tests['geolocation'] = function() {
return 'geolocation' in navigator;
};
tests['postmessage'] = function() {
return !!window.postMessage;
};
// Chrome incognito mode used to throw an exception when using openDatabase
// It doesn't anymore.
tests['websqldatabase'] = function() {
return !!window.openDatabase;
};
// Vendors had inconsistent prefixing with the experimental Indexed DB:
// - Webkit's implementation is accessible through webkitIndexedDB
// - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
// For speed, we don't test the legacy (and beta-only) indexedDB
tests['indexedDB'] = function() {
return !!testPropsAll("indexedDB", window);
};
// documentMode logic from YUI to filter out IE8 Compat Mode
// which false positives.
tests['hashchange'] = function() {
return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
};
// Per 1.6:
// This used to be Modernizr.historymanagement but the longer
// name has been deprecated in favor of a shorter and property-matching one.
// The old API is still available in 1.6, but as of 2.0 will throw a warning,
// and in the first release thereafter disappear entirely.
tests['history'] = function() {
return !!(window.history && history.pushState);
};
tests['draganddrop'] = function() {
var div = document.createElement('div');
return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};
// FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10
// will be supported until FF19 (2/12/13), at which time, ESR becomes FF17.
// FF10 still uses prefixes, so check for it until then.
// for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/
tests['websockets'] = function() {
return 'WebSocket' in window || 'MozWebSocket' in window;
};
// css-tricks.com/rgba-browser-support/
tests['rgba'] = function() {
// Set an rgba() color and check the returned value
setCss('background-color:rgba(150,255,150,.5)');
return contains(mStyle.backgroundColor, 'rgba');
};
tests['hsla'] = function() {
// Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
// except IE9 who retains it as hsla
setCss('background-color:hsla(120,40%,100%,.5)');
return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
};
tests['multiplebgs'] = function() {
// Setting multiple images AND a color on the background shorthand property
// and then querying the style.background property value for the number of
// occurrences of "url(" is a reliable method for detecting ACTUAL support for this!
setCss('background:url(https://),url(https://),red url(https://)');
// If the UA supports multiple backgrounds, there should be three occurrences
// of the string "url(" in the return value for elemStyle.background
return (/(url\s*\(.*?){3}/).test(mStyle.background);
};
// this will false positive in Opera Mini
// github.com/Modernizr/Modernizr/issues/396
tests['backgroundsize'] = function() {
return testPropsAll('backgroundSize');
};
tests['borderimage'] = function() {
return testPropsAll('borderImage');
};
// Super comprehensive table about all the unique implementations of
// border-radius: muddledramblings.com/table-of-css3-border-radius-compliance
tests['borderradius'] = function() {
return testPropsAll('borderRadius');
};
// WebOS unfortunately false positives on this test.
tests['boxshadow'] = function() {
return testPropsAll('boxShadow');
};
// FF3.0 will false positive on this test
tests['textshadow'] = function() {
return document.createElement('div').style.textShadow === '';
};
tests['opacity'] = function() {
// Browsers that actually have CSS Opacity implemented have done so
// according to spec, which means their return values are within the
// range of [0.0,1.0] - including the leading zero.
setCssAll('opacity:.55');
// The non-literal . in this regex is intentional:
// German Chrome returns this value as 0,55
// github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
return (/^0.55$/).test(mStyle.opacity);
};
// Note, Android < 4 will pass this test, but can only animate
// a single property at a time
// daneden.me/2011/12/putting-up-with-androids-bullshit/
tests['cssanimations'] = function() {
return testPropsAll('animationName');
};
tests['csscolumns'] = function() {
return testPropsAll('columnCount');
};
tests['cssgradients'] = function() {
/**
* For CSS Gradients syntax, please see:
* webkit.org/blog/175/introducing-css-gradients/
* developer.mozilla.org/en/CSS/-moz-linear-gradient
* developer.mozilla.org/en/CSS/-moz-radial-gradient
* dev.w3.org/csswg/css3-images/#gradients-
*/
var str1 = 'background-image:',
str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
str3 = 'linear-gradient(left top,#9f9, white);';
setCss(
// legacy webkit syntax (FIXME: remove when syntax not in use anymore)
(str1 + '-webkit- '.split(' ').join(str2 + str1) +
// standard syntax // trailing 'background-image:'
prefixes.join(str3 + str1)).slice(0, -str1.length)
);
return contains(mStyle.backgroundImage, 'gradient');
};
tests['cssreflections'] = function() {
return testPropsAll('boxReflect');
};
tests['csstransforms'] = function() {
return !!testPropsAll('transform');
};
tests['csstransforms3d'] = function() {
var ret = !!testPropsAll('perspective');
// Webkit's 3D transforms are passed off to the browser's own graphics renderer.
// It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
// some conditions. As a result, Webkit typically recognizes the syntax but
// will sometimes throw a false positive, thus we must do a more thorough check:
if ( ret && 'webkitPerspective' in docElement.style ) {
// Webkit allows this media query to succeed only if the feature is enabled.
// `@media (transform-3d),(-webkit-transform-3d){ ... }`
injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) {
ret = node.offsetLeft === 9 && node.offsetHeight === 3;
});
}
return ret;
};
tests['csstransitions'] = function() {
return testPropsAll('transition');
};
/*>>fontface*/
// @font-face detection routine by Diego Perini
// javascript.nwbox.com/CSSSupport/
// false positives:
// WebOS github.com/Modernizr/Modernizr/issues/342
// WP7 github.com/Modernizr/Modernizr/issues/538
tests['fontface'] = function() {
var bool;
injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) {
var style = document.getElementById('smodernizr'),
sheet = style.sheet || style.styleSheet,
cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : '';
bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0;
});
return bool;
};
/*>>fontface*/
// CSS generated content detection
tests['generatedcontent'] = function() {
var bool;
injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) {
bool = node.offsetHeight >= 3;
});
return bool;
};
// These tests evaluate support of the video/audio elements, as well as
// testing what types of content they support.
//
// We're using the Boolean constructor here, so that we can extend the value
// e.g. Modernizr.video // true
// Modernizr.video.ogg // 'probably'
//
// Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
// thx to NielsLeenheer and zcorpan
// Note: in some older browsers, "no" was a return value instead of empty string.
// It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2
// It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5
tests['video'] = function() {
var elem = document.createElement('video'),
bool = false;
// IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
try {
if ( bool = !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,'');
// Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,'');
bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,'');
}
} catch(e) { }
return bool;
};
tests['audio'] = function() {
var elem = document.createElement('audio'),
bool = false;
try {
if ( bool = !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,'');
bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,'');
// Mimetypes accepted:
// developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
// bit.ly/iphoneoscodecs
bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,'');
bool.m4a = ( elem.canPlayType('audio/x-m4a;') ||
elem.canPlayType('audio/aac;')) .replace(/^no$/,'');
}
} catch(e) { }
return bool;
};
// In FF4, if disabled, window.localStorage should === null.
// Normally, we could not test that directly and need to do a
// `('localStorage' in window) && ` test first because otherwise Firefox will
// throw bugzil.la/365772 if cookies are disabled
// Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
// QUOTA_EXCEEDED_ERRROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.
// Because we are forced to try/catch this, we'll go aggressive.
// Just FWIW: IE8 Compat mode supports these features completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
tests['localstorage'] = function() {
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
};
tests['sessionstorage'] = function() {
try {
sessionStorage.setItem(mod, mod);
sessionStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
};
tests['webworkers'] = function() {
return !!window.Worker;
};
tests['applicationcache'] = function() {
return !!window.applicationCache;
};
// Thanks to Erik Dahlstrom
tests['svg'] = function() {
return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
};
// specifically for SVG inline in HTML, not within XHTML
// test page: paulirish.com/demo/inline-svg
tests['inlinesvg'] = function() {
var div = document.createElement('div');
div.innerHTML = '<svg/>';
return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
};
// SVG SMIL animation
tests['smil'] = function() {
return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
};
// This test is only for clip paths in SVG proper, not clip paths on HTML content
// demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg
// However read the comments to dig into applying SVG clippaths to HTML content here:
// github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491
tests['svgclippaths'] = function() {
return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
};
/*>>webforms*/
// input features and input types go directly onto the ret object, bypassing the tests loop.
// Hold this guy to execute in a moment.
function webforms() {
/*>>input*/
// Run through HTML5's new input attributes to see if the UA understands any.
// We're using f which is the <input> element created early on
// Mike Taylr has created a comprehensive resource for testing these attributes
// when applied to all input types:
// miketaylr.com/code/input-type-attr.html
// spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
// Only input placeholder is tested while textarea's placeholder is not.
// Currently Safari 4 and Opera 11 have support only for the input placeholder
// Both tests are available in feature-detects/forms-placeholder.js
Modernizr['input'] = (function( props ) {
for ( var i = 0, len = props.length; i < len; i++ ) {
attrs[ props[i] ] = !!(props[i] in inputElem);
}
if (attrs.list){
// safari false positive's on datalist: webk.it/74252
// see also github.com/Modernizr/Modernizr/issues/146
attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement);
}
return attrs;
})('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
/*>>input*/
/*>>inputtypes*/
// Run through HTML5's new input types to see if the UA understands any.
// This is put behind the tests runloop because it doesn't return a
// true/false like all the other tests; instead, it returns an object
// containing each input type with its corresponding true/false value
// Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/
Modernizr['inputtypes'] = (function(props) {
for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {
inputElem.setAttribute('type', inputElemType = props[i]);
bool = inputElem.type !== 'text';
// We first check to see if the type we give it sticks..
// If the type does, we feed it a textual value, which shouldn't be valid.
// If the value doesn't stick, we know there's input sanitization which infers a custom UI
if ( bool ) {
inputElem.value = smile;
inputElem.style.cssText = 'position:absolute;visibility:hidden;';
if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
// Safari 2-4 allows the smiley as a value, despite making a slider
bool = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
// Mobile android web browser has false positive, so must
// check the height to see if the widget is actually there.
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
} else if ( /^(search|tel)$/.test(inputElemType) ){
// Spec doesn't define any special parsing or detectable UI
// behaviors so we pass these through as true
// Interestingly, opera fails the earlier test, so it doesn't
// even make it here.
} else if ( /^(url|email)$/.test(inputElemType) ) {
// Real url and email support comes with prebaked validation.
bool = inputElem.checkValidity && inputElem.checkValidity() === false;
} else {
// If the upgraded input compontent rejects the :) text, we got a winner
bool = inputElem.value != smile;
}
}
inputs[ props[i] ] = !!bool;
}
return inputs;
})('search tel url email datetime date month week time datetime-local number range color'.split(' '));
/*>>inputtypes*/
}
/*>>webforms*/
// End of test definitions
// -----------------------
// Run through all tests and detect their support in the current UA.
// todo: hypothetically we could be doing an array of tests and use a basic loop here.
for ( var feature in tests ) {
if ( hasOwnProp(tests, feature) ) {
// run the test, throw the return value into the Modernizr,
// then based on that boolean, define an appropriate className
// and push it into an array of classes we'll join later.
featureName = feature.toLowerCase();
Modernizr[featureName] = tests[feature]();
classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
}
}
/*>>webforms*/
// input tests need to run.
Modernizr.input || webforms();
/*>>webforms*/
/**
* addTest allows the user to define their own feature tests
* the result will be added onto the Modernizr object,
* as well as an appropriate className set on the html element
*
* @param feature - String naming the feature
* @param test - Function returning true if feature is supported, false if not
*/
Modernizr.addTest = function ( feature, test ) {
if ( typeof feature == 'object' ) {
for ( var key in feature ) {
if ( hasOwnProp( feature, key ) ) {
Modernizr.addTest( key, feature[ key ] );
}
}
} else {
feature = feature.toLowerCase();
if ( Modernizr[feature] !== undefined ) {
// we're going to quit if you're trying to overwrite an existing test
// if we were to allow it, we'd do this:
// var re = new RegExp("\\b(no-)?" + feature + "\\b");
// docElement.className = docElement.className.replace( re, '' );
// but, no rly, stuff 'em.
return Modernizr;
}
test = typeof test == 'function' ? test() : test;
if (typeof enableClasses !== "undefined" && enableClasses) {
docElement.className += ' ' + (test ? '' : 'no-') + feature;
}
Modernizr[feature] = test;
}
return Modernizr; // allow chaining.
};
// Reset modElem.cssText to nothing to reduce memory footprint.
setCss('');
modElem = inputElem = null;
/*>>shiv*/
/*! HTML5 Shiv v3.6.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */
;(function(window, document) {
/*jshint evil:true */
/** Preset options */
var options = window.html5 || {};
/** Used to skip problem elements */
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
/** Not all elements can be cloned in IE **/
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
/** Detect whether the browser supports default html5 styles */
var supportsHtml5Styles;
/** Name of the expando, to work with multiple documents or to re-shiv one document */
var expando = '_html5shiv';
/** The id for the the documents expando */
var expanID = 0;
/** Cached data for each document */
var expandoData = {};
/** Detect whether the browser supports unknown elements */
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '<xyz></xyz>';
//if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
// assign a false positive if unable to shiv
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a style sheet with the given CSS text and adds it to the document.
* @private
* @param {Document} ownerDocument The document.
* @param {String} cssText The CSS text.
* @returns {StyleSheet} The style element.
*/
function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x<style>' + cssText + '</style>';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
/**
* Returns the value of `html5.elements` as an array.
* @private
* @returns {Array} An array of shived element node names.
*/
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
/**
* Returns the data associated to the given document
* @private
* @param {Document} ownerDocument The document.
* @returns {Object} An object of data.
*/
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
/**
* returns a shived element for the given nodeName and document
* @memberOf html5
* @param {String} nodeName name of the element
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived element.
*/
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
// Avoid adding some elements to fragments in IE < 9 because
// * Attributes like `name` or `type` cannot be set/changed once an element
// is inserted into a document/fragment
// * Link elements with `src` attributes that are inaccessible, as with
// a 403 response, will cause the tab/window to crash
// * Script elements appended to fragments will execute when their `src`
// or `text` property is set
return node.canHaveChildren && !reSkip.test(nodeName) ? data.frag.appendChild(node) : node;
}
/**
* returns a shived DocumentFragment for the given document
* @memberOf html5
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived DocumentFragment.
*/
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
/**
* Shivs the `createElement` and `createDocumentFragment` methods of the document.
* @private
* @param {Document|DocumentFragment} ownerDocument The document.
* @param {Object} data of the document.
*/
function shivMethods(ownerDocument, data) {
if (!data.cache) {
data.cache = {};
data.createElem = ownerDocument.createElement;
data.createFrag = ownerDocument.createDocumentFragment;
data.frag = data.createFrag();
}
ownerDocument.createElement = function(nodeName) {
//abort shiv
if (!html5.shivMethods) {
return data.createElem(nodeName);
}
return createElement(nodeName, ownerDocument, data);
};
ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
'var n=f.cloneNode(),c=n.createElement;' +
'h.shivMethods&&(' +
// unroll the `createElement` calls
getElements().join().replace(/\w+/g, function(nodeName) {
data.createElem(nodeName);
data.frag.createElement(nodeName);
return 'c("' + nodeName + '")';
}) +
');return n}'
)(html5, data.frag);
}
/*--------------------------------------------------------------------------*/
/**
* Shivs the given document.
* @memberOf html5
* @param {Document} ownerDocument The document to shiv.
* @returns {Document} The shived document.
*/
function shivDocument(ownerDocument) {
if (!ownerDocument) {
ownerDocument = document;
}
var data = getExpandoData(ownerDocument);
if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
data.hasCSS = !!addStyleSheet(ownerDocument,
// corrects block display not defined in IE6/7/8/9
'article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}' +
// adds styling not present in IE6/7/8/9
'mark{background:#FF0;color:#000}'
);
}
if (!supportsUnknownElements) {
shivMethods(ownerDocument, data);
}
return ownerDocument;
}
/*--------------------------------------------------------------------------*/
/**
* The `html5` object is exposed so that more elements can be shived and
* existing shiving can be detected on iframes.
* @type Object
* @example
*
* // options can be changed before the script is included
* html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
*/
var html5 = {
/**
* An array or space separated string of node names of the elements to shiv.
* @memberOf html5
* @type Array|String
*/
'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video',
/**
* A flag to indicate that the HTML5 style sheet should be inserted.
* @memberOf html5
* @type Boolean
*/
'shivCSS': (options.shivCSS !== false),
/**
* Is equal to true if a browser supports creating unknown/HTML5 elements
* @memberOf html5
* @type boolean
*/
'supportsUnknownElements': supportsUnknownElements,
/**
* A flag to indicate that the document's `createElement` and `createDocumentFragment`
* methods should be overwritten.
* @memberOf html5
* @type Boolean
*/
'shivMethods': (options.shivMethods !== false),
/**
* A string to describe the type of `html5` object ("default" or "default print").
* @memberOf html5
* @type String
*/
'type': 'default',
// shivs the document according to the specified `html5` object options
'shivDocument': shivDocument,
//creates a shived element
createElement: createElement,
//creates a shived documentFragment
createDocumentFragment: createDocumentFragment
};
/*--------------------------------------------------------------------------*/
// expose html5
window.html5 = html5;
// shiv the document
shivDocument(document);
}(this, document));
/*>>shiv*/
// Assign private properties to the return object with prefix
Modernizr._version = version;
// expose these for the plugin API. Look in the source for how to join() them against your input
/*>>prefixes*/
Modernizr._prefixes = prefixes;
/*>>prefixes*/
/*>>domprefixes*/
Modernizr._domPrefixes = domPrefixes;
Modernizr._cssomPrefixes = cssomPrefixes;
/*>>domprefixes*/
/*>>mq*/
// Modernizr.mq tests a given media query, live against the current state of the window
// A few important notes:
// * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false
// * A max-width or orientation query will be evaluated against the current state, which may change later.
// * You must specify values. Eg. If you are testing support for the min-width media query use:
// Modernizr.mq('(min-width:0)')
// usage:
// Modernizr.mq('only screen and (max-width:768)')
Modernizr.mq = testMediaQuery;
/*>>mq*/
/*>>hasevent*/
// Modernizr.hasEvent() detects support for a given event, with an optional element to test on
// Modernizr.hasEvent('gesturestart', elem)
Modernizr.hasEvent = isEventSupported;
/*>>hasevent*/
/*>>testprop*/
// Modernizr.testProp() investigates whether a given style property is recognized
// Note that the property names must be provided in the camelCase variant.
// Modernizr.testProp('pointerEvents')
Modernizr.testProp = function(prop){
return testProps([prop]);
};
/*>>testprop*/
/*>>testallprops*/
// Modernizr.testAllProps() investigates whether a given style property,
// or any of its vendor-prefixed variants, is recognized
// Note that the property names must be provided in the camelCase variant.
// Modernizr.testAllProps('boxSizing')
Modernizr.testAllProps = testPropsAll;
/*>>testallprops*/
/*>>teststyles*/
// Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards
// Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... })
Modernizr.testStyles = injectElementWithStyles;
/*>>teststyles*/
/*>>prefixed*/
// Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input
// Modernizr.prefixed('boxSizing') // 'MozBoxSizing'
// Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style.
// Return values will also be the camelCase variant, if you need to translate that to hypenated style use:
//
// str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');
// If you're trying to ascertain which transition end event to bind to, you might do something like...
//
// var transEndEventNames = {
// 'WebkitTransition' : 'webkitTransitionEnd',
// 'MozTransition' : 'transitionend',
// 'OTransition' : 'oTransitionEnd',
// 'msTransition' : 'MSTransitionEnd',
// 'transition' : 'transitionend'
// },
// transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
Modernizr.prefixed = function(prop, obj, elem){
if(!obj) {
return testPropsAll(prop, 'pfx');
} else {
// Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame'
return testPropsAll(prop, obj, elem);
}
};
/*>>prefixed*/
/*>>cssclasses*/
// Remove "no-js" class from <html> element, if it exists:
docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') +
// Add the new classes to the <html> element.
(enableClasses ? ' js ' + classes.join(' ') : '');
/*>>cssclasses*/
return Modernizr;
})(this, this.document);
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>17B48</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>Shiki</string>
<key>CFBundleIdentifier</key>
<string>as.vit9696.Shiki</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Shiki</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>2.2.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>2.2.0</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>9B55</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>17B41</string>
<key>DTSDKName</key>
<string>macosx10.13</string>
<key>DTXcode</key>
<string>0910</string>
<key>DTXcodeBuild</key>
<string>9B55</string>
<key>IOKitPersonalities</key>
<dict>
<key>as.vit9696.Shiki</key>
<dict>
<key>CFBundleIdentifier</key>
<string>as.vit9696.Shiki</string>
<key>IOClass</key>
<string>Shiki</string>
<key>IOMatchCategory</key>
<string>Shiki</string>
<key>IOProviderClass</key>
<string>IOResources</string>
<key>IOResourceMatch</key>
<string>IOKit</string>
</dict>
</dict>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2017 vit9696. All rights reserved.</string>
<key>OSBundleCompatibleVersion</key>
<string>1.0</string>
<key>OSBundleLibraries</key>
<dict>
<key>as.vit9696.Lilu</key>
<string>1.2.0</string>
<key>com.apple.kpi.bsd</key>
<string>12.0.0</string>
<key>com.apple.kpi.dsep</key>
<string>12.0.0</string>
<key>com.apple.kpi.iokit</key>
<string>12.0.0</string>
<key>com.apple.kpi.libkern</key>
<string>12.0.0</string>
<key>com.apple.kpi.mach</key>
<string>12.0.0</string>
<key>com.apple.kpi.unsupported</key>
<string>12.0.0</string>
</dict>
<key>OSBundleRequired</key>
<string>Root</string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.