text stringlengths 2 99k | meta dict |
|---|---|
/*
* Globalize Culture en-ZA
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "en-ZA", "default", {
name: "en-ZA",
englishName: "English (South Africa)",
nativeName: "English (South Africa)",
numberFormat: {
",": " ",
percent: {
pattern: ["-n%","n%"],
",": " "
},
currency: {
pattern: ["$-n","$ n"],
",": " ",
".": ",",
symbol: "R"
}
},
calendars: {
standard: {
patterns: {
d: "yyyy/MM/dd",
D: "dd MMMM yyyy",
t: "hh:mm tt",
T: "hh:mm:ss tt",
f: "dd MMMM yyyy hh:mm tt",
F: "dd MMMM yyyy hh:mm:ss tt",
M: "dd MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
| {
"pile_set_name": "Github"
} |
<?php
// This file was auto-generated from sdk-root/src/data/apigateway/2015-07-09/examples-1.json
return [ 'version' => '1.0', 'examples' => [],];
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2003-2018, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "mask.h"
namespace ledger {
mask_t::mask_t(const string& pat) : expr()
{
*this = pat;
TRACE_CTOR(mask_t, "const string&");
}
mask_t& mask_t::operator=(const string& pat)
{
#if HAVE_BOOST_REGEX_UNICODE
expr = boost::make_u32regex(pat.c_str(), boost::regex::perl | boost::regex::icase);
#else
expr.assign(pat.c_str(), boost::regex::perl | boost::regex::icase);
#endif
VERIFY(valid());
return *this;
}
mask_t& mask_t::assign_glob(const string& pat)
{
string re_pat = "";
string::size_type len = pat.length();
for (string::size_type i = 0; i < len; i++) {
switch (pat[i]) {
case '?':
re_pat += '.';
break;
case '*':
re_pat += ".*";
break;
case '[':
while (i < len && pat[i] != ']')
re_pat += pat[i++];
if (i < len)
re_pat += pat[i];
break;
case '\\':
if (i + 1 < len) {
re_pat += pat[++i];
break;
}
// fallthrough...
default:
re_pat += pat[i];
break;
}
}
return (*this = re_pat);
}
} // namespace ledger
| {
"pile_set_name": "Github"
} |
/*
* SonarQube
* Copyright (C) 2009-2020 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner.scan.branch;
import javax.annotation.ParametersAreNonnullByDefault;
| {
"pile_set_name": "Github"
} |
This is a paragraph.
---
> Block quote with horizontal lines.
> ---
> > Double block quote.
> > ---
> > End of the double block quote.
> A new paragraph.
> With multiple lines.
Even a lazy line.
> ---
> The last line.
| {
"pile_set_name": "Github"
} |
package com.taobao.arthas.bytekit.asm.location.filter;
import com.alibaba.arthas.deps.org.objectweb.asm.tree.AbstractInsnNode;
import com.alibaba.arthas.deps.org.objectweb.asm.tree.MethodInsnNode;
import com.taobao.arthas.bytekit.asm.location.LocationType;
/**
*
* 检查整个method里,是否有某个函数调用。用于检查 enter/exit/exception exit
*
* @author hengyunabc 2020-05-04
*
*/
public class InvokeContainLocationFilter implements LocationFilter {
private String owner;
private String methodName;
private LocationType locationType;
public InvokeContainLocationFilter(String owner, String methodName, LocationType locationType) {
this.owner = owner;
this.methodName = methodName;
this.locationType = locationType;
}
@Override
public boolean allow(AbstractInsnNode insnNode, LocationType locationType, boolean complete) {
// 只检查自己对应的 LocationType
if (!this.locationType.equals(locationType)) {
return false;
}
MethodInsnNode methodInsnNode = findMethodInsnNode(insnNode);
if (methodInsnNode != null) {
if (methodInsnNode.owner.equals(this.owner) && methodInsnNode.name.equals(this.methodName)) {
return false;
}
}
return true;
}
private MethodInsnNode findMethodInsnNode(AbstractInsnNode insnNode) {
AbstractInsnNode current = insnNode;
while (current != null) {
current = current.getNext();
if (current instanceof MethodInsnNode) {
MethodInsnNode methodInsnNode = (MethodInsnNode) current;
if (methodInsnNode.owner.equals(this.owner) && methodInsnNode.name.equals(this.methodName)) {
return methodInsnNode;
}
}
}
current = insnNode;
while (current != null) {
current = current.getPrevious();
if (current instanceof MethodInsnNode) {
MethodInsnNode methodInsnNode = (MethodInsnNode) current;
if (methodInsnNode.owner.equals(this.owner) && methodInsnNode.name.equals(this.methodName)) {
return methodInsnNode;
}
}
}
return null;
}
}
| {
"pile_set_name": "Github"
} |
/*!
* Bootstrap Reboot v4.3.1 (https://getbootstrap.com/)
* Copyright 2011-2019 The Bootstrap Authors
* Copyright 2011-2019 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
font-family: sans-serif;
line-height: 1.15;
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
article, aside, figcaption, figure, footer, header, hgroup, main, nav, section {
display: block;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #212529;
text-align: left;
background-color: #fff;
}
[tabindex="-1"]:focus {
outline: 0 !important;
}
hr {
box-sizing: content-box;
height: 0;
overflow: visible;
}
h1, h2, h3, h4, h5, h6 {
margin-top: 0;
margin-bottom: 0.5rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-original-title] {
text-decoration: underline;
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
border-bottom: 0;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: .5rem;
margin-left: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -.25em;
}
sup {
top: -.5em;
}
a {
color: #007bff;
text-decoration: none;
background-color: transparent;
}
a:hover {
color: #0056b3;
text-decoration: underline;
}
a:not([href]):not([tabindex]) {
color: inherit;
text-decoration: none;
}
a:not([href]):not([tabindex]):hover, a:not([href]):not([tabindex]):focus {
color: inherit;
text-decoration: none;
}
a:not([href]):not([tabindex]):focus {
outline: 0;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
}
pre {
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
}
figure {
margin: 0 0 1rem;
}
img {
vertical-align: middle;
border-style: none;
}
svg {
overflow: hidden;
vertical-align: middle;
}
table {
border-collapse: collapse;
}
caption {
padding-top: 0.75rem;
padding-bottom: 0.75rem;
color: #6c757d;
text-align: left;
caption-side: bottom;
}
th {
text-align: inherit;
}
label {
display: inline-block;
margin-bottom: 0.5rem;
}
button {
border-radius: 0;
}
button:focus {
outline: 1px dotted;
outline: 5px auto -webkit-focus-ring-color;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
input {
overflow: visible;
}
button,
select {
text-transform: none;
}
select {
word-wrap: normal;
}
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
}
button:not(:disabled),
[type="button"]:not(:disabled),
[type="reset"]:not(:disabled),
[type="submit"]:not(:disabled) {
cursor: pointer;
}
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
padding: 0;
border-style: none;
}
input[type="radio"],
input[type="checkbox"] {
box-sizing: border-box;
padding: 0;
}
input[type="date"],
input[type="time"],
input[type="datetime-local"],
input[type="month"] {
-webkit-appearance: listbox;
}
textarea {
overflow: auto;
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
display: block;
width: 100%;
max-width: 100%;
padding: 0;
margin-bottom: .5rem;
font-size: 1.5rem;
line-height: inherit;
color: inherit;
white-space: normal;
}
progress {
vertical-align: baseline;
}
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
[type="search"] {
outline-offset: -2px;
-webkit-appearance: none;
}
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
summary {
display: list-item;
cursor: pointer;
}
template {
display: none;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.css.map */ | {
"pile_set_name": "Github"
} |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/favicon/core/large_icon_service.h"
#include <deque>
#include <memory>
#include "base/bind.h"
#include "base/macros.h"
#include "base/memory/ref_counted_memory.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/favicon/core/favicon_client.h"
#include "components/favicon/core/favicon_service.h"
#include "components/favicon_base/fallback_icon_style.h"
#include "components/favicon_base/favicon_types.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
namespace favicon {
namespace {
const char kDummyUrl[] = "http://www.example.com";
const char kDummyIconUrl[] = "http://www.example.com/touch_icon.png";
const SkColor kTestColor = SK_ColorRED;
favicon_base::FaviconRawBitmapResult CreateTestBitmap(
int w, int h, SkColor color) {
favicon_base::FaviconRawBitmapResult result;
result.expired = false;
// Create bitmap and fill with |color|.
scoped_refptr<base::RefCountedBytes> data(new base::RefCountedBytes());
SkBitmap bitmap;
bitmap.allocN32Pixels(w, h);
bitmap.eraseColor(color);
gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &data->data());
result.bitmap_data = data;
result.pixel_size = gfx::Size(w, h);
result.icon_url = GURL(kDummyIconUrl);
result.icon_type = favicon_base::TOUCH_ICON;
CHECK(result.is_valid());
return result;
}
// A mock FaviconService that emits pre-programmed response.
class MockFaviconService : public FaviconService {
public:
MockFaviconService() : FaviconService(nullptr, nullptr) {
}
~MockFaviconService() override {
}
base::CancelableTaskTracker::TaskId GetLargestRawFaviconForPageURL(
const GURL& page_url,
const std::vector<int>& icon_types,
int minimum_size_in_pixels,
const favicon_base::FaviconRawBitmapCallback& callback,
base::CancelableTaskTracker* tracker) override {
favicon_base::FaviconRawBitmapResult mock_result =
mock_result_queue_.front();
mock_result_queue_.pop_front();
return tracker->PostTask(base::ThreadTaskRunnerHandle::Get().get(),
FROM_HERE, base::Bind(callback, mock_result));
}
void InjectResult(const favicon_base::FaviconRawBitmapResult& mock_result) {
mock_result_queue_.push_back(mock_result);
}
bool HasUnusedResults() {
return !mock_result_queue_.empty();
}
private:
std::deque<favicon_base::FaviconRawBitmapResult> mock_result_queue_;
DISALLOW_COPY_AND_ASSIGN(MockFaviconService);
};
// This class provides access to LargeIconService internals, using the current
// thread's task runner for testing.
class TestLargeIconService : public LargeIconService {
public:
explicit TestLargeIconService(MockFaviconService* mock_favicon_service)
: LargeIconService(mock_favicon_service,
base::ThreadTaskRunnerHandle::Get()) {}
~TestLargeIconService() override {
}
private:
DISALLOW_COPY_AND_ASSIGN(TestLargeIconService);
};
class LargeIconServiceTest : public testing::Test {
public:
LargeIconServiceTest() : is_callback_invoked_(false) {
}
~LargeIconServiceTest() override {
}
void SetUp() override {
testing::Test::SetUp();
mock_favicon_service_.reset(new MockFaviconService());
large_icon_service_.reset(
new TestLargeIconService(mock_favicon_service_.get()));
}
void ResultCallback(const favicon_base::LargeIconResult& result) {
is_callback_invoked_ = true;
// Checking presence and absence of results.
EXPECT_EQ(expected_bitmap_.is_valid(), result.bitmap.is_valid());
EXPECT_EQ(expected_fallback_icon_style_ != nullptr,
result.fallback_icon_style != nullptr);
if (expected_bitmap_.is_valid()) {
EXPECT_EQ(expected_bitmap_.pixel_size, result.bitmap.pixel_size);
// Not actually checking bitmap content.
}
if (expected_fallback_icon_style_.get()) {
EXPECT_EQ(*expected_fallback_icon_style_,
*result.fallback_icon_style);
}
// Ensure all mock results have been consumed.
EXPECT_FALSE(mock_favicon_service_->HasUnusedResults());
}
protected:
base::MessageLoopForIO loop_;
std::unique_ptr<MockFaviconService> mock_favicon_service_;
std::unique_ptr<TestLargeIconService> large_icon_service_;
base::CancelableTaskTracker cancelable_task_tracker_;
favicon_base::FaviconRawBitmapResult expected_bitmap_;
std::unique_ptr<favicon_base::FallbackIconStyle>
expected_fallback_icon_style_;
bool is_callback_invoked_;
private:
DISALLOW_COPY_AND_ASSIGN(LargeIconServiceTest);
};
TEST_F(LargeIconServiceTest, SameSize) {
mock_favicon_service_->InjectResult(CreateTestBitmap(24, 24, kTestColor));
expected_bitmap_ = CreateTestBitmap(24, 24, kTestColor);
large_icon_service_->GetLargeIconOrFallbackStyle(
GURL(kDummyUrl),
24, // |min_source_size_in_pixel|
24, // |desired_size_in_pixel|
base::Bind(&LargeIconServiceTest::ResultCallback, base::Unretained(this)),
&cancelable_task_tracker_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(is_callback_invoked_);
}
TEST_F(LargeIconServiceTest, ScaleDown) {
mock_favicon_service_->InjectResult(CreateTestBitmap(32, 32, kTestColor));
expected_bitmap_ = CreateTestBitmap(24, 24, kTestColor);
large_icon_service_->GetLargeIconOrFallbackStyle(
GURL(kDummyUrl),
24,
24,
base::Bind(&LargeIconServiceTest::ResultCallback, base::Unretained(this)),
&cancelable_task_tracker_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(is_callback_invoked_);
}
TEST_F(LargeIconServiceTest, ScaleUp) {
mock_favicon_service_->InjectResult(CreateTestBitmap(16, 16, kTestColor));
expected_bitmap_ = CreateTestBitmap(24, 24, kTestColor);
large_icon_service_->GetLargeIconOrFallbackStyle(
GURL(kDummyUrl),
14, // Lowered requirement so stored bitmap is admitted.
24,
base::Bind(&LargeIconServiceTest::ResultCallback, base::Unretained(this)),
&cancelable_task_tracker_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(is_callback_invoked_);
}
// |desired_size_in_pixel| == 0 means retrieve original image without scaling.
TEST_F(LargeIconServiceTest, NoScale) {
mock_favicon_service_->InjectResult(CreateTestBitmap(24, 24, kTestColor));
expected_bitmap_ = CreateTestBitmap(24, 24, kTestColor);
large_icon_service_->GetLargeIconOrFallbackStyle(
GURL(kDummyUrl),
16,
0,
base::Bind(&LargeIconServiceTest::ResultCallback, base::Unretained(this)),
&cancelable_task_tracker_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(is_callback_invoked_);
}
TEST_F(LargeIconServiceTest, FallbackSinceIconTooSmall) {
mock_favicon_service_->InjectResult(CreateTestBitmap(16, 16, kTestColor));
expected_fallback_icon_style_.reset(new favicon_base::FallbackIconStyle);
expected_fallback_icon_style_->background_color = kTestColor;
expected_fallback_icon_style_->is_default_background_color = false;
large_icon_service_->GetLargeIconOrFallbackStyle(
GURL(kDummyUrl),
24,
24,
base::Bind(&LargeIconServiceTest::ResultCallback, base::Unretained(this)),
&cancelable_task_tracker_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(is_callback_invoked_);
}
TEST_F(LargeIconServiceTest, FallbackSinceIconNotSquare) {
mock_favicon_service_->InjectResult(CreateTestBitmap(24, 32, kTestColor));
expected_fallback_icon_style_.reset(new favicon_base::FallbackIconStyle);
expected_fallback_icon_style_->background_color = kTestColor;
expected_fallback_icon_style_->is_default_background_color = false;
large_icon_service_->GetLargeIconOrFallbackStyle(
GURL(kDummyUrl),
24,
24,
base::Bind(&LargeIconServiceTest::ResultCallback, base::Unretained(this)),
&cancelable_task_tracker_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(is_callback_invoked_);
}
TEST_F(LargeIconServiceTest, FallbackSinceIconMissing) {
mock_favicon_service_->InjectResult(favicon_base::FaviconRawBitmapResult());
// Expect default fallback style, including background.
expected_fallback_icon_style_.reset(new favicon_base::FallbackIconStyle);
large_icon_service_->GetLargeIconOrFallbackStyle(
GURL(kDummyUrl),
24,
24,
base::Bind(&LargeIconServiceTest::ResultCallback, base::Unretained(this)),
&cancelable_task_tracker_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(is_callback_invoked_);
}
TEST_F(LargeIconServiceTest, FallbackSinceIconMissingNoScale) {
mock_favicon_service_->InjectResult(favicon_base::FaviconRawBitmapResult());
// Expect default fallback style, including background.
expected_fallback_icon_style_.reset(new favicon_base::FallbackIconStyle);
large_icon_service_->GetLargeIconOrFallbackStyle(
GURL(kDummyUrl),
24,
0,
base::Bind(&LargeIconServiceTest::ResultCallback, base::Unretained(this)),
&cancelable_task_tracker_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(is_callback_invoked_);
}
// Oddball case where we demand a high resolution icon to scale down. Generates
// fallback even though an icon with the final size is available.
TEST_F(LargeIconServiceTest, FallbackSinceTooPicky) {
mock_favicon_service_->InjectResult(CreateTestBitmap(24, 24, kTestColor));
expected_fallback_icon_style_.reset(new favicon_base::FallbackIconStyle);
expected_fallback_icon_style_->background_color = kTestColor;
expected_fallback_icon_style_->is_default_background_color = false;
large_icon_service_->GetLargeIconOrFallbackStyle(
GURL(kDummyUrl),
32,
24,
base::Bind(&LargeIconServiceTest::ResultCallback, base::Unretained(this)),
&cancelable_task_tracker_);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(is_callback_invoked_);
}
} // namespace
} // namespace favicon
| {
"pile_set_name": "Github"
} |
site_name: DRF-schema-adapter documentation
repo_url: https://github.com/drf-forms/drf-schema-adapter
pages:
- Home: index.md
- 'DRF-auto-endpoint':
- 'DRF-auto-endpoint': drf_auto_endpoint/index.md
- 'Endpoint': drf_auto_endpoint/endpoint.md
- 'Metadata': drf_auto_endpoint/metadata.md
- 'Export-app': export_app/index.md
- 'Cookbooks':
- 'Basics':
- 'Quick start': cookbooks/basics/quickstart.md
- 'Creating endpoints from models': cookbooks/basics/endpoints.md
- 'Using drf-schema-adapter with Ember.js': cookbooks/basics/ember.md
- 'Topics':
- 'Custom MetaData Adapter': cookbooks/topics/custom_metadata_adapter.md
- 'Custom Export Adapter': cookbooks/topics/custom_export_adapter.md
- 'Custom ViewSets': cookbooks/topics/viewsets.md
- 'Custom Serializers': cookbooks/topics/serializers.md
- 'Custom Actions': cookbooks/topics/actions.md
- 'Custom Actions With Specialized Serializers': cookbooks/topics/wizards.md
- License: LICENSE.md
- 'Code of conduct': COC.md
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2012-2020 Wojciech Figat. All rights reserved.
using System;
using System.IO;
using FlaxEngine;
namespace FlaxEditor.GUI.Timeline.Tracks
{
/// <summary>
/// The timeline media that represents a nested scene animation media event.
/// </summary>
/// <seealso cref="FlaxEditor.GUI.Timeline.Media" />
public class NestedSceneAnimationMedia : SingleMediaAssetMedia
{
private sealed class Proxy : ProxyBase<NestedSceneAnimationTrack, NestedSceneAnimationMedia>
{
/// <summary>
/// Gets or sets the nested scene animation to play.
/// </summary>
[EditorDisplay("General"), EditorOrder(10), Tooltip("The nested scene animation to play.")]
public SceneAnimation NestedSceneAnimation
{
get => Track.Asset;
set => Track.Asset = value;
}
/// <summary>
/// Gets or sets the nested animation looping mode.
/// </summary>
[EditorDisplay("General"), EditorOrder(20), Tooltip("If checked, the nested animation will loop when playback exceeds its duration. Otherwise it will stop play.")]
public bool Loop
{
get => Track.Loop;
set => Track.Loop = value;
}
/// <inheritdoc />
public Proxy(NestedSceneAnimationTrack track, NestedSceneAnimationMedia media)
: base(track, media)
{
}
}
/// <inheritdoc />
public override void OnTimelineChanged(Track track)
{
base.OnTimelineChanged(track);
PropertiesEditObject = new Proxy(Track as NestedSceneAnimationTrack, this);
}
}
/// <summary>
/// The timeline track that represents a nested scene animation playback.
/// </summary>
/// <seealso cref="FlaxEditor.GUI.Timeline.Track" />
public class NestedSceneAnimationTrack : SingleMediaAssetTrack<SceneAnimation, NestedSceneAnimationMedia>
{
/// <summary>
/// Gets the archetype.
/// </summary>
/// <returns>The archetype.</returns>
public static TrackArchetype GetArchetype()
{
return new TrackArchetype
{
TypeId = 3,
Name = "Nested Timeline",
Create = options => new NestedSceneAnimationTrack(ref options),
Load = LoadTrack,
Save = SaveTrack,
};
}
private static void LoadTrack(int version, Track track, BinaryReader stream)
{
var e = (NestedSceneAnimationTrack)track;
Guid id = new Guid(stream.ReadBytes(16));
e.Asset = FlaxEngine.Content.LoadAsync<SceneAnimation>(id);
var m = e.TrackMedia;
m.StartFrame = stream.ReadInt32();
m.DurationFrames = stream.ReadInt32();
}
private static void SaveTrack(Track track, BinaryWriter stream)
{
var e = (NestedSceneAnimationTrack)track;
var assetId = e.Asset?.ID ?? Guid.Empty;
stream.Write(assetId.ToByteArray());
if (e.Media.Count != 0)
{
var m = e.TrackMedia;
stream.Write(m.StartFrame);
stream.Write(m.DurationFrames);
}
else
{
stream.Write(0);
stream.Write(track.Timeline.DurationFrames);
}
}
/// <summary>
/// Gets or sets the nested animation looping mode.
/// </summary>
public bool TrackLoop
{
get => Loop;
set
{
NestedSceneAnimationMedia media = TrackMedia;
if (Loop == value)
return;
Loop = value;
Timeline?.MarkAsEdited();
}
}
/// <inheritdoc />
public NestedSceneAnimationTrack(ref TrackCreateOptions options)
: base(ref options)
{
}
}
}
| {
"pile_set_name": "Github"
} |
\documentclass{book}
\usepackage[a4paper,top=2.5cm,bottom=2.5cm,left=2.5cm,right=2.5cm]{geometry}
\usepackage{makeidx}
\usepackage{natbib}
\usepackage{graphicx}
\usepackage{multicol}
\usepackage{float}
\usepackage{listings}
\usepackage{color}
\usepackage{ifthen}
\usepackage[table]{xcolor}
\usepackage{textcomp}
\usepackage{alltt}
\usepackage{ifpdf}
\ifpdf
\usepackage[pdftex,
pagebackref=true,
colorlinks=true,
linkcolor=blue,
unicode
]{hyperref}
\else
\usepackage[ps2pdf,
pagebackref=true,
colorlinks=true,
linkcolor=blue,
unicode
]{hyperref}
\usepackage{pspicture}
\fi
\usepackage[utf8]{inputenc}
\usepackage{mathptmx}
\usepackage[scaled=.90]{helvet}
\usepackage{courier}
\usepackage{sectsty}
\usepackage{amssymb}
\usepackage[titles]{tocloft}
\usepackage{doxygen}
\lstset{language=C++,inputencoding=utf8,basicstyle=\footnotesize,breaklines=true,breakatwhitespace=true,tabsize=4,numbers=left }
\makeindex
\setcounter{tocdepth}{3}
\renewcommand{\footrulewidth}{0.4pt}
\renewcommand{\familydefault}{\sfdefault}
\hfuzz=15pt
\setlength{\emergencystretch}{15pt}
\hbadness=750
\tolerance=750
\begin{document}
\hypersetup{pageanchor=false,citecolor=blue}
\begin{titlepage}
\vspace*{7cm}
\begin{center}
{\Huge libopencm3: API Reference\\ STM STM32F3 ARM Cortex M3 Series}\\
\vspace*{1cm}
{\large Generated by Doxygen 1.8.2}\\
\vspace*{0.5cm}
{\small Thu Sep 13 2012 23:26:45}\\
\end{center}
\end{titlepage}
\pagenumbering{arabic}
\hypersetup{pageanchor=true,citecolor=blue}
| {
"pile_set_name": "Github"
} |
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 48 (0x30)
Signature Algorithm: sha1WithRSAEncryption
Issuer: C=FR, ST=Radius, L=Somewhere, O=Example Inc./emailAddress=admin@example.com, CN=Example Certificate Authority
Validity
Not Before: Jun 7 08:06:49 2017 GMT
Not After : Jun 5 08:06:49 2027 GMT
Subject: C=FR, ST=Radius, O=Example Inc., CN=user@example.com/emailAddress=user@example.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:d2:f6:be:72:a5:ab:2e:56:0c:dd:f2:3b:2c:7c:
e0:5d:05:40:af:0c:8c:f3:82:0c:d0:18:34:b4:e3:
7d:5f:8d:0a:3e:aa:79:02:f9:96:ad:10:00:ec:51:
e9:dc:3f:fb:ea:b0:57:eb:48:c7:ca:ef:e8:05:ab:
ee:3f:66:ba:5c:9e:7f:40:85:9f:25:a0:e0:e3:7c:
cf:b6:e6:31:f5:fd:24:03:c8:f4:fb:d8:a4:f3:92:
29:05:aa:55:43:80:f7:3e:13:10:43:3a:89:24:be:
d8:01:86:d1:69:73:44:7d:f8:b9:46:2b:6b:51:d0:
11:31:4b:06:ae:9f:45:fa:12:17:0c:ef:6a:fa:d0:
f7:36:46:eb:2e:db:4e:20:46:01:33:ac:b1:f7:4a:
e6:18:3d:53:22:dc:e8:4a:12:78:11:2f:e4:3b:92:
bd:d7:07:5a:c9:81:5d:48:58:c8:0f:9b:e9:a4:0f:
bb:89:b1:ad:38:07:6f:93:d0:a6:12:56:f9:07:48:
d2:23:2f:a3:a9:93:b0:11:0a:27:4c:48:0a:8d:70:
41:68:76:7a:dd:bc:54:c3:42:33:b0:7b:f6:ae:1f:
e7:95:5e:11:ca:f2:b4:4b:5c:ba:47:64:f0:f3:d7:
87:95:7f:93:06:a1:72:c9:81:12:a5:b7:8f:9d:7e:
d1:ef
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Extended Key Usage:
TLS Web Client Authentication
X509v3 CRL Distribution Points:
Full Name:
URI:http://www.example.com/example_ca.crl
Signature Algorithm: sha1WithRSAEncryption
2d:02:bc:7b:88:b8:5c:e1:07:b8:bb:ba:b2:f3:98:14:8f:cb:
b0:21:13:b5:e5:6f:05:4f:92:fa:ac:c0:53:a7:b0:cd:7e:ba:
87:36:85:25:d7:41:c5:29:84:22:74:af:bf:3e:34:36:d5:24:
7a:81:e2:1b:54:52:85:6f:76:de:dc:63:98:45:fc:2c:31:fa:
22:a4:72:3a:8d:d4:6a:2e:de:33:10:41:eb:94:1d:e3:59:cd:
b2:be:ab:f0:b6:20:86:9c:b8:46:ee:c5:64:ba:b6:6c:cc:53:
44:7a:80:12:77:7c:e7:51:67:91:32:2f:88:9d:93:a8:ef:d6:
cd:de
-----BEGIN CERTIFICATE-----
MIIDTjCCAregAwIBAgIBMDANBgkqhkiG9w0BAQUFADCBkzELMAkGA1UEBhMCRlIx
DzANBgNVBAgMBlJhZGl1czESMBAGA1UEBwwJU29tZXdoZXJlMRUwEwYDVQQKDAxF
eGFtcGxlIEluYy4xIDAeBgkqhkiG9w0BCQEWEWFkbWluQGV4YW1wbGUuY29tMSYw
JAYDVQQDDB1FeGFtcGxlIENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNzA2MDcw
ODA2NDlaFw0yNzA2MDUwODA2NDlaMHExCzAJBgNVBAYTAkZSMQ8wDQYDVQQIDAZS
YWRpdXMxFTATBgNVBAoMDEV4YW1wbGUgSW5jLjEZMBcGA1UEAwwQdXNlckBleGFt
cGxlLmNvbTEfMB0GCSqGSIb3DQEJARYQdXNlckBleGFtcGxlLmNvbTCCASIwDQYJ
KoZIhvcNAQEBBQADggEPADCCAQoCggEBANL2vnKlqy5WDN3yOyx84F0FQK8MjPOC
DNAYNLTjfV+NCj6qeQL5lq0QAOxR6dw/++qwV+tIx8rv6AWr7j9mulyef0CFnyWg
4ON8z7bmMfX9JAPI9PvYpPOSKQWqVUOA9z4TEEM6iSS+2AGG0WlzRH34uUYra1HQ
ETFLBq6fRfoSFwzvavrQ9zZG6y7bTiBGATOssfdK5hg9UyLc6EoSeBEv5DuSvdcH
WsmBXUhYyA+b6aQPu4mxrTgHb5PQphJW+QdI0iMvo6mTsBEKJ0xICo1wQWh2et28
VMNCM7B79q4f55VeEcrytEtcukdk8PPXh5V/kwahcsmBEqW3j51+0e8CAwEAAaNP
ME0wEwYDVR0lBAwwCgYIKwYBBQUHAwIwNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDov
L3d3dy5leGFtcGxlLmNvbS9leGFtcGxlX2NhLmNybDANBgkqhkiG9w0BAQUFAAOB
gQAtArx7iLhc4Qe4u7qy85gUj8uwIRO15W8FT5L6rMBTp7DNfrqHNoUl10HFKYQi
dK+/PjQ21SR6geIbVFKFb3be3GOYRfwsMfoipHI6jdRqLt4zEEHrlB3jWc2yvqvw
tiCGnLhG7sVkurZszFNEeoASd3znUWeRMi+InZOo79bN3g==
-----END CERTIFICATE-----
| {
"pile_set_name": "Github"
} |
package jetbrains.mps.lang.editor.menus.style.testLanguage.editor;
/*Generated by MPS */
import jetbrains.mps.nodeEditor.DefaultNodeEditor;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.openapi.editor.EditorContext;
import org.jetbrains.mps.openapi.model.SNode;
public class TestCompletionCustomization_ParentTestContextMatcher_Editor extends DefaultNodeEditor {
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return new TestCompletionCustomization_ParentTestContextMatcher_EditorBuilder_a(editorContext, node).createCell();
}
}
| {
"pile_set_name": "Github"
} |
<blockquote>
<p>Decentralized and 100% autonomous P2P VPN Network on blockchain with the first Internet bandwidth marketplace powered by own crypto-economy</p>
<footer><a href="https://privatix.io/" target="_blank">https://privatix.io/</a></footer>
</blockquote>
| {
"pile_set_name": "Github"
} |
*%(basename)s:8: ReferenceError: foo is not defined
static x = foo();
^
ReferenceError: foo is not defined
at Function.<static_fields_initializer> (*%(basename)s:8:14)
at *%(basename)s:1:1 | {
"pile_set_name": "Github"
} |
/********************************************************************
* *
* THIS FILE IS PART OF THE OggTheora SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE Theora SOURCE CODE IS COPYRIGHT (C) 2002-2009 *
* by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
* *
********************************************************************
function:
last mod: $Id: x86int.h 15675 2009-02-06 09:43:27Z tterribe $
********************************************************************/
#if !defined(_x86_vc_x86enc_H)
# define _x86_vc_x86enc_H (1)
# include "x86int.h"
# if defined(OC_X86_ASM)
# define oc_enc_accel_init oc_enc_accel_init_x86
# define OC_ENC_USE_VTABLE (1)
# endif
# include "../encint.h"
void oc_enc_accel_init_x86(oc_enc_ctx *_enc);
unsigned oc_enc_frag_sad_mmxext(const unsigned char *_src,
const unsigned char *_ref,int _ystride);
unsigned oc_enc_frag_sad_thresh_mmxext(const unsigned char *_src,
const unsigned char *_ref,int _ystride,unsigned _thresh);
unsigned oc_enc_frag_sad2_thresh_mmxext(const unsigned char *_src,
const unsigned char *_ref1,const unsigned char *_ref2,int _ystride,
unsigned _thresh);
unsigned oc_enc_frag_satd_mmxext(unsigned *_dc,const unsigned char *_src,
const unsigned char *_ref,int _ystride);
unsigned oc_enc_frag_satd2_mmxext(unsigned *_dc,const unsigned char *_src,
const unsigned char *_ref1,const unsigned char *_ref2,int _ystride);
unsigned oc_enc_frag_intra_satd_mmxext(unsigned *_dc,
const unsigned char *_src,int _ystride);
void oc_enc_frag_sub_mmx(ogg_int16_t _diff[64],
const unsigned char *_x,const unsigned char *_y,int _stride);
void oc_enc_frag_sub_128_mmx(ogg_int16_t _diff[64],
const unsigned char *_x,int _stride);
void oc_enc_frag_copy2_mmxext(unsigned char *_dst,
const unsigned char *_src1,const unsigned char *_src2,int _ystride);
void oc_enc_fdct8x8_mmxext(ogg_int16_t _y[64],const ogg_int16_t _x[64]);
void oc_enc_fdct8x8_x86_64sse2(ogg_int16_t _y[64],const ogg_int16_t _x[64]);
#endif
| {
"pile_set_name": "Github"
} |
---
home: true
# heroImage: /code.jpg
actionText: 开始 →
actionLink: /components/agree
footer: MIT Licensed | Copyright © 2018 独孤求败
---
### 快速使用
``` bash
# 安装
npm i -S mp-weui
# 在 App.vue 中全局引入 css 文件
import 'mp-weui/lib/style.css'
# 由于 mpvue component 暂不支持全局注册,暂时只能使用局部注册
import MpRadio from 'mp-weui/packages/radio'
export default {
components: {
MpRadio
}
}
```
<!-- ### 示例
<img
style="display:block;width:100%;max-width:430px;margin:0 auto 60px;"
src="/mp-weui/code.jpg"
alt="小程序码"
/> -->
| {
"pile_set_name": "Github"
} |
import numpy as np
from tqdm import tqdm
from data.reader import DataReader
from planner.planner import Planner
from scorer.scorer import Scorer
from utils.graph import Graph
class NaivePlanner(Planner):
is_parallel = True
re_plan = "PREMADE"
def __init__(self, scorer: Scorer):
self.scorer = scorer
def learn(self, train_reader: DataReader, dev_reader: DataReader):
for i in range(5):
self.scorer.learn(train_reader, dev_reader)
if not self.scorer.is_trainable:
break
return self
def score(self, g: Graph, plan: str):
return self.scorer.score(plan)
def plan_best(self, g: Graph, ranker_plans=None):
if ranker_plans:
all_plans = list(set(ranker_plans))
else:
all_plans = list(self.plan_all(g))
plan_scores = [(p, self.scorer.score(p)) for p in tqdm(all_plans)]
plan_scores = sorted(plan_scores, key=lambda a: a[1], reverse=True)
best_50_plans = [p for p, s in plan_scores[:50]]
return best_50_plans
| {
"pile_set_name": "Github"
} |
class AddReplyToIdToReplies < ActiveRecord::Migration
def change
add_column :homeland_replies, :reply_to_id, :integer
add_index :homeland_replies, :reply_to_id
end
end
| {
"pile_set_name": "Github"
} |
# SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved.
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Author:
# Alberto Solino (@agsolino)
#
# Description:
# DPAPI and Windows Vault parsing structures and manipulation
#
# References: All of the work done by these guys. I just adapted their work to my needs.
# https://www.passcape.com/index.php?section=docsys&cmd=details&id=28
# https://github.com/jordanbtucker/dpapick
# https://github.com/gentilkiwi/mimikatz/wiki/howto-~-credential-manager-saved-credentials (and everything else Ben did )
# http://blog.digital-forensics.it/2016/01/windows-revaulting.html
# https://www.passcape.com/windows_password_recovery_vault_explorer
# https://www.passcape.com/windows_password_recovery_dpapi_master_key
#
from __future__ import division
from __future__ import print_function
import sys
from struct import unpack
from datetime import datetime
from binascii import unhexlify, hexlify
from struct import pack
from Cryptodome.Hash import HMAC, SHA512, SHA1
from Cryptodome.Cipher import AES, DES3
from Cryptodome.Util.Padding import unpad
from Cryptodome.PublicKey import RSA
from Cryptodome.Util.number import bytes_to_long
from six import PY3
from impacket.ese import getUnixTime
from impacket.structure import Structure, hexdump
from impacket.uuid import bin_to_string
from impacket.dcerpc.v5.enum import Enum
from impacket.dcerpc.v5.dtypes import RPC_SID
# Algorithm classes
ALG_CLASS_ANY = (0)
ALG_CLASS_SIGNATURE = (1 << 13)
ALG_CLASS_MSG_ENCRYPT = (2 << 13)
ALG_CLASS_DATA_ENCRYPT = (3 << 13)
ALG_CLASS_HASH = (4 << 13)
ALG_CLASS_KEY_EXCHANGE = (5 << 13)
ALG_CLASS_ALL = (7 << 13)
# Algorithm types
ALG_TYPE_ANY = (0)
ALG_TYPE_DSS = (1 << 9)
ALG_TYPE_RSA = (2 << 9)
ALG_TYPE_BLOCK = (3 << 9)
ALG_TYPE_STREAM = (4 << 9)
ALG_TYPE_DH = (5 << 9)
ALG_TYPE_SECURECHANNEL = (6 << 9)
ALG_SID_ANY = (0)
ALG_SID_RSA_ANY = 0
ALG_SID_RSA_PKCS = 1
ALG_SID_RSA_MSATWORK = 2
ALG_SID_RSA_ENTRUST = 3
ALG_SID_RSA_PGP = 4
ALG_SID_DSS_ANY = 0
ALG_SID_DSS_PKCS = 1
ALG_SID_DSS_DMS = 2
ALG_SID_ECDSA = 3
# Block cipher sub ids
ALG_SID_DES = 1
ALG_SID_3DES = 3
ALG_SID_DESX = 4
ALG_SID_IDEA = 5
ALG_SID_CAST = 6
ALG_SID_SAFERSK64 = 7
ALG_SID_SAFERSK128 = 8
ALG_SID_3DES_112 = 9
ALG_SID_CYLINK_MEK = 12
ALG_SID_RC5 = 13
ALG_SID_AES_128 = 14
ALG_SID_AES_192 = 15
ALG_SID_AES_256 = 16
ALG_SID_AES = 17
ALG_SID_SKIPJACK = 10
ALG_SID_TEK = 11
CRYPT_MODE_CBCI = 6 # ANSI CBC Interleaved
CRYPT_MODE_CFBP = 7 # ANSI CFB Pipelined
CRYPT_MODE_OFBP = 8 # ANSI OFB Pipelined
CRYPT_MODE_CBCOFM = 9 # ANSI CBC + OF Masking
CRYPT_MODE_CBCOFMI = 10 # ANSI CBC + OFM Interleaved
ALG_SID_RC2 = 2
ALG_SID_RC4 = 1
ALG_SID_SEAL = 2
# Diffie - Hellman sub - ids
ALG_SID_DH_SANDF = 1
ALG_SID_DH_EPHEM = 2
ALG_SID_AGREED_KEY_ANY = 3
ALG_SID_KEA = 4
ALG_SID_ECDH = 5
# Hash sub ids
ALG_SID_MD2 = 1
ALG_SID_MD4 = 2
ALG_SID_MD5 = 3
ALG_SID_SHA = 4
ALG_SID_SHA1 = 4
ALG_SID_MAC = 5
ALG_SID_RIPEMD = 6
ALG_SID_RIPEMD160 = 7
ALG_SID_SSL3SHAMD5 = 8
ALG_SID_HMAC = 9
ALG_SID_TLS1PRF = 10
ALG_SID_HASH_REPLACE_OWF = 11
ALG_SID_SHA_256 = 12
ALG_SID_SHA_384 = 13
ALG_SID_SHA_512 = 14
# secure channel sub ids
ALG_SID_SSL3_MASTER = 1
ALG_SID_SCHANNEL_MASTER_HASH = 2
ALG_SID_SCHANNEL_MAC_KEY = 3
ALG_SID_PCT1_MASTER = 4
ALG_SID_SSL2_MASTER = 5
ALG_SID_TLS1_MASTER = 6
ALG_SID_SCHANNEL_ENC_KEY = 7
ALG_SID_ECMQV = 1
def getFlags(myenum, flags):
return '|'.join([name for name, member in myenum.__members__.items() if member.value & flags])
class FLAGS(Enum):
CRYPTPROTECT_UI_FORBIDDEN = 0x1
CRYPTPROTECT_LOCAL_MACHINE = 0x4
CRYPTPROTECT_CRED_SYNC = 0x8
CRYPTPROTECT_AUDIT = 0x10
CRYPTPROTECT_VERIFY_PROTECTION = 0x40
CRYPTPROTECT_CRED_REGENERATE = 0x80
CRYPTPROTECT_SYSTEM = 0x20000000
# algorithm identifier definitions
class ALGORITHMS(Enum):
CALG_MD2 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD2)
CALG_MD4 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD4)
CALG_MD5 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD5)
CALG_SHA = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA)
CALG_SHA1 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA1)
CALG_RSA_SIGN = (ALG_CLASS_SIGNATURE | ALG_TYPE_RSA | ALG_SID_RSA_ANY)
CALG_DSS_SIGN = (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_DSS_ANY)
CALG_NO_SIGN = (ALG_CLASS_SIGNATURE | ALG_TYPE_ANY | ALG_SID_ANY)
CALG_RSA_KEYX = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_RSA|ALG_SID_RSA_ANY)
CALG_DES = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_DES)
CALG_3DES_112 = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_3DES_112)
CALG_3DES = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_3DES)
CALG_DESX = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_DESX)
CALG_RC2 = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_RC2)
CALG_RC4 = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_STREAM|ALG_SID_RC4)
CALG_SEAL = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_STREAM|ALG_SID_SEAL)
CALG_DH_SF = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_DH_SANDF)
CALG_DH_EPHEM = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_DH_EPHEM)
CALG_AGREEDKEY_ANY = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_AGREED_KEY_ANY)
CALG_KEA_KEYX = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_KEA)
CALG_HUGHES_MD5 = (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_ANY|ALG_SID_MD5)
CALG_SKIPJACK = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_SKIPJACK)
CALG_TEK = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_TEK)
CALG_SSL3_SHAMD5 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5)
CALG_SSL3_MASTER = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SSL3_MASTER)
CALG_SCHANNEL_MASTER_HASH = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SCHANNEL_MASTER_HASH)
CALG_SCHANNEL_MAC_KEY = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SCHANNEL_MAC_KEY)
CALG_SCHANNEL_ENC_KEY = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SCHANNEL_ENC_KEY)
CALG_PCT1_MASTER = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_PCT1_MASTER)
CALG_SSL2_MASTER = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SSL2_MASTER)
CALG_TLS1_MASTER = (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_TLS1_MASTER)
CALG_RC5 = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_RC5)
CALG_HMAC = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HMAC)
CALG_TLS1PRF = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_TLS1PRF)
CALG_HASH_REPLACE_OWF = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HASH_REPLACE_OWF)
CALG_AES_128 = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_128)
CALG_AES_192 = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_192)
CALG_AES_256 = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_256)
CALG_AES = (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES)
CALG_SHA_256 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
CALG_SHA_384 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
CALG_SHA_512 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
CALG_ECDH = (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_ECDH)
CALG_ECMQV = (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ANY | ALG_SID_ECMQV)
CALG_ECDSA = (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_ECDSA)
class CREDENTIAL_FLAGS(Enum):
CRED_FLAGS_PASSWORD_FOR_CERT = 0x1
CRED_FLAGS_PROMPT_NOW = 0x2
CRED_FLAGS_USERNAME_TARGET = 0x4
CRED_FLAGS_OWF_CRED_BLOB = 0x8
CRED_FLAGS_REQUIRE_CONFIRMATION = 0x10
CRED_FLAGS_WILDCARD_MATCH = 0x20
CRED_FLAGS_VSM_PROTECTED = 0x40
CRED_FLAGS_NGC_CERT = 0x80
class CREDENTIAL_TYPE(Enum):
CRED_TYPE_GENERIC = 0x1
CRED_TYPE_DOMAIN_PASSWORD = 0x2
CRED_TYPE_DOMAIN_CERTIFICATE = 0x3
CRED_TYPE_DOMAIN_VISIBLE_PASSWORD = 0x4
CRED_TYPE_GENERIC_CERTIFICATE = 0x5
CRED_TYPE_DOMAIN_EXTENDED = 0x6
CRED_TYPE_MAXIMUM = 0x7
CRED_TYPE_MAXIMUM_EX = 0x8
class CREDENTIAL_PERSIST(Enum):
CRED_PERSIST_NONE = 0x0
CRED_PERSIST_SESSION = 0x1
CRED_PERSIST_LOCAL_MACHINE = 0x2
CRED_PERSIST_ENTERPRISE = 0x3
ALGORITHMS_DATA = {
# Algorithm: key/SaltLen, CryptHashModule, Mode, IVLen, BlockSize
ALGORITHMS.CALG_SHA.value: (160//8, SHA1, None, None, 512//8),
ALGORITHMS.CALG_HMAC.value: (160//8, SHA512, None, None, 512//8),
ALGORITHMS.CALG_3DES.value: (192//8, DES3, DES3.MODE_CBC, 64//8),
ALGORITHMS.CALG_SHA_512.value: (128//8, SHA512, None, None, 1024//8),
ALGORITHMS.CALG_AES_256.value: (256//8, AES, AES.MODE_CBC, 128//8),
}
class MasterKeyFile(Structure):
structure = (
('Version', '<L=0'),
('unk1', '<L=0'),
('unk2', '<L=0'),
('Guid', "72s=b''"),
('Unkown', '<L=0'),
('Policy', '<L=0'),
('Flags', '<L=0'),
('MasterKeyLen', '<Q=0'),
('BackupKeyLen', '<Q=0'),
('CredHistLen', '<Q=0'),
('DomainKeyLen', '<Q=0'),
)
def dump(self):
print("[MASTERKEYFILE]")
print("Version : %8x (%d)" % (self['Version'], self['Version']))
print("Guid : %s" % self['Guid'].decode('utf-16le'))
print("Flags : %8x (%d)" % (self['Flags'], self['Flags']))
print("Policy : %8x (%d)" % (self['Policy'], self['Policy']))
print("MasterKeyLen: %.8x (%d)" % (self['MasterKeyLen'], self['MasterKeyLen']))
print("BackupKeyLen: %.8x (%d)" % (self['BackupKeyLen'], self['BackupKeyLen']))
print("CredHistLen : %.8x (%d)" % (self['CredHistLen'], self['CredHistLen']))
print("DomainKeyLen: %.8x (%d)" % (self['DomainKeyLen'], self['DomainKeyLen']))
print()
class MasterKey(Structure):
structure = (
('Version', '<L=0'),
('Salt', '16s=b""'),
('MasterKeyIterationCount', '<L=0'),
('HashAlgo', "<L=0"),
('CryptAlgo', '<L=0'),
('data', ':'),
)
def __init__(self, data = None, alignment = 0):
Structure.__init__(self, data, alignment)
self.decryptedKey = None
def dump(self):
print("[MASTERKEY]")
print("Version : %8x (%d)" % (self['Version'], self['Version']))
print("Salt : %s" % hexlify(self['Salt']))
print("Rounds : %8x (%d)" % (self['MasterKeyIterationCount'], self['MasterKeyIterationCount']))
print("HashAlgo : %.8x (%d) (%s)" % (self['HashAlgo'], self['HashAlgo'], ALGORITHMS(self['HashAlgo']).name))
print("CryptAlgo : %.8x (%d) (%s)" % (self['CryptAlgo'], self['CryptAlgo'], ALGORITHMS(self['CryptAlgo']).name))
print("data : %s" % (hexlify(self['data'])))
print()
def deriveKey(self, passphrase, salt, keylen, count, hashFunction):
keyMaterial = b""
i = 1
while len(keyMaterial) < keylen:
U = salt + pack("!L", i)
i += 1
derived = bytearray(hashFunction(passphrase, U))
for r in range(count - 1):
actual = bytearray(hashFunction(passphrase, derived))
if PY3:
derived = (int.from_bytes(derived, sys.byteorder) ^ int.from_bytes(actual, sys.byteorder)).to_bytes(len(actual), sys.byteorder)
else:
derived = bytearray([ chr((a) ^ (b)) for (a,b) in zip(derived, actual) ])
keyMaterial += derived
return keyMaterial[:keylen]
def decrypt(self, key):
if self['HashAlgo'] == ALGORITHMS.CALG_HMAC.value:
hashModule = SHA1
else:
hashModule = ALGORITHMS_DATA[self['HashAlgo']][1]
prf = lambda p, s: HMAC.new(p, s, hashModule).digest()
derivedBlob = self.deriveKey(key, self['Salt'],
ALGORITHMS_DATA[self['CryptAlgo']][0] + ALGORITHMS_DATA[self['CryptAlgo']][3],
count=self['MasterKeyIterationCount'], hashFunction=prf)
cryptKey = derivedBlob[:ALGORITHMS_DATA[self['CryptAlgo']][0]]
iv = derivedBlob[ALGORITHMS_DATA[self['CryptAlgo']][0]:][:ALGORITHMS_DATA[self['CryptAlgo']][3]]
cipher = ALGORITHMS_DATA[self['CryptAlgo']][1].new(cryptKey, mode = ALGORITHMS_DATA[self['CryptAlgo']][2], iv = iv)
cleartext = cipher.decrypt(self['data'])
decryptedKey = cleartext[-64:]
hmacSalt = cleartext[:16]
hmac = cleartext[16:][:ALGORITHMS_DATA[self['HashAlgo']][0]]
hmacKey = HMAC.new(key, hmacSalt, hashModule).digest()
hmacCalculated = HMAC.new(hmacKey, decryptedKey, hashModule ).digest()
if hmacCalculated[:ALGORITHMS_DATA[self['HashAlgo']][0]] == hmac:
self.decryptedKey = decryptedKey
return decryptedKey
else:
return None
class CredHist(Structure):
structure = (
('Version', '<L=0'),
('Guid', "16s=b''"),
)
def dump(self):
print("[CREDHIST]")
print("Version : %8x (%d)" % (self['Version'], self['Version']))
print("Guid : %s" % bin_to_string(self['Guid']))
print()
class DomainKey(Structure):
structure = (
('Version', '<L=0'),
('SecretLen', '<L=0'),
('AccessCheckLen', '<L=0'),
('Guid', "16s=b"""),
('_SecretData', '_-SecretData', 'self["SecretLen"]'),
('SecretData', ':'),
('_AccessCheck', '_-AccessCheck', 'self["AccessCheckLen"]'),
('AccessCheck', ':'),
)
def dump(self):
print("[DOMAINKEY]")
print("Version : %8x (%d)" % (self['Version'], self['Version']))
print("Guid : %s" % bin_to_string(self['Guid']))
print("SecretLen : %8x (%d)" % (self['SecretLen'], self['SecretLen']))
print("AccessCheckLen: %.8x (%d)" % (self['AccessCheckLen'], self['AccessCheckLen']))
print("SecretData : %s" % (hexlify(self['SecretData'])))
print("AccessCheck : %s" % (hexlify(self['AccessCheck'])))
print()
class DPAPI_SYSTEM(Structure):
structure = (
('Version', '<L=0'),
('MachineKey', '20s=b""'),
('UserKey', '20s=b""'),
)
def dump(self):
print("[DPAPI_SYSTEM]")
print("Version : %8x (%d)" % (self['Version'], self['Version']))
print("MachineKey : 0x%s" % hexlify(self['MachineKey']).decode('latin-1'))
print("UserKey : 0x%s" % hexlify(self['UserKey']).decode('latin-1'))
print()
class CredentialFile(Structure):
structure = (
('Version', '<L=0'),
('Size', '<L=0'),
('Unknown', '<L=0'),
('_Data', '_-Data', 'self["Size"]'),
('Data', ':'),
)
#def dump(self):
# print("[CREDENTIAL FILE]")
# print("Version : %8x (%d)" % (self['Version'], self['Version']))
# print("MachineKey : %s" % hexlify(self['MachineKey']))
# print("UserKey : %s" % hexlify(self['UserKey']))
# print("CryptAlgo : %.8x (%d) (%s)" % (self['CryptAlgo'], self['CryptAlgo'], ALGORITHMS(self['CryptAlgo']).name))
# print()
class DPAPI_BLOB(Structure):
structure = (
('Version', '<L=0'),
('GuidCredential', "16s=b"""),
('MasterKeyVersion', '<L=0'),
('GuidMasterKey', "16s=b"""),
('Flags', '<L=0'),
('DescriptionLen', '<L=0'),
('_Description', '_-Description', 'self["DescriptionLen"]'),
('Description', ':'),
('CryptAlgo', '<L=0'),
('CryptAlgoLen', '<L=0'),
('SaltLen', '<L=0'),
('_Salt', '_-Salt', 'self["SaltLen"]'),
('Salt', ':'),
('HMacKeyLen', '<L=0'),
('_HMacKey', '_-HMacKey', 'self["HMacKeyLen"]'),
('HMacKey', ':'),
('HashAlgo', '<L=0'),
('HashAlgoLen', '<L=0'),
('HMac', '<L=0'),
('_HMac', '_-HMac', 'self["HMac"]'),
('HMac', ':'),
('DataLen', '<L=0'),
('_Data', '_-Data', 'self["DataLen"]'),
('Data', ':'),
('SignLen', '<L=0'),
('_Sign', '_-Sign', 'self["SignLen"]'),
('Sign', ':'),
)
def dump(self):
print("[BLOB]")
print("Version : %8x (%d)" % (self['Version'], self['Version']))
print("Guid Credential : %s" % bin_to_string(self['GuidCredential']))
print("MasterKeyVersion : %8x (%d)" % (self['MasterKeyVersion'], self['MasterKeyVersion']))
print("Guid MasterKey : %s" % bin_to_string(self['GuidMasterKey']))
print("Flags : %8x (%s)" % (self['Flags'], getFlags(FLAGS, self['Flags'])))
print("Description : %s" % (self['Description'].decode('utf-16le')))
print("CryptAlgo : %.8x (%d) (%s)" % (self['CryptAlgo'], self['CryptAlgo'], ALGORITHMS(self['CryptAlgo']).name))
print("Salt : %s" % (hexlify(self['Salt'])))
print("HMacKey : %s" % (hexlify(self['HMacKey'])))
print("HashAlgo : %.8x (%d) (%s)" % (self['HashAlgo'], self['HashAlgo'], ALGORITHMS(self['HashAlgo']).name))
print("HMac : %s" % (hexlify(self['HMac'])))
print("Data : %s" % (hexlify(self['Data'])))
print("Sign : %s" % (hexlify(self['Sign'])))
print()
def deriveKey(self, sessionKey):
def fixparity(deskey):
from six import indexbytes, b
temp = b''
for i in range(len(deskey)):
t = (bin(indexbytes(deskey,i))[2:]).rjust(8,'0')
if t[:7].count('1') %2 == 0:
temp+= b(chr(int(t[:7]+'1',2)))
else:
temp+= b(chr(int(t[:7]+'0',2)))
return temp
if len(sessionKey) > ALGORITHMS_DATA[self['HashAlgo']][4]:
derivedKey = HMAC.new(sessionKey, digestmod = ALGORITHMS_DATA[self['HashAlgo']][1]).digest()
else:
derivedKey = sessionKey
if len(derivedKey) < ALGORITHMS_DATA[self['CryptAlgo']][0]:
# Extend the key
derivedKey += b'\x00'*ALGORITHMS_DATA[self['HashAlgo']][4]
ipad = bytearray([ i ^ 0x36 for i in bytearray(derivedKey)][:ALGORITHMS_DATA[self['HashAlgo']][4]])
opad = bytearray([ i ^ 0x5c for i in bytearray(derivedKey)][:ALGORITHMS_DATA[self['HashAlgo']][4]])
derivedKey = ALGORITHMS_DATA[self['HashAlgo']][1].new(ipad).digest() + \
ALGORITHMS_DATA[self['HashAlgo']][1].new(opad).digest()
derivedKey = fixparity(derivedKey)
return derivedKey
def decrypt(self, key, entropy = None):
keyHash = SHA1.new(key).digest()
sessionKey = HMAC.new(keyHash, self['Salt'], ALGORITHMS_DATA[self['HashAlgo']][1])
if entropy is not None:
sessionKey.update(entropy)
sessionKey = sessionKey.digest()
# Derive the key
derivedKey = self.deriveKey(sessionKey)
cipher = ALGORITHMS_DATA[self['CryptAlgo']][1].new(derivedKey[:ALGORITHMS_DATA[self['CryptAlgo']][0]],
mode=ALGORITHMS_DATA[self['CryptAlgo']][2], iv=b'\x00'*ALGORITHMS_DATA[self['CryptAlgo']][3])
cleartext = unpad(cipher.decrypt(self['Data']), ALGORITHMS_DATA[self['CryptAlgo']][1].block_size)
# Now check the signature
# ToDo Fix this, it's just ugly, more testing so we can remove one
toSign = (self.rawData[20:][:len(self.rawData)-20-len(self['Sign'])-4])
# Calculate the different HMACKeys
keyHash2 = keyHash + b"\x00"*ALGORITHMS_DATA[self['HashAlgo']][1].block_size
ipad = bytearray([i ^ 0x36 for i in bytearray(keyHash2)][:ALGORITHMS_DATA[self['HashAlgo']][1].block_size])
opad = bytearray([i ^ 0x5c for i in bytearray(keyHash2)][:ALGORITHMS_DATA[self['HashAlgo']][1].block_size])
a = ALGORITHMS_DATA[self['HashAlgo']][1].new(ipad)
a.update(self['HMac'])
hmacCalculated1 = ALGORITHMS_DATA[self['HashAlgo']][1].new(opad)
hmacCalculated1.update(a.digest())
if entropy is not None:
hmacCalculated1.update(entropy)
hmacCalculated1.update(toSign)
hmacCalculated3 = HMAC.new(keyHash, self['HMac'], ALGORITHMS_DATA[self['HashAlgo']][1])
if entropy is not None:
hmacCalculated3.update(entropy)
hmacCalculated3.update(toSign)
if hmacCalculated1.digest() == self['Sign'] or hmacCalculated3.digest() == self['Sign']:
return cleartext
else:
return None
class VAULT_ATTRIBUTE(Structure):
structure = (
('Id', '<L=0'),
('Unknown1', '<L=0'),
('Unknown2', '<L=0'),
('Unknown3', '<L=0'),
)
padding = (
('Pad', '6s=b""'),
)
id100 = (
('Unknown5', '<L=0'),
)
extended = (
('Size','<L=0'),
('IVPresent', '<B=?&IVSize'),
('IVSize', '<L=0'),
('_IV', '_-IV', 'self["IVSize"] if self["IVSize"] is not None else 0'),
('IV', ':'),
('_Data','_-Data', 'self["Size"]-self["IVSize"]-5 if self["IVPresent"] else self["Size"]-1'),
('Data',':'),
)
def __init__(self, data = None, alignment = 0):
if len(data) > 20:
if data[16:][:6] == b'\x00'*6:
self.structure += self.padding
if unpack('<L',data[:4])[0] >= 100:
self.structure += self.id100
if len(data[16:]) >= 9:
self.structure += self.extended
Structure.__init__(self, data, alignment)
def dump(self):
print("[ATTRIBUTE %d]" % self['Id'])
if len(self.rawData) > 28:
print("Size : 0x%x" % self['Size'])
if self['IVPresent'] > 0:
print("IVSize : 0x%x" % self['IVSize'])
print("IV : %s" % hexlify(self['IV']))
print("Data : %s" % hexlify(self['Data']))
class VAULT_ATTRIBUTE_MAP_ENTRY(Structure):
structure = (
('Id', '<L=0'),
('Offset', '<L=0'),
('Unknown1', '<L=0'),
)
def dump(self):
print("[MAP ENTRY %d @ 0x%.8x]" % (self['Id'], self['Offset']))
class VAULT_VCRD(Structure):
structure = (
('SchemaGuid', "16s=b"""),
('Unknown0', '<L=0'),
('LastWritten', '<Q=0'),
('Unknown1', '<L=0'),
('Unknown2', '<L=0'),
('FriendlyNameLen', '<L=0'),
('FriendlyNameL', '_-FriendlyName', 'self["FriendlyNameLen"]'),
('FriendlyName', ':'),
('AttributesMapsSize', '<L=0'),
('AttributeL', '_-AttributeMaps', 'self["AttributesMapsSize"]'),
('AttributeMaps', ':'),
('Data', ':'),
)
def __init__(self, data = None, alignment = 0):
Structure.__init__(self, data, alignment)
if data is not None:
# Process the MAP entries
self.mapEntries = list()
data = self['AttributeMaps']
for i in range(self['AttributesMapsSize']//len(VAULT_ATTRIBUTE_MAP_ENTRY())):
entry = VAULT_ATTRIBUTE_MAP_ENTRY(data)
self.mapEntries.append(entry)
data = data[len(VAULT_ATTRIBUTE_MAP_ENTRY()):]
self.attributesLen = list()
for i in range(len(self.mapEntries)):
if i > 0:
self.attributesLen.append(self.mapEntries[i]['Offset']-self.mapEntries[i-1]['Offset'])
self.attributesLen.append(len(self.rawData) - self.mapEntries[i]['Offset'] )
self.attributes = list()
for i, entry in enumerate(self.mapEntries):
attribute = VAULT_ATTRIBUTE(self.rawData[entry['Offset']:][:self.attributesLen[i]])
self.attributes.append(attribute)
# Do we have remaining data?
self['Data'] = self.rawData[self.mapEntries[-1]['Offset']+len(self.attributes[-1].getData()):]
def dump(self):
print("[VCRD]")
print("SchemaGuid : %s" % bin_to_string(self['SchemaGuid']))
print("LastWritten : %s" % (datetime.utcfromtimestamp(getUnixTime(self['LastWritten']))))
print("FriendlyName: %s" % (self['FriendlyName'].decode('utf-16le')))
print()
for i,entry in enumerate(self.mapEntries):
entry.dump()
self.attributes[i].dump()
print()
print("Remaining : %s" % (hexlify(self['Data'])))
print()
class VAULT_VPOL(Structure):
structure = (
('Version', '<L=0'),
('Guid', "16s=b"""),
('DescriptionLen', '<L=0'),
('_Description', '_-Description', 'self["DescriptionLen"]'),
('Description', ':'),
('Unknown', '12s=b""'),
('Size', '<L=0'),
('Guid2', "16s=b"""),
('Guid3', "16s=b"""),
('KeySize','<L=0'),
('_Blob', '_-Blob', 'self["KeySize"]'),
('Blob', ':', DPAPI_BLOB),
)
def dump(self):
print("[VAULT_VPOL]")
print("Version : %8x (%d)" % (self['Version'], self['Version']))
print("Guid : %s" % bin_to_string(self['Guid']))
print("Description : %s" % (self['Description'].decode('utf-16le')))
print("Size : 0x%.8x (%d)" % (self['Size'], self['Size']))
print("Guid2 : %s" % bin_to_string(self['Guid2']))
print("Guid3 : %s" % bin_to_string(self['Guid3']))
print("KeySize : 0x%.8x (%d)" % (self['KeySize'], self['KeySize']))
self['Blob'].dump()
print()
# from bcrypt.h
class BCRYPT_KEY_DATA_BLOB_HEADER(Structure):
structure = (
('dwMagic','<L=0'),
('dwVersion','<L=0'),
('cbKeyData','<L=0'),
('_bKey','_-bKey', 'self["cbKeyData"]'),
('bKey',':'),
)
# from https://media.defcon.org/DEF%20CON%2024/DEF%20CON%2024%20presentations/DEFCON-24-Jkambic-Cunning-With-Cng-Soliciting-Secrets-From-Schannel-WP.pdf
class BCRYPT_KSSM_DATA_BLOB_HEADER(Structure):
structure = (
('cbLength','<L=0'),
('dwKeyMagic','<L=0'),
('dwUnknown2','<L=0'),
('dwUnknown3','<L=0'),
('dwKeyBitLen','<L=0'),
('cbKeyLength','<L=0'),
#('_bKey','_-bKey', 'self["cbKeyData"]'),
#('AesKey','32s=""'),
#('dwUnknown4','<L=0'),
#('KeySchedule','448s=""'),
#('dwUnknown5','<L=0'),
#('cbScheduleLen','<L=0'),
#('Unknown6','16s=""'),
)
class BCRYPT_KEY_WRAP(Structure):
structureKDBM = (
('Size','<L=0'),
('Version','<L=0'),
('Unknown2','<L=0'),
('_bKeyBlob','_-bKeyBlob', 'self["Size"]'),
('bKeyBlob',':', BCRYPT_KEY_DATA_BLOB_HEADER),
)
structureKSSM = (
('Size','<L=0'),
('Version','<L=0'),
('Unknown2','<L=0'),
('_bKeyBlob','_-bKeyBlob', 'self["Size"]-8'),
('bKeyBlob',':'),
)
def __init__(self, data = None, alignment = 0):
if len(data) >=16:
if data[0:1] == b'\x24' or data[0:1] == b'\x34':
self.structure = self.structureKDBM
else:
self.structure = self.structureKSSM
Structure.__init__(self, data, alignment)
class VAULT_VPOL_KEYS(Structure):
structure = (
('Key1',':', BCRYPT_KEY_WRAP),
('Key2',':', BCRYPT_KEY_WRAP),
)
def dump(self):
print("[VAULT_VPOL_KEYS]")
if self['Key1']['Size'] > 0x24:
print('Key1:')
hexdump(self['Key1']['bKeyBlob'])
print('Key2:')
hexdump(self['Key2']['bKeyBlob'])
else:
print('Key1: 0x%s' % hexlify(self['Key1']['bKeyBlob']['bKey']).decode('latin-1'))
print('Key2: 0x%s' % hexlify(self['Key2']['bKeyBlob']['bKey']).decode('latin-1'))
print()
class VAULT_INTERNET_EXPLORER(Structure):
structure = (
('Version','<L=0'),
('Count','<L=0'),
('Unknown','<L=0'),
('Id1', '<L=0'),
('UsernameLen', '<L=0'),
('_Username', '_-Username','self["UsernameLen"]'),
('Username', ':'),
('Id2', '<L=0'),
('ResourceLen', '<L=0'),
('_Resource', '_-Resource', 'self["ResourceLen"]'),
('Resource', ':'),
('Id3', '<L=0'),
('PasswordLen', '<L=0'),
('_Password', '_-Password', 'self["PasswordLen"]'),
('Password', ':'),
)
def fromString(self, data):
Structure.fromString(self, data)
def dump(self):
print("[Internet Explorer]")
print('Username : %s' % self['Username'].decode('utf-16le'))
print('Resource : %s' % self['Resource'].decode('utf-16le'))
print('Password : %s' % (hexlify(self['Password'])))
print()
class VAULT_WIN_BIO_KEY(Structure):
structure = (
('Version','<L=0'),
('Count','<L=0'),
('Unknown','<L=0'),
('Id1', '<L=0'),
('SidLen', '<L=0'),
('_Sid', '_-Sid','self["SidLen"]'),
('Sid', ':'),
('Id2', '<L=0'),
('NameLen', '<L=0'),
('_Name', '_-Name', 'self["NameLen"]'),
('Name', ':'),
('Id3', '<L=0'),
('BioKeyLen', '<L=0'),
('_BioKey', '_-BioKey', 'self["BioKeyLen"]'),
('BioKey', ':'),
)
def fromString(self, data):
Structure.fromString(self, data)
if data is not None:
bioKey = BCRYPT_KEY_DATA_BLOB_HEADER(unhexlify(self['BioKey'].decode('utf-16le')[:-1]))
self['BioKey'] = bioKey
def dump(self):
print("[WINDOWS BIOMETRIC KEY]")
print('Sid : %s' % RPC_SID(b'\x05\x00\x00\x00'+self['Sid']).formatCanonical())
print('Friendly Name: %s' % self['Name'].decode('utf-16le'))
print('Biometric Key: 0x%s' % (hexlify(self['BioKey']['bKey'])).decode('latin-1'))
print()
class NGC_LOCAL_ACCOOUNT(Structure):
structure = (
('Version','<L=0'),
('UnlockKeySize','<L=0'),
('IVSize','<L=0'),
('CipherTextSize','<L=0'),
('MustBeZeroTest','<L=0'),
('_UnlockKey', '_-UnlockKey', 'self["UnlockKeySize"]'),
('UnlockKey', ':'),
('_IV', '_-IV', 'self["IVSize"]'),
('IV', ':'),
('_CipherText', '_-CipherText', 'self["CipherTextSize"]'),
('CipherText', ':'),
)
# def __init__(self, data=None, alignment = 0):
# hexdump(data)
def dump(self):
print("[NGC LOCAL ACCOOUNT]")
print('UnlockKey : %s' % hexlify(self["UnlockKey"]))
print('IV : %s' % hexlify(self["IV"]))
print('CipherText : %s' % hexlify(self["CipherText"]))
class VAULT_NGC_ACCOOUNT(Structure):
structure = (
('Version','<L=0'),
('Count','<L=0'),
('Unknown','<L=0'),
('Id1', '<L=0'),
('SidLen', '<L=0'),
('_Sid', '_-Sid','self["SidLen"]'),
('Sid', ':'),
('Id2', '<L=0'),
('NameLen', '<L=0'),
('_Name', '_-Name', 'self["NameLen"]'),
('Name', ':'),
('Id3', '<L=0'),
('BlobLen', '<L=0'),
('Blob', '_-Blob', 'self["BlobLen"]'),
('Blob', ':', NGC_LOCAL_ACCOOUNT),
)
def dump(self):
print("[NGC VAULT]")
print('Sid : %s' % RPC_SID(b'\x05\x00\x00\x00'+self['Sid']).formatCanonical())
print('Friendly Name: %s' % self['Name'].decode('utf-16le'))
self['Blob'].dump()
print()
VAULT_KNOWN_SCHEMAS = {
'WinBio Key': VAULT_WIN_BIO_KEY,
'NGC Local Accoount Logon Vault Credential': VAULT_NGC_ACCOOUNT,
'Internet Explorer': VAULT_INTERNET_EXPLORER,
}
class CREDENTIAL_ATTRIBUTE(Structure):
# some info here https://docs.microsoft.com/en-us/windows/desktop/api/wincred/ns-wincred-_credential_attributea
structure = (
('Flags','<L=0'),
('KeyWordSize', '<L=0'),
('_KeyWord', '_-KeyWord', 'self["KeyWordSize"]'),
('KeyWord', ':'),
('DataSize', '<L=0'),
('_Data', '_-Data', 'self["DataSize"]'),
('Data', ':'),
)
def dump(self):
print("KeyWord : %s" % (self['KeyWord'].decode('utf-16le')))
#print("Flags : %8x (%s)" % (self['Flags'], getFlags(CREDENTIAL_FLAGS, self['Flags'])))
print("Data : ")
hexdump(self['Data'])
class CREDENTIAL_BLOB(Structure):
# some info here https://docs.microsoft.com/en-us/windows/desktop/api/wincred/ns-wincred-_credentiala
structure = (
('Flags','<L=0'),
('Size','<L=0'),
('Unknown0','<L=0'),
('Type','<L=0'),
('Flags2','<L=0'),
('LastWritten','<Q=0'),
('Unknown2','<L=0'),
('Persist','<L=0'),
('AttrCount','<L=0'),
('Unknown3','<Q=0'),
('TargetSize','<L=0'),
('_Target','_-Target','self["TargetSize"]'),
('Target',':'),
('TargetAliasSize', '<L=0'),
('_TargetAliast', '_-TargetAlias', 'self["TargetAliasSize"]'),
('TargetAlias', ':'),
('DescriptionSize', '<L=0'),
('_Description', '_-Description', 'self["DescriptionSize"]'),
('Description', ':'),
('UnknownSize', '<L=0'),
('_Unknown', '_-Unknown', 'self["UnknownSize"]'),
('Unknown', ':'),
('UsernameSize', '<L=0'),
('_Username', '_-Username', 'self["UsernameSize"]'),
('Username', ':'),
('Unknown3Size', '<L=0'),
('_Unknown3', '_-Unknown3', 'self["Unknown3Size"]'),
('Unknown3', ':'),
('Remaining', ':'),
)
def __init__(self, data = None, alignment = 0):
Structure.__init__(self, data, alignment)
self.attributes = 0
if data is not None:
# Unpack the attributes
remaining = self['Remaining']
self.attributes = list()
for i in range(self['AttrCount']):
attr = CREDENTIAL_ATTRIBUTE(remaining)
self.attributes.append(attr)
remaining = remaining[len(attr):]
def dump(self):
print("[CREDENTIAL]")
print("LastWritten : %s" % (datetime.utcfromtimestamp(getUnixTime(self['LastWritten']))))
print("Flags : 0x%.8x (%s)" % (self['Flags'], getFlags(CREDENTIAL_FLAGS, self['Flags'])))
print("Persist : 0x%.8x (%s)" % (self['Persist'], CREDENTIAL_PERSIST(self['Persist']).name))
print("Type : 0x%.8x (%s)" % (self['Type'], CREDENTIAL_PERSIST(self['Type']).name))
print("Target : %s" % (self['Target'].decode('utf-16le')))
print("Description : %s" % (self['Description'].decode('utf-16le')))
print("Unknown : %s" % (self['Unknown'].decode('utf-16le')))
print("Username : %s" % (self['Username'].decode('utf-16le')))
try:
print("Unknown : %s" % (self['Unknown3'].decode('utf-16le')))
except UnicodeDecodeError:
print("Unknown : %s" % (self['Unknown3'].decode('latin-1')))
print()
for entry in self.attributes:
entry.dump()
ALG_ID = '<L=0'
class P_BACKUP_KEY(Structure):
structure = (
('Version', '<L=0'),
('Data', ':'),
)
class PREFERRED_BACKUP_KEY(Structure):
structure = (
('Version', '<L=0'),
('KeyLength', '<L=0'),
('CertificateLength', '<L=0'),
('Data', ':'),
)
class PVK_FILE_HDR(Structure):
structure = (
('dwMagic', '<L=0'),
('dwVersion', '<L=0'),
('dwKeySpec', '<L=0'),
('dwEncryptType', '<L=0'),
('cbEncryptData', '<L=0'),
('cbPvk', '<L=0'),
)
class PUBLICKEYSTRUC(Structure):
structure = (
('bType', '<B=0'),
('bVersion', '<B=0'),
('reserved', '<H=0'),
('aiKeyAlg', ALG_ID),
)
class RSAPUBKEY(Structure):
structure = (
('magic', '<L=0'),
('bitlen', '<L=0'),
('pubexp', '<L=0'),
)
class PUBLIC_KEY_BLOB(Structure):
structure = (
('publickeystruc', ':', PUBLICKEYSTRUC),
('rsapubkey', ':', RSAPUBKEY),
('_modulus', '_-modulus', 'self["rsapubkey"]["bitlen"] // 8'),
)
class PRIVATE_KEY_BLOB(Structure):
structure = (
('publickeystruc', ':', PUBLICKEYSTRUC),
('rsapubkey', ':', RSAPUBKEY),
('_modulus', '_-modulus', 'self["rsapubkey"]["bitlen"] // 8'),
('modulus', ':'),
('_prime1', '_-prime1', 'self["rsapubkey"]["bitlen"] // 16'),
('prime1', ':'),
('_prime2', '_-prime2', 'self["rsapubkey"]["bitlen"] // 16'),
('prime2', ':'),
('_exponent1', '_-exponent1', 'self["rsapubkey"]["bitlen"] // 16'),
('exponent1', ':'),
('_exponent2', '_-exponent2', 'self["rsapubkey"]["bitlen"] // 16'),
('exponent2', ':'),
('_coefficient', '_-coefficient', 'self["rsapubkey"]["bitlen"] // 16'),
('coefficient', ':'),
('_privateExponent', '_-privateExponent', 'self["rsapubkey"]["bitlen"] // 8'),
('privateExponent', ':'),
)
class SIMPLE_KEY_BLOB(Structure):
structure = (
('publickeystruc', ':', PUBLICKEYSTRUC),
('algid', ALG_ID),
('encryptedkey', ':'),
)
class DPAPI_DOMAIN_RSA_MASTER_KEY(Structure):
structure = (
('cbMasterKey', '<L=0'),
('cbSuppKey', '<L=0'),
('buffer', ':'),
)
def privatekeyblob_to_pkcs1(key):
'''
parse private key into pkcs#1 format
:param key:
:return:
'''
modulus = bytes_to_long(key['modulus'][::-1]) # n
prime1 = bytes_to_long(key['prime1'][::-1]) # p
prime2 = bytes_to_long(key['prime2'][::-1]) # q
exp1 = bytes_to_long(key['exponent1'][::-1])
exp2 = bytes_to_long(key['exponent2'][::-1])
coefficient = bytes_to_long(key['coefficient'][::-1])
privateExp = bytes_to_long(key['privateExponent'][::-1]) # d
if PY3:
long = int
pubExp = long(key['rsapubkey']['pubexp']) # e
# RSA.Integer(prime2).inverse(prime1) # u
r = RSA.construct((modulus, pubExp, privateExp, prime1, prime2))
return r
| {
"pile_set_name": "Github"
} |
package com.dubture.twig.core.codeassist;
public interface ICompletionProposalFlag {
public static final ICompletionProposalFlag[] NO_FLAGS = {};
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>brooklyn-rest-server</artifactId>
<packaging>jar</packaging>
<name>Brooklyn REST Server</name>
<description>
Brooklyn REST Endpoint
</description>
<parent>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-parent</artifactId>
<version>0.9.0-SNAPSHOT</version><!-- BROOKLYN_VERSION -->
<relativePath>../../parent/pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-rest-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-camp</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.brooklyn.camp</groupId>
<artifactId>camp-base</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-utils-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-software-base</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-utils-rest-swagger</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<exclusions>
<exclusion>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-test-support</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-policy</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-core</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-software-base</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-rest-api</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-locations-jclouds</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey.jersey-test-framework</groupId>
<artifactId>jersey-test-framework-inmemory</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey.jersey-test-framework</groupId>
<artifactId>jersey-test-framework-grizzly2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-rt-osgi</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<!-- Required to set values in build-metadata.properties -->
<filtering>true</filtering>
</resource>
<resource>
<directory>${basedir}/src/main/webapp</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<!-- configure plugin to generate MANIFEST.MF
adapted from http://blog.knowhowlab.org/2010/06/osgi-tutorial-from-project-structure-to.html -->
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
<configuration>
<supportedProjectTypes>
<supportedProjectType>jar</supportedProjectType>
</supportedProjectTypes>
<instructions>
<Import-Package>
com.sun.jersey.spi.container.servlet;version="[1.18.1,2.0)",
*
</Import-Package>
<Export-Package>org.apache.brooklyn.*</Export-Package>
<Web-ContextPath>/</Web-ContextPath>
<_wab>src/main/webapp</_wab>
</instructions>
</configuration>
</plugin>
<!-- if you want to build a WAR, full or skinny:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<executions>
<execution>
<id>make-skinny-war</id>
<phase>install</phase>
<goals>
<goal>war</goal>
</goals>
<configuration>
<classifier>skinny</classifier>
<packagingExcludes>WEB-INF/lib/*.jar,WEB-INF/classes/**/*.class</packagingExcludes>
</configuration>
</execution>
<execution>
<id>make-full-war</id>
<phase>install</phase>
<goals>
<goal>war</goal>
</goals>
<configuration>
<classifier>full</classifier>
</configuration>
</execution>
</executions>
</plugin>
-->
</plugins>
</build>
</project>
| {
"pile_set_name": "Github"
} |
// Package subscriptions implements the Azure ARM Subscriptions service API version 2016-06-01.
//
// All resource groups and resources exist within subscriptions. These operation enable you get information about your
// subscriptions and tenants. A tenant is a dedicated instance of Azure Active Directory (Azure AD) for your
// organization.
package subscriptions
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Subscriptions
DefaultBaseURI = "https://management.azure.com"
)
// BaseClient is the base client for Subscriptions.
type BaseClient struct {
autorest.Client
BaseURI string
}
// New creates an instance of the BaseClient client.
func New() BaseClient {
return NewWithBaseURI(DefaultBaseURI)
}
// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with
// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewWithBaseURI(baseURI string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
}
}
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// Preprocessed version of "boost/mpl/map.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
namespace aux {
template< int N >
struct map_chooser;
}
namespace aux {
template<>
struct map_chooser<0>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef map0<
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<1>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map1<
T0
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<2>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map2<
T0, T1
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<3>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map3<
T0, T1, T2
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<4>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map4<
T0, T1, T2, T3
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<5>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map5<
T0, T1, T2, T3, T4
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<6>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map6<
T0, T1, T2, T3, T4, T5
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<7>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map7<
T0, T1, T2, T3, T4, T5, T6
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<8>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map8<
T0, T1, T2, T3, T4, T5, T6, T7
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<9>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map9<
T0, T1, T2, T3, T4, T5, T6, T7, T8
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<10>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map10<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<11>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map11<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<12>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map12<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<13>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map13<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<14>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map14<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<15>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map15<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<16>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map16<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<17>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map17<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<18>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map18<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<19>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map19<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<20>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map20<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
>::type type;
};
};
} // namespace aux
namespace aux {
template< typename T >
struct is_map_arg
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
template<>
struct is_map_arg<na>
{
BOOST_STATIC_CONSTANT(bool, value = false);
};
template<
typename T1, typename T2, typename T3, typename T4, typename T5
, typename T6, typename T7, typename T8, typename T9, typename T10
, typename T11, typename T12, typename T13, typename T14, typename T15
, typename T16, typename T17, typename T18, typename T19, typename T20
>
struct map_count_args
{
BOOST_STATIC_CONSTANT(int, value =
is_map_arg<T1>::value + is_map_arg<T2>::value
+ is_map_arg<T3>::value + is_map_arg<T4>::value
+ is_map_arg<T5>::value + is_map_arg<T6>::value
+ is_map_arg<T7>::value + is_map_arg<T8>::value
+ is_map_arg<T9>::value + is_map_arg<T10>::value
+ is_map_arg<T11>::value + is_map_arg<T12>::value
+ is_map_arg<T13>::value + is_map_arg<T14>::value
+ is_map_arg<T15>::value + is_map_arg<T16>::value
+ is_map_arg<T17>::value + is_map_arg<T18>::value
+ is_map_arg<T19>::value + is_map_arg<T20>::value
);
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct map_impl
{
typedef aux::map_count_args<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
> arg_num_;
typedef typename aux::map_chooser< arg_num_::value >
::template result_< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19 >::type type;
};
} // namespace aux
template<
typename T0 = na, typename T1 = na, typename T2 = na, typename T3 = na
, typename T4 = na, typename T5 = na, typename T6 = na, typename T7 = na
, typename T8 = na, typename T9 = na, typename T10 = na, typename T11 = na
, typename T12 = na, typename T13 = na, typename T14 = na
, typename T15 = na, typename T16 = na, typename T17 = na
, typename T18 = na, typename T19 = na
>
struct map
: aux::map_impl<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
>::type
{
typedef typename aux::map_impl<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
>::type type;
};
}}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="3dp" />
<stroke
android:width="0.5dp"
android:color="@color/white" />
<solid android:color="@color/transparent" />
</shape> | {
"pile_set_name": "Github"
} |
/***********************************************************************************
Main.cpp
* Copyright (c) 1997
* Mark of the Unicorn, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Mark of the Unicorn makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
* Copyright (c) 1997
* Moscow Center for SPARC Technology
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Moscow Center for SPARC Technology makes
no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
***********************************************************************************/
#include "Prefix.h"
#include "Tests.h"
#if defined (EH_NEW_IOSTREAMS)
# include <iostream>
# else
# include <iostream.h>
#endif
#if defined(macintosh)&&(!defined(__MRC__) && !defined(__SC__)) || defined (_MAC) && defined(__MWERKS__)
# include <console.h>
# include <Types.h>
# include <Strings.h>
# ifdef EH_NEW_HEADERS
# include <cstdio>
# include <cstring>
# include <cassert>
# else
# include <stdio.h>
# include <string.h>
# include <assert.h>
# endif
# if defined (_STL_DEBUG)
# if defined ( EH_USE_SGI_STL )
// Override assertion behavior
# include <cstdarg>
//# include <stldebug.h>
void STLPORT::__stl_debug_message(const char * format_str, ...)
{
std::va_list args;
va_start( args, format_str );
char msg[256];
std::vsnprintf(msg, sizeof(msg)/sizeof(*msg) - 1, format_str, args );
DebugStr( c2pstr(msg) );
}
# else
/*===================================================================================
__assertion_failed (override standard library function)
EFFECTS: Breaks into the debugger and shows the assertion. This implementation
is Mac-specific; others could be added for other platforms.
====================================================================================*/
extern "C"
{
void __assertion_failed(char *condition, char *testfilename, int lineno);
void __assertion_failed(char *condition, char *testfilename, int lineno)
{
char msg[256];
std::strncpy( msg, condition, 255 );
std::strncat( msg, ": ", 255 );
std::strncat( msg, testfilename, 255 );
std::strncat( msg, ", ", 255 );
char line[20];
std::sprintf( line, "%d", lineno );
std::strncat( msg, line, 255 );
DebugStr( c2pstr( msg ) );
}
}
# endif
# endif
#endif
#include "nc_alloc.h"
#if defined (EH_NEW_HEADERS)
# include <vector>
# include <cstring>
# else
# include <vector.h>
# include <string.h>
#endif
#include "TestClass.h"
#include "LeakCheck.h"
#include "test_construct.h"
#ifdef __BORLANDC__
# include <except.h>
#endif
# if defined(EH_USE_NAMESPACES)
namespace // dwa 1/21/00 - must use unnamed namespace here to avoid conflict under gcc using native streams
{
using namespace std;
// using std::cerr;
// using std::endl;
}
# endif
/*===================================================================================
usage (file-static helper)
EFFECTS: Prints a message describing the command-line parameters
====================================================================================*/
static void usage(const char* name)
{
cerr<<"Usage : "<<name<<" [-n <iterations>] [-s <size>] [-l] [-e] [-q]/[-v] [-t] [test_name...]\n";
cerr<<"\t[-n <iterations>] : number of test iterations, default==100;"<<endl;
cerr<<"\t[-s <size>] : base value for random container sizes, default==1000;"<<endl;
cerr<<"\t[-e] : don't throw exceptions, test for leak in normal conditions;"<<endl;
// This option was never actually used -- dwa 9/22/97
// cerr<<"\t[-i] : ignore leak errors;"<<endl;
cerr<<"\t[-q] : quiet mode;"<<endl;
cerr<<"\t[-v] : verbose mode;"<<endl;
cerr<<"\t[-t] : track each allocation;"<<endl;
cerr<<"\t[test name [test name...]] : run only some of the tests by name (default==all tests):"<<endl;
cerr<<"\t\tpossible test names are : algo vector bit_vector list slist deque set map hash_set hash_map rope string bitset valarray"<<endl;
EH_CSTD::exit(1);
}
#ifdef EH_NEW_HEADERS
# include <set>
#else
# include <set.h>
#endif
#if defined(_WIN32_WCE)
#include <fstream>
#endif
int _STLP_CALL main(int argc, char** argv)
{
#if defined(_WIN32_WCE)
std::ofstream file( "\\eh_test.txt" );
std::streambuf* old_cout_buf = cout.rdbuf(file.rdbuf());
std::streambuf* old_cerr_buf = cerr.rdbuf(file.rdbuf());
#endif
#if defined( __MWERKS__ ) && defined( macintosh ) // Get command line.
argc = ccommand(&argv);
// Allow the i/o window to be repositioned.
// EH_STD::string s;
// getline(EH_STD::cin, s);
#endif
unsigned int niters=2;
bool run_all=true;
bool run_slist = false;
bool run_list = false;
bool run_vector = false;
bool run_bit_vector = false;
bool run_deque = false;
bool run_hash_map = false;
bool run_hash_set = false;
bool run_set = false;
bool run_map = false;
bool run_algo = false;
bool run_algobase = false;
bool run_rope = false;
bool run_string = false;
bool run_bitset = false;
bool run_valarray = false;
int cur_argv;
char *p, *p1;
#if defined (EH_NEW_IOSTREAMS)
std::ios_base::sync_with_stdio(false);
#endif
cerr << argv[0]<<" : Exception handling testsuite.\n";
cerr.flush();
bool track_allocations = false;
// parse parameters :
// leak_test [-iterations] [-test] ...
for (cur_argv=1; cur_argv<argc; cur_argv++) {
p = argv[cur_argv];
if (*p == '-') {
switch (p[1]) {
case 'q':
gTestController.SetVerbose(false);
break;
case 'v':
gTestController.SetVerbose(true);
break;
#if 0 // This option was never actually used -- dwa 9/22/97
case 'i':
gTestController.IgnoreLeaks(true);
break;
#endif
case 'n':
p1 = argv[++cur_argv];
if (p1 && EH_CSTD::sscanf(p1, "%i", &niters)==1)
cerr <<" Doing "<<niters<<" iterations\n";
else
usage(argv[0]);
break;
case 't':
track_allocations = true;
break;
case 'e':
gTestController.TurnOffExceptions();
break;
case 's':
p1 = argv[++cur_argv];
if (p1 && EH_CSTD::sscanf(p1, "%i", &random_base)==1)
cerr <<" Setting "<<random_base<<" as base for random sizes.\n";
else
usage(argv[0]);
break;
default:
usage(argv[0]);
break;
}
} else {
run_all = false;
// test name
if (EH_CSTD::strcmp(p, "algo")==0) {
run_algo=true;
} else if (EH_CSTD::strcmp(p, "vector")==0) {
run_vector=true;
} else if (EH_CSTD::strcmp(p, "bit_vector")==0) {
run_bit_vector=true;
} else if (EH_CSTD::strcmp(p, "list")==0) {
run_list=true;
} else if (EH_CSTD::strcmp(p, "slist")==0) {
run_slist=true;
} else if (EH_CSTD::strcmp(p, "deque")==0) {
run_deque=true;
} else if (EH_CSTD::strcmp(p, "set")==0) {
run_set=true;
} else if (EH_CSTD::strcmp(p, "map")==0) {
run_map=true;
} else if (EH_CSTD::strcmp(p, "hash_set")==0) {
run_hash_set=true;
} else if (EH_CSTD::strcmp(p, "hash_map")==0) {
run_hash_map=true;
} else if (EH_CSTD::strcmp(p, "rope")==0) {
run_rope=true;
} else if (EH_CSTD::strcmp(p, "string")==0) {
run_string=true;
} else if (EH_CSTD::strcmp(p, "bitset")==0) {
run_bitset=true;
} else if (EH_CSTD::strcmp(p, "valarray")==0) {
run_valarray=true;
} else {
usage(argv[0]);
}
}
}
gTestController.TrackAllocations( track_allocations );
// Over and over...
for ( unsigned i = 0; i < niters ; i++ )
{
cerr << "iteration #" << i << "\n";
if (run_all || run_algobase) {
gTestController.SetCurrentContainer("algobase");
cerr << "EH test : algobase" << endl;
test_algobase();
}
if (run_all || run_algo) {
gTestController.SetCurrentContainer("algo");
cerr << "EH test : algo" << endl;
test_algo();
}
if (run_all || run_vector) {
gTestController.SetCurrentContainer("vector");
cerr << "EH test : vector" << endl;
test_vector();
}
#if defined( EH_BIT_VECTOR_IMPLEMENTED )
if (run_all || run_bit_vector) {
gTestController.SetCurrentContainer("bit_vector");
cerr << "EH test : bit_vector" << endl;
test_bit_vector();
}
#endif
if (run_all || run_list) {
gTestController.SetCurrentContainer("list");
cerr << "EH test : list" << endl;
test_list();
}
#if defined( EH_SLIST_IMPLEMENTED )
if (run_all || run_slist) {
gTestController.SetCurrentContainer("slist");
cerr << "EH test : slist" << endl;
test_slist();
}
#endif // EH_SLIST_IMPLEMENTED
if (run_all || run_deque) {
gTestController.SetCurrentContainer("deque");
cerr << "EH test : deque" << endl;
test_deque();
}
if (run_all || run_set) {
gTestController.SetCurrentContainer("set");
cerr << "EH test : set" << endl;
test_set();
gTestController.SetCurrentContainer("multiset");
cerr << "EH test : multiset" << endl;
test_multiset();
}
if (run_all || run_map) {
gTestController.SetCurrentContainer("map");
cerr << "EH test : map" << endl;
test_map();
gTestController.SetCurrentContainer("multimap");
cerr << "EH test : multimap" << endl;
test_multimap();
}
#if defined( EH_HASHED_CONTAINERS_IMPLEMENTED )
if (run_all || run_hash_map) {
gTestController.SetCurrentContainer("hash_map");
cerr << "EH test : hash_map" << endl;
test_hash_map();
gTestController.SetCurrentContainer("hash_multimap");
cerr << "EH test : hash_multimap" << endl;
test_hash_multimap();
}
if (run_all || run_hash_set) {
gTestController.SetCurrentContainer("hash_set");
cerr << "EH test : hash_set" << endl;
test_hash_set();
gTestController.SetCurrentContainer("hash_multiset");
cerr << "EH test : hash_multiset" << endl;
test_hash_multiset();
}
#endif // EH_HASHED_CONTAINERS_IMPLEMENTED
#if defined( EH_ROPE_IMPLEMENTED )
// CW1.8 can't compile this for some reason!
#if !( defined(__MWERKS__) && __MWERKS__ < 0x1900 )
if (run_all || run_rope) {
gTestController.SetCurrentContainer("rope");
cerr << "EH test : rope" << endl;
test_rope();
}
#endif
#endif // EH_ROPE_IMPLEMENTED
#if defined( EH_STRING_IMPLEMENTED )
if (run_all || run_string) {
gTestController.SetCurrentContainer("string");
cerr << "EH test : string" << endl;
test_string();
}
#endif
#if defined( EH_BITSET_IMPLEMENTED )
if (run_all || run_bitset) {
gTestController.SetCurrentContainer("bitset");
cerr << "EH test : bitset" << endl;
test_bitset();
}
#endif
#if defined( EH_VALARRAY_IMPLEMENTED )
if (run_all || run_bitset) {
gTestController.SetCurrentContainer("valarray");
cerr << "EH test : valarray" << endl;
test_valarray();
}
#endif
}
gTestController.TrackAllocations( false );
cerr << "EH test : Done\n";
#if defined(_WIN32_WCE)
cout.rdbuf(old_cout_buf);
cerr.rdbuf(old_cerr_buf);
file.close();
#endif
return 0;
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 5eeef2bdd71292c4ebcbc55afadc1384
timeCreated: 1488062344
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
<!--
Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
This program and the accompanying materials are made available under the
terms of the Eclipse Public License v. 2.0, which is available at
http://www.eclipse.org/legal/epl-2.0.
This Source Code may also be made available under the following Secondary
Licenses when the conditions for such availability set forth in the
Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
version 2 with the GNU Classpath Exception, which is available at
https://www.gnu.org/software/classpath/license.html.
SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
-->
<!-- jdbc/jdbcResource.inc -->
<!-- used by jdbcResourceEdit.jsf and jdbcResourceNew.jsf -->
<sun:propertySheet id="propertySheet">
<!-- Text Field section -->
<sun:propertySheetSection id="propertSectionTextField">
<sun:property id="nameNew" rendered="#{!edit}" labelAlign="left" noWrap="#{true}" overlapLabel="#{false}" label="$resource{i18n.common.jndiName}">
<sun:textField id="name" styleClass="required" required="#{true}" columns="$int{30}" maxLength="#{sessionScope.fieldLengths['maxLength.common.jndiName']}" text="#{pageSession.valueMap['name']}" >
<!afterCreate
getClientId(component="$this{component}" clientId=>$page{resCompId});
/>
</sun:textField>
</sun:property>
<sun:property id="name" rendered="#{edit}" labelAlign="left" noWrap="#{true}" overlapLabel="#{false}" label="$resource{i18n.common.jndiName}">
<sun:staticText id="name" text="#{pageSession.Name}" rendered="#{Edit}" />
</sun:property>
#include "/common/resourceNode/logicalName.inc"
<sun:property id="logicalName" rendered="#{edit and renderLogic}" labelAlign="left" noWrap="#{true}" overlapLabel="#{false}" label="$resource{i18n.common.logicalJndiName}">
<sun:staticText id="lName" text="#{pageSession.logicalJndiName}" rendered="#{Edit}" />
<!beforeCreate
setPageSessionAttribute(key="listCommand" value="list-jdbc-resources");
setPageSessionAttribute(key="logicalJndiMapKey" value="jdbcResources");
gfr.prepareLogicalJndiNameForEdit();
/>
</sun:property>
<sun:property id="poolNameProp" labelAlign="left" noWrap="#{true}" overlapLabel="#{false}" label="$resource{i18n.common.poolName}" helpText="$resource{i18njdbc.jdbcResource.poolHelp}">
<sun:dropDown id="PoolName" selected="#{pageSession.valueMap['poolName']}" labels="$pageSession{jdbcList}" values="$pageSession{jdbcList}" >
<!beforeCreate
gf.getChildrenNamesList(endpoint="#{pageSession.parentUrl}/jdbc-connection-pool", result="#{pageSession.jdbcList}");
/>
</sun:dropDown>
</sun:property>
<sun:property id="deploymentOrder" rendered="#{edit}" labelAlign="left" noWrap="#{true}" overlapLabel="#{false}" label="$resource{i18n.common.resource.deploymentOrder}" helpText="$resource{i18n.common.resource.deploymentOrderHelp}" >
<sun:textField id="deploymentOrder" styleClass="integer" columns="$int{10}" maxLength="#{sessionScope.fieldLengths['maxLength.common.deploymentOrder']}" text="#{pageSession.valueMap['deploymentOrder']}" />
</sun:property>
<sun:property id="descProp" labelAlign="left" noWrap="#{true}" overlapLabel="#{false}" label="$resource{i18n.common.description}">
<sun:textField id="desc" columns="$int{55}" maxLength="#{sessionScope.fieldLengths['maxLength.common.description']}" text="#{pageSession.valueMap['description']}" />
</sun:property>
<sun:property id="statusProp" rendered="#{useCheckBox}" labelAlign="left" noWrap="#{true}" overlapLabel="#{false}" label="$resource{i18n.common.status}">
<sun:checkbox id="enabled" selected="#{pageSession.valueMap2['enabled']}" selectedValue="true" />
</sun:property>
<sun:property id="statusProp2" rendered="#{useString}" labelAlign="left" noWrap="#{true}" overlapLabel="#{false}"
label="$resource{i18n.common.status}" helpText="$resource{i18n.application.EnableTargetHelp}">
<sun:staticText id="enabledStr" text="#{requestScope.enabledString}" >
<!beforeCreate
gf.getTargetEnableInfo(appName="#{pageSession.encodedName}" isApp="#{false}" status="#{requestScope.enabledString}");
/>
</sun:staticText>
</sun:property>
"<br /><br />
</sun:propertySheetSection>
</sun:propertySheet>
| {
"pile_set_name": "Github"
} |
== Git Multiplayer ==
Inicialmente, utilizei o Git em um projeto particular onde era o único desenvolvedor. Entre os comandos relacionados a natureza distribuída do Git, eu precisava somente do *pull* e *clone*, de modo a manter o mesmo projeto em vários lugares.
Mais tarde, quis publicar meu código com o Git, e incluir as alterações dos contribuidores. Tive que aprender como gerenciar projetos com vários desenvolvedores de todas as partes do mundo. Felizmente, esse é o forte do Git, e indiscutivelmente sua razão de existir.
=== Quem sou eu? ===
Cada commit tem um nome de autor e e-mail, que pode ser mostrado pelo *git log*. O Git utiliza as configurações do sistema para preencher esses campos. Para fazer o preenchimento explícito, digite:
$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com
Omita o flag global para configurar essas opções somente para o repositório atual.
=== Git sob SSH, HTTP ===
Suponha que você tenha acesso SSH a um servidor web, mas que o Git não esteja instalado. Embora não tão eficiente quanto seu protocolo nativo, o Git pode se comunicar via HTTP.
Baixe, compile e instale o Git em sua conta, e crie um repositório no seu diretório web:
$ GIT_DIR=proj.git git init
$ cd proj.git
$ git --bare update-server-info
$ cp hooks/post-update.sample hooks/post-update
Para versões mais antigas do Git, o comando copy falha e você deve executar:
$ chmod a+x hooks/post-update
Agora você pode publicar suas últimas edições via SSH de qualquer clone:
$ git push web.server:/path/to/proj.git master
E qualquer um pode obter seu projeto com:
$ git clone http://web.server/proj.git
=== Git sobre qualquer coisa ===
Deseja sincronizar os repositórios sem servidores, ou mesmo sem uma conexão de rede? Precisa improvisar durante uma emergência? Vimos que <<makinghistory, *git fast-export* e *git fast-import* podem converter repositórios para um único arquivo e vice-versa>>. Podemos enviar esses arquivos para outros lugares fazendo o transporte de repositórios git sob qualquer meio, mas uma ferramenta mais eficiente é o *git bundle*.
O emissor cria um 'bundle':
$ git bundle create somefile HEAD
E então transporta o pacote, +somefile+, para outro lugar: por e-mail, pen-drive (ou mesmo uma saida impressa *xxd* e um scanner com ocr, sinais binários pelo telefone, sinais de fumaça, etc). O receptor recupera os commits do pacote executando:
$ git pull somefile
O receptor pode inclusive fazer isso em um diretório vazio. Apesar do seu tamanho, +somefile+ contém todo o repositório git original.
Em grandes projetos, podemos eliminar o desperdício fazendo o empacotamento somente das mudanças que o outro repositório necessita. Por exemplo, suponha que o commit ``1b6d...'' é o commit mais recente compartilhado por ambas as partes:
$ git bundle create somefile HEAD ^1b6d
Se executado frequentemente, podemos esquecer que commit foi feito por último. A página de ajuda sugere utilizar tags para resolver esse problema. Isto é, após enviar um pacote, digite:
$ git tag -f lastbundle HEAD
e crie um novo pacote de atualização com:
$ git bundle create newbundle HEAD ^lastbundle
=== Patches: A moeda Universal ===
Patches são representações textuais das suas mudanças que podem ser facilmente entendidas pelos computadores e pelos seres humanos. Isso tem um forte apelo. Você pode mandar um patch por e-mail para os desenvolvedores não importando que sistema de versão eles estão utilizando. Como os desenvolvedores podem ler o e-mail, eles podem ver o que você editou.
Da mesma maneira, do seu lado, tudo o que você precisa é de uma conta de e-mail: não é necessário configurar um repositório online do Git.
Lembrando do primeiro capítulo:
$ git diff 1b6d > my.patch
produz um patch que pode ser colado em um e-mail para discussão. Em um repositório Git, digite:
$ git apply < my.patch
para aplicar o patch.
Em configurações mais formais, quando o nome do autor e talvez sua assinatura precisem ser armazenadas, podemos gerar os patches correspondentes a partir de um certo ponto com o comando:
$ git format-patch 1b6d
Os arquivos resultantes podem ser fornecidos ao *git-send-email*, ou enviados manualmente. Você também pode especificar uma faixa de commits:
$ git format-patch 1b6d..HEAD^^
No lado do receptor, salve o e-mail como um arquivo, e entre com:
$ git am < email.txt
Isso aplica o patch de entrada e também cria um commit, incluindo as informações tais como o autor.
Com um navegador cliente de e-mail, pode ser necessário clicar o botão para ver o e-mail em seu formato original antes de salvar o patch para um arquivo.
Existem pequenas diferenças para os clientes de e-mail baseados em mbox, mas se você utiliza algum desses, provavelmente é o tipo de pessoa que pode resolver os problemas sem ler o manual.
=== Sinto muito, mas mudamos ===
Após fazer o clone de um repositório, executar o *git push* ou *git pull* irá automaticamente fazer o push ou pull da URL original. Como o Git faz isso? O segredo reside nas opções de configuração criadas com o clone. Vamos dar uma olhada:
$ git config --list
A opção +remote.origin.url+ controla a URL de origem; ``origin'' é um apelido dados ao repositório fonte. Da mesma maneira que a convenção do branch ``master'', podemos mudar ou deletar esse apelido mas geralmente não existe um motivo para fazê-lo.
Se o repositório original for movido, podemos atualizar a URL via:
$ git config remote.origin.url git://new.url/proj.git
A opção +branch.master.merge+ especifica o branch remoto default em um *git pull*. Durante a clonagem inicial, ele é configurado para o branch atual do repositório fonte, mesmo que o HEAD do repositório fonte subsequentemente mova para um branch diferente, um pull posterior irá seguir fielmente o branch original.
Essa opção somente aplica ao repositório que fizemos a clonagem em primeiro lugar, que é armazenado na opção +branch.master.remote+. Se fizermos um pull de outro repositório devemos estabelecer explicitamente que branch desejamos:
$ git pull git://example.com/other.git master
Isso explica por que alguns de nossos exemplos de pull e push não possuem argumentos.
=== Branches Remotos ===
Quando clonamos um repositório, clonamos também todos os seus branches. Voce pode não ter notado isso porque o Git sempre esconde os branches: mas podemos solicitá-los especificamente. Isso previne os branches no repositório remoto de interferir com seus branches, e também torna o Git mais fácil para os iniciantes.
Liste os branches remotos com:
$ git branch -r
Voce deve obter uma saída como:
origin/HEAD
origin/master
origin/experimental
Eles representam branches e a HEAD de um repositório remoto, e pode ser utilizado em comandos normais do Git. Por exemplo, suponha que você fez vários commits, e gostaria de comparar contra a última versão buscada (fetched). Você pode buscar nos logs pelo hash apropriado SHA1, mas é muito mais fácil digitar:
$ git diff origin/HEAD
Ou você pode ver o que o branch ``experimental'' contém:
$ git log origin/experimental
=== Remotos Múltiplos ===
Suponha que dois desenvolvedores estão trabalhando em nosso projeto, e que queremos manter o controle de ambos. Podemos seguir mais de um repositório a qualquer hora com:
$ git remote add other git://example.com/some_repo.git
$ git pull other some_branch
Agora temos merged em um branch a partir do segundo repositório, e temos fácil acesso a todos os branches de todos os repositórios:
$ git diff origin/experimental^ other/some_branch~5
Mas e se só queremos comparar as suas alterações sem afetar o trabalho de ambos? Em outras palavras, queremos examinar seus branches sem ter que suas alterações invadam nosso diretório de trabalho. Então ao invés de pull, execute:
$ git fetch # Fetch from origin, the default.
$ git fetch other # Fetch from the second programmer.
Isso faz com que somente busque os históricos. Embora o diretório de trabalho continue intocado, podemos fazer referencia a qualquer branch de qualquer repositório em um comando Git pois agora possuímos uma copia local.
Lembre-se de nos bastidores, um pull é simplesmente um *fetch* e um *merge*. Geralmente fazemos um *pull* pois queremos fazer um merge do ultimo commit após o fetch; essa situação é uma exceção notável.
Veja *git help remote* para saber como remover repositórios remotos, ignorar certos branches e outras informações.
=== Minhas preferencias ===
Para meus projetos, eu gosto que contribuidores para preparar os repositórios a partir dos quais eu possa fazer um pull. Alguns serviços hospedeiros de Git permite que você hospede seu próprio fork de um projeto com o clique de um botão.
Após ter buscado (fetch) uma árvore, eu executo comandos Git para navegar e examinar as alterações, que idealmente estão bem organizadas e bem descritas. Faço merge de minhas próprias alterações, e talvez faça edições posteriores. Uma vez satisfeito, eu faço um push para o repositório principal.
Embora eu receba infrequentes contribuições, eu acredito que essa abordagem funciona bem. Veja http://torvalds-family.blogspot.com/2009/06/happiness-is-warm-scm.html[esse post do blog do Linus Torvalds].
Continuar no mundo Git é mais conveniente do que fazer patch de arquivos, já que ele me salva de convertê-los para commits Git. Além disso, o Git trata dos detalhes tais como registrar o nome do autor e seu endereço de e-mail, bem como o dia e hora, alem de pedir ao autor para descrever sua própria alteração.
| {
"pile_set_name": "Github"
} |
{
"title":"Event.stopImmediatePropagation()",
"description":"Prevents any further event listeners from being invoked during the dispatch of this event.",
"spec":"https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation",
"status":"ls",
"links":[
{
"url":"https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation",
"title":"MDN Web Docs - stopImmediatePropagation"
}
],
"bugs":[
],
"categories":[
"DOM"
],
"stats":{
"ie":{
"5.5":"n",
"6":"n",
"7":"n",
"8":"n",
"9":"y",
"10":"y",
"11":"y"
},
"edge":{
"12":"y",
"13":"y",
"14":"y",
"15":"y",
"16":"y",
"17":"y",
"18":"y"
},
"firefox":{
"2":"n",
"3":"n",
"3.5":"n",
"3.6":"n",
"4":"n",
"5":"n",
"6":"n",
"7":"n",
"8":"n",
"9":"n",
"10":"y",
"11":"y",
"12":"y",
"13":"y",
"14":"y",
"15":"y",
"16":"y",
"17":"y",
"18":"y",
"19":"y",
"20":"y",
"21":"y",
"22":"y",
"23":"y",
"24":"y",
"25":"y",
"26":"y",
"27":"y",
"28":"y",
"29":"y",
"30":"y",
"31":"y",
"32":"y",
"33":"y",
"34":"y",
"35":"y",
"36":"y",
"37":"y",
"38":"y",
"39":"y",
"40":"y",
"41":"y",
"42":"y",
"43":"y",
"44":"y",
"45":"y",
"46":"y",
"47":"y",
"48":"y",
"49":"y",
"50":"y",
"51":"y",
"52":"y",
"53":"y",
"54":"y",
"55":"y",
"56":"y",
"57":"y",
"58":"y",
"59":"y",
"60":"y",
"61":"y",
"62":"y",
"63":"y"
},
"chrome":{
"4":"u",
"5":"u",
"6":"u",
"7":"u",
"8":"u",
"9":"u",
"10":"u",
"11":"u",
"12":"u",
"13":"u",
"14":"u",
"15":"u",
"16":"u",
"17":"u",
"18":"u",
"19":"u",
"20":"u",
"21":"u",
"22":"u",
"23":"u",
"24":"u",
"25":"u",
"26":"y",
"27":"y",
"28":"y",
"29":"y",
"30":"y",
"31":"y",
"32":"y",
"33":"y",
"34":"y",
"35":"y",
"36":"y",
"37":"y",
"38":"y",
"39":"y",
"40":"y",
"41":"y",
"42":"y",
"43":"y",
"44":"y",
"45":"y",
"46":"y",
"47":"y",
"48":"y",
"49":"y",
"50":"y",
"51":"y",
"52":"y",
"53":"y",
"54":"y",
"55":"y",
"56":"y",
"57":"y",
"58":"y",
"59":"y",
"60":"y",
"61":"y",
"62":"y",
"63":"y",
"64":"y",
"65":"y",
"66":"y",
"67":"y",
"68":"y",
"69":"y",
"70":"y",
"71":"y"
},
"safari":{
"3.1":"u",
"3.2":"u",
"4":"u",
"5":"u",
"5.1":"y",
"6":"y",
"6.1":"y",
"7":"y",
"7.1":"y",
"8":"y",
"9":"y",
"9.1":"y",
"10":"y",
"10.1":"y",
"11":"y",
"11.1":"y",
"12":"y",
"TP":"y"
},
"opera":{
"9":"n",
"9.5-9.6":"n",
"10.0-10.1":"n",
"10.5":"n",
"10.6":"n",
"11":"n",
"11.1":"n",
"11.5":"n",
"11.6":"n",
"12":"u",
"12.1":"y",
"15":"y",
"16":"y",
"17":"y",
"18":"y",
"19":"y",
"20":"y",
"21":"y",
"22":"y",
"23":"y",
"24":"y",
"25":"y",
"26":"y",
"27":"y",
"28":"y",
"29":"y",
"30":"y",
"31":"y",
"32":"y",
"33":"y",
"34":"y",
"35":"y",
"36":"y",
"37":"y",
"38":"y",
"39":"y",
"40":"y",
"41":"y",
"42":"y",
"43":"y",
"44":"y",
"45":"y",
"46":"y",
"47":"y",
"48":"y",
"49":"y",
"50":"y",
"51":"y",
"52":"y",
"53":"y"
},
"ios_saf":{
"3.2":"u",
"4.0-4.1":"u",
"4.2-4.3":"u",
"5.0-5.1":"u",
"6.0-6.1":"y",
"7.0-7.1":"y",
"8":"y",
"8.1-8.4":"y",
"9.0-9.2":"y",
"9.3":"y",
"10.0-10.2":"y",
"10.3":"y",
"11.0-11.2":"y",
"11.3-11.4":"y",
"12":"y"
},
"op_mini":{
"all":"u"
},
"android":{
"2.1":"u",
"2.2":"u",
"2.3":"u",
"3":"u",
"4":"y",
"4.1":"y",
"4.2-4.3":"y",
"4.4":"y",
"4.4.3-4.4.4":"y",
"67":"y"
},
"bb":{
"7":"u",
"10":"u"
},
"op_mob":{
"10":"u",
"11":"u",
"11.1":"u",
"11.5":"u",
"12":"u",
"12.1":"u",
"46":"u"
},
"and_chr":{
"67":"y"
},
"and_ff":{
"60":"y"
},
"ie_mob":{
"10":"u",
"11":"u"
},
"and_uc":{
"11.8":"u"
},
"samsung":{
"4":"u",
"5":"y",
"6.2":"y",
"7.2":"y"
},
"and_qq":{
"1.2":"y"
},
"baidu":{
"7.12":"y"
}
},
"notes":"",
"notes_by_num":{
},
"usage_perc_y":85.51,
"usage_perc_a":0,
"ucprefix":false,
"parent":"",
"keywords":"Event,stopImmediatePropagation,stop,immediate,propagation",
"ie_id":"",
"chrome_id":"",
"firefox_id":"",
"webkit_id":"",
"shown":false
}
| {
"pile_set_name": "Github"
} |
<!--This file was generated from the python source
Please edit the source to make changes
-->
PassengerCollector
=====
The PasengerCollector collects CPU and memory utilization of apache, nginx
and passenger processes.
It also collects requests in top-level and passenger applications group queues.
Four key attributes to be published:
* phusion_passenger_cpu
* total_apache_memory
* total_apache_procs
* total_passenger_memory
* total_passenger_procs
* total_nginx_memory
* total_nginx_procs
* top_level_queue_size
* passenger_queue_size
#### Dependencies
* passenger-memory-stats
* passenger-status
#### Options
Setting | Default | Description | Type
--------|---------|-------------|-----
bin | /usr/lib/ruby-flo/bin/passenger-memory-stats | The path to the binary | str
byte_unit | byte | Default numeric output(s) | str
enabled | False | Enable collecting these metrics | bool
measure_collector_time | False | Collect the collector run time in ms | bool
metrics_blacklist | None | Regex to match metrics to block. Mutually exclusive with metrics_whitelist | NoneType
metrics_whitelist | None | Regex to match metrics to transmit. Mutually exclusive with metrics_blacklist | NoneType
passenger_memory_stats_bin | /usr/bin/passenger-memory-stats | The path to the binary passenger-memory-stats | str
passenger_status_bin | /usr/bin/passenger-status | The path to the binary passenger-status | str
sudo_cmd | /usr/bin/sudo | Path to sudo | str
use_sudo | False | Use sudo? | bool
#### Example Output
```
__EXAMPLESHERE__
```
| {
"pile_set_name": "Github"
} |
[[
"start",
["keyword.control.module.elixir","defmodule"],
["meta.module.elixir"," "],
["entity.name.type.module.elixir","HelloModule"],
["text"," "],
["keyword.control.elixir","do"]
],[
"comment.documentation.heredoc",
["text"," "],
["comment.documentation.heredoc","@moduledoc \"\"\""]
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," This is supposed to be `markdown`."]
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," __Yes__ this is [mark](http://down.format)"]
],[
"comment.documentation.heredoc"
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," # Truly"]
],[
"comment.documentation.heredoc"
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," ## marked"]
],[
"comment.documentation.heredoc"
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," * with lists"]
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," * more"]
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," * and more"]
],[
"comment.documentation.heredoc"
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," Even.with(code)"]
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," blocks |> with |> samples"]
],[
"comment.documentation.heredoc"
],[
"comment.documentation.heredoc",
["comment.documentation.heredoc"," _Docs are first class citizens in Elixir_ (Jose Valim)"]
],[
"start",
["comment.documentation.heredoc"," \"\"\""]
],[
"start",
["text"," "]
],[
"start",
["text"," "],
["punctuation.definition.comment.elixir","#"],
["comment.line.number-sign.elixir"," A \"Hello world\" function"]
],[
"start",
["text"," "],
["keyword.control.elixir","def"],
["text"," some_fun "],
["keyword.control.elixir","do"]
],[
"start",
["text"," "],
["variable.other.constant.elixir","IO"],
["punctuation.separator.method.elixir","."],
["text","puts "],
["punctuation.definition.string.begin.elixir","\""],
["string.quoted.double.elixir","Juhu Kinners!"],
["punctuation.definition.string.end.elixir","\""]
],[
"start",
["text"," "],
["keyword.control.elixir","end"]
],[
"start",
["text"," "],
["punctuation.definition.comment.elixir","#"],
["comment.line.number-sign.elixir"," A private function"]
],[
"start",
["text"," "],
["keyword.control.elixir","defp"],
["text"," priv "],
["keyword.control.elixir","do"]
],[
"punctuation.definition.string.begin.elixir7",
["text"," is_regex "],
["punctuation.definition.string.begin.elixir","~r\"\"\""]
],[
"punctuation.definition.string.begin.elixir7",
["string.quoted.double.heredoc.elixir"," This is a regex"]
],[
"punctuation.definition.string.begin.elixir7",
["string.quoted.double.heredoc.elixir"," spanning several"]
],[
"punctuation.definition.string.begin.elixir7",
["string.quoted.double.heredoc.elixir"," lines."]
],[
"start",
["punctuation.definition.string.end.elixir"," \"\"\""]
],[
"start",
["text"," x "],
["keyword.operator.assignment.elixir","="],
["text"," elem"],
["punctuation.section.function.elixir","("],
["punctuation.section.scope.elixir","{"],
["text"," "],
["punctuation.definition.constant.elixir",":"],
["constant.other.symbol.elixir","a"],
["punctuation.separator.object.elixir",","],
["text"," "],
["punctuation.definition.constant.elixir",":"],
["constant.other.symbol.elixir","b"],
["punctuation.separator.object.elixir",","],
["text"," "],
["punctuation.definition.constant.elixir",":"],
["constant.other.symbol.elixir","c"],
["text"," "],
["punctuation.section.scope.elixir","}"],
["punctuation.separator.object.elixir",","],
["text"," "],
["constant.numeric.elixir","0"],
["punctuation.section.function.elixir",")"],
["text"," "],
["punctuation.definition.comment.elixir","#"],
["comment.line.number-sign.elixir","=> :a"]
],[
"start",
["text"," "],
["keyword.control.elixir","end"]
],[
"start",
["keyword.control.elixir","end"]
],[
"start"
],[
"start",
["text","test_fun "],
["keyword.operator.assignment.elixir","="],
["text"," "],
["keyword.control.elixir","fn"],
["punctuation.section.function.elixir","("],
["text","x"],
["punctuation.section.function.elixir",")"],
["text"," "],
["keyword.operator.arithmetic.elixir","-"],
["keyword.operator.comparison.elixir",">"]
],[
"start",
["text"," "],
["keyword.control.elixir","cond"],
["text"," "],
["keyword.control.elixir","do"]
],[
"start",
["text"," x "],
["keyword.operator.comparison.elixir",">"],
["text"," "],
["constant.numeric.elixir","10"],
["text"," "],
["keyword.operator.arithmetic.elixir","-"],
["keyword.operator.comparison.elixir",">"]
],[
"start",
["text"," "],
["punctuation.definition.constant.elixir",":"],
["constant.other.symbol.elixir","greater_than_ten"]
],[
"start",
["text"," "],
["constant.language.elixir","true"],
["text"," "],
["keyword.operator.arithmetic.elixir","-"],
["keyword.operator.comparison.elixir",">"]
],[
"start",
["text"," "],
["punctuation.definition.constant.elixir",":"],
["constant.other.symbol.elixir","maybe_ten"]
],[
"start",
["text"," "],
["keyword.control.elixir","end"]
],[
"start",
["keyword.control.elixir","end"]
]] | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="windows-1251"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="Blow"
SccProjectName=""
SccLocalPath="">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory=".\Debug"
IntermediateDirectory=".\Debug"
ConfigurationType="1"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="2"
PrecompiledHeaderFile=".\Debug/Blow.pch"
AssemblerListingLocation=".\Debug/"
ObjectFile=".\Debug/"
ProgramDataBaseFileName=".\Debug/"
WarningLevel="3"
SuppressStartupBanner="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="../bin/config.exe"
LinkIncremental="1"
SuppressStartupBanner="TRUE"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile=".\Debug/config.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"
TypeLibraryName=".\Debug/Blow.tlb"
HeaderFileName=""/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="1049"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory=".\Release"
IntermediateDirectory=".\Release"
ConfigurationType="1"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
InlineFunctionExpansion="1"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
StringPooling="TRUE"
RuntimeLibrary="4"
EnableFunctionLevelLinking="TRUE"
UsePrecompiledHeader="2"
PrecompiledHeaderFile=".\Release/Blow.pch"
AssemblerListingLocation=".\Release/"
ObjectFile=".\Release/"
ProgramDataBaseFileName=".\Release/"
WarningLevel="3"
SuppressStartupBanner="TRUE"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile=".\Release/Blow.exe"
LinkIncremental="1"
SuppressStartupBanner="TRUE"
ProgramDatabaseFile=".\Release/Blow.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"
TypeLibraryName=".\Release/Blow.tlb"
HeaderFileName=""/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="1049"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath="Blow.cpp">
<FileConfiguration
Name="Debug|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions=""
BasicRuntimeChecks="3"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions=""/>
</FileConfiguration>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
| {
"pile_set_name": "Github"
} |
# -*- mode: perl; -*-
# Copyright 2016-2016 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the OpenSSL license (the "License"). You may not use
# this file except in compliance with the License. You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html
## Test Renegotiation
use strict;
use warnings;
package ssltests;
my $dir_sep = $^O ne "VMS" ? "/" : "";
our @tests = (
{
name => "renegotiate-client-no-resume",
server => {
"Options" => "NoResumptionOnRenegotiation"
},
client => {},
test => {
"Method" => "TLS",
"HandshakeMode" => "RenegotiateClient",
"ResumptionExpected" => "No",
"ExpectedResult" => "Success"
}
},
{
name => "renegotiate-client-resume",
server => {},
client => {},
test => {
"Method" => "TLS",
"HandshakeMode" => "RenegotiateClient",
"ResumptionExpected" => "Yes",
"ExpectedResult" => "Success"
}
},
{
name => "renegotiate-server-no-resume",
server => {
"Options" => "NoResumptionOnRenegotiation"
},
client => {},
test => {
"Method" => "TLS",
"HandshakeMode" => "RenegotiateServer",
"ResumptionExpected" => "No",
"ExpectedResult" => "Success"
}
},
{
name => "renegotiate-server-resume",
server => {},
client => {},
test => {
"Method" => "TLS",
"HandshakeMode" => "RenegotiateServer",
"ResumptionExpected" => "Yes",
"ExpectedResult" => "Success"
}
},
{
name => "renegotiate-client-auth-require",
server => {
"Options" => "NoResumptionOnRenegotiation",
"MaxProtocol" => "TLSv1.2",
"VerifyCAFile" => "\${ENV::TEST_CERTS_DIR}${dir_sep}root-cert.pem",
"VerifyMode" => "Require",
},
client => {
"Certificate" => "\${ENV::TEST_CERTS_DIR}${dir_sep}ee-client-chain.pem",
"PrivateKey" => "\${ENV::TEST_CERTS_DIR}${dir_sep}ee-key.pem"
},
test => {
"Method" => "TLS",
"HandshakeMode" => "RenegotiateServer",
"ResumptionExpected" => "No",
"ExpectedResult" => "Success"
}
},
{
name => "renegotiate-client-auth-once",
server => {
"Options" => "NoResumptionOnRenegotiation",
"MaxProtocol" => "TLSv1.2",
"VerifyCAFile" => "\${ENV::TEST_CERTS_DIR}${dir_sep}root-cert.pem",
"VerifyMode" => "Once",
},
client => {
"Certificate" => "\${ENV::TEST_CERTS_DIR}${dir_sep}ee-client-chain.pem",
"PrivateKey" => "\${ENV::TEST_CERTS_DIR}${dir_sep}ee-key.pem"
},
test => {
"Method" => "TLS",
"HandshakeMode" => "RenegotiateServer",
"ResumptionExpected" => "No",
"ExpectedResult" => "Success"
}
}
);
| {
"pile_set_name": "Github"
} |
// Copyright 2019 The Druid 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.
use druid::widget::{Checkbox, Either, Flex, Label, Slider};
use druid::{AppLauncher, Data, Lens, LocalizedString, Widget, WidgetExt, WindowDesc};
#[derive(Clone, Default, Data, Lens)]
struct AppState {
which: bool,
value: f64,
}
pub fn main() {
let main_window = WindowDesc::new(ui_builder).title(
LocalizedString::new("either-demo-window-title")
.with_placeholder("Switcheroo")
.with_arg("view", |data: &AppState, _env| (data.which as u8).into()),
);
let data = AppState::default();
AppLauncher::with_window(main_window)
.use_simple_logger()
.launch(data)
.expect("launch failed");
}
fn ui_builder() -> impl Widget<AppState> {
let label = Label::new("Click to reveal slider");
let mut col = Flex::column();
col.add_child(
Checkbox::new("Toggle slider")
.lens(AppState::which)
.padding(5.0),
);
let either = Either::new(
|data, _env| data.which,
Slider::new().lens(AppState::value).padding(5.0),
label.padding(5.0),
);
col.add_child(either);
col
}
| {
"pile_set_name": "Github"
} |
import {Controller, Get, PathParams, PlatformTest, QueryParams} from "@tsed/common";
import {expect} from "chai";
import * as SuperTest from "supertest";
import {PlatformTestOptions} from "../interfaces";
export abstract class TestBaseController {
@Get("/")
scenario1(@QueryParams("search") search: string) {
return {
search
};
}
@Get("/override")
scenario3(@QueryParams("q") q: string) {
return {data: q};
}
}
@Controller("/test")
export class TestChildController extends TestBaseController {
@Get("/:id")
scenario2(@PathParams("id") id: string) {
return {id};
}
@Get("/override")
scenario3(@QueryParams("s") s: string) {
return {data: s};
}
}
export function testCtrlInheritance(options: PlatformTestOptions) {
let request: SuperTest.SuperTest<SuperTest.Test>;
before(
PlatformTest.bootstrap(options.server, {
...options,
mount: {
"/rest": [TestChildController]
}
})
);
before(() => {
request = SuperTest(PlatformTest.callback());
});
after(PlatformTest.reset);
it("Scenario1: should call inherited method", async () => {
const {body} = await request.get("/rest/test/?search=test").expect(200);
expect(body).to.deep.equal({
search: "test"
});
});
it("Scenario2: should the Child method", async () => {
const {body} = await request.get("/rest/test/1").expect(200);
expect(body).to.deep.equal({id: "1"});
});
it("Scenario2: should call the Child method and not the base method", async () => {
const {body} = await request.get("/rest/test/1").expect(200);
expect(body).to.deep.equal({id: "1"});
});
}
| {
"pile_set_name": "Github"
} |
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
namespace Js {
struct SIMDFloat64x2Operation
{
// following are operation wrappers for SIMD.Float64x2 general implementation
static SIMDValue OpFloat64x2(double x, double y);
static SIMDValue OpSplat(double x);
// conversion
static SIMDValue OpFromFloat32x4(const SIMDValue& value);
static SIMDValue OpFromInt32x4(const SIMDValue& value);
// Unary Ops
static SIMDValue OpAbs(const SIMDValue& v);
static SIMDValue OpNeg(const SIMDValue& v);
static SIMDValue OpNot(const SIMDValue& v);
static SIMDValue OpReciprocal(const SIMDValue& v);
static SIMDValue OpReciprocalSqrt(const SIMDValue& v);
static SIMDValue OpSqrt(const SIMDValue& v);
// Binary Ops
static SIMDValue OpAdd(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpSub(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpMul(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpDiv(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpAnd(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpOr (const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpXor(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpMin(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpMax(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpScale(const SIMDValue& Value, double scaleValue);
static SIMDValue OpLessThan(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpLessThanOrEqual(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpEqual(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpNotEqual(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpGreaterThan(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpGreaterThanOrEqual(const SIMDValue& aValue, const SIMDValue& bValue);
static SIMDValue OpSelect(const SIMDValue& mV, const SIMDValue& tV, const SIMDValue& fV);
template<typename T> static void OpConv(SIMDValue* dst, SIMDValue* src);
};
} // namespace Js
| {
"pile_set_name": "Github"
} |
#!/bin/sh
set -o nounset
set -o errexit
VERSION=`cat VERSION`
git tag $VERSION
git push origin --tags
| {
"pile_set_name": "Github"
} |
namespace Avalonia.Logging
{
/// <summary>
/// Specifies the meaning and relative importance of a log event.
/// </summary>
public enum LogEventLevel
{
/// <summary>
/// Anything and everything you might want to know about a running block of code.
/// </summary>
Verbose,
/// <summary>
/// Internal system events that aren't necessarily observable from the outside.
/// </summary>
Debug,
/// <summary>
/// The lifeblood of operational intelligence - things happen.
/// </summary>
Information,
/// <summary>
/// Service is degraded or endangered.
/// </summary>
Warning,
/// <summary>
/// Functionality is unavailable, invariants are broken or data is lost.
/// </summary>
Error,
/// <summary>
/// If you have a pager, it goes off when one of these occurs.
/// </summary>
Fatal
}
}
| {
"pile_set_name": "Github"
} |
Found at:
http://www.redhat.com/archives/fedora-cvs-commits/2007-March/msg00788.html
Size is, correctly, size_t and mmap, correctly, takes
size_t as the size argument; the cast to int flunks
64bit thinking.
diff -Naur ElectricFence-2.2.2/page.c ElectricFence-2.2.3/page.c
--- page.c 2007-03-16 13:20:44.000000000 -0400
+++ page.c 2007-03-16 13:23:28.000000000 -0400
@@ -70,7 +70,7 @@
*/
allocation = (caddr_t) mmap(
startAddr
- ,(int)size
+ ,size
,PROT_READ|PROT_WRITE
,MAP_PRIVATE|MAP_ANONYMOUS
,-1
@@ -122,7 +122,7 @@
*/
allocation = (caddr_t) mmap(
startAddr
- ,(int)size
+ ,size
,PROT_READ|PROT_WRITE
,MAP_PRIVATE
,devZeroFd
| {
"pile_set_name": "Github"
} |
import "../math/trigonometry";
import "color";
import "lab";
import "rgb";
d3.hcl = function(h, c, l) {
return arguments.length === 1
? (h instanceof d3_Hcl ? d3_hcl(h.h, h.c, h.l)
: (h instanceof d3_Lab ? d3_lab_hcl(h.l, h.a, h.b)
: d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b)))
: d3_hcl(+h, +c, +l);
};
function d3_hcl(h, c, l) {
return new d3_Hcl(h, c, l);
}
function d3_Hcl(h, c, l) {
this.h = h;
this.c = c;
this.l = l;
}
var d3_hclPrototype = d3_Hcl.prototype = new d3_Color;
d3_hclPrototype.brighter = function(k) {
return d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
};
d3_hclPrototype.darker = function(k) {
return d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
};
d3_hclPrototype.rgb = function() {
return d3_hcl_lab(this.h, this.c, this.l).rgb();
};
function d3_hcl_lab(h, c, l) {
if (isNaN(h)) h = 0;
if (isNaN(c)) c = 0;
return d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
}
| {
"pile_set_name": "Github"
} |
//
// QLPreviewPanel+iTerm.m
// iTerm2
//
// Created by Rony Fadel on 2/20/16.
//
//
#import "QLPreviewPanel+iTerm.h"
@implementation QLPreviewPanel (iTerm)
+ (instancetype)sharedPreviewPanelIfExists {
if ([QLPreviewPanel sharedPreviewPanelExists]) {
return [QLPreviewPanel sharedPreviewPanel];
} else {
return nil;
}
}
@end
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
body {
font-family: sans-serif;
}
h2 {
margin: 15px 0 5px 0;
}
ul,
p,
canvas {
margin: 0;
}
#media-players td,
#media-players th {
padding: 0 10px;
}
.audio-stream[status='created'] {
color: blue;
}
.audio-stream[status='closed'] {
text-decoration: line-through;
}
.audio-stream[status='error'] {
color: red;
}
#cache-entries ul,
#media-players ul {
list-style-type: none;
}
.cache-entry {
margin: 0 0 5px 0;
}
.cache-entry-controls {
font-size: smaller;
}
.cache-table {
table-layout: fixed;
width: 500px;
}
thead {
text-align: left;
}
tfoot {
text-align: right;
}
.buffered {
display: table;
}
.buffered > div {
display: table-row;
}
.buffered > div > div {
display: table-cell;
vertical-align: bottom;
}
.buffered > div > div:first-child {
font-weight: bold;
padding-right: 2px;
}
| {
"pile_set_name": "Github"
} |
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var error = "error";
function counter(x) {
return (function() { if (x-- == 0) throw error;});
}
// TODO(asm): This module is not valid asm.js.
function Module() {
"use asm";
function w0(f) {
while (1) f();
return 108;
}
function w1(f) {
if (1) while (1) f();
return 109;
}
function w2(f) {
if (1) while (1) f();
else while (1) f();
return 110;
}
function w3(f) {
if (0) while (1) f();
return 111;
}
return { w0: w0, w1: w1, w2: w2, w3: w3 };
}
var m = Module();
assertThrowsEquals(function() { m.w0(counter(5)) }, error);
assertThrowsEquals(function() { m.w1(counter(5)) }, error);
assertThrowsEquals(function() { m.w2(counter(5)) }, error);
assertEquals(111, m.w3(counter(5)));
| {
"pile_set_name": "Github"
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.addthis.hydra.data.query;
import org.junit.Test;
public class TestOpDepivot extends TestOp {
@Test
public void defaultsAndArbitraryIndexLabel() throws Exception {
doOpTest(
new DataTableHelper().
tr().td("index").td("a", "b").td().
tr().td("aaa", "1", "3", "4").
tr().td("bbb", "2", "2", "4").
tr().td("ccc", "3", "1", "4"),
"depivot=row,col,val",
new DataTableHelper().
tr().td("aaa", "a", "1").
tr().td("aaa", "b", "3").
tr().td("bbb", "a", "2").
tr().td("bbb", "b", "2").
tr().td("ccc", "a", "3").
tr().td("ccc", "b", "1")
);
}
@Test
public void defaultsPlusCopyMetadata() throws Exception {
doOpTest(
new DataTableHelper()
.tr().td("index").td("a", "b").td()
.tr().td("aaa", "1", "3", "1")
.tr().td("bbb", "2", "2", "2")
.tr().td("ccc", "3", "1", "1"),
"depivot=row,col,val,extra",
new DataTableHelper()
.tr().td("aaa", "a", "1", "1")
.tr().td("aaa", "b", "3", "1")
.tr().td("bbb", "a", "2", "2")
.tr().td("bbb", "b", "2", "2")
.tr().td("ccc", "a", "3", "1")
.tr().td("ccc", "b", "1", "1")
);
}
}
| {
"pile_set_name": "Github"
} |
package com.legend.demo;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import com.lody.legend.Hook;
import com.lody.legend.HookManager;
/**
* @author Lody
* @version 1.0
*/
public class App extends Application {
public static boolean ENABLE_TOAST = true;
public static boolean ALLOW_LAUNCH_ACTIVITY = true;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
HookManager.getDefault().applyHooks(App.class);
}
@Hook("android.app.Application::onCreate")
public static void Application_onCreate(Application app) {
Toast.makeText(app, "Application => onCreate()", Toast.LENGTH_SHORT).show();
HookManager.getDefault().callSuper(app);
}
@Hook("android.telephony.TelephonyManager::getSimSerialNumber")
public static String TelephonyManager_getSimSerialNumber(TelephonyManager thiz) {
return "110";
}
@Hook("android.widget.Toast::show")
public static void Toast_show(Toast toast) {
if (ENABLE_TOAST) {
HookManager.getDefault().callSuper(toast);
}
}
@Hook("android.app.Activity::startActivity@android.content.Intent")
public static void Activity_startActivity(Activity activity, Intent intent) {
if (!ALLOW_LAUNCH_ACTIVITY) {
Toast.makeText(activity, "I am sorry to turn your Activity down :)", Toast.LENGTH_SHORT).show();
}else {
HookManager.getDefault().callSuper(activity, intent);
}
}
}
| {
"pile_set_name": "Github"
} |
package opentracing
import "golang.org/x/net/context"
type contextKey struct{}
var activeSpanKey = contextKey{}
// ContextWithSpan returns a new `context.Context` that holds a reference to
// `span`'s SpanContext.
func ContextWithSpan(ctx context.Context, span Span) context.Context {
return context.WithValue(ctx, activeSpanKey, span)
}
// SpanFromContext returns the `Span` previously associated with `ctx`, or
// `nil` if no such `Span` could be found.
//
// NOTE: context.Context != SpanContext: the former is Go's intra-process
// context propagation mechanism, and the latter houses OpenTracing's per-Span
// identity and baggage information.
func SpanFromContext(ctx context.Context) Span {
val := ctx.Value(activeSpanKey)
if sp, ok := val.(Span); ok {
return sp
}
return nil
}
// StartSpanFromContext starts and returns a Span with `operationName`, using
// any Span found within `ctx` as a ChildOfRef. If no such parent could be
// found, StartSpanFromContext creates a root (parentless) Span.
//
// The second return value is a context.Context object built around the
// returned Span.
//
// Example usage:
//
// SomeFunction(ctx context.Context, ...) {
// sp, ctx := opentracing.StartSpanFromContext(ctx, "SomeFunction")
// defer sp.Finish()
// ...
// }
func StartSpanFromContext(ctx context.Context, operationName string, opts ...StartSpanOption) (Span, context.Context) {
return startSpanFromContextWithTracer(ctx, GlobalTracer(), operationName, opts...)
}
// startSpanFromContextWithTracer is factored out for testing purposes.
func startSpanFromContextWithTracer(ctx context.Context, tracer Tracer, operationName string, opts ...StartSpanOption) (Span, context.Context) {
var span Span
if parentSpan := SpanFromContext(ctx); parentSpan != nil {
opts = append(opts, ChildOf(parentSpan.Context()))
span = tracer.StartSpan(operationName, opts...)
} else {
span = tracer.StartSpan(operationName, opts...)
}
return span, ContextWithSpan(ctx, span)
}
| {
"pile_set_name": "Github"
} |
---
layout: base
title: 'Statistics of Typo in UD_Erzya-JR'
udver: '2'
---
## Treebank Statistics: UD_Erzya-JR: Features: `Typo`
This feature is language-specific.
It occurs with 1 different values: `Yes`.
5 tokens (0%) have a non-empty value of `Typo`.
5 types (0%) occur at least once with a non-empty value of `Typo`.
5 lemmas (0%) occur at least once with a non-empty value of `Typo`.
The feature is used with 4 part-of-speech tags: <tt><a href="myv_jr-pos-ADV.html">ADV</a></tt> (2; 0% instances), <tt><a href="myv_jr-pos-NOUN.html">NOUN</a></tt> (1; 0% instances), <tt><a href="myv_jr-pos-PUNCT.html">PUNCT</a></tt> (1; 0% instances), <tt><a href="myv_jr-pos-VERB.html">VERB</a></tt> (1; 0% instances).
### `ADV`
2 <tt><a href="myv_jr-pos-ADV.html">ADV</a></tt> tokens (0% of all `ADV` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `ADV` and `Typo` co-occurred: <tt><a href="myv_jr-feat-AdvType.html">AdvType</a></tt><tt>=EMPTY</tt> (2; 100%), <tt><a href="myv_jr-feat-Case.html">Case</a></tt><tt>=EMPTY</tt> (2; 100%), <tt><a href="myv_jr-feat-PronType.html">PronType</a></tt><tt>=EMPTY</tt> (2; 100%).
`ADV` tokens may have the following values of `Typo`:
* `Yes` (2; 100% of non-empty `Typo`): <em>вицтэ, Седе</em>
### `NOUN`
1 <tt><a href="myv_jr-pos-NOUN.html">NOUN</a></tt> tokens (0% of all `NOUN` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `NOUN` and `Typo` co-occurred: <tt><a href="myv_jr-feat-Case.html">Case</a></tt><tt>=Nom</tt> (1; 100%), <tt><a href="myv_jr-feat-Definite.html">Definite</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="myv_jr-feat-Number.html">Number</a></tt><tt>=Sing</tt> (1; 100%), <tt><a href="myv_jr-feat-Number-psor.html">Number[psor]</a></tt><tt>=Sing</tt> (1; 100%), <tt><a href="myv_jr-feat-Person-psor.html">Person[psor]</a></tt><tt>=2</tt> (1; 100%).
`NOUN` tokens may have the following values of `Typo`:
* `Yes` (1; 100% of non-empty `Typo`): <em>Мирьдеть</em>
### `PUNCT`
1 <tt><a href="myv_jr-pos-PUNCT.html">PUNCT</a></tt> tokens (0% of all `PUNCT` tokens) have a non-empty value of `Typo`.
`PUNCT` tokens may have the following values of `Typo`:
* `Yes` (1; 100% of non-empty `Typo`): <em>.</em>
### `VERB`
1 <tt><a href="myv_jr-pos-VERB.html">VERB</a></tt> tokens (0% of all `VERB` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `VERB` and `Typo` co-occurred: <tt><a href="myv_jr-feat-Case.html">Case</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="myv_jr-feat-Derivation.html">Derivation</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="myv_jr-feat-Mood.html">Mood</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="myv_jr-feat-Number-obj.html">Number[obj]</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="myv_jr-feat-Number-subj.html">Number[subj]</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="myv_jr-feat-Person-obj.html">Person[obj]</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="myv_jr-feat-Person-subj.html">Person[subj]</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="myv_jr-feat-Tense.html">Tense</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="myv_jr-feat-Valency.html">Valency</a></tt><tt>=1</tt> (1; 100%), <tt><a href="myv_jr-feat-VerbForm.html">VerbForm</a></tt><tt>=EMPTY</tt> (1; 100%).
`VERB` tokens may have the following values of `Typo`:
* `Yes` (1; 100% of non-empty `Typo`): <em>аварьть</em>
| {
"pile_set_name": "Github"
} |
Entropy = 7.999992 bits per byte.
Optimum compression would reduce the size
of this 25000000 byte file by 0 percent.
Chi square distribution for 25000000 samples is 272.53, and randomly
would exceed this value 21.52 percent of the times.
Arithmetic mean value of data bytes is 127.5030 (127.5 = random).
Monte Carlo value for Pi is 3.140968823 (error 0.02 percent).
Serial correlation coefficient is 0.000289 (totally uncorrelated = 0.0).
| {
"pile_set_name": "Github"
} |
section: view
id: comment
description: 展示评论的列表视图
icon: icon-comments
filter: pinglun pl
---
# 评论
评论视图用于展示评论消息,评论列表允许进行嵌套。
## 结构
评论视图使用 `.comments` 作为父级容器,并使用如下特殊类标记子容器:
<table class="table">
<tbody>
<tr>
<td style="width: 150px">`<header>`</td>
<td style="width: 80px">头部</td>
<td>标题等信息</td>
</tr>
<tr>
<td>`.comments-list`</td>
<td>列表项组</td>
<td>`.comments-list` 也可以嵌套放入 `.comment` 内。</td>
</tr>
<tr>
<td>`<footer>`</td>
<td>底部</td>
<td>显示评论表达及分页信息等。</td>
</tr>
</tbody>
</table>
一般 HTML 结构如下:
```html
<div class="comments">
<header>
<h1>所有评论</h1>
</header>
<div class="comments-list">
<div class="comment">
...
</div>
...
</div>
<footer>
<form action="">
...
</form>
</footer>
</div>
```
## 评论条目
评论条目使用 `.comment` 类标识。在评论条目内可以使用如下特殊类:
- `.avatar`,可选,用于包含一张图片作为发表评论的用户头像;
- `.content`,用于包含评论内容的容器;
- `.text`,用于包裹评论正文内容的容器,作为 `.content` 的直接子元素;
- `.actions`,用于包裹评论操作按钮或链接,作为 `.content` 的直接子元素;
- `.comments-list`,为该条评论嵌套一个新的评论列表,一般用于显示用户回复的评论条目。
### 一般形式
包含用户头像、用户名称、操作链接、发布时间等。
<example>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-user icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
</div>
</example>
```html
<div class="comment">
<a href="###" class="avatar">
<i class="icon-user icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
</div>
```
<div class="alert alert-primary-inverse">
<h4>自定义头像</h4>
<p>文档内使用图标作为头像内容仅仅作为演示,并非 ZUI 提供,你需要在 .avatar 内包含一张图片用作头像内容。</p>
</div>
### 不包含头像
直接移除 `.avatar` 元素即可。
<example>
<div class="comment">
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
</div>
</example>
```html
<div class="comment">
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
</div>
```
### 嵌套评论列表
在 `.comment` 内直接包含一个新的 `.comments-list` 即可。
<example>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-camera-retro icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">3 个小时前</div>
<div><a href="###"><strong>张士超</strong></a></div>
<div class="text">今天玩的真开心!~~~~~~</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
<div class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-user icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
<div class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-yinyang icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">1 个小时前</div>
<div><a href="###"><strong>门口大爷</strong></a> <span class="text-muted">回复</span> <a href="###">Catouse</a></div>
<div class="text">不在我这儿...</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-cube-alt icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">1 个小时前</div>
<div><a href="###"><strong>队长</strong></a> <span class="text-muted">回复</span> <a href="###">Catouse</a></div>
<div class="text">也不在我这儿...</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
</div>
</div>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-heart-empty icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">30 分钟前</div>
<div><a href="###"><strong>华师大第一美女</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">很开心~~~</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
</div>
</div>
</example>
<template class="pre-scrollable linenums"/>
```html
<div class="comment">
<a href="###" class="avatar">
<i class="icon-camera-retro icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">3 个小时前</div>
<div><a href="###"><strong>张士超</strong></a></div>
<div class="text">今天玩的真开心!~~~~~~</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
<div class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-user icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
<div class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-yinyang icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">1 个小时前</div>
<div><a href="###"><strong>门口大爷</strong></a> <span class="text-muted">回复</span> <a href="###">Catouse</a></div>
<div class="text">不在我这儿...</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-cube-alt icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">1 个小时前</div>
<div><a href="###"><strong>队长</strong></a> <span class="text-muted">回复</span> <a href="###">Catouse</a></div>
<div class="text">也不在我这儿...</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
</div>
</div>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-heart-empty icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">30 分钟前</div>
<div><a href="###"><strong>华师大第一美女</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">很开心~~~</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
</div>
</div>
```
<div class="alert alert-primary-inverse">
<h4>限制嵌套层次</h4>
<p>虽然你可以无限的嵌套评论列表,但受限于视窗大小和便于用户阅读,不应该使用超过 3 个层级的嵌套。</p>
</div>
## 评论表单
评论表单通常放置在 `<footer>` 内。在 `<form>` 上添加 `.reply-form` 类来获得外观一致性的评论表单。
<example>
<div class="comments">
<section class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-user icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
</div>
</section>
<footer>
<div class="reply-form" id="commentReplyForm1">
<a href="###" class="avatar"><i class="icon-user icon-2x"></i></a>
<form class="form">
<div class="form-group">
<textarea class="form-control new-comment-text" rows="2" placeholder="撰写评论..."></textarea>
</div>
<div class="form-group comment-user">
<div class="row">
<div class="col-md-3">
<span class="pull-right">或者</span>
<a href="#">登录</a> <a href="##">注册</a>
</div>
<div class="col-md-7">
<div class="form-group">
<input type="text" class="form-control" id="nameInputEmail1" placeholder="输入评论显示名称">
</div>
<div class="form-group">
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="输入电子邮件(不会在评论显示)">
</div>
</div>
<div class="col-md-2"><button type="submit" class="btn btn-block btn-primary"><i class="icon-ok"></i></button></div>
</div>
</div>
</form>
</div>
</footer>
</div>
</example>
<template class="pre-scrollable linenums"/>
```html
<div class="comments">
<section class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-user icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
</div>
</section>
<footer>
<div class="reply-form" id="commentReplyForm1">
<a href="###" class="avatar"><i class="icon-user icon-2x"></i></a>
<form class="form">
<div class="form-group">
<textarea class="form-control new-comment-text" rows="2" placeholder="撰写评论..."></textarea>
</div>
<div class="form-group comment-user">
<div class="row">
<div class="col-md-3">
<span class="pull-right">或者</span>
<a href="#">登录</a> <a href="##">注册</a>
</div>
<div class="col-md-7">
<div class="form-group">
<input type="text" class="form-control" id="nameInputEmail1" placeholder="输入评论显示名称">
</div>
<div class="form-group">
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="输入电子邮件(不会在评论显示)">
</div>
</div>
<div class="col-md-2"><button type="submit" class="btn btn-block btn-primary"><i class="icon-ok"></i></button></div>
</div>
</div>
</form>
</div>
</footer>
</div>
```
## 综合示例
<example style="padding-bottom: 0">
<div class="comments">
<header>
<div class="pull-right"><a href="#commentReplyForm2" class="btn btn-primary"><i class="icon-comment-alt"></i> 发表评论</a></div>
<h3>所有评论</h3>
</header>
<section class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-camera-retro icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">3 个小时前</div>
<div><a href="###"><strong>张士超</strong></a></div>
<div class="text">今天玩的真开心!~~~~~~</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
<div class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-user icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
<div class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-yinyang icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">1 个小时前</div>
<div><a href="###"><strong>门口大爷</strong></a> <span class="text-muted">回复</span> <a href="###">Catouse</a></div>
<div class="text">不在我这儿...</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-cube-alt icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">1 个小时前</div>
<div><a href="###"><strong>队长</strong></a> <span class="text-muted">回复</span> <a href="###">Catouse</a></div>
<div class="text">也不在我这儿...</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
</div>
</div>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-heart-empty icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">30 分钟前</div>
<div><a href="###"><strong>华师大第一美女</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">很开心~~~</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
</div>
</div>
</section>
<footer>
<div class="reply-form" id="commentReplyForm2">
<a href="###" class="avatar"><i class="icon-user icon-2x"></i></a>
<form class="form">
<div class="form-group">
<textarea class="form-control new-comment-text" rows="2" placeholder="撰写评论..."></textarea>
</div>
<div class="form-group comment-user">
<div class="row">
<div class="col-md-3">
<span class="pull-right">或者</span>
<a href="#">登录</a> <a href="##">注册</a>
</div>
<div class="col-md-7">
<div class="form-group">
<input type="text" class="form-control" id="nameInputEmail1" placeholder="输入评论显示名称">
</div>
<div class="form-group">
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="输入电子邮件(不会在评论显示)">
</div>
</div>
<div class="col-md-2"><button type="submit" class="btn btn-block btn-primary"><i class="icon-ok"></i></button></div>
</div>
</div>
</form>
</div>
</footer>
</div>
</example>
<template class="pre-scrollable linenums"/>
```html
<div class="comments">
<header>
<div class="pull-right"><a href="#commentReplyForm2" class="btn btn-primary"><i class="icon-comment-alt"></i> 发表评论</a></div>
<h3>所有评论</h3>
</header>
<section class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-camera-retro icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">3 个小时前</div>
<div><a href="###"><strong>张士超</strong></a></div>
<div class="text">今天玩的真开心!~~~~~~</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
<div class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-user icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">2 个小时前</div>
<div><a href="###"><strong>Catouse</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">你到底把我家钥匙放哪里了...</div>
<div class="actions">
<a href="##">回复</a>
<a href="##">编辑</a>
<a href="##">删除</a>
</div>
</div>
<div class="comments-list">
<div class="comment">
<a href="###" class="avatar">
<i class="icon-yinyang icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">1 个小时前</div>
<div><a href="###"><strong>门口大爷</strong></a> <span class="text-muted">回复</span> <a href="###">Catouse</a></div>
<div class="text">不在我这儿...</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-cube-alt icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">1 个小时前</div>
<div><a href="###"><strong>队长</strong></a> <span class="text-muted">回复</span> <a href="###">Catouse</a></div>
<div class="text">也不在我这儿...</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
</div>
</div>
<div class="comment">
<a href="###" class="avatar">
<i class="icon-heart-empty icon-2x"></i>
</a>
<div class="content">
<div class="pull-right text-muted">30 分钟前</div>
<div><a href="###"><strong>华师大第一美女</strong></a> <span class="text-muted">回复</span> <a href="###">张士超</a></div>
<div class="text">很开心~~~</div>
<div class="actions">
<a href="##">回复</a>
</div>
</div>
</div>
</div>
</div>
</section>
<footer>
<div class="reply-form" id="commentReplyForm2">
<a href="###" class="avatar"><i class="icon-user icon-2x"></i></a>
<form class="form">
<div class="form-group">
<textarea class="form-control new-comment-text" rows="2" placeholder="撰写评论..."></textarea>
</div>
<div class="form-group comment-user">
<div class="row">
<div class="col-md-3">
<span class="pull-right">或者</span>
<a href="#">登录</a> <a href="##">注册</a>
</div>
<div class="col-md-7">
<div class="form-group">
<input type="text" class="form-control" id="nameInputEmail1" placeholder="输入评论显示名称">
</div>
<div class="form-group">
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="输入电子邮件(不会在评论显示)">
</div>
</div>
<div class="col-md-2"><button type="submit" class="btn btn-block btn-primary"><i class="icon-ok"></i></button></div>
</div>
</div>
</form>
</div>
</footer>
</div>
```
| {
"pile_set_name": "Github"
} |
package com.example.xch.generateqrcode;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.util.Hashtable;
public class QRCodeUtil {
/**
* 生成自定义二维码
*
* @param content 字符串内容
* @param width 二维码宽度
* @param height 二维码高度
* @param character_set 编码方式(一般使用UTF-8)
* @param error_correction_level 容错率 L:7% M:15% Q:25% H:35%
* @param margin 空白边距(二维码与边框的空白区域)
* @param color_black 黑色色块
* @param color_white 白色色块
* @param logoBitmap logo图片(传null时不添加logo)
* @param logoPercent logo所占百分比
* @param bitmap_black 用来代替黑色色块的图片(传null时不代替)
* @return
*/
public static Bitmap createQRCodeBitmap(String content, int width, int height, String character_set, String error_correction_level,
String margin, int color_black, int color_white, Bitmap logoBitmap, float logoPercent, Bitmap bitmap_black) {
// 字符串内容判空
if (TextUtils.isEmpty(content)) {
return null;
}
// 宽和高>=0
if (width < 0 || height < 0) {
return null;
}
try {
/** 1.设置二维码相关配置,生成BitMatrix(位矩阵)对象 */
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
// 字符转码格式设置
if (!TextUtils.isEmpty(character_set)) {
hints.put(EncodeHintType.CHARACTER_SET, character_set);
}
// 容错率设置
if (!TextUtils.isEmpty(error_correction_level)) {
hints.put(EncodeHintType.ERROR_CORRECTION, error_correction_level);
}
// 空白边距设置
if (!TextUtils.isEmpty(margin)) {
hints.put(EncodeHintType.MARGIN, margin);
}
/** 2.将配置参数传入到QRCodeWriter的encode方法生成BitMatrix(位矩阵)对象 */
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
/** 3.创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */
if (bitmap_black != null) {
//从当前位图按一定的比例创建一个新的位图
bitmap_black = Bitmap.createScaledBitmap(bitmap_black, width, height, false);
}
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//bitMatrix.get(x,y)方法返回true是黑色色块,false是白色色块
if (bitMatrix.get(x, y)) {// 黑色色块像素设置
if (bitmap_black != null) {//图片不为null,则将黑色色块换为新位图的像素。
pixels[y * width + x] = bitmap_black.getPixel(x, y);
} else {
pixels[y * width + x] = color_black;
}
} else {
pixels[y * width + x] = color_white;// 白色色块像素设置
}
}
}
/** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象 */
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
/** 5.为二维码添加logo图标 */
if (logoBitmap != null) {
return addLogo(bitmap, logoBitmap, logoPercent);
}
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
/**
* 向二维码中间添加logo图片(图片合成)
*
* @param srcBitmap 原图片(生成的简单二维码图片)
* @param logoBitmap logo图片
* @param logoPercent 百分比 (用于调整logo图片在原图片中的显示大小, 取值范围[0,1] )
* 原图片是二维码时,建议使用0.2F,百分比过大可能导致二维码扫描失败。
* @return
*/
@Nullable
private static Bitmap addLogo(@Nullable Bitmap srcBitmap, @Nullable Bitmap logoBitmap, float logoPercent) {
if (srcBitmap == null) {
return null;
}
if (logoBitmap == null) {
return srcBitmap;
}
//传值不合法时使用0.2F
if (logoPercent < 0F || logoPercent > 1F) {
logoPercent = 0.2F;
}
/** 1. 获取原图片和Logo图片各自的宽、高值 */
int srcWidth = srcBitmap.getWidth();
int srcHeight = srcBitmap.getHeight();
int logoWidth = logoBitmap.getWidth();
int logoHeight = logoBitmap.getHeight();
/** 2. 计算画布缩放的宽高比 */
float scaleWidth = srcWidth * logoPercent / logoWidth;
float scaleHeight = srcHeight * logoPercent / logoHeight;
/** 3. 使用Canvas绘制,合成图片 */
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(srcBitmap, 0, 0, null);
canvas.scale(scaleWidth, scaleHeight, srcWidth / 2, srcHeight / 2);
canvas.drawBitmap(logoBitmap, srcWidth / 2 - logoWidth / 2, srcHeight / 2 - logoHeight / 2, null);
return bitmap;
}
}
| {
"pile_set_name": "Github"
} |
package v1alpha1
// ParamSpec defines an arbitrary named input whose value can be supplied by a
// `Param`.
type ParamSpec struct {
// Name declares the name by which a parameter is referenced.
Name string `json:"name"`
// Description is a user-facing description of the parameter that may be
// used to populate a UI.
// +optional
Description string `json:"description,omitempty"`
// Default is the value a parameter takes if no input value via a Param is supplied.
// +optional
Default *string `json:"default,omitempty"`
}
// Param defines a string value to be used for a ParamSpec with the same name.
type Param struct {
Name string `json:"name"`
Value string `json:"value"`
}
| {
"pile_set_name": "Github"
} |
(ns babar.parser-test
(:require [midje.sweet :refer :all]
[babar.parser :refer :all]))
(fact "about programs that are one expression"
(parse "+ 1 2") => 3)
(facts "about ignorning newline as whitespace in expression"
(parse "(+ 1\n 3)") => 4
(parse "+ 1\n 3") => 4)
(facts "about reading babar files"
(parse "read \"./examples/simple.babar\"") => anything
(parse "c") => [:a :b 11])
| {
"pile_set_name": "Github"
} |
package com.alibaba.jvm.sandbox.api.util;
/**
* 数组操作工具类
*
* @author luanjia@taobao.com
* @since {@code sandbox-api:1.0.10}
*/
public class GaArrayUtils {
/**
* 判断数组是否为空
*
* @param array 数组
* @param <T> 数组类型
* @return TRUE:数组为空(null或length==0);FALSE:数组不为空
*/
public static <T> boolean isEmpty(T[] array) {
return null == array
|| array.length == 0;
}
/**
* 判断数组是否不为空
*
* @param array 数组
* @param <T> 数组类型
* @return TRUE:数组不为空;FALSE:数组为空(null或length==0)
*/
public static <T> boolean isNotEmpty(T[] array) {
return !isEmpty(array);
}
/**
* 获取数组长度
*
* @param array 数组
* @param <T> 数组类型
* @return 数组长度(null为0)
*/
public static <T> int getLength(T[] array) {
return isNotEmpty(array)
? array.length
: 0;
}
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of Jitamin.
*
* Copyright (C) Jitamin Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Jitamin\Http\Controllers\Api;
use Jitamin\Foundation\ObjectStorage\ObjectStorageException;
use Jitamin\Policy\ProjectPolicy;
/**
* Project File API controller.
*/
class ProjectFileController extends Controller
{
/**
* Get a file by the id.
*
* @param int $project_id
* @param int $file_id
*
* @return array
*/
public function getProjectFile($project_id, $file_id)
{
ProjectPolicy::getInstance($this->container)->check($this->getClassName(), 'getProjectFile', $project_id);
return $this->projectFileModel->getById($file_id);
}
/**
* Get all tasks for a given project.
*
* @param int $project_id Project id
*
* @return array
*/
public function getAllProjectFiles($project_id)
{
ProjectPolicy::getInstance($this->container)->check($this->getClassName(), 'getAllProjectFiles', $project_id);
return $this->projectFileModel->getAll($project_id);
}
/**
* Download a file by the id.
*
* @param int $project_id
* @param int $file_id
*
* @return array
*/
public function downloadProjectFile($project_id, $file_id)
{
ProjectPolicy::getInstance($this->container)->check($this->getClassName(), 'downloadProjectFile', $project_id);
try {
$file = $this->projectFileModel->getById($file_id);
if (!empty($file)) {
return base64_encode($this->objectStorage->get($file['path']));
}
} catch (ObjectStorageException $e) {
$this->logger->error($e->getMessage());
}
return '';
}
/**
* Handle file upload (base64 encoded content).
*
* @param int $project_id
* @param string $filename
* @param string $blob
*
* @return bool|int
*/
public function createProjectFile($project_id, $filename, $blob)
{
ProjectPolicy::getInstance($this->container)->check($this->getClassName(), 'createProjectFile', $project_id);
try {
return $this->projectFileModel->uploadContent($project_id, $filename, $blob);
} catch (ObjectStorageException $e) {
$this->logger->error(__METHOD__.': '.$e->getMessage());
return false;
}
}
/**
* Remove a file.
*
* @param int $project_id
* @param int $file_id
*
* @return bool
*/
public function removeProjectFile($project_id, $file_id)
{
ProjectPolicy::getInstance($this->container)->check($this->getClassName(), 'removeProjectFile', $project_id);
return $this->projectFileModel->remove($file_id);
}
/**
* Remove all files.
*
* @param int $project_id
*
* @return bool
*/
public function removeAllProjectFiles($project_id)
{
ProjectPolicy::getInstance($this->container)->check($this->getClassName(), 'removeAllProjectFiles', $project_id);
return $this->projectFileModel->removeAll($project_id);
}
}
| {
"pile_set_name": "Github"
} |
package io.swagger.v3.plugin.maven.petstore.petstore.callback;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.callbacks.Callback;
import io.swagger.v3.oas.annotations.callbacks.Callbacks;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
public class SimpleCallbackWithOperationResource {
@Callbacks({
@Callback(
name = "testCallback1",
operation = @Operation(
operationId = "getAllReviews",
summary = "get all the reviews",
method = "get",
responses = @ApiResponse(
responseCode = "200",
description = "successful operation",
content = @Content(
mediaType = "application/json",
schema = @Schema(
type = "integer",
format = "int32")))),
callbackUrlExpression = "http://www.url.com")
})
@Operation(
summary = "Simple get operation",
operationId = "getWithNoParameters",
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!")
})
@GET
@Path("/simplecallback")
public String simpleGet() {
return null;
}
}
| {
"pile_set_name": "Github"
} |
/*
* This file is part of Mockey, a tool for testing application
* interactions over HTTP, with a focus on testing web services,
* specifically web applications that consume XML, JSON, and HTML.
*
* Copyright (C) 2009-2010 Authors:
*
* chad.lafontaine (chad.lafontaine AT gmail DOT com)
* neil.cronin (neil AT rackle DOT com)
* lorin.kobashigawa (lkb AT kgawa DOT com)
* rob.meyer (rob AT bigdis DOT com)
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package com.mockey.ui;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.mockey.ServiceValidator;
import com.mockey.model.Service;
import com.mockey.model.Url;
import com.mockey.plugin.IRequestInspector;
import com.mockey.plugin.PluginStore;
import com.mockey.storage.IMockeyStorage;
import com.mockey.storage.StorageRegistry;
public class ServiceSetupServlet extends HttpServlet {
private static final long serialVersionUID = 5503460488900643184L;
private static IMockeyStorage store = StorageRegistry.MockeyStorage;
private static final Boolean TRANSIENT_STATE = new Boolean(true);
private static final String DATE_FORMAT = "MM/dd/yyyy";
private static final SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
private static Logger logger = Logger.getLogger(ServiceSetupServlet.class);
/**
*
*/
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("all") != null && req.getParameter("responseType") != null) {
List<Service> services = store.getServices();
// #1. Get a handle of the original read-only-mode (transient?)
Boolean origReadOnlyMode = store.getReadOnlyMode();
try {
// #2. Put the store in TRANSIENT STATE (memory only)
// why? To prevent repeating file writes to the file system
store.setReadOnlyMode(TRANSIENT_STATE);
int serviceResponseType = Integer.parseInt(req.getParameter("responseType"));
for (Iterator<Service> iterator = services.iterator(); iterator.hasNext();) {
Service service = iterator.next();
service.setServiceResponseType(serviceResponseType);
store.saveOrUpdateService(service);
}
} catch (Exception e) {
logger.error("Unable to update service(s", e);
}
// #3 Return store back to original setting.
store.setReadOnlyMode(origReadOnlyMode);
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
Map<String, String> successMessage = new HashMap<String, String>();
successMessage.put("success", "updated");
String resultingJSON = Util.getJSON(successMessage);
out.println(resultingJSON);
out.flush();
out.close();
return;
}
Long serviceId = null;
try {
serviceId = new Long(req.getParameter("serviceId"));
} catch (Exception e) {
// Do nothing
}
if (req.getParameter("deleteService") != null && serviceId != null) {
Service service = store.getServiceById(serviceId);
store.deleteService(service);
store.deleteFulfilledClientRequestsForService(serviceId);
Util.saveSuccessMessage("Service '" + service.getServiceName() + "' was deleted.", req);
// Check to see if any plans need an update.
String errorMessage = null;
if (service.isReferencedInAServicePlan()) {
errorMessage = "Warning: the deleted service is referenced in service plans.";
}
if (errorMessage != null) {
Util.saveErrorMessage(errorMessage, req);
}
resp.sendRedirect(Url.getAbsoluteURL(req, "/home"));
return;
} else if (req.getParameter("duplicateService") != null && serviceId != null) {
Service service = store.getServiceById(serviceId);
Service duplicateService = store.duplicateService(service);
resp.sendRedirect(Url.getAbsoluteURL(req, "/setup?serviceId=" + duplicateService.getId()));
return;
}
super.service(req, resp);
}
/**
*
*
* @param req
* basic request
* @param resp
* basic resp
* @throws ServletException
* basic
* @throws IOException
* basic
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Long serviceId = null;
try {
serviceId = new Long(req.getParameter("serviceId"));
} catch (Exception e) {
// Do nothing
}
Service service = null;
if (serviceId != null) {
service = store.getServiceById(serviceId);
}
if (service == null) {
service = new Service();
}
req.setAttribute("mockservice", service);
req.setAttribute("requestInspectorList", PluginStore.getInstance().getRequestInspectorImplClassList());
RequestDispatcher dispatch = req.getRequestDispatcher("/service_setup.jsp");
dispatch.forward(req, resp);
}
/**
*
*
* @param req
* basic request
* @param resp
* basic resp
* @throws ServletException
* basic
* @throws IOException
* basic
*/
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String[] realSrvUrl = req.getParameterValues("realServiceUrl[]");
Service service = new Service();
Long serviceId = null;
// ************************************************
// HACK A: if renaming an existing Service Name, then
// we need to update this Service's Name in a
// Service Plan.
// ************************************************
String oldName = null;
String newName = null;
try {
serviceId = new Long(req.getParameter("serviceId"));
service = store.getServiceById(serviceId);
oldName = service.getServiceName();
} catch (Exception e) {
// Do nothing
}
if (service == null) {
service = new Service();
}
// NEW REAL URL LIST
// 1. Overwrite list of predefined URLs
// 2. Ensure non-empty trim String for new Url objects.
if (realSrvUrl != null) {
List<Url> newUrlList = new ArrayList<Url>();
for (int i = 0; i < realSrvUrl.length; i++) {
String url = realSrvUrl[i];
if (url.trim().length() > 0) {
newUrlList.add(new Url(realSrvUrl[i].trim()));
}
}
// Before we ADD new URLS, let's start with a clean list.
// Why? In case the user removes the URL within the form,
// then it will be an 'empty' value.
service.clearRealServiceUrls();
// Now we add.
for (Url urlItem : newUrlList) {
service.saveOrUpdateRealServiceUrl(urlItem);
}
}
// UPDATE HANGTIME - optional
try {
service.setHangTime(Integer.parseInt(req.getParameter("hangTime")));
} catch (Exception e) {
// DO NOTHING
}
// NAME - optional
if (req.getParameter("serviceName") != null) {
service.setServiceName(req.getParameter("serviceName"));
newName = service.getServiceName();
}
// TAG - optional
if (req.getParameter("tag") != null) {
service.setTag(req.getParameter("tag"));
}
// REQUEST INSPECTION rules in JSON format. - optional
if (req.getParameter("requestInspectorJsonRules") != null) {
service.setRequestInspectorJsonRules(req.getParameter("requestInspectorJsonRules").trim());
}
// REQUEST INSPECTION enable flag - optional
if (req.getParameter("requestInspectorJsonRulesEnableFlag") != null) {
try {
service.setRequestInspectorJsonRulesEnableFlag(
new Boolean(req.getParameter("requestInspectorJsonRulesEnableFlag")).booleanValue());
} catch (Exception e) {
logger.error("Json Rule Enable flag has an invalid format.", e);
}
}
// REQUEST SCHEMA rules in JSON format. - optional
if (req.getParameter("responseSchema") != null) {
service.setResponseSchema(req.getParameter("responseSchema").trim());
}
// RESPONSE SCHEMA enable flag - optional
if (req.getParameter("responseSchemaEnableFlag") != null) {
try {
service.setResponseSchemaFlag(new Boolean(req.getParameter("responseSchemaEnableFlag")).booleanValue());
} catch (Exception e) {
logger.error("Json Rule Enable flag has an invalid format.", e);
}
}
// Last visit
if (req.getParameter("lastVisit") != null) {
try {
String lastvisit = req.getParameter("lastVisit");
if (lastvisit.trim().length() > 0 && !"mm/dd/yyyy".equals(lastvisit.trim().toLowerCase())) {
Date f = formatter.parse(lastvisit);
service.setLastVisit(f.getTime());
} else {
service.setLastVisit(null);
}
} catch (Exception e) {
logger.error("Last visit has an invalid format. Should be " + DATE_FORMAT, e);
}
}
String classNameForRequestInspector = req.getParameter("requestInspectorName");
if (classNameForRequestInspector != null && classNameForRequestInspector.trim().length() > 0) {
/**
* OPTIONAL See if we can create an instance of a request inspector.
* If yes, then set the service to the name.
*/
try {
Class<?> clazz = Class.forName(classNameForRequestInspector);
if (!clazz.isInterface() && IRequestInspector.class.isAssignableFrom(clazz)) {
service.setRequestInspectorName(classNameForRequestInspector);
} else {
service.setRequestInspectorName("");
}
} catch (ClassNotFoundException t) {
logger.error("Service setup: unable to find class '" + classNameForRequestInspector + "'", t);
}
}
// DESCRIPTION - optional
if (req.getParameter("description") != null) {
service.setDescription(req.getParameter("description"));
}
// MOCK URL - optional
if (req.getParameter("url") != null) {
service.setUrl(req.getParameter("url"));
}
Map<String, String> errorMap = ServiceValidator.validate(service);
if ((errorMap != null) && (errorMap.size() == 0)) {
// no errors, so create service.
Service updatedService = store.saveOrUpdateService(service);
Util.saveSuccessMessage("Service updated.", req);
// ***************** HACK A ****************
if (newName != null && oldName != null && !oldName.trim().equals(newName.trim())) {
// OK, we had an existing Service Scenario with a name change.
// Let's update the appropriate Service Plan.
store.updateServicePlansWithNewServiceName(oldName, newName);
}
// *****************************************
String redirectUrl = Url.getAbsoluteURL(req, "/setup?serviceId=" + updatedService.getId());
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String resultingJSON = "{ \"result\": { \"redirect\": \"" + redirectUrl + "\"}}";
out.println(resultingJSON);
out.flush();
out.close();
return;
} else {
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String resultingJSON = Util.getJSON(errorMap);
out.println(resultingJSON);
out.flush();
out.close();
}
return;
// AJAX thing. Return nothing at this time.
}
}
| {
"pile_set_name": "Github"
} |
/*
* code-forensics
* Copyright (C) 2016-2019 Silvio Montanari
* Distributed under the GNU General Public License v3.0
* see http://www.gnu.org/licenses/gpl.html
*/
var _ = require('lodash');
var Model = require('../diagrams/treemap/diagram_model.js'),
LayoutAdapter = require('../diagrams/treemap/treemap_layout_adapter.js'),
ColorScaleFactory = require('../utils/color_scale_factory.js'),
ZoomHandler = require('../diagrams/treemap/zoom_handler.js'),
widgets = require('../widgets/index.js');
var nodeNames = function(series) {
return _.sortBy(_.uniq(_.map(
_.filter(series, function(node) { return !node.children; }),
function(node) { return node.data.name; })
));
};
module.exports = function(manifest) {
var diagramConfig = function() {
return {
Model: Model,
layoutAdapter: new LayoutAdapter({ width: 1000, height: 650, valueProperty: 'revisions' }),
graphHandlers: [new ZoomHandler()],
configuration: {
style: {
cssClass: 'treemap-diagram',
width: 1000,
height: 650,
margin: { top: 24, right: 0, bottom: 0, left: 0 }
},
colorScaleFactory: function(series) {
return ColorScaleFactory.sequentialRainbow(nodeNames(series));
},
series: { valueProperty: 'revisions' }
},
controls: {
widgets: {
colorMap: {
instance: new widgets.ColorMap(),
group: 'colorMap',
dataTransform: nodeNames
}
}
}
};
};
return {
metadata: {
title: 'Developer effort analysis',
description: 'effort distribution (revisions) between programmers/teams',
diagramSelectionTitle: 'Effort distribution',
dateRange: manifest.parseDateRange()
},
graphModels: manifest.selectAvailableGraphs([
{
id: 'individual-effort',
diagramName: 'individual-effort',
label: 'By developer',
dataFile: _.find(manifest.dataFiles, { fileType: 'individual-effort' }),
controlTemplates: {
widgets: [
{ name: 'colorMapWidgetTemplate', data: { labels: ['Developers'] } }
]
},
diagram: diagramConfig()
},
{
id: 'team-effort',
diagramName: 'team-effort',
label: 'By team',
dataFile: _.find(manifest.dataFiles, { fileType: 'team-effort' }),
controlTemplates: {
widgets: [
{ name: 'colorMapWidgetTemplate', data: { labels: ['Teams'] } }
]
},
diagram: diagramConfig()
}
])
};
};
| {
"pile_set_name": "Github"
} |
# 如何使用这个库
原先想的是只介绍一下原理,但是有的同学好像看了之后还不会使用。因此,接入了jitpack以便使用。
Add it in your root build.gradle at the end of repositories:
```
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
```
Step 2. Add the dependency
```
dependencies {
implementation 'com.github.Guolei1130:android_p_no_sdkapi_support:0.1.1'
}
```
### 用法
1. 可以用PCompat#compat(Class reflectionHelperClz) 将所有的反射操作,用reflectionHelperClz这个类去执行即可
2. 可以用PCompat#useDefaultReflectHelperClass 所有的反射操作,用ReflectHelper去操作j也可以
[Android P 调用隐藏API限制原理](https://mp.weixin.qq.com/s/sktB0x5yBexkn4ORQ1YofA)
[突破Android P(Preview 1)对调用隐藏API限制的方法](https://mp.weixin.qq.com/s/4k3DBlxlSO2xNNKqjqUdaQ)
[java_lang_Class.cc](https://android.googlesource.com/platform/art/+/android-9.0.0_r5/runtime/native/java_lang_Class.cc)
### 前言
Android P对非SDK API的使用做了限制,导致在Android P上会出现一些状况。在很早前预览版本刚出来的时候,360团队就出了两篇文章。
[Android P 调用隐藏API限制原理](https://mp.weixin.qq.com/s/sktB0x5yBexkn4ORQ1YofA) 以及
[突破Android P(Preview 1)对调用隐藏API限制的方法](https://mp.weixin.qq.com/s/4k3DBlxlSO2xNNKqjqUdaQ)
限制方式三种:
* 反射
* 直接调用
* jni调用
这一篇文章就是根据上面的文章来的。
### 方法一(不建议)
使用Provided(CompileOnly)的方式去解决调用限制,只能解决反射调用的问题,而无法解决直接调用或者jni调用的方式。不建议使用
### 方法二(不建议)
这个方法二对应的是360文章中的方法三。主要代码如下。
```
class ObjPtr {
public:
uintptr_t reference_;
};
ObjPtr
(*sys_GetDeclaredMethodInternal)(void *self, jobject kclass, jstring name, jobjectArray args);
void *(*executableGetArtMethod)(void *ex);
ObjPtr myGetDeclaredMethodInternal(void *self, jobject kclass, jstring name, jobjectArray args) {
ObjPtr res = sys_GetDeclaredMethodInternal(self, kclass, name, args);
if (res.reference_ != 0) {
void *pMethod = executableGetArtMethod((void *) (res.reference_));
reinterpret_cast<uint32_t *>(pMethod)[1] &= 0xcfffffff;
}
return res;
}
extern "C" int hookForPMethod() {
void *libc = fake_dlopen("/system/lib/libart.so", RTLD_NOW);
if (libc != NULL) {
void *p = fake_dlsym(libc, "_ZN3art6mirror5Class25GetDeclaredMethodInternalILNS_11Poin"
"terSizeE4ELb0EEENS_6ObjPtrINS0_6MethodEEEPNS_6ThreadENS4_IS1_EENS4_INS0_6StringEEEN"
"S4_INS0_11ObjectArrayIS1_EEEE");
if (p != NULL) {
MSHookFunction(p,
reinterpret_cast<void *>(myGetDeclaredMethodInternal),
reinterpret_cast<void **>(&sys_GetDeclaredMethodInternal));
}
*(void **) (&executableGetArtMethod) =
fake_dlsym(libc, "_ZN3art6mirror10Executable12GetArtMethodEv");
fake_dlclose(libc);
} //if
return 1;
}
```
其中,fake_dlopen、fake_dlsym 使用的是[Nougat_dlfunctions](https://github.com/Guolei1130/Nougat_dlfunctions),主要是Android 7.0以上对dlopen、dlsym等函数做了限制。因此用这个库。而MSHookFunction,则是大名鼎鼎的[cydiasubstrate](http://www.cydiasubstrate.com/)。

上面的代码只解决了反射方法的问题。我按照这种思路去解决字段问题的时候发现。


GetDeclaredField是inline的,无法切入。而CreateFromArtField又是hidden的,也不好切入。

因此,放弃了这种方法。
### 方法三(可用,但是有更好的)
这里对应的方法三,对应的是360文章中的方法二,也就是修改classloader的方式。代码如下。
```
void (*setClassLoader)(void *pClass, void *new_cl);
ObjPtr (*toClass)(jclass global_jclss);
extern "C" void makeHiddenApiAccessable(JNIEnv *env) {
void *libart = fake_dlopen("/system/lib/libart.so", RTLD_NOW);
if (libart != NULL) {
*(void **) (&toClass) = fake_dlsym(libart, "_ZN3art16WellKnownClasses7ToClassEP7_jclass");
*(void **) (&setClassLoader) =
fake_dlsym(libart, "_ZN3art6mirror5Class14SetClassLoaderENS_6ObjPtrINS0_11ClassLoaderEEE");
jclass cls = env->FindClass("com/example/support_p/ReflectionHelper");
ObjPtr op = toClass(cls);
setClassLoader((void *) op.reference_, NULL);
}
}
```
没错,代码就是这么点。这样,我们就可以在ReflectionHelper中调用非公开API了。但是这里会依赖Nougat_dlfunctions这个库。


### 方法四(超级好)
既然是修改classloader,那么我们为什么不在java层修改呢。代码如下。
```
private void testJavaPojie() {
try {
Class reflectionHelperClz = Class.forName("com.example.support_p.ReflectionHelper");
Class classClz = Class.class;
Field classLoaderField = classClz.getDeclaredField("classLoader");
classLoaderField.setAccessible(true);
classLoaderField.set(reflectionHelperClz, null);
} catch (Exception e) {
e.printStackTrace();
}
}
```
而这里用的相关反射只是light级别的,没有什么影响。反而代码量超小,也不依赖其他。
### 方法五(超级好+1)
这个方案来自 @区长 大神
方法四还是存在一点问题。如果以后把classloader加入到深灰或者黑名单,那就僵硬了。所以,我们不用反射,直接用unsafe去修改。代码这就不贴了。为了得到classloader的偏移量,我们写一个和Class结构一样的类,用这个类得到的classLoader的偏移量和Class是一样的。
补充:
### 方法6
[田维术](https://zhuanlan.zhihu.com/p/59455212)
VMRuntime.setHiddenApiExemptions 方法
### 注意:
如果我们用修改ClassLoader的方式的话,那么ReflectionHelper类中只能反射调用非公开API,注意了。
[代码在这里,觉得好的给个star吧](https://github.com/Guolei1130/android_p_no_sdkapi_support)
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2017-2020 original 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
*
* https://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.micronaut.docs.function.client.aws;
import io.micronaut.context.annotation.Requires;
//tag::imports[]
import io.micronaut.function.FunctionBean;
import java.util.function.Function;
//end::imports[]
@Requires(property = "spec.name", value = "IsbnValidationSpec")
//tag::clazz[]
@FunctionBean("isbn-validator")
public class IsbnValidatorFunction implements Function<IsbnValidationRequest, IsbnValidationResponse> {
@Override
public IsbnValidationResponse apply(IsbnValidationRequest request) {
return new IsbnValidationResponse();
}
}
//end::clazz[] | {
"pile_set_name": "Github"
} |
/******************************************************************************
Copyright:: 2020- IBM, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*****************************************************************************/
import { Rule, RuleResult, RuleFail, RuleContext, RulePotential, RuleManual, RulePass } from "../../../api/IEngine";
import { RPTUtil } from "../util/legacy";
let a11yRulesFieldset: Rule[] = [
{
/**
* Description: Trigger if fieldset is missing a legend
* Origin: WCAG 2.0 Technique H71
*/
id: "WCAG20_Fieldset_HasLegend",
context: "dom:fieldset",
run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => {
const ruleContext = context["dom"].node as Element;
// In the case a legend is hidden, we should still trigger a violations for this
let legends = RPTUtil.getChildByTagHidden(ruleContext, "legend", true, false);
if (legends.length === 0) {
// Fieldset has NO Legend
return RuleFail("Fail_1");
} else if (legends.length > 1) {
// Fieldset has more than one legend
return RuleFail("Fail_2");
} else if (RPTUtil.getInnerText(legends[0]).trim().length === 0) {
// Fieldset has legend but legend is empty
return RuleFail("Fail_3");
} else {
return RulePass("Pass_0");
}
}
}
]
export { a11yRulesFieldset } | {
"pile_set_name": "Github"
} |
package com.venusic.handwrite.view.point;
/**
* @version 1.0
* @auth wastrel
* @date 2018/1/3 9:46
* @copyRight 四川金信石信息技术有限公司
* @since 1.0
*/
public class TimedPoint {
public float x;
public float y;
public long timestamp;
public TimedPoint(float x, float y) {
this.x = x;
this.y = y;
this.timestamp = System.currentTimeMillis();
}
public TimedPoint set(float x, float y) {
this.x = x;
this.y = y;
this.timestamp = System.currentTimeMillis();
return this;
}
public float distanceTo(TimedPoint point) {
return (float) Math.sqrt(Math.pow(point.x - x, 2) + Math.pow(point.y - y, 2));
}
public float velocityTo(TimedPoint point) {
long t = point.timestamp - timestamp;
if (t == 0) return 0;
else return distanceTo(point) / t;
}
}
| {
"pile_set_name": "Github"
} |
require 'yaks'
require 'yaks-html'
require 'yaks-sinatra'
require 'yaks-transit'
require 'rspec/core/rake_task'
require 'rubocop/rake_task'
require 'rubygems/package_task'
require 'yard'
def delegate_task(gem, task_name)
task task_name do
chdir gem.to_s do
sh "rake", task_name.to_s
end
end
end
[:yaks, :"yaks-html", :"yaks-sinatra"].each do |gem|
namespace gem do
desc 'Run rspec'
delegate_task gem, :rspec
desc 'Build gem'
delegate_task gem, :gem
desc 'Generate YARD docs'
delegate_task gem, :yard
desc 'push gem to rubygems'
task :push => "#{gem}:gem" do
sh "gem push pkg/#{gem}-#{Yaks::VERSION}.gem"
end
end
end
desc "Tag current release and push to Github"
task :tag do
sh "git tag v#{Yaks::VERSION}"
sh "git push --tags"
end
desc "Tag, build, and push all gems to rubygems.org"
task :push_all => [
:tag,
"yaks:gem",
"yaks-html:gem",
"yaks-sinatra:gem",
"yaks:push",
"yaks-html:push",
"yaks-sinatra:push"
]
task :push => :push_all
desc "Run all the tests"
task :rspec => ["yaks:rspec", "yaks-html:rspec", "yaks-sinatra:rspec"]
desc 'Run mutation tests'
delegate_task :yaks, :mutant
desc "Start a console"
task :console do
require 'irb'
require 'irb/completion'
ARGV.clear
IRB.start
end
task :ataru do
require "ataru"
Dir.chdir("yaks")
Ataru::CLI::Application.start(["check", "README.md"])
end
RuboCop::RakeTask.new do |task|
task.options << '--display-cop-names'
end
task :default => [:rspec, :rubocop]
| {
"pile_set_name": "Github"
} |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package stats
import (
"fmt"
"testing"
"rsc.io/benchstat/internal/go-moremath/internal/mathtest"
"rsc.io/benchstat/internal/go-moremath/vec"
)
var aeq = mathtest.Aeq
var testFunc = mathtest.WantFunc
func testDiscreteCDF(t *testing.T, name string, dist DiscreteDist) {
// Build the expected CDF out of the PMF.
l, h := dist.Bounds()
s := dist.Step()
want := map[float64]float64{l - 0.1: 0, h: 1}
sum := 0.0
for x := l; x < h; x += s {
sum += dist.PMF(x)
want[x] = sum
want[x+s/2] = sum
}
testFunc(t, name, dist.CDF, want)
}
func testInvCDF(t *testing.T, dist Dist, bounded bool) {
inv := InvCDF(dist)
name := fmt.Sprintf("InvCDF(%+v)", dist)
cdfName := fmt.Sprintf("CDF(%+v)", dist)
// Test bounds.
vals := map[float64]float64{-0.01: nan, 1.01: nan}
if !bounded {
vals[0] = -inf
vals[1] = inf
}
testFunc(t, name, inv, vals)
if bounded {
lo, hi := inv(0), inv(1)
vals := map[float64]float64{
lo - 0.01: 0, lo: 0,
hi: 1, hi + 0.01: 1,
}
testFunc(t, cdfName, dist.CDF, vals)
if got := dist.CDF(lo + 0.01); !(got > 0) {
t.Errorf("%s(0)=%v, but %s(%v)=0", name, lo, cdfName, lo+0.01)
}
if got := dist.CDF(hi - 0.01); !(got < 1) {
t.Errorf("%s(1)=%v, but %s(%v)=1", name, hi, cdfName, hi-0.01)
}
}
// Test points between.
vals = map[float64]float64{}
for _, p := range vec.Linspace(0, 1, 11) {
if p == 0 || p == 1 {
continue
}
x := inv(p)
vals[x] = x
}
testFunc(t, fmt.Sprintf("InvCDF(CDF(%+v))", dist),
func(x float64) float64 {
return inv(dist.CDF(x))
},
vals)
}
| {
"pile_set_name": "Github"
} |
/*
* Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
* Copyright (C) 2013 - Scilab Enterprises - Cedric Delamarre
*
* Copyright (C) 2012 - 2016 - Scilab Enterprises
*
* This file is hereby licensed under the terms of the GNU GPL v2.0,
* pursuant to article 5.3.4 of the CeCILL v.2.1.
* This file was originally licensed under the terms of the CeCILL v2.1,
* and continues to be available under such terms.
* For more information, see the COPYING file which you should have received
* along with this program.
*
*/
#ifndef __COMMOM_STRUCTURE_OPTIMIZATION_H__
#define __COMMOM_STRUCTURE_OPTIMIZATION_H__
#include "machine.h"
#include "dynlib_optimization.h"
typedef struct
{
int nizs, nrzs, ndzs;
} STR_NIRD;
typedef struct
{
double u1;
int nc;
} STR_FPRF2C;
typedef struct
{
char nomsub[80];
} STR_OPTIM;
typedef struct {
double t0, tf, dti, dtf, ermx;
int iu[5], nuc, nuv, ilin, nti, ntf, ny, nea, itmx, nex,
nob, ntob, ntobi, nitu, ndtu;
} STR_ICSEZ;
#ifdef _MSC_VER
OPTIMIZATION_IMPEXP STR_NIRD C2F(nird);
OPTIMIZATION_IMPEXP STR_FPRF2C C2F(fprf2c);
OPTIMIZATION_IMPEXP STR_OPTIM C2F(optim);
OPTIMIZATION_IMPEXP STR_ICSEZ C2F(icsez);
#else
#ifndef __OPTIMIZATION_GW_HXX__
extern STR_NIRD C2F(nird);
extern STR_FPRF2C C2F(fprf2c);
extern STR_OPTIM C2F(optim);
extern STR_ICSEZ C2F(icsez);
#else
STR_NIRD C2F(nird);
STR_FPRF2C C2F(fprf2c);
STR_OPTIM C2F(optim);
STR_ICSEZ C2F(icsez);
#endif
#endif
#endif /* !__COMMOM_STRUCTURE_OPTIMIZATION_H__ */
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1998, 2001, 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.
*/
/***
*** THIS IMPLEMENTS ONLY THE OBSOLETE java.awt.Event CLASS! SEE
*** awt_AWTEvent.[ch] FOR THE NEWER EVENT CLASSES.
***
***/
#ifdef HEADLESS
#error This file should not be included in headless library
#endif
#include "java_awt_Event.h"
#include "jni_util.h"
#include "awt_Event.h"
struct EventIDs eventIDs;
JNIEXPORT void JNICALL
Java_java_awt_Event_initIDs(JNIEnv *env, jclass cls)
{
CHECK_NULL(eventIDs.data = (*env)->GetFieldID(env, cls, "data", "J"));
CHECK_NULL(eventIDs.consumed = (*env)->GetFieldID(env, cls, "consumed", "Z"));
CHECK_NULL(eventIDs.id = (*env)->GetFieldID(env, cls, "id", "I"));
}
| {
"pile_set_name": "Github"
} |
---
title: Các phiên bản được hỗ trợ của tài liệu Kubernetes
content_type: concept
card:
name: about
weight: 10
title: Các phiên bản được hỗ trợ của tài liệu Kubernetes
---
<!-- overview -->
Trang web này lưu tài liệu của phiên bản hiện tại và bốn phiên bản trước của Kubernetes.
<!-- body -->
## Phiên bản hiện tại
Phiên bản hiện tại là
[{{< param "version" >}}](/).
## Các phiên bản trước
{{< versions-other >}}
| {
"pile_set_name": "Github"
} |
/**
* This method invokes `interceptor` and returns `value`. The interceptor is
* bound to `thisArg` and invoked with one argument; (value). The purpose of
* this method is to "tap into" a method chain in order to perform operations
* on intermediate results within the chain.
*
* @static
* @memberOf _
* @category Chain
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @param {*} [thisArg] The `this` binding of `interceptor`.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
*/
function tap(value, interceptor, thisArg) {
interceptor.call(thisArg, value);
return value;
}
module.exports = tap;
| {
"pile_set_name": "Github"
} |
! RUN: %S/test_errors.sh %s %t %f18
! C711 An assumed-type actual argument that corresponds to an assumed-rank
! dummy argument shall be assumed-shape or assumed-rank.
subroutine s(arg1, arg2, arg3)
type(*), dimension(..) :: arg1 ! assumed rank
type(*), dimension(:) :: arg2 ! assumed shape
type(*) :: arg3
call inner(arg1) ! OK, assumed rank
call inner(arg2) ! OK, assumed shape
!ERROR: Assumed-type 'arg3' must be either assumed shape or assumed rank to be associated with assumed-type dummy argument 'dummy='
call inner(arg3)
contains
subroutine inner(dummy)
type(*), dimension(..) :: dummy
end subroutine inner
end subroutine s
| {
"pile_set_name": "Github"
} |
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2020 iText Group NV
Authors: Bruno Lowagie, Paulo Soares, et al.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: sales@itextpdf.com
*/
package com.itextpdf.styledxmlparser.css.selector;
import java.util.Comparator;
/**
* Comparator class for CSS Selectors.
*/
public class CssSelectorComparator implements Comparator<ICssSelector> {
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(ICssSelector o1, ICssSelector o2) {
return o1.calculateSpecificity() - o2.calculateSpecificity();
}
}
| {
"pile_set_name": "Github"
} |
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next closest element that is less than that element.
//
// 3. We did not find the exact element, and there is no next-closest
// element which is less than the one we are searching for, so we
// return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
}
else if (cmp > 0) {
// aHaystack[mid] is greater than our needle.
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
// We did not find an exact match, return the next closest one
// (termination case 2).
return mid;
}
else {
// aHaystack[mid] is less than our needle.
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (2) or (3) and return the appropriate thing.
return aLow < 0 ? -1 : aLow;
}
}
/**
* This is an implementation of binary search which will always try and return
* the index of next lowest value checked if there is no exact hit. This is
* because mappings between original and generated line/col pairs are single
* points, and there is an implicit region between each of them, so a miss
* just means that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
*/
exports.search = function search(aNeedle, aHaystack, aCompare) {
if (aHaystack.length === 0) {
return -1;
}
return recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
};
});
| {
"pile_set_name": "Github"
} |
post_install(){
libtool --finish /usr/lib > /dev/null
}
post_upgrade(){
post_install
}
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0+
/*
* (C) Copyright 2015 Miao Yan <yanmiaobest@gmail.com>
*/
#include <common.h>
#include <command.h>
#include <errno.h>
#include <malloc.h>
#include <qfw.h>
#include <asm/io.h>
#ifdef CONFIG_GENERATE_ACPI_TABLE
#include <asm/tables.h>
#endif
#include <linux/list.h>
static bool fwcfg_present;
static bool fwcfg_dma_present;
static struct fw_cfg_arch_ops *fwcfg_arch_ops;
static LIST_HEAD(fw_list);
#ifdef CONFIG_GENERATE_ACPI_TABLE
/*
* This function allocates memory for ACPI tables
*
* @entry : BIOS linker command entry which tells where to allocate memory
* (either high memory or low memory)
* @addr : The address that should be used for low memory allcation. If the
* memory allocation request is 'ZONE_HIGH' then this parameter will
* be ignored.
* @return: 0 on success, or negative value on failure
*/
static int bios_linker_allocate(struct bios_linker_entry *entry, ulong *addr)
{
uint32_t size, align;
struct fw_file *file;
unsigned long aligned_addr;
align = le32_to_cpu(entry->alloc.align);
/* align must be power of 2 */
if (align & (align - 1)) {
printf("error: wrong alignment %u\n", align);
return -EINVAL;
}
file = qemu_fwcfg_find_file(entry->alloc.file);
if (!file) {
printf("error: can't find file %s\n", entry->alloc.file);
return -ENOENT;
}
size = be32_to_cpu(file->cfg.size);
/*
* ZONE_HIGH means we need to allocate from high memory, since
* malloc space is already at the end of RAM, so we directly use it.
* If allocation zone is ZONE_FSEG, then we use the 'addr' passed
* in which is low memory
*/
if (entry->alloc.zone == BIOS_LINKER_LOADER_ALLOC_ZONE_HIGH) {
aligned_addr = (unsigned long)memalign(align, size);
if (!aligned_addr) {
printf("error: allocating resource\n");
return -ENOMEM;
}
} else if (entry->alloc.zone == BIOS_LINKER_LOADER_ALLOC_ZONE_FSEG) {
aligned_addr = ALIGN(*addr, align);
} else {
printf("error: invalid allocation zone\n");
return -EINVAL;
}
debug("bios_linker_allocate: allocate file %s, size %u, zone %d, align %u, addr 0x%lx\n",
file->cfg.name, size, entry->alloc.zone, align, aligned_addr);
qemu_fwcfg_read_entry(be16_to_cpu(file->cfg.select),
size, (void *)aligned_addr);
file->addr = aligned_addr;
/* adjust address for low memory allocation */
if (entry->alloc.zone == BIOS_LINKER_LOADER_ALLOC_ZONE_FSEG)
*addr = (aligned_addr + size);
return 0;
}
/*
* This function patches ACPI tables previously loaded
* by bios_linker_allocate()
*
* @entry : BIOS linker command entry which tells how to patch
* ACPI tables
* @return: 0 on success, or negative value on failure
*/
static int bios_linker_add_pointer(struct bios_linker_entry *entry)
{
struct fw_file *dest, *src;
uint32_t offset = le32_to_cpu(entry->pointer.offset);
uint64_t pointer = 0;
dest = qemu_fwcfg_find_file(entry->pointer.dest_file);
if (!dest || !dest->addr)
return -ENOENT;
src = qemu_fwcfg_find_file(entry->pointer.src_file);
if (!src || !src->addr)
return -ENOENT;
debug("bios_linker_add_pointer: dest->addr 0x%lx, src->addr 0x%lx, offset 0x%x size %u, 0x%llx\n",
dest->addr, src->addr, offset, entry->pointer.size, pointer);
memcpy(&pointer, (char *)dest->addr + offset, entry->pointer.size);
pointer = le64_to_cpu(pointer);
pointer += (unsigned long)src->addr;
pointer = cpu_to_le64(pointer);
memcpy((char *)dest->addr + offset, &pointer, entry->pointer.size);
return 0;
}
/*
* This function updates checksum fields of ACPI tables previously loaded
* by bios_linker_allocate()
*
* @entry : BIOS linker command entry which tells where to update ACPI table
* checksums
* @return: 0 on success, or negative value on failure
*/
static int bios_linker_add_checksum(struct bios_linker_entry *entry)
{
struct fw_file *file;
uint8_t *data, cksum = 0;
uint8_t *cksum_start;
file = qemu_fwcfg_find_file(entry->cksum.file);
if (!file || !file->addr)
return -ENOENT;
data = (uint8_t *)(file->addr + le32_to_cpu(entry->cksum.offset));
cksum_start = (uint8_t *)(file->addr + le32_to_cpu(entry->cksum.start));
cksum = table_compute_checksum(cksum_start,
le32_to_cpu(entry->cksum.length));
*data = cksum;
return 0;
}
/* This function loads and patches ACPI tables provided by QEMU */
ulong write_acpi_tables(ulong addr)
{
int i, ret = 0;
struct fw_file *file;
struct bios_linker_entry *table_loader;
struct bios_linker_entry *entry;
uint32_t size;
/* make sure fw_list is loaded */
ret = qemu_fwcfg_read_firmware_list();
if (ret) {
printf("error: can't read firmware file list\n");
return addr;
}
file = qemu_fwcfg_find_file("etc/table-loader");
if (!file) {
printf("error: can't find etc/table-loader\n");
return addr;
}
size = be32_to_cpu(file->cfg.size);
if ((size % sizeof(*entry)) != 0) {
printf("error: table-loader maybe corrupted\n");
return addr;
}
table_loader = malloc(size);
if (!table_loader) {
printf("error: no memory for table-loader\n");
return addr;
}
qemu_fwcfg_read_entry(be16_to_cpu(file->cfg.select),
size, table_loader);
for (i = 0; i < (size / sizeof(*entry)); i++) {
entry = table_loader + i;
switch (le32_to_cpu(entry->command)) {
case BIOS_LINKER_LOADER_COMMAND_ALLOCATE:
ret = bios_linker_allocate(entry, &addr);
if (ret)
goto out;
break;
case BIOS_LINKER_LOADER_COMMAND_ADD_POINTER:
ret = bios_linker_add_pointer(entry);
if (ret)
goto out;
break;
case BIOS_LINKER_LOADER_COMMAND_ADD_CHECKSUM:
ret = bios_linker_add_checksum(entry);
if (ret)
goto out;
break;
default:
break;
}
}
out:
if (ret) {
struct fw_cfg_file_iter iter;
for (file = qemu_fwcfg_file_iter_init(&iter);
!qemu_fwcfg_file_iter_end(&iter);
file = qemu_fwcfg_file_iter_next(&iter)) {
if (file->addr) {
free((void *)file->addr);
file->addr = 0;
}
}
}
free(table_loader);
return addr;
}
ulong acpi_get_rsdp_addr(void)
{
struct fw_file *file;
file = qemu_fwcfg_find_file("etc/acpi/rsdp");
return file->addr;
}
#endif
/* Read configuration item using fw_cfg PIO interface */
static void qemu_fwcfg_read_entry_pio(uint16_t entry,
uint32_t size, void *address)
{
debug("qemu_fwcfg_read_entry_pio: entry 0x%x, size %u address %p\n",
entry, size, address);
return fwcfg_arch_ops->arch_read_pio(entry, size, address);
}
/* Read configuration item using fw_cfg DMA interface */
static void qemu_fwcfg_read_entry_dma(uint16_t entry,
uint32_t size, void *address)
{
struct fw_cfg_dma_access dma;
dma.length = cpu_to_be32(size);
dma.address = cpu_to_be64((uintptr_t)address);
dma.control = cpu_to_be32(FW_CFG_DMA_READ);
/*
* writting FW_CFG_INVALID will cause read operation to resume at
* last offset, otherwise read will start at offset 0
*/
if (entry != FW_CFG_INVALID)
dma.control |= cpu_to_be32(FW_CFG_DMA_SELECT | (entry << 16));
barrier();
debug("qemu_fwcfg_read_entry_dma: entry 0x%x, size %u address %p, control 0x%x\n",
entry, size, address, be32_to_cpu(dma.control));
fwcfg_arch_ops->arch_read_dma(&dma);
}
bool qemu_fwcfg_present(void)
{
return fwcfg_present;
}
bool qemu_fwcfg_dma_present(void)
{
return fwcfg_dma_present;
}
void qemu_fwcfg_read_entry(uint16_t entry, uint32_t length, void *address)
{
if (fwcfg_dma_present)
qemu_fwcfg_read_entry_dma(entry, length, address);
else
qemu_fwcfg_read_entry_pio(entry, length, address);
}
int qemu_fwcfg_online_cpus(void)
{
uint16_t nb_cpus;
if (!fwcfg_present)
return -ENODEV;
qemu_fwcfg_read_entry(FW_CFG_NB_CPUS, 2, &nb_cpus);
return le16_to_cpu(nb_cpus);
}
int qemu_fwcfg_read_firmware_list(void)
{
int i;
uint32_t count;
struct fw_file *file;
struct list_head *entry;
/* don't read it twice */
if (!list_empty(&fw_list))
return 0;
qemu_fwcfg_read_entry(FW_CFG_FILE_DIR, 4, &count);
if (!count)
return 0;
count = be32_to_cpu(count);
for (i = 0; i < count; i++) {
file = malloc(sizeof(*file));
if (!file) {
printf("error: allocating resource\n");
goto err;
}
qemu_fwcfg_read_entry(FW_CFG_INVALID,
sizeof(struct fw_cfg_file), &file->cfg);
file->addr = 0;
list_add_tail(&file->list, &fw_list);
}
return 0;
err:
list_for_each(entry, &fw_list) {
file = list_entry(entry, struct fw_file, list);
free(file);
}
return -ENOMEM;
}
struct fw_file *qemu_fwcfg_find_file(const char *name)
{
struct list_head *entry;
struct fw_file *file;
list_for_each(entry, &fw_list) {
file = list_entry(entry, struct fw_file, list);
if (!strcmp(file->cfg.name, name))
return file;
}
return NULL;
}
struct fw_file *qemu_fwcfg_file_iter_init(struct fw_cfg_file_iter *iter)
{
iter->entry = fw_list.next;
return list_entry((struct list_head *)iter->entry,
struct fw_file, list);
}
struct fw_file *qemu_fwcfg_file_iter_next(struct fw_cfg_file_iter *iter)
{
iter->entry = ((struct list_head *)iter->entry)->next;
return list_entry((struct list_head *)iter->entry,
struct fw_file, list);
}
bool qemu_fwcfg_file_iter_end(struct fw_cfg_file_iter *iter)
{
return iter->entry == &fw_list;
}
void qemu_fwcfg_init(struct fw_cfg_arch_ops *ops)
{
uint32_t qemu;
uint32_t dma_enabled;
fwcfg_present = false;
fwcfg_dma_present = false;
fwcfg_arch_ops = NULL;
if (!ops || !ops->arch_read_pio || !ops->arch_read_dma)
return;
fwcfg_arch_ops = ops;
qemu_fwcfg_read_entry_pio(FW_CFG_SIGNATURE, 4, &qemu);
if (be32_to_cpu(qemu) == QEMU_FW_CFG_SIGNATURE)
fwcfg_present = true;
if (fwcfg_present) {
qemu_fwcfg_read_entry_pio(FW_CFG_ID, 1, &dma_enabled);
if (dma_enabled & FW_CFG_DMA_ENABLED)
fwcfg_dma_present = true;
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2006,2007,2009,2010,2011 Tel-Aviv University (Israel).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// 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.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
//
//
// Author(s) : Ron Wein <wein@post.tau.ac.il>
// Efi Fogel <efif@post.tau.ac.il>
#ifndef CGAL_ARR_SEGMENT_TRAITS_2_H
#define CGAL_ARR_SEGMENT_TRAITS_2_H
/*! \file
* The segment traits-class for the arrangement package.
*/
#include <CGAL/tags.h>
#include <CGAL/intersections.h>
#include <CGAL/Arr_tags.h>
#include <CGAL/Arr_geometry_traits/Segment_assertions.h>
#include <fstream>
namespace CGAL {
template <class Kernel_> class Arr_segment_2;
/*!
* \class A traits class for maintaining an arrangement of segments, aoviding
* cascading of computations as much as possible.
*
* The class is derived from the parameterized kernel to extend the traits
* with all the types and operations supported by the kernel. This makes it
* possible to use the traits class for data structures that extends the
* Arrangement_2 type and require objects and operations supported by the
* kernel, but not defined in this derived class.
*/
template <class Kernel_>
class Arr_segment_traits_2 : public Kernel_
{
friend class Arr_segment_2<Kernel_>;
public:
typedef Kernel_ Kernel;
typedef typename Kernel::FT FT;
typedef typename Algebraic_structure_traits<FT>::Is_exact
Has_exact_division;
// Category tags:
typedef Tag_true Has_left_category;
typedef Tag_true Has_merge_category;
typedef Tag_false Has_do_intersect_category;
typedef Arr_oblivious_side_tag Left_side_category;
typedef Arr_oblivious_side_tag Bottom_side_category;
typedef Arr_oblivious_side_tag Top_side_category;
typedef Arr_oblivious_side_tag Right_side_category;
typedef typename Kernel::Line_2 Line_2;
typedef CGAL::Segment_assertions<Arr_segment_traits_2<Kernel> >
Segment_assertions;
/*!
* \class Representation of a segement with cached data.
*/
class _Segment_cached_2
{
public:
typedef typename Kernel::Line_2 Line_2;
typedef typename Kernel::Segment_2 Segment_2;
typedef typename Kernel::Point_2 Point_2;
protected:
Line_2 l; // The line that supports the segment.
Point_2 ps; // The source point of the segment.
Point_2 pt; // The target point of the segment.
bool is_pt_max; // Is the target (lexicographically) larger
// than the source.
bool is_vert; // Is this a vertical segment.
bool is_degen; // Is the segment degenerate (a single point).
public:
/*!
* Default constructor.
*/
_Segment_cached_2 () :
is_vert(false),
is_degen(true)
{}
/*!
* Constructor from a segment.
* \param seg The segment.
* \pre The segment is not degenerate.
*/
_Segment_cached_2 (const Segment_2& seg)
{
Kernel kernel;
typename Kernel_::Construct_vertex_2
construct_vertex = kernel.construct_vertex_2_object();
ps = construct_vertex(seg, 0);
pt = construct_vertex(seg, 1);
Comparison_result res = kernel.compare_xy_2_object()(ps, pt);
is_degen = (res == EQUAL);
is_pt_max = (res == SMALLER);
CGAL_precondition_msg (! is_degen,
"Cannot contruct a degenerate segment.");
l = kernel.construct_line_2_object()(seg);
is_vert = kernel.is_vertical_2_object()(seg);
}
/*!
* Construct a segment from two end-points.
* \param source The source point.
* \param target The target point.
* \param The two points must not be equal.
*/
_Segment_cached_2 (const Point_2& source, const Point_2& target) :
ps (source),
pt (target)
{
Kernel kernel;
Comparison_result res = kernel.compare_xy_2_object()(ps, pt);
is_degen = (res == EQUAL);
is_pt_max = (res == SMALLER);
CGAL_precondition_msg (! is_degen,
"Cannot contruct a degenerate segment.");
l = kernel.construct_line_2_object()(source, target);
is_vert = kernel.is_vertical_2_object()(l);
}
/*!
* Construct a segment from two end-points on a supporting line.
* \param supp_line The supporting line.
* \param source The source point.
* \param target The target point.
* \pre The two endpoints are not the same and both lie on the given line.
*/
_Segment_cached_2 (const Line_2& supp_line,
const Point_2& source, const Point_2& target) :
l (supp_line),
ps (source),
pt (target)
{
Kernel kernel;
CGAL_precondition(
Segment_assertions::_assert_is_point_on(source, l,
Has_exact_division()) &&
Segment_assertions::_assert_is_point_on(target,l,
Has_exact_division())
);
is_vert = kernel.is_vertical_2_object()(l);
Comparison_result res = kernel.compare_xy_2_object()(ps, pt);
is_degen = (res == EQUAL);
is_pt_max = (res == SMALLER);
CGAL_precondition_msg (! is_degen,
"Cannot contruct a degenerate segment.");
}
/*!
* Assignment operator.
* \param seg the source segment to copy from
* \pre The segment is not degenerate.
*/
const _Segment_cached_2& operator= (const Segment_2& seg)
{
Kernel kernel;
typename Kernel_::Construct_vertex_2
construct_vertex = kernel.construct_vertex_2_object();
ps = construct_vertex(seg, 0);
pt = construct_vertex(seg, 1);
Comparison_result res = kernel.compare_xy_2_object()(ps, pt);
is_degen = (res == EQUAL);
is_pt_max = (res == SMALLER);
CGAL_precondition_msg (! is_degen,
"Cannot contruct a degenerate segment.");
l = kernel.construct_line_2_object()(seg);
is_vert = kernel.is_vertical_2_object()(seg);
return (*this);
}
/*!
* Get the (lexicographically) left endpoint.
*/
const Point_2& left () const
{
return (is_pt_max ? ps : pt);
}
/*!
* Set the (lexicographically) left endpoint.
* \param p The point to set.
* \pre p lies on the supporting line to the left of the right endpoint.
*/
void set_left (const Point_2& p)
{
CGAL_precondition (! is_degen);
CGAL_precondition_code (
Kernel kernel;
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, l,
Has_exact_division()) &&
kernel.compare_xy_2_object() (p, right()) == SMALLER);
if (is_pt_max)
ps = p;
else
pt = p;
}
/*!
* Get the (lexicographically) right endpoint.
*/
const Point_2& right () const
{
return (is_pt_max ? pt : ps);
}
/*!
* Set the (lexicographically) right endpoint.
* \param p The point to set.
* \pre p lies on the supporting line to the right of the left endpoint.
*/
void set_right (const Point_2& p)
{
CGAL_precondition (! is_degen);
CGAL_precondition_code (
Kernel kernel;
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, l,
Has_exact_division()) &&
kernel.compare_xy_2_object() (p, left()) == LARGER);
if (is_pt_max)
pt = p;
else
ps = p;
}
/*!
* Get the supporting line.
*/
const Line_2& line () const
{
CGAL_precondition (! is_degen);
return (l);
}
/*!
* Check if the curve is vertical.
*/
bool is_vertical () const
{
CGAL_precondition (! is_degen);
return (is_vert);
}
/*!
* Check if the curve is directed lexicographic from left to right
*/
bool is_directed_right () const
{
return (is_pt_max);
}
/*!
* Check if the given point is in the x-range of the segment.
* \param p The query point.
* \return (true) is in the x-range of the segment; (false) if it is not.
*/
bool is_in_x_range (const Point_2& p) const
{
Kernel kernel;
typename Kernel_::Compare_x_2 compare_x = kernel.compare_x_2_object();
const Comparison_result res1 = compare_x (p, left());
if (res1 == SMALLER)
return (false);
else if (res1 == EQUAL)
return (true);
const Comparison_result res2 = compare_x (p, right());
return (res2 != LARGER);
}
/*!
* Check if the given point is in the y-range of the segment.
* \param p The query point.
* \return (true) is in the y-range of the segment; (false) if it is not.
*/
bool is_in_y_range (const Point_2& p) const
{
Kernel kernel;
typename Kernel_::Compare_y_2 compare_y = kernel.compare_y_2_object();
const Comparison_result res1 = compare_y (p, left());
if (res1 == SMALLER)
return (false);
else if (res1 == EQUAL)
return (true);
const Comparison_result res2 = compare_y (p, right());
return (res2 != LARGER);
}
};
public:
// Traits objects
typedef typename Kernel::Point_2 Point_2;
typedef Arr_segment_2<Kernel> X_monotone_curve_2;
typedef Arr_segment_2<Kernel> Curve_2;
typedef unsigned int Multiplicity;
public:
/*!
* Default constructor.
*/
Arr_segment_traits_2 ()
{}
/// \name Basic functor definitions.
//@{
class Compare_x_2
{
public:
/*!
* Compare the x-coordinates of two points.
* \param p1 The first point.
* \param p2 The second point.
* \return LARGER if x(p1) > x(p2);
* SMALLER if x(p1) < x(p2);
* EQUAL if x(p1) = x(p2).
*/
Comparison_result operator() (const Point_2& p1, const Point_2& p2) const
{
Kernel kernel;
return (kernel.compare_x_2_object()(p1, p2));
}
};
/*! Get a Compare_x_2 functor object. */
Compare_x_2 compare_x_2_object () const
{
return Compare_x_2();
}
class Compare_xy_2
{
public:
/*!
* Compare two points lexigoraphically: by x, then by y.
* \param p1 The first point.
* \param p2 The second point.
* \return LARGER if x(p1) > x(p2), or if x(p1) = x(p2) and y(p1) > y(p2);
* SMALLER if x(p1) < x(p2), or if x(p1) = x(p2) and y(p1) < y(p2);
* EQUAL if the two points are equal.
*/
Comparison_result operator() (const Point_2& p1, const Point_2& p2) const
{
Kernel kernel;
return (kernel.compare_xy_2_object()(p1, p2));
}
};
/*! Get a Compare_xy_2 functor object. */
Compare_xy_2 compare_xy_2_object () const
{
return Compare_xy_2();
}
class Construct_min_vertex_2
{
public:
/*!
* Get the left endpoint of the x-monotone curve (segment).
* \param cv The curve.
* \return The left endpoint.
*/
const Point_2& operator() (const X_monotone_curve_2& cv) const
{
return (cv.left());
}
};
/*! Get a Construct_min_vertex_2 functor object. */
Construct_min_vertex_2 construct_min_vertex_2_object () const
{
return Construct_min_vertex_2();
}
class Construct_max_vertex_2
{
public:
/*!
* Get the right endpoint of the x-monotone curve (segment).
* \param cv The curve.
* \return The right endpoint.
*/
const Point_2& operator() (const X_monotone_curve_2& cv) const
{
return (cv.right());
}
};
/*! Get a Construct_max_vertex_2 functor object. */
Construct_max_vertex_2 construct_max_vertex_2_object () const
{
return Construct_max_vertex_2();
}
class Is_vertical_2
{
public:
/*!
* Check whether the given x-monotone curve is a vertical segment.
* \param cv The curve.
* \return (true) if the curve is a vertical segment; (false) otherwise.
*/
bool operator() (const X_monotone_curve_2& cv) const
{
return (cv.is_vertical());
}
};
/*! Get an Is_vertical_2 functor object. */
Is_vertical_2 is_vertical_2_object () const
{
return Is_vertical_2();
}
class Compare_y_at_x_2
{
public:
/*!
* Return the location of the given point with respect to the input curve.
* \param cv The curve.
* \param p The point.
* \pre p is in the x-range of cv.
* \return SMALLER if y(p) < cv(x(p)), i.e. the point is below the curve;
* LARGER if y(p) > cv(x(p)), i.e. the point is above the curve;
* EQUAL if p lies on the curve.
*/
Comparison_result operator() (const Point_2& p,
const X_monotone_curve_2& cv) const
{
CGAL_precondition (cv.is_in_x_range (p));
Kernel kernel;
if (! cv.is_vertical())
{
// Compare p with the segment's supporting line.
return (kernel.compare_y_at_x_2_object()(p, cv.line()));
}
else
{
// Compare with the vertical segment's end-points.
typename Kernel::Compare_y_2 compare_y = kernel.compare_y_2_object();
Comparison_result res1 = compare_y (p, cv.left());
Comparison_result res2 = compare_y (p, cv.right());
if (res1 == res2)
return (res1);
else
return (EQUAL);
}
}
};
/*! Get a Compare_y_at_x_2 functor object. */
Compare_y_at_x_2 compare_y_at_x_2_object () const
{
return Compare_y_at_x_2();
}
class Compare_y_at_x_left_2
{
public:
/*!
* Compare the y value of two x-monotone curves immediately to the left
* of their intersection point.
* \param cv1 The first curve.
* \param cv2 The second curve.
* \param p The intersection point.
* \pre The point p lies on both curves, and both of them must be also be
* defined (lexicographically) to its left.
* \return The relative position of cv1 with respect to cv2 immdiately to
* the left of p: SMALLER, LARGER or EQUAL.
*/
Comparison_result operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
const Point_2& CGAL_assertion_code(p)) const
{
Kernel kernel;
// Make sure that p lies on both curves, and that both are defined to its
// left (so their left endpoint is lexicographically smaller than p).
CGAL_precondition_code (
typename Kernel::Compare_xy_2 compare_xy =
kernel.compare_xy_2_object();
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, cv1,
Has_exact_division()) &&
Segment_assertions::_assert_is_point_on (p, cv2,
Has_exact_division()));
CGAL_precondition (compare_xy(cv1.left(), p) == SMALLER &&
compare_xy(cv2.left(), p) == SMALLER);
// Compare the slopes of the two segments to determine thir relative
// position immediately to the left of q.
// Notice we use the supporting lines in order to compare the slopes,
// and that we swap the order of the curves in order to obtain the
// correct result to the left of p.
return (kernel.compare_slope_2_object()(cv2.line(), cv1.line()));
}
};
/*! Get a Compare_y_at_x_left_2 functor object. */
Compare_y_at_x_left_2 compare_y_at_x_left_2_object () const
{
return Compare_y_at_x_left_2();
}
class Compare_y_at_x_right_2
{
public:
/*!
* Compare the y value of two x-monotone curves immediately to the right
* of their intersection point.
* \param cv1 The first curve.
* \param cv2 The second curve.
* \param p The intersection point.
* \pre The point p lies on both curves, and both of them must be also be
* defined (lexicographically) to its right.
* \return The relative position of cv1 with respect to cv2 immdiately to
* the right of p: SMALLER, LARGER or EQUAL.
*/
Comparison_result operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
const Point_2& CGAL_assertion_code(p)) const
{
Kernel kernel;
// Make sure that p lies on both curves, and that both are defined to its
// right (so their right endpoint is lexicographically larger than p).
CGAL_precondition_code (
typename Kernel::Compare_xy_2 compare_xy =
kernel.compare_xy_2_object();
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, cv1,
Has_exact_division()) &&
Segment_assertions::_assert_is_point_on (p, cv2,
Has_exact_division()));
CGAL_precondition (compare_xy(cv1.right(), p) == LARGER &&
compare_xy(cv2.right(), p) == LARGER);
// Compare the slopes of the two segments to determine thir relative
// position immediately to the left of q.
// Notice we use the supporting lines in order to compare the slopes.
return (kernel.compare_slope_2_object()(cv1.line(), cv2.line()));
}
};
/*! Get a Compare_y_at_x_right_2 functor object. */
Compare_y_at_x_right_2 compare_y_at_x_right_2_object () const
{
return Compare_y_at_x_right_2();
}
class Equal_2
{
public:
/*!
* Check if the two x-monotone curves are the same (have the same graph).
* \param cv1 The first curve.
* \param cv2 The second curve.
* \return (true) if the two curves are the same; (false) otherwise.
*/
bool operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2) const
{
Kernel kernel;
typename Kernel::Equal_2 equal = kernel.equal_2_object();
return (equal(cv1.left(), cv2.left()) &&
equal(cv1.right(), cv2.right()));
}
/*!
* Check if the two points are the same.
* \param p1 The first point.
* \param p2 The second point.
* \return (true) if the two point are the same; (false) otherwise.
*/
bool operator() (const Point_2& p1, const Point_2& p2) const
{
Kernel kernel;
return (kernel.equal_2_object()(p1, p2));
}
};
/*! Get an Equal_2 functor object. */
Equal_2 equal_2_object () const
{
return Equal_2();
}
//@}
/// \name Functor definitions for supporting intersections.
//@{
class Make_x_monotone_2
{
public:
/*!
* Cut the given curve into x-monotone subcurves and insert them into the
* given output iterator. As segments are always x_monotone, only one
* object will be contained in the iterator.
* \param cv The curve.
* \param oi The output iterator, whose value-type is Object.
* \return The past-the-end iterator.
*/
template<class OutputIterator>
OutputIterator operator() (const Curve_2& cv, OutputIterator oi) const
{
// Wrap the segment with an object.
*oi = make_object (cv);
++oi;
return (oi);
}
};
/*! Get a Make_x_monotone_2 functor object. */
Make_x_monotone_2 make_x_monotone_2_object () const
{
return Make_x_monotone_2();
}
class Split_2
{
public:
/*!
* Split a given x-monotone curve at a given point into two sub-curves.
* \param cv The curve to split
* \param p The split point.
* \param c1 Output: The left resulting subcurve (p is its right endpoint).
* \param c2 Output: The right resulting subcurve (p is its left endpoint).
* \pre p lies on cv but is not one of its end-points.
*/
void operator() (const X_monotone_curve_2& cv, const Point_2& p,
X_monotone_curve_2& c1, X_monotone_curve_2& c2) const
{
// Make sure that p lies on the interior of the curve.
CGAL_precondition_code (
Kernel kernel;
typename Kernel::Compare_xy_2 compare_xy =
kernel.compare_xy_2_object();
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, cv,
Has_exact_division()) &&
compare_xy(cv.left(), p) == SMALLER &&
compare_xy(cv.right(), p) == LARGER);
// Perform the split.
c1 = cv;
c1.set_right (p);
c2 = cv;
c2.set_left (p);
return;
}
};
/*! Get a Split_2 functor object. */
Split_2 split_2_object () const
{
return Split_2();
}
class Intersect_2
{
public:
/*!
* Find the intersections of the two given curves and insert them into the
* given output iterator. As two segments may itersect only once, only a
* single intersection will be contained in the iterator.
* \param cv1 The first curve.
* \param cv2 The second curve.
* \param oi The output iterator.
* \return The past-the-end iterator.
*/
template<class OutputIterator>
OutputIterator operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
OutputIterator oi) const
{
// Intersect the two supporting lines.
Kernel kernel;
CGAL::Object obj = kernel.intersect_2_object()(cv1.line(), cv2.line());
if (obj.is_empty())
{
// The supporting line are parallel lines and do not intersect:
return (oi);
}
// Check if we have a single intersection point.
const Point_2 *ip = object_cast<Point_2> (&obj);
if (ip != NULL)
{
// Check if the intersection point ip lies on both segments.
const bool ip_on_cv1 = cv1.is_vertical() ? cv1.is_in_y_range(*ip) :
cv1.is_in_x_range(*ip);
if (ip_on_cv1)
{
const bool ip_on_cv2 = cv2.is_vertical() ? cv2.is_in_y_range(*ip) :
cv2.is_in_x_range(*ip);
if (ip_on_cv2)
{
// Create a pair representing the point with its multiplicity,
// which is always 1 for line segments.
std::pair<Point_2, Multiplicity> ip_mult (*ip, 1);
*oi = make_object (ip_mult);
oi++;
}
}
return (oi);
}
// In this case, the two supporting lines overlap.
// The overlapping segment is therefore [p_l,p_r], where p_l is the
// rightmost of the two left endpoints and p_r is the leftmost of the
// two right endpoints.
typename Kernel::Compare_xy_2 compare_xy = kernel.compare_xy_2_object();
Point_2 p_l, p_r;
if (compare_xy (cv1.left(), cv2.left()) == SMALLER)
p_l = cv2.left();
else
p_l = cv1.left();
if (compare_xy (cv1.right(), cv2.right()) == SMALLER)
p_r = cv1.right();
else
p_r = cv2.right();
// Examine the resulting segment.
const Comparison_result res = compare_xy (p_l, p_r);
if (res == SMALLER)
{
// We have discovered an overlapping segment:
if(cv1.is_directed_right() == cv2.is_directed_right())
{
// cv1 and cv2 have the same directions, maintain this direction
// in the overlap segment
if(cv1.is_directed_right())
{
X_monotone_curve_2 overlap_seg (cv1.line(), p_l, p_r);
*oi = make_object (overlap_seg);
oi++;
}
else
{
X_monotone_curve_2 overlap_seg (cv1.line(), p_r, p_l);
*oi = make_object (overlap_seg);
oi++;
}
}
else
{
// cv1 and cv2 have opposite directions, the overlap segment
// will be directed from left to right
X_monotone_curve_2 overlap_seg (cv1.line(), p_l, p_r);
*oi = make_object (overlap_seg);
oi++;
}
}
else if (res == EQUAL)
{
// The two segment have the same supporting line, but they just share
// a common endpoint. Thus we have an intersection point, but we leave
// the multiplicity of this point undefined.
std::pair<Point_2, Multiplicity> ip_mult (p_r, 0);
*oi = make_object (ip_mult);
oi++;
}
return (oi);
}
};
/*! Get an Intersect_2 functor object. */
Intersect_2 intersect_2_object () const
{
return Intersect_2();
}
class Are_mergeable_2 {
protected:
typedef Arr_segment_traits_2<Kernel> Traits;
/*! The traits (in case it has state) */
const Traits* m_traits;
/*! Constructor
* \param traits the traits (in case it has state)
*/
Are_mergeable_2(const Traits* traits) : m_traits(traits) {}
friend class Arr_segment_traits_2<Kernel>;
public:
/*!
* Check whether it is possible to merge two given x-monotone curves.
* \param cv1 The first curve.
* \param cv2 The second curve.
* \return (true) if the two curves are mergeable, that is, if they are
* supported by the same line; (false) otherwise.
* \pre cv1 and cv2 share a common endpoint.
*/
bool operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2) const
{
if (!m_traits->equal_2_object()(cv1.right(), cv2.left()) &&
!m_traits->equal_2_object()(cv2.right(), cv1.left()))
return false;
// Check whether the two curves have the same supporting line.
const Kernel* kernel = m_traits;
typename Kernel::Equal_2 equal = kernel->equal_2_object();
return (equal(cv1.line(), cv2.line()) ||
equal(cv1.line(),
kernel->construct_opposite_line_2_object()(cv2.line())));
}
};
/*! Get an Are_mergeable_2 functor object. */
Are_mergeable_2 are_mergeable_2_object() const
{ return Are_mergeable_2(this); }
/*! \class Merge_2
* A functor that merges two x-monotone arcs into one.
*/
class Merge_2 {
protected:
typedef Arr_segment_traits_2<Kernel> Traits;
/*! The traits (in case it has state) */
const Traits* m_traits;
/*! Constructor
* \param traits the traits (in case it has state)
*/
Merge_2(const Traits* traits) : m_traits(traits) {}
friend class Arr_segment_traits_2<Kernel>;
public:
/*!
* Merge two given x-monotone curves into a single curve (segment).
* \param cv1 The first curve.
* \param cv2 The second curve.
* \param c Output: The merged curve.
* \pre The two curves are mergeable.
*/
void operator()(const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
X_monotone_curve_2& c) const
{
CGAL_precondition(m_traits->are_mergeable_2_object()(cv1, cv2));
Equal_2 equal = m_traits->equal_2_object();
// Check which curve extends to the right of the other.
if (equal(cv1.right(), cv2.left())) {
// cv2 extends cv1 to the right.
c = cv1;
c.set_right(cv2.right());
}
else {
CGAL_precondition(equal(cv2.right(), cv1.left()));
// cv1 extends cv2 to the right.
c = cv2;
c.set_right(cv1.right());
}
}
};
/*! Get a Merge_2 functor object. */
Merge_2 merge_2_object () const { return Merge_2(this); }
//@}
/// \name Functor definitions for the landmarks point-location strategy.
//@{
typedef double Approximate_number_type;
class Approximate_2
{
public:
/*!
* Return an approximation of a point coordinate.
* \param p The exact point.
* \param i The coordinate index (either 0 or 1).
* \pre i is either 0 or 1.
* \return An approximation of p's x-coordinate (if i == 0), or an
* approximation of p's y-coordinate (if i == 1).
*/
Approximate_number_type operator() (const Point_2& p,
int i) const
{
CGAL_precondition (i == 0 || i == 1);
return (i == 0) ? (CGAL::to_double(p.x())) : (CGAL::to_double(p.y()));
}
};
/*! Get an Approximate_2 functor object. */
Approximate_2 approximate_2_object () const
{
return Approximate_2();
}
class Construct_x_monotone_curve_2
{
public:
/*!
* Return an x-monotone curve connecting the two given endpoints.
* \param p The first point.
* \param q The second point.
* \pre p and q must not be the same.
* \return A segment connecting p and q.
*/
X_monotone_curve_2 operator() (const Point_2& p,
const Point_2& q) const
{
return (X_monotone_curve_2 (p, q));
}
};
/*! Get a Construct_x_monotone_curve_2 functor object. */
Construct_x_monotone_curve_2 construct_x_monotone_curve_2_object () const
{
return Construct_x_monotone_curve_2();
}
//@}
/// \name Functor definitions for the Boolean set-operation traits.
//@{
class Compare_endpoints_xy_2
{
public:
/*!
* Compare the endpoints of an $x$-monotone curve lexicographically.
* (assuming the curve has a designated source and target points).
* \param cv The curve.
* \return SMALLER if the curve is directed right;
* LARGER if the curve is directed left.
*/
Comparison_result operator() (const X_monotone_curve_2& cv) const
{
return (cv.is_directed_right()) ? (SMALLER) : (LARGER);
}
};
/*! Get a Compare_endpoints_xy_2 functor object. */
Compare_endpoints_xy_2 compare_endpoints_xy_2_object() const
{
return Compare_endpoints_xy_2();
}
class Construct_opposite_2
{
public:
/*!
* Construct an opposite x-monotone (with swapped source and target).
* \param cv The curve.
* \return The opposite curve.
*/
X_monotone_curve_2 operator() (const X_monotone_curve_2& cv) const
{
return (cv.flip());
}
};
/*! Get a Construct_opposite_2 functor object. */
Construct_opposite_2 construct_opposite_2_object() const
{
return Construct_opposite_2();
}
//@}
};
/*!
* \class A representation of a segment, as used by the Arr_segment_traits_2
* traits-class.
*/
template <class Kernel_>
class Arr_segment_2 :
public Arr_segment_traits_2<Kernel_>::_Segment_cached_2
{
typedef Kernel_ Kernel;
typedef typename Arr_segment_traits_2<Kernel>::_Segment_cached_2 Base;
typedef typename Kernel::Segment_2 Segment_2;
typedef typename Kernel::Point_2 Point_2;
typedef typename Kernel::Line_2 Line_2;
public:
/*!
* Default constructor.
*/
Arr_segment_2 () :
Base()
{}
/*!
* Constructor from a "kernel" segment.
* \param seg The segment.
* \pre The segment is not degenerate.
*/
Arr_segment_2 (const Segment_2& seg) :
Base(seg)
{}
/*!
* Construct a segment from two end-points.
* \param source The source point.
* \param target The target point.
* \pre The two points are not the same.
*/
Arr_segment_2 (const Point_2& source, const Point_2& target) :
Base(source,target)
{}
/*!
* Construct a segment from a line and two end-points.
* \param line The supporting line.
* \param source The source point.
* \param target The target point.
* \pre Both source and target must be on the supporting line.
* \pre The two points are not the same.
*/
Arr_segment_2 (const Line_2& line,
const Point_2& source, const Point_2& target) :
Base(line,source,target)
{}
/*!
* Cast to a segment.
*/
operator Segment_2 () const
{
Kernel kernel;
Segment_2 seg = kernel.construct_segment_2_object() (this->ps, this->pt);
return (seg);
}
/*!
* Create a bounding box for the segment.
*/
Bbox_2 bbox() const
{
Kernel kernel;
Segment_2 seg = kernel.construct_segment_2_object() (this->ps, this->pt);
return (kernel.construct_bbox_2_object() (seg));
}
/*!
* Get the segment source.
*/
const Point_2& source() const
{
return (this->ps);
}
/*!
* Get the segment target.
*/
const Point_2& target() const
{
return (this->pt);
}
/*! Flip the segment (swap its source and target). */
Arr_segment_2 flip () const
{
Arr_segment_2 opp;
opp.l = this->l;
opp.ps = this->pt;
opp.pt = this->ps;
opp.is_pt_max = !(this->is_pt_max);
opp.is_vert = this->is_vert;
opp.is_degen = this->is_degen;
return (opp);
}
};
/*!
* Exporter for the segment class used by the traits-class.
*/
template <class Kernel, class OutputStream>
OutputStream& operator<< (OutputStream& os, const Arr_segment_2<Kernel>& seg)
{
os << static_cast<typename Kernel::Segment_2>(seg);
return (os);
}
/*!
* Importer for the segment class used by the traits-class.
*/
template <class Kernel, class InputStream>
InputStream& operator>> (InputStream& is, Arr_segment_2<Kernel>& seg)
{
typename Kernel::Segment_2 kernel_seg;
is >> kernel_seg;
seg = kernel_seg;
return (is);
}
} //namespace CGAL
#endif
| {
"pile_set_name": "Github"
} |
package assets
import (
"bytes"
"compress/gzip"
"encoding/hex"
"fmt"
"io"
"net/http"
"path"
"regexp"
"sort"
"strings"
"text/template"
"github.com/openshift/origin/pkg/quota/admission/clusterresourceoverride/api"
utilruntime "k8s.io/kubernetes/pkg/util/runtime"
)
var varyHeaderRegexp = regexp.MustCompile("\\s*,\\s*")
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
sniffDone bool
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if !w.sniffDone {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
w.sniffDone = true
}
return w.Writer.Write(b)
}
// GzipHandler wraps a http.Handler to support transparent gzip encoding.
func GzipHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Accept-Encoding")
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
h.ServeHTTP(w, r)
return
}
// Normalize the Accept-Encoding header for improved caching
r.Header.Set("Accept-Encoding", "gzip")
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
h.ServeHTTP(&gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
})
}
func generateEtag(r *http.Request, version string, varyHeaders []string) string {
varyHeaderValues := ""
for _, varyHeader := range varyHeaders {
varyHeaderValues += r.Header.Get(varyHeader)
}
return fmt.Sprintf("W/\"%s_%s\"", version, hex.EncodeToString([]byte(varyHeaderValues)))
}
func CacheControlHandler(version string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vary := w.Header().Get("Vary")
varyHeaders := []string{}
if vary != "" {
varyHeaders = varyHeaderRegexp.Split(vary, -1)
}
etag := generateEtag(r, version, varyHeaders)
if r.Header.Get("If-None-Match") == etag {
w.WriteHeader(http.StatusNotModified)
return
}
// Clients must revalidate their cached copy every time.
w.Header().Add("Cache-Control", "public, max-age=0, must-revalidate")
w.Header().Add("ETag", etag)
h.ServeHTTP(w, r)
})
}
type LongestToShortest []string
func (s LongestToShortest) Len() int {
return len(s)
}
func (s LongestToShortest) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s LongestToShortest) Less(i, j int) bool {
return len(s[i]) > len(s[j])
}
// HTML5ModeHandler will serve any static assets we know about, all other paths
// are assumed to be HTML5 paths for the console application and index.html will
// be served.
// contextRoot must contain leading and trailing slashes, e.g. /console/
//
// subcontextMap is a map of keys (subcontexts, no leading or trailing slashes) to the asset path (no
// leading slash) to serve for that subcontext if a resource that does not exist is requested
func HTML5ModeHandler(contextRoot string, subcontextMap map[string]string, h http.Handler, getAsset AssetFunc) (http.Handler, error) {
subcontextData := map[string][]byte{}
subcontexts := []string{}
for subcontext, index := range subcontextMap {
b, err := getAsset(index)
if err != nil {
return nil, err
}
base := path.Join(contextRoot, subcontext)
// Make sure the base always ends in a trailing slash but don't end up with a double trailing slash
if !strings.HasSuffix(base, "/") {
base += "/"
}
b = bytes.Replace(b, []byte(`<base href="/">`), []byte(fmt.Sprintf(`<base href="%s">`, base)), 1)
subcontextData[subcontext] = b
subcontexts = append(subcontexts, subcontext)
}
// Sort by length, longest first
sort.Sort(LongestToShortest(subcontexts))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
urlPath := strings.TrimPrefix(r.URL.Path, "/")
if _, err := getAsset(urlPath); err != nil {
// find the index we want to serve instead
for _, subcontext := range subcontexts {
prefix := subcontext
if subcontext != "" {
prefix += "/"
}
if urlPath == subcontext || strings.HasPrefix(urlPath, prefix) {
w.Write(subcontextData[subcontext])
return
}
}
}
h.ServeHTTP(w, r)
}), nil
}
var versionTemplate = template.Must(template.New("webConsoleVersion").Parse(`
window.OPENSHIFT_VERSION = {
openshift: "{{ .OpenShiftVersion | js}}",
kubernetes: "{{ .KubernetesVersion | js}}"
};
`))
type WebConsoleVersion struct {
KubernetesVersion string
OpenShiftVersion string
}
var extensionPropertiesTemplate = template.Must(template.New("webConsoleExtensionProperties").Parse(`
window.OPENSHIFT_EXTENSION_PROPERTIES = {
{{ range $i, $property := .ExtensionProperties }}{{ if $i }},{{ end }}
"{{ $property.Key | js }}": "{{ $property.Value | js }}"{{ end }}
};
`))
type WebConsoleExtensionProperty struct {
Key string
Value string
}
type WebConsoleExtensionProperties struct {
ExtensionProperties []WebConsoleExtensionProperty
}
var configTemplate = template.Must(template.New("webConsoleConfig").Parse(`
window.OPENSHIFT_CONFIG = {
apis: {
hostPort: "{{ .APIGroupAddr | js}}",
prefix: "{{ .APIGroupPrefix | js}}"
},
api: {
openshift: {
hostPort: "{{ .MasterAddr | js}}",
prefix: "{{ .MasterPrefix | js}}"
},
k8s: {
hostPort: "{{ .KubernetesAddr | js}}",
prefix: "{{ .KubernetesPrefix | js}}"
}
},
auth: {
oauth_authorize_uri: "{{ .OAuthAuthorizeURI | js}}",
oauth_redirect_base: "{{ .OAuthRedirectBase | js}}",
oauth_client_id: "{{ .OAuthClientID | js}}",
logout_uri: "{{ .LogoutURI | js}}"
},
{{ with .LimitRequestOverrides }}
limitRequestOverrides: {
limitCPUToMemoryPercent: {{ .LimitCPUToMemoryPercent }},
cpuRequestToLimitPercent: {{ .CPURequestToLimitPercent }},
memoryRequestToLimitPercent: {{ .MemoryRequestToLimitPercent }}
},
{{ end }}
loggingURL: "{{ .LoggingURL | js}}",
metricsURL: "{{ .MetricsURL | js}}"
};
`))
type WebConsoleConfig struct {
// APIGroupAddr is the host:port the UI should call the API groups on. Scheme is derived from the scheme the UI is served on, so they must be the same.
APIGroupAddr string
// APIGroupPrefix is the API group context root
APIGroupPrefix string
// MasterAddr is the host:port the UI should call the master API on. Scheme is derived from the scheme the UI is served on, so they must be the same.
MasterAddr string
// MasterPrefix is the OpenShift API context root
MasterPrefix string
// MasterResources holds resource names for the OpenShift API
MasterResources []string
// KubernetesAddr is the host:port the UI should call the kubernetes API on. Scheme is derived from the scheme the UI is served on, so they must be the same.
// TODO this is probably unneeded since everything goes through the openshift master's proxy
KubernetesAddr string
// KubernetesPrefix is the Kubernetes API context root
KubernetesPrefix string
// KubernetesResources holds resource names for the Kubernetes API
KubernetesResources []string
// OAuthAuthorizeURI is the OAuth2 endpoint to use to request an API token. It must support request_type=token.
OAuthAuthorizeURI string
// OAuthRedirectBase is the base URI of the web console. It must be a valid redirect_uri for the OAuthClientID
OAuthRedirectBase string
// OAuthClientID is the OAuth2 client_id to use to request an API token. It must be authorized to redirect to the web console URL.
OAuthClientID string
// LogoutURI is an optional (absolute) URI to redirect to after completing a logout. If not specified, the built-in logout page is shown.
LogoutURI string
// LoggingURL is the endpoint for logging (optional)
LoggingURL string
// MetricsURL is the endpoint for metrics (optional)
MetricsURL string
// LimitRequestOverrides contains the ratios for overriding request/limit on containers.
// Applied in order:
// LimitCPUToMemoryPercent
// CPURequestToLimitPercent
// MemoryRequestToLimitPercent
LimitRequestOverrides *api.ClusterResourceOverrideConfig
}
func GeneratedConfigHandler(config WebConsoleConfig, version WebConsoleVersion, extensionProps WebConsoleExtensionProperties) (http.Handler, error) {
var buffer bytes.Buffer
if err := configTemplate.Execute(&buffer, config); err != nil {
return nil, err
}
if err := versionTemplate.Execute(&buffer, version); err != nil {
return nil, err
}
// We include the extension properties in config.js and not extensions.js because we
// want them treated with the same caching behavior as the rest of the values in config.js
if err := extensionPropertiesTemplate.Execute(&buffer, extensionProps); err != nil {
return nil, err
}
content := buffer.Bytes()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Cache-Control", "no-cache, no-store")
w.Header().Add("Content-Type", "application/javascript")
if _, err := w.Write(content); err != nil {
utilruntime.HandleError(fmt.Errorf("Error serving Web Console config and version: %v", err))
}
}), nil
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2006-2009, 2017, 2020 United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA World Wind Java (WWJ) platform is 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.
*
* NASA World Wind Java (WWJ) also contains the following 3rd party Open Source
* software:
*
* Jackson Parser – Licensed under Apache 2.0
* GDAL – Licensed under MIT
* JOGL – Licensed under Berkeley Software Distribution (BSD)
* Gluegen – Licensed under Berkeley Software Distribution (BSD)
*
* A complete listing of 3rd Party software notices and licenses included in
* NASA World Wind Java (WWJ) can be found in the WorldWindJava-v2.2 3rd-party
* notices and licenses PDF found in code directory.
*/
package gov.nasa.worldwindx.examples.layermanager;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.layers.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Represents one layer in the layer manager's layer list.
*
* @author tag
* @version $Id: LayerPanel.java 1179 2013-02-15 17:47:37Z tgaskins $
*/
public class LayerPanel extends JPanel
{
public static final ImageIcon UP_ARROW =
new ImageIcon(LayerPanel.class.getResource("/images/up_arrow_16x16.png"));
public static final ImageIcon DOWN_ARROW =
new ImageIcon(LayerPanel.class.getResource("/images/down_arrow_16x16.png"));
protected Layer layer; // the layer represented by this instance
protected JCheckBox checkBox; // the checkbox of this instance
protected JButton upButton;
protected JButton downButton;
public LayerPanel(final WorldWindow wwd, final Layer layer)
{
super(new BorderLayout(10, 10));
this.layer = layer;
SelectLayerAction action = new SelectLayerAction(wwd, layer, layer.isEnabled());
this.checkBox = new JCheckBox(action);
this.checkBox.setSelected(action.selected);
this.add(this.checkBox, BorderLayout.CENTER);
this.upButton = new JButton(UP_ARROW);
this.upButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent)
{
moveLayer(wwd, layer, -1);
}
});
this.downButton = new JButton(DOWN_ARROW);
this.downButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent)
{
moveLayer(wwd, layer, +1);
}
});
// The buttons shouldn't look like actual JButtons.
this.upButton.setBorderPainted(false);
this.upButton.setContentAreaFilled(false);
this.upButton.setPreferredSize(new Dimension(24, 24));
this.downButton.setBorderPainted(false);
this.downButton.setContentAreaFilled(false);
this.downButton.setPreferredSize(new Dimension(24, 24));
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(this.upButton);
buttonPanel.add(this.downButton);
this.add(buttonPanel, BorderLayout.EAST);
int index = this.findLayerPosition(wwd, layer);
this.upButton.setEnabled(index != 0);
this.downButton.setEnabled(index != wwd.getModel().getLayers().size() - 1);
}
public Layer getLayer()
{
return this.layer;
}
public Font getLayerNameFont()
{
return this.checkBox.getFont();
}
public void setLayerNameFont(Font font)
{
this.checkBox.setFont(font);
}
protected void moveLayer(WorldWindow wwd, Layer layer, int direction)
{
// Moves the layer associated with this instance in the direction indicated relative to the other layers.
int index = this.findLayerPosition(wwd, layer);
if (index < 0)
return; // layer not found
LayerList layerList = wwd.getModel().getLayers();
this.upButton.setEnabled(true);
this.downButton.setEnabled(true);
if (direction < 0 && index == 0) // can't move lowest layer any lower
{
this.upButton.setEnabled(false);
return;
}
if (direction > 0 && index == layerList.size() - 1) // can't move highest layer any higher
{
this.downButton.setEnabled(false);
return;
}
// Remove the layer from the layer list and then re-insert it.
layerList.remove(layer);
if (direction > 0)
layerList.add(index + 1, layer);
else if (direction < 0)
layerList.add(index - 1, layer);
// Update WorldWind so the change is visible.
wwd.redraw();
}
protected int findLayerPosition(WorldWindow wwd, Layer layer)
{
// Determines the ordinal location of a layer in the layer list.
for (int i = 0; i < wwd.getModel().getLayers().size(); i++)
{
if (layer == wwd.getModel().getLayers().get(i))
return i;
}
return -1;
}
protected static class SelectLayerAction extends AbstractAction
{
// This action handles layer selection and de-selection.
protected WorldWindow wwd;
protected Layer layer;
protected boolean selected;
public SelectLayerAction(WorldWindow wwd, Layer layer, boolean selected)
{
super(layer.getName());
this.wwd = wwd;
this.layer = layer;
this.selected = selected;
this.layer.setEnabled(this.selected);
}
public void actionPerformed(ActionEvent actionEvent)
{
// Simply enable or disable the layer based on its toggle button.
if (((JCheckBox) actionEvent.getSource()).isSelected())
this.layer.setEnabled(true);
else
this.layer.setEnabled(false);
wwd.redraw();
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright © 2013 Mobs and Geeks
*
* 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.mobsandgeeks.adapters;
import android.view.View;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* Interface that provides a mechanism to customize Views. You can setup one {@link ViewHandler}
* per {@link View}.
*
* @author Ragunath Jawahar <rj@mobsandgeeks.com>
*
* @param <T> The model you will be using for customizing the associated {@link View}.
*/
public interface ViewHandler<T> {
/**
* Allows you to make changes to an associated View by supplying the adapter, the View's
* parent, an instance of the data associated with the position and the position itself.
*
* @param adapter The adapter to which this {@link ViewHandler} is assigned to.
* @param parent Parent for the View that is being handled. Usually the custom layout
* instance for individual views and a {@link ListView} or a {@link GridView}
* for the layout.
* @param view The {@link View} that has to be handled.
* @param instance The instance that is associated with the position.
* @param position Position of the item within the adapter's data set.
*/
void handleView(ListAdapter adapter, View parent, View view, T instance, int position);
}
| {
"pile_set_name": "Github"
} |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Transmogrificator.cpp
//
// A background thread which has the purpose of transmogrifying UTs to make them appear as NT threads to the layer
// above them. This is done via queued creation of a TransmogrifiedPrimary. The reason there is a background thread
// that does this is that we can only make a determination of when to transmogrify at a SwitchTo(..., Nesting) or subsequent
// SwitchOut in the RM. At this point, we **CANNOT** perform a heap allocation without hopelessly confusing the scheduler
// or deadlocking it. But we **MUST** not allow the running thread to continue without performing a heap allocation. The
// catch-22 is solved here by returning the virtual processor (allowing the SwitchTo to happen) and letting it run things
// which may hold the heap lock. The original UT (which certainly isn't holding any blasted locks at this stage) isn't run again
// until this thread can perform the allocation and get it set up.
//
// Note that this thread may **VERY WELL** cache transmogrified primaries in order to avoid having to do the thread creation and
// heap allocations on each nesting.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#include "concrtinternal.h"
namespace Concurrency
{
namespace details
{
/// <summary>
/// Constructs a new Transmogrificator.
/// </summary>
Transmogrificator::Transmogrificator()
: m_hWaitHandle(NULL)
, m_hUnblock(NULL)
, m_queuedProxyCount(0)
, m_cacheCount(0)
{
m_hUnblock = CreateEventW(NULL, FALSE, FALSE, NULL); // VSO#459907
if (m_hUnblock == NULL)
{
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
}
InitializeSListHead(&m_cachedProxies);
if (!RegisterWaitForSingleObject(&m_hWaitHandle,
m_hUnblock,
Transmogrificator::TransmogrificationHandler,
this, INFINITE, WT_EXECUTEDEFAULT))
{
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
}
}
/// <summary>
/// Destructs the Transmogrificator.
/// </summary>
Transmogrificator::~Transmogrificator()
{
ASSERT(m_queuedProxyCount == 0);
//
// Get rid of everything in the cache.
//
PSLIST_ENTRY pLE = InterlockedFlushSList(&m_cachedProxies);
while (pLE != NULL)
{
PSLIST_ENTRY pNext = pLE->Next;
CachedTransmogrifiedPrimary *pCachedPrimary = CONTAINING_RECORD(pLE, CachedTransmogrifiedPrimary, m_cacheEntry);
pCachedPrimary->Shutdown();
pLE = pNext;
}
// Cancels the wait and ensure that all callbacks have indeed completed.
if (m_hWaitHandle != NULL)
{
UnregisterWaitEx(m_hWaitHandle, INVALID_HANDLE_VALUE);
}
CloseHandle(m_hUnblock);
}
/// <summary>
/// Callback handler for m_hUnblock
/// </summary>
void CALLBACK Transmogrificator::TransmogrificationHandler(PVOID parameter, BOOLEAN)
{
Transmogrificator * pTransmogrificator = reinterpret_cast<Transmogrificator *>(parameter);
pTransmogrificator->BeginTransmogrifying();
}
/// <summary>
/// Performs a transmogrification of pProxy. The Transmogrified primary which is created will not start until
/// UnblockTransmogrification is called.
/// </summary>
/// <param name="pProxy">
/// The thread proxy which is being transmogrified.
/// </param>
void Transmogrificator::PerformTransmogrification(UMSThreadProxy *pProxy)
{
//
// This **CANNOT** do anything that cannot be done in a HyperCritical region or on an arbitrary primary! Try to grab one off the cache
// before we defer to the transmogrificator's thread.
//
PSLIST_ENTRY pEntry = InterlockedPopEntrySList(&m_cachedProxies);
if (pEntry != NULL)
{
InterlockedDecrement(&m_cacheCount);
//
// This does not need a fence as there's no race since we cannot unblock it until after this call returns.
//
pProxy->m_pTransmogrification = CONTAINING_RECORD(pEntry, CachedTransmogrifiedPrimary, m_cacheEntry);
}
else
{
//
// There's nothing on the cache. We cannot perform *ANY* allocation or creation of threads here. We must go back to the transmogrificator's
// thread.
//
m_queuedProxies.AddTail(&(pProxy->m_transmogrificatorPendingQueue));
if (InterlockedIncrement(&m_queuedProxyCount) == 1)
SetEvent(m_hUnblock);
}
}
/// <summary>
/// Unblocks the transmogrification which was created in PerformTransmogrification. Note that PerformTransmogrification
/// must be called first!
/// </summary>
/// <param name="pProxy">
/// The thread proxy whose transmogrification is being unblocked.
/// </param>
void Transmogrificator::UnblockTransmogrification(UMSThreadProxy *pProxy)
{
//
// CAS in a magic constant indicating an immediate unblock. If we pull out the primary, we unblock it. If the other side pulls out
// they unblock.
//
TransmogrifiedPrimary *pTransmogrifiedPrimary = reinterpret_cast<TransmogrifiedPrimary *>(
InterlockedCompareExchangePointer((volatile PVOID *)&pProxy->m_pTransmogrification, (PVOID)TRANSMOGRIFICATION_UNBLOCKED, (PVOID)NULL)
);
if (pTransmogrifiedPrimary != NULL)
pTransmogrifiedPrimary->QueueToCompletion(pProxy);
}
/// <summary>
/// The thread function which awakens when necessary to bind proxies which wish to be transmogrified with new
/// TransmogrifiedPrimary objects.
/// </summary>
void Transmogrificator::BeginTransmogrifying()
{
do
{
ListEntry *pLE = m_queuedProxies.RemoveHead();
UMSThreadProxy *pProxy = CONTAINING_RECORD(pLE, UMSThreadProxy, m_transmogrificatorPendingQueue);
TransmogrifiedPrimary *pTransmogrifiedPrimary = _concrt_new CachedTransmogrifiedPrimary(this);
if ((PVOID)InterlockedExchangePointer((volatile PVOID *)&pProxy->m_pTransmogrification, pTransmogrifiedPrimary) == (PVOID)TRANSMOGRIFICATION_UNBLOCKED)
pTransmogrifiedPrimary->QueueToCompletion(pProxy);
} while (InterlockedDecrement(&m_queuedProxyCount) > 0);
}
/// <summary>
/// Called in order to return a cached transmogrified primary to the transmogrificator.
/// </summary>
void Transmogrificator::ReturnToCache(CachedTransmogrifiedPrimary *pTransmogrifiedPrimary)
{
if (m_cacheCount >= TRANSMOGRIFICATOR_CACHE_DEPTH)
pTransmogrifiedPrimary->Shutdown();
else
{
InterlockedIncrement(&m_cacheCount);
InterlockedPushEntrySList(&m_cachedProxies, &(pTransmogrifiedPrimary->m_cacheEntry));
}
}
} // namespace details
} // namespace Concurrency
| {
"pile_set_name": "Github"
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Routing;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ApplicationModels
{
public class ControllerModelTest
{
[Fact]
public void CopyConstructor_DoesDeepCopyOfOtherModels()
{
// Arrange
var controller = new ControllerModel(typeof(TestController).GetTypeInfo(),
new List<object>());
var action = new ActionModel(typeof(TestController).GetMethod("Edit"),
new List<object>());
controller.Actions.Add(action);
action.Controller = controller;
controller.ControllerProperties.Add(new PropertyModel(
controller.ControllerType.AsType().GetProperty("TestProperty"),
new List<object>() { }));
var route = new AttributeRouteModel(new HttpGetAttribute("api/Products"));
controller.Selectors.Add(new SelectorModel() { AttributeRouteModel = route });
var apiExplorer = controller.ApiExplorer;
controller.ApiExplorer.GroupName = "group";
controller.ApiExplorer.IsVisible = true;
// Act
var controller2 = new ControllerModel(controller);
// Assert
Assert.NotSame(action, controller2.Actions[0]);
Assert.NotNull(controller2.ControllerProperties);
Assert.Single(controller2.ControllerProperties);
Assert.NotNull(controller2.Selectors);
Assert.Single(controller2.Selectors);
Assert.NotSame(route, controller2.Selectors[0].AttributeRouteModel);
Assert.NotSame(apiExplorer, controller2.ApiExplorer);
Assert.NotSame(controller.Selectors[0].ActionConstraints, controller2.Selectors[0].ActionConstraints);
Assert.NotSame(controller.Actions, controller2.Actions);
Assert.NotSame(controller.Attributes, controller2.Attributes);
Assert.NotSame(controller.Filters, controller2.Filters);
Assert.NotSame(controller.RouteValues, controller2.RouteValues);
Assert.NotSame(controller, controller2.Actions[0].Controller);
Assert.Same(controller2, controller2.Actions[0].Controller);
Assert.NotSame(controller, controller2.ControllerProperties[0].Controller);
Assert.Same(controller2, controller2.ControllerProperties[0].Controller);
}
[Fact]
public void CopyConstructor_CopiesAllProperties()
{
// Arrange
var controller = new ControllerModel(
typeof(TestController).GetTypeInfo(),
new List<object>()
{
new HttpGetAttribute(),
new MyFilterAttribute(),
});
var selectorModel = new SelectorModel();
selectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(new string[] { "GET" }));
controller.Selectors.Add(selectorModel);
controller.Application = new ApplicationModel();
controller.ControllerName = "cool";
controller.Filters.Add(new MyFilterAttribute());
controller.RouteValues.Add("key", "value");
controller.Properties.Add(new KeyValuePair<object, object>("test key", "test value"));
controller.ControllerProperties.Add(
new PropertyModel(typeof(TestController).GetProperty("TestProperty"), new List<object>()));
// Act
var controller2 = new ControllerModel(controller);
// Assert
foreach (var property in typeof(ControllerModel).GetProperties())
{
if (property.Name.Equals("Actions") ||
property.Name.Equals("Selectors") ||
property.Name.Equals("ApiExplorer") ||
property.Name.Equals("ControllerProperties"))
{
// This test excludes other ApplicationModel objects on purpose because we deep copy them.
continue;
}
var value1 = property.GetValue(controller);
var value2 = property.GetValue(controller2);
if (typeof(IEnumerable<object>).IsAssignableFrom(property.PropertyType))
{
Assert.Equal<object>((IEnumerable<object>)value1, (IEnumerable<object>)value2);
// Ensure non-default value
Assert.NotEmpty((IEnumerable<object>)value1);
}
else if (typeof(IDictionary<string, string>).IsAssignableFrom(property.PropertyType))
{
Assert.Equal(value1, value2);
// Ensure non-default value
Assert.NotEmpty((IDictionary<string, string>)value1);
}
else if (typeof(IDictionary<object, object>).IsAssignableFrom(property.PropertyType))
{
Assert.Equal(value1, value2);
// Ensure non-default value
Assert.NotEmpty((IDictionary<object, object>)value1);
}
else if (property.PropertyType.GetTypeInfo().IsValueType ||
Nullable.GetUnderlyingType(property.PropertyType) != null)
{
Assert.Equal(value1, value2);
// Ensure non-default value
Assert.NotEqual(value1, Activator.CreateInstance(property.PropertyType));
}
else if (property.Name.Equals(nameof(ControllerModel.DisplayName)))
{
// DisplayName is re-calculated, hence reference equality wouldn't work.
Assert.Equal(value1, value2);
}
else
{
Assert.Same(value1, value2);
// Ensure non-default value
Assert.NotNull(value1);
}
}
}
private class TestController
{
public string TestProperty { get; set; }
public void Edit()
{
}
}
private class MyFilterAttribute : Attribute, IFilterMetadata
{
}
private class MyRouteValueAttribute : Attribute, IRouteValueProvider
{
public string RouteKey { get; set; }
public string RouteValue { get; set; }
}
}
} | {
"pile_set_name": "Github"
} |
import re
#from core.color import bcolors
from color import bcolors
AV_list = {
"Kaspersky": ["avp", "avpui", "klif", "KAVFS", "kavfsslp","prunsrv"],
"Malwarebytes":["mbcloudea","mbamservice"],
"Symantec": ["SmcGui", "SISIPSService","SemSvc","snac64","sesmcontinst"],
"Bitdefender": ["vsserv"],
"TrendMicro": ["tmntsrv","PwmTower"],
"Windows Defender": ["MsMpEng"],
"Avast": ["aswBcc", "bcc"],
"Cylance": ["CylanceSvc", "CylanceUi"],
"ESET": ["epfw", "epfwlwf", "epfwwfp"],
"FireEye Endpoint Agent": ["xagt"],
"F-Secure": ["fsdevcon", "FSORSPClient"],
"MacAfee": ["enterceptagent", "McAfeeEngineService", "McAfeeFramework"],
"SentinelOne": ["SentinelAgent", "SentinelOne"],
"Sophos": ["sophosssp", "sophossps"],
"ZoneALarm": ["zlclient"],
"Panda AntiVirus": ["AVENGINE"],
"AVG": ["avgemc"],
"Avira" : ["avscan"],
"G data" : ["AVKProxy"],
}
AV_score={
"Kaspersky": 8,
"Malwarebytes":5,
"Symantec": 5,
"Bitdefender": 5,
"TrendMicro": 6,
"Windows Defender": 5,
"Avast": 4,
"Cylance": 4,
"ESET": 4,
"FireEye Endpoint Agent": 6,
"F-Secure": 5,
"MacAfee": 3,
"SentinelOne": 5,
"Sophos": 4,
"ZoneALarm": 3,
"Panda AntiVirus": 3,
"AVG": 4,
"Avira" : 3,
"G data" : 3,
}
Sandbox_IOC={
"wireshark": 6,
"vboxservice":7,
"vboxtray":7,
"autorun":7,
"procexp":7,
"procmon":7,
"tcpview":7,
"powershell_ise":4,
"sysmon":7,
}
SIEM = {
"Splunk":["splunk-admon","splunkd","splunk-winevtlog","splunk-netmon"],
"Sysmon":["sysmon"],
"Elastic Search / Gray Log":["winlogbeat"]
}
score=[]
sandbox=[]
def detect_SIEM(ps):
global SIEM,score,sandbox
siem=[]
for i in ps.split():
for t,s in SIEM.items():
for pc in s:
if i.split(".")[0]==pc.lower() and not (t in siem):
siem.append(t)
score.append(9)
sandbox.append(6)
l=len(siem)
if l>0:
print bcolors.FAIL +"SIEM detected using process list : "+ bcolors.ENDC,siem
print "###################################"
else:
print bcolors.OKGREEN+"No SIEM Detected "+ bcolors.ENDC
print "###################################"
def detect_AV(ps,av):
global AV_list,score,sandbox,AV_score
AV=[]
AVP=[]
for i in av.split("\n"):
fields=i.split(":")
if fields[0].strip()=="displayName":
AV.append(fields[1])
l=len(AV)
if l>0:
print bcolors.FAIL +"AV detected using powershell API : "+ bcolors.ENDC,AV
for i in ps.split():
for t,s in AV_list.items():
for pc in s:
if i.split(".")[0]==pc.lower() and not (t in AVP):
AVP.append(t)
score.append(AV_score[t])
l=len(AVP)
if l>0:
print bcolors.FAIL +"AV detected using process list : "+ bcolors.ENDC,AVP
print "###################################"
else:
print bcolors.OKGREEN+"No AV Detected "+ bcolors.ENDC
print "###################################"
def AD_enum(adusers,adgroups,ADPC):
print "\n\nDomain Users :\n"
for i in adusers.split("\n"):
fields=i.split(": ")
#print fields[0]
if fields[0].strip()=="Name":
print fields[1].strip(),",",
print "\n\n############\nDomain Groups :\n"
for i in adgroups.split("\n")[4:]:
print i.strip(),",",
print "\n\n############\nDomain Computers :\n"
#print ADPC.split("\n\n")[1].split("\n")
for i in ADPC.split("\n\n"):
for d in i.split("\n"):
fields=d.split(": ")
if fields[0].strip()=="name":
print fields[1].strip(),",",
print "\n\n###################################"
def detect_sandbox(ps):
global Sandbox_IOC
for i in ps.split():
for t,s in Sandbox_IOC.items():
if i.split(".")[0]==t.lower():
sandbox.append(s)
def PCinfo(pcinfo):
global score,sandbox
pclist={}
"""for i in pcinfo.split("\n"):
fields=i.split(": ")
#if fields[0].strip()=="OsVersion":
if len(fields)>1:
pclist[fields[0].strip()]=fields[1]
print "PC Report : \nHost Name: %s \nUser Name: %s \nOS : %s \nOS Version : %s \nLocal Time : %s \nTime Zone : %s \nUP Time : %s \nBios Manufacturer : %s \n" % (pclist["CsDNSHostName"],pclist["CsUserName"],pclist["OsName"],pclist["OsVersion"],pclist["OsLocalDateTime"],pclist["TimeZone"],pclist["OsUptime"],pclist["BiosManufacturer"])
"""
for i in pcinfo.split("\n"):
fields=i.split(": ")
#if fields[0].strip()=="OsVersion":
if len(fields)>1:
pclist[fields[0].strip()]=fields[1]
print "PC Report : \n Host Name: %s \n OS : %s \n Build Number : %s \n Local Time : %s \n Time Zone : %s \n Last Boot Time : %s \n " % (pclist["CSName"],pclist["Caption"],pclist["BuildNumber"],pclist["LocalDateTime"],pclist["CurrentTimeZone"],pclist["LastBootUpTime"]),"Bios Manufacturer : "+pclist["Manufacturer"].strip()+" , "+pclist["SMBIOSBIOSVersion"].strip()+" \n###################################"
if pclist["Manufacturer"].strip().lower().find("innotek")>-1 or pclist["SMBIOSBIOSVersion"].strip().lower().find("virtualbox")>-1:
sandbox.append(9)
if pclist["Caption"].strip().lower().find("windows 10")>-1:
score.append(8)
if pclist["Caption"].strip().lower().find("windows 7")>-1:
score.append(4)
if pclist["Caption"].strip().lower().find("windows 8")>-1:
score.append(5)
if pclist["Caption"].strip().lower().find("windows server 2012")>-1:
score.append(5)
if pclist["Caption"].strip().lower().find("windows server 2016")>-1:
score.append(8)
def gethotfix(hotfixes):
result = re.findall(r"KB\d{7}", hotfixes)
print "Installed Updates : ",
for i in result:
print i,
print "\n###################################"
def getpwl(pwl):
global score,sandbox
if pwl.find("Windows PowerShell")>=0:
print bcolors.FAIL +"powershell logging enabled"+ bcolors.ENDC
score.append(2)
sandbox.append(8)
else:
score.append(8)
sandbox.append(1)
print "###################################"
def getadmin(isadmin):
global score,sandbox
if isadmin.strip()=="True":
print "you have admin privileges"+ bcolors.ENDC
score.append(3)
sandbox.append(7)
else:
print bcolors.FAIL +"you don't have admin privileges"+ bcolors.ENDC
score.append(9)
sandbox.append(1)
print "###################################"
def getjoined(isjoined):
global score,sandbox
if isjoined.strip().replace("\n","").split(",")[0].strip()=="True":
print bcolors.OKGREEN +"this device part of the domain "+isjoined.strip("\n").split(",")[1]+ bcolors.ENDC
score.append(8)
sandbox.append(1)
print "###################################"
return True
else:
print bcolors.FAIL +"this device is not part of domain"+ bcolors.ENDC
score.append(3)
sandbox.append(5)
print "###################################"
return False
def getscore():
global score,sandbox
sum=0
for i in score:
#print i,
sum=sum+i
avg=(sum/len(score))
if avg<=4:
print bcolors.OKGREEN +"Hardness score ("+str(avg)+"/10"+") : Easy , you can pwn the system easily"+ bcolors.ENDC
if avg>=5 and avg<=7:
print bcolors.WARNING +"Hardness score ("+str(avg)+"/10"+") : Medium , you can pwn the system with good enumeration and availble local exploit "+ bcolors.ENDC
if avg>7:
print bcolors.FAIL +"Hardness score ("+str(avg)+"/10"+") : Hard , be careful from the AV and the security updates installed"+ bcolors.ENDC
sum=0
for i in sandbox:
#print i,
sum=sum+i
avg=(sum/len(sandbox))
if avg<=4:
print bcolors.OKGREEN +"Sandbox Score ("+str(avg)+"/10"+") : you are probably in real live system"+ bcolors.ENDC
if avg>=5 and avg<=7:
print bcolors.WARNING +"Sandbox Score ("+str(avg)+"/10"+") : check and confirm as you probably in a security analyst device"+ bcolors.ENDC
if avg>7:
print bcolors.FAIL +"Sandbox Score ("+str(avg)+"/10"+") : you are in a sandbox"+ bcolors.ENDC
print "###################################"
def main(fname="DA/DA_out.txt"):
try:
file=open(fname)
data=file.read()
data=data.split("###############")
av=data[1] # AV data
ps=data[2] # process list
pwl=data[3] # powershell winevent logging
isadmin=data[4] # is the user admin ( true or flase)
isjoined=data[5] # is the device joined to domain ( true or flase)
pcinfo=data[6] # system info
hotfixes=data[7] # HOT FIXES Updates
adusers=data[8] # active directory user list
adgroups=data[9] # active directory groups
#loggedin=data[10]
ADPC=data[10] # active directory PCs
shares=data[11] # network shares
#print av,ps,pwl,isadmin,isjoined,pcinfo,hotfixes
detect_SIEM(ps)
detect_AV(ps,av)
detect_sandbox(ps)
getpwl(pwl)
getadmin(isadmin)
joined=getjoined(isjoined)
PCinfo(pcinfo)
getscore()
gethotfix(hotfixes)
if joined:
AD_enum(adusers,adgroups,ADPC)
print "\nShares :\n",shares
except Exception as e:
print '[-] ERROR(webserver->main): %s' % str(e)
| {
"pile_set_name": "Github"
} |
// import { shallow } from 'enzyme'
// import React from 'react'
import {
// HeaderMessagesUnconnected,
mapStateToProps
} from "../header-messages";
// describe('HeaderMessagesUnconnected React component', () => {
//
// })
describe("HeaderMessages mapStateToProps", () => {
let state;
let ownProps;
beforeEach(() => {
state = {
viewMode: "EXPLORE_VIEW",
userData: {
name: "user"
},
notebookInfo: {
user_can_save: true,
revision_is_latest: true,
connectionMode: "SERVER"
}
};
ownProps = {};
});
it("displays standalone notification", () => {
state.notebookInfo.connectionMode = "STANDALONE";
expect(mapStateToProps(state, ownProps).message).toEqual("STANDALONE_MODE");
});
it("displays login message", () => {
state.userData.name = undefined;
state.notebookInfo.user_can_save = false;
expect(mapStateToProps(state, ownProps).message).toEqual("NEED_TO_LOGIN");
});
it("displays make a copy message", () => {
state.notebookInfo.user_can_save = false;
state.notebookInfo.username = "test";
const props = mapStateToProps(state, ownProps);
expect(props.message).toEqual("NEED_TO_MAKE_COPY");
expect(props.owner).toEqual("test");
});
[
["ERROR_GENERAL", "SERVER_ERROR_GENERAL"],
["ERROR_OUT_OF_DATE", "NOTEBOOK_REVISION_ID_OUT_OF_DATE"],
["ERROR_UNAUTHORIZED", "SERVER_ERROR_UNAUTHORIZED"]
].forEach(errorTuple => {
const [serverError, expectedMessage] = errorTuple;
it(`gives ${expectedMessage} when server error is ${serverError}`, () => {
state.notebookInfo.serverSaveStatus = serverError;
const props = mapStateToProps(state, ownProps);
expect(props.message).toEqual(expectedMessage);
});
});
it("lets you know when your notebook is based on an historical revision", () => {
state.notebookInfo.revision_is_latest = false;
const props = mapStateToProps(state, ownProps);
expect(props.message).toEqual("NOTEBOOK_REVISION_ID_OUT_OF_DATE");
});
it("displays nothing", () => {
expect(mapStateToProps(state, ownProps).message).toEqual(undefined);
});
});
| {
"pile_set_name": "Github"
} |
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<command>
<create>
<domain:create
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>%DOMAIN%</domain:name>
<domain:period unit="y">2</domain:period>
<domain:ns>
<domain:hostObj>ns1.example.net</domain:hostObj>
<domain:hostObj>ns2.example.net</domain:hostObj>
</domain:ns>
<domain:registrant>jd1234</domain:registrant>
<domain:contact type="admin">sh8013</domain:contact>
<domain:contact type="tech">sh8013</domain:contact>
<domain:authInfo>
<domain:pw>2fooBAR</domain:pw>
</domain:authInfo>
</domain:create>
</create>
<clTRID>ABC-12345</clTRID>
</command>
</epp>
| {
"pile_set_name": "Github"
} |
/*-
* Copyright (c) 2005 Doug Rabson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/lib/libgssapi/gss_release_buffer.c,v 1.1 2005/12/29 14:40:20 dfr Exp $
*/
#include "mech_locl.h"
GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
gss_release_buffer(OM_uint32 *minor_status,
gss_buffer_t buffer)
{
*minor_status = 0;
if (buffer->value)
free(buffer->value);
_mg_buffer_zero(buffer);
return (GSS_S_COMPLETE);
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 85cf57768a283fa4987b42b68edc3bb1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
set(_compiler_id_pp_test "defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__)")
set(_compiler_id_version_compute "
#if defined(__VISUALDSPVERSION__)
/* __VISUALDSPVERSION__ = 0xVVRRPP00 */
# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_HEX@(__VISUALDSPVERSION__>>24)
# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_HEX@(__VISUALDSPVERSION__>>16 & 0xFF)
# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_HEX@(__VISUALDSPVERSION__>>8 & 0xFF)
#endif")
| {
"pile_set_name": "Github"
} |
"""
literal = [|
class Foo:
def bar():
print 'Hello'
|]
literal = [|
def main():
print('Hello, world!')
|]
literal = [|
private foo as int
|]
literal = [|
private foo = 0
|]
literal = [|
private foo as object = object()
|]
literal = [|
event Foo as Bar
|]
litera = [|
[once]
def bar():
return foo()
|]
"""
literal = [|
class Foo:
def bar():
print 'Hello'
end
end
|]
literal = [|
def main():
print('Hello, world!')
end
|]
literal = [|
private foo as int
|]
literal = [|
private foo = 0
|]
literal = [|
private foo as object = object()
|]
literal = [|
event Foo as Bar
|]
litera = [|
[once]
def bar():
return foo()
end
|]
| {
"pile_set_name": "Github"
} |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is auto-generated from
// gpu/ipc/common/generate_vulkan_types.py
// It's formatted by clang-format using chromium coding style:
// clang-format -i -style=chromium filename
// DO NOT EDIT!
#ifndef GPU_IPC_COMMON_VULKAN_TYPES_MOJOM_TRAITS_H_
#define GPU_IPC_COMMON_VULKAN_TYPES_MOJOM_TRAITS_H_
#include "base/containers/span.h"
#include "base/strings/string_piece.h"
#include "gpu/ipc/common/vulkan_types.h"
#include "gpu/ipc/common/vulkan_types.mojom-shared.h"
namespace mojo {
template <>
struct StructTraits<gpu::mojom::VkExtensionPropertiesDataView,
VkExtensionProperties> {
static base::StringPiece extensionName(const VkExtensionProperties& input) {
return input.extensionName;
}
static uint32_t specVersion(const VkExtensionProperties& input) {
return input.specVersion;
}
static bool Read(gpu::mojom::VkExtensionPropertiesDataView data,
VkExtensionProperties* out);
};
template <>
struct StructTraits<gpu::mojom::VkLayerPropertiesDataView, VkLayerProperties> {
static base::StringPiece layerName(const VkLayerProperties& input) {
return input.layerName;
}
static uint32_t specVersion(const VkLayerProperties& input) {
return input.specVersion;
}
static uint32_t implementationVersion(const VkLayerProperties& input) {
return input.implementationVersion;
}
static base::StringPiece description(const VkLayerProperties& input) {
return input.description;
}
static bool Read(gpu::mojom::VkLayerPropertiesDataView data,
VkLayerProperties* out);
};
template <>
struct StructTraits<gpu::mojom::VkPhysicalDevicePropertiesDataView,
VkPhysicalDeviceProperties> {
static uint32_t apiVersion(const VkPhysicalDeviceProperties& input) {
return input.apiVersion;
}
static uint32_t driverVersion(const VkPhysicalDeviceProperties& input) {
return input.driverVersion;
}
static uint32_t vendorID(const VkPhysicalDeviceProperties& input) {
return input.vendorID;
}
static uint32_t deviceID(const VkPhysicalDeviceProperties& input) {
return input.deviceID;
}
static VkPhysicalDeviceType deviceType(
const VkPhysicalDeviceProperties& input) {
return input.deviceType;
}
static base::StringPiece deviceName(const VkPhysicalDeviceProperties& input) {
return input.deviceName;
}
static base::span<const uint8_t> pipelineCacheUUID(
const VkPhysicalDeviceProperties& input) {
return input.pipelineCacheUUID;
}
static const VkPhysicalDeviceLimits& limits(
const VkPhysicalDeviceProperties& input) {
return input.limits;
}
static const VkPhysicalDeviceSparseProperties& sparseProperties(
const VkPhysicalDeviceProperties& input) {
return input.sparseProperties;
}
static bool Read(gpu::mojom::VkPhysicalDevicePropertiesDataView data,
VkPhysicalDeviceProperties* out);
};
template <>
struct EnumTraits<gpu::mojom::VkPhysicalDeviceType, VkPhysicalDeviceType> {
static gpu::mojom::VkPhysicalDeviceType ToMojom(VkPhysicalDeviceType input) {
switch (input) {
case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_OTHER:
return gpu::mojom::VkPhysicalDeviceType::OTHER;
case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
return gpu::mojom::VkPhysicalDeviceType::INTEGRATED_GPU;
case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
return gpu::mojom::VkPhysicalDeviceType::DISCRETE_GPU;
case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
return gpu::mojom::VkPhysicalDeviceType::VIRTUAL_GPU;
case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_CPU:
return gpu::mojom::VkPhysicalDeviceType::CPU;
default:
NOTREACHED();
return gpu::mojom::VkPhysicalDeviceType::INVALID_VALUE;
}
}
static bool FromMojom(gpu::mojom::VkPhysicalDeviceType input,
VkPhysicalDeviceType* out) {
switch (input) {
case gpu::mojom::VkPhysicalDeviceType::OTHER:
*out = VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_OTHER;
return true;
case gpu::mojom::VkPhysicalDeviceType::INTEGRATED_GPU:
*out = VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
return true;
case gpu::mojom::VkPhysicalDeviceType::DISCRETE_GPU:
*out = VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
return true;
case gpu::mojom::VkPhysicalDeviceType::VIRTUAL_GPU:
*out = VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU;
return true;
case gpu::mojom::VkPhysicalDeviceType::CPU:
*out = VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_CPU;
return true;
case gpu::mojom::VkPhysicalDeviceType::INVALID_VALUE:
NOTREACHED();
return false;
}
NOTREACHED();
return false;
}
};
template <>
struct StructTraits<gpu::mojom::VkPhysicalDeviceLimitsDataView,
VkPhysicalDeviceLimits> {
static uint32_t maxImageDimension1D(const VkPhysicalDeviceLimits& input) {
return input.maxImageDimension1D;
}
static uint32_t maxImageDimension2D(const VkPhysicalDeviceLimits& input) {
return input.maxImageDimension2D;
}
static uint32_t maxImageDimension3D(const VkPhysicalDeviceLimits& input) {
return input.maxImageDimension3D;
}
static uint32_t maxImageDimensionCube(const VkPhysicalDeviceLimits& input) {
return input.maxImageDimensionCube;
}
static uint32_t maxImageArrayLayers(const VkPhysicalDeviceLimits& input) {
return input.maxImageArrayLayers;
}
static uint32_t maxTexelBufferElements(const VkPhysicalDeviceLimits& input) {
return input.maxTexelBufferElements;
}
static uint32_t maxUniformBufferRange(const VkPhysicalDeviceLimits& input) {
return input.maxUniformBufferRange;
}
static uint32_t maxStorageBufferRange(const VkPhysicalDeviceLimits& input) {
return input.maxStorageBufferRange;
}
static uint32_t maxPushConstantsSize(const VkPhysicalDeviceLimits& input) {
return input.maxPushConstantsSize;
}
static uint32_t maxMemoryAllocationCount(
const VkPhysicalDeviceLimits& input) {
return input.maxMemoryAllocationCount;
}
static uint32_t maxSamplerAllocationCount(
const VkPhysicalDeviceLimits& input) {
return input.maxSamplerAllocationCount;
}
static bool bufferImageGranularity(const VkPhysicalDeviceLimits& input) {
return input.bufferImageGranularity;
}
static bool sparseAddressSpaceSize(const VkPhysicalDeviceLimits& input) {
return input.sparseAddressSpaceSize;
}
static uint32_t maxBoundDescriptorSets(const VkPhysicalDeviceLimits& input) {
return input.maxBoundDescriptorSets;
}
static uint32_t maxPerStageDescriptorSamplers(
const VkPhysicalDeviceLimits& input) {
return input.maxPerStageDescriptorSamplers;
}
static uint32_t maxPerStageDescriptorUniformBuffers(
const VkPhysicalDeviceLimits& input) {
return input.maxPerStageDescriptorUniformBuffers;
}
static uint32_t maxPerStageDescriptorStorageBuffers(
const VkPhysicalDeviceLimits& input) {
return input.maxPerStageDescriptorStorageBuffers;
}
static uint32_t maxPerStageDescriptorSampledImages(
const VkPhysicalDeviceLimits& input) {
return input.maxPerStageDescriptorSampledImages;
}
static uint32_t maxPerStageDescriptorStorageImages(
const VkPhysicalDeviceLimits& input) {
return input.maxPerStageDescriptorStorageImages;
}
static uint32_t maxPerStageDescriptorInputAttachments(
const VkPhysicalDeviceLimits& input) {
return input.maxPerStageDescriptorInputAttachments;
}
static uint32_t maxPerStageResources(const VkPhysicalDeviceLimits& input) {
return input.maxPerStageResources;
}
static uint32_t maxDescriptorSetSamplers(
const VkPhysicalDeviceLimits& input) {
return input.maxDescriptorSetSamplers;
}
static uint32_t maxDescriptorSetUniformBuffers(
const VkPhysicalDeviceLimits& input) {
return input.maxDescriptorSetUniformBuffers;
}
static uint32_t maxDescriptorSetUniformBuffersDynamic(
const VkPhysicalDeviceLimits& input) {
return input.maxDescriptorSetUniformBuffersDynamic;
}
static uint32_t maxDescriptorSetStorageBuffers(
const VkPhysicalDeviceLimits& input) {
return input.maxDescriptorSetStorageBuffers;
}
static uint32_t maxDescriptorSetStorageBuffersDynamic(
const VkPhysicalDeviceLimits& input) {
return input.maxDescriptorSetStorageBuffersDynamic;
}
static uint32_t maxDescriptorSetSampledImages(
const VkPhysicalDeviceLimits& input) {
return input.maxDescriptorSetSampledImages;
}
static uint32_t maxDescriptorSetStorageImages(
const VkPhysicalDeviceLimits& input) {
return input.maxDescriptorSetStorageImages;
}
static uint32_t maxDescriptorSetInputAttachments(
const VkPhysicalDeviceLimits& input) {
return input.maxDescriptorSetInputAttachments;
}
static uint32_t maxVertexInputAttributes(
const VkPhysicalDeviceLimits& input) {
return input.maxVertexInputAttributes;
}
static uint32_t maxVertexInputBindings(const VkPhysicalDeviceLimits& input) {
return input.maxVertexInputBindings;
}
static uint32_t maxVertexInputAttributeOffset(
const VkPhysicalDeviceLimits& input) {
return input.maxVertexInputAttributeOffset;
}
static uint32_t maxVertexInputBindingStride(
const VkPhysicalDeviceLimits& input) {
return input.maxVertexInputBindingStride;
}
static uint32_t maxVertexOutputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxVertexOutputComponents;
}
static uint32_t maxTessellationGenerationLevel(
const VkPhysicalDeviceLimits& input) {
return input.maxTessellationGenerationLevel;
}
static uint32_t maxTessellationPatchSize(
const VkPhysicalDeviceLimits& input) {
return input.maxTessellationPatchSize;
}
static uint32_t maxTessellationControlPerVertexInputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxTessellationControlPerVertexInputComponents;
}
static uint32_t maxTessellationControlPerVertexOutputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxTessellationControlPerVertexOutputComponents;
}
static uint32_t maxTessellationControlPerPatchOutputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxTessellationControlPerPatchOutputComponents;
}
static uint32_t maxTessellationControlTotalOutputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxTessellationControlTotalOutputComponents;
}
static uint32_t maxTessellationEvaluationInputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxTessellationEvaluationInputComponents;
}
static uint32_t maxTessellationEvaluationOutputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxTessellationEvaluationOutputComponents;
}
static uint32_t maxGeometryShaderInvocations(
const VkPhysicalDeviceLimits& input) {
return input.maxGeometryShaderInvocations;
}
static uint32_t maxGeometryInputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxGeometryInputComponents;
}
static uint32_t maxGeometryOutputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxGeometryOutputComponents;
}
static uint32_t maxGeometryOutputVertices(
const VkPhysicalDeviceLimits& input) {
return input.maxGeometryOutputVertices;
}
static uint32_t maxGeometryTotalOutputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxGeometryTotalOutputComponents;
}
static uint32_t maxFragmentInputComponents(
const VkPhysicalDeviceLimits& input) {
return input.maxFragmentInputComponents;
}
static uint32_t maxFragmentOutputAttachments(
const VkPhysicalDeviceLimits& input) {
return input.maxFragmentOutputAttachments;
}
static uint32_t maxFragmentDualSrcAttachments(
const VkPhysicalDeviceLimits& input) {
return input.maxFragmentDualSrcAttachments;
}
static uint32_t maxFragmentCombinedOutputResources(
const VkPhysicalDeviceLimits& input) {
return input.maxFragmentCombinedOutputResources;
}
static uint32_t maxComputeSharedMemorySize(
const VkPhysicalDeviceLimits& input) {
return input.maxComputeSharedMemorySize;
}
static base::span<const uint32_t> maxComputeWorkGroupCount(
const VkPhysicalDeviceLimits& input) {
return input.maxComputeWorkGroupCount;
}
static uint32_t maxComputeWorkGroupInvocations(
const VkPhysicalDeviceLimits& input) {
return input.maxComputeWorkGroupInvocations;
}
static base::span<const uint32_t> maxComputeWorkGroupSize(
const VkPhysicalDeviceLimits& input) {
return input.maxComputeWorkGroupSize;
}
static uint32_t subPixelPrecisionBits(const VkPhysicalDeviceLimits& input) {
return input.subPixelPrecisionBits;
}
static uint32_t subTexelPrecisionBits(const VkPhysicalDeviceLimits& input) {
return input.subTexelPrecisionBits;
}
static uint32_t mipmapPrecisionBits(const VkPhysicalDeviceLimits& input) {
return input.mipmapPrecisionBits;
}
static uint32_t maxDrawIndexedIndexValue(
const VkPhysicalDeviceLimits& input) {
return input.maxDrawIndexedIndexValue;
}
static uint32_t maxDrawIndirectCount(const VkPhysicalDeviceLimits& input) {
return input.maxDrawIndirectCount;
}
static float maxSamplerLodBias(const VkPhysicalDeviceLimits& input) {
return input.maxSamplerLodBias;
}
static float maxSamplerAnisotropy(const VkPhysicalDeviceLimits& input) {
return input.maxSamplerAnisotropy;
}
static uint32_t maxViewports(const VkPhysicalDeviceLimits& input) {
return input.maxViewports;
}
static base::span<const uint32_t> maxViewportDimensions(
const VkPhysicalDeviceLimits& input) {
return input.maxViewportDimensions;
}
static base::span<const float> viewportBoundsRange(
const VkPhysicalDeviceLimits& input) {
return input.viewportBoundsRange;
}
static uint32_t viewportSubPixelBits(const VkPhysicalDeviceLimits& input) {
return input.viewportSubPixelBits;
}
static size_t minMemoryMapAlignment(const VkPhysicalDeviceLimits& input) {
return input.minMemoryMapAlignment;
}
static bool minTexelBufferOffsetAlignment(
const VkPhysicalDeviceLimits& input) {
return input.minTexelBufferOffsetAlignment;
}
static bool minUniformBufferOffsetAlignment(
const VkPhysicalDeviceLimits& input) {
return input.minUniformBufferOffsetAlignment;
}
static bool minStorageBufferOffsetAlignment(
const VkPhysicalDeviceLimits& input) {
return input.minStorageBufferOffsetAlignment;
}
static int32_t minTexelOffset(const VkPhysicalDeviceLimits& input) {
return input.minTexelOffset;
}
static uint32_t maxTexelOffset(const VkPhysicalDeviceLimits& input) {
return input.maxTexelOffset;
}
static int32_t minTexelGatherOffset(const VkPhysicalDeviceLimits& input) {
return input.minTexelGatherOffset;
}
static uint32_t maxTexelGatherOffset(const VkPhysicalDeviceLimits& input) {
return input.maxTexelGatherOffset;
}
static float minInterpolationOffset(const VkPhysicalDeviceLimits& input) {
return input.minInterpolationOffset;
}
static float maxInterpolationOffset(const VkPhysicalDeviceLimits& input) {
return input.maxInterpolationOffset;
}
static uint32_t subPixelInterpolationOffsetBits(
const VkPhysicalDeviceLimits& input) {
return input.subPixelInterpolationOffsetBits;
}
static uint32_t maxFramebufferWidth(const VkPhysicalDeviceLimits& input) {
return input.maxFramebufferWidth;
}
static uint32_t maxFramebufferHeight(const VkPhysicalDeviceLimits& input) {
return input.maxFramebufferHeight;
}
static uint32_t maxFramebufferLayers(const VkPhysicalDeviceLimits& input) {
return input.maxFramebufferLayers;
}
static VkSampleCountFlags framebufferColorSampleCounts(
const VkPhysicalDeviceLimits& input) {
return input.framebufferColorSampleCounts;
}
static VkSampleCountFlags framebufferDepthSampleCounts(
const VkPhysicalDeviceLimits& input) {
return input.framebufferDepthSampleCounts;
}
static VkSampleCountFlags framebufferStencilSampleCounts(
const VkPhysicalDeviceLimits& input) {
return input.framebufferStencilSampleCounts;
}
static VkSampleCountFlags framebufferNoAttachmentsSampleCounts(
const VkPhysicalDeviceLimits& input) {
return input.framebufferNoAttachmentsSampleCounts;
}
static uint32_t maxColorAttachments(const VkPhysicalDeviceLimits& input) {
return input.maxColorAttachments;
}
static VkSampleCountFlags sampledImageColorSampleCounts(
const VkPhysicalDeviceLimits& input) {
return input.sampledImageColorSampleCounts;
}
static VkSampleCountFlags sampledImageIntegerSampleCounts(
const VkPhysicalDeviceLimits& input) {
return input.sampledImageIntegerSampleCounts;
}
static VkSampleCountFlags sampledImageDepthSampleCounts(
const VkPhysicalDeviceLimits& input) {
return input.sampledImageDepthSampleCounts;
}
static VkSampleCountFlags sampledImageStencilSampleCounts(
const VkPhysicalDeviceLimits& input) {
return input.sampledImageStencilSampleCounts;
}
static VkSampleCountFlags storageImageSampleCounts(
const VkPhysicalDeviceLimits& input) {
return input.storageImageSampleCounts;
}
static uint32_t maxSampleMaskWords(const VkPhysicalDeviceLimits& input) {
return input.maxSampleMaskWords;
}
static bool timestampComputeAndGraphics(const VkPhysicalDeviceLimits& input) {
return input.timestampComputeAndGraphics;
}
static float timestampPeriod(const VkPhysicalDeviceLimits& input) {
return input.timestampPeriod;
}
static uint32_t maxClipDistances(const VkPhysicalDeviceLimits& input) {
return input.maxClipDistances;
}
static uint32_t maxCullDistances(const VkPhysicalDeviceLimits& input) {
return input.maxCullDistances;
}
static uint32_t maxCombinedClipAndCullDistances(
const VkPhysicalDeviceLimits& input) {
return input.maxCombinedClipAndCullDistances;
}
static uint32_t discreteQueuePriorities(const VkPhysicalDeviceLimits& input) {
return input.discreteQueuePriorities;
}
static base::span<const float> pointSizeRange(
const VkPhysicalDeviceLimits& input) {
return input.pointSizeRange;
}
static base::span<const float> lineWidthRange(
const VkPhysicalDeviceLimits& input) {
return input.lineWidthRange;
}
static float pointSizeGranularity(const VkPhysicalDeviceLimits& input) {
return input.pointSizeGranularity;
}
static float lineWidthGranularity(const VkPhysicalDeviceLimits& input) {
return input.lineWidthGranularity;
}
static bool strictLines(const VkPhysicalDeviceLimits& input) {
return input.strictLines;
}
static bool standardSampleLocations(const VkPhysicalDeviceLimits& input) {
return input.standardSampleLocations;
}
static bool optimalBufferCopyOffsetAlignment(
const VkPhysicalDeviceLimits& input) {
return input.optimalBufferCopyOffsetAlignment;
}
static bool optimalBufferCopyRowPitchAlignment(
const VkPhysicalDeviceLimits& input) {
return input.optimalBufferCopyRowPitchAlignment;
}
static bool nonCoherentAtomSize(const VkPhysicalDeviceLimits& input) {
return input.nonCoherentAtomSize;
}
static bool Read(gpu::mojom::VkPhysicalDeviceLimitsDataView data,
VkPhysicalDeviceLimits* out);
};
template <>
struct StructTraits<gpu::mojom::VkPhysicalDeviceSparsePropertiesDataView,
VkPhysicalDeviceSparseProperties> {
static bool residencyStandard2DBlockShape(
const VkPhysicalDeviceSparseProperties& input) {
return input.residencyStandard2DBlockShape;
}
static bool residencyStandard2DMultisampleBlockShape(
const VkPhysicalDeviceSparseProperties& input) {
return input.residencyStandard2DMultisampleBlockShape;
}
static bool residencyStandard3DBlockShape(
const VkPhysicalDeviceSparseProperties& input) {
return input.residencyStandard3DBlockShape;
}
static bool residencyAlignedMipSize(
const VkPhysicalDeviceSparseProperties& input) {
return input.residencyAlignedMipSize;
}
static bool residencyNonResidentStrict(
const VkPhysicalDeviceSparseProperties& input) {
return input.residencyNonResidentStrict;
}
static bool Read(gpu::mojom::VkPhysicalDeviceSparsePropertiesDataView data,
VkPhysicalDeviceSparseProperties* out);
};
template <>
struct StructTraits<gpu::mojom::VkPhysicalDeviceFeaturesDataView,
VkPhysicalDeviceFeatures> {
static bool robustBufferAccess(const VkPhysicalDeviceFeatures& input) {
return input.robustBufferAccess;
}
static bool fullDrawIndexUint32(const VkPhysicalDeviceFeatures& input) {
return input.fullDrawIndexUint32;
}
static bool imageCubeArray(const VkPhysicalDeviceFeatures& input) {
return input.imageCubeArray;
}
static bool independentBlend(const VkPhysicalDeviceFeatures& input) {
return input.independentBlend;
}
static bool geometryShader(const VkPhysicalDeviceFeatures& input) {
return input.geometryShader;
}
static bool tessellationShader(const VkPhysicalDeviceFeatures& input) {
return input.tessellationShader;
}
static bool sampleRateShading(const VkPhysicalDeviceFeatures& input) {
return input.sampleRateShading;
}
static bool dualSrcBlend(const VkPhysicalDeviceFeatures& input) {
return input.dualSrcBlend;
}
static bool logicOp(const VkPhysicalDeviceFeatures& input) {
return input.logicOp;
}
static bool multiDrawIndirect(const VkPhysicalDeviceFeatures& input) {
return input.multiDrawIndirect;
}
static bool drawIndirectFirstInstance(const VkPhysicalDeviceFeatures& input) {
return input.drawIndirectFirstInstance;
}
static bool depthClamp(const VkPhysicalDeviceFeatures& input) {
return input.depthClamp;
}
static bool depthBiasClamp(const VkPhysicalDeviceFeatures& input) {
return input.depthBiasClamp;
}
static bool fillModeNonSolid(const VkPhysicalDeviceFeatures& input) {
return input.fillModeNonSolid;
}
static bool depthBounds(const VkPhysicalDeviceFeatures& input) {
return input.depthBounds;
}
static bool wideLines(const VkPhysicalDeviceFeatures& input) {
return input.wideLines;
}
static bool largePoints(const VkPhysicalDeviceFeatures& input) {
return input.largePoints;
}
static bool alphaToOne(const VkPhysicalDeviceFeatures& input) {
return input.alphaToOne;
}
static bool multiViewport(const VkPhysicalDeviceFeatures& input) {
return input.multiViewport;
}
static bool samplerAnisotropy(const VkPhysicalDeviceFeatures& input) {
return input.samplerAnisotropy;
}
static bool textureCompressionETC2(const VkPhysicalDeviceFeatures& input) {
return input.textureCompressionETC2;
}
static bool textureCompressionASTC_LDR(
const VkPhysicalDeviceFeatures& input) {
return input.textureCompressionASTC_LDR;
}
static bool textureCompressionBC(const VkPhysicalDeviceFeatures& input) {
return input.textureCompressionBC;
}
static bool occlusionQueryPrecise(const VkPhysicalDeviceFeatures& input) {
return input.occlusionQueryPrecise;
}
static bool pipelineStatisticsQuery(const VkPhysicalDeviceFeatures& input) {
return input.pipelineStatisticsQuery;
}
static bool vertexPipelineStoresAndAtomics(
const VkPhysicalDeviceFeatures& input) {
return input.vertexPipelineStoresAndAtomics;
}
static bool fragmentStoresAndAtomics(const VkPhysicalDeviceFeatures& input) {
return input.fragmentStoresAndAtomics;
}
static bool shaderTessellationAndGeometryPointSize(
const VkPhysicalDeviceFeatures& input) {
return input.shaderTessellationAndGeometryPointSize;
}
static bool shaderImageGatherExtended(const VkPhysicalDeviceFeatures& input) {
return input.shaderImageGatherExtended;
}
static bool shaderStorageImageExtendedFormats(
const VkPhysicalDeviceFeatures& input) {
return input.shaderStorageImageExtendedFormats;
}
static bool shaderStorageImageMultisample(
const VkPhysicalDeviceFeatures& input) {
return input.shaderStorageImageMultisample;
}
static bool shaderStorageImageReadWithoutFormat(
const VkPhysicalDeviceFeatures& input) {
return input.shaderStorageImageReadWithoutFormat;
}
static bool shaderStorageImageWriteWithoutFormat(
const VkPhysicalDeviceFeatures& input) {
return input.shaderStorageImageWriteWithoutFormat;
}
static bool shaderUniformBufferArrayDynamicIndexing(
const VkPhysicalDeviceFeatures& input) {
return input.shaderUniformBufferArrayDynamicIndexing;
}
static bool shaderSampledImageArrayDynamicIndexing(
const VkPhysicalDeviceFeatures& input) {
return input.shaderSampledImageArrayDynamicIndexing;
}
static bool shaderStorageBufferArrayDynamicIndexing(
const VkPhysicalDeviceFeatures& input) {
return input.shaderStorageBufferArrayDynamicIndexing;
}
static bool shaderStorageImageArrayDynamicIndexing(
const VkPhysicalDeviceFeatures& input) {
return input.shaderStorageImageArrayDynamicIndexing;
}
static bool shaderClipDistance(const VkPhysicalDeviceFeatures& input) {
return input.shaderClipDistance;
}
static bool shaderCullDistance(const VkPhysicalDeviceFeatures& input) {
return input.shaderCullDistance;
}
static bool shaderFloat64(const VkPhysicalDeviceFeatures& input) {
return input.shaderFloat64;
}
static bool shaderInt64(const VkPhysicalDeviceFeatures& input) {
return input.shaderInt64;
}
static bool shaderInt16(const VkPhysicalDeviceFeatures& input) {
return input.shaderInt16;
}
static bool shaderResourceResidency(const VkPhysicalDeviceFeatures& input) {
return input.shaderResourceResidency;
}
static bool shaderResourceMinLod(const VkPhysicalDeviceFeatures& input) {
return input.shaderResourceMinLod;
}
static bool sparseBinding(const VkPhysicalDeviceFeatures& input) {
return input.sparseBinding;
}
static bool sparseResidencyBuffer(const VkPhysicalDeviceFeatures& input) {
return input.sparseResidencyBuffer;
}
static bool sparseResidencyImage2D(const VkPhysicalDeviceFeatures& input) {
return input.sparseResidencyImage2D;
}
static bool sparseResidencyImage3D(const VkPhysicalDeviceFeatures& input) {
return input.sparseResidencyImage3D;
}
static bool sparseResidency2Samples(const VkPhysicalDeviceFeatures& input) {
return input.sparseResidency2Samples;
}
static bool sparseResidency4Samples(const VkPhysicalDeviceFeatures& input) {
return input.sparseResidency4Samples;
}
static bool sparseResidency8Samples(const VkPhysicalDeviceFeatures& input) {
return input.sparseResidency8Samples;
}
static bool sparseResidency16Samples(const VkPhysicalDeviceFeatures& input) {
return input.sparseResidency16Samples;
}
static bool sparseResidencyAliased(const VkPhysicalDeviceFeatures& input) {
return input.sparseResidencyAliased;
}
static bool variableMultisampleRate(const VkPhysicalDeviceFeatures& input) {
return input.variableMultisampleRate;
}
static bool inheritedQueries(const VkPhysicalDeviceFeatures& input) {
return input.inheritedQueries;
}
static bool Read(gpu::mojom::VkPhysicalDeviceFeaturesDataView data,
VkPhysicalDeviceFeatures* out);
};
template <>
struct StructTraits<gpu::mojom::VkQueueFamilyPropertiesDataView,
VkQueueFamilyProperties> {
static VkQueueFlags queueFlags(const VkQueueFamilyProperties& input) {
return input.queueFlags;
}
static uint32_t queueCount(const VkQueueFamilyProperties& input) {
return input.queueCount;
}
static uint32_t timestampValidBits(const VkQueueFamilyProperties& input) {
return input.timestampValidBits;
}
static const VkExtent3D& minImageTransferGranularity(
const VkQueueFamilyProperties& input) {
return input.minImageTransferGranularity;
}
static bool Read(gpu::mojom::VkQueueFamilyPropertiesDataView data,
VkQueueFamilyProperties* out);
};
template <>
struct StructTraits<gpu::mojom::VkExtent3DDataView, VkExtent3D> {
static uint32_t width(const VkExtent3D& input) { return input.width; }
static uint32_t height(const VkExtent3D& input) { return input.height; }
static uint32_t depth(const VkExtent3D& input) { return input.depth; }
static bool Read(gpu::mojom::VkExtent3DDataView data, VkExtent3D* out);
};
} // namespace mojo
#endif // GPU_IPC_COMMON_VULKAN_TYPES_MOJOM_TRAITS_H_ | {
"pile_set_name": "Github"
} |
form=七律
tags=
雨沐芙蓉秋意清。
可人风月满江城。
怜风爱月方留恋,
对月临风又送行。
人渐远,
酒须倾。
只凭一醉遣多情。
重来休厌刘郎老,
明月清风有素盟。
| {
"pile_set_name": "Github"
} |
package org.jboss.resteasy.test.nextgen.wadl.resources;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/extended")
public class ExtendedResource {
@POST
@Consumes({"application/xml"})
public String post(ListType income) {
return "foo";
}
}
| {
"pile_set_name": "Github"
} |
Компоненты
=========
Компоненты — это главные строительные блоки приложений основанных на Yii. Компоненты наследуются от класса
[[yii\base\Component]] или его наследников. Три главные возможности, которые компоненты предоставляют для других классов:
* [Свойства](concept-properties.md).
* [События](concept-events.md).
* [Поведения](concept-behaviors.md).
Как по отдельности, так и вместе, эти возможности делают классы Yii более простыми в настройке и использовании.
Например, пользовательские компоненты, включающие в себя [[yii\jui\DatePicker|виджет выбора даты]], могут быть
использованы в [представлении](structure-views.md) для генерации интерактивных элементов выбора даты:
```php
use yii\jui\DatePicker;
echo DatePicker::widget([
'language' => 'ru',
'name' => 'country',
'clientOptions' => [
'dateFormat' => 'yy-mm-dd',
],
]);
```
Свойства виджета легко доступны для записи потому, что его класс унаследован от класса [[yii\base\Component]].
Компоненты — очень мощный инструмент. Но в то же время они немного тяжелее обычных объектов, потому что на поддержку
[событий](concept-events.md) и [поведений](concept-behaviors.md) тратится дополнительные память и процессорное время.
Если ваши компоненты не нуждаются в этих двух возможностях, вам стоит унаследовать их от [[yii\base\BaseObject]],
а не от [[yii\base\Component]]. Поступив так, вы сделаете ваши компоненты такими же эффективными, как и обычные PHP объекты,
но с поддержкой [свойств](concept-properties.md).
При наследовании ваших классов от [[yii\base\Component]] или [[yii\base\BaseObject]], рекомендуется следовать некоторым
соглашениям:
- Если вы переопределяете конструктор, то добавьте *последним* аргументом параметр `$config` и затем передайте его
в конструктор предка.
- Всегда вызывайте конструктор предка *в конце* вашего переопределенного конструктора.
- Если вы переопределяете метод [[yii\base\BaseObject::init()]], убедитесь, что вы вызываете родительскую реализацию этого
метода *в начале* вашего метода `init()`.
Пример:
```php
<?php
namespace yii\components;
use yii\base\BaseObject;
class MyClass extends BaseObject
{
public $prop1;
public $prop2;
public function __construct($param1, $param2, $config = [])
{
// ... инициализация происходит перед тем, как будет применена конфигурация.
parent::__construct($config);
}
public function init()
{
parent::init();
// ... инициализация происходит после того, как была применена конфигурация.
}
}
```
Следуя этому руководству вы позволите [настраивать](concept-configurations.md) ваш компонент при создании. Например:
```php
$component = new MyClass(1, 2, ['prop1' => 3, 'prop2' => 4]);
// альтернативный способ
$component = \Yii::createObject([
'class' => MyClass::className(),
'prop1' => 3,
'prop2' => 4,
], [1, 2]);
```
> Info: Способ инициализации через вызов [[Yii::createObject()]] выглядит более сложным. Но в то же время он более
мощный из-за того, что он реализован на самом верху [контейнера внедрения зависимостей](concept-di-container.md).
Жизненный цикл объектов класса [[yii\base\BaseObject]] содержит следующие этапы:
1. Предварительная инициализация в конструкторе. Здесь вы можете установить значения свойств по умолчанию.
2. Конфигурация объекта с помощью `$config`. Во время конфигурации могут быть перезаписаны значения свойств по умолчанию,
установленные в конструкторе.
3. Конфигурация после инициализации в методе [[yii\base\BaseObject::init()|init()]]. Вы можете переопределить этот метод,
для проверки готовности объекта и нормализации свойств.
4. Вызов методов объекта.
Первые три шага всегда выполняются из конструктора объекта. Это значит, что если вы получите экземпляр объекта, он уже
будет проинициализирован и готов к работе.
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Test\Block\Adminhtml\Product\Edit\Section\Websites;
use Magento\Mtf\Client\Locator;
use Magento\Mtf\Client\Element\SimpleElement;
/**
* Typified element class for store tree element.
*/
class StoreTree extends SimpleElement
{
/**
* Selector for website checkbox.
*
* @var string
*/
protected $website = './/label[contains(text(), "%s")]';
/**
* Selector for selected website checkbox.
*
* @var string
*/
protected $selectedWebsite = '(.//input[contains(@name, "product[website_ids]") and not(@value="0")])[%d]/../label';
/**
* Set value.
*
* @param array|string $values
* @return void
* @throws \Exception
*/
public function setValue($values)
{
$this->clearValue();
$values = is_array($values) ? $values : [$values];
foreach ($values as $value) {
$website = $this->find(sprintf($this->website, $value), Locator::SELECTOR_XPATH);
if (!$website->isVisible()) {
throw new \Exception("Can't find website: \"{$value}\".");
}
if (!$website->isSelected()) {
$website->click();
}
}
}
/**
* Get value.
*
* @return array
*/
public function getValue()
{
$values = [];
$count = 1;
$website = $this->find(sprintf($this->selectedWebsite, $count), Locator::SELECTOR_XPATH);
while ($website->isVisible()) {
$values[] = $website->getText();
++$count;
$website = $this->find(sprintf($this->selectedWebsite, $count), Locator::SELECTOR_XPATH);
}
return $values;
}
/**
* Clear selected checkboxes.
*
* @return void
*/
private function clearValue()
{
foreach ($this->getValue() as $value) {
$this->find(sprintf($this->website, $value), Locator::SELECTOR_XPATH)->click();
}
}
}
| {
"pile_set_name": "Github"
} |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>$(ResourceProviderTargetFramework)</TargetFramework>
<PackageId>SqlToolsResourceProviderService</PackageId>
<AssemblyName>SqlToolsResourceProviderService</AssemblyName>
<OutputType>Exe</OutputType>
<Company>Microsoft</Company>
<Product>Sql Tools Service for Resource Provider services</Product>
<Description>Provides Resource Provider and control plane support.</Description>
<Copyright>� Microsoft Corporation. All rights reserved.</Copyright>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<PreserveCompilationContext>true</PreserveCompilationContext>
<EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems>
<RuntimeIdentifiers>win7-x64;win7-x86;ubuntu.14.04-x64;ubuntu.16.04-x64;centos.7-x64;rhel.7.2-x64;debian.8-x64;fedora.23-x64;opensuse.13.2-x64;osx.10.11-x64;linux-x64;win10-arm;win10-arm64</RuntimeIdentifiers>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>TRACE;DEBUG;NETCOREAPP1_0;NETCOREAPP2_0</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Text.Encoding.CodePages"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Microsoft.SqlTools.Hosting\Microsoft.SqlTools.Hosting.csproj" />
<!-- Note: must reference the resource provider projects in order for them to be bundled into the app. Otherwise will not have any of the required DLLs and
dependencies included when the project is shipped. If adding new DLLs, add them here or find another solution to keep them bundled
-->
<ProjectReference Include="..\Microsoft.SqlTools.ResourceProvider.Core\Microsoft.SqlTools.ResourceProvider.Core.csproj" />
<ProjectReference Include="..\Microsoft.SqlTools.ResourceProvider.DefaultImpl\Microsoft.SqlTools.ResourceProvider.DefaultImpl.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Localization\sr.resx" />
<None Include="Localization\sr.strings" />
</ItemGroup>
</Project> | {
"pile_set_name": "Github"
} |
const routes = [
{
path: '/splash',
component: () => import('layouts/SplashLayout/Index.vue'),
children: [
{ path: '', component: () => import('pages/Splash/Index.vue') }
]
},
{
path: '/',
redirect: '/splash'
}
]
// Always leave this as last one
if (process.env.MODE !== 'ssr') {
routes.push({
path: '*',
component: () => import('pages/Error404.vue')
})
}
export default routes
| {
"pile_set_name": "Github"
} |
# wchar_t.m4 serial 4 (gettext-0.18.2)
dnl Copyright (C) 2002-2003, 2008-2011 Free Software Foundation, Inc.
dnl This file is free software; the Free Software Foundation
dnl gives unlimited permission to copy and/or distribute it,
dnl with or without modifications, as long as this notice is preserved.
dnl From Bruno Haible.
dnl Test whether <stddef.h> has the 'wchar_t' type.
dnl Prerequisite: AC_PROG_CC
AC_DEFUN([gt_TYPE_WCHAR_T],
[
AC_CACHE_CHECK([for wchar_t], [gt_cv_c_wchar_t],
[AC_COMPILE_IFELSE(
[AC_LANG_PROGRAM(
[[#include <stddef.h>
wchar_t foo = (wchar_t)'\0';]],
[[]])],
[gt_cv_c_wchar_t=yes],
[gt_cv_c_wchar_t=no])])
if test $gt_cv_c_wchar_t = yes; then
AC_DEFINE([HAVE_WCHAR_T], [1], [Define if you have the 'wchar_t' type.])
fi
])
| {
"pile_set_name": "Github"
} |
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'models.dart';
/// Api wrapper to retrieve Star Wars related data
class StarWarsApi {
/// load and return one page of planets
Future<PlanetPageModel> getPlanets([String page]) async {
page ??= 'https://swapi.co/api/planets';
final response = await http.get(page);
final dynamic json = jsonDecode(utf8.decode(response.bodyBytes));
return serializers.deserializeWith(PlanetPageModel.serializer, json);
}
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class UIGestureRecognizer, UIScrollView, UIView;
@protocol ImageScrollViewDelegate <NSObject>
@optional
- (void)onFullScreenItemChangeAlpha:(double)arg1;
- (void)ImageScrollViewWillBeginZooming:(UIScrollView *)arg1 withView:(UIView *)arg2;
- (void)OnLongPressBegin:(id)arg1;
- (void)OnLongPress:(id)arg1;
- (void)onDoubleTap:(UIGestureRecognizer *)arg1;
- (void)onSingleTap:(UIGestureRecognizer *)arg1;
@end
| {
"pile_set_name": "Github"
} |
/*
* turbostat -- show CPU frequency and C-state residency
* on modern Intel turbo-capable processors.
*
* Copyright (c) 2013 Intel Corporation.
* Len Brown <len.brown@intel.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define _GNU_SOURCE
#include MSRHEADER
#include <stdarg.h>
#include <stdio.h>
#include <err.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/time.h>
#include <stdlib.h>
#include <getopt.h>
#include <dirent.h>
#include <string.h>
#include <ctype.h>
#include <sched.h>
#include <cpuid.h>
#include <linux/capability.h>
#include <errno.h>
char *proc_stat = "/proc/stat";
unsigned int interval_sec = 5;
unsigned int debug;
unsigned int rapl_joules;
unsigned int summary_only;
unsigned int dump_only;
unsigned int skip_c0;
unsigned int skip_c1;
unsigned int do_nhm_cstates;
unsigned int do_snb_cstates;
unsigned int do_pc2;
unsigned int do_pc3;
unsigned int do_pc6;
unsigned int do_pc7;
unsigned int do_c8_c9_c10;
unsigned int do_slm_cstates;
unsigned int use_c1_residency_msr;
unsigned int has_aperf;
unsigned int has_epb;
unsigned int units = 1000000; /* MHz etc */
unsigned int genuine_intel;
unsigned int has_invariant_tsc;
unsigned int do_nhm_platform_info;
unsigned int do_nhm_turbo_ratio_limit;
unsigned int do_ivt_turbo_ratio_limit;
unsigned int extra_msr_offset32;
unsigned int extra_msr_offset64;
unsigned int extra_delta_offset32;
unsigned int extra_delta_offset64;
int do_smi;
double bclk;
unsigned int show_pkg;
unsigned int show_core;
unsigned int show_cpu;
unsigned int show_pkg_only;
unsigned int show_core_only;
char *output_buffer, *outp;
unsigned int do_rapl;
unsigned int do_dts;
unsigned int do_ptm;
unsigned int tcc_activation_temp;
unsigned int tcc_activation_temp_override;
double rapl_power_units, rapl_energy_units, rapl_time_units;
double rapl_joule_counter_range;
unsigned int do_core_perf_limit_reasons;
unsigned int do_gfx_perf_limit_reasons;
unsigned int do_ring_perf_limit_reasons;
#define RAPL_PKG (1 << 0)
/* 0x610 MSR_PKG_POWER_LIMIT */
/* 0x611 MSR_PKG_ENERGY_STATUS */
#define RAPL_PKG_PERF_STATUS (1 << 1)
/* 0x613 MSR_PKG_PERF_STATUS */
#define RAPL_PKG_POWER_INFO (1 << 2)
/* 0x614 MSR_PKG_POWER_INFO */
#define RAPL_DRAM (1 << 3)
/* 0x618 MSR_DRAM_POWER_LIMIT */
/* 0x619 MSR_DRAM_ENERGY_STATUS */
/* 0x61c MSR_DRAM_POWER_INFO */
#define RAPL_DRAM_PERF_STATUS (1 << 4)
/* 0x61b MSR_DRAM_PERF_STATUS */
#define RAPL_CORES (1 << 5)
/* 0x638 MSR_PP0_POWER_LIMIT */
/* 0x639 MSR_PP0_ENERGY_STATUS */
#define RAPL_CORE_POLICY (1 << 6)
/* 0x63a MSR_PP0_POLICY */
#define RAPL_GFX (1 << 7)
/* 0x640 MSR_PP1_POWER_LIMIT */
/* 0x641 MSR_PP1_ENERGY_STATUS */
/* 0x642 MSR_PP1_POLICY */
#define TJMAX_DEFAULT 100
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int aperf_mperf_unstable;
int backwards_count;
char *progname;
cpu_set_t *cpu_present_set, *cpu_affinity_set;
size_t cpu_present_setsize, cpu_affinity_setsize;
struct thread_data {
unsigned long long tsc;
unsigned long long aperf;
unsigned long long mperf;
unsigned long long c1;
unsigned long long extra_msr64;
unsigned long long extra_delta64;
unsigned long long extra_msr32;
unsigned long long extra_delta32;
unsigned int smi_count;
unsigned int cpu_id;
unsigned int flags;
#define CPU_IS_FIRST_THREAD_IN_CORE 0x2
#define CPU_IS_FIRST_CORE_IN_PACKAGE 0x4
} *thread_even, *thread_odd;
struct core_data {
unsigned long long c3;
unsigned long long c6;
unsigned long long c7;
unsigned int core_temp_c;
unsigned int core_id;
} *core_even, *core_odd;
struct pkg_data {
unsigned long long pc2;
unsigned long long pc3;
unsigned long long pc6;
unsigned long long pc7;
unsigned long long pc8;
unsigned long long pc9;
unsigned long long pc10;
unsigned int package_id;
unsigned int energy_pkg; /* MSR_PKG_ENERGY_STATUS */
unsigned int energy_dram; /* MSR_DRAM_ENERGY_STATUS */
unsigned int energy_cores; /* MSR_PP0_ENERGY_STATUS */
unsigned int energy_gfx; /* MSR_PP1_ENERGY_STATUS */
unsigned int rapl_pkg_perf_status; /* MSR_PKG_PERF_STATUS */
unsigned int rapl_dram_perf_status; /* MSR_DRAM_PERF_STATUS */
unsigned int pkg_temp_c;
} *package_even, *package_odd;
#define ODD_COUNTERS thread_odd, core_odd, package_odd
#define EVEN_COUNTERS thread_even, core_even, package_even
#define GET_THREAD(thread_base, thread_no, core_no, pkg_no) \
(thread_base + (pkg_no) * topo.num_cores_per_pkg * \
topo.num_threads_per_core + \
(core_no) * topo.num_threads_per_core + (thread_no))
#define GET_CORE(core_base, core_no, pkg_no) \
(core_base + (pkg_no) * topo.num_cores_per_pkg + (core_no))
#define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no)
struct system_summary {
struct thread_data threads;
struct core_data cores;
struct pkg_data packages;
} sum, average;
struct topo_params {
int num_packages;
int num_cpus;
int num_cores;
int max_cpu_num;
int num_cores_per_pkg;
int num_threads_per_core;
} topo;
struct timeval tv_even, tv_odd, tv_delta;
void setup_all_buffers(void);
int cpu_is_not_present(int cpu)
{
return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set);
}
/*
* run func(thread, core, package) in topology order
* skip non-present cpus
*/
int for_all_cpus(int (func)(struct thread_data *, struct core_data *, struct pkg_data *),
struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base)
{
int retval, pkg_no, core_no, thread_no;
for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
for (thread_no = 0; thread_no <
topo.num_threads_per_core; ++thread_no) {
struct thread_data *t;
struct core_data *c;
struct pkg_data *p;
t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
if (cpu_is_not_present(t->cpu_id))
continue;
c = GET_CORE(core_base, core_no, pkg_no);
p = GET_PKG(pkg_base, pkg_no);
retval = func(t, c, p);
if (retval)
return retval;
}
}
}
return 0;
}
int cpu_migrate(int cpu)
{
CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set);
if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1)
return -1;
else
return 0;
}
int get_msr(int cpu, off_t offset, unsigned long long *msr)
{
ssize_t retval;
char pathname[32];
int fd;
sprintf(pathname, "/dev/cpu/%d/msr", cpu);
fd = open(pathname, O_RDONLY);
if (fd < 0)
err(-1, "%s open failed, try chown or chmod +r /dev/cpu/*/msr, or run as root", pathname);
retval = pread(fd, msr, sizeof *msr, offset);
close(fd);
if (retval != sizeof *msr)
err(-1, "%s offset 0x%llx read failed", pathname, (unsigned long long)offset);
return 0;
}
/*
* Example Format w/ field column widths:
*
* Package Core CPU Avg_MHz Bzy_MHz TSC_MHz SMI %Busy CPU_%c1 CPU_%c3 CPU_%c6 CPU_%c7 CoreTmp PkgTmp Pkg%pc2 Pkg%pc3 Pkg%pc6 Pkg%pc7 PkgWatt CorWatt GFXWatt
* 123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678
*/
void print_header(void)
{
if (show_pkg)
outp += sprintf(outp, " Package");
if (show_core)
outp += sprintf(outp, " Core");
if (show_cpu)
outp += sprintf(outp, " CPU");
if (has_aperf)
outp += sprintf(outp, " Avg_MHz");
if (has_aperf)
outp += sprintf(outp, " %%Busy");
if (has_aperf)
outp += sprintf(outp, " Bzy_MHz");
outp += sprintf(outp, " TSC_MHz");
if (do_smi)
outp += sprintf(outp, " SMI");
if (extra_delta_offset32)
outp += sprintf(outp, " count 0x%03X", extra_delta_offset32);
if (extra_delta_offset64)
outp += sprintf(outp, " COUNT 0x%03X", extra_delta_offset64);
if (extra_msr_offset32)
outp += sprintf(outp, " MSR 0x%03X", extra_msr_offset32);
if (extra_msr_offset64)
outp += sprintf(outp, " MSR 0x%03X", extra_msr_offset64);
if (do_nhm_cstates)
outp += sprintf(outp, " CPU%%c1");
if (do_nhm_cstates && !do_slm_cstates)
outp += sprintf(outp, " CPU%%c3");
if (do_nhm_cstates)
outp += sprintf(outp, " CPU%%c6");
if (do_snb_cstates)
outp += sprintf(outp, " CPU%%c7");
if (do_dts)
outp += sprintf(outp, " CoreTmp");
if (do_ptm)
outp += sprintf(outp, " PkgTmp");
if (do_pc2)
outp += sprintf(outp, " Pkg%%pc2");
if (do_pc3)
outp += sprintf(outp, " Pkg%%pc3");
if (do_pc6)
outp += sprintf(outp, " Pkg%%pc6");
if (do_pc7)
outp += sprintf(outp, " Pkg%%pc7");
if (do_c8_c9_c10) {
outp += sprintf(outp, " Pkg%%pc8");
outp += sprintf(outp, " Pkg%%pc9");
outp += sprintf(outp, " Pk%%pc10");
}
if (do_rapl && !rapl_joules) {
if (do_rapl & RAPL_PKG)
outp += sprintf(outp, " PkgWatt");
if (do_rapl & RAPL_CORES)
outp += sprintf(outp, " CorWatt");
if (do_rapl & RAPL_GFX)
outp += sprintf(outp, " GFXWatt");
if (do_rapl & RAPL_DRAM)
outp += sprintf(outp, " RAMWatt");
if (do_rapl & RAPL_PKG_PERF_STATUS)
outp += sprintf(outp, " PKG_%%");
if (do_rapl & RAPL_DRAM_PERF_STATUS)
outp += sprintf(outp, " RAM_%%");
} else if (do_rapl && rapl_joules) {
if (do_rapl & RAPL_PKG)
outp += sprintf(outp, " Pkg_J");
if (do_rapl & RAPL_CORES)
outp += sprintf(outp, " Cor_J");
if (do_rapl & RAPL_GFX)
outp += sprintf(outp, " GFX_J");
if (do_rapl & RAPL_DRAM)
outp += sprintf(outp, " RAM_W");
if (do_rapl & RAPL_PKG_PERF_STATUS)
outp += sprintf(outp, " PKG_%%");
if (do_rapl & RAPL_DRAM_PERF_STATUS)
outp += sprintf(outp, " RAM_%%");
outp += sprintf(outp, " time");
}
outp += sprintf(outp, "\n");
}
int dump_counters(struct thread_data *t, struct core_data *c,
struct pkg_data *p)
{
outp += sprintf(outp, "t %p, c %p, p %p\n", t, c, p);
if (t) {
outp += sprintf(outp, "CPU: %d flags 0x%x\n",
t->cpu_id, t->flags);
outp += sprintf(outp, "TSC: %016llX\n", t->tsc);
outp += sprintf(outp, "aperf: %016llX\n", t->aperf);
outp += sprintf(outp, "mperf: %016llX\n", t->mperf);
outp += sprintf(outp, "c1: %016llX\n", t->c1);
outp += sprintf(outp, "msr0x%x: %08llX\n",
extra_delta_offset32, t->extra_delta32);
outp += sprintf(outp, "msr0x%x: %016llX\n",
extra_delta_offset64, t->extra_delta64);
outp += sprintf(outp, "msr0x%x: %08llX\n",
extra_msr_offset32, t->extra_msr32);
outp += sprintf(outp, "msr0x%x: %016llX\n",
extra_msr_offset64, t->extra_msr64);
if (do_smi)
outp += sprintf(outp, "SMI: %08X\n", t->smi_count);
}
if (c) {
outp += sprintf(outp, "core: %d\n", c->core_id);
outp += sprintf(outp, "c3: %016llX\n", c->c3);
outp += sprintf(outp, "c6: %016llX\n", c->c6);
outp += sprintf(outp, "c7: %016llX\n", c->c7);
outp += sprintf(outp, "DTS: %dC\n", c->core_temp_c);
}
if (p) {
outp += sprintf(outp, "package: %d\n", p->package_id);
outp += sprintf(outp, "pc2: %016llX\n", p->pc2);
if (do_pc3)
outp += sprintf(outp, "pc3: %016llX\n", p->pc3);
if (do_pc6)
outp += sprintf(outp, "pc6: %016llX\n", p->pc6);
if (do_pc7)
outp += sprintf(outp, "pc7: %016llX\n", p->pc7);
outp += sprintf(outp, "pc8: %016llX\n", p->pc8);
outp += sprintf(outp, "pc9: %016llX\n", p->pc9);
outp += sprintf(outp, "pc10: %016llX\n", p->pc10);
outp += sprintf(outp, "Joules PKG: %0X\n", p->energy_pkg);
outp += sprintf(outp, "Joules COR: %0X\n", p->energy_cores);
outp += sprintf(outp, "Joules GFX: %0X\n", p->energy_gfx);
outp += sprintf(outp, "Joules RAM: %0X\n", p->energy_dram);
outp += sprintf(outp, "Throttle PKG: %0X\n",
p->rapl_pkg_perf_status);
outp += sprintf(outp, "Throttle RAM: %0X\n",
p->rapl_dram_perf_status);
outp += sprintf(outp, "PTM: %dC\n", p->pkg_temp_c);
}
outp += sprintf(outp, "\n");
return 0;
}
/*
* column formatting convention & formats
*/
int format_counters(struct thread_data *t, struct core_data *c,
struct pkg_data *p)
{
double interval_float;
char *fmt8;
/* if showing only 1st thread in core and this isn't one, bail out */
if (show_core_only && !(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
return 0;
/* if showing only 1st thread in pkg and this isn't one, bail out */
if (show_pkg_only && !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
return 0;
interval_float = tv_delta.tv_sec + tv_delta.tv_usec/1000000.0;
/* topo columns, print blanks on 1st (average) line */
if (t == &average.threads) {
if (show_pkg)
outp += sprintf(outp, " -");
if (show_core)
outp += sprintf(outp, " -");
if (show_cpu)
outp += sprintf(outp, " -");
} else {
if (show_pkg) {
if (p)
outp += sprintf(outp, "%8d", p->package_id);
else
outp += sprintf(outp, " -");
}
if (show_core) {
if (c)
outp += sprintf(outp, "%8d", c->core_id);
else
outp += sprintf(outp, " -");
}
if (show_cpu)
outp += sprintf(outp, "%8d", t->cpu_id);
}
/* Avg_MHz */
if (has_aperf)
outp += sprintf(outp, "%8.0f",
1.0 / units * t->aperf / interval_float);
/* %Busy */
if (has_aperf) {
if (!skip_c0)
outp += sprintf(outp, "%8.2f", 100.0 * t->mperf/t->tsc);
else
outp += sprintf(outp, "********");
}
/* Bzy_MHz */
if (has_aperf)
outp += sprintf(outp, "%8.0f",
1.0 * t->tsc / units * t->aperf / t->mperf / interval_float);
/* TSC_MHz */
outp += sprintf(outp, "%8.0f", 1.0 * t->tsc/units/interval_float);
/* SMI */
if (do_smi)
outp += sprintf(outp, "%8d", t->smi_count);
/* delta */
if (extra_delta_offset32)
outp += sprintf(outp, " %11llu", t->extra_delta32);
/* DELTA */
if (extra_delta_offset64)
outp += sprintf(outp, " %11llu", t->extra_delta64);
/* msr */
if (extra_msr_offset32)
outp += sprintf(outp, " 0x%08llx", t->extra_msr32);
/* MSR */
if (extra_msr_offset64)
outp += sprintf(outp, " 0x%016llx", t->extra_msr64);
if (do_nhm_cstates) {
if (!skip_c1)
outp += sprintf(outp, "%8.2f", 100.0 * t->c1/t->tsc);
else
outp += sprintf(outp, "********");
}
/* print per-core data only for 1st thread in core */
if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
goto done;
if (do_nhm_cstates && !do_slm_cstates)
outp += sprintf(outp, "%8.2f", 100.0 * c->c3/t->tsc);
if (do_nhm_cstates)
outp += sprintf(outp, "%8.2f", 100.0 * c->c6/t->tsc);
if (do_snb_cstates)
outp += sprintf(outp, "%8.2f", 100.0 * c->c7/t->tsc);
if (do_dts)
outp += sprintf(outp, "%8d", c->core_temp_c);
/* print per-package data only for 1st core in package */
if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
goto done;
if (do_ptm)
outp += sprintf(outp, "%8d", p->pkg_temp_c);
if (do_pc2)
outp += sprintf(outp, "%8.2f", 100.0 * p->pc2/t->tsc);
if (do_pc3)
outp += sprintf(outp, "%8.2f", 100.0 * p->pc3/t->tsc);
if (do_pc6)
outp += sprintf(outp, "%8.2f", 100.0 * p->pc6/t->tsc);
if (do_pc7)
outp += sprintf(outp, "%8.2f", 100.0 * p->pc7/t->tsc);
if (do_c8_c9_c10) {
outp += sprintf(outp, "%8.2f", 100.0 * p->pc8/t->tsc);
outp += sprintf(outp, "%8.2f", 100.0 * p->pc9/t->tsc);
outp += sprintf(outp, "%8.2f", 100.0 * p->pc10/t->tsc);
}
/*
* If measurement interval exceeds minimum RAPL Joule Counter range,
* indicate that results are suspect by printing "**" in fraction place.
*/
if (interval_float < rapl_joule_counter_range)
fmt8 = "%8.2f";
else
fmt8 = " %6.0f**";
if (do_rapl && !rapl_joules) {
if (do_rapl & RAPL_PKG)
outp += sprintf(outp, fmt8, p->energy_pkg * rapl_energy_units / interval_float);
if (do_rapl & RAPL_CORES)
outp += sprintf(outp, fmt8, p->energy_cores * rapl_energy_units / interval_float);
if (do_rapl & RAPL_GFX)
outp += sprintf(outp, fmt8, p->energy_gfx * rapl_energy_units / interval_float);
if (do_rapl & RAPL_DRAM)
outp += sprintf(outp, fmt8, p->energy_dram * rapl_energy_units / interval_float);
if (do_rapl & RAPL_PKG_PERF_STATUS)
outp += sprintf(outp, fmt8, 100.0 * p->rapl_pkg_perf_status * rapl_time_units / interval_float);
if (do_rapl & RAPL_DRAM_PERF_STATUS)
outp += sprintf(outp, fmt8, 100.0 * p->rapl_dram_perf_status * rapl_time_units / interval_float);
} else if (do_rapl && rapl_joules) {
if (do_rapl & RAPL_PKG)
outp += sprintf(outp, fmt8,
p->energy_pkg * rapl_energy_units);
if (do_rapl & RAPL_CORES)
outp += sprintf(outp, fmt8,
p->energy_cores * rapl_energy_units);
if (do_rapl & RAPL_GFX)
outp += sprintf(outp, fmt8,
p->energy_gfx * rapl_energy_units);
if (do_rapl & RAPL_DRAM)
outp += sprintf(outp, fmt8,
p->energy_dram * rapl_energy_units);
if (do_rapl & RAPL_PKG_PERF_STATUS)
outp += sprintf(outp, fmt8, 100.0 * p->rapl_pkg_perf_status * rapl_time_units / interval_float);
if (do_rapl & RAPL_DRAM_PERF_STATUS)
outp += sprintf(outp, fmt8, 100.0 * p->rapl_dram_perf_status * rapl_time_units / interval_float);
outp += sprintf(outp, fmt8, interval_float);
}
done:
outp += sprintf(outp, "\n");
return 0;
}
void flush_stdout()
{
fputs(output_buffer, stdout);
fflush(stdout);
outp = output_buffer;
}
void flush_stderr()
{
fputs(output_buffer, stderr);
outp = output_buffer;
}
void format_all_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
{
static int printed;
if (!printed || !summary_only)
print_header();
if (topo.num_cpus > 1)
format_counters(&average.threads, &average.cores,
&average.packages);
printed = 1;
if (summary_only)
return;
for_all_cpus(format_counters, t, c, p);
}
#define DELTA_WRAP32(new, old) \
if (new > old) { \
old = new - old; \
} else { \
old = 0x100000000 + new - old; \
}
void
delta_package(struct pkg_data *new, struct pkg_data *old)
{
old->pc2 = new->pc2 - old->pc2;
if (do_pc3)
old->pc3 = new->pc3 - old->pc3;
if (do_pc6)
old->pc6 = new->pc6 - old->pc6;
if (do_pc7)
old->pc7 = new->pc7 - old->pc7;
old->pc8 = new->pc8 - old->pc8;
old->pc9 = new->pc9 - old->pc9;
old->pc10 = new->pc10 - old->pc10;
old->pkg_temp_c = new->pkg_temp_c;
DELTA_WRAP32(new->energy_pkg, old->energy_pkg);
DELTA_WRAP32(new->energy_cores, old->energy_cores);
DELTA_WRAP32(new->energy_gfx, old->energy_gfx);
DELTA_WRAP32(new->energy_dram, old->energy_dram);
DELTA_WRAP32(new->rapl_pkg_perf_status, old->rapl_pkg_perf_status);
DELTA_WRAP32(new->rapl_dram_perf_status, old->rapl_dram_perf_status);
}
void
delta_core(struct core_data *new, struct core_data *old)
{
old->c3 = new->c3 - old->c3;
old->c6 = new->c6 - old->c6;
old->c7 = new->c7 - old->c7;
old->core_temp_c = new->core_temp_c;
}
/*
* old = new - old
*/
void
delta_thread(struct thread_data *new, struct thread_data *old,
struct core_data *core_delta)
{
old->tsc = new->tsc - old->tsc;
/* check for TSC < 1 Mcycles over interval */
if (old->tsc < (1000 * 1000))
errx(-3, "Insanely slow TSC rate, TSC stops in idle?\n"
"You can disable all c-states by booting with \"idle=poll\"\n"
"or just the deep ones with \"processor.max_cstate=1\"");
old->c1 = new->c1 - old->c1;
if (has_aperf) {
if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) {
old->aperf = new->aperf - old->aperf;
old->mperf = new->mperf - old->mperf;
} else {
if (!aperf_mperf_unstable) {
fprintf(stderr, "%s: APERF or MPERF went backwards *\n", progname);
fprintf(stderr, "* Frequency results do not cover entire interval *\n");
fprintf(stderr, "* fix this by running Linux-2.6.30 or later *\n");
aperf_mperf_unstable = 1;
}
/*
* mperf delta is likely a huge "positive" number
* can not use it for calculating c0 time
*/
skip_c0 = 1;
skip_c1 = 1;
}
}
if (use_c1_residency_msr) {
/*
* Some models have a dedicated C1 residency MSR,
* which should be more accurate than the derivation below.
*/
} else {
/*
* As counter collection is not atomic,
* it is possible for mperf's non-halted cycles + idle states
* to exceed TSC's all cycles: show c1 = 0% in that case.
*/
if ((old->mperf + core_delta->c3 + core_delta->c6 + core_delta->c7) > old->tsc)
old->c1 = 0;
else {
/* normal case, derive c1 */
old->c1 = old->tsc - old->mperf - core_delta->c3
- core_delta->c6 - core_delta->c7;
}
}
if (old->mperf == 0) {
if (debug > 1) fprintf(stderr, "cpu%d MPERF 0!\n", old->cpu_id);
old->mperf = 1; /* divide by 0 protection */
}
old->extra_delta32 = new->extra_delta32 - old->extra_delta32;
old->extra_delta32 &= 0xFFFFFFFF;
old->extra_delta64 = new->extra_delta64 - old->extra_delta64;
/*
* Extra MSR is just a snapshot, simply copy latest w/o subtracting
*/
old->extra_msr32 = new->extra_msr32;
old->extra_msr64 = new->extra_msr64;
if (do_smi)
old->smi_count = new->smi_count - old->smi_count;
}
int delta_cpu(struct thread_data *t, struct core_data *c,
struct pkg_data *p, struct thread_data *t2,
struct core_data *c2, struct pkg_data *p2)
{
/* calculate core delta only for 1st thread in core */
if (t->flags & CPU_IS_FIRST_THREAD_IN_CORE)
delta_core(c, c2);
/* always calculate thread delta */
delta_thread(t, t2, c2); /* c2 is core delta */
/* calculate package delta only for 1st core in package */
if (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)
delta_package(p, p2);
return 0;
}
void clear_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
{
t->tsc = 0;
t->aperf = 0;
t->mperf = 0;
t->c1 = 0;
t->smi_count = 0;
t->extra_delta32 = 0;
t->extra_delta64 = 0;
/* tells format_counters to dump all fields from this set */
t->flags = CPU_IS_FIRST_THREAD_IN_CORE | CPU_IS_FIRST_CORE_IN_PACKAGE;
c->c3 = 0;
c->c6 = 0;
c->c7 = 0;
c->core_temp_c = 0;
p->pc2 = 0;
if (do_pc3)
p->pc3 = 0;
if (do_pc6)
p->pc6 = 0;
if (do_pc7)
p->pc7 = 0;
p->pc8 = 0;
p->pc9 = 0;
p->pc10 = 0;
p->energy_pkg = 0;
p->energy_dram = 0;
p->energy_cores = 0;
p->energy_gfx = 0;
p->rapl_pkg_perf_status = 0;
p->rapl_dram_perf_status = 0;
p->pkg_temp_c = 0;
}
int sum_counters(struct thread_data *t, struct core_data *c,
struct pkg_data *p)
{
average.threads.tsc += t->tsc;
average.threads.aperf += t->aperf;
average.threads.mperf += t->mperf;
average.threads.c1 += t->c1;
average.threads.extra_delta32 += t->extra_delta32;
average.threads.extra_delta64 += t->extra_delta64;
/* sum per-core values only for 1st thread in core */
if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
return 0;
average.cores.c3 += c->c3;
average.cores.c6 += c->c6;
average.cores.c7 += c->c7;
average.cores.core_temp_c = MAX(average.cores.core_temp_c, c->core_temp_c);
/* sum per-pkg values only for 1st core in pkg */
if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
return 0;
average.packages.pc2 += p->pc2;
if (do_pc3)
average.packages.pc3 += p->pc3;
if (do_pc6)
average.packages.pc6 += p->pc6;
if (do_pc7)
average.packages.pc7 += p->pc7;
average.packages.pc8 += p->pc8;
average.packages.pc9 += p->pc9;
average.packages.pc10 += p->pc10;
average.packages.energy_pkg += p->energy_pkg;
average.packages.energy_dram += p->energy_dram;
average.packages.energy_cores += p->energy_cores;
average.packages.energy_gfx += p->energy_gfx;
average.packages.pkg_temp_c = MAX(average.packages.pkg_temp_c, p->pkg_temp_c);
average.packages.rapl_pkg_perf_status += p->rapl_pkg_perf_status;
average.packages.rapl_dram_perf_status += p->rapl_dram_perf_status;
return 0;
}
/*
* sum the counters for all cpus in the system
* compute the weighted average
*/
void compute_average(struct thread_data *t, struct core_data *c,
struct pkg_data *p)
{
clear_counters(&average.threads, &average.cores, &average.packages);
for_all_cpus(sum_counters, t, c, p);
average.threads.tsc /= topo.num_cpus;
average.threads.aperf /= topo.num_cpus;
average.threads.mperf /= topo.num_cpus;
average.threads.c1 /= topo.num_cpus;
average.threads.extra_delta32 /= topo.num_cpus;
average.threads.extra_delta32 &= 0xFFFFFFFF;
average.threads.extra_delta64 /= topo.num_cpus;
average.cores.c3 /= topo.num_cores;
average.cores.c6 /= topo.num_cores;
average.cores.c7 /= topo.num_cores;
average.packages.pc2 /= topo.num_packages;
if (do_pc3)
average.packages.pc3 /= topo.num_packages;
if (do_pc6)
average.packages.pc6 /= topo.num_packages;
if (do_pc7)
average.packages.pc7 /= topo.num_packages;
average.packages.pc8 /= topo.num_packages;
average.packages.pc9 /= topo.num_packages;
average.packages.pc10 /= topo.num_packages;
}
static unsigned long long rdtsc(void)
{
unsigned int low, high;
asm volatile("rdtsc" : "=a" (low), "=d" (high));
return low | ((unsigned long long)high) << 32;
}
/*
* get_counters(...)
* migrate to cpu
* acquire and record local counters for that cpu
*/
int get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
{
int cpu = t->cpu_id;
unsigned long long msr;
if (cpu_migrate(cpu)) {
fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
return -1;
}
t->tsc = rdtsc(); /* we are running on local CPU of interest */
if (has_aperf) {
if (get_msr(cpu, MSR_IA32_APERF, &t->aperf))
return -3;
if (get_msr(cpu, MSR_IA32_MPERF, &t->mperf))
return -4;
}
if (do_smi) {
if (get_msr(cpu, MSR_SMI_COUNT, &msr))
return -5;
t->smi_count = msr & 0xFFFFFFFF;
}
if (extra_delta_offset32) {
if (get_msr(cpu, extra_delta_offset32, &msr))
return -5;
t->extra_delta32 = msr & 0xFFFFFFFF;
}
if (extra_delta_offset64)
if (get_msr(cpu, extra_delta_offset64, &t->extra_delta64))
return -5;
if (extra_msr_offset32) {
if (get_msr(cpu, extra_msr_offset32, &msr))
return -5;
t->extra_msr32 = msr & 0xFFFFFFFF;
}
if (extra_msr_offset64)
if (get_msr(cpu, extra_msr_offset64, &t->extra_msr64))
return -5;
if (use_c1_residency_msr) {
if (get_msr(cpu, MSR_CORE_C1_RES, &t->c1))
return -6;
}
/* collect core counters only for 1st thread in core */
if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
return 0;
if (do_nhm_cstates && !do_slm_cstates) {
if (get_msr(cpu, MSR_CORE_C3_RESIDENCY, &c->c3))
return -6;
}
if (do_nhm_cstates) {
if (get_msr(cpu, MSR_CORE_C6_RESIDENCY, &c->c6))
return -7;
}
if (do_snb_cstates)
if (get_msr(cpu, MSR_CORE_C7_RESIDENCY, &c->c7))
return -8;
if (do_dts) {
if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
return -9;
c->core_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
}
/* collect package counters only for 1st core in package */
if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
return 0;
if (do_pc3)
if (get_msr(cpu, MSR_PKG_C3_RESIDENCY, &p->pc3))
return -9;
if (do_pc6)
if (get_msr(cpu, MSR_PKG_C6_RESIDENCY, &p->pc6))
return -10;
if (do_pc2)
if (get_msr(cpu, MSR_PKG_C2_RESIDENCY, &p->pc2))
return -11;
if (do_pc7)
if (get_msr(cpu, MSR_PKG_C7_RESIDENCY, &p->pc7))
return -12;
if (do_c8_c9_c10) {
if (get_msr(cpu, MSR_PKG_C8_RESIDENCY, &p->pc8))
return -13;
if (get_msr(cpu, MSR_PKG_C9_RESIDENCY, &p->pc9))
return -13;
if (get_msr(cpu, MSR_PKG_C10_RESIDENCY, &p->pc10))
return -13;
}
if (do_rapl & RAPL_PKG) {
if (get_msr(cpu, MSR_PKG_ENERGY_STATUS, &msr))
return -13;
p->energy_pkg = msr & 0xFFFFFFFF;
}
if (do_rapl & RAPL_CORES) {
if (get_msr(cpu, MSR_PP0_ENERGY_STATUS, &msr))
return -14;
p->energy_cores = msr & 0xFFFFFFFF;
}
if (do_rapl & RAPL_DRAM) {
if (get_msr(cpu, MSR_DRAM_ENERGY_STATUS, &msr))
return -15;
p->energy_dram = msr & 0xFFFFFFFF;
}
if (do_rapl & RAPL_GFX) {
if (get_msr(cpu, MSR_PP1_ENERGY_STATUS, &msr))
return -16;
p->energy_gfx = msr & 0xFFFFFFFF;
}
if (do_rapl & RAPL_PKG_PERF_STATUS) {
if (get_msr(cpu, MSR_PKG_PERF_STATUS, &msr))
return -16;
p->rapl_pkg_perf_status = msr & 0xFFFFFFFF;
}
if (do_rapl & RAPL_DRAM_PERF_STATUS) {
if (get_msr(cpu, MSR_DRAM_PERF_STATUS, &msr))
return -16;
p->rapl_dram_perf_status = msr & 0xFFFFFFFF;
}
if (do_ptm) {
if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
return -17;
p->pkg_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
}
return 0;
}
/*
* MSR_PKG_CST_CONFIG_CONTROL decoding for pkg_cstate_limit:
* If you change the values, note they are used both in comparisons
* (>= PCL__7) and to index pkg_cstate_limit_strings[].
*/
#define PCLUKN 0 /* Unknown */
#define PCLRSV 1 /* Reserved */
#define PCL__0 2 /* PC0 */
#define PCL__1 3 /* PC1 */
#define PCL__2 4 /* PC2 */
#define PCL__3 5 /* PC3 */
#define PCL__4 6 /* PC4 */
#define PCL__6 7 /* PC6 */
#define PCL_6N 8 /* PC6 No Retention */
#define PCL_6R 9 /* PC6 Retention */
#define PCL__7 10 /* PC7 */
#define PCL_7S 11 /* PC7 Shrink */
#define PCLUNL 12 /* Unlimited */
int pkg_cstate_limit = PCLUKN;
char *pkg_cstate_limit_strings[] = { "reserved", "unknown", "pc0", "pc1", "pc2",
"pc3", "pc4", "pc6", "pc6n", "pc6r", "pc7", "pc7s", "unlimited"};
int nhm_pkg_cstate_limits[8] = {PCL__0, PCL__1, PCL__3, PCL__6, PCL__7, PCLRSV, PCLRSV, PCLUNL};
int snb_pkg_cstate_limits[8] = {PCL__0, PCL__2, PCL_6N, PCL_6R, PCL__7, PCL_7S, PCLRSV, PCLUNL};
int hsw_pkg_cstate_limits[8] = {PCL__0, PCL__2, PCL__3, PCL__6, PCL__7, PCL_7S, PCLRSV, PCLUNL};
int slv_pkg_cstate_limits[8] = {PCL__0, PCL__1, PCLRSV, PCLRSV, PCL__4, PCLRSV, PCL__6, PCL__7};
int amt_pkg_cstate_limits[8] = {PCL__0, PCL__1, PCL__2, PCLRSV, PCLRSV, PCLRSV, PCL__6, PCL__7};
int phi_pkg_cstate_limits[8] = {PCL__0, PCL__2, PCL_6N, PCL_6R, PCLRSV, PCLRSV, PCLRSV, PCLUNL};
void print_verbose_header(void)
{
unsigned long long msr;
unsigned int ratio;
if (!do_nhm_platform_info)
return;
get_msr(0, MSR_NHM_PLATFORM_INFO, &msr);
fprintf(stderr, "cpu0: MSR_NHM_PLATFORM_INFO: 0x%08llx\n", msr);
ratio = (msr >> 40) & 0xFF;
fprintf(stderr, "%d * %.0f = %.0f MHz max efficiency\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 8) & 0xFF;
fprintf(stderr, "%d * %.0f = %.0f MHz TSC frequency\n",
ratio, bclk, ratio * bclk);
get_msr(0, MSR_IA32_POWER_CTL, &msr);
fprintf(stderr, "cpu0: MSR_IA32_POWER_CTL: 0x%08llx (C1E auto-promotion: %sabled)\n",
msr, msr & 0x2 ? "EN" : "DIS");
if (!do_ivt_turbo_ratio_limit)
goto print_nhm_turbo_ratio_limits;
get_msr(0, MSR_IVT_TURBO_RATIO_LIMIT, &msr);
fprintf(stderr, "cpu0: MSR_IVT_TURBO_RATIO_LIMIT: 0x%08llx\n", msr);
ratio = (msr >> 56) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 16 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 48) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 15 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 40) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 14 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 32) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 13 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 24) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 12 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 16) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 11 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 8) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 10 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 0) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 9 active cores\n",
ratio, bclk, ratio * bclk);
print_nhm_turbo_ratio_limits:
get_msr(0, MSR_NHM_SNB_PKG_CST_CFG_CTL, &msr);
#define SNB_C1_AUTO_UNDEMOTE (1UL << 27)
#define SNB_C3_AUTO_UNDEMOTE (1UL << 28)
fprintf(stderr, "cpu0: MSR_NHM_SNB_PKG_CST_CFG_CTL: 0x%08llx", msr);
fprintf(stderr, " (%s%s%s%s%slocked: pkg-cstate-limit=%d: %s)\n",
(msr & SNB_C3_AUTO_UNDEMOTE) ? "UNdemote-C3, " : "",
(msr & SNB_C1_AUTO_UNDEMOTE) ? "UNdemote-C1, " : "",
(msr & NHM_C3_AUTO_DEMOTE) ? "demote-C3, " : "",
(msr & NHM_C1_AUTO_DEMOTE) ? "demote-C1, " : "",
(msr & (1 << 15)) ? "" : "UN",
(unsigned int)msr & 7,
pkg_cstate_limit_strings[pkg_cstate_limit]);
if (!do_nhm_turbo_ratio_limit)
return;
get_msr(0, MSR_NHM_TURBO_RATIO_LIMIT, &msr);
fprintf(stderr, "cpu0: MSR_NHM_TURBO_RATIO_LIMIT: 0x%08llx\n", msr);
ratio = (msr >> 56) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 8 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 48) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 7 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 40) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 6 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 32) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 5 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 24) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 4 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 16) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 3 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 8) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 2 active cores\n",
ratio, bclk, ratio * bclk);
ratio = (msr >> 0) & 0xFF;
if (ratio)
fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 1 active cores\n",
ratio, bclk, ratio * bclk);
}
void free_all_buffers(void)
{
CPU_FREE(cpu_present_set);
cpu_present_set = NULL;
cpu_present_set = 0;
CPU_FREE(cpu_affinity_set);
cpu_affinity_set = NULL;
cpu_affinity_setsize = 0;
free(thread_even);
free(core_even);
free(package_even);
thread_even = NULL;
core_even = NULL;
package_even = NULL;
free(thread_odd);
free(core_odd);
free(package_odd);
thread_odd = NULL;
core_odd = NULL;
package_odd = NULL;
free(output_buffer);
output_buffer = NULL;
outp = NULL;
}
/*
* Open a file, and exit on failure
*/
FILE *fopen_or_die(const char *path, const char *mode)
{
FILE *filep = fopen(path, "r");
if (!filep)
err(1, "%s: open failed", path);
return filep;
}
/*
* Parse a file containing a single int.
*/
int parse_int_file(const char *fmt, ...)
{
va_list args;
char path[PATH_MAX];
FILE *filep;
int value;
va_start(args, fmt);
vsnprintf(path, sizeof(path), fmt, args);
va_end(args);
filep = fopen_or_die(path, "r");
if (fscanf(filep, "%d", &value) != 1)
err(1, "%s: failed to parse number from file", path);
fclose(filep);
return value;
}
/*
* cpu_is_first_sibling_in_core(cpu)
* return 1 if given CPU is 1st HT sibling in the core
*/
int cpu_is_first_sibling_in_core(int cpu)
{
return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
}
/*
* cpu_is_first_core_in_package(cpu)
* return 1 if given CPU is 1st core in package
*/
int cpu_is_first_core_in_package(int cpu)
{
return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", cpu);
}
int get_physical_package_id(int cpu)
{
return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
}
int get_core_id(int cpu)
{
return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", cpu);
}
int get_num_ht_siblings(int cpu)
{
char path[80];
FILE *filep;
int sib1, sib2;
int matches;
char character;
sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
filep = fopen_or_die(path, "r");
/*
* file format:
* if a pair of number with a character between: 2 siblings (eg. 1-2, or 1,4)
* otherwinse 1 sibling (self).
*/
matches = fscanf(filep, "%d%c%d\n", &sib1, &character, &sib2);
fclose(filep);
if (matches == 3)
return 2;
else
return 1;
}
/*
* run func(thread, core, package) in topology order
* skip non-present cpus
*/
int for_all_cpus_2(int (func)(struct thread_data *, struct core_data *,
struct pkg_data *, struct thread_data *, struct core_data *,
struct pkg_data *), struct thread_data *thread_base,
struct core_data *core_base, struct pkg_data *pkg_base,
struct thread_data *thread_base2, struct core_data *core_base2,
struct pkg_data *pkg_base2)
{
int retval, pkg_no, core_no, thread_no;
for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
for (thread_no = 0; thread_no <
topo.num_threads_per_core; ++thread_no) {
struct thread_data *t, *t2;
struct core_data *c, *c2;
struct pkg_data *p, *p2;
t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
if (cpu_is_not_present(t->cpu_id))
continue;
t2 = GET_THREAD(thread_base2, thread_no, core_no, pkg_no);
c = GET_CORE(core_base, core_no, pkg_no);
c2 = GET_CORE(core_base2, core_no, pkg_no);
p = GET_PKG(pkg_base, pkg_no);
p2 = GET_PKG(pkg_base2, pkg_no);
retval = func(t, c, p, t2, c2, p2);
if (retval)
return retval;
}
}
}
return 0;
}
/*
* run func(cpu) on every cpu in /proc/stat
* return max_cpu number
*/
int for_all_proc_cpus(int (func)(int))
{
FILE *fp;
int cpu_num;
int retval;
fp = fopen_or_die(proc_stat, "r");
retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
if (retval != 0)
err(1, "%s: failed to parse format", proc_stat);
while (1) {
retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
if (retval != 1)
break;
retval = func(cpu_num);
if (retval) {
fclose(fp);
return(retval);
}
}
fclose(fp);
return 0;
}
void re_initialize(void)
{
free_all_buffers();
setup_all_buffers();
printf("turbostat: re-initialized with num_cpus %d\n", topo.num_cpus);
}
/*
* count_cpus()
* remember the last one seen, it will be the max
*/
int count_cpus(int cpu)
{
if (topo.max_cpu_num < cpu)
topo.max_cpu_num = cpu;
topo.num_cpus += 1;
return 0;
}
int mark_cpu_present(int cpu)
{
CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
return 0;
}
void turbostat_loop()
{
int retval;
int restarted = 0;
restart:
restarted++;
retval = for_all_cpus(get_counters, EVEN_COUNTERS);
if (retval < -1) {
exit(retval);
} else if (retval == -1) {
if (restarted > 1) {
exit(retval);
}
re_initialize();
goto restart;
}
restarted = 0;
gettimeofday(&tv_even, (struct timezone *)NULL);
while (1) {
if (for_all_proc_cpus(cpu_is_not_present)) {
re_initialize();
goto restart;
}
sleep(interval_sec);
retval = for_all_cpus(get_counters, ODD_COUNTERS);
if (retval < -1) {
exit(retval);
} else if (retval == -1) {
re_initialize();
goto restart;
}
gettimeofday(&tv_odd, (struct timezone *)NULL);
timersub(&tv_odd, &tv_even, &tv_delta);
for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS);
compute_average(EVEN_COUNTERS);
format_all_counters(EVEN_COUNTERS);
flush_stdout();
sleep(interval_sec);
retval = for_all_cpus(get_counters, EVEN_COUNTERS);
if (retval < -1) {
exit(retval);
} else if (retval == -1) {
re_initialize();
goto restart;
}
gettimeofday(&tv_even, (struct timezone *)NULL);
timersub(&tv_even, &tv_odd, &tv_delta);
for_all_cpus_2(delta_cpu, EVEN_COUNTERS, ODD_COUNTERS);
compute_average(ODD_COUNTERS);
format_all_counters(ODD_COUNTERS);
flush_stdout();
}
}
void check_dev_msr()
{
struct stat sb;
if (stat("/dev/cpu/0/msr", &sb))
err(-5, "no /dev/cpu/0/msr, Try \"# modprobe msr\" ");
}
void check_permissions()
{
struct __user_cap_header_struct cap_header_data;
cap_user_header_t cap_header = &cap_header_data;
struct __user_cap_data_struct cap_data_data;
cap_user_data_t cap_data = &cap_data_data;
extern int capget(cap_user_header_t hdrp, cap_user_data_t datap);
int do_exit = 0;
/* check for CAP_SYS_RAWIO */
cap_header->pid = getpid();
cap_header->version = _LINUX_CAPABILITY_VERSION;
if (capget(cap_header, cap_data) < 0)
err(-6, "capget(2) failed");
if ((cap_data->effective & (1 << CAP_SYS_RAWIO)) == 0) {
do_exit++;
warnx("capget(CAP_SYS_RAWIO) failed,"
" try \"# setcap cap_sys_rawio=ep %s\"", progname);
}
/* test file permissions */
if (euidaccess("/dev/cpu/0/msr", R_OK)) {
do_exit++;
warn("/dev/cpu/0/msr open failed, try chown or chmod +r /dev/cpu/*/msr");
}
/* if all else fails, thell them to be root */
if (do_exit)
if (getuid() != 0)
warnx("... or simply run as root");
if (do_exit)
exit(-6);
}
/*
* NHM adds support for additional MSRs:
*
* MSR_SMI_COUNT 0x00000034
*
* MSR_NHM_PLATFORM_INFO 0x000000ce
* MSR_NHM_SNB_PKG_CST_CFG_CTL 0x000000e2
*
* MSR_PKG_C3_RESIDENCY 0x000003f8
* MSR_PKG_C6_RESIDENCY 0x000003f9
* MSR_CORE_C3_RESIDENCY 0x000003fc
* MSR_CORE_C6_RESIDENCY 0x000003fd
*
* Side effect:
* sets global pkg_cstate_limit to decode MSR_NHM_SNB_PKG_CST_CFG_CTL
*/
int probe_nhm_msrs(unsigned int family, unsigned int model)
{
unsigned long long msr;
int *pkg_cstate_limits;
if (!genuine_intel)
return 0;
if (family != 6)
return 0;
switch (model) {
case 0x1A: /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
case 0x1E: /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
case 0x1F: /* Core i7 and i5 Processor - Nehalem */
case 0x25: /* Westmere Client - Clarkdale, Arrandale */
case 0x2C: /* Westmere EP - Gulftown */
case 0x2E: /* Nehalem-EX Xeon - Beckton */
case 0x2F: /* Westmere-EX Xeon - Eagleton */
pkg_cstate_limits = nhm_pkg_cstate_limits;
break;
case 0x2A: /* SNB */
case 0x2D: /* SNB Xeon */
case 0x3A: /* IVB */
case 0x3E: /* IVB Xeon */
pkg_cstate_limits = snb_pkg_cstate_limits;
break;
case 0x3C: /* HSW */
case 0x3F: /* HSX */
case 0x45: /* HSW */
case 0x46: /* HSW */
case 0x3D: /* BDW */
case 0x47: /* BDW */
case 0x4F: /* BDX */
case 0x56: /* BDX-DE */
pkg_cstate_limits = hsw_pkg_cstate_limits;
break;
case 0x37: /* BYT */
case 0x4D: /* AVN */
pkg_cstate_limits = slv_pkg_cstate_limits;
break;
case 0x4C: /* AMT */
pkg_cstate_limits = amt_pkg_cstate_limits;
break;
case 0x57: /* PHI */
pkg_cstate_limits = phi_pkg_cstate_limits;
break;
default:
return 0;
}
get_msr(0, MSR_NHM_SNB_PKG_CST_CFG_CTL, &msr);
pkg_cstate_limit = pkg_cstate_limits[msr & 0x7];
return 1;
}
int has_nhm_turbo_ratio_limit(unsigned int family, unsigned int model)
{
switch (model) {
/* Nehalem compatible, but do not include turbo-ratio limit support */
case 0x2E: /* Nehalem-EX Xeon - Beckton */
case 0x2F: /* Westmere-EX Xeon - Eagleton */
return 0;
default:
return 1;
}
}
int has_ivt_turbo_ratio_limit(unsigned int family, unsigned int model)
{
if (!genuine_intel)
return 0;
if (family != 6)
return 0;
switch (model) {
case 0x3E: /* IVB Xeon */
return 1;
default:
return 0;
}
}
/*
* print_epb()
* Decode the ENERGY_PERF_BIAS MSR
*/
int print_epb(struct thread_data *t, struct core_data *c, struct pkg_data *p)
{
unsigned long long msr;
char *epb_string;
int cpu;
if (!has_epb)
return 0;
cpu = t->cpu_id;
/* EPB is per-package */
if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
return 0;
if (cpu_migrate(cpu)) {
fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
return -1;
}
if (get_msr(cpu, MSR_IA32_ENERGY_PERF_BIAS, &msr))
return 0;
switch (msr & 0x7) {
case ENERGY_PERF_BIAS_PERFORMANCE:
epb_string = "performance";
break;
case ENERGY_PERF_BIAS_NORMAL:
epb_string = "balanced";
break;
case ENERGY_PERF_BIAS_POWERSAVE:
epb_string = "powersave";
break;
default:
epb_string = "custom";
break;
}
fprintf(stderr, "cpu%d: MSR_IA32_ENERGY_PERF_BIAS: 0x%08llx (%s)\n", cpu, msr, epb_string);
return 0;
}
/*
* print_perf_limit()
*/
int print_perf_limit(struct thread_data *t, struct core_data *c, struct pkg_data *p)
{
unsigned long long msr;
int cpu;
cpu = t->cpu_id;
/* per-package */
if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
return 0;
if (cpu_migrate(cpu)) {
fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
return -1;
}
if (do_core_perf_limit_reasons) {
get_msr(cpu, MSR_CORE_PERF_LIMIT_REASONS, &msr);
fprintf(stderr, "cpu%d: MSR_CORE_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
fprintf(stderr, " (Active: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
(msr & 1 << 0) ? "PROCHOT, " : "",
(msr & 1 << 1) ? "ThermStatus, " : "",
(msr & 1 << 2) ? "bit2, " : "",
(msr & 1 << 4) ? "Graphics, " : "",
(msr & 1 << 5) ? "Auto-HWP, " : "",
(msr & 1 << 6) ? "VR-Therm, " : "",
(msr & 1 << 8) ? "Amps, " : "",
(msr & 1 << 9) ? "CorePwr, " : "",
(msr & 1 << 10) ? "PkgPwrL1, " : "",
(msr & 1 << 11) ? "PkgPwrL2, " : "",
(msr & 1 << 12) ? "MultiCoreTurbo, " : "",
(msr & 1 << 13) ? "Transitions, " : "",
(msr & 1 << 14) ? "bit14, " : "",
(msr & 1 << 15) ? "bit15, " : "");
fprintf(stderr, " (Logged: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)\n",
(msr & 1 << 16) ? "PROCHOT, " : "",
(msr & 1 << 17) ? "ThermStatus, " : "",
(msr & 1 << 18) ? "bit18, " : "",
(msr & 1 << 20) ? "Graphics, " : "",
(msr & 1 << 21) ? "Auto-HWP, " : "",
(msr & 1 << 22) ? "VR-Therm, " : "",
(msr & 1 << 24) ? "Amps, " : "",
(msr & 1 << 25) ? "CorePwr, " : "",
(msr & 1 << 26) ? "PkgPwrL1, " : "",
(msr & 1 << 27) ? "PkgPwrL2, " : "",
(msr & 1 << 28) ? "MultiCoreTurbo, " : "",
(msr & 1 << 29) ? "Transitions, " : "",
(msr & 1 << 30) ? "bit30, " : "",
(msr & 1 << 31) ? "bit31, " : "");
}
if (do_gfx_perf_limit_reasons) {
get_msr(cpu, MSR_GFX_PERF_LIMIT_REASONS, &msr);
fprintf(stderr, "cpu%d: MSR_GFX_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
fprintf(stderr, " (Active: %s%s%s%s%s%s%s%s)",
(msr & 1 << 0) ? "PROCHOT, " : "",
(msr & 1 << 1) ? "ThermStatus, " : "",
(msr & 1 << 4) ? "Graphics, " : "",
(msr & 1 << 6) ? "VR-Therm, " : "",
(msr & 1 << 8) ? "Amps, " : "",
(msr & 1 << 9) ? "GFXPwr, " : "",
(msr & 1 << 10) ? "PkgPwrL1, " : "",
(msr & 1 << 11) ? "PkgPwrL2, " : "");
fprintf(stderr, " (Logged: %s%s%s%s%s%s%s%s)\n",
(msr & 1 << 16) ? "PROCHOT, " : "",
(msr & 1 << 17) ? "ThermStatus, " : "",
(msr & 1 << 20) ? "Graphics, " : "",
(msr & 1 << 22) ? "VR-Therm, " : "",
(msr & 1 << 24) ? "Amps, " : "",
(msr & 1 << 25) ? "GFXPwr, " : "",
(msr & 1 << 26) ? "PkgPwrL1, " : "",
(msr & 1 << 27) ? "PkgPwrL2, " : "");
}
if (do_ring_perf_limit_reasons) {
get_msr(cpu, MSR_RING_PERF_LIMIT_REASONS, &msr);
fprintf(stderr, "cpu%d: MSR_RING_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
fprintf(stderr, " (Active: %s%s%s%s%s%s)",
(msr & 1 << 0) ? "PROCHOT, " : "",
(msr & 1 << 1) ? "ThermStatus, " : "",
(msr & 1 << 6) ? "VR-Therm, " : "",
(msr & 1 << 8) ? "Amps, " : "",
(msr & 1 << 10) ? "PkgPwrL1, " : "",
(msr & 1 << 11) ? "PkgPwrL2, " : "");
fprintf(stderr, " (Logged: %s%s%s%s%s%s)\n",
(msr & 1 << 16) ? "PROCHOT, " : "",
(msr & 1 << 17) ? "ThermStatus, " : "",
(msr & 1 << 22) ? "VR-Therm, " : "",
(msr & 1 << 24) ? "Amps, " : "",
(msr & 1 << 26) ? "PkgPwrL1, " : "",
(msr & 1 << 27) ? "PkgPwrL2, " : "");
}
return 0;
}
#define RAPL_POWER_GRANULARITY 0x7FFF /* 15 bit power granularity */
#define RAPL_TIME_GRANULARITY 0x3F /* 6 bit time granularity */
double get_tdp(model)
{
unsigned long long msr;
if (do_rapl & RAPL_PKG_POWER_INFO)
if (!get_msr(0, MSR_PKG_POWER_INFO, &msr))
return ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units;
switch (model) {
case 0x37:
case 0x4D:
return 30.0;
default:
return 135.0;
}
}
/*
* rapl_probe()
*
* sets do_rapl, rapl_power_units, rapl_energy_units, rapl_time_units
*/
void rapl_probe(unsigned int family, unsigned int model)
{
unsigned long long msr;
unsigned int time_unit;
double tdp;
if (!genuine_intel)
return;
if (family != 6)
return;
switch (model) {
case 0x2A:
case 0x3A:
case 0x3C: /* HSW */
case 0x45: /* HSW */
case 0x46: /* HSW */
case 0x3D: /* BDW */
case 0x47: /* BDW */
do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_GFX | RAPL_PKG_POWER_INFO;
break;
case 0x3F: /* HSX */
case 0x4F: /* BDX */
case 0x56: /* BDX-DE */
do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
break;
case 0x2D:
case 0x3E:
do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_PKG_PERF_STATUS | RAPL_DRAM_PERF_STATUS | RAPL_PKG_POWER_INFO;
break;
case 0x37: /* BYT */
case 0x4D: /* AVN */
do_rapl = RAPL_PKG | RAPL_CORES ;
break;
default:
return;
}
/* units on package 0, verify later other packages match */
if (get_msr(0, MSR_RAPL_POWER_UNIT, &msr))
return;
rapl_power_units = 1.0 / (1 << (msr & 0xF));
if (model == 0x37)
rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
else
rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
time_unit = msr >> 16 & 0xF;
if (time_unit == 0)
time_unit = 0xA;
rapl_time_units = 1.0 / (1 << (time_unit));
tdp = get_tdp(model);
rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
if (debug)
fprintf(stderr, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
return;
}
void perf_limit_reasons_probe(family, model)
{
if (!genuine_intel)
return;
if (family != 6)
return;
switch (model) {
case 0x3C: /* HSW */
case 0x45: /* HSW */
case 0x46: /* HSW */
do_gfx_perf_limit_reasons = 1;
case 0x3F: /* HSX */
do_core_perf_limit_reasons = 1;
do_ring_perf_limit_reasons = 1;
default:
return;
}
}
int print_thermal(struct thread_data *t, struct core_data *c, struct pkg_data *p)
{
unsigned long long msr;
unsigned int dts;
int cpu;
if (!(do_dts || do_ptm))
return 0;
cpu = t->cpu_id;
/* DTS is per-core, no need to print for each thread */
if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
return 0;
if (cpu_migrate(cpu)) {
fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
return -1;
}
if (do_ptm && (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) {
if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
return 0;
dts = (msr >> 16) & 0x7F;
fprintf(stderr, "cpu%d: MSR_IA32_PACKAGE_THERM_STATUS: 0x%08llx (%d C)\n",
cpu, msr, tcc_activation_temp - dts);
#ifdef THERM_DEBUG
if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_INTERRUPT, &msr))
return 0;
dts = (msr >> 16) & 0x7F;
dts2 = (msr >> 8) & 0x7F;
fprintf(stderr, "cpu%d: MSR_IA32_PACKAGE_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
#endif
}
if (do_dts) {
unsigned int resolution;
if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
return 0;
dts = (msr >> 16) & 0x7F;
resolution = (msr >> 27) & 0xF;
fprintf(stderr, "cpu%d: MSR_IA32_THERM_STATUS: 0x%08llx (%d C +/- %d)\n",
cpu, msr, tcc_activation_temp - dts, resolution);
#ifdef THERM_DEBUG
if (get_msr(cpu, MSR_IA32_THERM_INTERRUPT, &msr))
return 0;
dts = (msr >> 16) & 0x7F;
dts2 = (msr >> 8) & 0x7F;
fprintf(stderr, "cpu%d: MSR_IA32_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
#endif
}
return 0;
}
void print_power_limit_msr(int cpu, unsigned long long msr, char *label)
{
fprintf(stderr, "cpu%d: %s: %sabled (%f Watts, %f sec, clamp %sabled)\n",
cpu, label,
((msr >> 15) & 1) ? "EN" : "DIS",
((msr >> 0) & 0x7FFF) * rapl_power_units,
(1.0 + (((msr >> 22) & 0x3)/4.0)) * (1 << ((msr >> 17) & 0x1F)) * rapl_time_units,
(((msr >> 16) & 1) ? "EN" : "DIS"));
return;
}
int print_rapl(struct thread_data *t, struct core_data *c, struct pkg_data *p)
{
unsigned long long msr;
int cpu;
if (!do_rapl)
return 0;
/* RAPL counters are per package, so print only for 1st thread/package */
if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
return 0;
cpu = t->cpu_id;
if (cpu_migrate(cpu)) {
fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
return -1;
}
if (get_msr(cpu, MSR_RAPL_POWER_UNIT, &msr))
return -1;
if (debug) {
fprintf(stderr, "cpu%d: MSR_RAPL_POWER_UNIT: 0x%08llx "
"(%f Watts, %f Joules, %f sec.)\n", cpu, msr,
rapl_power_units, rapl_energy_units, rapl_time_units);
}
if (do_rapl & RAPL_PKG_POWER_INFO) {
if (get_msr(cpu, MSR_PKG_POWER_INFO, &msr))
return -5;
fprintf(stderr, "cpu%d: MSR_PKG_POWER_INFO: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
cpu, msr,
((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
}
if (do_rapl & RAPL_PKG) {
if (get_msr(cpu, MSR_PKG_POWER_LIMIT, &msr))
return -9;
fprintf(stderr, "cpu%d: MSR_PKG_POWER_LIMIT: 0x%08llx (%slocked)\n",
cpu, msr, (msr >> 63) & 1 ? "": "UN");
print_power_limit_msr(cpu, msr, "PKG Limit #1");
fprintf(stderr, "cpu%d: PKG Limit #2: %sabled (%f Watts, %f* sec, clamp %sabled)\n",
cpu,
((msr >> 47) & 1) ? "EN" : "DIS",
((msr >> 32) & 0x7FFF) * rapl_power_units,
(1.0 + (((msr >> 54) & 0x3)/4.0)) * (1 << ((msr >> 49) & 0x1F)) * rapl_time_units,
((msr >> 48) & 1) ? "EN" : "DIS");
}
if (do_rapl & RAPL_DRAM) {
if (get_msr(cpu, MSR_DRAM_POWER_INFO, &msr))
return -6;
fprintf(stderr, "cpu%d: MSR_DRAM_POWER_INFO,: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
cpu, msr,
((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
if (get_msr(cpu, MSR_DRAM_POWER_LIMIT, &msr))
return -9;
fprintf(stderr, "cpu%d: MSR_DRAM_POWER_LIMIT: 0x%08llx (%slocked)\n",
cpu, msr, (msr >> 31) & 1 ? "": "UN");
print_power_limit_msr(cpu, msr, "DRAM Limit");
}
if (do_rapl & RAPL_CORE_POLICY) {
if (debug) {
if (get_msr(cpu, MSR_PP0_POLICY, &msr))
return -7;
fprintf(stderr, "cpu%d: MSR_PP0_POLICY: %lld\n", cpu, msr & 0xF);
}
}
if (do_rapl & RAPL_CORES) {
if (debug) {
if (get_msr(cpu, MSR_PP0_POWER_LIMIT, &msr))
return -9;
fprintf(stderr, "cpu%d: MSR_PP0_POWER_LIMIT: 0x%08llx (%slocked)\n",
cpu, msr, (msr >> 31) & 1 ? "": "UN");
print_power_limit_msr(cpu, msr, "Cores Limit");
}
}
if (do_rapl & RAPL_GFX) {
if (debug) {
if (get_msr(cpu, MSR_PP1_POLICY, &msr))
return -8;
fprintf(stderr, "cpu%d: MSR_PP1_POLICY: %lld\n", cpu, msr & 0xF);
if (get_msr(cpu, MSR_PP1_POWER_LIMIT, &msr))
return -9;
fprintf(stderr, "cpu%d: MSR_PP1_POWER_LIMIT: 0x%08llx (%slocked)\n",
cpu, msr, (msr >> 31) & 1 ? "": "UN");
print_power_limit_msr(cpu, msr, "GFX Limit");
}
}
return 0;
}
/*
* SNB adds support for additional MSRs:
*
* MSR_PKG_C7_RESIDENCY 0x000003fa
* MSR_CORE_C7_RESIDENCY 0x000003fe
* MSR_PKG_C2_RESIDENCY 0x0000060d
*/
int has_snb_msrs(unsigned int family, unsigned int model)
{
if (!genuine_intel)
return 0;
switch (model) {
case 0x2A:
case 0x2D:
case 0x3A: /* IVB */
case 0x3E: /* IVB Xeon */
case 0x3C: /* HSW */
case 0x3F: /* HSW */
case 0x45: /* HSW */
case 0x46: /* HSW */
case 0x3D: /* BDW */
case 0x47: /* BDW */
case 0x4F: /* BDX */
case 0x56: /* BDX-DE */
return 1;
}
return 0;
}
/*
* HSW adds support for additional MSRs:
*
* MSR_PKG_C8_RESIDENCY 0x00000630
* MSR_PKG_C9_RESIDENCY 0x00000631
* MSR_PKG_C10_RESIDENCY 0x00000632
*/
int has_hsw_msrs(unsigned int family, unsigned int model)
{
if (!genuine_intel)
return 0;
switch (model) {
case 0x45: /* HSW */
case 0x3D: /* BDW */
return 1;
}
return 0;
}
int is_slm(unsigned int family, unsigned int model)
{
if (!genuine_intel)
return 0;
switch (model) {
case 0x37: /* BYT */
case 0x4D: /* AVN */
return 1;
}
return 0;
}
#define SLM_BCLK_FREQS 5
double slm_freq_table[SLM_BCLK_FREQS] = { 83.3, 100.0, 133.3, 116.7, 80.0};
double slm_bclk(void)
{
unsigned long long msr = 3;
unsigned int i;
double freq;
if (get_msr(0, MSR_FSB_FREQ, &msr))
fprintf(stderr, "SLM BCLK: unknown\n");
i = msr & 0xf;
if (i >= SLM_BCLK_FREQS) {
fprintf(stderr, "SLM BCLK[%d] invalid\n", i);
msr = 3;
}
freq = slm_freq_table[i];
fprintf(stderr, "SLM BCLK: %.1f Mhz\n", freq);
return freq;
}
double discover_bclk(unsigned int family, unsigned int model)
{
if (has_snb_msrs(family, model))
return 100.00;
else if (is_slm(family, model))
return slm_bclk();
else
return 133.33;
}
/*
* MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
* the Thermal Control Circuit (TCC) activates.
* This is usually equal to tjMax.
*
* Older processors do not have this MSR, so there we guess,
* but also allow cmdline over-ride with -T.
*
* Several MSR temperature values are in units of degrees-C
* below this value, including the Digital Thermal Sensor (DTS),
* Package Thermal Management Sensor (PTM), and thermal event thresholds.
*/
int set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
{
unsigned long long msr;
unsigned int target_c_local;
int cpu;
/* tcc_activation_temp is used only for dts or ptm */
if (!(do_dts || do_ptm))
return 0;
/* this is a per-package concept */
if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
return 0;
cpu = t->cpu_id;
if (cpu_migrate(cpu)) {
fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
return -1;
}
if (tcc_activation_temp_override != 0) {
tcc_activation_temp = tcc_activation_temp_override;
fprintf(stderr, "cpu%d: Using cmdline TCC Target (%d C)\n",
cpu, tcc_activation_temp);
return 0;
}
/* Temperature Target MSR is Nehalem and newer only */
if (!do_nhm_platform_info)
goto guess;
if (get_msr(0, MSR_IA32_TEMPERATURE_TARGET, &msr))
goto guess;
target_c_local = (msr >> 16) & 0xFF;
if (debug)
fprintf(stderr, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C)\n",
cpu, msr, target_c_local);
if (!target_c_local)
goto guess;
tcc_activation_temp = target_c_local;
return 0;
guess:
tcc_activation_temp = TJMAX_DEFAULT;
fprintf(stderr, "cpu%d: Guessing tjMax %d C, Please use -T to specify\n",
cpu, tcc_activation_temp);
return 0;
}
void check_cpuid()
{
unsigned int eax, ebx, ecx, edx, max_level;
unsigned int fms, family, model, stepping;
eax = ebx = ecx = edx = 0;
__get_cpuid(0, &max_level, &ebx, &ecx, &edx);
if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
genuine_intel = 1;
if (debug)
fprintf(stderr, "CPUID(0): %.4s%.4s%.4s ",
(char *)&ebx, (char *)&edx, (char *)&ecx);
__get_cpuid(1, &fms, &ebx, &ecx, &edx);
family = (fms >> 8) & 0xf;
model = (fms >> 4) & 0xf;
stepping = fms & 0xf;
if (family == 6 || family == 0xf)
model += ((fms >> 16) & 0xf) << 4;
if (debug)
fprintf(stderr, "%d CPUID levels; family:model:stepping 0x%x:%x:%x (%d:%d:%d)\n",
max_level, family, model, stepping, family, model, stepping);
if (!(edx & (1 << 5)))
errx(1, "CPUID: no MSR");
/*
* check max extended function levels of CPUID.
* This is needed to check for invariant TSC.
* This check is valid for both Intel and AMD.
*/
ebx = ecx = edx = 0;
__get_cpuid(0x80000000, &max_level, &ebx, &ecx, &edx);
if (max_level >= 0x80000007) {
/*
* Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
* this check is valid for both Intel and AMD
*/
__get_cpuid(0x80000007, &eax, &ebx, &ecx, &edx);
has_invariant_tsc = edx & (1 << 8);
}
/*
* APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
* this check is valid for both Intel and AMD
*/
__get_cpuid(0x6, &eax, &ebx, &ecx, &edx);
has_aperf = ecx & (1 << 0);
do_dts = eax & (1 << 0);
do_ptm = eax & (1 << 6);
has_epb = ecx & (1 << 3);
if (debug)
fprintf(stderr, "CPUID(6): %sAPERF, %sDTS, %sPTM, %sEPB\n",
has_aperf ? "" : "No ",
do_dts ? "" : "No ",
do_ptm ? "" : "No ",
has_epb ? "" : "No ");
do_nhm_platform_info = do_nhm_cstates = do_smi = probe_nhm_msrs(family, model);
do_snb_cstates = has_snb_msrs(family, model);
do_pc2 = do_snb_cstates && (pkg_cstate_limit >= PCL__2);
do_pc3 = (pkg_cstate_limit >= PCL__3);
do_pc6 = (pkg_cstate_limit >= PCL__6);
do_pc7 = do_snb_cstates && (pkg_cstate_limit >= PCL__7);
do_c8_c9_c10 = has_hsw_msrs(family, model);
do_slm_cstates = is_slm(family, model);
bclk = discover_bclk(family, model);
do_nhm_turbo_ratio_limit = do_nhm_platform_info && has_nhm_turbo_ratio_limit(family, model);
do_ivt_turbo_ratio_limit = has_ivt_turbo_ratio_limit(family, model);
rapl_probe(family, model);
perf_limit_reasons_probe(family, model);
return;
}
void help()
{
fprintf(stderr,
"Usage: turbostat [OPTIONS][(--interval seconds) | COMMAND ...]\n"
"\n"
"Turbostat forks the specified COMMAND and prints statistics\n"
"when COMMAND completes.\n"
"If no COMMAND is specified, turbostat wakes every 5-seconds\n"
"to print statistics, until interrupted.\n"
"--debug run in \"debug\" mode\n"
"--interval sec Override default 5-second measurement interval\n"
"--help print this help message\n"
"--counter msr print 32-bit counter at address \"msr\"\n"
"--Counter msr print 64-bit Counter at address \"msr\"\n"
"--msr msr print 32-bit value at address \"msr\"\n"
"--MSR msr print 64-bit Value at address \"msr\"\n"
"--version print version information\n"
"\n"
"For more help, run \"man turbostat\"\n");
}
/*
* in /dev/cpu/ return success for names that are numbers
* ie. filter out ".", "..", "microcode".
*/
int dir_filter(const struct dirent *dirp)
{
if (isdigit(dirp->d_name[0]))
return 1;
else
return 0;
}
int open_dev_cpu_msr(int dummy1)
{
return 0;
}
void topology_probe()
{
int i;
int max_core_id = 0;
int max_package_id = 0;
int max_siblings = 0;
struct cpu_topology {
int core_id;
int physical_package_id;
} *cpus;
/* Initialize num_cpus, max_cpu_num */
topo.num_cpus = 0;
topo.max_cpu_num = 0;
for_all_proc_cpus(count_cpus);
if (!summary_only && topo.num_cpus > 1)
show_cpu = 1;
if (debug > 1)
fprintf(stderr, "num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
cpus = calloc(1, (topo.max_cpu_num + 1) * sizeof(struct cpu_topology));
if (cpus == NULL)
err(1, "calloc cpus");
/*
* Allocate and initialize cpu_present_set
*/
cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
if (cpu_present_set == NULL)
err(3, "CPU_ALLOC");
cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
for_all_proc_cpus(mark_cpu_present);
/*
* Allocate and initialize cpu_affinity_set
*/
cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
if (cpu_affinity_set == NULL)
err(3, "CPU_ALLOC");
cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
/*
* For online cpus
* find max_core_id, max_package_id
*/
for (i = 0; i <= topo.max_cpu_num; ++i) {
int siblings;
if (cpu_is_not_present(i)) {
if (debug > 1)
fprintf(stderr, "cpu%d NOT PRESENT\n", i);
continue;
}
cpus[i].core_id = get_core_id(i);
if (cpus[i].core_id > max_core_id)
max_core_id = cpus[i].core_id;
cpus[i].physical_package_id = get_physical_package_id(i);
if (cpus[i].physical_package_id > max_package_id)
max_package_id = cpus[i].physical_package_id;
siblings = get_num_ht_siblings(i);
if (siblings > max_siblings)
max_siblings = siblings;
if (debug > 1)
fprintf(stderr, "cpu %d pkg %d core %d\n",
i, cpus[i].physical_package_id, cpus[i].core_id);
}
topo.num_cores_per_pkg = max_core_id + 1;
if (debug > 1)
fprintf(stderr, "max_core_id %d, sizing for %d cores per package\n",
max_core_id, topo.num_cores_per_pkg);
if (!summary_only && topo.num_cores_per_pkg > 1)
show_core = 1;
topo.num_packages = max_package_id + 1;
if (debug > 1)
fprintf(stderr, "max_package_id %d, sizing for %d packages\n",
max_package_id, topo.num_packages);
if (!summary_only && topo.num_packages > 1)
show_pkg = 1;
topo.num_threads_per_core = max_siblings;
if (debug > 1)
fprintf(stderr, "max_siblings %d\n", max_siblings);
free(cpus);
}
void
allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
{
int i;
*t = calloc(topo.num_threads_per_core * topo.num_cores_per_pkg *
topo.num_packages, sizeof(struct thread_data));
if (*t == NULL)
goto error;
for (i = 0; i < topo.num_threads_per_core *
topo.num_cores_per_pkg * topo.num_packages; i++)
(*t)[i].cpu_id = -1;
*c = calloc(topo.num_cores_per_pkg * topo.num_packages,
sizeof(struct core_data));
if (*c == NULL)
goto error;
for (i = 0; i < topo.num_cores_per_pkg * topo.num_packages; i++)
(*c)[i].core_id = -1;
*p = calloc(topo.num_packages, sizeof(struct pkg_data));
if (*p == NULL)
goto error;
for (i = 0; i < topo.num_packages; i++)
(*p)[i].package_id = i;
return;
error:
err(1, "calloc counters");
}
/*
* init_counter()
*
* set cpu_id, core_num, pkg_num
* set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
*
* increment topo.num_cores when 1st core in pkg seen
*/
void init_counter(struct thread_data *thread_base, struct core_data *core_base,
struct pkg_data *pkg_base, int thread_num, int core_num,
int pkg_num, int cpu_id)
{
struct thread_data *t;
struct core_data *c;
struct pkg_data *p;
t = GET_THREAD(thread_base, thread_num, core_num, pkg_num);
c = GET_CORE(core_base, core_num, pkg_num);
p = GET_PKG(pkg_base, pkg_num);
t->cpu_id = cpu_id;
if (thread_num == 0) {
t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
if (cpu_is_first_core_in_package(cpu_id))
t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
}
c->core_id = core_num;
p->package_id = pkg_num;
}
int initialize_counters(int cpu_id)
{
int my_thread_id, my_core_id, my_package_id;
my_package_id = get_physical_package_id(cpu_id);
my_core_id = get_core_id(cpu_id);
if (cpu_is_first_sibling_in_core(cpu_id)) {
my_thread_id = 0;
topo.num_cores++;
} else {
my_thread_id = 1;
}
init_counter(EVEN_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
init_counter(ODD_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
return 0;
}
void allocate_output_buffer()
{
output_buffer = calloc(1, (1 + topo.num_cpus) * 1024);
outp = output_buffer;
if (outp == NULL)
err(-1, "calloc output buffer");
}
void setup_all_buffers(void)
{
topology_probe();
allocate_counters(&thread_even, &core_even, &package_even);
allocate_counters(&thread_odd, &core_odd, &package_odd);
allocate_output_buffer();
for_all_proc_cpus(initialize_counters);
}
void turbostat_init()
{
check_dev_msr();
check_permissions();
check_cpuid();
setup_all_buffers();
if (debug)
print_verbose_header();
if (debug)
for_all_cpus(print_epb, ODD_COUNTERS);
if (debug)
for_all_cpus(print_perf_limit, ODD_COUNTERS);
if (debug)
for_all_cpus(print_rapl, ODD_COUNTERS);
for_all_cpus(set_temperature_target, ODD_COUNTERS);
if (debug)
for_all_cpus(print_thermal, ODD_COUNTERS);
}
int fork_it(char **argv)
{
pid_t child_pid;
int status;
status = for_all_cpus(get_counters, EVEN_COUNTERS);
if (status)
exit(status);
/* clear affinity side-effect of get_counters() */
sched_setaffinity(0, cpu_present_setsize, cpu_present_set);
gettimeofday(&tv_even, (struct timezone *)NULL);
child_pid = fork();
if (!child_pid) {
/* child */
execvp(argv[0], argv);
} else {
/* parent */
if (child_pid == -1)
err(1, "fork");
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
if (waitpid(child_pid, &status, 0) == -1)
err(status, "waitpid");
}
/*
* n.b. fork_it() does not check for errors from for_all_cpus()
* because re-starting is problematic when forking
*/
for_all_cpus(get_counters, ODD_COUNTERS);
gettimeofday(&tv_odd, (struct timezone *)NULL);
timersub(&tv_odd, &tv_even, &tv_delta);
for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS);
compute_average(EVEN_COUNTERS);
format_all_counters(EVEN_COUNTERS);
flush_stderr();
fprintf(stderr, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec/1000000.0);
return status;
}
int get_and_dump_counters(void)
{
int status;
status = for_all_cpus(get_counters, ODD_COUNTERS);
if (status)
return status;
status = for_all_cpus(dump_counters, ODD_COUNTERS);
if (status)
return status;
flush_stdout();
return status;
}
void print_version() {
fprintf(stderr, "turbostat version 4.1 10-Feb, 2015"
" - Len Brown <lenb@kernel.org>\n");
}
void cmdline(int argc, char **argv)
{
int opt;
int option_index = 0;
static struct option long_options[] = {
{"Counter", required_argument, 0, 'C'},
{"counter", required_argument, 0, 'c'},
{"Dump", no_argument, 0, 'D'},
{"debug", no_argument, 0, 'd'},
{"interval", required_argument, 0, 'i'},
{"help", no_argument, 0, 'h'},
{"Joules", no_argument, 0, 'J'},
{"MSR", required_argument, 0, 'M'},
{"msr", required_argument, 0, 'm'},
{"Package", no_argument, 0, 'p'},
{"processor", no_argument, 0, 'p'},
{"Summary", no_argument, 0, 'S'},
{"TCC", required_argument, 0, 'T'},
{"version", no_argument, 0, 'v' },
{0, 0, 0, 0 }
};
progname = argv[0];
while ((opt = getopt_long_only(argc, argv, "C:c:Ddhi:JM:m:PpST:v",
long_options, &option_index)) != -1) {
switch (opt) {
case 'C':
sscanf(optarg, "%x", &extra_delta_offset64);
break;
case 'c':
sscanf(optarg, "%x", &extra_delta_offset32);
break;
case 'D':
dump_only++;
break;
case 'd':
debug++;
break;
case 'h':
default:
help();
exit(1);
case 'i':
interval_sec = atoi(optarg);
break;
case 'J':
rapl_joules++;
break;
case 'M':
sscanf(optarg, "%x", &extra_msr_offset64);
break;
case 'm':
sscanf(optarg, "%x", &extra_msr_offset32);
break;
case 'P':
show_pkg_only++;
break;
case 'p':
show_core_only++;
break;
case 'S':
summary_only++;
break;
case 'T':
tcc_activation_temp_override = atoi(optarg);
break;
case 'v':
print_version();
exit(0);
break;
}
}
}
int main(int argc, char **argv)
{
cmdline(argc, argv);
if (debug)
print_version();
turbostat_init();
/* dump counters and exit */
if (dump_only)
return get_and_dump_counters();
/*
* if any params left, it must be a command to fork
*/
if (argc - optind)
return fork_it(argv + optind);
else
turbostat_loop();
return 0;
}
| {
"pile_set_name": "Github"
} |
package io.jenkins.jenkinsfile.runner;
import io.jenkins.jenkinsfile.runner.bootstrap.Bootstrap;
import io.jenkins.jenkinsfile.runner.bootstrap.IApp;
/**
* This code runs after Jetty and Jenkins classloaders are set up correctly.
*/
public class App implements IApp {
@Override
public int run(Bootstrap bootstrap) throws Throwable {
JenkinsLauncher launcher = createLauncherFor(bootstrap);
return launcher.launch();
}
private JenkinsLauncher createLauncherFor(Bootstrap bootstrap) {
if(bootstrap.cliOnly) {
return new CLILauncher(bootstrap);
} else {
return new JenkinsfileRunnerLauncher(bootstrap);
}
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 66f14294598384e4f98e25c3dd900f87
timeCreated: 1536867831
licenseType: Pro
NativeFormatImporter:
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
package com.taobao.zeus.schedule.mvc;
import com.taobao.zeus.client.ZeusException;
public class ZeusJobException extends ZeusException{
private static final long serialVersionUID = 1L;
private String causeJobId;
public ZeusJobException(String jobId,String msg){
super(msg);
this.causeJobId=jobId;
}
public ZeusJobException(String jobId,String msg,Throwable cause){
super(msg, cause);
this.causeJobId=jobId;
}
public String getCauseJobId() {
return causeJobId;
}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.