max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
66,985 | <reponame>techAi007/spring-boot<gh_stars>1000+
/*
* Copyright 2012-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.boot.buildpack.platform.docker.ssl;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.springframework.util.Assert;
/**
* Builds an {@link SSLContext} for use with an HTTP connection.
*
* @author <NAME>
* @author <NAME>
* @since 2.3.0
*/
public class SslContextFactory {
private static final char[] NO_PASSWORD = {};
private static final String KEY_STORE_ALIAS = "spring-boot-docker";
public SslContextFactory() {
}
/**
* Create an {@link SSLContext} from files in the specified directory. The directory
* must contain files with the names 'key.pem', 'cert.pem', and 'ca.pem'.
* @param directory the path to a directory containing certificate and key files
* @return the {@code SSLContext}
*/
public SSLContext forDirectory(String directory) {
try {
Path keyPath = Paths.get(directory, "key.pem");
Path certPath = Paths.get(directory, "cert.pem");
Path caPath = Paths.get(directory, "ca.pem");
Path caKeyPath = Paths.get(directory, "ca-key.pem");
verifyCertificateFiles(keyPath, certPath, caPath);
KeyManagerFactory keyManagerFactory = getKeyManagerFactory(keyPath, certPath);
TrustManagerFactory trustManagerFactory = getTrustManagerFactory(caPath, caKeyPath);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
return sslContext;
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
private KeyManagerFactory getKeyManagerFactory(Path keyPath, Path certPath) throws Exception {
KeyStore store = KeyStoreFactory.create(certPath, keyPath, KEY_STORE_ALIAS);
KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
factory.init(store, NO_PASSWORD);
return factory;
}
private TrustManagerFactory getTrustManagerFactory(Path caPath, Path caKeyPath)
throws NoSuchAlgorithmException, KeyStoreException {
KeyStore store = KeyStoreFactory.create(caPath, caKeyPath, KEY_STORE_ALIAS);
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(store);
return factory;
}
private static void verifyCertificateFiles(Path... paths) {
for (Path path : paths) {
Assert.state(Files.exists(path) && Files.isRegularFile(path),
"Certificate path must contain the files 'ca.pem', 'cert.pem', and 'key.pem' files");
}
}
}
| 1,089 |
1,030 | <gh_stars>1000+
// Copyright (c) 2012-2013 NetEase Youdao Inc. and other heX contributors. All
// rights reserved. Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
#include "hex_object.h"
#include "hex_switches_port.h"
#include "hex_shared_win.h"
#include <windowsx.h>
#include <TlHelp32.h>
#include <process.h>
namespace hex {
static int ppid = 0;
static HWND mainWindowHandle = NULL;
#define BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(name) \
void name##Getter(v8::Local<v8::String> property, \
const v8::PropertyCallbackInfo<v8::Value>& info) { \
v8::HandleScope scope;
#define END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER() }
#define BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER(name) \
void name##Setter(v8::Local<v8::String> property, \
v8::Local<v8::Value> value, \
const v8::PropertyCallbackInfo<void>& info) { \
v8::HandleScope scope;
#define END_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER() }
#define GET_TOP(from) (HWND)from.This()->Get(v8::String::NewSymbol( \
"topWindowHandle"))->Int32Value()
#define GET_BROWSER(from) (HWND)from.This()->Get(v8::String::NewSymbol( \
"browserWindowHandle"))->Int32Value()
#define GET_WIDGET(from) (HWND)from.This()->Get(v8::String::NewSymbol( \
"widgetWindowHandle"))->Int32Value()
#define GET_RENDERER(from) (HWND)from.This()->Get(v8::String::NewSymbol( \
"rendererWindowHandle"))->Int32Value()
#define REQUIRE_HEX_THIS() \
if (args.Holder() != v8::Context::GetEntered()->Global()->Get(HEX_SYMBOL)) {\
return v8::ThrowException(v8::Exception::TypeError( \
v8::String::New("Illegal invocation"))); \
}
#define BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(name) \
void name##Callback(const v8::FunctionCallbackInfo<v8::Value>& args) { \
v8::HandleScope scope; \
//REQUIRE_HEX_THIS();
#define END_IMPLEMENT_HEX_OBJECT_METHOD() }
#define RESULT(info, obj) info.GetReturnValue().Set(obj)
/*static void ChangeDirectory(v8::Handle<v8::String> dir) {
v8::String::Utf8Value path(dir->ToString());
uv_err_t r = uv_chdir(*path);
}*/
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(WidgetWindowHandle)
HWND widget = NULL;
HWND browser = GET_BROWSER(info);
widget = GetWidgetWindowHandle(browser);
RESULT(info, v8::Integer::New((int)widget));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(RendererWindowHandle)
HWND renderer = NULL;
HWND browser = GET_BROWSER(info);
HWND widget = GetWidgetWindowHandle(browser);
renderer = GetRendererWindowHandle(widget);
RESULT(info, v8::Integer::New((int)renderer));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(AeroGlassEnabled)
RESULT(info, v8::Boolean::New(IsAeroGlassEnabled()));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(Restore)
bool directly = false;
if (args.Length() >= 1 && args[0]->IsBoolean()) {
directly = args[0]->BooleanValue();
}
HWND top = GET_TOP(args);
DoSystemCommand(top, RESTORE, directly);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(Move)
bool directly = false;
if (args.Length() >= 1 && args[0]->IsBoolean()) {
directly = args[0]->BooleanValue();
}
HWND top = GET_TOP(args);
DoSystemCommand(top, MOVE, directly);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(Size)
bool directly = false;
if (args.Length() >= 1 && args[0]->IsBoolean()) {
directly = args[0]->BooleanValue();
}
HWND top = GET_TOP(args);
DoSystemCommand(top, SIZE, directly);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(Minimize)
bool directly = false;
if (args.Length() >= 1 && args[0]->IsBoolean()) {
directly = args[0]->BooleanValue();
}
HWND top = GET_TOP(args);
DoSystemCommand(top, MINIMIZE, directly);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(Maximize)
bool directly = false;
if (args.Length() >= 1 && args[0]->IsBoolean()) {
directly = args[0]->BooleanValue();
}
HWND top = GET_TOP(args);
DoSystemCommand(top, MAXIMIZE, directly);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(Close)
bool directly = false;
if (args.Length() >= 1 && args[0]->IsBoolean()) {
directly = args[0]->BooleanValue();
}
HWND top = GET_TOP(args);
DoSystemCommand(top, CLOSE, directly);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(ShowSystemMenu)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
RESULT(args, v8::Undefined());
return;
}
HWND renderer = GET_RENDERER(args);
int x = (int)args[0]->Int32Value();
int y = (int)args[1]->Int32Value();
DWORD returnCommand = TrackSystemMenu(renderer, x, y, NULL);
RESULT(args, v8::Integer::New(returnCommand));
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(DeleteSystemCommand)
if (args.Length() < 1 || !args[0]->IsInt32()) {
RESULT(args, v8::False());
return;
}
HWND top = GET_TOP(args);
SystemCommand command = static_cast<SystemCommand>(args[0]->Int32Value());
BOOL success = DeleteSystemCommand(top, command);
RESULT(args, v8::Boolean::New(!!success));
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(EnableSystemCommand)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsBoolean()) {
RESULT(args, v8::Undefined());
return;
}
HWND renderer = GET_RENDERER(args);
SystemCommand command = static_cast<SystemCommand>(args[0]->Int32Value());
bool enabled = args[1]->BooleanValue();
BOOL prevState = EnableSystemCommand(renderer, command, enabled);
RESULT(args, v8::Boolean::New(!!prevState));
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(InsertSystemCommand)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
RESULT(args, v8::False());
return;
}
HWND top = GET_TOP(args);
SystemCommand insCommand = static_cast<SystemCommand>(args[0]->Int32Value());
int command = args[1]->Int32Value();
BOOL success = InsertSystemCommand(top, insCommand, command);
RESULT(args, v8::Boolean::New(!!success));
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(FormState)
FormState state = NORMAL;
HWND top = GET_TOP(info);
state = GetState(top);
RESULT(info, v8::Integer::New(static_cast<int>(state)));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER(FormState)
if (!value->IsInt32()) {
return;
}
HWND top = GET_TOP(info);
FormState state = static_cast<FormState>(value->Int32Value());
SetState(top, state);
END_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(FormActivation)
bool activation = true;
HWND top = GET_TOP(info);
activation = IsFormActivated(top);
RESULT(info, v8::Boolean::New(activation));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(SetAsParentForm)
if (args.Length() < 1 || !args[0]->IsBoolean()) {
RESULT(args, v8::Undefined());
return;
}
HWND browser = GET_BROWSER(args);
bool modelDialog = args[0]->BooleanValue();
SetAsParentForm(browser, modelDialog);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(TopMost)
HWND top = GET_TOP(info);
BOOL topMost = IsTopMost(top);
RESULT(info, v8::Boolean::New(!!topMost));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER(TopMost)
if (!value->IsBoolean()) {
return;
}
HWND top = GET_TOP(info);
bool topMost = value->BooleanValue();
SetTopMost(top, topMost);
END_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(SizeTo)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
RESULT(args, v8::Undefined());
return;
}
bool sendMoving = true;
if (args.Length() > 2 && args[2]->IsBoolean()) {
sendMoving = args[2]->BooleanValue();
}
HWND top = GET_TOP(args);
int x = (int)args[0]->Int32Value();
int y = (int)args[1]->Int32Value();
SIZEL size = SizeTo(top, x, y, sendMoving);
v8::Handle<v8::Object> retObj = v8::Object::New();
retObj->Set(v8::String::New("width"), v8::Int32::New(size.cx));
retObj->Set(v8::String::New("height"), v8::Int32::New(size.cy));
RESULT(args, retObj);
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(MoveTo)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
RESULT(args, v8::Undefined());
return;
}
bool sendMoving = true;
if (args.Length() > 2 && args[2]->IsBoolean()) {
sendMoving = args[2]->BooleanValue();
}
HWND top = GET_TOP(args);
int x = (int)args[0]->Int32Value();
int y = (int)args[1]->Int32Value();
POINT point = MoveTo(top, x, y, sendMoving);
v8::Handle<v8::Object> retObj = v8::Object::New();
retObj->Set(v8::String::New("x"), v8::Int32::New(point.x));
retObj->Set(v8::String::New("y"), v8::Int32::New(point.y));
RESULT(args, retObj);
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(FormEnabled)
bool enabled = true;
HWND top = GET_TOP(info);
enabled = IsFormEnabled(top);
RESULT(info, v8::Boolean::New(enabled));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER(FormEnabled)
HWND top = GET_TOP(info);
HWND browser = GET_BROWSER(info);
SetFormEnable(top, browser, (BOOL)value->BooleanValue());
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(FocusForm)
HWND top = GET_TOP(args);
BOOL success = FocusForm(top);
RESULT(args, v8::Boolean::New(!!success));
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(Transparency)
HWND top = GET_TOP(info);
int alpha = GetTransparency(top);
if (alpha < 0) {
RESULT(info, v8::Undefined());
return;
}
RESULT(info, v8::Int32::New(alpha));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER(Transparency)
HWND top = GET_TOP(info);
int alpha = (int)value->Int32Value();
if (alpha >= 0 && alpha <= 255) {
SetTransparency(top, alpha);
}
END_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(SetAsTitleBarAreas)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
RESULT(args, v8::Undefined());
return;
}
HWND top = GET_TOP(args);
HWND renderer = GET_RENDERER(args);
int x = (int)args[0]->Int32Value();
int y = (int)args[1]->Int32Value();
SetAsTitleBarAreas(top, x, y);
SetAsTitleBarAreas(renderer, x, y);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(SetAsNonBorderAreas)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
RESULT(args, v8::Undefined());
return;
}
HWND top = GET_TOP(args);
HWND renderer = GET_RENDERER(args);
int x = (int)args[0]->Int32Value();
int y = (int)args[1]->Int32Value();
SetAsNonBorderAreas(top, x, y);
SetAsNonBorderAreas(renderer, x, y);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(SetAsSystemMenuIconAreas)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
RESULT(args, v8::Undefined());
return;
}
HWND top = GET_TOP(args);
HWND renderer = GET_RENDERER(args);
int x = (int)args[0]->Int32Value();
int y = (int)args[1]->Int32Value();
SetAsSystemMenuIconAreas(top, x, y);
SetAsSystemMenuIconAreas(renderer, x, y);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(SetPopupFormSize)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
RESULT(args, v8::Undefined());
return;
}
HWND browser = GET_BROWSER(args);
int width = (int)args[0]->Int32Value();
int height = (int)args[1]->Int32Value();
SetPopupFormSize(browser, width, height);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(SetPopupFormPosition)
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
RESULT(args, v8::Undefined());
return;
}
HWND browser = GET_BROWSER(args);
int x = (int)args[0]->Int32Value();
int y = (int)args[1]->Int32Value();
SetPopupFormPosition(browser, x, y);
RESULT(args, v8::Undefined());
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(MinWidth)
HWND browser = GET_BROWSER(info);
int minWidth = GetMinWidth(browser);
RESULT(info, v8::Int32::New(minWidth));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER(MinWidth)
if (!value->IsInt32()) {
return;
}
HWND browser = GET_BROWSER(info);
int minWidth = value->Int32Value();
SetMinWidth(browser, minWidth);
END_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(MinHeight)
HWND browser = GET_BROWSER(info);
int minHeight = GetMinHeight(browser);
RESULT(info, v8::Int32::New(minHeight));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER(MinHeight)
if (!value->IsInt32()) {
return;
}
HWND browser = GET_BROWSER(info);
int minHeight = value->Int32Value();
SetMinHeight(browser, minHeight);
END_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(MaxWidth)
HWND browser = GET_BROWSER(info);
int maxWidth = GetMaxWidth(browser);
RESULT(info, v8::Int32::New(maxWidth));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER(MaxWidth)
if (!value->IsInt32()) {
return;
}
HWND browser = GET_BROWSER(info);
int maxWidth = value->Int32Value();
SetMaxWidth(browser, maxWidth);
END_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER(MaxHeight)
HWND browser = GET_BROWSER(info);
int maxHeight = GetMaxHeight(browser);
RESULT(info, v8::Int32::New(maxHeight));
END_IMPLEMENT_HEX_OBJECT_PROPERTY_GETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER(MaxHeight)
if (!value->IsInt32()) {
return;
}
HWND browser = GET_BROWSER(info);
int maxHeight = value->Int32Value();
SetMaxHeight(browser, maxHeight);
END_IMPLEMENT_HEX_OBJECT_PROPERTY_SETTER();
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(GetSize)
HWND top = GET_TOP(args);
SIZEL size = GetSize(top);
v8::Handle<v8::Object> returnObject = v8::Object::New();
returnObject->Set(v8::String::New("width"), v8::Int32::New(size.cx));
returnObject->Set(v8::String::New("height"), v8::Int32::New(size.cy));
RESULT(args, returnObject);
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(GetPosition)
HWND top = GET_TOP(args);
POINT point = GetPosition(top);
v8::Handle<v8::Object> returnObject = v8::Object::New();
returnObject->Set(v8::String::New("x"), v8::Int32::New(point.x));
returnObject->Set(v8::String::New("y"), v8::Int32::New(point.y));
RESULT(args, returnObject);
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(GetWorkspaceRect)
HWND top = GET_TOP(args);
RECT rect = GetWorkspaceRect(top);
v8::Handle<v8::Object> returnObject = v8::Object::New();
returnObject->Set(v8::String::New("left"), v8::Int32::New(rect.left));
returnObject->Set(v8::String::New("top"), v8::Int32::New(rect.top));
returnObject->Set(v8::String::New("right"), v8::Int32::New(rect.right));
returnObject->Set(v8::String::New("bottom"), v8::Int32::New(rect.bottom));
RESULT(args, returnObject);
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(SetFormIcon)
if (args.Length() < 1 || !args[0]->IsString()) {
RESULT(args, v8::False());
return;
}
HWND top = GET_TOP(args);
v8::Local<v8::String> path_str = args[0]->ToString();
int len = path_str->Length();
if (len == 0) {
RESULT(args, v8::False());
return;
}
WCHAR* path = new WCHAR[len + 1];
path_str->Write(reinterpret_cast<uint16_t*>(path), 0, len + 1);
bool result = SetFormIcon(top, path);
delete [] path;
RESULT(args, v8::Boolean::New(result));
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(Terminate)
HWND top = GET_TOP(args);
RESULT(args, v8::Boolean::New(Terminate(top)));
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(CancelMode)
HWND top = GET_TOP(args);
CancelMode(top);
END_IMPLEMENT_HEX_OBJECT_METHOD()
BEGIN_IMPLEMENT_HEX_OBJECT_METHOD(GetMaximizedAdjustedBorderWidth)
HWND renderer = GET_RENDERER(args);
RESULT(args, v8::Int32::New(GetMaximizedAdjustedBorderWidth(renderer)));
END_IMPLEMENT_HEX_OBJECT_METHOD()
} // namespace hex
| 7,259 |
521 | <gh_stars>100-1000
/* $Id: DBGPlugInDarwin.cpp $ */
/** @file
* DBGPlugInDarwin - Debugger and Guest OS Digger Plugin For Darwin / OS X.
*/
/*
* Copyright (C) 2008-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DBGF /// @todo add new log group.
#include "DBGPlugIns.h"
#include <VBox/vmm/dbgf.h>
#include <iprt/string.h>
#include <iprt/mem.h>
#include <iprt/stream.h>
#include <iprt/uuid.h>
#include <iprt/ctype.h>
#include <iprt/formats/mach-o.h>
/*********************************************************************************************************************************
* Structures and Typedefs *
*********************************************************************************************************************************/
/** @name Internal Darwin structures
* @{ */
/**
* 32-bit darwin kernel module info structure (kmod_info_t).
*/
typedef struct OSX32_kmod_info
{
uint32_t next;
int32_t info_version;
uint32_t id;
char name[64];
char version[64];
int32_t reference_count;
uint32_t reference_list; /**< Points to kmod_reference_t. */
uint32_t address; /**< Where in memory the kext is loaded. */
uint32_t size;
uint32_t hdr_size;
uint32_t start; /**< Address of kmod_start_func_t. */
uint32_t stop; /**< Address of kmod_stop_func_t. */
} OSX32_kmod_info_t;
/**
* 32-bit darwin kernel module info structure (kmod_info_t).
*/
#pragma pack(1)
typedef struct OSX64_kmod_info
{
uint64_t next;
int32_t info_version;
uint32_t id;
char name[64];
char version[64];
int32_t reference_count;
uint64_t reference_list; /**< Points to kmod_reference_t. Misaligned, duh. */
uint64_t address; /**< Where in memory the kext is loaded. */
uint64_t size;
uint64_t hdr_size;
uint64_t start; /**< Address of kmod_start_func_t. */
uint64_t stop; /**< Address of kmod_stop_func_t. */
} OSX64_kmod_info_t;
#pragma pack()
/** The value of the info_version field. */
#define OSX_KMOD_INFO_VERSION INT32_C(1)
/** @} */
/**
* Linux guest OS digger instance data.
*/
typedef struct DBGDIGGERDARWIN
{
/** Whether the information is valid or not.
* (For fending off illegal interface method calls.) */
bool fValid;
/** Set if 64-bit kernel, clear if 32-bit.
* Set during probing. */
bool f64Bit;
/** The address of an kernel version string (there are several).
* This is set during probing. */
DBGFADDRESS AddrKernelVersion;
/** Kernel base address.
* This is set during probing. */
DBGFADDRESS AddrKernel;
/** The kernel message log interface. */
DBGFOSIDMESG IDmesg;
} DBGDIGGERDARWIN;
/** Pointer to the linux guest OS digger instance data. */
typedef DBGDIGGERDARWIN *PDBGDIGGERDARWIN;
/*********************************************************************************************************************************
* Defined Constants And Macros *
*********************************************************************************************************************************/
/** Validates a 32-bit darwin kernel address */
#define OSX32_VALID_ADDRESS(Addr) ((Addr) > UINT32_C(0x00001000) && (Addr) < UINT32_C(0xfffff000))
/** Validates a 64-bit darwin kernel address */
#define OSX64_VALID_ADDRESS(Addr) ((Addr) > UINT64_C(0xffff800000000000) && (Addr) < UINT64_C(0xfffffffffffff000))
/** Validates a 32-bit or 64-bit darwin kernel address. */
#define OSX_VALID_ADDRESS(a_f64Bits, a_Addr) \
((a_f64Bits) ? OSX64_VALID_ADDRESS(a_Addr) : OSX32_VALID_ADDRESS(a_Addr))
/** AppleOsX on little endian ASCII systems. */
#define DIG_DARWIN_MOD_TAG UINT64_C(0x58734f656c707041)
/*********************************************************************************************************************************
* Internal Functions *
*********************************************************************************************************************************/
static DECLCALLBACK(int) dbgDiggerDarwinInit(PUVM pUVM, void *pvData);
/**
* @interface_method_impl{DBGFOSIDMESG,pfnQueryKernelLog}
*/
static DECLCALLBACK(int) dbgDiggerDarwinIDmsg_QueryKernelLog(PDBGFOSIDMESG pThis, PUVM pUVM, uint32_t fFlags, uint32_t cMessages,
char *pszBuf, size_t cbBuf, size_t *pcbActual)
{
RT_NOREF1(fFlags);
PDBGDIGGERDARWIN pData = RT_FROM_MEMBER(pThis, DBGDIGGERDARWIN, IDmesg);
if (cMessages < 1)
return VERR_INVALID_PARAMETER;
/*
* The 'msgbufp' variable points to a struct msgbuf (bsd/kern/subr_log.c).
*/
RTDBGAS hAs = DBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
RTDBGMOD hMod;
int rc = RTDbgAsModuleByName(hAs, "mach_kernel", 0, &hMod);
if (RT_FAILURE(rc))
return VERR_NOT_FOUND;
RTDbgAsRelease(hAs);
DBGFADDRESS Addr;
RTGCPTR GCPtrMsgBufP = 0;
RTDBGSYMBOL SymInfo;
rc = RTDbgModSymbolByName(hMod, "_msgbufp", &SymInfo);
if (RT_SUCCESS(rc))
{
rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &Addr, SymInfo.Value + pData->AddrKernel.FlatPtr),
&GCPtrMsgBufP, pData->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t));
if (RT_FAILURE(rc))
{
Log(("dbgDiggerDarwinIDmsg_QueryKernelLog: failed to read _msgbufp at %RGv: %Rrc\n", Addr.FlatPtr, rc));
return VERR_NOT_FOUND;
}
if (!OSX_VALID_ADDRESS(pData->f64Bit, GCPtrMsgBufP))
{
Log(("dbgDiggerDarwinIDmsg_QueryKernelLog: Invalid address for _msgbufp: %RGv\n", GCPtrMsgBufP));
return VERR_NOT_FOUND;
}
}
else
{
rc = RTDbgModSymbolByName(hMod, "_msgbuf", &SymInfo);
if (RT_FAILURE(rc))
{
Log(("dbgDiggerDarwinIDmsg_QueryKernelLog: failed to find _msgbufp and _msgbuf: %Rrc\n", rc));
return VERR_NOT_FOUND;
}
GCPtrMsgBufP = SymInfo.Value + pData->AddrKernel.FlatPtr;
if (!OSX_VALID_ADDRESS(pData->f64Bit, GCPtrMsgBufP))
{
Log(("dbgDiggerDarwinIDmsg_QueryKernelLog: Invalid address for _msgbuf: %RGv\n", GCPtrMsgBufP));
return VERR_NOT_FOUND;
}
}
/*
* Read the msgbuf structure.
*/
struct
{
uint32_t msg_magic;
uint32_t msg_size;
uint32_t msg_bufx;
uint32_t msg_bufr;
uint64_t msg_bufc; /**< Size depends on windows size. */
} MsgBuf;
rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &Addr, GCPtrMsgBufP),
&MsgBuf, sizeof(MsgBuf) - (pData->f64Bit ? 0 : sizeof(uint32_t)) );
if (RT_FAILURE(rc))
{
Log(("dbgDiggerDarwinIDmsg_QueryKernelLog: failed to read msgbuf struct at %RGv: %Rrc\n", Addr.FlatPtr, rc));
return VERR_NOT_FOUND;
}
if (!pData->f64Bit)
MsgBuf.msg_bufc &= UINT32_MAX;
/*
* Validate the structure.
*/
if ( MsgBuf.msg_magic != UINT32_C(0x63061)
|| MsgBuf.msg_size < UINT32_C(4096)
|| MsgBuf.msg_size > 16*_1M
|| MsgBuf.msg_bufx > MsgBuf.msg_size
|| MsgBuf.msg_bufr > MsgBuf.msg_size
|| !OSX_VALID_ADDRESS(pData->f64Bit, MsgBuf.msg_bufc) )
{
Log(("dbgDiggerDarwinIDmsg_QueryKernelLog: Invalid MsgBuf data: magic=%#x size=%#x bufx=%#x bufr=%#x bufc=%RGv\n",
MsgBuf.msg_magic, MsgBuf.msg_size, MsgBuf.msg_bufx, MsgBuf.msg_bufr, MsgBuf.msg_bufc));
return VERR_INVALID_STATE;
}
/*
* Read the buffer.
*/
char *pchMsgBuf = (char *)RTMemAlloc(MsgBuf.msg_size);
if (!pchMsgBuf)
{
Log(("dbgDiggerDarwinIDmsg_QueryKernelLog: Failed to allocate %#x bytes of memory for the log buffer\n",
MsgBuf.msg_size));
return VERR_INVALID_STATE;
}
rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &Addr, MsgBuf.msg_bufc), pchMsgBuf, MsgBuf.msg_size);
if (RT_SUCCESS(rc))
{
/*
* Copy it out raw.
*/
uint32_t offDst = 0;
if (MsgBuf.msg_bufr < MsgBuf.msg_bufx)
{
/* Single chunk between the read and write offsets. */
uint32_t cbToCopy = MsgBuf.msg_bufx - MsgBuf.msg_bufr;
if (cbToCopy < cbBuf)
{
memcpy(pszBuf, &pchMsgBuf[MsgBuf.msg_bufr], cbToCopy);
pszBuf[cbToCopy] = '\0';
rc = VINF_SUCCESS;
}
else
{
if (cbBuf)
{
memcpy(pszBuf, &pchMsgBuf[MsgBuf.msg_bufr], cbBuf - 1);
pszBuf[cbBuf - 1] = '\0';
}
rc = VERR_BUFFER_OVERFLOW;
}
offDst = cbToCopy + 1;
}
else
{
/* Two chunks, read offset to end, start to write offset. */
uint32_t cbFirst = MsgBuf.msg_size - MsgBuf.msg_bufr;
uint32_t cbSecond = MsgBuf.msg_bufx;
if (cbFirst + cbSecond < cbBuf)
{
memcpy(pszBuf, &pchMsgBuf[MsgBuf.msg_bufr], cbFirst);
memcpy(&pszBuf[cbFirst], pchMsgBuf, cbSecond);
offDst = cbFirst + cbSecond;
pszBuf[offDst++] = '\0';
rc = VINF_SUCCESS;
}
else
{
offDst = cbFirst + cbSecond + 1;
if (cbFirst < cbBuf)
{
memcpy(pszBuf, &pchMsgBuf[MsgBuf.msg_bufr], cbFirst);
memcpy(&pszBuf[cbFirst], pchMsgBuf, cbBuf - cbFirst);
pszBuf[cbBuf - 1] = '\0';
}
else if (cbBuf)
{
memcpy(pszBuf, &pchMsgBuf[MsgBuf.msg_bufr], cbBuf - 1);
pszBuf[cbBuf - 1] = '\0';
}
rc = VERR_BUFFER_OVERFLOW;
}
}
if (pcbActual)
*pcbActual = offDst;
}
else
Log(("dbgDiggerDarwinIDmsg_QueryKernelLog: Error reading %#x bytes at %RGv: %Rrc\n", MsgBuf.msg_size, MsgBuf.msg_bufc, rc));
RTMemFree(pchMsgBuf);
return rc;
}
/**
* @copydoc DBGFOSREG::pfnQueryInterface
*/
static DECLCALLBACK(void *) dbgDiggerDarwinQueryInterface(PUVM pUVM, void *pvData, DBGFOSINTERFACE enmIf)
{
RT_NOREF1(pUVM);
PDBGDIGGERDARWIN pThis = (PDBGDIGGERDARWIN)pvData;
switch (enmIf)
{
case DBGFOSINTERFACE_DMESG:
return &pThis->IDmesg;
default:
return NULL;
}
}
/**
* @copydoc DBGFOSREG::pfnQueryVersion
*/
static DECLCALLBACK(int) dbgDiggerDarwinQueryVersion(PUVM pUVM, void *pvData, char *pszVersion, size_t cchVersion)
{
PDBGDIGGERDARWIN pThis = (PDBGDIGGERDARWIN)pvData;
Assert(pThis->fValid);
/*
* It's all in the linux banner.
*/
int rc = DBGFR3MemReadString(pUVM, 0, &pThis->AddrKernelVersion, pszVersion, cchVersion);
if (RT_SUCCESS(rc))
{
char *pszEnd = RTStrEnd(pszVersion, cchVersion);
AssertReturn(pszEnd, VERR_BUFFER_OVERFLOW);
while ( pszEnd > pszVersion
&& RT_C_IS_SPACE(pszEnd[-1]))
pszEnd--;
*pszEnd = '\0';
}
else
RTStrPrintf(pszVersion, cchVersion, "DBGFR3MemRead -> %Rrc", rc);
return rc;
}
/**
* @copydoc DBGFOSREG::pfnTerm
*/
static DECLCALLBACK(void) dbgDiggerDarwinTerm(PUVM pUVM, void *pvData)
{
RT_NOREF1(pUVM);
PDBGDIGGERDARWIN pThis = (PDBGDIGGERDARWIN)pvData;
pThis->fValid = false;
}
/**
* @copydoc DBGFOSREG::pfnRefresh
*/
static DECLCALLBACK(int) dbgDiggerDarwinRefresh(PUVM pUVM, void *pvData)
{
PDBGDIGGERDARWIN pThis = (PDBGDIGGERDARWIN)pvData;
NOREF(pThis);
Assert(pThis->fValid);
/*
* For now we'll flush and reload everything.
*/
dbgDiggerDarwinTerm(pUVM, pvData);
return dbgDiggerDarwinInit(pUVM, pvData);
}
/**
* Helper function that validates a segment (or section) name.
*
* @returns true if valid, false if not.
* @param pszName The name string.
* @param cbName The size of the string, including terminator.
*/
static bool dbgDiggerDarwinIsValidSegOrSectName(const char *pszName, size_t cbName)
{
/* ascii chars */
char ch;
size_t off = 0;
while (off < cbName && (ch = pszName[off]))
{
if (RT_C_IS_CNTRL(ch) || ch >= 127)
return false;
off++;
}
/* Not empty nor 100% full. */
if (off == 0 || off == cbName)
return false;
/* remainder should be zeros. */
while (off < cbName)
{
if (pszName[off])
return false;
off++;
}
return true;
}
static int dbgDiggerDarwinAddModule(PDBGDIGGERDARWIN pThis, PUVM pUVM, uint64_t uModAddr, const char *pszName, bool *pf64Bit)
{
RT_NOREF1(pThis);
union
{
uint8_t ab[2 * X86_PAGE_4K_SIZE];
mach_header_64_t Hdr64;
mach_header_32_t Hdr32;
} uBuf;
/* Read the first page of the image. */
DBGFADDRESS ModAddr;
int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &ModAddr, uModAddr), uBuf.ab, X86_PAGE_4K_SIZE);
if (RT_FAILURE(rc))
return rc;
/* Validate the header. */
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, magic, mach_header_32_t, magic);
if ( uBuf.Hdr64.magic != IMAGE_MACHO64_SIGNATURE
&& uBuf.Hdr32.magic != IMAGE_MACHO32_SIGNATURE)
return VERR_INVALID_EXE_SIGNATURE;
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, cputype, mach_header_32_t, cputype);
bool f64Bit = uBuf.Hdr64.magic == IMAGE_MACHO64_SIGNATURE;
if (uBuf.Hdr32.cputype != (f64Bit ? CPU_TYPE_X86_64 : CPU_TYPE_I386))
return VERR_LDR_ARCH_MISMATCH;
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, filetype, mach_header_32_t, filetype);
if ( uBuf.Hdr32.filetype != MH_EXECUTE
&& uBuf.Hdr32.filetype != (f64Bit ? MH_KEXT_BUNDLE : MH_OBJECT))
return VERR_BAD_EXE_FORMAT;
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, ncmds, mach_header_32_t, ncmds);
if (uBuf.Hdr32.ncmds > 256)
return VERR_BAD_EXE_FORMAT;
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, sizeofcmds, mach_header_32_t, sizeofcmds);
if (uBuf.Hdr32.sizeofcmds > X86_PAGE_4K_SIZE * 2 - sizeof(mach_header_64_t))
return VERR_BAD_EXE_FORMAT;
/* Do we need to read a 2nd page to get all the load commands? If so, do it. */
if (uBuf.Hdr32.sizeofcmds + (f64Bit ? sizeof(mach_header_64_t) : sizeof(mach_header_32_t)) > X86_PAGE_4K_SIZE)
{
rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &ModAddr, uModAddr + X86_PAGE_4K_SIZE),
&uBuf.ab[X86_PAGE_4K_SIZE], X86_PAGE_4K_SIZE);
if (RT_FAILURE(rc))
return rc;
}
/*
* Process the load commands.
*/
RTDBGSEGMENT aSegs[24];
uint32_t cSegs = 0;
RTUUID Uuid = RTUUID_INITIALIZE_NULL;
uint32_t cLeft = uBuf.Hdr32.ncmds;
uint32_t cbLeft = uBuf.Hdr32.sizeofcmds;
union
{
uint8_t const *pb;
load_command_t const *pGenric;
segment_command_32_t const *pSeg32;
segment_command_64_t const *pSeg64;
section_32_t const *pSect32;
section_64_t const *pSect64;
symtab_command_t const *pSymTab;
uuid_command_t const *pUuid;
} uLCmd;
uLCmd.pb = &uBuf.ab[f64Bit ? sizeof(mach_header_64_t) : sizeof(mach_header_32_t)];
while (cLeft-- > 0)
{
uint32_t const cbCmd = uLCmd.pGenric->cmdsize;
if (cbCmd > cbLeft || cbCmd < sizeof(load_command_t))
return VERR_BAD_EXE_FORMAT;
switch (uLCmd.pGenric->cmd)
{
case LC_SEGMENT_32:
if (cbCmd != sizeof(segment_command_32_t) + uLCmd.pSeg32->nsects * sizeof(section_32_t))
return VERR_BAD_EXE_FORMAT;
if (!dbgDiggerDarwinIsValidSegOrSectName(uLCmd.pSeg32->segname, sizeof(uLCmd.pSeg32->segname)))
return VERR_INVALID_NAME;
if (!strcmp(uLCmd.pSeg32->segname, "__LINKEDIT"))
break; /* This usually is discarded or not loaded at all. */
if (cSegs >= RT_ELEMENTS(aSegs))
return VERR_BUFFER_OVERFLOW;
aSegs[cSegs].Address = uLCmd.pSeg32->vmaddr;
aSegs[cSegs].uRva = uLCmd.pSeg32->vmaddr - uModAddr;
aSegs[cSegs].cb = uLCmd.pSeg32->vmsize;
aSegs[cSegs].fFlags = uLCmd.pSeg32->flags; /* Abusing the flags field here... */
aSegs[cSegs].iSeg = cSegs;
AssertCompile(RTDBG_SEGMENT_NAME_LENGTH > sizeof(uLCmd.pSeg32->segname));
strcpy(aSegs[cSegs].szName, uLCmd.pSeg32->segname);
cSegs++;
break;
case LC_SEGMENT_64:
if (cbCmd != sizeof(segment_command_64_t) + uLCmd.pSeg64->nsects * sizeof(section_64_t))
return VERR_BAD_EXE_FORMAT;
if (!dbgDiggerDarwinIsValidSegOrSectName(uLCmd.pSeg64->segname, sizeof(uLCmd.pSeg64->segname)))
return VERR_INVALID_NAME;
if (!strcmp(uLCmd.pSeg64->segname, "__LINKEDIT"))
break; /* This usually is discarded or not loaded at all. */
if (cSegs >= RT_ELEMENTS(aSegs))
return VERR_BUFFER_OVERFLOW;
aSegs[cSegs].Address = uLCmd.pSeg64->vmaddr;
aSegs[cSegs].uRva = uLCmd.pSeg64->vmaddr - uModAddr;
aSegs[cSegs].cb = uLCmd.pSeg64->vmsize;
aSegs[cSegs].fFlags = uLCmd.pSeg64->flags; /* Abusing the flags field here... */
aSegs[cSegs].iSeg = cSegs;
AssertCompile(RTDBG_SEGMENT_NAME_LENGTH > sizeof(uLCmd.pSeg64->segname));
strcpy(aSegs[cSegs].szName, uLCmd.pSeg64->segname);
cSegs++;
break;
case LC_UUID:
if (cbCmd != sizeof(uuid_command_t))
return VERR_BAD_EXE_FORMAT;
if (RTUuidIsNull((PCRTUUID)&uLCmd.pUuid->uuid[0]))
return VERR_BAD_EXE_FORMAT;
memcpy(&Uuid, &uLCmd.pUuid->uuid[0], sizeof(uLCmd.pUuid->uuid));
break;
default:
/* Current known max plus a lot of slack. */
if (uLCmd.pGenric->cmd > LC_DYLIB_CODE_SIGN_DRS + 32)
return VERR_BAD_EXE_FORMAT;
break;
}
/* next */
cbLeft -= cbCmd;
uLCmd.pb += cbCmd;
}
if (cbLeft != 0)
return VERR_BAD_EXE_FORMAT;
/*
* Some post processing checks.
*/
uint32_t iSeg;
for (iSeg = 0; iSeg < cSegs; iSeg++)
if (aSegs[iSeg].Address == uModAddr)
break;
if (iSeg >= cSegs)
return VERR_ADDRESS_CONFLICT;
/*
* Create a debug module.
*/
RTDBGMOD hMod;
rc = RTDbgModCreateFromMachOImage(&hMod, pszName, NULL, f64Bit ? RTLDRARCH_AMD64 : RTLDRARCH_X86_32, 0 /*cbImage*/,
cSegs, aSegs, &Uuid, DBGFR3AsGetConfig(pUVM), RTDBGMOD_F_NOT_DEFERRED);
if (RT_FAILURE(rc))
{
/*
* Final fallback is a container module.
*/
rc = RTDbgModCreate(&hMod, pszName, 0, 0);
if (RT_FAILURE(rc))
return rc;
uint64_t uRvaNext = 0;
for (iSeg = 0; iSeg < cSegs && RT_SUCCESS(rc); iSeg++)
{
if ( aSegs[iSeg].uRva > uRvaNext
&& aSegs[iSeg].uRva - uRvaNext < _1M)
uRvaNext = aSegs[iSeg].uRva;
rc = RTDbgModSegmentAdd(hMod, aSegs[iSeg].uRva, aSegs[iSeg].cb, aSegs[iSeg].szName, 0, NULL);
if (aSegs[iSeg].cb > 0 && RT_SUCCESS(rc))
{
char szTmp[RTDBG_SEGMENT_NAME_LENGTH + sizeof("_start")];
strcat(strcpy(szTmp, aSegs[iSeg].szName), "_start");
rc = RTDbgModSymbolAdd(hMod, szTmp, iSeg, 0 /*uRva*/, 0 /*cb*/, 0 /*fFlags*/, NULL);
}
uRvaNext += aSegs[iSeg].cb;
}
if (RT_FAILURE(rc))
{
RTDbgModRelease(hMod);
return rc;
}
}
/* Tag the module. */
rc = RTDbgModSetTag(hMod, DIG_DARWIN_MOD_TAG);
AssertRC(rc);
/*
* Link the module.
*/
RTDBGAS hAs = DBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
if (hAs != NIL_RTDBGAS)
{
//uint64_t uRvaNext = 0; - what was this?
uint32_t cLinked = 0;
iSeg = cSegs;
while (iSeg-- > 0) /* HACK: Map in reverse order to avoid replacing __TEXT. */
if (aSegs[iSeg].cb)
{
/* Find matching segment in the debug module. */
uint32_t iDbgSeg = 0;
while (iDbgSeg < cSegs)
{
RTDBGSEGMENT SegInfo;
int rc3 = RTDbgModSegmentByIndex(hMod, iDbgSeg, &SegInfo);
if (RT_SUCCESS(rc3) && !strcmp(SegInfo.szName, aSegs[iSeg].szName))
break;
iDbgSeg++;
}
AssertMsgStmt(iDbgSeg < cSegs, ("%s\n", aSegs[iSeg].szName), continue);
/* Map it. */
int rc2 = RTDbgAsModuleLinkSeg(hAs, hMod, iDbgSeg, aSegs[iSeg].Address, RTDBGASLINK_FLAGS_REPLACE /*fFlags*/);
if (RT_SUCCESS(rc2))
cLinked++;
else if (RT_SUCCESS(rc))
rc = rc2;
}
if (RT_FAILURE(rc) && cLinked != 0)
rc = -rc;
}
else
rc = VERR_INTERNAL_ERROR;
RTDbgModRelease(hMod);
RTDbgAsRelease(hAs);
if (pf64Bit)
*pf64Bit = f64Bit;
return rc;
}
static bool dbgDiggerDarwinIsValidName(const char *pszName)
{
char ch;
while ((ch = *pszName++) != '\0')
{
if (ch < 0x20 || ch >= 127)
return false;
}
return true;
}
static bool dbgDiggerDarwinIsValidVersion(const char *pszVersion)
{
char ch;
while ((ch = *pszVersion++) != '\0')
{
if (ch < 0x20 || ch >= 127)
return false;
}
return true;
}
/**
* @copydoc DBGFOSREG::pfnInit
*/
static DECLCALLBACK(int) dbgDiggerDarwinInit(PUVM pUVM, void *pvData)
{
PDBGDIGGERDARWIN pThis = (PDBGDIGGERDARWIN)pvData;
Assert(!pThis->fValid);
/*
* Add the kernel module.
*/
bool f64Bit;
int rc = dbgDiggerDarwinAddModule(pThis, pUVM, pThis->AddrKernel.FlatPtr, "mach_kernel", &f64Bit);
if (RT_SUCCESS(rc))
{
/*
* The list of modules can be found at the 'kmod' symbol, that means
* that we currently require some kind of symbol file for the kernel
* to be loaded at this point.
*
* Note! Could also use the 'gLoadedKextSummaries', but I don't think
* it's any easier to find without any kernel map than 'kmod'.
*/
RTDBGSYMBOL SymInfo;
rc = DBGFR3AsSymbolByName(pUVM, DBGF_AS_KERNEL, "mach_kernel!kmod", &SymInfo, NULL);
if (RT_FAILURE(rc))
rc = DBGFR3AsSymbolByName(pUVM, DBGF_AS_KERNEL, "mach_kernel!_kmod", &SymInfo, NULL);
if (RT_SUCCESS(rc))
{
DBGFADDRESS AddrModInfo;
DBGFR3AddrFromFlat(pUVM, &AddrModInfo, SymInfo.Value);
/* Read the variable. */
RTUINT64U uKmodValue = { 0 };
if (f64Bit)
rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &AddrModInfo, &uKmodValue.u, sizeof(uKmodValue.u));
else
rc = DBGFR3MemRead (pUVM, 0 /*idCpu*/, &AddrModInfo, &uKmodValue.s.Lo, sizeof(uKmodValue.s.Lo));
if (RT_SUCCESS(rc))
{
DBGFR3AddrFromFlat(pUVM, &AddrModInfo, uKmodValue.u);
/* Walk the list of modules. */
uint32_t cIterations = 0;
while (AddrModInfo.FlatPtr != 0)
{
/* Some extra loop conditions... */
if (!OSX_VALID_ADDRESS(f64Bit, AddrModInfo.FlatPtr))
{
Log(("OSXDig: Invalid kmod_info pointer: %RGv\n", AddrModInfo.FlatPtr));
break;
}
if (AddrModInfo.FlatPtr == uKmodValue.u && cIterations != 0)
{
Log(("OSXDig: kmod_info list looped back to the start.\n"));
break;
}
if (cIterations++ >= 2048)
{
Log(("OSXDig: Too many mod_info loops (%u)\n", cIterations));
break;
}
/*
* Read the kmod_info_t structure.
*/
union
{
OSX64_kmod_info_t Info64;
OSX32_kmod_info_t Info32;
} uMod;
RT_ZERO(uMod);
rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &AddrModInfo, &uMod,
f64Bit ? sizeof(uMod.Info64) : sizeof(uMod.Info32));
if (RT_FAILURE(rc))
{
Log(("OSXDig: Error reading kmod_info structure at %RGv: %Rrc\n", AddrModInfo.FlatPtr, rc));
break;
}
/*
* Validate the kmod_info_t structure.
*/
int32_t iInfoVer = f64Bit ? uMod.Info64.info_version : uMod.Info32.info_version;
if (iInfoVer != OSX_KMOD_INFO_VERSION)
{
Log(("OSXDig: kmod_info @%RGv: Bad info_version %d\n", AddrModInfo.FlatPtr, iInfoVer));
break;
}
const char *pszName = f64Bit ? uMod.Info64.name : uMod.Info32.name;
if ( !*pszName
|| !RTStrEnd(pszName, sizeof(uMod.Info64.name))
|| !dbgDiggerDarwinIsValidName(pszName) )
{
Log(("OSXDig: kmod_info @%RGv: Bad name '%.*s'\n", AddrModInfo.FlatPtr,
sizeof(uMod.Info64.name), pszName));
break;
}
const char *pszVersion = f64Bit ? uMod.Info64.version : uMod.Info32.version;
if ( !RTStrEnd(pszVersion, sizeof(uMod.Info64.version))
|| !dbgDiggerDarwinIsValidVersion(pszVersion) )
{
Log(("OSXDig: kmod_info @%RGv: Bad version '%.*s'\n", AddrModInfo.FlatPtr,
sizeof(uMod.Info64.version), pszVersion));
break;
}
int32_t cRefs = f64Bit ? uMod.Info64.reference_count : uMod.Info32.reference_count;
if (cRefs < -1 || cRefs > 16384)
{
Log(("OSXDig: kmod_info @%RGv: Bad reference_count %d\n", AddrModInfo.FlatPtr, cRefs));
break;
}
uint64_t uImageAddr = f64Bit ? uMod.Info64.address : uMod.Info32.address;
if (!OSX_VALID_ADDRESS(f64Bit, uImageAddr))
{
Log(("OSXDig: kmod_info @%RGv: Bad address %#llx\n", AddrModInfo.FlatPtr, uImageAddr));
break;
}
uint64_t cbImage = f64Bit ? uMod.Info64.size : uMod.Info32.size;
if (cbImage > 64U*_1M)
{
Log(("OSXDig: kmod_info @%RGv: Bad size %#llx\n", AddrModInfo.FlatPtr, cbImage));
break;
}
uint64_t cbHdr = f64Bit ? uMod.Info64.hdr_size : uMod.Info32.hdr_size;
if (cbHdr > 16U*_1M)
{
Log(("OSXDig: kmod_info @%RGv: Bad hdr_size %#llx\n", AddrModInfo.FlatPtr, cbHdr));
break;
}
uint64_t uStartAddr = f64Bit ? uMod.Info64.start : uMod.Info32.start;
if (!uStartAddr && !OSX_VALID_ADDRESS(f64Bit, uStartAddr))
{
Log(("OSXDig: kmod_info @%RGv: Bad start function %#llx\n", AddrModInfo.FlatPtr, uStartAddr));
break;
}
uint64_t uStopAddr = f64Bit ? uMod.Info64.stop : uMod.Info32.stop;
if (!uStopAddr && !OSX_VALID_ADDRESS(f64Bit, uStopAddr))
{
Log(("OSXDig: kmod_info @%RGv: Bad stop function %#llx\n", AddrModInfo.FlatPtr, uStopAddr));
break;
}
/*
* Try add the module.
*/
Log(("OSXDig: kmod_info @%RGv: '%s' ver '%s', image @%#llx LB %#llx cbHdr=%#llx\n", AddrModInfo.FlatPtr,
pszName, pszVersion, uImageAddr, cbImage, cbHdr));
rc = dbgDiggerDarwinAddModule(pThis, pUVM, uImageAddr, pszName, NULL);
/*
* Advance to the next kmod_info entry.
*/
DBGFR3AddrFromFlat(pUVM, &AddrModInfo, f64Bit ? uMod.Info64.next : uMod.Info32.next);
}
}
else
Log(("OSXDig: Error reading the 'kmod' variable: %Rrc\n", rc));
}
else
Log(("OSXDig: Failed to locate the 'kmod' variable in mach_kernel.\n"));
pThis->fValid = true;
return VINF_SUCCESS;
}
return rc;
}
/**
* @copydoc DBGFOSREG::pfnProbe
*/
static DECLCALLBACK(bool) dbgDiggerDarwinProbe(PUVM pUVM, void *pvData)
{
PDBGDIGGERDARWIN pThis = (PDBGDIGGERDARWIN)pvData;
/*
* Look for a section + segment combo that normally only occures in
* mach_kernel. Follow it up with probing of the rest of the executable
* header. We must search a largish area because the more recent versions
* of darwin have random load address for security raisins.
*/
static struct { uint64_t uStart, uEnd; } const s_aRanges[] =
{
/* 64-bit: */
{ UINT64_C(0xffffff8000000000), UINT64_C(0xffffff81ffffffff), },
/* 32-bit - always search for this because of the hybrid 32-bit kernel
with cpu in long mode that darwin used for a number of versions. */
{ UINT64_C(0x00001000), UINT64_C(0x0ffff000), }
};
for (unsigned iRange = DBGFR3CpuGetMode(pUVM, 0 /*idCpu*/) != CPUMMODE_LONG;
iRange < RT_ELEMENTS(s_aRanges);
iRange++)
{
DBGFADDRESS KernelAddr;
for (DBGFR3AddrFromFlat(pUVM, &KernelAddr, s_aRanges[iRange].uStart);
KernelAddr.FlatPtr < s_aRanges[iRange].uEnd;
KernelAddr.FlatPtr += X86_PAGE_4K_SIZE)
{
static const uint8_t s_abNeedle[16 + 16] =
{
'_','_','t','e','x','t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* section_32_t::sectname */
'_','_','K','L','D', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* section_32_t::segname. */
};
int rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &KernelAddr, s_aRanges[iRange].uEnd - KernelAddr.FlatPtr,
1, s_abNeedle, sizeof(s_abNeedle), &KernelAddr);
if (RT_FAILURE(rc))
break;
DBGFR3AddrSub(&KernelAddr, KernelAddr.FlatPtr & X86_PAGE_4K_OFFSET_MASK);
/*
* Read the first page of the image and check the headers.
*/
union
{
uint8_t ab[X86_PAGE_4K_SIZE];
mach_header_64_t Hdr64;
mach_header_32_t Hdr32;
} uBuf;
rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &KernelAddr, uBuf.ab, X86_PAGE_4K_SIZE);
if (RT_FAILURE(rc))
continue;
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, magic, mach_header_32_t, magic);
if ( uBuf.Hdr64.magic != IMAGE_MACHO64_SIGNATURE
&& uBuf.Hdr32.magic != IMAGE_MACHO32_SIGNATURE)
continue;
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, cputype, mach_header_32_t, cputype);
bool f64Bit = uBuf.Hdr64.magic == IMAGE_MACHO64_SIGNATURE;
if (uBuf.Hdr32.cputype != (f64Bit ? CPU_TYPE_X86_64 : CPU_TYPE_I386))
continue;
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, filetype, mach_header_32_t, filetype);
if (uBuf.Hdr32.filetype != MH_EXECUTE)
continue;
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, ncmds, mach_header_32_t, ncmds);
if (uBuf.Hdr32.ncmds > 256)
continue;
AssertCompileMembersSameSizeAndOffset(mach_header_64_t, sizeofcmds, mach_header_32_t, sizeofcmds);
if (uBuf.Hdr32.sizeofcmds > X86_PAGE_4K_SIZE * 2 - sizeof(mach_header_64_t))
continue;
/* Seems good enough for now.
If the above causes false positives, check the segments and make
sure there is a kernel version string in the right one. */
pThis->AddrKernel = KernelAddr;
pThis->f64Bit = f64Bit;
/*
* Finally, find the kernel version string.
*/
rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &KernelAddr, 32*_1M, 1, RT_STR_TUPLE("Darwin Kernel Version"),
&pThis->AddrKernelVersion);
if (RT_FAILURE(rc))
DBGFR3AddrFromFlat(pUVM, &pThis->AddrKernelVersion, 0);
return true;
}
}
return false;
}
/**
* @copydoc DBGFOSREG::pfnDestruct
*/
static DECLCALLBACK(void) dbgDiggerDarwinDestruct(PUVM pUVM, void *pvData)
{
RT_NOREF2(pUVM, pvData);
}
/**
* @copydoc DBGFOSREG::pfnConstruct
*/
static DECLCALLBACK(int) dbgDiggerDarwinConstruct(PUVM pUVM, void *pvData)
{
RT_NOREF1(pUVM);
PDBGDIGGERDARWIN pThis = (PDBGDIGGERDARWIN)pvData;
pThis->IDmesg.u32Magic = DBGFOSIDMESG_MAGIC;
pThis->IDmesg.pfnQueryKernelLog = dbgDiggerDarwinIDmsg_QueryKernelLog;
pThis->IDmesg.u32EndMagic = DBGFOSIDMESG_MAGIC;
return VINF_SUCCESS;
}
const DBGFOSREG g_DBGDiggerDarwin =
{
/* .u32Magic = */ DBGFOSREG_MAGIC,
/* .fFlags = */ 0,
/* .cbData = */ sizeof(DBGDIGGERDARWIN),
/* .szName = */ "Darwin",
/* .pfnConstruct = */ dbgDiggerDarwinConstruct,
/* .pfnDestruct = */ dbgDiggerDarwinDestruct,
/* .pfnProbe = */ dbgDiggerDarwinProbe,
/* .pfnInit = */ dbgDiggerDarwinInit,
/* .pfnRefresh = */ dbgDiggerDarwinRefresh,
/* .pfnTerm = */ dbgDiggerDarwinTerm,
/* .pfnQueryVersion = */ dbgDiggerDarwinQueryVersion,
/* .pfnQueryInterface = */ dbgDiggerDarwinQueryInterface,
/* .u32EndMagic = */ DBGFOSREG_MAGIC
};
| 20,128 |
1,106 | /* measure the throughput of encoding and decoding 3D blocks of doubles */
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "zfp.h"
/* example 3D block of (reinterpreted) doubles */
static const uint64 block[] = {
0xbf7c3a7bb8495ca9ull,
0xbf79f9d9058ffdafull,
0xbf77c7abd0b61999ull,
0xbf75a42c806bd1daull,
0xbf738f8f740b8ea8ull,
0xbf718a050399fef8ull,
0xbf6f2772ff8c30feull,
0xbf6b59aa63d22f68ull,
0xbf67aaf8b80cff9eull,
0xbf641b9e71983592ull,
0xbf60abd3f723f2b7ull,
0xbf5ab7934169cc04ull,
0xbf54574f6f4897d3ull,
0xbf4c6e39da7fb99bull,
0xbf40ae5826a893d1ull,
0xbf25bce8e19d48e1ull,
0x3f253bfed65904d7ull,
0x3f3f18ab46a04cf3ull,
0x3f4948e7cb74278bull,
0x3f51427b51aeec2eull,
0x3f55a0716d8b4b6bull,
0x3f59be96aeaac56full,
0x3f5d9d3ba7bfd327ull,
0x3f609e608469e93eull,
0x3f624ecbcfa3832cull,
0x3f63e0202ae84b4dull,
0x3f6552a61a3f4812ull,
0x3f66a6ae305af268ull,
0x3f67dc910e9935bcull,
0x3f68f4af65036ff7ull,
0x3f69ef71f24e7182ull,
0x3f6acd4983da7d43ull,
0x3f6b8eaef5b348a0ull,
0x3f6c3423328ffb7aull,
0x3f6cbe2f33d33034ull,
0x3f6d2d64018af3acull,
0x3f6d825ab270c540ull,
0x3f6dbdb46be996ccull,
0x3f6de01a6205cca9ull,
0x3f6dea3dd7813dafull,
0x3f6ddcd81dc33335ull,
0x3f6db8aa94de690full,
0x3f6d7e7eab910d8full,
0x3f6d2f25df44c187ull,
0x3f6ccb79bc0e9844ull,
0x3f6c545bdcaf1795ull,
0x3f6bcab5ea9237c4ull,
0x3f6b2f799dcf639bull,
0x3f6a83a0bd297862ull,
0x3f69c82d1e0ec5deull,
0x3f68fe28a4990e53ull,
0x3f6826a5438d8685ull,
0x3f6742bcfc5cd5b2ull,
0x3f665391df231599ull,
0x3f655a4e0aa7d278ull,
0x3f645823ac5e0b09ull,
0x3f634e4d00643085ull,
0x3f623e0c518426a3ull,
0x3f6128abf933439aull,
0x3f600f7e5f92501cull,
0x3f5de7bbf6db0eb7ull,
0x3f5bae5aa4792e11ull,
0x3f5975adf0453ea2ull,
0x3f57409b1fdc65c4ull,
};
int main(int argc, char* argv[])
{
size_t n = 0x200000;
double rate = 1;
zfp_field* field;
uint insize;
zfp_stream* zfp;
bitstream* stream;
void* buffer;
size_t bytes;
clock_t c;
double time;
uint i;
switch (argc) {
case 3:
sscanf(argv[2], "%zu", &n);
/* FALLTHROUGH */
case 2:
sscanf(argv[1], "%lf", &rate);
break;
}
/* declare array to compress */
field = zfp_field_3d(NULL, zfp_type_double, 4, 4, 4 * n);
insize = n * sizeof(block);
/* allocate storage for compressed bit stream */
zfp = zfp_stream_open(NULL);
zfp_stream_set_rate(zfp, rate, zfp_field_type(field), zfp_field_dimensionality(field), 0);
bytes = zfp_stream_maximum_size(zfp, field);
buffer = malloc(bytes);
stream = stream_open(buffer, bytes);
zfp_stream_set_bit_stream(zfp, stream);
zfp_field_free(field);
/* compress */
c = clock();
for (i = 0; i < n; i++)
zfp_encode_block_double_3(zfp, (const double*)block);
zfp_stream_flush(zfp);
time = (double)(clock() - c) / CLOCKS_PER_SEC;
printf("encode in=%u out=%u %.0f MB/s\n", insize, (uint)stream_size(stream), insize / (1024 * 1024 * time));
/* decompress */
zfp_stream_rewind(zfp);
c = clock();
for (i = 0; i < n; i++) {
double a[64];
zfp_decode_block_double_3(zfp, a);
}
time = (double)(clock() - c) / CLOCKS_PER_SEC;
printf("decode in=%u out=%u %.0f MB/s\n", (uint)stream_size(stream), insize, insize / (1024 * 1024 * time));
zfp_stream_close(zfp);
stream_close(stream);
free(buffer);
return 0;
}
| 1,732 |
12,940 | <filename>quickstarts/microsoft.compute/vm-sql-existing-keyvault-update/azuredeploy.json
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"existingVirtualMachineName": {
"type": "string",
"metadata": {
"description": "Existing SQL Server virtual machine name"
}
},
"sqlCredentialName": {
"type": "string",
"metadata": {
"description": "SQL credential name to create on the SQL Server virtual machine"
}
},
"servicePrincipalName": {
"type": "string",
"metadata": {
"description": "Azure Key Vault principal name or id"
}
},
"servicePrincipalSecret": {
"type": "securestring",
"metadata": {
"description": "Azure Key Vault principal secret"
}
},
"sqlAkvName": {
"type": "string",
"metadata": {
"description": "Azure Key Vault Name"
}
},
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Location for all resources."
}
}
},
"variables": {
"sqlAkvUrl": "[concat('https://', parameters('sqlAkvName'), environment().suffixes.keyVaultDns)]"
},
"resources": [
{
"apiVersion": "2020-12-01",
"type": "Microsoft.Compute/virtualMachines/extensions",
"name": "[concat(parameters('existingVirtualMachineName'), '/SqlIaasExtension')]",
"location": "[parameters('location')]",
"properties": {
"type": "SqlIaaSAgent",
"publisher": "Microsoft.SqlServer.Management",
"typeHandlerVersion": "1.2",
"autoUpgradeMinorVersion": "true",
"settings": {
"KeyVaultCredentialSettings": {
"Enable": true,
"CredentialName": "[parameters('sqlCredentialName')]"
}
},
"protectedSettings": {
"PrivateKeyVaultCredentialSettings": {
"AzureKeyVaultUrl": "[variables('sqlAkvUrl')]",
"ServicePrincipalName": "[parameters('servicePrincipalName')]",
"ServicePrincipalSecret": "[parameters('servicePrincipalSecret')]"
}
}
}
}
]
}
| 996 |
461 | /*******************************************************************************
* 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.ofbiz.service.engine;
import clojure.java.api.Clojure;
import clojure.lang.IFn;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.ModelService;
import org.apache.ofbiz.service.ServiceDispatcher;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* Clojure service engine. Enables OFBiz services written in Clojure.
*/
public class StandardClojureEngine extends GenericAsyncEngine {
private static final String MODULE = StandardClojureEngine.class.getName();
public StandardClojureEngine(ServiceDispatcher dispatcher) {
super(dispatcher);
Debug.logInfo("Created Clojure engine.", MODULE);
}
/**
* Load Clojure ns and call service function.
* <p>
* See https://clojure.github.io/clojure/javadoc/clojure/java/api/Clojure.html
*
* @param ns Clojure namespace to load
* @param fn Clojure function to call
* @param dctx OFBiz dispatch context
* @param context OFBiz context - input parameters
* @return
* @throws Exception
*/
public static Object callClojure(String ns, String fn, DispatchContext dctx, Map<String, Object> context) throws Exception {
Debug.logInfo("Call %s/%s ", MODULE, ns, fn);
IFn require = Clojure.var("clojure.core", "require");
require.invoke(Clojure.read(ns));
return Clojure.var(ns, fn).invoke(dctx, context);
}
@Override
public void runSyncIgnore(String localName, ModelService modelService,
Map<String, Object> context) throws GenericServiceException {
runSync(localName, modelService, context);
}
@Override
public Map<String, Object> runSync(String localName, ModelService modelService,
Map<String, Object> context) throws GenericServiceException {
Object result = serviceInvoker(localName, modelService, context);
if (result == null || !(result instanceof Map<?, ?>)) {
throw new GenericServiceException(
"Service [" + modelService.getName() + "] did not return a Map object");
}
return UtilGenerics.cast(result);
}
private Object serviceInvoker(String localName, ModelService modelService,
Map<String, Object> context) throws GenericServiceException {
DispatchContext dctx = getDispatcher().getLocalContext(localName);
if (modelService == null) {
Debug.logError("ERROR: Null Model Service.", MODULE);
}
if (dctx == null) {
Debug.logError("ERROR: Null DispatchContext.", MODULE);
}
if (context == null) {
Debug.logError("ERROR: Null Service Context.", MODULE);
}
Object result = null;
// check the namespace and function names
if (modelService.getLocation() == null || modelService.getInvoke() == null) {
throw new GenericServiceException("Service [" + modelService.getName()
+ "] is missing location and/or invoke values which are required for execution.");
}
try {
String ns = this.getLocation(modelService);
String fn = modelService.getInvoke();
result = callClojure(ns, fn, dctx, context);
} catch (ClassNotFoundException cnfe) {
throw new GenericServiceException(
"Cannot find service [" + modelService.getName() + "] location class", cnfe);
} catch (NoSuchMethodException nsme) {
throw new GenericServiceException("Service [" + modelService.getName()
+ "] specified Java method (invoke attribute) does not exist",
nsme);
} catch (SecurityException se) {
throw new GenericServiceException("Service [" + modelService.getName() + "] Access denied",
se);
} catch (IllegalAccessException iae) {
throw new GenericServiceException(
"Service [" + modelService.getName() + "] Method not accessible", iae);
} catch (IllegalArgumentException iarge) {
throw new GenericServiceException(
"Service [" + modelService.getName() + "] Invalid parameter match", iarge);
} catch (InvocationTargetException ite) {
throw new GenericServiceException(
"Service [" + modelService.getName() + "] target threw an unexpected exception",
ite.getTargetException());
} catch (NullPointerException npe) {
throw new GenericServiceException(
"Service [" + modelService.getName() + "] ran into an unexpected null object", npe);
} catch (ExceptionInInitializerError eie) {
throw new GenericServiceException(
"Service [" + modelService.getName() + "] Initialization failed", eie);
} catch (Throwable th) {
throw new GenericServiceException(
"Service [" + modelService.getName() + "] Error or unknown exception", th);
}
return result;
}
}
| 2,293 |
3,024 | <reponame>NathanHowell/sqlfluff<filename>src/sqlfluff/core/parser/segments/raw.py<gh_stars>1000+
"""Raw segment definitions.
This is designed to be the root segment, without
any children, and the output of the lexer.
"""
from typing import Optional, Tuple
from sqlfluff.core.parser.segments.base import BaseSegment
from sqlfluff.core.parser.markers import PositionMarker
class RawSegment(BaseSegment):
"""This is a segment without any subsegments."""
type = "raw"
_is_code = True
_is_comment = False
_is_whitespace = False
# Classes inheriting from RawSegment may provide a _default_raw
# to enable simple initialisation.
_default_raw = ""
def __init__(
self,
raw: Optional[str] = None,
pos_marker: Optional[PositionMarker] = None,
type: Optional[str] = None,
name: Optional[str] = None,
trim_start: Optional[Tuple[str, ...]] = None,
trim_chars: Optional[Tuple[str, ...]] = None,
):
"""Initialise raw segment.
If raw is not provided, we default to _default_raw if present.
If pos_marker is not provided, it is assume that this will be
inserted later as part of a reposition phase.
"""
if raw is not None: # NB, raw *can* be an empty string and be valid
self._raw = raw
else:
self._raw = self._default_raw
self._raw_upper = self._raw.upper()
# pos marker is required here. We ignore the typing initially
# because it might *initially* be unset, but it will be reset
# later.
self.pos_marker: PositionMarker = pos_marker # type: ignore
# if a surrogate type is provided, store it for later.
self._surrogate_type = type
self._surrogate_name = name
# What should we trim off the ends to get to content
self.trim_start = trim_start
self.trim_chars = trim_chars
# A cache variable for expandable
self._is_expandable = None
def __repr__(self):
return "<{}: ({}) {!r}>".format(
self.__class__.__name__, self.pos_marker, self.raw
)
# ################ PUBLIC PROPERTIES
@property
def matched_length(self):
"""Return the length of the segment in characters."""
return len(self._raw)
@property
def is_expandable(self):
"""Return true if it is meaningful to call `expand` on this segment."""
return False
@property
def is_code(self):
"""Return True if this segment is code."""
return self._is_code
@property
def is_comment(self):
"""Return True if this segment is a comment."""
return self._is_comment
@property
def is_whitespace(self):
"""Return True if this segment is whitespace."""
return self._is_whitespace
@property
def raw_upper(self):
"""Make an uppercase string from the segments of this segment."""
return self._raw_upper
@property
def segments(self):
"""Return an empty list of child segments.
This is in case something tries to iterate on this segment.
"""
return []
# ################ INSTANCE METHODS
def get_type(self):
"""Returns the type of this segment as a string."""
return self._surrogate_type or self.type
def is_type(self, *seg_type):
"""Extend the parent class method with the surrogate types."""
if self._surrogate_type and self._surrogate_type in seg_type:
return True
return self.class_is_type(*seg_type)
def iter_raw_seg(self):
"""Iterate raw segments, mostly for searching."""
yield self
def raw_trimmed(self):
"""Return a trimmed version of the raw content."""
raw_buff = self.raw
if self.trim_start:
for seq in self.trim_start:
if raw_buff.startswith(seq):
raw_buff = raw_buff[len(seq) :]
if self.trim_chars:
raw_buff = self.raw
# for each thing to trim
for seq in self.trim_chars:
# trim start
while raw_buff.startswith(seq):
raw_buff = raw_buff[len(seq) :]
# trim end
while raw_buff.endswith(seq):
raw_buff = raw_buff[: -len(seq)]
return raw_buff
return raw_buff
def raw_list(self): # pragma: no cover TODO?
"""Return a list of the raw content of this segment."""
return [self.raw]
def _reconstruct(self):
"""Return a string of the raw content of this segment."""
return self._raw
def stringify(self, ident=0, tabsize=4, code_only=False):
"""Use indentation to render this segment and its children as a string."""
preface = self._preface(ident=ident, tabsize=tabsize)
return preface + "\n"
def _suffix(self):
"""Return any extra output required at the end when logging.
NB Override this for specific subclasses if we want extra output.
"""
return f"{self.raw!r}"
def edit(self, raw):
"""Create a new segment, with exactly the same position but different content.
Returns:
A copy of this object with new contents.
Used mostly by fixes.
"""
return self.__class__(
raw=raw,
pos_marker=self.pos_marker,
type=self._surrogate_type,
name=self._surrogate_name,
trim_start=self.trim_start,
trim_chars=self.trim_chars,
)
class CodeSegment(RawSegment):
"""An alias for RawSegment.
This has a more explicit name for segment creation.
"""
pass
class UnlexableSegment(CodeSegment):
"""A placeholder to unlexable sections.
This otherwise behaves exaclty like a code section.
"""
type = "unlexable"
class CommentSegment(RawSegment):
"""Segment containing a comment."""
type = "comment"
_name = "comment"
_is_code = False
_is_comment = True
class WhitespaceSegment(RawSegment):
"""Segment containing whitespace."""
type = "whitespace"
_name = "whitespace"
_is_whitespace = True
_is_code = False
_is_comment = False
_default_raw = " "
class NewlineSegment(RawSegment):
"""Segment containing a newline.
NOTE: NewlineSegment does not inherit from WhitespaceSegment.
Therefore NewlineSegment.is_type('whitespace') returns False.
This is intentional and convenient for rules. If users want
to match on both, call .is_type('whitespace', 'newline')
"""
type = "newline"
_name = "newline"
_is_whitespace = True
_is_code = False
_is_comment = False
_default_raw = "\n"
class KeywordSegment(CodeSegment):
"""A segment used for matching single words.
We rename the segment class here so that descendants of
_ProtoKeywordSegment can use the same functionality
but don't end up being labelled as a `keyword` later.
"""
type = "keyword"
def __init__(
self,
raw: Optional[str] = None,
pos_marker: Optional[PositionMarker] = None,
type: Optional[str] = None,
name: Optional[str] = None,
):
"""If no other name is provided we extrapolate it from the raw."""
if raw and not name:
# names are all lowercase by convention.
name = raw.lower()
super().__init__(raw=raw, pos_marker=pos_marker, type=type, name=name)
def edit(self, raw):
"""Create a new segment, with exactly the same position but different content.
Returns:
A copy of this object with new contents.
Used mostly by fixes.
"""
return self.__class__(
raw=raw,
pos_marker=self.pos_marker,
type=self._surrogate_type,
name=self._surrogate_name,
)
class SymbolSegment(CodeSegment):
"""A segment used for matching single entities which aren't keywords.
We rename the segment class here so that descendants of
_ProtoKeywordSegment can use the same functionality
but don't end up being labelled as a `keyword` later.
"""
type = "symbol"
| 3,413 |
1,056 | package test;
public class Test {
public void op() {
}
}
| 26 |
852 | <gh_stars>100-1000
import FWCore.ParameterSet.Config as cms
def custom_geometry_decentralized_V11(process, links='signaldriven',implementation=1):
if links=='signaldriven':
links_mapping = 'L1Trigger/L1THGCal/data/links_mapping_V11_decentralized_signaldriven_0.txt'
elif links=='pudriven':
links_mapping = 'L1Trigger/L1THGCal/data/links_mapping_V11_decentralized_march20_0.txt'
else:
raise RuntimeError('Unknown links mapping "{}". Options are "signaldriven" or "pudriven".'.format(links))
if implementation==1:
process.hgcalTriggerGeometryESProducer.TriggerGeometry.TriggerGeometryName = cms.string('HGCalTriggerGeometryV9Imp2')
elif implementation==2:
process.hgcalTriggerGeometryESProducer.TriggerGeometry.TriggerGeometryName = cms.string('HGCalTriggerGeometryV9Imp3')
process.hgcalTriggerGeometryESProducer.TriggerGeometry.ScintillatorTriggerCellSize = cms.uint32(2)
process.hgcalTriggerGeometryESProducer.TriggerGeometry.ScintillatorModuleSize = cms.uint32(6)
process.hgcalTriggerGeometryESProducer.TriggerGeometry.L1TModulesMapping = cms.FileInPath("L1Trigger/L1THGCal/data/panel_mapping_V11_decentralized_march20_2.txt")
process.hgcalTriggerGeometryESProducer.TriggerGeometry.L1TLinksMapping = cms.FileInPath(links_mapping)
process.hgcalTriggerGeometryESProducer.TriggerGeometry.DisconnectedModules = cms.vuint32(0)
process.hgcalTriggerGeometryESProducer.TriggerGeometry.ScintillatorLinksPerModule = cms.uint32(2)
process.hgcalTriggerGeometryESProducer.TriggerGeometry.JsonMappingFile = cms.FileInPath("L1Trigger/L1THGCal/data/hgcal_trigger_link_mapping_v1.json")
return process
def custom_geometry_decentralized_V10(process, links='signaldriven'):
if links=='signaldriven':
links_mapping = 'L1Trigger/L1THGCal/data/links_mapping_decentralized_signaldriven_0.txt'
elif links=='pudriven':
links_mapping = 'L1Trigger/L1THGCal/data/links_mapping_decentralized_jun19_0.txt'
else:
raise RuntimeError('Unknown links mapping "{}". Options are "signaldriven" or "pudriven".'.format(links))
process.hgcalTriggerGeometryESProducer.TriggerGeometry.TriggerGeometryName = cms.string('HGCalTriggerGeometryV9Imp2')
process.hgcalTriggerGeometryESProducer.TriggerGeometry.ScintillatorTriggerCellSize = cms.uint32(2)
process.hgcalTriggerGeometryESProducer.TriggerGeometry.ScintillatorModuleSize = cms.uint32(6)
process.hgcalTriggerGeometryESProducer.TriggerGeometry.L1TModulesMapping = cms.FileInPath("L1Trigger/L1THGCal/data/panel_mapping_V9_decentralized_jun19_0.txt")
process.hgcalTriggerGeometryESProducer.TriggerGeometry.L1TLinksMapping = cms.FileInPath(links_mapping)
process.hgcalTriggerGeometryESProducer.TriggerGeometry.DisconnectedModules = cms.vuint32(0)
process.hgcalTriggerGeometryESProducer.TriggerGeometry.ScintillatorLinksPerModule = cms.uint32(2)
return process
| 1,120 |
2,813 | <reponame>fernandes-natanael/jabref
package org.jabref.gui.integrity;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.AbstractViewModel;
import org.jabref.logic.integrity.IntegrityMessage;
public class IntegrityCheckDialogViewModel extends AbstractViewModel {
private final ObservableList<IntegrityMessage> messages;
public IntegrityCheckDialogViewModel(List<IntegrityMessage> messages) {
this.messages = FXCollections.observableArrayList(messages);
}
public ObservableList<IntegrityMessage> getMessages() {
return messages;
}
}
| 215 |
348 | <filename>docs/data/t2/065/65105.json<gh_stars>100-1000
{"nom":"Bourg-de-Bigorre","dpt":"Hautes-Pyrénées","inscrits":158,"abs":39,"votants":119,"blancs":15,"nuls":5,"exp":99,"res":[{"panneau":"1","voix":79},{"panneau":"2","voix":20}]} | 105 |
6,717 | <reponame>crossmob/WinObjC<filename>include/UIKit/UITableViewDataSource.h
//******************************************************************************
//
// Copyright (c) 2016 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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.
//
//******************************************************************************
#pragma once
#import <UIKit/UIKitExport.h>
#import <UIKit/UITableViewCell.h>
@class UITableView;
@class NSIndexPath;
@class NSArray;
@class NSString;
@protocol UITableViewDataSource <NSObject>
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath;
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section;
@optional
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView;
- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView;
- (NSInteger)tableView:(UITableView*)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index;
- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section;
- (NSString*)tableView:(UITableView*)tableView titleForFooterInSection:(NSInteger)section;
- (void)tableView:(UITableView*)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath*)indexPath;
- (BOOL)tableView:(UITableView*)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath;
- (BOOL)tableView:(UITableView*)tableView canMoveRowAtIndexPath:(NSIndexPath*)indexPath;
- (void)tableView:(UITableView*)tableView moveRowAtIndexPath:(NSIndexPath*)fromIndexPath toIndexPath:(NSIndexPath*)toIndexPath;
@end
| 652 |
687 | <reponame>mbattista/stream-m<gh_stars>100-1000
/*
* Copyright 2018 <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.
*/
package org.czentral.data.binary.serializer;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.czentral.data.binary.AnnotationMapSerializationContext;
import org.czentral.data.binary.BitBuffer;
import org.czentral.data.binary.SerializationContext;
import org.czentral.data.binary.annotation.BitField;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author <NAME> (<EMAIL>)
*/
public class ByteBufferSerializerTest {
SerializationContext context = null;
BitfieldImplementation bfi = null;
public ByteBufferSerializerTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
final int BUFFER_LENGTH = 6;
BitBuffer bb = new BitBuffer(new byte[BUFFER_LENGTH], 0, BUFFER_LENGTH * 8);
AnnotationMapSerializationContext sc = new AnnotationMapSerializationContext(bb, null, null);
bfi = new BitfieldImplementation();
sc.putAnnotation(BitField.class, bfi);
context = sc;
}
@After
public void tearDown() {
}
/**
* Test of serialize method, of class ByteBufferSerializer.
*/
@Test
public void testSerialize() {
System.out.println("serialize");
byte[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Object o = ByteBuffer.wrap(array, 1, 5);
ByteBufferSerializer instance = new ByteBufferSerializer();
instance.serialize(o, context);
byte[] expected = {1, 2, 3, 4, 5, 0};
assert(Arrays.equals(context.getBuffer().getBuffer(), expected));
}
}
| 1,008 |
987 | import pytest
from asyncio import Future
from unittest import mock
import tornado.testing
import tornado.web
from tornado.httpclient import HTTPResponse
from tornado.escape import json_decode
from mopidy_iris import handlers
from mopidy_iris import core
from mopidy_iris.mem import iris
def async_return_helper(result):
f = Future()
f.set_result(result)
return f
class HttpHandlerTest(tornado.testing.AsyncHTTPTestCase):
@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog):
self._caplog = caplog
def get_app(self):
http_handler = handlers.HttpHandler
# http_handler.handle_result = mock.Mock()
# self.handler_mock = http_handler.handle_result
return tornado.web.Application(
[
(
r"/(.*)",
http_handler,
{
"core": None,
"config": {},
},
)
]
)
def test_get_method(self):
with mock.patch("time.time", return_value=100):
response = self.fetch("/test", method="GET")
assert 200 == response.code
result = json_decode(response.body)
assert "2.0" == result["jsonrpc"]
assert "test" == result["method"]
assert 100 == result["id"]
assert "Running test... please wait" == result["result"]["message"]
def test_get_method_headers(self):
response = self.fetch("/test", method="GET")
assert response.headers["Access-Control-Allow-Origin"] == "*"
assert "Origin" in response.headers["Access-Control-Allow-Headers"]
def test_get_unknown_method_is_error(self):
response = self.fetch("/baz", method="GET")
assert 400 == response.code
error = json_decode(response.body)["error"]
assert "Method baz does not exist" == error["message"]
@mock.patch.object(handlers, "iris")
def test_get_method_called(self, iris_mock):
iris_mock.foo = mock.Mock()
response = self.fetch("/foo", method="GET")
iris_mock.foo.assert_called_once()
assert 200 == response.code
@mock.patch.object(handlers, "iris")
def test_get_method_any_exception_handled(self, iris_mock):
iris_mock.foo = mock.Mock(side_effect=Exception("bar"))
response = self.fetch("/foo", method="GET")
iris_mock.foo.assert_called_once()
assert 200 == response.code
assert "bar" in self._caplog.text
@mock.patch.object(handlers.iris, "do_fetch")
def test_get_method_with_fetch(self, fetch_mock):
iris.config = {"spotify": {"client_id": 123, "client_secret": 456}}
result = mock.Mock(spec=HTTPResponse, body='{"expires_in":88}')
fetch_mock.return_value = async_return_helper(result)
response = self.fetch("/refresh_spotify_token", method="GET")
assert 200 == response.code
assert len(response.body) > 0
result = json_decode(response.body)
assert "refresh_spotify_token" == result["method"]
assert 88 == result["result"]["spotify_token"]["expires_in"]
| 1,389 |
1,288 | <reponame>JPeMu/shaka-packager<gh_stars>1000+
// Copyright 2014 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 "packager/media/formats/webm/webm_cluster_parser.h"
#include <algorithm>
#include <vector>
#include "packager/base/logging.h"
#include "packager/base/sys_byteorder.h"
#include "packager/media/base/decrypt_config.h"
#include "packager/media/base/timestamp.h"
#include "packager/media/codecs/vp8_parser.h"
#include "packager/media/codecs/vp9_parser.h"
#include "packager/media/codecs/webvtt_util.h"
#include "packager/media/formats/webm/webm_constants.h"
#include "packager/media/formats/webm/webm_crypto_helpers.h"
#include "packager/media/formats/webm/webm_webvtt_parser.h"
namespace shaka {
namespace media {
namespace {
const int64_t kMicrosecondsPerMillisecond = 1000;
} // namespace
WebMClusterParser::WebMClusterParser(
int64_t timecode_scale,
std::shared_ptr<AudioStreamInfo> audio_stream_info,
std::shared_ptr<VideoStreamInfo> video_stream_info,
const VPCodecConfigurationRecord& vp_config,
int64_t audio_default_duration,
int64_t video_default_duration,
const WebMTracksParser::TextTracks& text_tracks,
const std::set<int64_t>& ignored_tracks,
const std::string& audio_encryption_key_id,
const std::string& video_encryption_key_id,
const MediaParser::NewMediaSampleCB& new_sample_cb,
const MediaParser::InitCB& init_cb,
KeySource* decryption_key_source)
: timecode_multiplier_(timecode_scale /
static_cast<double>(kMicrosecondsPerMillisecond)),
audio_stream_info_(audio_stream_info),
video_stream_info_(video_stream_info),
vp_config_(vp_config),
ignored_tracks_(ignored_tracks),
audio_encryption_key_id_(audio_encryption_key_id),
video_encryption_key_id_(video_encryption_key_id),
parser_(kWebMIdCluster, this),
initialized_(false),
init_cb_(init_cb),
cluster_start_time_(kNoTimestamp),
audio_(audio_stream_info ? audio_stream_info->track_id() : -1,
false,
audio_default_duration,
new_sample_cb),
video_(video_stream_info ? video_stream_info->track_id() : -1,
true,
video_default_duration,
new_sample_cb) {
if (decryption_key_source) {
decryptor_source_.reset(new DecryptorSource(decryption_key_source));
if (audio_stream_info_)
audio_stream_info_->set_is_encrypted(false);
if (video_stream_info_)
video_stream_info_->set_is_encrypted(false);
}
for (WebMTracksParser::TextTracks::const_iterator it = text_tracks.begin();
it != text_tracks.end();
++it) {
text_track_map_.insert(std::make_pair(
it->first, Track(it->first, false, kNoTimestamp, new_sample_cb)));
}
}
WebMClusterParser::~WebMClusterParser() {}
void WebMClusterParser::Reset() {
last_block_timecode_ = -1;
cluster_timecode_ = -1;
cluster_start_time_ = kNoTimestamp;
cluster_ended_ = false;
parser_.Reset();
audio_.Reset();
video_.Reset();
ResetTextTracks();
}
bool WebMClusterParser::Flush() {
// Estimate the duration of the last frame if necessary.
bool audio_result = audio_.ApplyDurationEstimateIfNeeded();
bool video_result = video_.ApplyDurationEstimateIfNeeded();
Reset();
return audio_result && video_result;
}
int WebMClusterParser::Parse(const uint8_t* buf, int size) {
int result = parser_.Parse(buf, size);
if (result < 0) {
cluster_ended_ = false;
return result;
}
cluster_ended_ = parser_.IsParsingComplete();
if (cluster_ended_) {
// If there were no buffers in this cluster, set the cluster start time to
// be the |cluster_timecode_|.
if (cluster_start_time_ == kNoTimestamp) {
// If the cluster did not even have a |cluster_timecode_|, signal parse
// error.
if (cluster_timecode_ < 0)
return -1;
cluster_start_time_ = cluster_timecode_ * timecode_multiplier_;
}
// Reset the parser if we're done parsing so that
// it is ready to accept another cluster on the next
// call.
parser_.Reset();
last_block_timecode_ = -1;
cluster_timecode_ = -1;
}
return result;
}
WebMParserClient* WebMClusterParser::OnListStart(int id) {
if (id == kWebMIdCluster) {
cluster_timecode_ = -1;
cluster_start_time_ = kNoTimestamp;
} else if (id == kWebMIdBlockGroup) {
block_data_.reset();
block_data_size_ = -1;
block_duration_ = -1;
discard_padding_ = -1;
discard_padding_set_ = false;
reference_block_set_ = false;
} else if (id == kWebMIdBlockAdditions) {
block_add_id_ = -1;
block_additional_data_.reset();
block_additional_data_size_ = 0;
}
return this;
}
bool WebMClusterParser::OnListEnd(int id) {
if (id != kWebMIdBlockGroup)
return true;
// Make sure the BlockGroup actually had a Block.
if (block_data_size_ == -1) {
LOG(ERROR) << "Block missing from BlockGroup.";
return false;
}
bool result = ParseBlock(
false, block_data_.get(), block_data_size_, block_additional_data_.get(),
block_additional_data_size_, block_duration_,
discard_padding_set_ ? discard_padding_ : 0, reference_block_set_);
block_data_.reset();
block_data_size_ = -1;
block_duration_ = -1;
block_add_id_ = -1;
block_additional_data_.reset();
block_additional_data_size_ = 0;
discard_padding_ = -1;
discard_padding_set_ = false;
reference_block_set_ = false;
return result;
}
bool WebMClusterParser::OnUInt(int id, int64_t val) {
int64_t* dst;
switch (id) {
case kWebMIdTimecode:
dst = &cluster_timecode_;
break;
case kWebMIdBlockDuration:
dst = &block_duration_;
break;
case kWebMIdBlockAddID:
dst = &block_add_id_;
break;
default:
return true;
}
if (*dst != -1)
return false;
*dst = val;
return true;
}
bool WebMClusterParser::ParseBlock(bool is_simple_block,
const uint8_t* buf,
int size,
const uint8_t* additional,
int additional_size,
int duration,
int64_t discard_padding,
bool reference_block_set) {
if (size < 4)
return false;
// Return an error if the trackNum > 127. We just aren't
// going to support large track numbers right now.
if (!(buf[0] & 0x80)) {
LOG(ERROR) << "TrackNumber over 127 not supported";
return false;
}
int track_num = buf[0] & 0x7f;
int timecode = buf[1] << 8 | buf[2];
int flags = buf[3] & 0xff;
int lacing = (flags >> 1) & 0x3;
if (lacing) {
LOG(ERROR) << "Lacing " << lacing << " is not supported yet.";
return false;
}
// Sign extend negative timecode offsets.
if (timecode & 0x8000)
timecode |= ~0xffff;
// The first bit of the flags is set when a SimpleBlock contains only
// keyframes. If this is a Block, then keyframe is inferred by the absence of
// the ReferenceBlock Element.
// http://www.matroska.org/technical/specs/index.html
bool is_key_frame =
is_simple_block ? (flags & 0x80) != 0 : !reference_block_set;
const uint8_t* frame_data = buf + 4;
int frame_size = size - (frame_data - buf);
return OnBlock(is_simple_block, track_num, timecode, duration, frame_data,
frame_size, additional, additional_size, discard_padding,
is_key_frame);
}
bool WebMClusterParser::OnBinary(int id, const uint8_t* data, int size) {
switch (id) {
case kWebMIdSimpleBlock:
return ParseBlock(true, data, size, NULL, 0, -1, 0, false);
case kWebMIdBlock:
if (block_data_) {
LOG(ERROR) << "More than 1 Block in a BlockGroup is not "
"supported.";
return false;
}
block_data_.reset(new uint8_t[size]);
memcpy(block_data_.get(), data, size);
block_data_size_ = size;
return true;
case kWebMIdBlockAdditional: {
uint64_t block_add_id = base::HostToNet64(block_add_id_);
if (block_additional_data_) {
// TODO: Technically, more than 1 BlockAdditional is allowed as per
// matroska spec. But for now we don't have a use case to support
// parsing of such files. Take a look at this again when such a case
// arises.
LOG(ERROR) << "More than 1 BlockAdditional in a "
"BlockGroup is not supported.";
return false;
}
// First 8 bytes of side_data in DecoderBuffer is the BlockAddID
// element's value in Big Endian format. This is done to mimic ffmpeg
// demuxer's behavior.
block_additional_data_size_ = size + sizeof(block_add_id);
block_additional_data_.reset(new uint8_t[block_additional_data_size_]);
memcpy(block_additional_data_.get(), &block_add_id,
sizeof(block_add_id));
memcpy(block_additional_data_.get() + 8, data, size);
return true;
}
case kWebMIdDiscardPadding: {
if (discard_padding_set_ || size <= 0 || size > 8)
return false;
discard_padding_set_ = true;
// Read in the big-endian integer.
discard_padding_ = static_cast<int8_t>(data[0]);
for (int i = 1; i < size; ++i)
discard_padding_ = (discard_padding_ << 8) | data[i];
return true;
}
case kWebMIdReferenceBlock:
// We use ReferenceBlock to determine whether the current Block contains a
// keyframe or not. Other than that, we don't care about the value of the
// ReferenceBlock element itself.
reference_block_set_ = true;
return true;
default:
return true;
}
}
bool WebMClusterParser::OnBlock(bool is_simple_block,
int track_num,
int timecode,
int block_duration,
const uint8_t* data,
int size,
const uint8_t* additional,
int additional_size,
int64_t discard_padding,
bool is_key_frame) {
DCHECK_GE(size, 0);
if (cluster_timecode_ == -1) {
LOG(ERROR) << "Got a block before cluster timecode.";
return false;
}
// TODO: Should relative negative timecode offsets be rejected? Or only when
// the absolute timecode is negative? See http://crbug.com/271794
if (timecode < 0) {
LOG(ERROR) << "Got a block with negative timecode offset " << timecode;
return false;
}
if (last_block_timecode_ != -1 && timecode < last_block_timecode_) {
LOG(ERROR) << "Got a block with a timecode before the previous block.";
return false;
}
Track* track = NULL;
StreamType stream_type = kStreamUnknown;
std::string encryption_key_id;
if (track_num == audio_.track_num()) {
track = &audio_;
encryption_key_id = audio_encryption_key_id_;
stream_type = kStreamAudio;
} else if (track_num == video_.track_num()) {
track = &video_;
encryption_key_id = video_encryption_key_id_;
stream_type = kStreamVideo;
} else if (ignored_tracks_.find(track_num) != ignored_tracks_.end()) {
return true;
} else if (Track* const text_track = FindTextTrack(track_num)) {
if (is_simple_block) // BlockGroup is required for WebVTT cues
return false;
if (block_duration < 0) // not specified
return false;
track = text_track;
stream_type = kStreamText;
} else {
LOG(ERROR) << "Unexpected track number " << track_num;
return false;
}
DCHECK_NE(stream_type, kStreamUnknown);
last_block_timecode_ = timecode;
int64_t timestamp = (cluster_timecode_ + timecode) * timecode_multiplier_;
std::shared_ptr<MediaSample> buffer;
if (stream_type != kStreamText) {
// Every encrypted Block has a signal byte and IV prepended to it. Current
// encrypted WebM request for comments specification is here
// http://wiki.webmproject.org/encryption/webm-encryption-rfc
std::unique_ptr<DecryptConfig> decrypt_config;
int data_offset = 0;
if (!encryption_key_id.empty() &&
!WebMCreateDecryptConfig(
data, size,
reinterpret_cast<const uint8_t*>(encryption_key_id.data()),
encryption_key_id.size(),
&decrypt_config, &data_offset)) {
return false;
}
const uint8_t* media_data = data + data_offset;
const size_t media_data_size = size - data_offset;
// Use a dummy data size of 0 to avoid copying overhead.
// Actual media data is set later.
const size_t kDummyDataSize = 0;
buffer = MediaSample::CopyFrom(media_data, kDummyDataSize, additional,
additional_size, is_key_frame);
if (decrypt_config) {
if (!decryptor_source_) {
buffer->SetData(media_data, media_data_size);
// If the demuxer does not have the decryptor_source_, store
// decrypt_config so that the demuxed sample can be decrypted later.
buffer->set_decrypt_config(std::move(decrypt_config));
buffer->set_is_encrypted(true);
} else {
std::shared_ptr<uint8_t> decrypted_media_data(
new uint8_t[media_data_size], std::default_delete<uint8_t[]>());
if (!decryptor_source_->DecryptSampleBuffer(
decrypt_config.get(), media_data, media_data_size,
decrypted_media_data.get())) {
LOG(ERROR) << "Cannot decrypt samples";
return false;
}
buffer->TransferData(std::move(decrypted_media_data), media_data_size);
}
} else {
buffer->SetData(media_data, media_data_size);
}
} else {
std::string id, settings, content;
WebMWebVTTParser::Parse(data, size, &id, &settings, &content);
std::vector<uint8_t> side_data;
MakeSideData(id.begin(), id.end(),
settings.begin(), settings.end(),
&side_data);
buffer = MediaSample::CopyFrom(
reinterpret_cast<const uint8_t*>(content.data()), content.length(),
&side_data[0], side_data.size(), true);
}
buffer->set_dts(timestamp);
buffer->set_pts(timestamp);
if (cluster_start_time_ == kNoTimestamp)
cluster_start_time_ = timestamp;
buffer->set_duration(block_duration > 0
? (block_duration * timecode_multiplier_)
: kNoTimestamp);
if (!init_cb_.is_null() && !initialized_) {
std::vector<std::shared_ptr<StreamInfo>> streams;
if (audio_stream_info_)
streams.push_back(audio_stream_info_);
if (video_stream_info_) {
if (stream_type == kStreamVideo) {
// Setup codec string and codec config for VP8 and VP9.
// Codec config for AV1 is already retrieved from WebM CodecPrivate
// instead of extracted from the bit stream.
if (video_stream_info_->codec() != kCodecAV1) {
std::unique_ptr<VPxParser> vpx_parser;
switch (video_stream_info_->codec()) {
case kCodecVP8:
vpx_parser.reset(new VP8Parser);
break;
case kCodecVP9:
vpx_parser.reset(new VP9Parser);
break;
default:
NOTIMPLEMENTED()
<< "Unsupported codec " << video_stream_info_->codec();
return false;
}
std::vector<VPxFrameInfo> vpx_frames;
if (!vpx_parser->Parse(buffer->data(), buffer->data_size(),
&vpx_frames)) {
LOG(ERROR) << "Failed to parse vpx frame.";
return false;
}
if (vpx_frames.size() != 1u || !vpx_frames[0].is_keyframe) {
LOG(ERROR) << "The first frame should be a key frame.";
return false;
}
vp_config_.MergeFrom(vpx_parser->codec_config());
video_stream_info_->set_codec_string(
vp_config_.GetCodecString(video_stream_info_->codec()));
std::vector<uint8_t> config_serialized;
vp_config_.WriteMP4(&config_serialized);
video_stream_info_->set_codec_config(config_serialized);
}
streams.push_back(video_stream_info_);
init_cb_.Run(streams);
initialized_ = true;
}
} else {
init_cb_.Run(streams);
initialized_ = true;
}
}
return track->EmitBuffer(buffer);
}
WebMClusterParser::Track::Track(
int track_num,
bool is_video,
int64_t default_duration,
const MediaParser::NewMediaSampleCB& new_sample_cb)
: track_num_(track_num),
is_video_(is_video),
default_duration_(default_duration),
estimated_next_frame_duration_(kNoTimestamp),
new_sample_cb_(new_sample_cb) {
DCHECK(default_duration_ == kNoTimestamp || default_duration_ > 0);
}
WebMClusterParser::Track::~Track() {}
bool WebMClusterParser::Track::EmitBuffer(
const std::shared_ptr<MediaSample>& buffer) {
DVLOG(2) << "EmitBuffer() : " << track_num_
<< " ts " << buffer->pts()
<< " dur " << buffer->duration()
<< " kf " << buffer->is_key_frame()
<< " size " << buffer->data_size();
if (last_added_buffer_missing_duration_.get()) {
int64_t derived_duration =
buffer->pts() - last_added_buffer_missing_duration_->pts();
last_added_buffer_missing_duration_->set_duration(derived_duration);
DVLOG(2) << "EmitBuffer() : applied derived duration to held-back buffer : "
<< " ts "
<< last_added_buffer_missing_duration_->pts()
<< " dur "
<< last_added_buffer_missing_duration_->duration()
<< " kf " << last_added_buffer_missing_duration_->is_key_frame()
<< " size " << last_added_buffer_missing_duration_->data_size();
std::shared_ptr<MediaSample> updated_buffer =
last_added_buffer_missing_duration_;
last_added_buffer_missing_duration_ = NULL;
if (!EmitBufferHelp(updated_buffer))
return false;
}
if (buffer->duration() == kNoTimestamp) {
last_added_buffer_missing_duration_ = buffer;
DVLOG(2) << "EmitBuffer() : holding back buffer that is missing duration";
return true;
}
return EmitBufferHelp(buffer);
}
bool WebMClusterParser::Track::ApplyDurationEstimateIfNeeded() {
if (!last_added_buffer_missing_duration_.get())
return true;
int64_t estimated_duration = GetDurationEstimate();
last_added_buffer_missing_duration_->set_duration(estimated_duration);
VLOG(1) << "Track " << track_num_ << ": Estimating WebM block duration to be "
<< estimated_duration / 1000
<< "ms for the last (Simple)Block in the Cluster for this Track. Use "
"BlockGroups with BlockDurations at the end of each Track in a "
"Cluster to avoid estimation.";
DVLOG(2) << " new dur : ts " << last_added_buffer_missing_duration_->pts()
<< " dur " << last_added_buffer_missing_duration_->duration()
<< " kf " << last_added_buffer_missing_duration_->is_key_frame()
<< " size " << last_added_buffer_missing_duration_->data_size();
// Don't use the applied duration as a future estimation (don't use
// EmitBufferHelp() here.)
if (!new_sample_cb_.Run(track_num_, last_added_buffer_missing_duration_))
return false;
last_added_buffer_missing_duration_ = NULL;
return true;
}
void WebMClusterParser::Track::Reset() {
last_added_buffer_missing_duration_ = NULL;
}
bool WebMClusterParser::Track::EmitBufferHelp(
const std::shared_ptr<MediaSample>& buffer) {
DCHECK(!last_added_buffer_missing_duration_.get());
int64_t duration = buffer->duration();
if (duration < 0 || duration == kNoTimestamp) {
LOG(ERROR) << "Invalid buffer duration: " << duration;
return false;
}
// The estimated frame duration is the maximum non-zero duration since the
// last initialization segment.
if (duration > 0) {
int64_t orig_duration_estimate = estimated_next_frame_duration_;
if (estimated_next_frame_duration_ == kNoTimestamp) {
estimated_next_frame_duration_ = duration;
} else {
estimated_next_frame_duration_ =
std::max(duration, estimated_next_frame_duration_);
}
if (orig_duration_estimate != estimated_next_frame_duration_) {
DVLOG(3) << "Updated duration estimate:"
<< orig_duration_estimate
<< " -> "
<< estimated_next_frame_duration_
<< " at timestamp: "
<< buffer->dts();
}
}
return new_sample_cb_.Run(track_num_, buffer);
}
int64_t WebMClusterParser::Track::GetDurationEstimate() {
int64_t duration = kNoTimestamp;
if (default_duration_ != kNoTimestamp) {
duration = default_duration_;
DVLOG(3) << __FUNCTION__ << " : using track default duration " << duration;
} else if (estimated_next_frame_duration_ != kNoTimestamp) {
duration = estimated_next_frame_duration_;
DVLOG(3) << __FUNCTION__ << " : using estimated duration " << duration;
} else {
if (is_video_) {
duration = kDefaultVideoBufferDurationInMs * kMicrosecondsPerMillisecond;
} else {
duration = kDefaultAudioBufferDurationInMs * kMicrosecondsPerMillisecond;
}
DVLOG(3) << __FUNCTION__ << " : using hardcoded default duration "
<< duration;
}
DCHECK_GT(duration, 0);
DCHECK_NE(duration, kNoTimestamp);
return duration;
}
void WebMClusterParser::ResetTextTracks() {
for (TextTrackMap::iterator it = text_track_map_.begin();
it != text_track_map_.end();
++it) {
it->second.Reset();
}
}
WebMClusterParser::Track*
WebMClusterParser::FindTextTrack(int track_num) {
const TextTrackMap::iterator it = text_track_map_.find(track_num);
if (it == text_track_map_.end())
return NULL;
return &it->second;
}
} // namespace media
} // namespace shaka
| 9,232 |
1,457 | <filename>flash/core/optimizers/schedulers.py
import inspect
from typing import Callable, List
from torch.optim import lr_scheduler
from torch.optim.lr_scheduler import (
_LRScheduler,
CosineAnnealingLR,
CosineAnnealingWarmRestarts,
CyclicLR,
MultiStepLR,
ReduceLROnPlateau,
StepLR,
)
from flash.core.registry import FlashRegistry
from flash.core.utilities.imports import _TORCH_AVAILABLE, _TRANSFORMERS_AVAILABLE
from flash.core.utilities.providers import _HUGGINGFACE
_SCHEDULERS_REGISTRY = FlashRegistry("scheduler")
_STEP_SCHEDULERS = (StepLR, MultiStepLR, CosineAnnealingLR, CyclicLR, CosineAnnealingWarmRestarts)
if _TORCH_AVAILABLE:
schedulers: List[_LRScheduler] = []
for n in dir(lr_scheduler):
sched = getattr(lr_scheduler, n)
if inspect.isclass(sched) and sched != _LRScheduler and issubclass(sched, _LRScheduler):
schedulers.append(sched)
# Adding `ReduceLROnPlateau` separately as it is subclassed from `object` and not `_LRScheduler`.
schedulers.append(ReduceLROnPlateau)
for scheduler in schedulers:
interval = "step" if issubclass(scheduler, _STEP_SCHEDULERS) else "epoch"
_SCHEDULERS_REGISTRY(scheduler, name=scheduler.__name__.lower(), interval=interval)
if _TRANSFORMERS_AVAILABLE:
from transformers import optimization
functions: List[Callable] = []
for n in dir(optimization):
if "get_" in n and n != "get_scheduler":
functions.append(getattr(optimization, n))
for fn in functions:
_SCHEDULERS_REGISTRY(fn, name=fn.__name__[4:].lower(), providers=_HUGGINGFACE, interval="step")
| 661 |
488 | <filename>tests/CompileTests/ElsaTestCases/t0149.cc
// t0149.cc
// operator%
struct A {
operator int& ();
};
struct Av {
operator int volatile & ();
};
struct B {
operator float& ();
};
struct Bad {
operator char (); // RHS instantiation: int
operator unsigned char (); // RHS instantiation: int
};
void f1()
{
A a;
Av av;
B b;
Bad bad;
a %= 3;
av %= 3;
//ERROR(1): b %= 3; // can't convert to reference-to-integral
//ERROR(2): a %= bad;
}
| 205 |
386 | <gh_stars>100-1000
/* Copyright 2018-2018 University Corporation for Atmospheric
Research/Unidata. */
/**
* @file
* @internal Includes prototypes for libzarr dispatch functions.
*
* @author <NAME>, <NAME>
*/
#ifndef ZDISPATCH_H
#define ZDISPATCH_H
#include "zincludes.h"
#if defined(__cplusplus)
extern "C" {
#endif
EXTERNL int NCZ_create(const char *path, int cmode, size_t initialsz, int basepe, size_t *chunksizehintp, void* parameters, const NC_Dispatch*, int);
EXTERNL int NCZ_open(const char *path, int mode, int basepe, size_t *chunksizehintp, void* parameters, const NC_Dispatch*, int);
EXTERNL int NCZ_redef(int ncid);
EXTERNL int NCZ__enddef(int ncid, size_t h_minfree, size_t v_align, size_t v_minfree, size_t r_align);
EXTERNL int NCZ_sync(int ncid);
EXTERNL int NCZ_abort(int ncid);
EXTERNL int NCZ_close(int ncid,void*);
EXTERNL int NCZ_set_fill(int ncid, int fillmode, int *old_modep);
EXTERNL int NCZ_set_base_pe(int ncid, int pe);
EXTERNL int NCZ_inq_base_pe(int ncid, int *pe);
EXTERNL int NCZ_inq_format(int ncid, int *formatp);
EXTERNL int NCZ_inq_format_extended(int ncid, int *formatp, int *modep);
EXTERNL int NCZ_inq(int ncid, int *ndimsp, int *nvarsp, int *nattsp, int *unlimdimidp);
EXTERNL int NCZ_inq_type(int, nc_type, char *, size_t *);
/* Begin _dim */
EXTERNL int NCZ_def_dim(int ncid, const char *name, size_t len, int *idp);
EXTERNL int NCZ_inq_dimid(int ncid, const char *name, int *idp);
EXTERNL int NCZ_inq_dim(int ncid, int dimid, char *name, size_t *lenp);
EXTERNL int NCZ_inq_unlimdim(int ncid, int *unlimdimidp);
EXTERNL int NCZ_rename_dim(int ncid, int dimid, const char *name);
/* End _dim */
/* Begin _att */
EXTERNL int NCZ_inq_att(int ncid, int varid, const char *name, nc_type *xtypep, size_t *lenp);
EXTERNL int NCZ_inq_attid(int ncid, int varid, const char *name, int *idp);
EXTERNL int NCZ_inq_attname(int ncid, int varid, int attnum, char *name);
EXTERNL int NCZ_rename_att(int ncid, int varid, const char *name, const char *newname);
EXTERNL int NCZ_del_att(int ncid, int varid, const char *name);
/* End _att */
/* Begin {put,get}_att */
EXTERNL int NCZ_get_att(int ncid, int varid, const char *name, void *value, nc_type);
EXTERNL int NCZ_put_att(int ncid, int varid, const char *name, nc_type file_type, size_t len, const void *data, nc_type mem_type);
/* End {put,get}_att */
/* Begin _var */
EXTERNL int NCZ_def_var(int ncid, const char *name, nc_type xtype, int ndims, const int *dimidsp, int *varidp);
EXTERNL int NCZ_inq_var_all(int ncid, int varid, char *name, nc_type *xtypep, int *ndimsp, int *dimidsp, int *nattsp, int *shufflep, int *deflatep, int *deflate_levelp, int *fletcher32p, int *contiguousp, size_t *chunksizesp, int *no_fill, void *fill_valuep, int *endiannessp, unsigned int* idp, size_t* nparamsp, unsigned int* params
);
EXTERNL int NCZ_inq_varid(int ncid, const char *name, int *varidp);
EXTERNL int NCZ_rename_var(int ncid, int varid, const char *name);
EXTERNL int NCZ_put_vara(int ncid, int varid, const size_t *start, const size_t *count, const void *value, nc_type);
EXTERNL int NCZ_get_vara(int ncid, int varid, const size_t *start, const size_t *count, void *value, nc_type);
extern int
NCZ_put_vars(int ncid, int varid, const size_t *start, const size_t *count, const ptrdiff_t* stride, const void *value, nc_type);
extern int
NCZ_get_vars(int ncid, int varid, const size_t *start, const size_t *count, const ptrdiff_t* stride, void *value, nc_type);
/* End _var */
/* netCDF4 API only */
EXTERNL int NCZ_inq_ncid(int, const char *, int *);
EXTERNL int NCZ_inq_grps(int, int *, int *);
EXTERNL int NCZ_inq_grpname(int, char *);
EXTERNL int NCZ_inq_grpname_full(int, size_t *, char *);
EXTERNL int NCZ_inq_grp_parent(int, int *);
EXTERNL int NCZ_inq_grp_full_ncid(int, const char *, int *);
EXTERNL int NCZ_inq_varids(int, int * nvars, int *);
EXTERNL int NCZ_inq_dimids(int, int * ndims, int *, int);
EXTERNL int NCZ_inq_typeids(int, int * ntypes, int *);
EXTERNL int NCZ_inq_type_equal(int, nc_type, int, nc_type, int *);
EXTERNL int NCZ_def_grp(int, const char *, int *);
EXTERNL int NCZ_rename_grp(int, const char *);
EXTERNL int NCZ_inq_user_type(int, nc_type, char *, size_t *, nc_type *, size_t *, int *);
EXTERNL int NCZ_def_compound(int, size_t, const char *, nc_type *);
EXTERNL int NCZ_insert_compound(int, nc_type, const char *, size_t, nc_type);
EXTERNL int NCZ_insert_array_compound(int, nc_type, const char *, size_t, nc_type, int, const int *);
EXTERNL int NCZ_inq_typeid(int, const char *, nc_type *);
EXTERNL int NCZ_inq_compound_field(int, nc_type, int, char *, size_t *, nc_type *, int *, int *);
EXTERNL int NCZ_inq_compound_fieldindex(int, nc_type, const char *, int *);
EXTERNL int NCZ_def_vlen(int, const char *, nc_type base_typeid, nc_type *);
EXTERNL int NCZ_put_vlen_element(int, int, void *, size_t, const void *);
EXTERNL int NCZ_get_vlen_element(int, int, const void *, size_t *, void *);
EXTERNL int NCZ_def_enum(int, nc_type, const char *, nc_type *);
EXTERNL int NCZ_insert_enum(int, nc_type, const char *, const void *);
EXTERNL int NCZ_inq_enum_member(int, nc_type, int, char *, void *);
EXTERNL int NCZ_inq_enum_ident(int, nc_type, long long, char *);
EXTERNL int NCZ_def_opaque(int, size_t, const char *, nc_type *);
EXTERNL int NCZ_def_var_deflate(int, int, int, int, int);
EXTERNL int NCZ_def_var_fletcher32(int, int, int);
EXTERNL int NCZ_def_var_chunking(int, int, int, const size_t *);
EXTERNL int NCZ_def_var_fill(int, int, int, const void *);
EXTERNL int NCZ_def_var_endian(int, int, int);
EXTERNL int NCZ_inq_unlimdims(int, int *, int *);
EXTERNL int NCZ_def_var_filter(int ncid, int varid, unsigned int filterid, size_t nparams, const unsigned int *params);
EXTERNL int NCZ_inq_var_filter_ids(int ncid, int varid, size_t* nfiltersp, unsigned int *filterids);
EXTERNL int NCZ_inq_var_filter_info(int ncid, int varid, unsigned int filterid, size_t* nparamsp, unsigned int *params);
EXTERNL int NCZ_def_var_filterx(int ncid, int varid, const char* text);
EXTERNL int NCZ_inq_var_filterx_ids(int ncid, int varid, char** textp);
EXTERNL int NCZ_inq_var_filterx_info(int ncid, int varid, const char* id, char** textp);
#if defined(__cplusplus)
}
#endif
#endif /* ZDISPATCH_H */
| 2,675 |
5,169 | <filename>Specs/4/1/c/viper-base/2.1.1/viper-base.podspec.json
{
"name": "viper-base",
"module_name": "VIPERBase",
"version": "2.1.1",
"summary": "Implementation of VIPER architecture for using in iOS platform",
"homepage": "https://github.com/rafaelrsilva/viper-base-ios.git",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"swift_version": "5.0",
"source": {
"git": "https://github.com/rafaelrsilva/viper-base-ios.git",
"tag": "2.1.1"
},
"source_files": "VIPERBase/**/*.{h,m,swift}",
"testspecs": [
{
"name": "VIPERBaseTests",
"test_type": "unit",
"source_files": "VIPERBaseTests/**/*.{h,m,swift}"
}
]
}
| 340 |
2,727 | <gh_stars>1000+
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//--------------------------------------------------------------------------------
// Include files
//--------------------------------------------------------------------------------
#include <android/log.h>
#include <android_native_app_glue.h>
#include <condition_variable>
#include <dlfcn.h>
#include <EGL/egl.h>
#include <thread>
#include "TeapotRenderer.h"
#include "NDKHelper.h"
//-------------------------------------------------------------------------
// Preprocessor
//-------------------------------------------------------------------------
#define HELPER_CLASS_NAME \
"com/sample/helper/NDKHelper" // Class name of helper function
// Indicate API mode to achieve 30 FPS.
enum APIMode {
kAPINone,
kAPINativeChoreographer,
kAPIJavaChoreographer,
kAPIEGLExtension,
};
const int32_t kFPSThrottleInterval = 2;
const int64_t kFPSThrottlePresentationInterval = (kFPSThrottleInterval / 60.0f) * 1000000000;
#define COULD_RENDER(now, last) (((now) - (last)) >= kFPSThrottlePresentationInterval)
// Declaration for native chreographer API.
struct AChoreographer;
typedef void (*AChoreographer_frameCallback)(long frameTimeNanos, void* data);
typedef AChoreographer* (*func_AChoreographer_getInstance)();
typedef void (*func_AChoreographer_postFrameCallback)(
AChoreographer* choreographer, AChoreographer_frameCallback callback,
void* data);
//-------------------------------------------------------------------------
// Shared state for our app.
//-------------------------------------------------------------------------
struct android_app;
class Engine {
android_app* app_;
TeapotRenderer renderer_;
ndk_helper::GLContext* gl_context_;
bool initialized_resources_;
bool has_focus_;
bool fps_throttle_;
ndk_helper::DoubletapDetector doubletap_detector_;
ndk_helper::PinchDetector pinch_detector_;
ndk_helper::DragDetector drag_detector_;
ndk_helper::PerfMonitor monitor_;
ndk_helper::TapCamera tap_camera_;
APIMode api_mode_;
APIMode original_api_mode_;
void UpdateFPS(float fFPS);
void ShowUI();
void TransformPosition(ndk_helper::Vec2& vec);
void Swap();
// Do swap operation at the end of rendering if necessary.
void DoSwap();
void CheckAPISupport();
void StartFPSThrottle();
void StopFPSThrottle();
int64_t GetCurrentTime();
void StartChoreographer();
void StartJavaChoreographer();
void StopJavaChoreographer();
static void choreographer_callback(long frameTimeNanos, void* data);
// Function pointers for native Choreographer API.
func_AChoreographer_getInstance AChoreographer_getInstance_;
func_AChoreographer_postFrameCallback AChoreographer_postFrameCallback_;
// Stuff for EGL Android presentation time extension.
int64_t presentation_time_;
bool (*eglPresentationTimeANDROID_)(EGLDisplay dpy, EGLSurface sur,
khronos_stime_nanoseconds_t time);
int64_t prevFrameTimeNanos_;
bool should_render_;
std::mutex mtx_; // mutex for critical section
std::condition_variable cv_; // condition variable for critical section
public:
static void HandleCmd(struct android_app* app, int32_t cmd);
static int32_t HandleInput(android_app* app, AInputEvent* event);
Engine();
~Engine();
void SetState(android_app *app);
int InitDisplay(android_app *app);
void LoadResources();
void UnloadResources();
void DrawFrame();
void TermDisplay();
void TrimMemory();
bool IsReady();
void UpdatePosition(AInputEvent* event, int32_t iIndex, float& fX, float& fY);
// Do swap operation while Choreographer callback. Need to be a public method
// since it's called from JNI callback.
void SynchInCallback(jlong frameTimeNamos);
};
// Global instance of the Engine class.
Engine g_engine;
Engine::Engine()
:app_(NULL),
initialized_resources_(false),
has_focus_(false),
fps_throttle_(true),
api_mode_(kAPINone),
prevFrameTimeNanos_(static_cast<int64_t>(0)),
should_render_(true) {
gl_context_ = ndk_helper::GLContext::GetInstance();
}
Engine::~Engine() {}
/**
* Check which API is supported in the device.
*/
void Engine::CheckAPISupport() {
auto apilevel = AConfiguration_getSdkVersion(app_->config);
LOGI("Device API Level %d", apilevel);
if (apilevel >= 24) {
// Native Choreographer API is supported in API level 24~.
void* lib = dlopen("libandroid.so", RTLD_NOW | RTLD_LOCAL);
if (lib != nullptr) {
LOGI("Run with Choreographer Native API.");
api_mode_ = kAPINativeChoreographer;
// Retrieve function pointers from shared object.
AChoreographer_getInstance_ =
reinterpret_cast<func_AChoreographer_getInstance>(
dlsym(lib, "AChoreographer_getInstance"));
AChoreographer_postFrameCallback_ =
reinterpret_cast<func_AChoreographer_postFrameCallback>(
dlsym(lib, "AChoreographer_postFrameCallback"));
assert(AChoreographer_getInstance_);
assert(AChoreographer_postFrameCallback_);
}
} else if (apilevel >= 18) {
// eglPresentationTimeANDROID would be supported in API level 18~.
LOGI("Run with EGLExtension.");
api_mode_ = kAPIEGLExtension;
// Retrieve the EGL extension's function pointer.
eglPresentationTimeANDROID_ = reinterpret_cast<
bool (*)(EGLDisplay, EGLSurface, khronos_stime_nanoseconds_t)>(
eglGetProcAddress("eglPresentationTimeANDROID"));
assert(eglPresentationTimeANDROID_);
presentation_time_ = GetCurrentTime();
} else if (apilevel >= 16) {
// Choreographer Java API is supported API level 16~.
LOGI("Run with Chreographer Java API.");
api_mode_ = kAPIJavaChoreographer;
} else {
api_mode_ = kAPINone;
}
original_api_mode_ = api_mode_;
StartFPSThrottle();
}
void Engine::StartFPSThrottle() {
api_mode_ = original_api_mode_;
if (api_mode_ == kAPINativeChoreographer) {
// Initiate choreographer callback.
StartChoreographer();
} else if (api_mode_ == kAPIJavaChoreographer) {
// Initiate Java choreographer callback.
StartJavaChoreographer();
}
}
void Engine::StopFPSThrottle() {
if (api_mode_ == kAPINativeChoreographer) {
should_render_ = true;
// ALooper_wake(app_->looper);
} else if (api_mode_ == kAPIJavaChoreographer) {
StopJavaChoreographer();
}
api_mode_ = kAPINone;
}
void Engine::DoSwap() {
if (api_mode_ == kAPINativeChoreographer) {
// Use choreographer to synchronize.
// Do nothing but wait the until choreographer callback.
should_render_ = false;
} else if (api_mode_ == kAPIJavaChoreographer) {
// Wait until the conditional variable is signaled.
std::unique_lock<std::mutex> lock(mtx_);
cv_.wait(lock);
Swap();
} else if (api_mode_ == kAPIEGLExtension) {
// Use eglPresentationTimeANDROID extension.
presentation_time_ += kFPSThrottlePresentationInterval;
eglPresentationTimeANDROID_(gl_context_->GetDisplay(),
gl_context_->GetSurface(), presentation_time_);
Swap();
} else {
// Regular Swap.
Swap();
}
}
// Native Chreographer API support.
void Engine::StartChoreographer() {
// Initiate choreographer callbacks.
if (api_mode_ == kAPINativeChoreographer) {
auto choreographer = AChoreographer_getInstance_();
AChoreographer_postFrameCallback_(choreographer, choreographer_callback,
this);
}
}
// Native Choreographer callback.
void Engine::choreographer_callback(long frameTimeNanos, void* data) {
auto engine = reinterpret_cast<Engine*>(data);
// Post next callback for self.
if (engine->has_focus_) {
engine->StartChoreographer();
}
// Swap buffer if the timing meets the 30fps time interval condition.
// The callback is in the same thread context, so that we can just invoke
// eglSwapBuffers().
if (COULD_RENDER(frameTimeNanos, engine->prevFrameTimeNanos_)) {
engine->should_render_ = true;
engine->Swap();
// Wake up main looper so that it will continue rendering.
ALooper_wake(engine->app_->looper);
engine->prevFrameTimeNanos_ = frameTimeNanos;
}
}
// Java choreographer API support.
// With Java API, we uses synch primitive to synchronize Java thread and render
// thread.
void Engine::StartJavaChoreographer() {
JNIEnv* jni;
app_->activity->vm->AttachCurrentThread(&jni, NULL);
// Intiate Java Chreographer API.
jclass clazz = jni->GetObjectClass(app_->activity->clazz);
jmethodID methodID = jni->GetMethodID(clazz, "startChoreographer", "()V");
jni->CallVoidMethod(app_->activity->clazz, methodID);
app_->activity->vm->DetachCurrentThread();
return;
}
void Engine::StopJavaChoreographer() {
JNIEnv* jni;
app_->activity->vm->AttachCurrentThread(&jni, NULL);
// Intiate Java Chreographer API.
jclass clazz = jni->GetObjectClass(app_->activity->clazz);
jmethodID methodID = jni->GetMethodID(clazz, "stopChoreographer", "()V");
jni->CallVoidMethod(app_->activity->clazz, methodID);
app_->activity->vm->DetachCurrentThread();
// Make sure the render thread is not blocked.
cv_.notify_one();
return;
}
void Engine::SynchInCallback(jlong frameTimeInNanos) {
// Signal render thread if the timing meets the 30fps time interval condition.
if (COULD_RENDER(frameTimeInNanos, prevFrameTimeNanos_)) {
prevFrameTimeNanos_ = frameTimeInNanos;
cv_.notify_one();
}
};
extern "C" JNIEXPORT void JNICALL
Java_com_sample_choreographer_ChoreographerNativeActivity_choregrapherCallback(
JNIEnv* env, jobject instance, jlong frameTimeInNanos) {
g_engine.SynchInCallback(frameTimeInNanos);
}
// Helper functions.
int64_t Engine::GetCurrentTime() {
timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return static_cast<int64_t>(time.tv_sec) * 1e9 +
static_cast<int64_t>(time.tv_nsec);
}
void Engine::Swap() {
if (EGL_SUCCESS != gl_context_->Swap()) {
UnloadResources();
LoadResources();
}
}
/**
* Load resources
*/
void Engine::LoadResources() {
renderer_.Init();
renderer_.Bind(&tap_camera_);
}
/**
* Unload resources
*/
void Engine::UnloadResources() { renderer_.Unload(); }
/**
* Initialize an EGL context for the current display.
*/
int Engine::InitDisplay(android_app *app) {
if (!initialized_resources_) {
gl_context_->Init(app_->window);
LoadResources();
initialized_resources_ = true;
} else if(app->window != gl_context_->GetANativeWindow()) {
// Re-initialize ANativeWindow.
// On some devices, ANativeWindow is re-created when the app is resumed
assert(gl_context_->GetANativeWindow());
UnloadResources();
gl_context_->Invalidate();
app_ = app;
gl_context_->Init(app->window);
LoadResources();
initialized_resources_ = true;
} else {
// initialize OpenGL ES and EGL
if (EGL_SUCCESS != gl_context_->Resume(app_->window)) {
UnloadResources();
LoadResources();
}
}
ShowUI();
// Initialize GL state.
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// Note that screen size might have been changed
glViewport(0, 0, gl_context_->GetScreenWidth(),
gl_context_->GetScreenHeight());
renderer_.UpdateViewport();
tap_camera_.SetFlip(1.f, -1.f, -1.f);
tap_camera_.SetPinchTransformFactor(2.f, 2.f, 8.f);
return 0;
}
/**
* Just the current frame in the display.
*/
void Engine::DrawFrame() {
float fps;
if (monitor_.Update(fps)) {
UpdateFPS(fps);
}
renderer_.Update(monitor_.GetCurrentTime());
// Just fill the screen with a color.
glClearColor(0.5f, 0.5f, 0.5f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float color[2][3] = {{1.0f, 0.5f, 0.5f}, {1.0f, 0.0f, 0.0f}};
int32_t i = fps_throttle_ ? 0 : 1;
renderer_.Render(color[i][0], color[i][1], color[i][2]);
DoSwap();
}
/**
* Tear down the EGL context currently associated with the display.
*/
void Engine::TermDisplay() { gl_context_->Suspend(); }
void Engine::TrimMemory() {
LOGI("Trimming memory");
gl_context_->Invalidate();
}
/**
* Process the next input event.
*/
int32_t Engine::HandleInput(android_app* app, AInputEvent* event) {
Engine* eng = (Engine*)app->userData;
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
ndk_helper::GESTURE_STATE doubleTapState =
eng->doubletap_detector_.Detect(event);
ndk_helper::GESTURE_STATE dragState = eng->drag_detector_.Detect(event);
ndk_helper::GESTURE_STATE pinchState = eng->pinch_detector_.Detect(event);
// Double tap detector has a priority over other detectors
if (doubleTapState == ndk_helper::GESTURE_STATE_ACTION) {
// Detect double tap
eng->tap_camera_.Reset(true);
// Switch mode between 30FPS <-> 60FPS.
eng->fps_throttle_ = !eng->fps_throttle_;
LOGI("Switched FPS throttle mode.");
if (eng->fps_throttle_) {
eng->StartFPSThrottle();
} else {
eng->StopFPSThrottle();
}
} else {
// Handle drag state
if (dragState & ndk_helper::GESTURE_STATE_START) {
// Otherwise, start dragging
ndk_helper::Vec2 v;
eng->drag_detector_.GetPointer(v);
eng->TransformPosition(v);
eng->tap_camera_.BeginDrag(v);
} else if (dragState & ndk_helper::GESTURE_STATE_MOVE) {
ndk_helper::Vec2 v;
eng->drag_detector_.GetPointer(v);
eng->TransformPosition(v);
eng->tap_camera_.Drag(v);
} else if (dragState & ndk_helper::GESTURE_STATE_END) {
eng->tap_camera_.EndDrag();
}
// Handle pinch state
if (pinchState & ndk_helper::GESTURE_STATE_START) {
// Start new pinch
ndk_helper::Vec2 v1;
ndk_helper::Vec2 v2;
eng->pinch_detector_.GetPointers(v1, v2);
eng->TransformPosition(v1);
eng->TransformPosition(v2);
eng->tap_camera_.BeginPinch(v1, v2);
} else if (pinchState & ndk_helper::GESTURE_STATE_MOVE) {
// Multi touch
// Start new pinch
ndk_helper::Vec2 v1;
ndk_helper::Vec2 v2;
eng->pinch_detector_.GetPointers(v1, v2);
eng->TransformPosition(v1);
eng->TransformPosition(v2);
eng->tap_camera_.Pinch(v1, v2);
}
}
return 1;
}
return 0;
}
/**
* Process the next main command.
*/
void Engine::HandleCmd(struct android_app* app, int32_t cmd) {
Engine* eng = (Engine*)app->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
break;
case APP_CMD_INIT_WINDOW:
// The window is being shown, get it ready.
if (app->window != NULL) {
eng->InitDisplay(app);
eng->has_focus_ = true;
eng->DrawFrame();
}
break;
case APP_CMD_TERM_WINDOW:
// The window is being hidden or closed, clean it up.
eng->TermDisplay();
eng->has_focus_ = false;
break;
case APP_CMD_STOP:
break;
case APP_CMD_GAINED_FOCUS:
// Start animation
eng->has_focus_ = true;
// Update counter when the app becomes active.
eng->presentation_time_ = eng->GetCurrentTime();
if (eng->api_mode_ == kAPINativeChoreographer) {
eng->StartChoreographer();
}
break;
case APP_CMD_LOST_FOCUS:
// Also stop animating.
eng->has_focus_ = false;
eng->DrawFrame();
break;
case APP_CMD_LOW_MEMORY:
// Free up GL resources
eng->TrimMemory();
break;
}
}
//-------------------------------------------------------------------------
// Misc
//-------------------------------------------------------------------------
void Engine::SetState(android_app* state) {
app_ = state;
doubletap_detector_.SetConfiguration(app_->config);
drag_detector_.SetConfiguration(app_->config);
pinch_detector_.SetConfiguration(app_->config);
CheckAPISupport();
}
bool Engine::IsReady() {
if (has_focus_ && should_render_) return true;
return false;
}
void Engine::TransformPosition(ndk_helper::Vec2& vec) {
vec = ndk_helper::Vec2(2.0f, 2.0f) * vec /
ndk_helper::Vec2(gl_context_->GetScreenWidth(),
gl_context_->GetScreenHeight()) -
ndk_helper::Vec2(1.f, 1.f);
}
void Engine::ShowUI() {
JNIEnv* jni;
app_->activity->vm->AttachCurrentThread(&jni, NULL);
// Default class retrieval
jclass clazz = jni->GetObjectClass(app_->activity->clazz);
jmethodID methodID = jni->GetMethodID(clazz, "showUI", "()V");
jni->CallVoidMethod(app_->activity->clazz, methodID);
app_->activity->vm->DetachCurrentThread();
return;
}
void Engine::UpdateFPS(float fFPS) {
JNIEnv* jni;
app_->activity->vm->AttachCurrentThread(&jni, NULL);
// Default class retrieval
jclass clazz = jni->GetObjectClass(app_->activity->clazz);
jmethodID methodID = jni->GetMethodID(clazz, "updateFPS", "(F)V");
jni->CallVoidMethod(app_->activity->clazz, methodID, fFPS);
app_->activity->vm->DetachCurrentThread();
return;
}
/**
* This is the main entry point of a native application that is using
* android_native_app_glue. It runs in its own thread, with its own
* event loop for receiving input events and doing other things.
*/
void android_main(android_app* state) {
g_engine.SetState(state);
// Init helper functions
ndk_helper::JNIHelper::Init(state->activity, HELPER_CLASS_NAME);
state->userData = &g_engine;
state->onAppCmd = Engine::HandleCmd;
state->onInputEvent = Engine::HandleInput;
// loop waiting for stuff to do.
while (1) {
// Read all pending events.
int id;
int events;
android_poll_source* source;
// If not animating, we will block forever waiting for events.
// If animating, we loop until all events are read, then continue
// to draw the next frame of animation.
while ((id = ALooper_pollAll(g_engine.IsReady() ? 0 : -1, NULL, &events,
(void**)&source)) >= 0) {
// Process this event.
if (source != NULL) source->process(state, source);
// Check if we are exiting.
if (state->destroyRequested != 0) {
g_engine.TermDisplay();
return;
}
}
if (g_engine.IsReady()) {
// Drawing is throttled to the screen update rate, so there
// is no need to do timing here.
g_engine.DrawFrame();
}
}
} | 7,039 |
10,225 | package io.quarkus.spring.web.deployment;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import io.quarkus.arc.Arc;
import io.quarkus.arc.ArcContainer;
import io.quarkus.arc.InstanceHandle;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.gizmo.FieldCreator;
import io.quarkus.gizmo.FieldDescriptor;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.spring.web.runtime.ResponseContentTypeResolver;
import io.quarkus.spring.web.runtime.ResponseEntityConverter;
class ControllerAdviceAbstractExceptionMapperGenerator extends AbstractExceptionMapperGenerator {
private static final DotName RESPONSE_ENTITY = DotName.createSimple("org.springframework.http.ResponseEntity");
// Preferred content types order for String or primitive type responses
private static final List<String> TEXT_MEDIA_TYPES = Arrays.asList(
MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML);
// Preferred content types order for object type responses
private static final List<String> OBJECT_MEDIA_TYPES = Arrays.asList(
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.TEXT_PLAIN);
private final MethodInfo controllerAdviceMethod;
private final TypesUtil typesUtil;
private final Type returnType;
private final List<Type> parameterTypes;
private final String declaringClassName;
private final Map<Type, FieldDescriptor> parameterTypeToField = new HashMap<>();
private FieldDescriptor httpHeadersField;
ControllerAdviceAbstractExceptionMapperGenerator(MethodInfo controllerAdviceMethod, DotName exceptionDotName,
ClassOutput classOutput, TypesUtil typesUtil) {
super(exceptionDotName, classOutput);
this.controllerAdviceMethod = controllerAdviceMethod;
this.typesUtil = typesUtil;
this.returnType = controllerAdviceMethod.returnType();
this.parameterTypes = controllerAdviceMethod.parameters();
this.declaringClassName = controllerAdviceMethod.declaringClass().name().toString();
}
/**
* We need to go through each parameter of the method of the ControllerAdvice
* and make sure it's supported
* The javax.ws.rs.ext.ExceptionMapper only has one parameter, the exception, however
* other parameters can be obtained using @Context and therefore injected into the target method
*/
@Override
protected void preGenerateMethodBody(ClassCreator cc) {
int notAllowedParameterIndex = -1;
for (int i = 0; i < parameterTypes.size(); i++) {
Type parameterType = parameterTypes.get(i);
DotName parameterTypeDotName = parameterType.name();
if (typesUtil.isAssignable(Exception.class, parameterTypeDotName)) {
// do nothing since this will be handled during in generateMethodBody
} else if (typesUtil.isAssignable(HttpServletRequest.class, parameterTypeDotName)) {
if (parameterTypeToField.containsKey(parameterType)) {
throw new IllegalArgumentException("Parameter type " + parameterTypes.get(notAllowedParameterIndex).name()
+ " is being used multiple times in method" + controllerAdviceMethod.name() + " of class"
+ controllerAdviceMethod.declaringClass().name());
}
// we need to generate a field that injects the HttpServletRequest into the class
FieldCreator httpRequestFieldCreator = cc.getFieldCreator("httpServletRequest", HttpServletRequest.class)
.setModifiers(Modifier.PRIVATE);
httpRequestFieldCreator.addAnnotation(Context.class);
// stash the fieldCreator in a map indexed by the parameter type so we can retrieve it later
parameterTypeToField.put(parameterType, httpRequestFieldCreator.getFieldDescriptor());
} else if (typesUtil.isAssignable(HttpServletResponse.class, parameterTypeDotName)) {
if (parameterTypeToField.containsKey(parameterType)) {
throw new IllegalArgumentException("Parameter type " + parameterTypes.get(notAllowedParameterIndex).name()
+ " is being used multiple times in method" + controllerAdviceMethod.name() + " of class"
+ controllerAdviceMethod.declaringClass().name());
}
// we need to generate a field that injects the HttpServletRequest into the class
FieldCreator httpRequestFieldCreator = cc.getFieldCreator("httpServletResponse", HttpServletResponse.class)
.setModifiers(Modifier.PRIVATE);
httpRequestFieldCreator.addAnnotation(Context.class);
// stash the fieldCreator in a map indexed by the parameter type so we can retrieve it later
parameterTypeToField.put(parameterType, httpRequestFieldCreator.getFieldDescriptor());
} else {
notAllowedParameterIndex = i;
}
}
if (notAllowedParameterIndex >= 0) {
throw new IllegalArgumentException(
"Parameter type " + parameterTypes.get(notAllowedParameterIndex).name() + " is not supported for method"
+ controllerAdviceMethod.name() + " of class" + controllerAdviceMethod.declaringClass().name());
}
createHttpHeadersField(cc);
}
private void createHttpHeadersField(ClassCreator classCreator) {
FieldCreator httpHeadersFieldCreator = classCreator
.getFieldCreator("httpHeaders", HttpHeaders.class)
.setModifiers(Modifier.PRIVATE);
httpHeadersFieldCreator.addAnnotation(Context.class);
httpHeadersField = httpHeadersFieldCreator.getFieldDescriptor();
}
@Override
void generateMethodBody(MethodCreator toResponse) {
if (isVoidType(returnType)) {
generateVoidExceptionHandler(toResponse);
} else if (isEntityType(returnType)) {
generateResponseEntityExceptionHandler(toResponse);
} else {
generateGenericResponseExceptionHandler(toResponse);
}
}
private void generateVoidExceptionHandler(MethodCreator methodCreator) {
invokeExceptionHandlerMethod(methodCreator);
int status = getAnnotationStatusOrDefault(Response.Status.NO_CONTENT.getStatusCode());
ResultHandle result = new ResponseBuilder(methodCreator, status)
.withType(getResponseContentType(methodCreator, TEXT_MEDIA_TYPES))
.build();
methodCreator.returnValue(result);
}
private void generateResponseEntityExceptionHandler(MethodCreator methodCreator) {
ResultHandle result = methodCreator.invokeStaticMethod(
MethodDescriptor.ofMethod(ResponseEntityConverter.class.getName(), "toResponse",
Response.class.getName(), RESPONSE_ENTITY.toString(), MediaType.class.getName()),
invokeExceptionHandlerMethod(methodCreator),
getResponseContentType(methodCreator, getSupportedMediaTypesForType(getResponseEntityType())));
methodCreator.returnValue(result);
}
private Type getResponseEntityType() {
if (isParameterizedType(returnType) && returnType.asParameterizedType().arguments().size() == 1) {
return returnType.asParameterizedType().arguments().get(0);
}
return returnType;
}
private void generateGenericResponseExceptionHandler(MethodCreator methodCreator) {
int status = getAnnotationStatusOrDefault(Response.Status.OK.getStatusCode());
ResultHandle result = new ResponseBuilder(methodCreator, status)
.withEntity(invokeExceptionHandlerMethod(methodCreator))
.withType(getResponseContentType(methodCreator, getSupportedMediaTypesForType(returnType)))
.build();
methodCreator.returnValue(result);
}
private List<String> getSupportedMediaTypesForType(Type type) {
if (isStringType(type) || isPrimitiveType(type)) {
return TEXT_MEDIA_TYPES;
}
return OBJECT_MEDIA_TYPES;
}
private ResultHandle getResponseContentType(MethodCreator methodCreator, List<String> supportedMediaTypeStrings) {
ResultHandle[] supportedMediaTypes = supportedMediaTypeStrings.stream()
.map(methodCreator::load)
.toArray(ResultHandle[]::new);
return methodCreator.invokeStaticMethod(
MethodDescriptor.ofMethod(ResponseContentTypeResolver.class, "resolve", MediaType.class,
HttpHeaders.class, String[].class),
methodCreator.readInstanceField(httpHeadersField, methodCreator.getThis()),
methodCreator.marshalAsArray(String.class, supportedMediaTypes));
}
private ResultHandle invokeExceptionHandlerMethod(MethodCreator toResponse) {
String returnTypeClassName = isVoidType(returnType) ? void.class.getName() : returnType.name().toString();
if (parameterTypes.isEmpty()) {
return toResponse.invokeVirtualMethod(
MethodDescriptor.ofMethod(declaringClassName, controllerAdviceMethod.name(), returnTypeClassName),
controllerAdviceInstance(toResponse));
}
String[] parameterTypesStr = new String[parameterTypes.size()];
ResultHandle[] parameterTypeHandles = new ResultHandle[parameterTypes.size()];
for (int i = 0; i < parameterTypes.size(); i++) {
Type parameterType = parameterTypes.get(i);
parameterTypesStr[i] = parameterType.name().toString();
if (typesUtil.isAssignable(Exception.class, parameterType.name())) {
parameterTypeHandles[i] = toResponse.getMethodParam(i);
} else {
parameterTypeHandles[i] = toResponse.readInstanceField(parameterTypeToField.get(parameterType),
toResponse.getThis());
}
}
return toResponse.invokeVirtualMethod(
MethodDescriptor.ofMethod(declaringClassName, controllerAdviceMethod.name(), returnTypeClassName,
parameterTypesStr),
controllerAdviceInstance(toResponse), parameterTypeHandles);
}
private ResultHandle controllerAdviceInstance(MethodCreator toResponse) {
ResultHandle controllerAdviceClass = toResponse.loadClass(declaringClassName);
ResultHandle container = toResponse
.invokeStaticMethod(MethodDescriptor.ofMethod(Arc.class, "container", ArcContainer.class));
ResultHandle instance = toResponse.invokeInterfaceMethod(
MethodDescriptor.ofMethod(ArcContainer.class, "instance", InstanceHandle.class, Class.class,
Annotation[].class),
container, controllerAdviceClass, toResponse.loadNull());
ResultHandle bean = toResponse.invokeInterfaceMethod(
MethodDescriptor.ofMethod(InstanceHandle.class, "get", Object.class),
instance);
return toResponse.checkCast(bean, controllerAdviceMethod.declaringClass().name().toString());
}
private int getAnnotationStatusOrDefault(int defaultValue) {
AnnotationInstance annotation = controllerAdviceMethod.annotation(RESPONSE_STATUS);
if (annotation == null) {
return defaultValue;
}
return getHttpStatusFromAnnotation(annotation);
}
private boolean isVoidType(Type type) {
return Type.Kind.VOID.equals(type.kind());
}
private boolean isPrimitiveType(Type type) {
return Type.Kind.PRIMITIVE.equals(type.kind());
}
private boolean isStringType(Type type) {
return DotName.createSimple(String.class.getName()).equals(type.name());
}
private boolean isEntityType(Type type) {
return RESPONSE_ENTITY.equals(type.name());
}
private boolean isParameterizedType(Type type) {
return Type.Kind.PARAMETERIZED_TYPE.equals(type.kind());
}
}
| 4,934 |
1,720 | #pragma once
#include <vector>
#include <unordered_map>
#include "Stream.h"
class CGameTestSheet
{
public:
enum ENVIRONMENT_ACTION_TYPE
{
ENVIRONMENT_ACTION_NONE,
ENVIRONMENT_ACTION_CREATE_DIRECTORY,
ENVIRONMENT_ACTION_CREATE_FILE,
};
struct ENVIRONMENT_ACTION
{
ENVIRONMENT_ACTION_TYPE type = ENVIRONMENT_ACTION_NONE;
std::string name;
uint32 size = 0;
};
typedef std::vector<ENVIRONMENT_ACTION> EnvironmentActionArray;
typedef EnvironmentActionArray ENVIRONMENT;
typedef std::unordered_map<uint32, ENVIRONMENT> EnvironmentMap;
typedef std::vector<std::string> EntryArray;
struct TEST
{
std::string query;
uint32 environmentId = 0;
int32 maxEntries = 0;
int32 result = 0;
std::string currentDirectory;
EntryArray entries;
};
typedef std::vector<TEST> TestArray;
CGameTestSheet();
CGameTestSheet(Framework::CStream&);
virtual ~CGameTestSheet();
ENVIRONMENT GetEnvironment(uint32) const;
const TestArray& GetTests() const;
private:
void ParseSheet(Framework::CStream&);
EnvironmentMap m_environments;
TestArray m_tests;
};
| 419 |
1,538 | // Lean compiler output
// Module: Lean.Elab.Exception
// Imports: Init Lean.InternalExceptionId Lean.Meta.Basic
#include <lean/lean.h>
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wunused-parameter"
#pragma clang diagnostic ignored "-Wunused-label"
#elif defined(__GNUC__) && !defined(__CLANG__)
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-label"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
#ifdef __cplusplus
extern "C" {
#endif
lean_object* l_Lean_stringToMessageData(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_throwPostpone___rarg(lean_object*);
lean_object* lean_name_mk_string(lean_object*, lean_object*);
LEAN_EXPORT uint8_t l_Lean_Elab_isAbortExceptionId(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortTactic(lean_object*, lean_object*);
static lean_object* l_Lean_Elab_throwUnsupportedSyntax___rarg___closed__1;
LEAN_EXPORT lean_object* l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___boxed(lean_object*);
static lean_object* l_Lean_Elab_mkMessageCore___closed__1;
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortTactic___rarg(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_autoBoundImplicitExceptionId;
LEAN_EXPORT lean_object* l_Lean_Elab_throwUnsupportedSyntax___rarg(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_abortCommandExceptionId;
static lean_object* l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__2;
static lean_object* l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__3;
LEAN_EXPORT lean_object* l_Lean_Elab_isAbortExceptionId___boxed(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_throwIllFormedSyntax___rarg(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32_(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4_(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18_(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60_(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74_(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46_(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_throwPostpone(lean_object*, lean_object*);
static lean_object* l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__1;
static lean_object* l_Lean_Elab_throwAbortCommand___rarg___closed__1;
LEAN_EXPORT lean_object* l_Lean_Elab_throwAutoBoundImplicitLocal___rarg(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_mkMessageCore___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_throwAutoBoundImplicitLocal(lean_object*, lean_object*);
uint8_t lean_nat_dec_eq(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortTerm___rarg(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_mkMessageCore(lean_object*, lean_object*, lean_object*, uint8_t, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortCommand(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_abortTacticExceptionId;
lean_object* l_Lean_KVMap_getName(lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Elab_throwIllFormedSyntax___rarg___closed__1;
LEAN_EXPORT lean_object* l_Lean_Elab_abortTermExceptionId;
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__1;
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__2;
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__2;
lean_object* l_Lean_FileMap_toPosition(lean_object*, lean_object*);
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__1;
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__1;
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortCommand___rarg(lean_object*);
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__1;
static lean_object* l_Lean_Elab_throwAbortTerm___rarg___closed__1;
lean_object* l_Lean_registerInternalExceptionId(lean_object*, lean_object*);
static lean_object* l_Lean_Elab_throwIllFormedSyntax___rarg___closed__2;
static lean_object* l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__1;
LEAN_EXPORT lean_object* l_Lean_Elab_isAutoBoundImplicitLocalException_x3f(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_postponeExceptionId;
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__2;
static lean_object* l_Lean_Elab_throwPostpone___rarg___closed__1;
static lean_object* l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__1;
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__2;
extern lean_object* l_Lean_KVMap_empty;
static lean_object* l_Lean_Elab_throwAbortTactic___rarg___closed__1;
LEAN_EXPORT lean_object* l_Lean_Elab_throwUnsupportedSyntax(lean_object*, lean_object*);
lean_object* l_Lean_KVMap_insertCore(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_throwIllFormedSyntax(lean_object*, lean_object*);
static lean_object* l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__2;
lean_object* l_Lean_throwError___rarg(lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__4;
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__1;
LEAN_EXPORT lean_object* l_Lean_Elab_unsupportedSyntaxExceptionId;
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__1;
static lean_object* l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__2;
LEAN_EXPORT uint8_t l_Lean_Elab_isAbortTacticException(lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_isAbortTacticException___boxed(lean_object*);
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__2;
LEAN_EXPORT lean_object* l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg(lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortTerm(lean_object*, lean_object*);
static lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__2;
LEAN_EXPORT lean_object* l_Lean_Elab_throwAlreadyDeclaredUniverseLevel(lean_object*, lean_object*);
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("postpone");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4_(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3;
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__2;
x_3 = l_Lean_registerInternalExceptionId(x_2, x_1);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("unsupportedSyntax");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18_(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3;
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__2;
x_3 = l_Lean_registerInternalExceptionId(x_2, x_1);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("abortCommandElab");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32_(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3;
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__2;
x_3 = l_Lean_registerInternalExceptionId(x_2, x_1);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("abortTermElab");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46_(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3;
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__2;
x_3 = l_Lean_registerInternalExceptionId(x_2, x_1);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("abortTactic");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60_(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3;
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__2;
x_3 = l_Lean_registerInternalExceptionId(x_2, x_1);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("autoBoundImplicit");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74_(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3;
x_2 = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__2;
x_3 = l_Lean_registerInternalExceptionId(x_2, x_1);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_throwPostpone___rarg___closed__1() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_postponeExceptionId;
x_3 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_3, 0, x_2);
lean_ctor_set(x_3, 1, x_1);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwPostpone___rarg(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3; lean_object* x_4;
x_2 = lean_ctor_get(x_1, 0);
lean_inc(x_2);
lean_dec(x_1);
x_3 = l_Lean_Elab_throwPostpone___rarg___closed__1;
x_4 = lean_apply_2(x_2, lean_box(0), x_3);
return x_4;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwPostpone(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_Lean_Elab_throwPostpone___rarg), 1, 0);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_throwUnsupportedSyntax___rarg___closed__1() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_unsupportedSyntaxExceptionId;
x_3 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_3, 0, x_2);
lean_ctor_set(x_3, 1, x_1);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwUnsupportedSyntax___rarg(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3; lean_object* x_4;
x_2 = lean_ctor_get(x_1, 0);
lean_inc(x_2);
lean_dec(x_1);
x_3 = l_Lean_Elab_throwUnsupportedSyntax___rarg___closed__1;
x_4 = lean_apply_2(x_2, lean_box(0), x_3);
return x_4;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwUnsupportedSyntax(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_Lean_Elab_throwUnsupportedSyntax___rarg), 1, 0);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_throwIllFormedSyntax___rarg___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("ill-formed syntax");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_throwIllFormedSyntax___rarg___closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2;
x_1 = l_Lean_Elab_throwIllFormedSyntax___rarg___closed__1;
x_2 = l_Lean_stringToMessageData(x_1);
return x_2;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwIllFormedSyntax___rarg(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3; lean_object* x_4;
x_3 = l_Lean_Elab_throwIllFormedSyntax___rarg___closed__2;
x_4 = l_Lean_throwError___rarg(x_1, x_2, x_3);
return x_4;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwIllFormedSyntax(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_Lean_Elab_throwIllFormedSyntax___rarg), 2, 0);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("localId");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAutoBoundImplicitLocal___rarg(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3; lean_object* x_4; lean_object* x_5; lean_object* x_6; lean_object* x_7; lean_object* x_8; lean_object* x_9; lean_object* x_10;
x_3 = lean_alloc_ctor(2, 1, 0);
lean_ctor_set(x_3, 0, x_2);
x_4 = l_Lean_KVMap_empty;
x_5 = l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__2;
x_6 = l_Lean_KVMap_insertCore(x_4, x_5, x_3);
x_7 = l_Lean_Elab_autoBoundImplicitExceptionId;
x_8 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_8, 0, x_7);
lean_ctor_set(x_8, 1, x_6);
x_9 = lean_ctor_get(x_1, 0);
lean_inc(x_9);
lean_dec(x_1);
x_10 = lean_apply_2(x_9, lean_box(0), x_8);
return x_10;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAutoBoundImplicitLocal(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_Lean_Elab_throwAutoBoundImplicitLocal___rarg), 2, 0);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("x");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_isAutoBoundImplicitLocalException_x3f(lean_object* x_1) {
_start:
{
if (lean_obj_tag(x_1) == 0)
{
lean_object* x_2;
x_2 = lean_box(0);
return x_2;
}
else
{
lean_object* x_3; lean_object* x_4; lean_object* x_5; uint8_t x_6;
x_3 = lean_ctor_get(x_1, 0);
x_4 = lean_ctor_get(x_1, 1);
x_5 = l_Lean_Elab_autoBoundImplicitExceptionId;
x_6 = lean_nat_dec_eq(x_3, x_5);
if (x_6 == 0)
{
lean_object* x_7;
x_7 = lean_box(0);
return x_7;
}
else
{
lean_object* x_8; lean_object* x_9; lean_object* x_10; lean_object* x_11;
x_8 = l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__2;
x_9 = l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__2;
x_10 = l_Lean_KVMap_getName(x_4, x_8, x_9);
x_11 = lean_alloc_ctor(1, 1, 0);
lean_ctor_set(x_11, 0, x_10);
return x_11;
}
}
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___boxed(lean_object* x_1) {
_start:
{
lean_object* x_2;
x_2 = l_Lean_Elab_isAutoBoundImplicitLocalException_x3f(x_1);
lean_dec(x_1);
return x_2;
}
}
static lean_object* _init_l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("a universe level named '");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2;
x_1 = l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__1;
x_2 = l_Lean_stringToMessageData(x_1);
return x_2;
}
}
static lean_object* _init_l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__3() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("' has already been declared");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__4() {
_start:
{
lean_object* x_1; lean_object* x_2;
x_1 = l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__3;
x_2 = l_Lean_stringToMessageData(x_1);
return x_2;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg(lean_object* x_1, lean_object* x_2, lean_object* x_3) {
_start:
{
lean_object* x_4; lean_object* x_5; lean_object* x_6; lean_object* x_7; lean_object* x_8; lean_object* x_9;
x_4 = lean_alloc_ctor(4, 1, 0);
lean_ctor_set(x_4, 0, x_3);
x_5 = l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__2;
x_6 = lean_alloc_ctor(10, 2, 0);
lean_ctor_set(x_6, 0, x_5);
lean_ctor_set(x_6, 1, x_4);
x_7 = l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__4;
x_8 = lean_alloc_ctor(10, 2, 0);
lean_ctor_set(x_8, 0, x_6);
lean_ctor_set(x_8, 1, x_7);
x_9 = l_Lean_throwError___rarg(x_1, x_2, x_8);
return x_9;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAlreadyDeclaredUniverseLevel(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg), 3, 0);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_throwAbortCommand___rarg___closed__1() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_abortCommandExceptionId;
x_3 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_3, 0, x_2);
lean_ctor_set(x_3, 1, x_1);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortCommand___rarg(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3; lean_object* x_4;
x_2 = lean_ctor_get(x_1, 0);
lean_inc(x_2);
lean_dec(x_1);
x_3 = l_Lean_Elab_throwAbortCommand___rarg___closed__1;
x_4 = lean_apply_2(x_2, lean_box(0), x_3);
return x_4;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortCommand(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_Lean_Elab_throwAbortCommand___rarg), 1, 0);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_throwAbortTerm___rarg___closed__1() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_abortTermExceptionId;
x_3 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_3, 0, x_2);
lean_ctor_set(x_3, 1, x_1);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortTerm___rarg(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3; lean_object* x_4;
x_2 = lean_ctor_get(x_1, 0);
lean_inc(x_2);
lean_dec(x_1);
x_3 = l_Lean_Elab_throwAbortTerm___rarg___closed__1;
x_4 = lean_apply_2(x_2, lean_box(0), x_3);
return x_4;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortTerm(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_Lean_Elab_throwAbortTerm___rarg), 1, 0);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_throwAbortTactic___rarg___closed__1() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Elab_abortTacticExceptionId;
x_3 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_3, 0, x_2);
lean_ctor_set(x_3, 1, x_1);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortTactic___rarg(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3; lean_object* x_4;
x_2 = lean_ctor_get(x_1, 0);
lean_inc(x_2);
lean_dec(x_1);
x_3 = l_Lean_Elab_throwAbortTactic___rarg___closed__1;
x_4 = lean_apply_2(x_2, lean_box(0), x_3);
return x_4;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_throwAbortTactic(lean_object* x_1, lean_object* x_2) {
_start:
{
lean_object* x_3;
x_3 = lean_alloc_closure((void*)(l_Lean_Elab_throwAbortTactic___rarg), 1, 0);
return x_3;
}
}
LEAN_EXPORT uint8_t l_Lean_Elab_isAbortTacticException(lean_object* x_1) {
_start:
{
if (lean_obj_tag(x_1) == 0)
{
uint8_t x_2;
x_2 = 0;
return x_2;
}
else
{
lean_object* x_3; lean_object* x_4; uint8_t x_5;
x_3 = lean_ctor_get(x_1, 0);
x_4 = l_Lean_Elab_abortTacticExceptionId;
x_5 = lean_nat_dec_eq(x_3, x_4);
return x_5;
}
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_isAbortTacticException___boxed(lean_object* x_1) {
_start:
{
uint8_t x_2; lean_object* x_3;
x_2 = l_Lean_Elab_isAbortTacticException(x_1);
lean_dec(x_1);
x_3 = lean_box(x_2);
return x_3;
}
}
LEAN_EXPORT uint8_t l_Lean_Elab_isAbortExceptionId(lean_object* x_1) {
_start:
{
lean_object* x_2; uint8_t x_3;
x_2 = l_Lean_Elab_abortCommandExceptionId;
x_3 = lean_nat_dec_eq(x_1, x_2);
if (x_3 == 0)
{
lean_object* x_4; uint8_t x_5;
x_4 = l_Lean_Elab_abortTermExceptionId;
x_5 = lean_nat_dec_eq(x_1, x_4);
if (x_5 == 0)
{
lean_object* x_6; uint8_t x_7;
x_6 = l_Lean_Elab_abortTacticExceptionId;
x_7 = lean_nat_dec_eq(x_1, x_6);
return x_7;
}
else
{
uint8_t x_8;
x_8 = 1;
return x_8;
}
}
else
{
uint8_t x_9;
x_9 = 1;
return x_9;
}
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_isAbortExceptionId___boxed(lean_object* x_1) {
_start:
{
uint8_t x_2; lean_object* x_3;
x_2 = l_Lean_Elab_isAbortExceptionId(x_1);
lean_dec(x_1);
x_3 = lean_box(x_2);
return x_3;
}
}
static lean_object* _init_l_Lean_Elab_mkMessageCore___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("");
return x_1;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_mkMessageCore(lean_object* x_1, lean_object* x_2, lean_object* x_3, uint8_t x_4, lean_object* x_5) {
_start:
{
lean_object* x_6; lean_object* x_7; lean_object* x_8; lean_object* x_9;
x_6 = l_Lean_FileMap_toPosition(x_2, x_5);
x_7 = lean_box(0);
x_8 = l_Lean_Elab_mkMessageCore___closed__1;
x_9 = lean_alloc_ctor(0, 5, 1);
lean_ctor_set(x_9, 0, x_1);
lean_ctor_set(x_9, 1, x_6);
lean_ctor_set(x_9, 2, x_7);
lean_ctor_set(x_9, 3, x_8);
lean_ctor_set(x_9, 4, x_3);
lean_ctor_set_uint8(x_9, sizeof(void*)*5, x_4);
return x_9;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_mkMessageCore___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) {
_start:
{
uint8_t x_6; lean_object* x_7;
x_6 = lean_unbox(x_4);
lean_dec(x_4);
x_7 = l_Lean_Elab_mkMessageCore(x_1, x_2, x_3, x_6, x_5);
lean_dec(x_5);
lean_dec(x_2);
return x_7;
}
}
lean_object* initialize_Init(lean_object*);
lean_object* initialize_Lean_InternalExceptionId(lean_object*);
lean_object* initialize_Lean_Meta_Basic(lean_object*);
static bool _G_initialized = false;
LEAN_EXPORT lean_object* initialize_Lean_Elab_Exception(lean_object* w) {
lean_object * res;
if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));
_G_initialized = true;
res = initialize_Init(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_InternalExceptionId(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Meta_Basic(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__1 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__1();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__1);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__2 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__2();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4____closed__2);
res = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_4_(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
l_Lean_Elab_postponeExceptionId = lean_io_result_get_value(res);
lean_mark_persistent(l_Lean_Elab_postponeExceptionId);
lean_dec_ref(res);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__1 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__1();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__1);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__2 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__2();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18____closed__2);
res = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_18_(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
l_Lean_Elab_unsupportedSyntaxExceptionId = lean_io_result_get_value(res);
lean_mark_persistent(l_Lean_Elab_unsupportedSyntaxExceptionId);
lean_dec_ref(res);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__1 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__1();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__1);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__2 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__2();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32____closed__2);
res = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_32_(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
l_Lean_Elab_abortCommandExceptionId = lean_io_result_get_value(res);
lean_mark_persistent(l_Lean_Elab_abortCommandExceptionId);
lean_dec_ref(res);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__1 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__1();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__1);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__2 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__2();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46____closed__2);
res = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_46_(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
l_Lean_Elab_abortTermExceptionId = lean_io_result_get_value(res);
lean_mark_persistent(l_Lean_Elab_abortTermExceptionId);
lean_dec_ref(res);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__1 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__1();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__1);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__2 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__2();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60____closed__2);
res = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_60_(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
l_Lean_Elab_abortTacticExceptionId = lean_io_result_get_value(res);
lean_mark_persistent(l_Lean_Elab_abortTacticExceptionId);
lean_dec_ref(res);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__1 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__1();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__1);
l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__2 = _init_l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__2();
lean_mark_persistent(l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74____closed__2);
res = l_Lean_Elab_initFn____x40_Lean_Elab_Exception___hyg_74_(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
l_Lean_Elab_autoBoundImplicitExceptionId = lean_io_result_get_value(res);
lean_mark_persistent(l_Lean_Elab_autoBoundImplicitExceptionId);
lean_dec_ref(res);
l_Lean_Elab_throwPostpone___rarg___closed__1 = _init_l_Lean_Elab_throwPostpone___rarg___closed__1();
lean_mark_persistent(l_Lean_Elab_throwPostpone___rarg___closed__1);
l_Lean_Elab_throwUnsupportedSyntax___rarg___closed__1 = _init_l_Lean_Elab_throwUnsupportedSyntax___rarg___closed__1();
lean_mark_persistent(l_Lean_Elab_throwUnsupportedSyntax___rarg___closed__1);
l_Lean_Elab_throwIllFormedSyntax___rarg___closed__1 = _init_l_Lean_Elab_throwIllFormedSyntax___rarg___closed__1();
lean_mark_persistent(l_Lean_Elab_throwIllFormedSyntax___rarg___closed__1);
l_Lean_Elab_throwIllFormedSyntax___rarg___closed__2 = _init_l_Lean_Elab_throwIllFormedSyntax___rarg___closed__2();
lean_mark_persistent(l_Lean_Elab_throwIllFormedSyntax___rarg___closed__2);
l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__1 = _init_l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__1();
lean_mark_persistent(l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__1);
l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__2 = _init_l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__2();
lean_mark_persistent(l_Lean_Elab_throwAutoBoundImplicitLocal___rarg___closed__2);
l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__1 = _init_l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__1();
lean_mark_persistent(l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__1);
l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__2 = _init_l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__2();
lean_mark_persistent(l_Lean_Elab_isAutoBoundImplicitLocalException_x3f___closed__2);
l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__1 = _init_l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__1();
lean_mark_persistent(l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__1);
l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__2 = _init_l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__2();
lean_mark_persistent(l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__2);
l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__3 = _init_l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__3();
lean_mark_persistent(l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__3);
l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__4 = _init_l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__4();
lean_mark_persistent(l_Lean_Elab_throwAlreadyDeclaredUniverseLevel___rarg___closed__4);
l_Lean_Elab_throwAbortCommand___rarg___closed__1 = _init_l_Lean_Elab_throwAbortCommand___rarg___closed__1();
lean_mark_persistent(l_Lean_Elab_throwAbortCommand___rarg___closed__1);
l_Lean_Elab_throwAbortTerm___rarg___closed__1 = _init_l_Lean_Elab_throwAbortTerm___rarg___closed__1();
lean_mark_persistent(l_Lean_Elab_throwAbortTerm___rarg___closed__1);
l_Lean_Elab_throwAbortTactic___rarg___closed__1 = _init_l_Lean_Elab_throwAbortTactic___rarg___closed__1();
lean_mark_persistent(l_Lean_Elab_throwAbortTactic___rarg___closed__1);
l_Lean_Elab_mkMessageCore___closed__1 = _init_l_Lean_Elab_mkMessageCore___closed__1();
lean_mark_persistent(l_Lean_Elab_mkMessageCore___closed__1);
return lean_io_result_mk_ok(lean_box(0));
}
#ifdef __cplusplus
}
#endif
| 13,921 |
318 | <gh_stars>100-1000
from flask import jsonify, request
from flask_login import current_user
from app.models import *
from app.util.case_change.core import HarParser
from . import api, login_required
from ..util.http_run import RunCase
from ..util.utils import *
@api.route('/apiMsg/add', methods=['POST'])
@login_required
def add_api_msg():
""" 接口信息增加、编辑 """
data = request.json
project_id = data.get('projectId')
api_msg_name = data.get('apiMsgName')
variable_type = data.get('variableType')
desc = data.get('desc')
header = data.get('header')
extract = data.get('extract')
validate = data.get('validate')
api_msg_id = data.get('apiMsgId')
up_func = data.get('upFunc')
down_func = data.get('downFunc')
method = data.get('method')
module_id = data.get('moduleId')
url = data.get('url').split('?')[0]
skip = data.get('skip')
status_url = data.get('choiceUrl')
variable = data.get('variable')
json_variable = data.get('jsonVariable')
param = data.get('param')
if not project_id:
return jsonify({'msg': '项目不能为空', 'status': 0})
if not module_id:
return jsonify({'msg': '接口模块不能为空', 'status': 0})
if not api_msg_name:
return jsonify({'msg': '接口名称不能为空', 'status': 0})
if method == -1:
return jsonify({'msg': '请求方式不能为空', 'status': 0})
if not url:
return jsonify({'msg': '接口url不能为空', 'status': 0})
if status_url == -1:
if 'http' not in url:
return jsonify({'msg': '基础url为空时,请补全api地址', 'status': 0})
num = auto_num(data.get('num'), ApiMsg, module_id=module_id)
if api_msg_id:
old_data = ApiMsg.query.filter_by(id=api_msg_id).first()
old_num = old_data.num
if ApiMsg.query.filter_by(name=api_msg_name, module_id=module_id).first() and api_msg_name != old_data.name:
return jsonify({'msg': '接口名字重复', 'status': 0})
list_data = Module.query.filter_by(id=module_id).first().api_msg.all()
num_sort(num, old_num, list_data, old_data)
old_data.project_id = project_id
old_data.name = api_msg_name
old_data.validate = validate
old_data.up_func = up_func
old_data.down_func = down_func
old_data.desc = desc
old_data.status_url = status_url
old_data.variable_type = variable_type
old_data.method = method
old_data.url = url
old_data.skip = skip
old_data.header = header
old_data.variable = variable
old_data.json_variable = json_variable
old_data.param = param
old_data.extract = extract
old_data.module_id = module_id
db.session.commit()
return jsonify({'msg': '修改成功', 'status': 1, 'api_msg_id': api_msg_id, 'num': num})
else:
if ApiMsg.query.filter_by(name=api_msg_name, module_id=module_id).first():
return jsonify({'msg': '接口名字重复', 'status': 0})
else:
new_cases = ApiMsg(name=api_msg_name,
num=num,
header=header,
up_func=up_func,
down_func=down_func,
url=url,
skip=skip,
desc=desc,
param=param,
method=method,
variable=variable,
validate=validate,
project_id=project_id,
module_id=module_id,
status_url=status_url,
variable_type=variable_type,
json_variable=json_variable,
extract=extract, )
db.session.add(new_cases)
db.session.commit()
return jsonify({'msg': '新建成功', 'status': 1, 'api_msg_id': new_cases.id, 'num': new_cases.num})
@api.route('/apiMsg/editAndCopy', methods=['POST'])
@login_required
def edit_api_msg():
""" 返回待编辑或复制的接口信息 """
data = request.json
case_id = data.get('apiMsgId')
_edit = ApiMsg.query.filter_by(id=case_id).first()
_data = {'name': _edit.name, 'num': _edit.num, 'desc': _edit.desc, 'url': _edit.url, 'skip': _edit.skip,
'method': _edit.method, 'status_url': int(_edit.status_url),
'up_func': _edit.up_func, 'down_func': _edit.down_func,
'variableType': _edit.variable_type,
'param': json.loads(_edit.param),
'header': json.loads(_edit.header),
'variable': json.loads(_edit.variable),
'json_variable': _edit.json_variable,
'extract': json.loads(_edit.extract),
'validate': json.loads(_edit.validate)}
return jsonify({'data': _data, 'status': 1})
@api.route('/apiMsg/run', methods=['POST'])
@login_required
def run_api_msg():
""" 跑接口信息 """
data = request.json
api_msg_data = data.get('apiMsgData')
project_id = data.get('projectId')
config_id = data.get('configId')
if not api_msg_data:
return jsonify({'msg': '请勾选信息后,再进行测试', 'status': 0})
# 前端传入的数据不是按照编号来的,所以这里重新排序
api_ids = [(item['num'], item['apiMsgId']) for item in api_msg_data]
api_ids.sort(key=lambda x: x[0])
# api_data = [ApiMsg.query.filter_by(id=c[1]).first() for c in api_ids]
api_ids = [c[1] for c in api_ids]
d = RunCase(project_id)
d.get_api_test(api_ids, config_id)
res = json.loads(d.run_case())
return jsonify({'msg': '测试完成', 'data': res, 'status': 1})
@api.route('/apiMsg/find', methods=['POST'])
@login_required
def find_api_msg():
""" 查接口信息 """
data = request.json
module_id = data.get('moduleId')
project_id = data.get('projectId')
api_name = data.get('apiName')
page = data.get('page') if data.get('page') else 1
per_page = data.get('sizePage') if data.get('sizePage') else 20
if not project_id:
return jsonify({'msg': '请选择项目', 'status': 0})
if not module_id:
return jsonify({'msg': '请先在当前项目下创建模块', 'status': 0})
if api_name:
_data = ApiMsg.query.filter_by(module_id=module_id).filter(ApiMsg.name.like('%{}%'.format(api_name)))
# total = len(api_data)
if not _data:
return jsonify({'msg': '没有该接口信息', 'status': 0})
else:
_data = ApiMsg.query.filter_by(module_id=module_id)
pagination = _data.order_by(ApiMsg.num.asc()).paginate(page, per_page=per_page, error_out=False)
items = pagination.items
total = pagination.total
end_data = [{'num': c.num,
'name': c.name,
'desc': c.desc,
'url': c.url,
'skip': c.skip,
'apiMsgId': c.id,
'gather_id': c.module_id,
'variableType': c.variable_type,
'variable': json.loads(c.variable),
'json_variable': c.json_variable,
'extract': json.loads(c.extract),
'validate': json.loads(c.validate),
'param': json.loads(c.param),
'header': json.loads(c.header),
# 'check': False,
'statusCase': {'extract': [True, True], 'variable': [True, True],
'validate': [True, True], 'param': [True, True], 'header': [True, True]},
'status': True, 'case_name': c.name, 'down_func': c.down_func, 'up_func': c.up_func, 'time': 1}
for c in items]
return jsonify({'data': end_data, 'total': total, 'status': 1})
@api.route('/apiMsg/del', methods=['POST'])
@login_required
def del_api_msg():
""" 删除接口信息 """
data = request.json
api_msg_id = data.get('apiMsgId')
_data = ApiMsg.query.filter_by(id=api_msg_id).first()
project_id = Module.query.filter_by(id=_data.module_id).first().project_id
if current_user.id != Project.query.filter_by(id=project_id).first().user_id:
return jsonify({'msg': '不能删除别人项目下的接口', 'status': 0})
# 同步删除接口信息下对应用例下的接口步骤信息
for d in CaseData.query.filter_by(api_msg_id=api_msg_id).all():
db.session.delete(d)
db.session.delete(_data)
db.session.commit()
return jsonify({'msg': '删除成功', 'status': 1})
@api.route('/apiMsg/fileChange', methods=['POST'])
@login_required
def file_change():
""" 导入接口信息 """
# 导入功能太过简单,所以前端屏蔽了111
data = request.json
project_name = data.get('projectName')
module_id = data.get('moduleId')
if not module_id and not project_name:
return jsonify({'msg': '项目和模块不能为空', 'status': 0})
import_format = data.get('importFormat')
if not import_format:
return jsonify({'msg': '请选择文件格式', 'status': 0})
import_format = 'har' if import_format == 'HAR' else 'json'
project_data = Project.query.filter_by(name=project_name).first()
host = json.loads(project_data.host)
import_api_address = data.get('importApiAddress')
if not import_api_address:
return jsonify({'msg': '请上传文件', 'status': 0})
har_parser = HarParser(import_api_address, import_format)
case_num = auto_num(data.get('caseNum'), ApiMsg, module_id=module_id)
for msg in har_parser.testset:
# status_url = msg['test']['url'].replace(msg['test']['name'], '')
# msg['test']['url'] = msg['test']['name']
# print(msg['test']['status_url'])
for h in host:
if msg['status_url'] in h:
msg['status_url'] = host.index(h)
break
else:
msg['status_url'] = '0'
new_case = ApiMsg(project_id=project_data.id, module_id=module_id, num=case_num, **msg)
db.session.add(new_case)
db.session.commit()
case_num += 1
return jsonify({'msg': '导入成功', 'status': 1})
| 5,194 |
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.db.dataview.table.celleditor;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.*;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.EventObject;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import org.netbeans.api.progress.ProgressUtils;
import org.netbeans.modules.db.dataview.util.CharsetSelector;
import org.netbeans.modules.db.dataview.util.EncodingHelper;
import org.netbeans.modules.db.dataview.util.FileBackedBlob;
import org.netbeans.modules.db.dataview.util.LobHelper;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.cookies.OpenCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileSystem;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.WindowManager;
public class BlobFieldTableCellEditor extends AbstractCellEditor
implements TableCellEditor,
ActionListener, AlwaysEnable {
private static final Logger LOG = Logger.getLogger(
BlobFieldTableCellEditor.class.getName());
private static final String EDIT = "edit";
private static File lastFile;
private static Charset lastSelectedCharset = Charset.defaultCharset();
private Blob currentValue;
private JButton button;
private JPopupMenu popup;
private JTable table;
private int currentRow;
private int currentColumn;
private int currentModelColumn;
private int currentModelRow;
private JMenuItem saveContentMenuItem;
private JMenuItem miOpenImageMenuItem;
private JMenuItem miOpenAsTextMenuItem;
private JMenuItem miLobLoadAction;
private JMenuItem miLobNullAction;
@SuppressWarnings("LeakingThisInConstructor")
public BlobFieldTableCellEditor() {
button = new JButton();
button.setActionCommand(EDIT);
button.addActionListener(this);
button.setContentAreaFilled(false);
button.setOpaque(false);
button.setBorderPainted(false);
button.setRolloverEnabled(false);
button.setAlignmentX(0);
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setFont(new Font(button.getFont().getFamily(), Font.ITALIC, 9));
popup = new JPopupMenu();
miOpenImageMenuItem = new JMenuItem("Open as Image");
miOpenImageMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openAsImage(currentValue);
fireEditingCanceled();
}
});
popup.add(miOpenImageMenuItem);
miOpenAsTextMenuItem = new JMenuItem("Open as Text");
miOpenAsTextMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openAsText();
fireEditingCanceled();
}
});
popup.add(miOpenAsTextMenuItem);
popup.addSeparator();
saveContentMenuItem = new JMenuItem(NbBundle.getMessage(BlobFieldTableCellEditor.class, "saveLob.title"));
saveContentMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveLobToFile(currentValue);
fireEditingCanceled();
}
});
popup.add(saveContentMenuItem);
miLobLoadAction = new JMenuItem(NbBundle.getMessage(BlobFieldTableCellEditor.class, "loadLob.title"));
miLobLoadAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object newValue = loadLobFromFile();
if (newValue != null) {
currentValue = (Blob) newValue;
}
fireEditingStopped();
}
});
popup.add(miLobLoadAction);
miLobNullAction = new JMenuItem(NbBundle.getMessage(BlobFieldTableCellEditor.class, "nullLob.title"));
miLobNullAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentValue = null;
fireEditingStopped();
}
});
popup.add(miLobNullAction);
}
@Override
public void actionPerformed(ActionEvent e) {
if (EDIT.equals(e.getActionCommand())) {
popup.show(button, 0, button.getHeight());
}
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
currentValue = (java.sql.Blob) value;
int modelRow = table.convertRowIndexToModel(row);
int modelColumn = table.convertColumnIndexToModel(column);
boolean editable = table.getModel().isCellEditable(modelRow, modelColumn);
if (currentValue != null) {
saveContentMenuItem.setEnabled(true);
miOpenImageMenuItem.setEnabled(true);
button.setText(LobHelper.blobToString(currentValue));
} else {
saveContentMenuItem.setEnabled(false);
miOpenImageMenuItem.setEnabled(false);
button.setText("<NULL>");
}
miLobLoadAction.setEnabled(editable);
miLobNullAction.setEnabled(editable);
this.table = table;
this.currentColumn = column;
this.currentRow = row;
this.currentModelColumn = table.convertColumnIndexToModel(column);
this.currentModelRow = table.convertRowIndexToModel(row);
return button;
}
@Override
public Object getCellEditorValue() {
return currentValue;
}
@Override
public boolean isCellEditable(EventObject anEvent) {
if (anEvent instanceof MouseEvent) {
return ((MouseEvent) anEvent).getClickCount() >= 2;
}
return super.isCellEditable(anEvent);
}
private void saveLobToFile(Blob b) {
if(b == null) {
return;
}
JFileChooser c = new JFileChooser();
c.setCurrentDirectory(lastFile);
int fileDialogState = c.showSaveDialog(table);
if (fileDialogState == JFileChooser.APPROVE_OPTION) {
File f = c.getSelectedFile();
lastFile = f;
InputStream is;
FileOutputStream fos;
try {
is = b.getBinaryStream();
fos = new FileOutputStream(f);
if(! doTransfer(is, fos, (int) b.length(), "Saving to file: " + f.toString())) {
f.delete();
}
} catch (IOException ex) {
LOG.log(Level.INFO, "IOError while saving BLOB to file", ex);
displayError(f, ex, false);
} catch (SQLException ex) {
LOG.log(Level.INFO, "SQLException while saving BLOB to file", ex);
displayError(f, ex, false);
}
}
}
private Blob loadLobFromFile() {
JFileChooser c = new JFileChooser();
c.setCurrentDirectory(lastFile);
Blob result = null;
int fileDialogState = c.showOpenDialog(table);
if (fileDialogState == JFileChooser.APPROVE_OPTION) {
File f = c.getSelectedFile();
lastFile = f;
FileInputStream fis;
try {
fis = new FileInputStream(f);
result = new FileBackedBlob();
if(! doTransfer(fis, result.setBinaryStream(1), (int) f.length(), "Loading file: " + f.toString())) {
result = null;
}
} catch (IOException ex) {
LOG.log(Level.INFO, "IOError while loading BLOB from file", ex);
displayError(f, ex, true);
result = null;
} catch (SQLException ex) {
LOG.log(Level.INFO, "SQLException while loading BLOB from file", ex);
displayError(f, ex, true);
result = null;
}
}
return result;
}
/**
* Note: The streams will be closed after this method was invoked
*
* @return true if transfer is complete and not interrupted
*/
private boolean doTransfer(InputStream is, OutputStream os, Integer size, String title) throws IOException {
MonitorableStreamTransfer ft = new MonitorableStreamTransfer(is, os, size);
Throwable t;
// Only show dialog, if the filesize is large enougth and has a use for the user
if (size == null || size > (1024 * 1024)) {
t = ProgressUtils.showProgressDialogAndRun(ft, title, false);
} else {
t = ft.run(null);
}
is.close();
os.close();
if (t != null && t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t != null && t instanceof IOException) {
throw (IOException) t;
} else if (t != null) {
throw new RuntimeException(t);
}
return !ft.isCancel();
}
private void displayError(File f, Exception ex, boolean read) {
DialogDisplayer dd = DialogDisplayer.getDefault();
String errorObjectMsg;
String messageMsg;
String titleMsg;
if (ex instanceof SQLException) {
errorObjectMsg = NbBundle.getMessage(BlobFieldTableCellEditor.class,
"lobErrorObject.database");
} else {
errorObjectMsg = NbBundle.getMessage(BlobFieldTableCellEditor.class,
"lobErrorObject.file");
}
if (!read) {
titleMsg = NbBundle.getMessage(BlobFieldTableCellEditor.class,
"blobSaveToFileError.title");
messageMsg = NbBundle.getMessage(BlobFieldTableCellEditor.class,
"blobSaveToFileError.message",
errorObjectMsg,
f.getAbsolutePath(),
ex.getLocalizedMessage());
} else {
titleMsg = NbBundle.getMessage(BlobFieldTableCellEditor.class,
"blobReadFromFileError.title");
messageMsg = NbBundle.getMessage(BlobFieldTableCellEditor.class,
"blobReadFromFileError.message",
errorObjectMsg,
f.getAbsolutePath(),
ex.getLocalizedMessage());
}
NotifyDescriptor nd = new NotifyDescriptor(
messageMsg,
titleMsg,
NotifyDescriptor.OK_CANCEL_OPTION,
NotifyDescriptor.WARNING_MESSAGE,
new Object[]{NotifyDescriptor.CANCEL_OPTION},
NotifyDescriptor.CANCEL_OPTION);
dd.notifyLater(nd);
}
private void openAsImage(Blob b) {
if (b == null) {
return;
}
try {
ImageInputStream iis = ImageIO.createImageInputStream(
b.getBinaryStream());
Iterator<ImageReader> irs = ImageIO.getImageReaders(iis);
if (irs.hasNext()) {
FileSystem fs = FileUtil.createMemoryFileSystem();
FileObject fob = fs.getRoot().createData(
Long.toString(System.currentTimeMillis()),
irs.next().getFormatName());
OutputStream os = fob.getOutputStream();
os.write(b.getBytes(1, (int) b.length()));
os.close();
DataObject data = DataObject.find(fob);
OpenCookie cookie = data.getLookup().lookup(OpenCookie.class);
if (cookie != null) {
cookie.open();
return;
}
}
displayErrorOpenImage("openImageErrorNotImage.message"); //NOI18N
} catch (SQLException ex) {
LOG.log(Level.INFO,
"SQLException while opening BLOB as file", ex); //NOI18N
displayErrorOpenImage("openImageErrorDB.message"); //NOI18N
} catch (IOException ex) {
LOG.log(Level.INFO, "IOError while opening BLOB as file", //NOI18N
ex);
}
}
private void displayErrorOpenImage(String messageProperty) {
DialogDisplayer dd = DialogDisplayer.getDefault();
String messageMsg = NbBundle.getMessage(BlobFieldTableCellEditor.class,
messageProperty);
String titleMsg = NbBundle.getMessage(BlobFieldTableCellEditor.class,
"openImageError.title"); //NOI18N
NotifyDescriptor nd = new NotifyDescriptor(
messageMsg,
titleMsg,
NotifyDescriptor.OK_CANCEL_OPTION,
NotifyDescriptor.WARNING_MESSAGE,
new Object[]{NotifyDescriptor.CANCEL_OPTION},
NotifyDescriptor.CANCEL_OPTION);
dd.notifyLater(nd);
}
protected void openAsText() {
GridBagConstraints gbc;
Charset detectedCharset = detectEncoding();
final CharsetSelector charsetSelector = new CharsetSelector();
charsetSelector.setSelectedItem(detectedCharset == null ? lastSelectedCharset : detectedCharset);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
final JTextArea textArea = new JTextArea(20, 80);
// Work around: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7100524
textArea.setDropTarget(null);
textArea.setText(getTextFromCurrentCell(charsetSelector.getSelectedItem()));
textArea.setCaretPosition(0);
textArea.setEditable(table.getModel().isCellEditable(currentModelRow, currentModelColumn));
JScrollPane pane = new JScrollPane(textArea);
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.BASELINE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weightx = 0d;
gbc.weighty = 0d;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JLabel("Charset-Encoding: "), gbc);
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.BASELINE;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weightx = 1d;
gbc.weighty = 0d;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(charsetSelector, gbc);
JButton reloadButton = new JButton("Reload");
reloadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText(getTextFromCurrentCell(charsetSelector.getSelectedItem()));
lastSelectedCharset = charsetSelector.getSelectedItem();
}
});
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weightx = 0d;
gbc.weighty = 0d;
gbc.fill = GridBagConstraints.NONE;
panel.add(reloadButton, gbc);
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weightx = 1d;
gbc.weighty = 1d;
gbc.fill = GridBagConstraints.BOTH;
panel.add(pane, gbc);
pane.addHierarchyListener(
new StringTableCellEditor.MakeResizableListener(panel));
Component parent = WindowManager.getDefault().getMainWindow();
if (table.isCellEditable(currentRow, currentColumn)) {
int result = JOptionPane.showOptionDialog(parent, panel, table.getColumnName(currentColumn), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
try {
table.setValueAt(new FileBackedBlob(
new ByteArrayInputStream(
textArea.getText().getBytes(charsetSelector.getSelectedItem()))),
currentRow, currentColumn);
lastSelectedCharset = charsetSelector.getSelectedItem();
} catch (SQLException ex) {
Exceptions.printStackTrace(ex);
}
}
} else {
JOptionPane.showMessageDialog(parent, panel, table.getColumnName(currentColumn), JOptionPane.PLAIN_MESSAGE, null);
}
}
private Charset detectEncoding() {
if(currentValue == null) {
return null;
}
InputStream blobStream = null;
try {
blobStream = currentValue.getBinaryStream();
BufferedInputStream inputStream = new BufferedInputStream(blobStream);
String charsetName = EncodingHelper.detectEncoding(inputStream);
Charset result = null;
if(charsetName != null) {
result = Charset.forName(charsetName);
}
return result;
} catch (SQLException | IOException ex) {
LOG.log(Level.FINE, "Failed to read BLOB contents.", ex);
} finally {
if (blobStream != null) {
try {
blobStream.close();
} catch (IOException ex) {
}
}
}
return null;
}
private String getTextFromCurrentCell(Charset charset) {
if(currentValue == null) {
return "";
}
InputStream blobStream = null;
try {
blobStream = currentValue.getBinaryStream();
Reader reader = new BufferedReader(
new InputStreamReader(blobStream, charset)
);
StringBuilder sb = new StringBuilder();
char[] buffer = new char[1024];
int read;
while((read = reader.read(buffer)) > 0) {
sb.append(buffer, 0, read);
}
return sb.toString();
} catch (SQLException | IOException ex) {
LOG.log(Level.FINE, "Failed to read BLOB contents.", ex);
} finally {
if(blobStream != null) {
try {
blobStream.close();
} catch (IOException ex) {
}
}
}
return "";
}
}
| 9,413 |
328 | <reponame>vanvught/rpidmx512
#if !defined(ORANGE_PI)
/**
* @file slushengine.cpp
*
*/
/*
* Based on https://github.com/Roboteurs/slushengine/tree/master/Slush
*/
/* Copyright (C) 2017-2020 by <NAME> mailto:<EMAIL>
*
* 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.
*/
#if defined (__linux__)
#include <cstdio>
#endif
#include <cassert>
#include "hal_spi.h"
#include "hal_gpio.h"
#include "slushmotor.h"
#include "slushboard.h"
#include "l6470constants.h"
#include "debug.h"
SlushMotor::SlushMotor(unsigned nMotor, bool bUseSPI): m_bIsBusy(false), m_bIsConnected(false) {
assert(nMotor <= 3);
m_nMotorNumber = nMotor;
m_bUseSpiBusy = bUseSPI;
switch (nMotor) {
case 0:
m_nSpiChipSelect = SLUSH_MTR0_CHIPSELECT;
m_nBusyPin = SLUSH_MTR0_BUSY;
break;
case 1:
m_nSpiChipSelect = SLUSH_MTR1_CHIPSELECT;
m_nBusyPin = SLUSH_MTR1_BUSY;
break;
case 2:
m_nSpiChipSelect = SLUSH_MTR2_CHIPSELECT;
m_nBusyPin = SLUSH_MTR2_BUSY;
break;
case 3:
m_nSpiChipSelect = SLUSH_MTR3_CHIPSELECT;
m_nBusyPin = SLUSH_MTR3_BUSY;
break;
default:
m_nSpiChipSelect = SLUSH_MTR0_CHIPSELECT;
m_nBusyPin = SLUSH_MTR0_BUSY;
break;
}
if (getParam(L6470_PARAM_CONFIG) == 0x2e88) {
#if defined (__linux__)
printf("Motor Drive Connected on GPIO %d\n", m_nSpiChipSelect);
#endif
setOverCurrent(2000);
setMicroSteps(16);
setCurrent(70, 90, 100, 100);
getStatus();
free();
m_bIsConnected = true;
} else {
#if defined (__linux__)
fprintf(stderr, "communication issues; check SPI configuration and cables\n");
#endif
}
}
SlushMotor::~SlushMotor(void) {
free();
m_bIsBusy = false;
m_bIsConnected = false;
}
int SlushMotor::busyCheck(void) {
if (m_bUseSpiBusy) {
if (getParam(L6470_PARAM_STATUS) & L6470_STATUS_BUSY) {
return 0;
} else {
return 1;
}
} else {
if (!m_bIsBusy) {
if (getParam(L6470_PARAM_STATUS) & L6470_STATUS_BUSY) {
return 0;
} else {
m_bIsBusy = true;
return 1;
}
}
// By default, the BUSY pin is forced low when the device is performing a command
if (FUNC_PREFIX(gpio_lev(m_nBusyPin)) == HIGH) {
m_bIsBusy = false;
return 0;
} else {
return 1;
}
}
}
uint8_t SlushMotor::SPIXfer(uint8_t data) {
char dataPacket[1];
dataPacket[0] = data;
FUNC_PREFIX(spi_chipSelect(SPI_CS_NONE));
FUNC_PREFIX(spi_set_speed_hz(4000000));
FUNC_PREFIX(spi_setDataMode(SPI_MODE3));
FUNC_PREFIX(gpio_clr(m_nSpiChipSelect));
FUNC_PREFIX(spi_transfern(dataPacket, 1));
FUNC_PREFIX(gpio_set(m_nSpiChipSelect));
return dataPacket[0];
}
/*
* Roboteurs Slushengine Phyton compatible methods
*/
int SlushMotor::isBusy(void) {
return busyCheck();
}
void SlushMotor::setAsHome(void) {
resetPos();
}
void SlushMotor::setOverCurrent(unsigned int nCurrentmA) {
uint8_t OCValue = nCurrentmA / 375;
if (OCValue > 0x0F) {
OCValue = 0x0F;
}
setParam(L6470_PARAM_OCD_TH, OCValue);
}
void SlushMotor::softFree(void) {
softHiZ();
}
void SlushMotor::free(void) {
hardHiZ();
}
/*
* Additional methods
*/
bool SlushMotor::IsConnected(void) const {
return m_bIsConnected;
}
bool SlushMotor::GetUseSpiBusy(void) const {
return m_bUseSpiBusy;
}
void SlushMotor::SetUseSpiBusy(bool bUseSpiBusy) {
m_bUseSpiBusy = bUseSpiBusy;
}
#endif
| 1,758 |
3,262 | <filename>angel-ps/core/src/main/java/com/tencent/angel/ps/server/data/request/UpdateOp.java
/*
* Tencent is pleased to support the open source community by making Angel available.
*
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. 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
*
* https://opensource.org/licenses/Apache-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.tencent.angel.ps.server.data.request;
import java.util.HashMap;
import java.util.Map;
public enum UpdateOp {
PLUS(1), REPLACE(2);
public static Map<Integer, UpdateOp> typeIdToTypeMap;
static {
typeIdToTypeMap = new HashMap<>();
typeIdToTypeMap.put(PLUS.opId, PLUS);
typeIdToTypeMap.put(REPLACE.opId, REPLACE);
}
public static UpdateOp valueOf(int id) {
return typeIdToTypeMap.get(id);
}
private final int opId;
UpdateOp(int opId) {
this.opId = opId;
}
public int getOpId() {
return opId;
}
}
| 439 |
507 | package top.lrshuai.security.config.security;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Set;
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class SecurityUser implements UserDetails {
/**
* 密码
*/
private String password;
/**
* 用户名
*/
private String username;
/**
* 权限
*/
private Set<GrantedAuthority> authorities;
/**
* 自定义字段
*/
private String nickName;
public SecurityUser(String password, String username, Set<GrantedAuthority> authorities) {
this.password = password;
this.username = username;
this.authorities = authorities;
}
public SecurityUser(String password, String username, Set<GrantedAuthority> authorities, String nickName) {
this.password = password;
this.username = username;
this.authorities = authorities;
this.nickName = nickName;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
/**
* 账号是否失效
* @return
*/
@Override
public boolean isAccountNonExpired() {
return true;
}
/**
* 账号是否锁定
* @return
*/
@Override
public boolean isAccountNonLocked() {
return true;
}
/**
* 密码是否失效
* @return
*/
@Override
public boolean isCredentialsNonExpired() {
return true;
}
/**
* 是否可用
* @return
*/
@Override
public boolean isEnabled() {
return true;
}
}
| 817 |
511 | /*
* Copyright 2011-present <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.grammar.test;
import com.intellij.extapi.psi.StubBasedPsiElementBase;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.stubs.StubBase;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
/**
* @author gregsh
*/
public class StubTest {
public static class SimpleStub extends StubBase<PsiElement> {
protected SimpleStub(StubElement parent, IStubElementType elementType) {
super(parent, elementType);
}
}
public static class SimpleBase extends StubBasedPsiElementBase<SimpleStub> {
public SimpleBase(@NotNull SimpleStub stub,
@NotNull IStubElementType nodeType) {
super(stub, nodeType);
}
public SimpleBase(@NotNull ASTNode node) {
super(node);
}
}
public static class GenericBase<T extends StubElement> extends StubBasedPsiElementBase<T> {
public GenericBase(@NotNull T stub,
@NotNull IStubElementType nodeType) {
super(stub, nodeType);
}
public GenericBase(@NotNull ASTNode node) {
super(node);
}
public GenericBase(T stub, IElementType nodeType, ASTNode node) {
super(stub, nodeType, node);
}
}
}
| 676 |
648 | {"resourceType":"DataElement","id":"Claim.use","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00"},"url":"http://hl7.org/fhir/DataElement/Claim.use","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"path":"Claim.use","short":"complete | proposed | exploratory | other","definition":"Complete (Bill or Claim), Proposed (Pre-Authorization), Exploratory (Pre-determination).","min":0,"max":"1","type":[{"code":"code"}],"isSummary":true,"binding":{"strength":"required","description":"Complete, proposed, exploratory, other.","valueSetReference":{"reference":"http://hl7.org/fhir/ValueSet/claim-use-link"}}}]} | 180 |
335 | <reponame>Safal08/Hacktoberfest-1<filename>E/Eldest_adjective.json
{
"word": "Eldest",
"definitions": [
"(of one out of a group of related or otherwise associated people) of the greatest age; oldest."
],
"parts-of-speech": "Adjective"
} | 105 |
460 | /*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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.
*/
#ifndef AccessibilityRenderObject_h
#define AccessibilityRenderObject_h
#include "AccessibilityObject.h"
namespace WebCore {
class AXObjectCache;
class Element;
class Frame;
class FrameView;
class HitTestResult;
class HTMLAnchorElement;
class HTMLAreaElement;
class HTMLElement;
class HTMLLabelElement;
class HTMLMapElement;
class HTMLSelectElement;
class IntPoint;
class IntSize;
class Node;
class RenderObject;
class RenderListBox;
class RenderTextControl;
class RenderView;
class VisibleSelection;
class String;
class Widget;
class AccessibilityRenderObject : public AccessibilityObject {
protected:
AccessibilityRenderObject(RenderObject*);
public:
static PassRefPtr<AccessibilityRenderObject> create(RenderObject*);
virtual ~AccessibilityRenderObject();
bool isAccessibilityRenderObject() const { return true; }
virtual bool isAnchor() const;
virtual bool isAttachment() const;
virtual bool isHeading() const;
virtual bool isLink() const;
virtual bool isImageButton() const;
virtual bool isImage() const;
virtual bool isNativeImage() const;
virtual bool isPasswordField() const;
virtual bool isTextControl() const;
virtual bool isNativeTextControl() const;
virtual bool isWebArea() const;
virtual bool isCheckboxOrRadio() const;
virtual bool isFileUploadButton() const;
virtual bool isInputImage() const;
virtual bool isProgressIndicator() const;
virtual bool isSlider() const;
virtual bool isMenuRelated() const;
virtual bool isMenu() const;
virtual bool isMenuBar() const;
virtual bool isMenuButton() const;
virtual bool isMenuItem() const;
virtual bool isControl() const;
virtual bool isFieldset() const;
virtual bool isGroup() const;
virtual bool isEnabled() const;
virtual bool isSelected() const;
virtual bool isFocused() const;
virtual bool isChecked() const;
virtual bool isHovered() const;
virtual bool isIndeterminate() const;
virtual bool isLoaded() const;
virtual bool isMultiSelectable() const;
virtual bool isOffScreen() const;
virtual bool isPressed() const;
virtual bool isReadOnly() const;
virtual bool isVisited() const;
virtual bool isRequired() const;
virtual bool isLinked() const;
virtual bool isExpanded() const;
virtual void setIsExpanded(bool);
const AtomicString& getAttribute(const QualifiedName&) const;
virtual bool canSetFocusAttribute() const;
virtual bool canSetTextRangeAttributes() const;
virtual bool canSetValueAttribute() const;
virtual bool canSetExpandedAttribute() const;
virtual bool hasIntValue() const;
// Provides common logic used by all elements when determining isIgnored.
AccessibilityObjectInclusion accessibilityIsIgnoredBase() const;
virtual bool accessibilityIsIgnored() const;
virtual int headingLevel() const;
virtual int intValue() const;
virtual String valueDescription() const;
virtual float valueForRange() const;
virtual float maxValueForRange() const;
virtual float minValueForRange() const;
virtual AccessibilityObject* selectedRadioButton();
virtual AccessibilityObject* selectedTabItem();
virtual int layoutCount() const;
virtual double estimatedLoadingProgress() const;
virtual AccessibilityObject* doAccessibilityHitTest(const IntPoint&) const;
virtual AccessibilityObject* focusedUIElement() const;
virtual AccessibilityObject* firstChild() const;
virtual AccessibilityObject* lastChild() const;
virtual AccessibilityObject* previousSibling() const;
virtual AccessibilityObject* nextSibling() const;
virtual AccessibilityObject* parentObject() const;
virtual AccessibilityObject* parentObjectIfExists() const;
virtual AccessibilityObject* observableObject() const;
virtual void linkedUIElements(AccessibilityChildrenVector&) const;
virtual bool exposesTitleUIElement() const;
virtual AccessibilityObject* titleUIElement() const;
virtual AccessibilityObject* correspondingControlForLabelElement() const;
virtual AccessibilityObject* correspondingLabelForControlElement() const;
virtual void ariaOwnsElements(AccessibilityChildrenVector&) const;
virtual bool supportsARIAOwns() const;
virtual AccessibilityRole ariaRoleAttribute() const;
virtual bool isPresentationalChildOfAriaRole() const;
virtual bool ariaRoleHasPresentationalChildren() const;
void updateAccessibilityRole();
virtual AXObjectCache* axObjectCache() const;
virtual Element* actionElement() const;
Element* mouseButtonListener() const;
FrameView* frameViewIfRenderView() const;
virtual Element* anchorElement() const;
AccessibilityObject* menuForMenuButton() const;
AccessibilityObject* menuButtonForMenu() const;
virtual IntRect boundingBoxRect() const;
virtual IntRect elementRect() const;
virtual IntSize size() const;
virtual IntPoint clickPoint() const;
void setRenderer(RenderObject* renderer) { m_renderer = renderer; }
RenderObject* renderer() const { return m_renderer; }
RenderView* topRenderer() const;
RenderTextControl* textControl() const;
Document* document() const;
FrameView* topDocumentFrameView() const;
HTMLLabelElement* labelElementContainer() const;
virtual KURL url() const;
virtual PlainTextRange selectedTextRange() const;
virtual VisibleSelection selection() const;
virtual String stringValue() const;
virtual String ariaLabeledByAttribute() const;
virtual String title() const;
virtual String ariaDescribedByAttribute() const;
virtual String accessibilityDescription() const;
virtual String helpText() const;
virtual String textUnderElement() const;
virtual String text() const;
virtual int textLength() const;
virtual PassRefPtr<Range> ariaSelectedTextDOMRange() const;
virtual String selectedText() const;
virtual const AtomicString& accessKey() const;
virtual const String& actionVerb() const;
virtual Widget* widget() const;
virtual Widget* widgetForAttachmentView() const;
virtual void getDocumentLinks(AccessibilityChildrenVector&);
virtual FrameView* documentFrameView() const;
virtual unsigned hierarchicalLevel() const;
virtual const AccessibilityChildrenVector& children();
virtual void clearChildren();
void updateChildrenIfNecessary();
virtual void setFocused(bool);
virtual void setSelectedTextRange(const PlainTextRange&);
virtual void setValue(const String&);
virtual void setSelected(bool);
virtual void setSelectedRows(AccessibilityChildrenVector&);
virtual void changeValueByPercent(float percentChange);
virtual AccessibilityOrientation orientation() const;
virtual void increment();
virtual void decrement();
virtual void detach();
virtual void childrenChanged();
virtual void contentChanged();
virtual void addChildren();
virtual bool canHaveChildren() const;
virtual void selectedChildren(AccessibilityChildrenVector&);
virtual void visibleChildren(AccessibilityChildrenVector&);
virtual void tabChildren(AccessibilityChildrenVector&);
virtual bool shouldFocusActiveDescendant() const;
virtual AccessibilityObject* activeDescendant() const;
virtual void handleActiveDescendantChanged();
virtual VisiblePositionRange visiblePositionRange() const;
virtual VisiblePositionRange visiblePositionRangeForLine(unsigned) const;
virtual IntRect boundsForVisiblePositionRange(const VisiblePositionRange&) const;
virtual void setSelectedVisiblePositionRange(const VisiblePositionRange&) const;
virtual bool supportsARIAFlowTo() const;
virtual void ariaFlowToElements(AccessibilityChildrenVector&) const;
virtual bool supportsARIADropping() const;
virtual bool supportsARIADragging() const;
virtual bool isARIAGrabbed();
virtual void setARIAGrabbed(bool);
virtual void determineARIADropEffects(Vector<String>&);
virtual VisiblePosition visiblePositionForPoint(const IntPoint&) const;
virtual VisiblePosition visiblePositionForIndex(unsigned indexValue, bool lastIndexOK) const;
virtual int index(const VisiblePosition&) const;
virtual VisiblePosition visiblePositionForIndex(int) const;
virtual int indexForVisiblePosition(const VisiblePosition&) const;
virtual PlainTextRange doAXRangeForLine(unsigned) const;
virtual PlainTextRange doAXRangeForIndex(unsigned) const;
virtual String doAXStringForRange(const PlainTextRange&) const;
virtual IntRect doAXBoundsForRange(const PlainTextRange&) const;
virtual void updateBackingStore();
virtual String stringValueForMSAA() const;
virtual String stringRoleForMSAA() const;
virtual String nameForMSAA() const;
virtual String descriptionForMSAA() const;
virtual AccessibilityRole roleValueForMSAA() const;
protected:
RenderObject* m_renderer;
AccessibilityRole m_ariaRole;
mutable bool m_childrenDirty;
void setRenderObject(RenderObject* renderer) { m_renderer = renderer; }
void ariaLabeledByElements(Vector<Element*>& elements) const;
bool needsToUpdateChildren() const { return m_childrenDirty; }
virtual bool isDetached() const { return !m_renderer; }
private:
void ariaListboxSelectedChildren(AccessibilityChildrenVector&);
void ariaListboxVisibleChildren(AccessibilityChildrenVector&);
bool ariaIsHidden() const;
bool isDescendantOfBarrenParent() const;
bool isAllowedChildOfTree() const;
bool hasTextAlternative() const;
String positionalDescriptionForMSAA() const;
virtual String language() const;
Element* menuElementForMenuButton() const;
Element* menuItemElementForMenu() const;
AccessibilityRole determineAccessibilityRole();
AccessibilityRole determineAriaRoleAttribute() const;
bool isTabItemSelected() const;
IntRect checkboxOrRadioRect() const;
void addRadioButtonGroupMembers(AccessibilityChildrenVector& linkedUIElements) const;
AccessibilityObject* internalLinkElement() const;
AccessibilityObject* accessibilityImageMapHitTest(HTMLAreaElement*, const IntPoint&) const;
AccessibilityObject* accessibilityParentForImageMap(HTMLMapElement* map) const;
void ariaSelectedRows(AccessibilityChildrenVector&);
bool elementAttributeValue(const QualifiedName&) const;
void setElementAttributeValue(const QualifiedName&, bool);
String accessibilityDescriptionForElements(Vector<Element*> &elements) const;
void elementsFromAttribute(Vector<Element*>& elements, const QualifiedName& name) const;
virtual const AtomicString& ariaLiveRegionStatus() const;
virtual const AtomicString& ariaLiveRegionRelevant() const;
virtual bool ariaLiveRegionAtomic() const;
virtual bool ariaLiveRegionBusy() const;
void setNeedsToUpdateChildren() const { m_childrenDirty = true; }
mutable AccessibilityRole m_roleForMSAA;
};
} // namespace WebCore
#endif // AccessibilityRenderObject_h
| 4,091 |
5,422 | #include <catch2/catch.hpp>
#include "types.hpp"
TEST_CASE("operation_type json") {
for (uint8_t i = static_cast<uint8_t>(krbn::operation_type::none);
i < static_cast<uint8_t>(krbn::operation_type::end_);
++i) {
auto t = krbn::operation_type(i);
nlohmann::json json = t;
REQUIRE(json.get<krbn::operation_type>() == t);
}
}
| 161 |
4,083 | <gh_stars>1000+
import copy
import datetime
import itertools
import multiprocessing as mp
import random
import string
import threading
import time
from collections import defaultdict
import cv2
import numpy as np
from scipy.spatial import distance as dist
from frigate.config import DetectConfig
from frigate.util import draw_box_with_label
class ObjectTracker:
def __init__(self, config: DetectConfig):
self.tracked_objects = {}
self.disappeared = {}
self.max_disappeared = config.max_disappeared
def register(self, index, obj):
rand_id = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
id = f"{obj['frame_time']}-{rand_id}"
obj["id"] = id
obj["start_time"] = obj["frame_time"]
self.tracked_objects[id] = obj
self.disappeared[id] = 0
def deregister(self, id):
del self.tracked_objects[id]
del self.disappeared[id]
def update(self, id, new_obj):
self.disappeared[id] = 0
self.tracked_objects[id].update(new_obj)
def match_and_update(self, frame_time, new_objects):
# group by name
new_object_groups = defaultdict(lambda: [])
for obj in new_objects:
new_object_groups[obj[0]].append(
{
"label": obj[0],
"score": obj[1],
"box": obj[2],
"area": obj[3],
"region": obj[4],
"frame_time": frame_time,
}
)
# update any tracked objects with labels that are not
# seen in the current objects and deregister if needed
for obj in list(self.tracked_objects.values()):
if not obj["label"] in new_object_groups:
if self.disappeared[obj["id"]] >= self.max_disappeared:
self.deregister(obj["id"])
else:
self.disappeared[obj["id"]] += 1
if len(new_objects) == 0:
return
# track objects for each label type
for label, group in new_object_groups.items():
current_objects = [
o for o in self.tracked_objects.values() if o["label"] == label
]
current_ids = [o["id"] for o in current_objects]
current_centroids = np.array([o["centroid"] for o in current_objects])
# compute centroids of new objects
for obj in group:
centroid_x = int((obj["box"][0] + obj["box"][2]) / 2.0)
centroid_y = int((obj["box"][1] + obj["box"][3]) / 2.0)
obj["centroid"] = (centroid_x, centroid_y)
if len(current_objects) == 0:
for index, obj in enumerate(group):
self.register(index, obj)
continue
new_centroids = np.array([o["centroid"] for o in group])
# compute the distance between each pair of tracked
# centroids and new centroids, respectively -- our
# goal will be to match each current centroid to a new
# object centroid
D = dist.cdist(current_centroids, new_centroids)
# in order to perform this matching we must (1) find the smallest
# value in each row (i.e. the distance from each current object to
# the closest new object) and then (2) sort the row indexes based
# on their minimum values so that the row with the smallest
# distance (the best match) is at the *front* of the index list
rows = D.min(axis=1).argsort()
# next, we determine which new object each existing object matched
# against, and apply the same sorting as was applied previously
cols = D.argmin(axis=1)[rows]
# many current objects may register with each new object, so only
# match the closest ones. unique returns the indices of the first
# occurrences of each value, and because the rows are sorted by
# distance, this will be index of the closest match
_, index = np.unique(cols, return_index=True)
rows = rows[index]
cols = cols[index]
# loop over the combination of the (row, column) index tuples
for row, col in zip(rows, cols):
# grab the object ID for the current row, set its new centroid,
# and reset the disappeared counter
objectID = current_ids[row]
self.update(objectID, group[col])
# compute the row and column indices we have NOT yet examined
unusedRows = set(range(D.shape[0])).difference(rows)
unusedCols = set(range(D.shape[1])).difference(cols)
# in the event that the number of object centroids is
# equal or greater than the number of input centroids
# we need to check and see if some of these objects have
# potentially disappeared
if D.shape[0] >= D.shape[1]:
for row in unusedRows:
id = current_ids[row]
if self.disappeared[id] >= self.max_disappeared:
self.deregister(id)
else:
self.disappeared[id] += 1
# if the number of input centroids is greater
# than the number of existing object centroids we need to
# register each new input centroid as a trackable object
else:
for col in unusedCols:
self.register(col, group[col])
| 2,608 |
815 | /*=========================================================================
Program: ParaView
Module: vtkSpyPlotFileSeriesReader.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*
* Copyright 2014 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
#include "vtkSpyPlotFileSeriesReader.h"
#include "vtkInformation.h"
#include "vtkInformationIntegerKey.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
//=============================================================================
vtkStandardNewMacro(vtkSpyPlotFileSeriesReader);
vtkSpyPlotFileSeriesReader::vtkSpyPlotFileSeriesReader()
{
this->SetNumberOfOutputPorts(2);
#ifdef PARAVIEW_ENABLE_SPYPLOT_MARKERS
this->SetNumberOfOutputPorts(3);
#endif // PARAVIEW_ENABLE_SPYPLOT_MARKERS
}
vtkSpyPlotFileSeriesReader::~vtkSpyPlotFileSeriesReader() = default;
void vtkSpyPlotFileSeriesReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
| 538 |
420 | //
// NERConstraint+NERChainable.h
// NerdyUI
//
// Created by nerdycat on 2016/10/10.
// Copyright © 2016 nerdycat. All rights reserved.
//
#import "NERConstraintMaker.h"
#import "NERDefs.h"
/**
* Making Constraints using a Masonry like syntax.
* Usages:
Constraint(view).width.height.equal.constants(100, 200).make();
Constraint(view).top.left.equal.view(view2).make();
* Another way of making constraints is:
view.makeCons(^{
make.width.height.equal.constants(100, 200);
make.top.left.equal.view(view2);
});
* Like Masonry, you have to make sure view1 and view2 are in the same view hierarchy.
*/
#define Constraint(view1) [[NERConstraint alloc] initWithFirstItem:view1]
@interface NERConstraint (NERChainable)
/**
* Setting multiplier value, default: 1.
* Can take multiply values if you are configure mulitply attributes at the same time.
* Usages: .multiplier(0.5), .size.equal.view(view2).multiply(1, 2)
*/
NER_CONSTRAINT_PROP(FloatList) multipliers;
/**
* Setting constant value, default: 0.
* Can take multiply values if you are configure mulitply attributes at the same time.
* Usages: .width.equal.constants(10), .width.height.equal.constants(10, 20)
*/
NER_CONSTRAINT_PROP(FloatList) constants;
/**
* Second view
* By default it is refer to first view's parent view.
* Usages:
Constraint(view).left.equal.view(view.suerpview).constants(10).make();
Constraint(view).left.equal.constants(10).make(); //same as above
Constraint(view1).left.equal.view(view2).right.constants(20).make();
*/
NER_CONSTRAINT_PROP(Object) view;
/**
* Setting priority value, default: UILayoutPriorityRequired (1000).
* Usages: .priority(900)
*/
NER_CONSTRAINT_PROP(Float) priority;
/**
* Setting identifier value.
* Usages: .identifier(@"top constraint")
*/
NER_CONSTRAINT_PROP(Object) identifier;
#define multipliers(...) multipliers(NER_MAKE_FLOAT_LIST(__VA_ARGS__))
#define constants(...) constants(NER_MAKE_FLOAT_LIST(__VA_ARGS__))
/**
* Constraint attributes
* If second view's attribute is equal to first view's attribute, it can be ignore eigher.
* Usages:
Constraint(view1).center.equal.view(view2).center.make();
Constraint(view1).center.equal.view(view2).make(); //same as above
Constraint(view).edge.equal.constants(10, 20, 30, 40).make();
*/
- (instancetype)left; //NSLayoutAttributeLeft
- (instancetype)right; //NSLayoutAttributeRight
- (instancetype)top; //NSLayoutAttributeTop
- (instancetype)bottom; //NSLayoutAttributeBottom
- (instancetype)leading; //NSLayoutAttributeLeading
- (instancetype)trailing; //NSLayoutAttributeTrailing
- (instancetype)width; //NSLayoutAttributeWidth
- (instancetype)height; //NSLayoutAttributeHeight
- (instancetype)centerX; //NSLayoutAttributeCenterX
- (instancetype)centerY; //NSLayoutAttributeCenterY
- (instancetype)baseline; //NSLayoutAttributeBaseline
- (instancetype)firstBaseline; //NSLayoutAttributeFirstBaseline
- (instancetype)leftMargin; //NSLayoutAttributeLeftMargin
- (instancetype)rightMargin; //NSLayoutAttributeRightMargin
- (instancetype)topMargin; //NSLayoutAttributeTopMargin
- (instancetype)bottomMargin; //NSLayoutAttributeBottomMargin
- (instancetype)leadingMargin; //NSLayoutAttributeLeadingMargin
- (instancetype)trailingMargin; //NSLayoutAttributeTrailingMargin
- (instancetype)centerXWithinMargins; //NSLayoutAttributeCenterXWithinMargins
- (instancetype)centerYWithinMargins; //NSLayoutAttributeCenterYWithinMargins
- (instancetype)center; //shorthand for .centerX.centerY
- (instancetype)size; //shorthand for .width.height
- (instancetype)edge; //shorthand for .top.left.bottom.right
/**
* Constraint relations
* For equal relation, you don't even have to use equal, it's the default behavior.
* Usages:
.width.equal.constants(50)
.width.constants(50) //same as above
.width.greaterEqual.constants(50)
*/
- (instancetype)equal; //NSLayoutRelationEqual
- (instancetype)lessEqual; //NSLayoutRelationLessThanOrEqual
- (instancetype)greaterEqual; //NSLayoutRelationGreaterThanOrEqual
/**
* Shorthand for setting second view.
* Because second view is refer to first view's suerpview by default,
you use superview only if you want to make it explicitly.
* Usages:
.width.equal.self.height.multiplier(0.5)
.width.equal.superview.multiplier(0.5)
*/
- (instancetype)self; //shorthand for .view(view1)
- (instancetype)superview; //shorthand for .view(superview)
/**
* Chain Constraint making process together.
* Usages: Constraint(view).size.equal.constants(50, 100).And.center.equal.view(view2).make();
*/
- (instancetype)And; //chaining constraints making progress together.
/*
* Use to suppress getter side effects warning. Optional.
* Usages: make.left.top.equal.view(view).left.bottom.End();
*/
- (void(^)())End;
/**
* Install constraints
* You have to call make/remake/update in the end in order the install the constraints if you use Constraint() macro.
* Usages:
.width.constants(10).make();
.width.constants(20).update();
.width.equal.superview.remake();
*/
- (NSArray *(^)())make; //create constraints and activate.
- (NSArray *(^)())remake; //deactivate previous constraints and create new constraints.
- (NSArray *(^)())update; //update previous constraints and create new constraints if needed.
@end
/**
* NERConstraintMaker support an Masonry like way of making constraints.
* You can use make variable inside makeCons/updateCons/remakeCons without declare it.
* Usages:
view.makeCons(^{
make.width.constants(10);
});
view.updateCons(^{
make.width.constants(20);
});
view.remakeCons(^{
make.width.equal.superview;
});
*/
@interface NERConstraintMaker (NERChainable)
- (NERConstraint *)left;
- (NERConstraint *)right;
- (NERConstraint *)top;
- (NERConstraint *)bottom;
- (NERConstraint *)leading;
- (NERConstraint *)trailing;
- (NERConstraint *)width;
- (NERConstraint *)height;
- (NERConstraint *)centerX;
- (NERConstraint *)centerY;
- (NERConstraint *)baseline;
- (NERConstraint *)firstBaseline;
- (NERConstraint *)leftMargin;
- (NERConstraint *)rightMargin;
- (NERConstraint *)topMargin;
- (NERConstraint *)bottomMargin;
- (NERConstraint *)leadingMargin;
- (NERConstraint *)trailingMargin;
- (NERConstraint *)centerXWithinMargins;
- (NERConstraint *)centerYWithinMargins;
- (NERConstraint *)center;
- (NERConstraint *)size;
- (NERConstraint *)edge;
@end
| 2,868 |
975 | <filename>shieldCore/src/main/java/com/dianping/shield/sectionrecycler/layoutmanager/SmoothScrollEventHelper.java
package com.dianping.shield.sectionrecycler.layoutmanager;
import android.support.v7.widget.RecyclerView;
import com.dianping.agentsdk.sectionrecycler.layoutmanager.OnSmoothScrollListener;
import java.util.ArrayList;
/**
* Created by runqi.wei at 2018/11/20
*/
public class SmoothScrollEventHelper extends RecyclerView.OnScrollListener {
protected RecyclerView recyclerView;
//滚动事件标志位
protected boolean hasScrollingRun;
protected boolean hasScrollingStopped;
protected boolean hasStateChanged;
protected ArrayList<OnSmoothScrollListener> listeners;
public void setRecyclerView(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
}
public void setListeners(ArrayList<OnSmoothScrollListener> listeners) {
this.listeners = listeners;
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
hasStateChanged = (newState == RecyclerView.SCROLL_STATE_SETTLING);
if (newState != RecyclerView.SCROLL_STATE_SETTLING && hasScrollingStopped) {
recyclerView.removeOnScrollListener(this);
resetSignals();
dispatchStopScrollEvent();
}
}
public void resetSignals() {
hasStateChanged = false;
hasScrollingRun = false;
hasScrollingStopped = false;
}
public void onStart() {
dispatchStartScrollEvent();
}
public void onScrolling() {
hasScrollingRun = true;
}
public void onStop() {
hasScrollingStopped = true;
// 如果没有滚动过
// 直接分发滚动结束回调
// 如果滚动过,要在 onScrollStateChanged 中分发滚动结束回调
if (!hasScrollingRun && !hasStateChanged) {
resetSignals();
if (recyclerView != null) {
recyclerView.removeOnScrollListener(this);
}
dispatchStopScrollEvent();
}
}
protected void dispatchStartScrollEvent() {
if (listeners != null && !listeners.isEmpty()) {
for (OnSmoothScrollListener listener : listeners) {
if (listener == null) {
continue;
}
listener.onScrollStart();
}
}
}
protected void dispatchStopScrollEvent() {
if (listeners != null && !listeners.isEmpty()) {
for (OnSmoothScrollListener listener : listeners) {
if (listener == null) {
continue;
}
listener.onScrollStop();
}
}
}
}
| 1,236 |
338 | package com.camnter.newlife.utils.volley;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import java.io.UnsupportedEncodingException;
/**
* Description:GsonRequest
* Created by:CaMnter
* Time:2016-05-25 12:01
*/
public abstract class GsonRequest<T> extends Request<T>
implements Response.Listener<T>, Response.ErrorListener {
protected static final String PROTOCOL_CHARSET = "utf-8";
private Gson mGson;
private Response.Listener<T> mResponseListener;
private Class<T> mClass;
public GsonRequest(String url, Class<T> clazz) {
this(Method.GET, url, clazz);
}
public GsonRequest(int method, String url, Class<T> clazz) {
super(method, url, null);
this.mGson = new Gson();
this.mClass = clazz;
this.mResponseListener = this;
}
@Override protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(this.mGson.fromJson(jsonString, this.mClass),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
@Override protected void deliverResponse(T response) {
this.mResponseListener.onResponse(response);
}
/**
* @return this request's {@link com.android.volley.Response.ErrorListener}.
*/
public Response.ErrorListener getErrorListener() {
return this;
}
/**
* Delivers error message to the ErrorListener that the Request was
* initialized with.
*
* @param error Error details
*/
@Override public void deliverError(VolleyError error) {
this.onErrorResponse(error);
}
/**
* Called when a response is received.
*/
public abstract void onResponse(T response);
/**
* Callback method that an error has been occurred with the
* provided error code and optional user-readable message.
*/
public abstract void onErrorResponse(VolleyError error);
}
| 900 |
852 | <reponame>ckamtsikis/cmssw
#ifndef BasicMultiTrajectoryState_H
#define BasicMultiTrajectoryState_H
#include "TrackingTools/TrajectoryState/interface/BasicTrajectoryState.h"
#include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h"
#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h"
#include "FWCore/Utilities/interface/Exception.h"
/** Class which combines a set of components of a Gaussian mixture
* into a single component. Given all the components of a mixture, it
* calculates the mean and covariance matrix of the entire mixture.
* This combiner class can also be used in the process of transforming a
* Gaussian mixture into another Gaussian mixture with a smaller number
* of components. The relevant formulas can be found in
* <NAME>, Computer Physics Communications 100 (1997), 1.
*/
class BasicMultiTrajectoryState final : public BasicTrajectoryState {
typedef TrajectoryStateOnSurface TSOS;
public:
explicit BasicMultiTrajectoryState(const std::vector<TSOS>& tsvec);
BasicMultiTrajectoryState() {}
/** Rescaling the error of the mixture with a given factor. Please note that
* this rescaling is imposed on each of the components of the mixture and does
* therefore not exactly correspond to rescaling theCombinedState with the same
* factor.
*/
void rescaleError(double factor);
pointer clone() const override { return build<BasicMultiTrajectoryState>(*this); }
using Components = BasicTrajectoryState::Components;
Components const& components() const override { return theStates; }
bool singleState() const override { return false; }
bool canUpdateLocalParameters() const override { return false; }
void update(const LocalTrajectoryParameters& p,
const Surface& aSurface,
const MagneticField* field,
const SurfaceSide side) override;
void update(double weight,
const LocalTrajectoryParameters& p,
const LocalTrajectoryError& err,
const Surface& aSurface,
const MagneticField* field,
const SurfaceSide side) override;
private:
Components theStates;
void combine() dso_internal;
};
#endif
| 679 |
3,172 | # Copyright (c) 2019 PaddlePaddle 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 argparse
import linecache
import os
import zmq
from flask import Flask, current_app, jsonify, make_response, request, send_file
from flask_cors import CORS
from parl.remote import remote_constants
from parl.utils import to_byte, logger
from parl.remote.grpc_heartbeat import HeartbeatServerThread
from parl.remote.zmq_utils import create_client_socket
app = Flask(__name__)
CORS(app)
@app.route(
"/get-log", methods=[
'GET',
])
def get_log():
'''
args:
job_id: id of the remote job
response:
log: newest `LINE_NUM` lines of the log file
'''
try:
job_id = request.args['job_id']
except:
return make_response(
jsonify(message="No job_id provided, please check your request."),
400)
log_dir = current_app.config.get('LOG_DIR')
log_dir = os.path.expanduser(log_dir)
log_file_path = os.path.join(log_dir, job_id, 'stdout.log')
if not os.path.isfile(log_file_path):
return make_response(
jsonify(message="Log not exsits, please check your job_id"), 400)
else:
line_num = current_app.config.get('LINE_NUM')
linecache.checkcache(log_file_path)
log_content = ''.join(linecache.getlines(log_file_path)[-line_num:])
return make_response(
jsonify(message="Log exsits, content in log", log=log_content),
200)
@app.route(
'/download-log', methods=[
'GET',
])
def download_log():
'''
args:
job_id: the id of the remote job
response:
log: log file
'''
try:
job_id = request.args['job_id']
except:
return make_response(
jsonify(message="No job_id provided, please check your request."),
400)
log_dir = current_app.config.get('LOG_DIR')
log_dir = os.path.expanduser(log_dir)
log_file_path = os.path.join(log_dir, job_id, 'stdout.log')
if not os.path.isfile(log_file_path):
return make_response(
jsonify(message="Log not exsits, please check your job_id"), 400)
else:
return send_file(log_file_path, as_attachment=True)
def send_heartbeat_addr_to_worker(worker_addr, heartbeat_server_addr):
ctx = zmq.Context()
socket = create_client_socket(ctx, worker_addr, heartbeat_timeout=True)
try:
socket.send_multipart([
remote_constants.NORMAL_TAG,
to_byte(heartbeat_server_addr),
])
message = socket.recv_multipart()
except zmq.error.Again as e:
err_str = "Can not connect to the worker please " \
"check if the worker is running."
logger.warning(err_str)
raise Exception(err_str)
if __name__ == "__main__":
import logging
log = logging.getLogger('werkzeug')
log.disabled = True
parser = argparse.ArgumentParser()
parser.add_argument('--port', required=True, type=int)
parser.add_argument('--log_dir', required=True, type=str)
parser.add_argument('--line_num', required=True, type=int)
parser.add_argument('--worker_address', required=True, type=str)
args = parser.parse_args()
app.config.from_mapping(
LOG_DIR=args.log_dir,
LINE_NUM=args.line_num,
)
def heartbeat_exit_callback_func():
logger.warning(
"[log_server] lost connnect with the worker. Please check if it is still alive."
)
os._exit(1)
heartbeat_server_thread = HeartbeatServerThread(
heartbeat_exit_callback_func=heartbeat_exit_callback_func)
heartbeat_server_thread.setDaemon(True)
heartbeat_server_thread.start()
send_heartbeat_addr_to_worker(args.worker_address,
heartbeat_server_thread.get_address())
app.run(host="0.0.0.0", port=args.port)
| 1,800 |
582 | /*******************************************************************************
* Copyright (c) 2000, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.gef.ui.palette.customize;
import java.util.List;
import org.eclipse.gef.palette.PaletteContainer;
import org.eclipse.gef.palette.PaletteEntry;
import org.eclipse.gef.palette.PaletteRoot;
/**
* Abstract factory for <code>PaletteContainer</code>s
*
* <p>
* This class does not create <code>PaletteContainer</code>s within other
* </code>PaletteContainer</code>s. The necessary methods may be overridden
* should such functionality be desired.
* </p>
*
* @author <NAME>
*/
public abstract class PaletteContainerFactory extends PaletteEntryFactory {
/**
* @see PaletteEntryFactory#determineContainerForNewEntry(PaletteEntry)
*/
@Override
protected PaletteContainer determineContainerForNewEntry(
PaletteEntry selected) {
if (selected instanceof PaletteRoot)
return (PaletteContainer) selected;
PaletteContainer current = selected.getParent();
while (!(current instanceof PaletteRoot))
current = current.getParent();
return current;
}
/**
* @see PaletteEntryFactory#determineIndexForNewEntry(PaletteContainer,
* PaletteEntry)
*/
@SuppressWarnings("rawtypes")
@Override
protected int determineIndexForNewEntry(PaletteContainer parent,
PaletteEntry selected) {
if (parent == selected) {
return 0;
}
List children = parent.getChildren();
PaletteEntry current = selected;
while (!children.contains(current)) {
current = current.getParent();
}
return children.indexOf(current) + 1;
}
/**
* You can always create a new container. So, this method always returns
* true.
*
* @see org.eclipse.gef.ui.palette.customize.PaletteEntryFactory#canCreate(PaletteEntry)
*/
@Override
public boolean canCreate(PaletteEntry selected) {
return true;
}
}
| 839 |
1,389 | <reponame>zbmain/PGL
# Copyright (c) 2019 PaddlePaddle 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.
"""
This package implement graph sampling algorithm.
"""
import unittest
import os
import json
import numpy as np
from pgl.redis_graph import RedisGraph
from pgl.sample import graphsage_sample
from pgl.sample import node2vec_sample
class SampleTest(unittest.TestCase):
"""SampleTest
"""
def setUp(self):
config_path = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'test_redis_graph_conf.json')
with open(config_path) as inf:
config = json.load(inf)
redis_configs = [config["redis"], ]
self.graph = RedisGraph(
"reddit-graph", redis_configs, num_parts=config["num_parts"])
def test_graphsage_sample(self):
"""test_graphsage_sample
"""
eids = np.random.choice(self.graph.num_edges, 1000)
edges = self.graph.get_edges_by_id(eids)
nodes = [n for edge in edges for n in edge]
ignore_edges = edges.tolist() + edges[:, [1, 0]].tolist()
np.random.seed(1)
subgraphs = graphsage_sample(self.graph, nodes, [10, 10], [])
np.random.seed(1)
subgraphs_ignored = graphsage_sample(self.graph, nodes, [10, 10],
ignore_edges)
self.assertEqual(subgraphs[0].num_nodes,
subgraphs_ignored[0].num_nodes)
self.assertGreaterEqual(subgraphs[0].num_edges,
subgraphs_ignored[0].num_edges)
def test_node2vec_sample(self):
"""test_node2vec_sample
"""
walks = node2vec_sample(self.graph, range(10), 3)
if __name__ == '__main__':
unittest.main()
| 971 |
323 | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "controller.h"
namespace fpl {
namespace pie_noon {
void Controller::ClearAllLogicalInputs() {
is_down_ = 0;
went_down_ = 0;
went_up_ = 0;
}
void Controller::SetLogicalInputs(uint32_t bitmap, bool set) {
if (set) {
uint32_t already_down = bitmap & is_down_;
went_down_ |= bitmap & ~already_down;
is_down_ |= bitmap;
} else {
went_up_ |= bitmap & is_down_;
is_down_ &= ~bitmap;
}
}
} // pie_noon
} // fpl
| 355 |
6,245 | <gh_stars>1000+
{
"name": "react-final-form-parse-and-format",
"version": "1.0.0",
"description": "Demonstrates how to use parse and format props to control how values are shown in the input and saved into the form state.",
"keywords": [
"parse",
"react",
"react-final-form",
"format",
"final-form"
],
"main": "index.js",
"dependencies": {
"final-form": "4.20.4",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-final-form": "6.5.3",
"styled-components": "latest"
}
}
| 223 |
1,006 | /****************************************************************************
* boards/arm/samd5e5/metro-m4/src/sam_usbhost.c
*
* 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <sched.h>
#include <errno.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/kthread.h>
#include <nuttx/usb/usbhost.h>
#include <nuttx/usb/usbdev_trace.h>
#include "chip.h"
#include "arm_arch.h"
#include "metro-m4.h"
#include "sam_port.h"
#include "sam_usbhost.h"
#include <arch/board/board.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#if defined(CONFIG_USBDEV) || defined(CONFIG_USBHOST)
#define HAVE_USB 1
#endif
#ifndef CONFIG_METRO_M4_USBHOST_PRIO
#define CONFIG_METRO_M4_USBHOST_PRIO 100
#endif
#ifndef CONFIG_METRO_M4_USBHOST_STACKSIZE
#define CONFIG_METRO_M4_USBHOST_STACKSIZE 1024
#endif
/****************************************************************************
* Private Data
****************************************************************************/
#ifdef CONFIG_USBHOST
static struct usbhost_connection_s *g_usbconn;
#endif
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: usbhost_waiter
*
* Description:
* Wait for USB devices to be connected.
*
****************************************************************************/
#ifdef CONFIG_USBHOST
static int usbhost_waiter(int argc, char *argv[])
{
struct usbhost_hubport_s *hport;
uinfo("Running\n");
for (; ; )
{
/* Wait for the device to change state */
DEBUGVERIFY(CONN_WAIT(g_usbconn, &hport));
uinfo("%s\n", hport->connected ? "connected" : "disconnected");
/* Did we just become connected? */
if (hport->connected)
{
/* Yes.. enumerate the newly connected device */
(void)CONN_ENUMERATE(g_usbconn, hport);
}
#ifdef CONFIG_METRO_M4_USB_AUTOMOUNT
/* Let the automounter know about the insertion event */
sam_automount_event(hport->connected);
#endif
}
/* Keep the compiler from complaining */
return 0;
}
#endif
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: sam_usbinitialize
*
* Description:
*
****************************************************************************/
void sam_usbinitialize(void)
{
}
/****************************************************************************
* Name: sam_usbhost_vbusdrive
*
* Description:
* Enable/disable driving of VBUS 5V output. This function must be provided
* be each platform that implements the HS host interface
*
* Input Parameters:
* iface - For future growth to handle multiple USB host interface. Should
* be zero.
* enable - true: enable VBUS power; false: disable VBUS power
*
****************************************************************************/
#ifdef CONFIG_USBHOST
void sam_usbhost_vbusdrive(int iface, bool enable)
{
DEBUGASSERT(iface == 0);
if (enable)
{
/* Set your function here! */
}
else
{
/* Set your function here! */
}
}
#endif
/****************************************************************************
* Name: samd_usbhost_initialize
*
* Description:
* Called at application startup time to initialize the USB host
* functionality. This function will start a thread that will monitor for
* device connection/disconnection events.
*
****************************************************************************/
#ifdef CONFIG_USBHOST
int samd_usbhost_initialize(void)
{
int pid;
int ret;
/* First, register all of the class drivers needed to support the drivers
* that we care about:
*/
uinfo("Register class drivers\n");
#ifdef CONFIG_USBHOST_MSC
/* Register the USB mass storage class class */
ret = usbhost_msc_initialize();
if (ret != OK)
{
uerr("ERROR: Failed to register the mass storage class: %d\n", ret);
}
#endif
#ifdef CONFIG_USBHOST_HIDKBD
/* Initialize the HID keyboard class */
ret = usbhost_kbdinit();
if (ret != OK)
{
uerr("ERROR: Failed to register the HID keyboard class\n");
}
#endif
#ifdef CONFIG_USBHOST_HIDMOUSE
/* Initialize the HID mouse class */
ret = usbhost_mouse_init();
if (ret != OK)
{
uerr("ERROR: Failed to register the HID mouse class\n");
}
#endif
/* Then get an instance of the USB host interface */
uinfo("Initialize USB host\n");
g_usbconn = sam_usbhost_initialize(0);
if (g_usbconn)
{
/* Start a thread to handle device connection. */
uinfo("Start usbhost_waiter\n");
pid =
kthread_create("usbhost", CONFIG_METRO_M4_USBHOST_PRIO,
CONFIG_METRO_M4_USBHOST_STACKSIZE,
(main_t) usbhost_waiter, (FAR char *const *)NULL);
return pid < 0 ? -ENOEXEC : OK;
}
return -ENODEV;
}
#endif
| 1,891 |
585 | <filename>src/compiler/ast/quantize.cc
/*!
* Copyright (c) 2017-2021 by Contributors
* \file quantize.cc
* \brief Quantize thresholds in condition nodes
*/
#include <treelite/math.h>
#include <treelite/logging.h>
#include <set>
#include <cmath>
#include "./builder.h"
namespace treelite {
namespace compiler {
template <typename ThresholdType>
static void
scan_thresholds(ASTNode* node, std::vector<std::set<ThresholdType>>* cut_pts) {
NumericalConditionNode<ThresholdType>* num_cond;
if ( (num_cond = dynamic_cast<NumericalConditionNode<ThresholdType>*>(node)) ) {
TREELITE_CHECK(!num_cond->quantized) << "should not be already quantized";
const ThresholdType threshold = num_cond->threshold.float_val;
if (std::isfinite(threshold)) {
(*cut_pts)[num_cond->split_index].insert(threshold);
}
}
for (ASTNode* child : node->children) {
scan_thresholds(child, cut_pts);
}
}
template <typename ThresholdType>
static void
rewrite_thresholds(ASTNode* node, const std::vector<std::vector<ThresholdType>>& cut_pts) {
NumericalConditionNode<ThresholdType>* num_cond;
if ( (num_cond = dynamic_cast<NumericalConditionNode<ThresholdType>*>(node)) ) {
TREELITE_CHECK(!num_cond->quantized) << "should not be already quantized";
const ThresholdType threshold = num_cond->threshold.float_val;
if (std::isfinite(threshold)) {
const auto& v = cut_pts[num_cond->split_index];
{
auto loc = math::binary_search(v.begin(), v.end(), threshold);
TREELITE_CHECK(loc != v.end());
num_cond->threshold.int_val = static_cast<int>(loc - v.begin()) * 2;
}
{
ThresholdType zero = static_cast<ThresholdType>(0);
auto loc = std::lower_bound(v.begin(), v.end(), zero);
num_cond->zero_quantized = static_cast<int>(loc - v.begin()) * 2;
if (loc != v.end() && zero != *loc) {
--num_cond->zero_quantized;
}
}
num_cond->quantized = true;
} // splits with infinite thresholds will not be quantized
}
for (ASTNode* child : node->children) {
rewrite_thresholds(child, cut_pts);
}
}
template <typename ThresholdType, typename LeafOutputType>
void
ASTBuilder<ThresholdType, LeafOutputType>::QuantizeThresholds() {
this->quantize_threshold_flag = true;
std::vector<std::set<ThresholdType>> cut_pts;
std::vector<std::vector<ThresholdType>> cut_pts_vec;
cut_pts.resize(this->num_feature);
cut_pts_vec.resize(this->num_feature);
scan_thresholds(this->main_node, &cut_pts);
// convert cut_pts into std::vector
for (int i = 0; i < this->num_feature; ++i) {
std::copy(cut_pts[i].begin(), cut_pts[i].end(), std::back_inserter(cut_pts_vec[i]));
}
/* revise all numerical splits by quantizing thresholds */
rewrite_thresholds(this->main_node, cut_pts_vec);
TREELITE_CHECK_EQ(this->main_node->children.size(), 1);
ASTNode* top_ac_node = this->main_node->children[0];
TREELITE_CHECK(dynamic_cast<AccumulatorContextNode*>(top_ac_node));
/* dynamic_cast<> is used here to check node types. This is to ensure
that we don't accidentally call QuantizeThresholds() twice. */
ASTNode* quantizer_node
= AddNode<QuantizerNode<ThresholdType>>(this->main_node, std::move(cut_pts_vec));
quantizer_node->children.push_back(top_ac_node);
top_ac_node->parent = quantizer_node;
this->main_node->children[0] = quantizer_node;
}
template void ASTBuilder<float, uint32_t>::QuantizeThresholds();
template void ASTBuilder<float, float>::QuantizeThresholds();
template void ASTBuilder<double, uint32_t>::QuantizeThresholds();
template void ASTBuilder<double, double>::QuantizeThresholds();
} // namespace compiler
} // namespace treelite
| 1,385 |
1,602 | <gh_stars>1000+
#include <zmq.h>
int main (void)
{
int major, minor, patch;
zmq_version (&major, &minor, &patch);
printf ("Current 0MQ version is %d.%d.%d\n", major, minor, patch);
return 0;
}
| 93 |
304 | #pragma once
#include <string>
#include <vector>
class QString;
namespace OsShell
{
QString shellExecutable();
// Pos must be global
bool openShellContextMenuForObjects(const std::vector<std::wstring>& objects, int xPos, int yPos, void * parentWindow);
bool copyObjectsToClipboard(const std::vector<std::wstring>& objects, void * parentWindow);
bool cutObjectsToClipboard(const std::vector<std::wstring>& objects, void * parentWindow);
bool pasteFilesAndFoldersFromClipboard(std::wstring destFolder, void * parentWindow);
std::wstring toolTip(std::wstring itemPath);
bool deleteItems(const std::vector<std::wstring>& items, bool moveToTrash = true, void *parentWindow = nullptr);
bool recycleBinContextMenu(int xPos, int yPos, void * parentWindow);
void executeShellCommand(const QString& command, const QString& workingDir);
bool runExecutable(const QString& command, const QString& arguments, const QString& workingDir);
#ifdef _WIN32
bool runExe(const QString& command, const QString& arguments, const QString& workingDir, bool asAdmin = false);
#endif
}
| 372 |
3,573 | from pathlib import Path
from typing import List
from pipx.constants import ExitCode
from pipx.util import PipxError
from pipx.venv import Venv
def run_pip(
package: str, venv_dir: Path, pip_args: List[str], verbose: bool
) -> ExitCode:
"""Returns pipx exit code."""
venv = Venv(venv_dir, verbose=verbose)
if not venv.python_path.exists():
raise PipxError(
f"venv for {package!r} was not found. Was {package!r} installed with pipx?"
)
venv.verbose = True
return venv.run_pip_get_exit_code(pip_args)
| 226 |
511 | <filename>external/include/libcxx/support/win32/locale_mgmt_win32.h
/****************************************************************************
*
* Copyright 2018 Samsung Electronics 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.
*
****************************************************************************/
// -*- C++ -*-
//===----------------- support/win32/locale_mgmt_win32.h ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_SUPPORT_WIN32_LOCALE_MGMT_WIN32_H
#define _LIBCPP_SUPPORT_WIN32_LOCALE_MGMT_WIN32_H
#include <xlocinfo.h> // _locale_t
#define locale_t _locale_t
#define LC_COLLATE_MASK _M_COLLATE
#define LC_CTYPE_MASK _M_CTYPE
#define LC_MONETARY_MASK _M_MONETARY
#define LC_NUMERIC_MASK _M_NUMERIC
#define LC_TIME_MASK _M_TIME
#define LC_MESSAGES_MASK _M_MESSAGES
#define LC_ALL_MASK ( LC_COLLATE_MASK \
| LC_CTYPE_MASK \
| LC_MESSAGES_MASK \
| LC_MONETARY_MASK \
| LC_NUMERIC_MASK \
| LC_TIME_MASK )
#define freelocale _free_locale
// FIXME: base currently unused. Needs manual work to construct the new locale
locale_t newlocale( int mask, const char * locale, locale_t base );
locale_t uselocale( locale_t newloc );
#endif // _LIBCPP_SUPPORT_WIN32_LOCALE_MGMT_WIN32_H
| 740 |
1,444 | <filename>Mage.Sets/src/mage/cards/g/GrizzledLeotau.java
package mage.cards.g;
import java.util.UUID;
import mage.MageInt;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
/**
*
* @author North
*/
public final class GrizzledLeotau extends CardImpl {
public GrizzledLeotau(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{G}{W}");
this.subtype.add(SubType.CAT);
this.power = new MageInt(1);
this.toughness = new MageInt(5);
}
private GrizzledLeotau(final GrizzledLeotau card) {
super(card);
}
@Override
public GrizzledLeotau copy() {
return new GrizzledLeotau(this);
}
}
| 320 |
366 | <reponame>BredaUniversityGames/LearningDirectX12
#include "DX12LibPCH.h"
#include <dx12lib/PipelineStateObject.h>
#include <dx12lib/Device.h>
using namespace dx12lib;
PipelineStateObject::PipelineStateObject(Device& device, const D3D12_PIPELINE_STATE_STREAM_DESC& desc)
: m_Device(device)
{
auto d3d12Device = device.GetD3D12Device();
ThrowIfFailed( d3d12Device->CreatePipelineState( &desc, IID_PPV_ARGS( &m_d3d12PipelineState ) ) );
} | 186 |
1,181 |
package com.neo.controller;
import com.neo.config.BaseResult;
import com.neo.model.Message;
import com.neo.repository.MessageRepository;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api(value = "消息", description = "消息操作 API", position = 100, protocols = "http")
@RestController
@RequestMapping("/")
public class MessageController {
@Autowired
private MessageRepository messageRepository;
@ApiOperation(
value = "消息列表",
notes = "完整的消息内容列表",
produces="application/json, application/xml",
consumes="application/json, application/xml",
response = List.class)
@GetMapping(value = "messages")
public List<Message> list() {
List<Message> messages = this.messageRepository.findAll();
return messages;
}
@ApiOperation(
value = "添加消息",
notes = "根据参数创建消息"
)
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "消息 ID", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "text", value = "正文", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "summary", value = "摘要", required = false, dataType = "String", paramType = "query"),
})
@PostMapping(value = "message")
public Message create(Message message) {
System.out.println("message===="+message.toString());
message = this.messageRepository.save(message);
return message;
}
@ApiOperation(
value = "修改消息",
notes = "根据参数修改消息"
)
@PutMapping(value = "message")
@ApiResponses({
@ApiResponse(code = 100, message = "请求参数有误"),
@ApiResponse(code = 101, message = "未授权"),
@ApiResponse(code = 103, message = "禁止访问"),
@ApiResponse(code = 104, message = "请求路径不存在"),
@ApiResponse(code = 200, message = "服务器内部错误")
})
public Message modify(Message message) {
Message messageResult=this.messageRepository.update(message);
return messageResult;
}
@PatchMapping(value="/message/text")
public BaseResult<Message> patch(Message message) {
Message messageResult=this.messageRepository.updateText(message);
return BaseResult.successWithData(messageResult);
}
@GetMapping(value = "message/{id}")
public Message get(@PathVariable Long id) {
Message message = this.messageRepository.findMessage(id);
return message;
}
@DeleteMapping(value = "message/{id}")
public void delete(@PathVariable("id") Long id) {
this.messageRepository.deleteMessage(id);
}
}
| 1,012 |
1,562 | <gh_stars>1000+
// Copyright 2019 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.
#include "sandboxed_api/sandbox2/logsink.h"
#include <unistd.h>
#include <csignal>
#include <iostream>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/synchronization/mutex.h"
#include "sandboxed_api/sandbox2/logserver.pb.h"
namespace sandbox2 {
constexpr char LogSink::kLogFDName[];
LogSink::LogSink(int fd) : comms_(fd) { AddLogSink(this); }
LogSink::~LogSink() { RemoveLogSink(this); }
void LogSink::send(google::LogSeverity severity, const char* full_filename,
const char* base_filename, int line,
const struct tm* tm_time, const char* message,
size_t message_len) {
absl::MutexLock l(&lock_);
LogMessage msg;
msg.set_severity(static_cast<int>(severity));
msg.set_path(base_filename);
msg.set_line(line);
msg.set_message(absl::StrCat(absl::string_view{message, message_len}, "\n"));
msg.set_pid(getpid());
if (!comms_.SendProtoBuf(msg)) {
std::cerr << "sending log message to supervisor failed: " << std::endl
<< msg.DebugString() << std::endl;
}
if (severity == google::FATAL) {
// Raise a SIGABRT to prevent the remaining code in logging to try to dump a
// symbolized stack trace which can lead to syscall violations.
kill(0, SIGABRT);
}
}
} // namespace sandbox2
| 698 |
4,283 | /*
* Copyright 2021 Hazelcast Inc.
*
* Licensed under the Hazelcast Community License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://hazelcast.com/hazelcast-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.sql.impl.opt;
import com.hazelcast.jet.sql.SqlTestSupport;
import com.hazelcast.jet.sql.impl.OptimizerContext;
import com.hazelcast.jet.sql.impl.opt.logical.LogicalRel;
import com.hazelcast.jet.sql.impl.opt.logical.LogicalRules;
import com.hazelcast.jet.sql.impl.opt.physical.PhysicalRel;
import com.hazelcast.jet.sql.impl.opt.physical.PhysicalRules;
import com.hazelcast.jet.sql.impl.parse.QueryParseResult;
import com.hazelcast.jet.sql.impl.schema.HazelcastSchema;
import com.hazelcast.jet.sql.impl.schema.HazelcastSchemaUtils;
import com.hazelcast.jet.sql.impl.schema.HazelcastTable;
import com.hazelcast.jet.sql.impl.schema.HazelcastTableStatistic;
import com.hazelcast.jet.sql.impl.validate.param.StrictParameterConverter;
import com.hazelcast.sql.impl.ParameterConverter;
import com.hazelcast.sql.impl.QueryParameterMetadata;
import com.hazelcast.sql.impl.QueryUtils;
import com.hazelcast.sql.impl.schema.ConstantTableStatistics;
import com.hazelcast.sql.impl.schema.TableField;
import com.hazelcast.sql.impl.schema.map.MapTableIndex;
import com.hazelcast.sql.impl.schema.map.PartitionedMapTable;
import com.hazelcast.sql.impl.type.QueryDataType;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.sql.SqlExplainLevel;
import org.apache.calcite.sql.parser.SqlParserPos;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.List;
import java.util.Objects;
import java.util.stream.IntStream;
import static com.hazelcast.jet.sql.impl.schema.TableResolverImpl.SCHEMA_NAME_PUBLIC;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.Collections.emptyList;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.assertj.core.api.Assertions.assertThat;
public abstract class OptimizerTestSupport extends SqlTestSupport {
protected RelNode optimizeLogical(String sql, HazelcastTable... tables) {
HazelcastSchema schema = schema(tables);
OptimizerContext context = context(schema);
return optimizeLogicalInternal(sql, context);
}
protected RelNode optimizeLogical(String sql, boolean requiresJob, HazelcastTable... tables) {
HazelcastSchema schema = schema(tables);
OptimizerContext context = context(schema);
context.setRequiresJob(requiresJob);
return optimizeLogicalInternal(sql, context);
}
protected Result optimizePhysical(String sql, List<QueryDataType> parameterTypes, HazelcastTable... tables) {
HazelcastSchema schema = schema(tables);
OptimizerContext context = context(schema, parameterTypes.toArray(new QueryDataType[0]));
return optimizePhysicalInternal(sql, context);
}
private static LogicalRel optimizeLogicalInternal(String sql, OptimizerContext context) {
QueryParseResult parseResult = context.parse(sql);
RelNode rel = context.convert(parseResult.getNode()).getRel();
return (LogicalRel) context
.optimize(rel, LogicalRules.getRuleSet(), OptUtils.toLogicalConvention(rel.getTraitSet()));
}
private static Result optimizePhysicalInternal(String sql, OptimizerContext context) {
LogicalRel logicalRel = optimizeLogicalInternal(sql, context);
PhysicalRel physicalRel = (PhysicalRel) context
.optimize(logicalRel, PhysicalRules.getRuleSet(), OptUtils.toPhysicalConvention(logicalRel.getTraitSet()));
return new Result(logicalRel, physicalRel);
}
private static HazelcastSchema schema(HazelcastTable... tables) {
return new HazelcastSchema(stream(tables).collect(toMap(table -> table.getTarget().getSqlName(), identity())));
}
private static OptimizerContext context(HazelcastSchema schema, QueryDataType... parameterTypes) {
OptimizerContext context = OptimizerContext.create(
HazelcastSchemaUtils.createCatalog(schema),
QueryUtils.prepareSearchPaths(null, null),
emptyList(),
1,
name -> null
);
ParameterConverter[] parameterConverters = IntStream.range(0, parameterTypes.length)
.mapToObj(i -> new StrictParameterConverter(i, SqlParserPos.ZERO, parameterTypes[i]))
.toArray(ParameterConverter[]::new);
QueryParameterMetadata parameterMetadata = new QueryParameterMetadata(parameterConverters);
context.setParameterMetadata(parameterMetadata);
return context;
}
protected static HazelcastTable partitionedTable(String name, List<TableField> fields, long rowCount) {
return partitionedTable(name, fields, emptyList(), rowCount);
}
protected static HazelcastTable partitionedTable(
String name,
List<TableField> fields,
List<MapTableIndex> indexes,
long rowCount
) {
PartitionedMapTable table = new PartitionedMapTable(
SCHEMA_NAME_PUBLIC,
name,
name,
fields,
new ConstantTableStatistics(rowCount),
null,
null,
null,
null,
indexes,
false
);
return new HazelcastTable(table, new HazelcastTableStatistic(rowCount));
}
protected static TableField field(String name, QueryDataType type) {
return new Field(name, type, false);
}
protected static void assertPlan(RelNode rel, PlanRows expected) {
BufferedReader reader = new BufferedReader(new StringReader(RelOptUtil.toString(rel, SqlExplainLevel.ALL_ATTRIBUTES)));
List<PlanRow> rows = reader.lines()
.map(PlanRow::parse)
.collect(toList());
assertPlan(new PlanRows(rows), expected);
}
private static void assertPlan(PlanRows actual, PlanRows expected) {
int expectedRowCount = expected.getRowCount();
int actualRowCount = actual.getRowCount();
assertThat(actualRowCount)
.as("Plan are different" + "\n\n>>> EXPECTED PLAN:\n%s\n>>> ACTUAL PLAN:\n%s", expected, actual)
.isEqualTo(expectedRowCount);
for (int i = 0; i < expectedRowCount; i++) {
PlanRow expectedRow = expected.getRow(i);
PlanRow actualRow = actual.getRow(i);
assertThat(actualRow)
.as("Plan rows are different at %s" + "\n\n>>> EXPECTED PLAN:\n%s\n>>> ACTUAL PLAN:\n%s", i + 1, expected, actual)
.isEqualTo(expectedRow);
}
}
protected static PlanRows plan(PlanRow... rows) {
return new PlanRows(asList(rows));
}
protected static PlanRow planRow(int level, Class<? extends RelNode> node) {
return new PlanRow(level, node);
}
private static class Field extends TableField {
private Field(String name, QueryDataType type, boolean hidden) {
super(name, type, hidden);
}
}
protected static class Result {
private final LogicalRel logical;
private final PhysicalRel physical;
private Result(LogicalRel logical, PhysicalRel physical) {
this.logical = logical;
this.physical = physical;
}
public LogicalRel getLogical() {
return logical;
}
public PhysicalRel getPhysical() {
return physical;
}
}
protected static class PlanRows {
private final List<PlanRow> rows;
private PlanRows(List<PlanRow> rows) {
this.rows = rows;
}
private int getRowCount() {
return rows.size();
}
private PlanRow getRow(int index) {
return rows.get(index);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < rows.size(); i++) {
PlanRow row = rows.get(i);
builder.append(String.format("%02d", i)).append(": ").append(row).append("\n");
}
return builder.toString();
}
}
protected static class PlanRow {
private final int level;
private final String node;
protected PlanRow(int level, Class<? extends RelNode> nodeClass) {
this(level, nodeClass.getSimpleName());
}
protected PlanRow(int level, String node) {
this.level = level;
this.node = node;
}
protected static PlanRow parse(String input) {
// level
int level = 0;
while (input.charAt(level * 2) == ' ') {
level++;
}
// node
String nodeAndSignature = input.substring(0, input.lastIndexOf(":")).trim();
String node = input.contains("(")
? nodeAndSignature.substring(0, nodeAndSignature.indexOf('('))
: nodeAndSignature;
return new PlanRow(level, node);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < level; i++) {
builder.append(" ");
}
builder.append(node);
return builder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PlanRow planRow = (PlanRow) o;
return level == planRow.level && Objects.equals(node, planRow.node);
}
@Override
public int hashCode() {
return Objects.hash(level, node);
}
}
}
| 4,307 |
1,668 | <reponame>DoNnMyTh/ralph
# -*- coding: utf-8 -*-
from ddt import data, ddt, unpack
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import FieldDoesNotExist
from django.test import TestCase
from ralph.admin.helpers import (
generate_html_link,
get_content_type_for_model,
get_field_by_relation_path,
getattr_dunder
)
from ralph.assets.models.assets import Asset, Manufacturer
from ralph.assets.models.base import BaseObject
@ddt
class ModelFieldsTestCase(TestCase):
def test_return_ok_when_simply_field(self):
field_name = 'barcode'
found = get_field_by_relation_path(Asset, field_name)
self.assertEqual(found, Asset._meta.get_field(field_name))
def test_return_ok_when_long_path(self):
found = get_field_by_relation_path(Asset, 'model__manufacturer__name')
self.assertEqual(found, Manufacturer._meta.get_field('name'))
def test_raise_exception_when_no_field(self):
fake_field = 'device_info__fortunately_unexisting_deprecated_field'
with self.assertRaises(FieldDoesNotExist):
found = get_field_by_relation_path(Asset, fake_field)
def test_getattr_dunder(self):
"""getattr_dunder works recursively"""
class A():
pass
a = A()
a.b = A()
a.b.name = 'spam'
self.assertEqual(getattr_dunder(a, 'b__name'), 'spam')
@unpack
@data(
(BaseObject, Asset),
(Manufacturer, Manufacturer)
)
def test_get_content_type_for_model(self, expected_model, model):
self.assertEqual(
ContentType.objects.get_for_model(expected_model),
get_content_type_for_model(model)
)
class GenerateLinkTest(TestCase):
def test_generate_html_link(self):
url = generate_html_link(
'http://test.com/',
label='Name',
params={'param': 1},
)
self.assertEqual(
url,
'<a href="http://test.com/?param=1">Name</a>'
)
| 903 |
22,688 | <reponame>jzjonah/apollo<filename>modules/perception/fusion/common/camera_util.cc
/******************************************************************************
* Copyright 2018 The Apollo 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.
*****************************************************************************/
/**
* @file camera_util.cc
**/
#include "modules/perception/fusion/common/camera_util.h"
#include <limits>
#include "modules/common/util/eigen_defs.h"
namespace apollo {
namespace perception {
namespace fusion {
void GetObjectEightVertices(std::shared_ptr<const base::Object> obj,
std::vector<Eigen::Vector3d>* vertices) {
vertices->clear();
vertices->resize(8);
Eigen::Vector3d center = obj->center;
Eigen::Vector2d dir = obj->direction.head(2).cast<double>();
dir.normalize();
Eigen::Vector2d orth_dir(-dir.y(), dir.x());
Eigen::Vector2d delta_x = dir * obj->size(0) * 0.5;
Eigen::Vector2d delta_y = orth_dir * obj->size(1) * 0.5;
// lower four points
center.z() -= obj->size(2) * 0.5;
(*vertices)[0] = center, (*vertices)[0].head(2) += (-delta_x - delta_y);
(*vertices)[1] = center, (*vertices)[1].head(2) += (-delta_x + delta_y);
(*vertices)[2] = center, (*vertices)[2].head(2) += (delta_x + delta_y);
(*vertices)[3] = center, (*vertices)[3].head(2) += (delta_x - delta_y);
// upper four points
(*vertices)[4] = (*vertices)[0], (*vertices)[4].z() += obj->size(2);
(*vertices)[5] = (*vertices)[1], (*vertices)[5].z() += obj->size(2);
(*vertices)[6] = (*vertices)[2], (*vertices)[6].z() += obj->size(2);
(*vertices)[7] = (*vertices)[3], (*vertices)[7].z() += obj->size(2);
}
bool Pt3dToCamera2d(const Eigen::Vector3d& pt3d,
const Eigen::Matrix4d& world2camera_pose,
base::BaseCameraModelPtr camera_model,
Eigen::Vector2d* pt2d) {
Eigen::Vector4d local_pt = static_cast<Eigen::Matrix<double, 4, 1, 0, 4, 1>>(
world2camera_pose * Eigen::Vector4d(pt3d(0), pt3d(1), pt3d(2), 1));
if (local_pt[2] > 0) {
*pt2d =
(camera_model->Project(Eigen::Vector3f(
static_cast<float>(local_pt[0]), static_cast<float>(local_pt[1]),
static_cast<float>(local_pt[2]))))
.cast<double>();
return true;
}
return false;
}
bool IsObjectEightVerticesAllBehindCamera(
const std::shared_ptr<const base::Object>& obj,
const Eigen::Matrix4d& world2camera_pose,
base::BaseCameraModelPtr camera_model) {
std::vector<Eigen::Vector3d> vertices(8);
GetObjectEightVertices(obj, &vertices);
Eigen::Vector2d pt2d;
for (const auto& vertice : vertices) {
if ((Pt3dToCamera2d(vertice, world2camera_pose, camera_model, &pt2d))) {
return false;
}
}
return true;
}
float ObjectInCameraView(SensorObjectConstPtr sensor_object,
base::BaseCameraModelPtr camera_model,
const Eigen::Affine3d& camera_sensor2world_pose,
double camera_ts, double camera_max_dist,
bool motion_compensation, bool all_in) {
constexpr float kFloatEpsilon = std::numeric_limits<float>::epsilon();
float in_view_ratio = 0.0f;
Eigen::Matrix4d world2sensor_pose =
camera_sensor2world_pose.matrix().inverse();
if (!world2sensor_pose.allFinite()) {
return in_view_ratio;
}
double width = static_cast<double>(camera_model->get_width());
double height = static_cast<double>(camera_model->get_height());
double time_diff =
camera_ts - sensor_object->GetBaseObject()->latest_tracked_time;
Eigen::Vector3f offset =
sensor_object->GetBaseObject()->velocity * static_cast<float>(time_diff);
if (!motion_compensation) {
offset.setZero();
}
// 2.compute distance
const auto& cloud =
sensor_object->GetBaseObject()->lidar_supplement.cloud_world;
Eigen::Vector3d center = sensor_object->GetBaseObject()->center;
Eigen::Vector2d center2d;
if (!Pt3dToCamera2d(center, world2sensor_pose, camera_model, ¢er2d)) {
return in_view_ratio;
}
double obj_length = sensor_object->GetBaseObject()->size(0);
double obj_width = sensor_object->GetBaseObject()->size(1);
double obj_height = sensor_object->GetBaseObject()->size(2);
if (cloud.size() > 0) {
// use point cloud
int point_num = static_cast<int>(cloud.size());
int in_view_point_num = 0;
for (int i = 0; i < point_num; ++i) {
const auto& pt = cloud.at(i);
Eigen::Vector3d pt3d(pt.x + offset[0], pt.y + offset[1],
pt.z + offset[2]);
Eigen::Vector2d pt2d;
bool flag = Pt3dToCamera2d(pt3d, world2sensor_pose, camera_model, &pt2d);
if (flag && IsPtInFrustum(pt2d, width, height)) {
++in_view_point_num;
}
}
in_view_ratio = static_cast<float>(in_view_point_num / point_num);
if (all_in) {
in_view_ratio = (in_view_point_num == point_num) ? 1.0 : 0.0;
}
} else if (obj_width > kFloatEpsilon && obj_height > kFloatEpsilon &&
obj_length > kFloatEpsilon) {
// use object box
std::vector<Eigen::Vector3d> box3d_vs(8);
GetObjectEightVertices(sensor_object->GetBaseObject(), &box3d_vs);
std::vector<Eigen::Vector2f> box2d_vs;
box2d_vs.reserve(box3d_vs.size());
for (const auto& box3d_v : box3d_vs) {
Eigen::Vector2d pt2d;
bool flag = Pt3dToCamera2d(box3d_v + offset.cast<double>(),
world2sensor_pose, camera_model, &pt2d);
if (!flag) {
return in_view_ratio;
}
box2d_vs.push_back(pt2d.cast<float>());
}
Eigen::Vector2d top_left;
Eigen::Vector2d bottom_right;
top_left.setConstant(std::numeric_limits<double>::max());
bottom_right = -top_left;
for (const auto& box2d_v : box2d_vs) {
top_left = top_left.cwiseMin(box2d_v.cast<double>());
bottom_right = bottom_right.cwiseMax(box2d_v.cast<double>());
}
Eigen::Vector2d box_size = bottom_right - top_left;
Eigen::Vector2d bound_top_left =
top_left.cwiseMax(Eigen::Vector2d(0.0, 0.0));
Eigen::Vector2d bound_bottom_right =
bottom_right.cwiseMin(Eigen::Vector2d(width, height));
Eigen::Vector2d bound_box_size = bound_bottom_right - bound_top_left;
if ((bound_box_size.array() > 0.0).all()) {
in_view_ratio =
static_cast<float>(bound_box_size.prod() / box_size.prod());
} else {
in_view_ratio = 0.0;
}
if (all_in) {
in_view_ratio = std::abs(1.0 - in_view_ratio) <= 1e-6 ? 1.0 : 0.0;
}
} else { // use center point
if (!((center2d.array() > 0.0).all())) {
in_view_ratio = 0.0;
} else if (center2d.x() > width || center2d.y() > height) {
in_view_ratio = 0.0;
} else {
in_view_ratio = 1.0;
}
}
// compute distance score, when object is too far from camera
// the camera is hard to detect object
// TODO(yuantingrong):
// maximum camera detection distance parameters, hard code
const double max_dist = camera_max_dist;
// 1 nearly 2m buffer
const double dist_slope = 0.25;
auto sigmoid_like_fun = [max_dist, dist_slope](double obj_dist) {
double x = obj_dist - max_dist;
return 0.5 - 0.5 * x * dist_slope /
std::sqrt(1 + x * x * dist_slope * dist_slope);
};
Eigen::Vector4d center3d_local = world2sensor_pose * center.homogeneous();
double dist_to_camera = center3d_local.z();
return static_cast<float>(in_view_ratio * sigmoid_like_fun(dist_to_camera));
}
} // namespace fusion
} // namespace perception
} // namespace apollo
| 3,383 |
1,473 | <reponame>PyCN/brainstorm
#!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
import pytest
from brainstorm.structure.construction import (ConstructionWrapper,
NetworkValidationError)
@pytest.fixture
def layers():
return [ConstructionWrapper.create('DummyLayerImpl') for _ in range(5)]
def test_constructor():
cl = ConstructionWrapper.create('FooLayerImpl')
assert cl.layer.layer_type == 'Foo'
assert repr(cl) == "<Layer: 'default' - Foo - 'default'>"
def test_raises_on_invalid_layer_type():
with pytest.raises(NetworkValidationError):
i = ConstructionWrapper.create('not valid!')
def test_raises_on_invalid_layer_name():
with pytest.raises(NetworkValidationError):
i = ConstructionWrapper.create('layertype', name='also invalid.')
def test_connecting_two_layers_sets_sinks_and_sources(layers):
l1, l2, l3, l4, l5 = layers
_ = l1 >> l2 >> l3
assert (l1.layer, 'default', 'default') in l2.layer.incoming
assert ('default', 'default', l2.layer) in l1.layer.outgoing
assert ('default', 'default', l3.layer) in l2.layer.outgoing
def test_connect_multiple_targets(layers):
l1, l2, l3, l4, l5 = layers
_ = l1 >> l2
_ = l1 >> l3
_ = l1 >> l4
assert ('default', 'default', l2.layer) in l1.layer.outgoing
assert ('default', 'default', l3.layer) in l1.layer.outgoing
assert ('default', 'default', l4.layer) in l1.layer.outgoing
def test_connect_multiple_sources(layers):
l1, l2, l3, l4, l5 = layers
_ = l2 >> l1
_ = l3 >> l1
_ = l4 >> l1
assert (l2.layer, 'default', 'default') in l1.layer.incoming
assert (l3.layer, 'default', 'default') in l1.layer.incoming
assert (l4.layer, 'default', 'default') in l1.layer.incoming
def test_connect_named_output(layers):
l1, l2, l3, l4, l5 = layers
_ = l1 >> l2 - 'out1' >> l3
assert ('default', 'default', l2.layer) in l1.layer.outgoing
assert (l1.layer, 'default', 'default') in l2.layer.incoming
assert (l2.layer, 'out1', 'default') in l3.layer.incoming
assert ('out1', 'default', l3.layer) in l2.layer.outgoing
def test_connect_named_input(layers):
l1, l2, l3, l4, l5 = layers
_ = l1 >> "in1" - l2 >> l3
assert (l1.layer, 'default', 'in1') in l2.layer.incoming
assert ('default', 'in1', l2.layer) in l1.layer.outgoing
assert ('default', 'default', l3.layer) in l2.layer.outgoing
assert (l2.layer, 'default', 'default') in l3.layer.incoming
def test_connect_named_output_to_name_input(layers):
l1, l2, l3, l4, l5 = layers
_ = l1 >> l2 - "out1" >> "in1" - l3 >> l4
assert ('default', 'default', l2.layer) in l1.layer.outgoing
assert (l1.layer, 'default', 'default') in l2.layer.incoming
assert ('out1', 'in1', l3.layer) in l2.layer.outgoing
assert (l2.layer, 'out1', 'in1') in l3.layer.incoming
assert ('default', 'default', l4.layer) in l3.layer.outgoing
assert (l3.layer, 'default', 'default') in l4.layer.incoming
def test_connect_named_output_to_name_input_in_chain(layers):
l1, l2, l3, l4, l5 = layers
_ = l1 >> "in1" - l2 - "out1" >> l3
assert ('default', 'in1', l2.layer) in l1.layer.outgoing
assert (l1.layer, 'default', 'in1') in l2.layer.incoming
assert ('out1', 'default', l3.layer) in l2.layer.outgoing
assert (l2.layer, 'out1', 'default') in l3.layer.incoming
def test_collect_connected_layers(layers):
l1, l2, l3, l4, l5 = layers
_ = l1 >> l2 >> l3 >> l4 >> l5
layer_set = {l.layer for l in layers}
assert l1.layer.collect_connected_layers() == layer_set
assert l5.layer.collect_connected_layers() == layer_set
def test_collect_connected_layers2(layers):
l1, l2, l3, l4, l5 = layers
_ = l1 >> l2 >> l3 >> l4
_ = l1 >> l5 >> l4
layer_set = {l.layer for l in layers}
assert l1.layer.collect_connected_layers() == layer_set
assert l4.layer.collect_connected_layers() == layer_set
assert l5.layer.collect_connected_layers() == layer_set
def test_name():
l = ConstructionWrapper.create('FooLayerImpl', name='bar')
assert l.layer.name == 'bar'
def test_default_name():
l = ConstructionWrapper.create('FooLayerImpl')
assert l.layer.name == 'Foo'
def test_name_unconnected():
l1 = ConstructionWrapper.create('FooLayerImpl', name='bar')
l2 = ConstructionWrapper.create('FooLayerImpl', name='bar')
assert l1.layer.name == 'bar'
assert l2.layer.name == 'bar'
def test_name_connected():
l1 = ConstructionWrapper.create('FooLayerImpl', name='bar')
l2 = ConstructionWrapper.create('FooLayerImpl', name='bar')
_ = l1 >> l2
assert l1.layer.name == 'bar_1'
assert l2.layer.name == 'bar_2'
def test_name_connected_complex(layers):
l1, l2, l3, l4, l5 = layers
_ = l3 >> l4
_ = l2 >> l1
_ = l5 >> l2 >> l3
assert l1.layer.name == 'Dummy_1'
assert l2.layer.name == 'Dummy_2'
assert l3.layer.name == 'Dummy_3'
assert l4.layer.name == 'Dummy_4'
assert l5.layer.name == 'Dummy_5'
| 2,126 |
521 | <reponame>Fimbure/icebox-1<gh_stars>100-1000
/** @file
* IPRT - Crypto - Time-Stamp Protocol (RFC-3161).
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
#ifndef ___iprt_crypto_tsp_h
#define ___iprt_crypto_tsp_h
#include <iprt/asn1.h>
#include <iprt/crypto/x509.h>
RT_C_DECLS_BEGIN
/** @defgroup grp_rt_cr_tap RTCrTap - Time-Stamp Protocol (RFC-3161)
* @ingroup grp_rt_crypto
* @{
*/
/**
* RFC-3161 MessageImprint (IPRT representation).
*/
typedef struct RTCRTSPMESSAGEIMPRINT
{
/** Sequence core. */
RTASN1SEQUENCECORE SeqCore;
/** The digest algorithm used to produce HashedMessage. */
RTCRX509ALGORITHMIDENTIFIER HashAlgorithm;
/** The digest of the message being timestamped. */
RTASN1OCTETSTRING HashedMessage;
} RTCRTSPMESSAGEIMPRINT;
/** Pointer to the IPRT representation of a RFC-3161 MessageImprint. */
typedef RTCRTSPMESSAGEIMPRINT *PRTCRTSPMESSAGEIMPRINT;
/** Pointer to the const IPRT representation of a RFC-3161 MessageImprint. */
typedef RTCRTSPMESSAGEIMPRINT const *PCRTCRTSPMESSAGEIMPRINT;
RTASN1TYPE_STANDARD_PROTOTYPES(RTCRTSPMESSAGEIMPRINT, RTDECL, RTCrTspMessageImprint, SeqCore.Asn1Core);
/**
* RFC-3161 Accuracy (IPRT representation).
*/
typedef struct RTCRTSPACCURACY
{
/** Sequence core. */
RTASN1SEQUENCECORE SeqCore;
/** The seconds accuracy.
* This will be larger than 0. If 1 inspect the Millis field. */
RTASN1INTEGER Seconds;
/** The millisecond accuracy, optional, implicit tag 0.
* Range 1..999. If 1 inspect the Micros field. */
RTASN1INTEGER Millis;
/** The microsecond accuracy, optional, implicit tag 1.
* Range 1..999. */
RTASN1INTEGER Micros;
} RTCRTSPACCURACY;
/** Pointer to the IPRT representation of a RFC-3161 Accuracy. */
typedef RTCRTSPACCURACY *PRTCRTSPACCURACY;
/** Pointer to the const IPRT representation of a RFC-3161 Accuracy. */
typedef RTCRTSPACCURACY const *PCRTCRTSPACCURACY;
RTASN1TYPE_STANDARD_PROTOTYPES(RTCRTSPACCURACY, RTDECL, RTCrTspAccuracy, SeqCore.Asn1Core);
/**
* RFC-3161 TSTInfo (IPRT representation).
*/
typedef struct RTCRTSPTSTINFO
{
/** Sequence core. */
RTASN1SEQUENCECORE SeqCore;
/** The structure version number, current only 1 is valid. */
RTASN1INTEGER Version;
/** Time authority policy. */
RTASN1OBJID Policy;
/** The message imprint. */
RTCRTSPMESSAGEIMPRINT MessageImprint;
/** Timestamp request serial number. */
RTASN1INTEGER SerialNumber;
/** The timestamp. */
RTASN1TIME GenTime;
/** The timestamp accuracy, optional. */
RTCRTSPACCURACY Accuracy;
/** Ordering, whatever that means, defaults to FALSE. */
RTASN1BOOLEAN Ordering;
/** Nonce, optional. */
RTASN1INTEGER Nonce;
/** Timestamp authority name, explicit optional.
* (Should match a name in the certificate of the signature.) */
struct
{
/** Context tag 0. */
RTASN1CONTEXTTAG0 CtxTag0;
/** The TSA name. */
RTCRX509GENERALNAME Tsa;
} T0;
/** Extensions, optional, implicit tag 1. */
RTCRX509EXTENSION Extensions;
} RTCRTSPTSTINFO;
/** Pointer to the IPRT representation of a RFC-3161 TSTInfo. */
typedef RTCRTSPTSTINFO *PRTCRTSPTSTINFO;
/** Pointer to the const IPRT representation of a RFC-3161 TSTInfo. */
typedef RTCRTSPTSTINFO const *PCRTCRTSPTSTINFO;
RTASN1TYPE_STANDARD_PROTOTYPES(RTCRTSPTSTINFO, RTDECL, RTCrTspTstInfo, SeqCore.Asn1Core);
/** The object identifier for RTCRTSPTSTINFO.
* Found in the ContentType field of PKCS \#7's ContentInfo structure and
* the equivalent CMS field. */
#define RTCRTSPTSTINFO_OID "1.2.840.113549.1.9.16.1.4"
/** @} */
RT_C_DECLS_END
#endif
| 2,078 |
1,283 | package com.pengrad.telegrambot.model;
import java.io.Serializable;
import java.util.Objects;
/**
* stas
* 8/5/15.
*/
public class Audio implements Serializable {
private final static long serialVersionUID = 0L;
private String file_id;
private String file_unique_id;
private Integer duration;
private String performer;
private String title;
private String file_name;
private String mime_type;
private Integer file_size;
private PhotoSize thumb;
public String fileId() {
return file_id;
}
public String fileUniqueId() {
return file_unique_id;
}
public Integer duration() {
return duration;
}
public String performer() {
return performer;
}
public String title() {
return title;
}
public String fileName() {
return file_name;
}
public String mimeType() {
return mime_type;
}
public Integer fileSize() {
return file_size;
}
public PhotoSize thumb() {
return thumb;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Audio audio = (Audio) o;
return Objects.equals(file_id, audio.file_id) &&
Objects.equals(file_unique_id, audio.file_unique_id) &&
Objects.equals(duration, audio.duration) &&
Objects.equals(performer, audio.performer) &&
Objects.equals(title, audio.title) &&
Objects.equals(file_name, audio.file_name) &&
Objects.equals(mime_type, audio.mime_type) &&
Objects.equals(file_size, audio.file_size) &&
Objects.equals(thumb, audio.thumb);
}
@Override
public int hashCode() {
return file_id != null ? file_id.hashCode() : 0;
}
@Override
public String toString() {
return "Audio{" +
"file_id='" + file_id + '\'' +
", file_unique_id='" + file_unique_id + '\'' +
", duration=" + duration +
", performer='" + performer + '\'' +
", title='" + title + '\'' +
", file_name='" + file_name + '\'' +
", mime_type='" + mime_type + '\'' +
", file_size=" + file_size +
", thumb=" + thumb +
'}';
}
}
| 1,116 |
593 | <filename>Pods/RMActionController/RMActionController/Grouping Actions/RMGroupedAction.h
//
// RMGroupedAction.h
// RMActionController-Demo
//
// Created by <NAME> on 19.11.16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import "RMAction.h"
/**
* A RMGroupedAction instance represents a number of actions that can be grouped.
*
* Normally, a RMActionController uses one row for every action that has been added. RMGroupedActions offers the possibility to show multiple RMActions in one row.
*/
@interface RMGroupedAction<T : UIView *> : RMAction<T>
/// @name Getting an Instance
#pragma mark - Getting an Instance
/**
* Returns a new instance of RMGroupedAction.
*
* @param style The style of the action.
* @param actions The actions that are contained in the grouped action.
*
* @return The new instance of RMGroupedAction
*/
+ (nullable instancetype)actionWithStyle:(RMActionStyle)style andActions:(nonnull NSArray<RMAction<T> *> *)actions;
/**
* An array of actions the RMGroupedAction consists of.
*/
@property (nonnull, nonatomic, strong, readonly) NSArray<RMAction<T> *> *actions;
@end
| 356 |
338 | <reponame>XmobiTea-Family/ezyfox-server<filename>ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/Websock.java
package com.tvd12.ezyfoxserver.nio.testing;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
public class Websock {
private static class Adapter extends WebSocketAdapter {
@Override
public void onWebSocketConnect(Session sess) {
System.out.print("client connected");
}
@Override
public void onWebSocketBinary(byte[] payload, int offset, int len) {
System.out.println("onWebSocketBinary");
}
@Override
public void onWebSocketText(String message) {
System.out.println("onWebSocketText");
}
}
public static void main(String[] args) throws Exception {
Server server = new Server(2208);
// needed.
ContextHandlerCollection handlerCollection = new ContextHandlerCollection();
handlerCollection.addHandler(createWebsocketHandler());
server.setHandler(handlerCollection);
server.start();
}
private static ContextHandler createWebsocketHandler() {
ContextHandler contextHandler = new ContextHandler("/ws");
contextHandler.setAllowNullPathInfo(true); // disable redirect from /ws
// to /ws/
final WebSocketCreator webSocketcreator = new WebSocketCreator() {
public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) {
return new Adapter();
}
};
Handler webSocketHandler = new WebSocketHandler() {
public void configure(WebSocketServletFactory factory) {
factory.setCreator(webSocketcreator);
}
};
contextHandler.setHandler(webSocketHandler);
return contextHandler;
}
}
| 738 |
3,301 | <reponame>starburst-project/Alink
package com.alibaba.alink.common.io.plugin;
public enum OsType {
LINUX,
MACOSX,
WINDOWS
}
| 52 |
3,372 | /*
* 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.ec2.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Describes an image attribute.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImageAttribute" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ImageAttribute implements Serializable, Cloneable {
/**
* <p>
* The block device mapping entries.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<BlockDeviceMapping> blockDeviceMappings;
/**
* <p>
* The ID of the AMI.
* </p>
*/
private String imageId;
/**
* <p>
* The launch permissions.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<LaunchPermission> launchPermissions;
/**
* <p>
* The product codes.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<ProductCode> productCodes;
/**
* <p>
* A description for the AMI.
* </p>
*/
private String description;
/**
* <p>
* The kernel ID.
* </p>
*/
private String kernelId;
/**
* <p>
* The RAM disk ID.
* </p>
*/
private String ramdiskId;
/**
* <p>
* Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.
* </p>
*/
private String sriovNetSupport;
private String bootMode;
/**
* <p>
* The block device mapping entries.
* </p>
*
* @return The block device mapping entries.
*/
public java.util.List<BlockDeviceMapping> getBlockDeviceMappings() {
if (blockDeviceMappings == null) {
blockDeviceMappings = new com.amazonaws.internal.SdkInternalList<BlockDeviceMapping>();
}
return blockDeviceMappings;
}
/**
* <p>
* The block device mapping entries.
* </p>
*
* @param blockDeviceMappings
* The block device mapping entries.
*/
public void setBlockDeviceMappings(java.util.Collection<BlockDeviceMapping> blockDeviceMappings) {
if (blockDeviceMappings == null) {
this.blockDeviceMappings = null;
return;
}
this.blockDeviceMappings = new com.amazonaws.internal.SdkInternalList<BlockDeviceMapping>(blockDeviceMappings);
}
/**
* <p>
* The block device mapping entries.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setBlockDeviceMappings(java.util.Collection)} or {@link #withBlockDeviceMappings(java.util.Collection)}
* if you want to override the existing values.
* </p>
*
* @param blockDeviceMappings
* The block device mapping entries.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withBlockDeviceMappings(BlockDeviceMapping... blockDeviceMappings) {
if (this.blockDeviceMappings == null) {
setBlockDeviceMappings(new com.amazonaws.internal.SdkInternalList<BlockDeviceMapping>(blockDeviceMappings.length));
}
for (BlockDeviceMapping ele : blockDeviceMappings) {
this.blockDeviceMappings.add(ele);
}
return this;
}
/**
* <p>
* The block device mapping entries.
* </p>
*
* @param blockDeviceMappings
* The block device mapping entries.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withBlockDeviceMappings(java.util.Collection<BlockDeviceMapping> blockDeviceMappings) {
setBlockDeviceMappings(blockDeviceMappings);
return this;
}
/**
* <p>
* The ID of the AMI.
* </p>
*
* @param imageId
* The ID of the AMI.
*/
public void setImageId(String imageId) {
this.imageId = imageId;
}
/**
* <p>
* The ID of the AMI.
* </p>
*
* @return The ID of the AMI.
*/
public String getImageId() {
return this.imageId;
}
/**
* <p>
* The ID of the AMI.
* </p>
*
* @param imageId
* The ID of the AMI.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withImageId(String imageId) {
setImageId(imageId);
return this;
}
/**
* <p>
* The launch permissions.
* </p>
*
* @return The launch permissions.
*/
public java.util.List<LaunchPermission> getLaunchPermissions() {
if (launchPermissions == null) {
launchPermissions = new com.amazonaws.internal.SdkInternalList<LaunchPermission>();
}
return launchPermissions;
}
/**
* <p>
* The launch permissions.
* </p>
*
* @param launchPermissions
* The launch permissions.
*/
public void setLaunchPermissions(java.util.Collection<LaunchPermission> launchPermissions) {
if (launchPermissions == null) {
this.launchPermissions = null;
return;
}
this.launchPermissions = new com.amazonaws.internal.SdkInternalList<LaunchPermission>(launchPermissions);
}
/**
* <p>
* The launch permissions.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setLaunchPermissions(java.util.Collection)} or {@link #withLaunchPermissions(java.util.Collection)} if
* you want to override the existing values.
* </p>
*
* @param launchPermissions
* The launch permissions.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withLaunchPermissions(LaunchPermission... launchPermissions) {
if (this.launchPermissions == null) {
setLaunchPermissions(new com.amazonaws.internal.SdkInternalList<LaunchPermission>(launchPermissions.length));
}
for (LaunchPermission ele : launchPermissions) {
this.launchPermissions.add(ele);
}
return this;
}
/**
* <p>
* The launch permissions.
* </p>
*
* @param launchPermissions
* The launch permissions.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withLaunchPermissions(java.util.Collection<LaunchPermission> launchPermissions) {
setLaunchPermissions(launchPermissions);
return this;
}
/**
* <p>
* The product codes.
* </p>
*
* @return The product codes.
*/
public java.util.List<ProductCode> getProductCodes() {
if (productCodes == null) {
productCodes = new com.amazonaws.internal.SdkInternalList<ProductCode>();
}
return productCodes;
}
/**
* <p>
* The product codes.
* </p>
*
* @param productCodes
* The product codes.
*/
public void setProductCodes(java.util.Collection<ProductCode> productCodes) {
if (productCodes == null) {
this.productCodes = null;
return;
}
this.productCodes = new com.amazonaws.internal.SdkInternalList<ProductCode>(productCodes);
}
/**
* <p>
* The product codes.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setProductCodes(java.util.Collection)} or {@link #withProductCodes(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param productCodes
* The product codes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withProductCodes(ProductCode... productCodes) {
if (this.productCodes == null) {
setProductCodes(new com.amazonaws.internal.SdkInternalList<ProductCode>(productCodes.length));
}
for (ProductCode ele : productCodes) {
this.productCodes.add(ele);
}
return this;
}
/**
* <p>
* The product codes.
* </p>
*
* @param productCodes
* The product codes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withProductCodes(java.util.Collection<ProductCode> productCodes) {
setProductCodes(productCodes);
return this;
}
/**
* <p>
* A description for the AMI.
* </p>
*
* @param description
* A description for the AMI.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* A description for the AMI.
* </p>
*
* @return A description for the AMI.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* A description for the AMI.
* </p>
*
* @param description
* A description for the AMI.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The kernel ID.
* </p>
*
* @param kernelId
* The kernel ID.
*/
public void setKernelId(String kernelId) {
this.kernelId = kernelId;
}
/**
* <p>
* The kernel ID.
* </p>
*
* @return The kernel ID.
*/
public String getKernelId() {
return this.kernelId;
}
/**
* <p>
* The kernel ID.
* </p>
*
* @param kernelId
* The kernel ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withKernelId(String kernelId) {
setKernelId(kernelId);
return this;
}
/**
* <p>
* The RAM disk ID.
* </p>
*
* @param ramdiskId
* The RAM disk ID.
*/
public void setRamdiskId(String ramdiskId) {
this.ramdiskId = ramdiskId;
}
/**
* <p>
* The RAM disk ID.
* </p>
*
* @return The RAM disk ID.
*/
public String getRamdiskId() {
return this.ramdiskId;
}
/**
* <p>
* The RAM disk ID.
* </p>
*
* @param ramdiskId
* The RAM disk ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withRamdiskId(String ramdiskId) {
setRamdiskId(ramdiskId);
return this;
}
/**
* <p>
* Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.
* </p>
*
* @param sriovNetSupport
* Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.
*/
public void setSriovNetSupport(String sriovNetSupport) {
this.sriovNetSupport = sriovNetSupport;
}
/**
* <p>
* Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.
* </p>
*
* @return Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.
*/
public String getSriovNetSupport() {
return this.sriovNetSupport;
}
/**
* <p>
* Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.
* </p>
*
* @param sriovNetSupport
* Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withSriovNetSupport(String sriovNetSupport) {
setSriovNetSupport(sriovNetSupport);
return this;
}
/**
* @param bootMode
*/
public void setBootMode(String bootMode) {
this.bootMode = bootMode;
}
/**
* @return
*/
public String getBootMode() {
return this.bootMode;
}
/**
* @param bootMode
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ImageAttribute withBootMode(String bootMode) {
setBootMode(bootMode);
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 (getBlockDeviceMappings() != null)
sb.append("BlockDeviceMappings: ").append(getBlockDeviceMappings()).append(",");
if (getImageId() != null)
sb.append("ImageId: ").append(getImageId()).append(",");
if (getLaunchPermissions() != null)
sb.append("LaunchPermissions: ").append(getLaunchPermissions()).append(",");
if (getProductCodes() != null)
sb.append("ProductCodes: ").append(getProductCodes()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getKernelId() != null)
sb.append("KernelId: ").append(getKernelId()).append(",");
if (getRamdiskId() != null)
sb.append("RamdiskId: ").append(getRamdiskId()).append(",");
if (getSriovNetSupport() != null)
sb.append("SriovNetSupport: ").append(getSriovNetSupport()).append(",");
if (getBootMode() != null)
sb.append("BootMode: ").append(getBootMode());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ImageAttribute == false)
return false;
ImageAttribute other = (ImageAttribute) obj;
if (other.getBlockDeviceMappings() == null ^ this.getBlockDeviceMappings() == null)
return false;
if (other.getBlockDeviceMappings() != null && other.getBlockDeviceMappings().equals(this.getBlockDeviceMappings()) == false)
return false;
if (other.getImageId() == null ^ this.getImageId() == null)
return false;
if (other.getImageId() != null && other.getImageId().equals(this.getImageId()) == false)
return false;
if (other.getLaunchPermissions() == null ^ this.getLaunchPermissions() == null)
return false;
if (other.getLaunchPermissions() != null && other.getLaunchPermissions().equals(this.getLaunchPermissions()) == false)
return false;
if (other.getProductCodes() == null ^ this.getProductCodes() == null)
return false;
if (other.getProductCodes() != null && other.getProductCodes().equals(this.getProductCodes()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getKernelId() == null ^ this.getKernelId() == null)
return false;
if (other.getKernelId() != null && other.getKernelId().equals(this.getKernelId()) == false)
return false;
if (other.getRamdiskId() == null ^ this.getRamdiskId() == null)
return false;
if (other.getRamdiskId() != null && other.getRamdiskId().equals(this.getRamdiskId()) == false)
return false;
if (other.getSriovNetSupport() == null ^ this.getSriovNetSupport() == null)
return false;
if (other.getSriovNetSupport() != null && other.getSriovNetSupport().equals(this.getSriovNetSupport()) == false)
return false;
if (other.getBootMode() == null ^ this.getBootMode() == null)
return false;
if (other.getBootMode() != null && other.getBootMode().equals(this.getBootMode()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getBlockDeviceMappings() == null) ? 0 : getBlockDeviceMappings().hashCode());
hashCode = prime * hashCode + ((getImageId() == null) ? 0 : getImageId().hashCode());
hashCode = prime * hashCode + ((getLaunchPermissions() == null) ? 0 : getLaunchPermissions().hashCode());
hashCode = prime * hashCode + ((getProductCodes() == null) ? 0 : getProductCodes().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getKernelId() == null) ? 0 : getKernelId().hashCode());
hashCode = prime * hashCode + ((getRamdiskId() == null) ? 0 : getRamdiskId().hashCode());
hashCode = prime * hashCode + ((getSriovNetSupport() == null) ? 0 : getSriovNetSupport().hashCode());
hashCode = prime * hashCode + ((getBootMode() == null) ? 0 : getBootMode().hashCode());
return hashCode;
}
@Override
public ImageAttribute clone() {
try {
return (ImageAttribute) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| 7,673 |
543 | /* NiuTrans.Tensor - an open-source tensor library
* Copyright (C) 2020, Natural Language Processing Lab, Northeastern University.
* 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.
*/
/*
* $Created by: <NAME> (<EMAIL>) 2018-07-31
* $Modified by: <NAME> (<EMAIL>) 2020-04
*/
#ifndef __T2TOUTPUT_H__
#define __T2TOUTPUT_H__
#include "T2TUtility.h"
#include "../../../tensor/function/FHeader.h"
using namespace nts;
namespace transformer
{
/* output layer */
class T2TOutput
{
public:
/* device id */
int devID;
/* vocabulary size */
int vSize;
/* vector size of the linear transformation */
int hSize;
/* transformation matrix */
XTensor w;
public:
/* constructor */
T2TOutput();
/* de-constructor */
~T2TOutput();
/* initialize the model */
void InitModel(T2TConfig& config);
/* make the network (redefined output tensor) */
void Make(XTensor& input, XTensor& output, bool isTraining, bool normalized);
};
}
#endif | 491 |
563 | package com.gentics.mesh.example;
import com.gentics.mesh.core.rest.admin.localconfig.LocalConfigModel;
public class LocalConfigExamples {
public LocalConfigModel createExample() {
return new LocalConfigModel().setReadOnly(false);
}
}
| 74 |
815 | /*
*
* Template Numerical Toolkit (TNT)
*
* Mathematical and Computational Sciences Division
* National Institute of Technology,
* Gaithersburg, MD USA
*
*
* This software was developed at the National Institute of Standards and
* Technology (NIST) by employees of the Federal Government in the course
* of their official duties. Pursuant to title 17 Section 105 of the
* United States Code, this software is not subject to copyright protection
* and is in the public domain. NIST assumes no responsibility whatsoever for
* its use by other parties, and makes no guarantees, expressed or implied,
* about its quality, reliability, or any other characteristic.
*
*/
#ifndef TNT_ARRAY1D_H
#define TNT_ARRAY1D_H
#include <cstdlib>
#include <iostream>
#ifdef TNT_BOUNDS_CHECK
#include <assert.h>
#endif
namespace TNT
{
/**
Tempplated one-dimensional, numerical array which
looks like a conventional C array.
Elements are accessed via the familiar A[i] notation.
<p>
Array assignment is by reference (i.e. shallow assignment).
That is, B=A implies that the A and B point to the
same array, so modifications to the elements of A
will be reflected in B. If an independent copy
is required, then B = A.copy() can be used. Note
that this facilitates returning arrays from functions
without relying on compiler optimizations to eliminate
extensive data copying.
<p>
The indexing and layout of this array object makes
it compatible with C and C++ algorithms that utilize
the familiar C[i] notation. This includes numerous
textbooks, such as Numercial Recipes, and various
public domain codes.
<p>
This class employs its own garbage collection via
the use of reference counts. That is, whenever
an internal array storage no longer has any references
to it, it is destroyed.
*/
template <class T>
class Array1D
{
private:
T* v_;
int n_;
int *ref_count_;
void initialize_(int n);
void copy_(T* p, const T* q, int len) const;
void set_(const T& val);
void destroy_();
inline const T* begin_() const;
inline T* begin_();
public:
typedef T value_type;
Array1D();
explicit Array1D(int n);
Array1D(int n, T *a);
Array1D(int n, const T &a);
inline Array1D(const Array1D &A);
inline Array1D & operator=(const T &a);
inline Array1D & operator=(const Array1D &A);
inline Array1D & ref(const Array1D &A);
Array1D copy() const;
Array1D & inject(const Array1D & A);
inline T& operator[](int i);
inline const T& operator[](int i) const;
inline int dim1() const;
inline int dim() const;
inline int ref_count() const;
~Array1D();
};
/**
Null constructor. Creates a 0-length (NULL) array.
(Reference count is also zero.)
*/
template <class T>
Array1D<T>::Array1D() : v_(0), n_(0), ref_count_(0)
{
ref_count_ = new int;
*ref_count_ = 1;
}
/**
Copy constructor. Array data is NOT copied, but shared.
Thus, in Array1D B(A), subsequent changes to A will
be reflected in B. For an indepent copy of A, use
Array1D B(A.copy()), or B = A.copy(), instead.
*/
template <class T>
Array1D<T>::Array1D(const Array1D<T> &A) : v_(A.v_),
n_(A.n_), ref_count_(A.ref_count_)
{
(*ref_count_)++;
}
/**
Create a new array (vector) of length <b>n</b>,
WITHOUT initializing array elements.
To create an initialized array of constants, see Array1D(n,value).
<p>
This version avoids the O(n) initialization overhead and
is used just before manual assignment.
@param n the dimension (length) of the new matrix.
*/
template <class T>
Array1D<T>::Array1D(int n) : v_(0), n_(n), ref_count_(0)
{
initialize_(n);
ref_count_ = new int;
*ref_count_ = 1;
}
/**
Create a new array of length <b>n</b>, initializing array elements to
constant specified by argument. Most often used to
create an array of zeros, as in A(n, 0.0).
@param n the dimension (length) of the new matrix.
@param val the constant value to set all elements of the new array to.
*/
template <class T>
Array1D<T>::Array1D(int n, const T &val) : v_(0), n_(n) ,
ref_count_(0)
{
initialize_(n);
set_(val);
ref_count_ = new int;
*ref_count_ = 1;
}
/**
Create a new n-length array, as a view of an existing one-dimensional
C array. (Note that the storage for this pre-existing array will
never be destroyed by the Aray1DRef class.)
@param n the dimension (length) of the new matrix.
@param a the one dimensional C array to use as data storage for
the array.
*/
template <class T>
Array1D<T>::Array1D(int n, T *a) : v_(a), n_(n) ,
ref_count_(0)
{
ref_count_ = new int;
*ref_count_ = 2; /* this avoid destroying original data. */
}
/**
A[i] indexes the ith element of A. The first element is
A[0]. If TNT_BOUNDS_CHECK is defined, then the index is
checked that it falls within the array bounds.
*/
template <class T>
inline T& Array1D<T>::operator[](int i)
{
#ifdef TNT_BOUNDS_CHECK
assert(i>= 0);
assert(i < n_);
#endif
return v_[i];
}
/**
A[i] indexes the ith element of A. The first element is
A[0]. If TNT_BOUNDS_CHECK is defined, then the index is
checked that it fall within the array bounds.
*/
template <class T>
inline const T& Array1D<T>::operator[](int i) const
{
#ifdef TNT_BOUNDS_CHECK
assert(i>= 0);
assert(i < n_);
#endif
return v_[i];
}
/**
Assign all elemnts of A to a constant scalar.
*/
template <class T>
Array1D<T> & Array1D<T>::operator=(const T &a)
{
set_(a);
return *this;
}
/**
Create a new of existing matrix. Used in B = A.copy()
or in the construction of B, e.g. Array1D B(A.copy()),
to create a new array that does not share data.
*/
template <class T>
Array1D<T> Array1D<T>::copy() const
{
Array1D A( n_);
copy_(A.begin_(), begin_(), n_);
return A;
}
/**
Copy the elements to from one array to another, in place.
That is B.inject(A), both A and B must conform (i.e. have
identical row and column dimensions).
This differs from B = A.copy() in that references to B
before this assignment are also affected. That is, if
we have
<pre>
Array1D A(n);
Array1D C(n);
Array1D B(C); // elements of B and C are shared.
</pre>
then B.inject(A) affects both and C, while B=A.copy() creates
a new array B which shares no data with C or A.
@param A the array from which elements will be copied
@return an instance of the modified array. That is, in B.inject(A),
it returns B. If A and B are not conformat, no modifications to
B are made.
*/
template <class T>
Array1D<T> & Array1D<T>::inject(const Array1D &A)
{
if (A.n_ == n_)
copy_(begin_(), A.begin_(), n_);
return *this;
}
/**
Create a reference (shallow assignment) to another existing array.
In B.ref(A), B and A shared the same data and subsequent changes
to the array elements of one will be reflected in the other.
<p>
This is what operator= calls, and B=A and B.ref(A) are equivalent
operations.
@return The new referenced array: in B.ref(A), it returns B.
*/
template <class T>
Array1D<T> & Array1D<T>::ref(const Array1D<T> &A)
{
if (this != &A)
{
(*ref_count_) --;
if ( *ref_count_ < 1)
{
destroy_();
}
n_ = A.n_;
v_ = A.v_;
ref_count_ = A.ref_count_;
(*ref_count_) ++ ;
}
return *this;
}
/**
B = A is shorthand notation for B.ref(A).
*/
template <class T>
Array1D<T> & Array1D<T>::operator=(const Array1D<T> &A)
{
return ref(A);
}
/**
@return the dimension (number of elements) of the array.
This is equivalent to dim() and dim1().
*/
template <class T>
inline int Array1D<T>::dim1() const { return n_; }
/**
@return the dimension (number of elements) of the array.
This is equivalent to dim1() and dim1().
*/
template <class T>
inline int Array1D<T>::dim() const { return n_; }
/**
@return the number of arrays that share the same storage area
as this one. (Must be at least one.)
*/
template <class T>
inline int Array1D<T>::ref_count() const
{
return *ref_count_;
}
template <class T>
Array1D<T>::~Array1D()
{
(*ref_count_) --;
if (*ref_count_ < 1)
destroy_();
}
/* private internal functions */
template <class T>
void Array1D<T>::initialize_(int n)
{
v_ = new T[n];
n_ = n;
}
template <class T>
void Array1D<T>::set_(const T& a)
{
T *begin = &(v_[0]);
T *end = begin+ n_;
for (T* p=begin; p<end; p++)
*p = a;
}
template <class T>
void Array1D<T>::copy_(T* p, const T* q, int len) const
{
T *end = p + len;
while (p<end )
*p++ = *q++;
}
template <class T>
void Array1D<T>::destroy_()
{
if (v_ != 0)
{
delete[] (v_);
}
if (ref_count_ != 0)
delete ref_count_;
}
/**
@returns location of first element, i.e. A[0] (mutable).
*/
template <class T>
const T* Array1D<T>::begin_() const { return &(v_[0]); }
/**
@returns location of first element, i.e. A[0] (mutable).
*/
template <class T>
T* Array1D<T>::begin_() { return &(v_[0]); }
} /* namespace TNT */
#endif
/* TNT_ARRAY1D_H */
| 3,703 |
394 | <reponame>Mu-L/UVAtlas
//-------------------------------------------------------------------------------------
// UVAtlas - graphcut.cpp
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkID=512686
//-------------------------------------------------------------------------------------
#include "pch.h"
#include "graphcut.h"
using namespace Isochart;
CGraphcut::CGraphcut()
{
}
CGraphcut::~CGraphcut()
{
Clear();
}
void CGraphcut::Clear()
{
graph.Reset();
}
CGraphcut::NODEHANDLE CGraphcut::AddNode()
{
return graph.AddNode();
}
CGraphcut::NODEHANDLE CGraphcut::AddNode(float fSourceWeight, float fSinkWeight)
{
CMaxFlow::node_id hnode = graph.AddNode();
graph.SetTweights(hnode, fSourceWeight, fSinkWeight);
return hnode;
}
HRESULT CGraphcut::AddEges(NODEHANDLE hFromNode, NODEHANDLE hToNode, float fWeight, float fReverseWeight)
{
graph.AddEdge(hFromNode, hToNode, fWeight, fReverseWeight);
return S_OK;
}
HRESULT CGraphcut::SetWeights(NODEHANDLE hNode, float fSourceWeight, float fSinkWeight)
{
graph.SetTweights(hNode, fSourceWeight, fSinkWeight);
return S_OK;
}
HRESULT CGraphcut::CutGraph(float& fMaxflow)
{
graph.ComputeMaxFlow();
fMaxflow = graph.GetFlow();
return S_OK;
}
bool CGraphcut::IsInSourceDomain(NODEHANDLE hNode)
{
return graph.TestToS(hNode);
}
| 574 |
2,829 | /* Copyright 2020 Alibaba Group Holding Limited. 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 "euler/parser/compiler.h"
#include <string>
#include <vector>
#include <memory>
#include "euler/common/str_util.h"
namespace euler {
Compiler::Compiler(int32_t shard_num,
OptimizerType type, std::string index_info):
shard_num_(shard_num), optimizer_(type, shard_num), translator_(type) {
/* parse index info */
std::vector<std::string> index_info_list = Split(index_info, ",");
for (std::string name_type : index_info_list) {
std::vector<std::string> name_type_info = Split(name_type, ":");
index_info_[name_type_info[1]].push_back(name_type_info[0]);
EULER_LOG(INFO) << name_type_info[1] << " : " << name_type_info[0];
}
/* unique -> API_GET_NB_NODE -> gather */
{
std::vector<std::string> adj_info = {"API_GET_NB_NODE:0"};
std::vector<std::vector<std::string>> unique_op_info = {
{"ID_UNIQUE", "0"}};
std::vector<std::vector<std::string>> gather_op_info = {
{"IDX_GATHER", "0", "0"},
{"DATA_GATHER", "0", "1,0"},
{"DATA_GATHER", "0", "2,0"},
{"DATA_GATHER", "0", "3,0"}};
std::shared_ptr<UniqueAndGatherRule> optmz_rule =
std::make_shared<UniqueAndGatherRule>(
adj_info, unique_op_info, gather_op_info);
optimizer_.AddRule(optmz_rule);
}
/* unique -> API_GET_P -> gather */
{
std::vector<std::string> adj_info = {"API_GET_P:0"};
std::vector<std::vector<std::string>> unique_op_info = {
{"ID_UNIQUE", "0"}};
std::vector<std::vector<std::string>> gather_op_info;
std::shared_ptr<UniqueAndGatherRule> optmz_rule =
std::make_shared<UniqueAndGatherRule>(
adj_info, unique_op_info, gather_op_info);
optmz_rule->dynamic_gather_ = true;
optmz_rule->gen_gather_op_info_ =
[](const NodeDef& node,
std::vector<std::vector<std::string>>* gather_op_info) {
for (size_t i = 0; i < node.attrs_.size(); ++i) {
int32_t idx0 = i * 2, idx1 = i * 2 + 1;
gather_op_info->push_back({"IDX_GATHER", "0", ToString(idx0)});
gather_op_info->push_back(
{"DATA_GATHER", "0", ToString(idx1, ",", idx0)});
}
};
optimizer_.AddRule(optmz_rule);
}
/* unique -> API_SAMPLE_NB -> gather */
{
std::vector<std::string> adj_info = {"API_SAMPLE_NB:0"};
std::vector<std::vector<std::string>> unique_op_info = {
{"ID_UNIQUE", "0"}};
std::vector<std::vector<std::string>> gather_op_info = {
{"IDX_GATHER", "0", "0"},
{"DATA_GATHER", "0", "1,0"},
{"DATA_GATHER", "0", "2,0"},
{"DATA_GATHER", "0", "3,0"}};
std::shared_ptr<UniqueAndGatherRule> optmz_rule =
std::make_shared<UniqueAndGatherRule>(
adj_info, unique_op_info, gather_op_info);
optimizer_.AddRule(optmz_rule);
}
/* API_SAMPLE_NB, API_GET_P
* [ID_MERGE_0,
* DATA_MERGE_0, // id
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> DATA_MERGE_1, // weight
* DATA_MERGE_2, // type
* ID_MERGE, DATA_MERGE, ...]
*/
{
std::vector<std::string> adj_info =
{"API_SAMPLE_NB:0 API_SAMPLE_NB:1 API_GET_P:2",
"API_SAMPLE_NB:1", "API_GET_P:2"};
std::vector<std::vector<std::string>>
fusion_output_map; // dynamically gen
std::vector<std::vector<std::string>> split_op_info =
{{"ID_SPLIT", "0"}, {"ID_SPLIT", "1"}};
std::vector<std::vector<std::string>>
merge_op_info; // dynamically gen
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
fusion_nodes_ = {1, 2};
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
dynamic_output_ = true;
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
dynamic_output_list_.push_back(
{
1, // API_SAMPLE_NB
[](const NodeDef& node_m,
const std::vector<std::vector<std::string>>& split_op_info,
std::vector<std::vector<std::string>>* fusion_output_map,
std::vector<std::vector<std::string>>* merge_op_info) {
(void) node_m;
(void) split_op_info;
fusion_output_map->push_back({"API_SAMPLE_NB", "1", "0", "0"});
fusion_output_map->push_back({"API_SAMPLE_NB", "1", "1", "1"});
fusion_output_map->push_back({"API_SAMPLE_NB", "1", "2", "2"});
fusion_output_map->push_back({"API_SAMPLE_NB", "1", "3", "3"});
merge_op_info->push_back({"IDX_MERGE", "split:0", "0"});
merge_op_info->push_back({"DATA_MERGE", "split:0", "1,0"});
merge_op_info->push_back({"DATA_MERGE", "split:0", "2,0"});
merge_op_info->push_back({"DATA_MERGE", "split:0", "3,0"});
}
});
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
dynamic_output_list_.push_back(
{
2, // API_GET_P
[](const NodeDef& node_m,
const std::vector<std::vector<std::string>>& split_op_info,
std::vector<std::vector<std::string>>* fusion_output_map,
std::vector<std::vector<std::string>>* merge_op_info) {
(void) split_op_info;
int32_t base_idx = fusion_output_map->size();
for (size_t i = 0; i < node_m.attrs_.size(); ++i) {
int32_t io0 = i * 2, io1 = i * 2 + 1;
int32_t fo0 = base_idx + io0, fo1 = base_idx + io1;
fusion_output_map->push_back(
{"API_GET_P", "2", ToString(io0), ToString(fo0)});
fusion_output_map->push_back(
{"API_GET_P", "2", ToString(io1), ToString(fo1)});
merge_op_info->push_back(
{"IDX_MERGE", "split:0", ToString(fo0)});
merge_op_info->push_back(
{"DATA_MERGE", "split:0", ToString(fo1, ",", fo0)});
}
}
});
optimizer_.AddRule(optmz_rule);
}
/* API_SAMPLE_NODE:
*
* BROAD_CAST_SPLIT
* -> [REMOTE_0, REMOTE_1 ...] -> APPEND_MERGE
* SAMPLE_NODE_SPLIT
*
*/
{
std::vector<std::string> adj_info = {"API_SAMPLE_NODE:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_SAMPLE_NODE", "0", "0", "0"}};
std::vector<std::vector<std::string>> split_op_info = {
{"BROAD_CAST_SPLIT", "0"}, {"SAMPLE_NODE_SPLIT", "1,0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"APPEND_MERGE", "split:1", "0"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_SAMPLE_N_WITH_TYPES:
*
* BROAD_CAST_SPLIT [MULTI_TYPE_IDX_MERGE,
* -> [REMOTE_0, REMOTE_1 ...]->
* SAMPLE_N_WITH_TYPES_SPLIT MULTI_TYPE_DATA_MERGE]
*
*/
{
std::vector<std::string> adj_info = {"API_SAMPLE_N_WITH_TYPES:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_SAMPLE_N_WITH_TYPES", "0", "0", "0"},
{"API_SAMPLE_N_WITH_TYPES", "0", "1", "1"}};
std::vector<std::vector<std::string>> split_op_info = {
{"BROAD_CAST_SPLIT", "0"}, {"SAMPLE_N_WITH_TYPES_SPLIT", "1,0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"MULTI_TYPE_IDX_MERGE", "split:-1", "0"},
{"MULTI_TYPE_DATA_MERGE", "split:-1", "1,0"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_SAMPLE_EDGE:
*
* BROAD_CAST_SPLIT
* -> [REMOTE_0, REMOTE_1 ...] -> APPEND_MERGE
* SAMPLE_EDGE_SPLIT
*
*/
{
std::vector<std::string> adj_info = {"API_SAMPLE_EDGE:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_SAMPLE_EDGE", "0", "0", "0"}};
std::vector<std::vector<std::string>> split_op_info = {
{"BROAD_CAST_SPLIT", "0"}, {"SAMPLE_EDGE_SPLIT", "1,0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"APPEND_MERGE", "split:1", "0"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_GET_NODE:
*
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> APPEND_MERGE
*/
{
std::vector<std::string> adj_info = {"API_GET_NODE:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_GET_NODE", "0", "0", "0"}};
std::vector<std::vector<std::string>> split_op_info = {{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"APPEND_MERGE", "split:-1", "0"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
// extra cond
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
extra_cond_["API_GET_NODE,0"] = [](const NodeDef& node_m){
return node_m.input_edges_.size() > 0 &&
node_m.attrs_.size() > 0;
};
optimizer_.AddRule(optmz_rule);
}
/* API_GET_NODE:
*
* [REMOTE_0, REMOTE_1 ...] -> APPEND_MERGE
*/
{
std::vector<std::string> adj_info = {"API_GET_NODE:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_GET_NODE", "0", "0", "0"}};
std::vector<std::vector<std::string>> split_op_info;
std::vector<std::vector<std::string>> merge_op_info = {
{"APPEND_MERGE", "split:-1", "0"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
// extra cond
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
extra_cond_["API_GET_NODE,0"] = [](const NodeDef& node_m){
return node_m.input_edges_.size() == 0;
};
optimizer_.AddRule(optmz_rule);
}
/* API_GET_EDGE:
*
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> APPEND_MERGE
*/
{
std::vector<std::string> adj_info = {"API_GET_EDGE:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_GET_EDGE", "0", "0", "0"}};
std::vector<std::vector<std::string>> split_op_info = {{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"APPEND_MERGE", "split:-1", "0"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
// extra cond
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
extra_cond_["API_GET_EDGE,0"] = [](const NodeDef& node_m){
return node_m.input_edges_.size() > 0 &&
node_m.attrs_.size() > 0;
};
optimizer_.AddRule(optmz_rule);
}
/* API_GET_EDGE:
*
* [REMOTE_0, REMOTE_1 ...] -> APPEND_MERGE
*/
{
std::vector<std::string> adj_info = {"API_GET_EDGE:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_GET_EDGE", "0", "0", "0"}};
std::vector<std::vector<std::string>> split_op_info;
std::vector<std::vector<std::string>> merge_op_info = {
{"APPEND_MERGE", "split:-1", "0"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
// extra cond
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
extra_cond_["API_GET_EDGE,0"] = [](const NodeDef& node_m){
return node_m.input_edges_.size() == 0;
};
optimizer_.AddRule(optmz_rule);
}
/* API_GET_NODE_T
*
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> [REGULAR_DATA_MERGE]
*
*/
{
std::vector<std::string> adj_info = {"API_GET_NODE_T:0"};
std::vector<std::vector<std::string>> fusion_output_map {
{"API_GET_NODE_T", "0", "0", "0"}};
std::vector<std::vector<std::string>> split_op_info =
{{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info =
{{"REGULAR_DATA_MERGE", "split:0", "0"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_GET_P:
*
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> [ID_MERGE, DATA_MERGE, ...]
*
*/
{
std::vector<std::string> adj_info = {"API_GET_P:0"};
std::vector<std::vector<std::string>> fusion_output_map; // dynamically gen
std::vector<std::vector<std::string>> split_op_info = {{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info; // dynamically gen
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
dynamic_output_ = true;
std::static_pointer_cast<FusionAndShardRule>(optmz_rule)->
dynamic_output_list_.push_back(
{
0,
[](const NodeDef& node_m,
const std::vector<std::vector<std::string>>& split_op_info,
std::vector<std::vector<std::string>>* fusion_output_map,
std::vector<std::vector<std::string>>* merge_op_info) {
(void) split_op_info;
for (size_t i = 0; i < node_m.attrs_.size(); ++i) {
std::string idx = ToString(i * 2);
fusion_output_map->push_back({"API_GET_P", "0", idx, idx});
merge_op_info->push_back({"IDX_MERGE", "split:0",
ToString(i * 2)});
idx = ToString(i * 2 + 1);
fusion_output_map->push_back({"API_GET_P", "0", idx, idx});
merge_op_info->push_back(
{"DATA_MERGE", "split:0", ToString(i * 2 + 1, ",", i * 2)});
}
}
});
optimizer_.AddRule(optmz_rule);
}
/* API_SAMPLE_NB:
* [ID_MERGE_0,
* DATA_MERGE_0, // id
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> DATA_MERGE_1, // weight
* DATA_MERGE_2] // type
*/
{
std::vector<std::string> adj_info = {"API_SAMPLE_NB:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_SAMPLE_NB", "0", "0", "0"},
{"API_SAMPLE_NB", "0", "1", "1"}, // id
{"API_SAMPLE_NB", "0", "2", "2"}, // weight
{"API_SAMPLE_NB", "0", "3", "3"}}; // type
std::vector<std::vector<std::string>> split_op_info = {{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"IDX_MERGE", "split:0", "0"},
{"DATA_MERGE", "split:0", "1,0"}, // merge id
{"DATA_MERGE", "split:0", "2,0"}, // merge weight
{"DATA_MERGE", "split:0", "3,0"}}; // merge type
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_GET_NB_NODE:
* [ID_MERGE_0,
* DATA_MERGE_0, // id
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> DATA_MERGE_1, // weight
* DATA_MERGE_2] // type
*/
{
std::vector<std::string> adj_info = {"API_GET_NB_NODE:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_GET_NB_NODE", "0", "0", "0"},
{"API_GET_NB_NODE", "0", "1", "1"}, // id
{"API_GET_NB_NODE", "0", "2", "2"}, // weight
{"API_GET_NB_NODE", "0", "3", "3"}}; // type
std::vector<std::vector<std::string>> split_op_info = {{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"IDX_MERGE", "split:0", "0"},
{"DATA_MERGE", "split:0", "1,0"}, // merge id
{"DATA_MERGE", "split:0", "2,0"}, // merge weight
{"DATA_MERGE", "split:0", "3,0"}}; // merge type
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_GET_NB_EDGE:
* [ID_MERGE_0,
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> DATA_MERGE_0, // id
* DATA_MERGE_1] // weight
*/
{
std::vector<std::string> adj_info = {"API_GET_NB_EDGE:0"};
std::vector<std::vector<std::string>> fusion_output_map = {
{"API_GET_NB_EDGE", "0", "0", "0"},
{"API_GET_NB_EDGE", "0", "1", "1"}, // id
{"API_GET_NB_EDGE", "0", "2", "2"}}; // weight
std::vector<std::vector<std::string>> split_op_info = {{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"IDX_MERGE", "split:0", "0"},
{"DATA_MERGE", "split:0", "1,0"}, // merge id
{"DATA_MERGE", "split:0", "2,0"}}; // merge weight
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_GET_EDGE_SUM_WEIGHT:
*
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> [REGULAR_DATA_MERGE,
* REGULAR_DATA_MERGE]
*
*/
{
std::vector<std::string> adj_info = {"API_GET_EDGE_SUM_WEIGHT:0"};
std::vector<std::vector<std::string>> fusion_output_map {
{"API_GET_EDGE_SUM_WEIGHT", "0", "0", "0"},
{"API_GET_EDGE_SUM_WEIGHT", "0", "1", "1"}};
std::vector<std::vector<std::string>> split_op_info = {{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"REGULAR_DATA_MERGE", "split:0", "0"},
{"REGULAR_DATA_MERGE", "split:0", "1"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_SAMPLE_L:
* [REGULAR_DATA_MERGE,
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> REGULAR_DATA_MERGE,
* REGULAR_DATA_MERGE]
*/
{
std::vector<std::string> adj_info = {"API_SAMPLE_L:0"};
std::vector<std::vector<std::string>> fusion_output_map {
{"API_SAMPLE_L", "0", "0", "0"},
{"API_SAMPLE_L", "0", "1", "1"},
{"API_SAMPLE_L", "0", "2", "2"}};
std::vector<std::vector<std::string>> split_op_info = {{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"REGULAR_DATA_MERGE", "split:0", "0"},
{"REGULAR_DATA_MERGE", "split:0", "1"},
{"REGULAR_DATA_MERGE", "split:0", "2"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_GET_ADJ:
*
* ID_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> [REGULAR_DATA_MERGE]
*/
{
std::vector<std::string> adj_info = {"API_GET_ADJ:0"};
std::vector<std::vector<std::string>> fusion_output_map {
{"API_GET_ADJ", "0", "0", "0"}};
std::vector<std::vector<std::string>> split_op_info =
{{"ID_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info =
{{"REGULAR_DATA_MERGE", "split:0", "0"}};
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_SPARSE_GET_ADJ:
*
* ID_SPLIT [ID_MERGE,
* -> [REMOTE_0, REMOTE_1 ...] -> DATA_MERGE
* BROAD_CAST_SPLIT ]
*/
{
std::vector<std::string> adj_info = {"API_SPARSE_GET_ADJ:0"};
std::vector<std::vector<std::string>> fusion_output_map {
{"API_SPARSE_GET_ADJ", "0", "0", "0"},
{"API_SPARSE_GET_ADJ", "0", "1", "1"}};
std::vector<std::vector<std::string>> split_op_info =
{{"ID_SPLIT", "0"}, {"BROAD_CAST_SPLIT", "1"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"IDX_MERGE", "split:0", "0"},
{"DATA_MERGE", "split:0", "1,0"}}; // merge id
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
/* API_GET_GRAPH_BY_LABEL:
* [IDX_ROW_APPEND_MERGE,
* BROAD_CAST_SPLIT -> [REMOTE_0, REMOTE_1 ...] -> DATA_ROW_APPEND_MERGE]
*
*/
{
std::vector<std::string> adj_info = {"API_GET_GRAPH_BY_LABEL:0"};
std::vector<std::vector<std::string>> fusion_output_map {
{"API_GET_GRAPH_BY_LABEL", "0", "0", "0"},
{"API_GET_GRAPH_BY_LABEL", "0", "1", "1"}};
std::vector<std::vector<std::string>> split_op_info =
{{"BROAD_CAST_SPLIT", "0"}};
std::vector<std::vector<std::string>> merge_op_info = {
{"IDX_ROW_APPEND_MERGE", "split:-1", "0"},
{"DATA_ROW_APPEND_MERGE", "split:-1", "1,0"}}; // merge id
std::shared_ptr<OptimizeRule> optmz_rule =
std::make_shared<FusionAndShardRule>(
adj_info, "REMOTE", fusion_output_map,
split_op_info, merge_op_info, shard_num);
optimizer_.AddRule(optmz_rule);
}
}
Compiler* Compiler::instance_ = nullptr;
} // namespace euler
| 11,694 |
6,717 | <reponame>crossmob/WinObjC
//******************************************************************************
//
// Copyright (c) 2016 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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.
//
//******************************************************************************
#pragma once
#import <CoreGraphics/CoreGraphicsExport.h>
#import <CoreGraphics/CGAffineTransform.h>
#import <CoreGraphics/CGPDFDocument.h>
#import <CoreGraphics/CGGeometry.h>
typedef enum {
kCGPDFMediaBox = 0,
kCGPDFCropBox = 1,
kCGPDFBleedBox = 2,
kCGPDFTrimBox = 3,
kCGPDFArtBox = 4,
} CGPDFBox;
COREGRAPHICS_EXPORT CGPDFPageRef CGPDFPageRetain(CGPDFPageRef page) STUB_METHOD;
COREGRAPHICS_EXPORT void CGPDFPageRelease(CGPDFPageRef page) STUB_METHOD;
COREGRAPHICS_EXPORT CFTypeID CGPDFPageGetTypeID() STUB_METHOD;
COREGRAPHICS_EXPORT CGRect CGPDFPageGetBoxRect(CGPDFPageRef page, CGPDFBox box) STUB_METHOD;
COREGRAPHICS_EXPORT CGPDFDictionaryRef CGPDFPageGetDictionary(CGPDFPageRef page) STUB_METHOD;
COREGRAPHICS_EXPORT CGPDFDocumentRef CGPDFPageGetDocument(CGPDFPageRef page) STUB_METHOD;
COREGRAPHICS_EXPORT CGAffineTransform
CGPDFPageGetDrawingTransform(CGPDFPageRef page, CGPDFBox box, CGRect rect, int rotate, bool preserveAspectRatio) STUB_METHOD;
COREGRAPHICS_EXPORT size_t CGPDFPageGetPageNumber(CGPDFPageRef page) STUB_METHOD;
COREGRAPHICS_EXPORT int CGPDFPageGetRotationAngle(CGPDFPageRef page) STUB_METHOD; | 648 |
5,169 | <reponame>Gantios/Specs
{
"name": "QiSlider",
"version": "0.0.4",
"summary": "This is the summary.",
"description": "This is the description.",
"homepage": "https://github.com/QiShare/QiSlider",
"license": "MIT",
"authors": {
"liusiqi": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/QiShare/QiSlider.git",
"tag": "0.0.4"
},
"source_files": "QiSlider/QiSlider/*.{h,m}",
"exclude_files": "Classes/Exclude",
"requires_arc": true
}
| 232 |
769 | /*===- ir.c - Simple test of C APIs ---------------------------------------===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
\*===----------------------------------------------------------------------===*/
/* RUN: circt-capi-ir-test 2>&1 | FileCheck %s
*/
#include "mlir-c/IR.h"
#include "circt-c/Dialect/HW.h"
#include "circt-c/Dialect/Seq.h"
#include "mlir-c/AffineExpr.h"
#include "mlir-c/AffineMap.h"
#include "mlir-c/BuiltinTypes.h"
#include "mlir-c/Diagnostics.h"
#include "mlir-c/Registration.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int registerOnlyHW() {
MlirContext ctx = mlirContextCreate();
// The built-in dialect is always loaded.
if (mlirContextGetNumLoadedDialects(ctx) != 1)
return 1;
// HW dialect tests.
MlirDialectHandle hwHandle = mlirGetDialectHandle__hw__();
MlirDialect hw =
mlirContextGetOrLoadDialect(ctx, mlirDialectHandleGetNamespace(hwHandle));
if (!mlirDialectIsNull(hw))
return 2;
mlirDialectHandleRegisterDialect(hwHandle, ctx);
if (mlirContextGetNumRegisteredDialects(ctx) != 2)
return 3;
if (mlirContextGetNumLoadedDialects(ctx) != 1)
return 4;
hw =
mlirContextGetOrLoadDialect(ctx, mlirDialectHandleGetNamespace(hwHandle));
if (mlirDialectIsNull(hw))
return 5;
if (mlirContextGetNumLoadedDialects(ctx) != 2)
return 6;
MlirDialect alsoRtl = mlirDialectHandleLoadDialect(hwHandle, ctx);
if (!mlirDialectEqual(hw, alsoRtl))
return 7;
// Seq dialect tests.
MlirDialectHandle seqHandle = mlirGetDialectHandle__seq__();
mlirDialectHandleRegisterDialect(seqHandle, ctx);
mlirDialectHandleLoadDialect(seqHandle, ctx);
MlirDialect seq = mlirContextGetOrLoadDialect(
ctx, mlirDialectHandleGetNamespace(seqHandle));
if (mlirDialectIsNull(seq))
return 8;
MlirDialect alsoSeq = mlirDialectHandleLoadDialect(seqHandle, ctx);
if (!mlirDialectEqual(seq, alsoSeq))
return 9;
registerSeqPasses();
mlirContextDestroy(ctx);
return 0;
}
int testHWTypes() {
MlirContext ctx = mlirContextCreate();
MlirDialectHandle hwHandle = mlirGetDialectHandle__hw__();
mlirDialectHandleRegisterDialect(hwHandle, ctx);
mlirDialectHandleLoadDialect(hwHandle, ctx);
MlirType i8type = mlirIntegerTypeGet(ctx, 8);
MlirType io8type = hwInOutTypeGet(i8type);
if (mlirTypeIsNull(io8type))
return 1;
MlirType elementType = hwInOutTypeGetElementType(io8type);
if (mlirTypeIsNull(elementType))
return 2;
if (hwTypeIsAInOut(i8type))
return 3;
if (!hwTypeIsAInOut(io8type))
return 4;
MlirStringRef scope = mlirStringRefCreateFromCString("myscope");
MlirStringRef name = mlirStringRefCreateFromCString("myname");
MlirType typeAliasType = hwTypeAliasTypeGet(scope, name, i8type);
if (mlirTypeIsNull(typeAliasType))
return 5;
if (!hwTypeIsATypeAliasType(typeAliasType))
return 6;
MlirType canonicalType = hwTypeAliasTypeGetCanonicalType(typeAliasType);
if (!mlirTypeEqual(canonicalType, i8type))
return 7;
MlirType innerType = hwTypeAliasTypeGetInnerType(typeAliasType);
if (!mlirTypeEqual(innerType, i8type))
return 8;
MlirStringRef theScope = hwTypeAliasTypeGetScope(typeAliasType);
if (theScope.length != scope.length)
return 9;
MlirStringRef theName = hwTypeAliasTypeGetName(typeAliasType);
if (theName.length != name.length)
return 10;
mlirContextDestroy(ctx);
return 0;
}
int main() {
fprintf(stderr, "@registration\n");
int errcode = registerOnlyHW();
fprintf(stderr, "%d\n", errcode);
fprintf(stderr, "@hwtypes\n");
errcode = testHWTypes();
fprintf(stderr, "%d\n", errcode);
// clang-format off
// CHECK-LABEL: @registration
// CHECK: 0
// CHECK-LABEL: @hwtypes
// CHECK: 0
// clang-format on
return 0;
}
| 1,801 |
1,645 | <reponame>smsahu/seldon-server
/*
* Seldon -- open source prediction engine
* =======================================
*
* Copyright 2011-2015 Seldon Technologies Ltd and Rummble Ltd (http://www.seldon.io/)
*
* ********************************************************************************************
*
* 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.seldon.cc;
import io.seldon.api.resource.ConsumerBean;
import io.seldon.api.resource.service.ItemService;
import io.seldon.clustering.recommender.MemoryUserClusterStore;
import io.seldon.clustering.recommender.UserCluster;
import io.seldon.db.jdo.JDOFactory;
import io.seldon.mf.PerClientExternalLocationListener;
import io.seldon.recommendation.model.ModelManager;
import io.seldon.resources.external.ExternalResourceStreamer;
import io.seldon.resources.external.NewResourceNotifier;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class UserClusterManager implements PerClientExternalLocationListener {
private static Logger logger = Logger.getLogger(UserClusterManager.class.getName());
private final ConcurrentMap<String,MemoryUserClusterStore> clientStores = new ConcurrentHashMap<>();
private final ConcurrentMap<String,ClusterDescription> clusterDescriptions = new ConcurrentHashMap<>();
private Set<NewResourceNotifier> notifiers = new HashSet<>();
private final ExternalResourceStreamer featuresFileHandler;
public static final String CLUSTER_NEW_LOC_PATTERN = "userclusters";
private static UserClusterManager theManager; // hack until rest of code Springified
//private final Executor executor = Executors.newFixedThreadPool(5);
private BlockingQueue<Runnable> queue = new LinkedBlockingDeque<>();
private ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 5, 10, TimeUnit.MINUTES, queue) {
protected void afterExecute(java.lang.Runnable runnable, java.lang.Throwable throwable)
{
JDOFactory.get().cleanupPM();
}
};
private ItemService itemService;
@Autowired
public UserClusterManager(ExternalResourceStreamer featuresFileHandler,NewResourceNotifier notifier,ItemService itemService){
this.featuresFileHandler = featuresFileHandler;
notifiers.add(notifier);
notifier.addListener(CLUSTER_NEW_LOC_PATTERN, this);
this.theManager = this;
this.itemService = itemService;
}
public static UserClusterManager get()
{
return theManager;
}
public void reloadFeatures(final String location, final String client){
executor.execute(new Runnable() {
@Override
public void run() {
logger.info("Reloading user clusters for client: "+ client);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
featuresFileHandler.getResourceStream(location + "/part-00000")
));
MemoryUserClusterStore userClusters = loadUserClusters(client, reader);
clientStores.put(client, userClusters);
reader.close();
logger.info("finished load of user clusters for client "+client);
}
catch (FileNotFoundException e) {
logger.error("Couldn't reloadFeatures for client "+ client, e);
} catch (IOException e) {
logger.error("Couldn't reloadFeatures for client "+ client, e);
}
}
});
}
protected MemoryUserClusterStore loadUserClusters(String client,BufferedReader reader) throws IOException
{
String line;
List<UserCluster> clusters = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
int numUsers = 0;
int numClusters = 0;
long lastUser = -1;
Set<Integer> dimensions = new HashSet<Integer>();
while((line = reader.readLine()) !=null)
{
UserDimWeight data = mapper.readValue(line.getBytes(), UserDimWeight.class);
if (lastUser != data.user)
numUsers++;
clusters.add(new UserCluster(data.user, data.dim, data.weight, 0, 0));
dimensions.add(data.dim);
lastUser = data.user;
numClusters++;
}
MemoryUserClusterStore store = new MemoryUserClusterStore(client,numUsers);
storeClusters(store,clusters);
store.setLoaded(true);
setClusterDescription(client, dimensions);
logger.info("Loaded user clusters for client "+client+" with num users "+numUsers+" and number of clusters "+numClusters);
return store;
}
private void setClusterDescription(String client,Set<Integer> dimensions)
{
ConsumerBean c = new ConsumerBean(client);
Map<Integer,String> clusterNames = new HashMap<>();
try
{
for(Integer dim : dimensions)
{
String[] names = itemService.getDimensionName(c, dim);
if (names != null && names.length == 2)
{
clusterNames.put(dim, names[0]+":"+names[1]);
}
else
logger.warn("Can't find cluster name in db for dimension "+dim+" for "+client);
}
}
catch (Exception e)
{
logger.error("Failed to create cluster descriptions for "+client,e);
}
clusterDescriptions.put(client, new ClusterDescription(clusterNames));
}
private void storeClusters(MemoryUserClusterStore store,List<UserCluster> clusters)
{
long currentUser = -1;
List<UserCluster> userClusters = new ArrayList<>();
for(UserCluster cluster : clusters)
{
if (currentUser != -1 && currentUser != cluster.getUser())
{
store.store(currentUser, userClusters);
userClusters = new ArrayList<>();
}
userClusters.add(cluster);
currentUser = cluster.getUser();
}
if (userClusters.size() > 0)
store.store(currentUser, userClusters);
}
public MemoryUserClusterStore getStore(String client)
{
return clientStores.get(client);
}
public ClusterDescription getClusterDescriptions(String client)
{
return clusterDescriptions.get(client);
}
@Override
public void newClientLocation(String client, String location,
String nodePattern) {
reloadFeatures(location, client);
}
@Override
public void clientLocationDeleted(String client, String nodePattern) {
clientStores.remove(client);
}
public static class ClusterDescription {
public final Map<Integer,String> clusterNames;
public ClusterDescription(Map<Integer, String> clusterNames) {
super();
this.clusterNames = clusterNames;
}
}
}
| 2,707 |
780 | <filename>src/main/java/com/codeborne/selenide/commands/GetPseudoValue.java
package com.codeborne.selenide.commands;
import com.codeborne.selenide.Command;
import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.impl.WebElementSource;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import static com.codeborne.selenide.commands.Util.firstOf;
@ParametersAreNonnullByDefault
public class GetPseudoValue implements Command<String> {
static final String JS_CODE = "return window.getComputedStyle(arguments[0], arguments[1])" +
".getPropertyValue(arguments[2]);";
@Override
@CheckReturnValue
@Nonnull
public String execute(SelenideElement proxy, WebElementSource locator, @Nullable Object[] args) {
String pseudoElement = firstOf(args);
if (args.length > 1) {
String propertyName = (String) args[1];
return locator.driver().executeJavaScript(JS_CODE, locator.getWebElement(), pseudoElement, propertyName);
}
return locator.driver().executeJavaScript(JS_CODE, locator.getWebElement(), pseudoElement, "content");
}
}
| 394 |
6,433 | <reponame>asiekierka/gb-studio
#include <stdio.h>
void puts(const char *s) NONBANKED
{
while (*s)
putchar(*s++);
putchar('\n');
}
| 69 |
791 | <gh_stars>100-1000
#define LDSO_ARCH "x32"
/* FIXME: x32 is very strange in its use of 64-bit relocation types in
* a 32-bit environment. As long as the memory at reloc_addr is
* zero-filled prior to relocations, just treating 64-bit relocations
* as operating on 32-bit slots should be fine, but this should be
* checked. In particular, R_X86_64_64, R_X86_64_DTPOFF64, and
* R_X86_64_TPOFF64 may need checking. */
/* The R_X86_64_64, R_X86_64_DTPOFF32, and R_X86_64_TPOFF32 reloc types
* were previously mapped in the switch table form of this file; however,
* they do not seem to be used/usable for anything. If needed, new
* mappings will have to be added. */
#define REL_SYMBOLIC R_X86_64_32
#define REL_OFFSET R_X86_64_PC32
#define REL_GOT R_X86_64_GLOB_DAT
#define REL_PLT R_X86_64_JUMP_SLOT
#define REL_RELATIVE R_X86_64_RELATIVE
#define REL_COPY R_X86_64_COPY
#define REL_DTPMOD R_X86_64_DTPMOD64
#define REL_DTPOFF R_X86_64_DTPOFF64
#define REL_TPOFF R_X86_64_TPOFF64
#define CRTJMP(pc,sp) __asm__ __volatile__( \
"mov %1,%%esp ; jmp *%0" : : "r"((uint64_t)(uintptr_t)pc), "r"(sp) : "memory" )
#define GETFUNCSYM(fp, sym, got) __asm__ ( \
".hidden " #sym "\n" \
" lea " #sym "(%%rip),%0\n" \
: "=r"(*fp) : : "memory" )
| 569 |
348 | {"nom":"<NAME>","circ":"5ème circonscription","dpt":"Ain","inscrits":521,"abs":280,"votants":241,"blancs":12,"nuls":3,"exp":226,"res":[{"nuance":"LR","nom":"<NAME>","voix":130},{"nuance":"REM","nom":"<NAME>","voix":96}]} | 89 |
403 | package com.codedisaster.steamworks;
@SuppressWarnings("unused")
class SteamNetworkingCallbackAdapter extends SteamCallbackAdapter<SteamNetworkingCallback> {
SteamNetworkingCallbackAdapter(SteamNetworkingCallback callback) {
super(callback);
}
void onP2PSessionConnectFail(long steamIDRemote, int sessionError) {
SteamID id = new SteamID(steamIDRemote);
callback.onP2PSessionConnectFail(id, SteamNetworking.P2PSessionError.byOrdinal(sessionError));
}
void onP2PSessionRequest(long steamIDRemote) {
SteamID id = new SteamID(steamIDRemote);
callback.onP2PSessionRequest(id);
}
}
| 187 |
713 | <reponame>alionkun/LightCTR_commented<filename>LightCTR/common/thread_pool.h
//
// thread_pool.h
// LightCTR
//
// Created by SongKuangshi on 2017/9/23.
// Copyright © 2017年 SongKuangshi. All rights reserved.
//
#ifndef thread_pool_h
#define thread_pool_h
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <atomic>
#include "assert.h"
static std::atomic<bool> isSynchronized(true);
inline void setNotSynchronized() {
isSynchronized.store(false, std::memory_order_release);
}
inline void synchronize() {
if(isSynchronized.load(std::memory_order_acquire)) {
return;
}
isSynchronized.store(true, std::memory_order_release);
}
class ThreadPool {
public:
explicit ThreadPool(size_t);
ThreadPool() = delete;
~ThreadPool();
static ThreadPool& Instance() { // singleton
static ThreadPool threadpool(std::thread::hardware_concurrency());
return threadpool;
}
template<class F, class... Args>
auto addTask(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
void wait();
private:
void init();
size_t threads;
std::vector<std::thread> workers;
std::queue<std::function<void()> > tasks;
std::mutex queue_mutex;
std::condition_variable condition;
std::atomic<bool> stop{false};
};
inline ThreadPool::ThreadPool(size_t _threads): threads(_threads) {
init();
}
inline void ThreadPool::init() {
if (!workers.empty()) {
return;
}
stop = false;
for(size_t i = 0;i < threads; i++) {
workers.emplace_back([this] {
for(;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock, [this] {
return this->stop || !this->tasks.empty();
});
if(this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}
template<class F, class... Args>
auto ThreadPool::addTask(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type> {
if (workers.empty()) {
init();
}
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> ret = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace([task](){
(*task)();
});
}
condition.notify_one();
return ret;
}
inline void ThreadPool::wait() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all(); // notify to stop
for (auto &worker : workers) {
worker.join();
}
workers.clear();
}
// destruct after join all threads
inline ThreadPool::~ThreadPool() {
wait();
}
template <class T>
class ThreadLocal {
public:
ThreadLocal() {
assert(pthread_key_create(&threadSpecificKey_, dataDestructor) == 0);
}
~ThreadLocal() {
pthread_key_delete(threadSpecificKey_);
}
// get thread local object
inline T* get(bool createLocal = true) {
T* p = (T*)pthread_getspecific(threadSpecificKey_);
if (!p && createLocal) {
p = new T();
assert(pthread_setspecific(threadSpecificKey_, p) == 0);
}
return p;
}
// overwrite threadlocal object and destructed last one
inline void set(T* p) {
if (T* q = get(false)) {
dataDestructor(q);
}
assert(pthread_setspecific(threadSpecificKey_, p) == 0);
}
T& operator*() { return *get(); }
operator T*() {
return get();
}
private:
static void dataDestructor(void* p) {
delete (T*)p;
}
pthread_key_t threadSpecificKey_;
};
#endif /* thread_pool_h */
| 1,962 |
852 | from __future__ import print_function
import FWCore.ParameterSet.Config as cms
import os, sys, imp, re
import FWCore.ParameterSet.VarParsing as VarParsing
import subprocess
import copy
from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
#sys.path(".")
############################################################
### SETUP OPTIONS
options = VarParsing.VarParsing('standard')
options.register('isCrab',
1, # default Value = true
VarParsing.VarParsing.multiplicity.singleton, # singleton or list
VarParsing.VarParsing.varType.int, # string, int, or float
"change files path in case of local test: isCrab=0 if you are running it locally with cmsRun")
options.register ('type',
"ALCARAW",
VarParsing.VarParsing.multiplicity.singleton,
VarParsing.VarParsing.varType.string,
"type of operations: ALCARAW, ALCARERECO, ALCARECO, ALCARECOSIM, AOD, RECO, SKIMEFFTEST")
options.register ('tagFile',
"",
VarParsing.VarParsing.multiplicity.singleton,
VarParsing.VarParsing.varType.string,
"path of the file with the reReco tags")
options.register('skim',
"",
VarParsing.VarParsing.multiplicity.singleton,
VarParsing.VarParsing.varType.string,
"type of skim: ZSkim, WSkim, ZHLTSkim, partGun, ZmmgSkim, EleSkim (at least one electron), ''")
options.register('jsonFile',
"",
VarParsing.VarParsing.multiplicity.singleton,
VarParsing.VarParsing.varType.string,
"path and name of the json file")
options.register('doTree',
0, #default value False
VarParsing.VarParsing.multiplicity.singleton, # singleton or list
VarParsing.VarParsing.varType.int, # string, int, or float
"doTree=0: no tree; 1: standard tree; 2: onlyExtraTree; 3: standard+extra; 4:only eleID; 5:eleID+standard; 6: eleID+extra; 7: standard+extra+eleID")
options.register('doTreeOnly',
0, #default value False
VarParsing.VarParsing.multiplicity.singleton, # singleton or list
VarParsing.VarParsing.varType.int, # string, int, or float
"bool: doTreeOnly=1 true, doTreeOnly=0 false")
options.register('pdfSyst',
0, #default value False
VarParsing.VarParsing.multiplicity.singleton, # singleton or list
VarParsing.VarParsing.varType.int, # string, int, or float
"bool: pdfSyst=1 true, pdfSyst=0 false")
### setup any defaults you want
options.output="alcaSkimALCARAW.root"
options.secondaryOutput="ntuple.root"
options.files= ""
options.maxEvents = -1 # -1 means all events
### get and parse the command line arguments
options.parseArguments()
print(options)
############################################################
# Use the options
# Do you want to filter events?
HLTFilter = False
ZSkim = False
WSkim = False
ZmmgSkim = False
if(options.skim=="ZSkim"):
ZSkim=True
elif(options.skim=="WSkim"):
WSkim=True
elif(options.skim=="ZHLTSkim"):
HLTFilter=True
elif(options.skim=="ZmmgSkim"):
ZmmgSkim=True
else:
if(options.type=="ALCARAW"):
print("[ERROR] no skim selected")
sys.exit(-1)
MC = False # please specify it if starting from AOD
if(options.type == "ALCARAW"):
processName = 'ALCASKIM'
elif(options.type == "ALCARERECO"):
processName = 'ALCARERECO'
elif(options.type == "ALCARECOSIM"):
processName = 'ALCARECO'
MC = True
elif(options.type == "ALCARECO"):
processName = 'ALCARECO'
MC = False
elif(options.type == 'SKIMEFFTEST'):
processName = 'SKIMEFFTEST'
MC = True
else:
print("[ERROR] wrong type defined")
sys.exit(-1)
doTreeOnly=False
if(options.doTree>0 and options.doTreeOnly==1):
print("doTreeOnly")
doTreeOnly=True
processName = processName+'DUMP'
# _____ __ _ _ _
# / ____|/ _| | | | | | |
# | | | |_ __ _ ___| |_ __ _ _ __| |_ ___ | |__ ___ _ __ ___
# | | | _/ _` | / __| __/ _` | '__| __/ __| | '_ \ / _ \ '__/ _ \
# | |____| || (_| | \__ \ || (_| | | | |_\__ \ | | | | __/ | | __/
# \_____|_| \__, | |___/\__\__,_|_| \__|___/ |_| |_|\___|_| \___|
# __/ |
# |___/
CMSSW_VERSION=os.getenv("CMSSW_VERSION")
CMSSW_BASE=os.getenv("CMSSW_BASE")
process = cms.Process(processName)
# import of standard configurations
process.load('Configuration.StandardSequences.Services_cff')
process.load('Configuration.StandardSequences.RawToDigi_Data_cff')
process.load('Configuration.StandardSequences.L1Reco_cff')
process.load('Configuration.StandardSequences.Reconstruction_Data_cff')
process.load('Configuration.StandardSequences.EndOfProcess_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('Configuration.StandardSequences.GeometryDB_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff')
process.load('Configuration.EventContent.EventContent_cff')
# import of ALCARECO sequences
process.load('Calibration.EcalAlCaRecoProducers.ALCARECOEcalCalIsolElectron_Output_cff')
process.load('Calibration.EcalAlCaRecoProducers.ALCARECOEcalUncalIsolElectron_Output_cff')
from Calibration.EcalAlCaRecoProducers.sandboxRerecoOutput_cff import *
#process.load('Configuration.StandardSequences.AlCaRecoStreams_cff') # this is for official ALCARAW ALCARECO production
process.load('Calibration.EcalAlCaRecoProducers.ALCARECOEcalCalIsolElectron_cff') # reduction of recHits
process.load("Calibration.EcalAlCaRecoProducers.PUDumper_cfi")
if (re.match("CMSSW_5_.*",CMSSW_VERSION) or re.match("CMSSW_6_.*",CMSSW_VERSION)):
process.load('Calibration.EcalAlCaRecoProducers.ALCARECOEcalUncalIsolElectron_cff') # ALCARAW
#from Calibration.EcalAlCaRecoProducers.ALCARECOEcalCalIsolElectron_cff import *
# this module provides:
#process.seqALCARECOEcalUncalElectron = uncalibRecHitSeq
process.load('Calibration.EcalAlCaRecoProducers.sandboxRerecoSeq_cff') # ALCARERECO
# this module provides:
# process.electronRecoSeq
# process.electronClusteringSeq # with ele-SC reassociation
# process.sandboxRerecoSeq = (electronRecoSeq * electronClusteringSeq)
# Tree production
process.load('Calibration.ZNtupleDumper.ntupledumper_cff')
# ntuple
# added by Shervin for ES recHits (saved as in AOD): large window 15x3 (strip x row)
process.load('RecoEcal.EgammaClusterProducers.interestingDetIdCollectionProducer_cfi')
# pdfSystematics
process.load('Calibration.EcalAlCaRecoProducers.pdfSystematics_cff')
process.MessageLogger.cerr = cms.untracked.PSet(
INFO = cms.untracked.PSet(
limit = cms.untracked.int32(0)
),
noTimeStamps = cms.untracked.bool(False),
FwkReport = cms.untracked.PSet(
reportEvery = cms.untracked.int32(1000),
limit = cms.untracked.int32(10000000)
),
default = cms.untracked.PSet(
limit = cms.untracked.int32(10000000)
),
Root_NoDictionary = cms.untracked.PSet(
limit = cms.untracked.int32(0)
),
FwkSummary = cms.untracked.PSet(
reportEvery = cms.untracked.int32(1),
limit = cms.untracked.int32(10000000)
),
threshold = cms.untracked.string('INFO')
)
if(options.isCrab==0):
process.MessageLogger.cerr.FwkReport.reportEvery = 1
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(options.maxEvents)
)
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(options.files),
secondaryFileNames = cms.untracked.vstring(options.secondaryFiles)
)
# try to drop as much as possible to reduce the running time
# process.source.inputCommands = cms.untracked.vstring("keep *",
# "drop recoPFTaus*_*_*_*",
# "drop recoPFTauDiscriminator*_*_*_*",
# "drop *_tevMuons*_*_*",
# # "drop *muon*_*_*_*",
# # "keep *Electron*_*_*_",
# # "keep *electron*_*_*_*"
# )
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.bool(True)
)
# Other statements
#
if(len(options.tagFile)>0):
execfile(options.tagFile) # load the GT
process.GlobalTag = RerecoGlobalTag
else:
if(options.type=="ALCARERECO" and not doTreeOnly):
print("******************************")
print("[ERROR] no file with tags specified, but rereco requested")
sys.exit(1)
if(re.match("CMSSW_4_2_.*",CMSSW_VERSION)):
if (MC):
print("[INFO] Using GT START42_V17::All")
process.GlobalTag.globaltag = 'START42_V17::All'
else:
print("[INFO] Using GT FT_R_42_V24::All") #GR_P_V22::All"
process.GlobalTag.globaltag = 'FT_R_42_V24::All' #'GR_P_V22::All' #GR_R_42_V21B::All' # rereco30Nov
elif(re.match("CMSSW_4_4_.*", CMSSW_VERSION)):
if (MC):
print("[INFO] Using GT START44_V13::All")
process.GlobalTag.globaltag = 'START44_V13::All'
else:
print("[INFO] Using GT GR_R_44_V15C::All")
#process.GlobalTag.globaltag = 'GR_R_44_V12::All'
process.GlobalTag.globaltag = 'GR_R_44_V15C::All'
elif(re.match("CMSSW_5_2_.*",CMSSW_VERSION)):
if(MC):
print("[INFO] Using GT START52_V16::All")
process.GlobalTag.globaltag = 'START52_V16::All'
else:
process.GlobalTag.globaltag = 'GR_P_V32::All' # 5_2_0 Prompt
# process.GlobalTag.globaltag = 'GR_R_52_V7::All' # 5_2_0
elif(re.match("CMSSW_5_3_11_patch3",CMSSW_VERSION)):
if(MC):
print("[INFO] Using GT START53_LV4::All")
process.GlobalTag.globaltag = 'START53_V7C::All'
# process.GlobalTag.globaltag = 'START53_LV4::All'
else:
process.GlobalTag.globaltag = 'FT_R_53_V21::All' #22Jan rereco
elif(re.match("CMSSW_5_3_.*",CMSSW_VERSION)):
if(MC):
print("[INFO] Using GT START53_V7N::All")
process.GlobalTag.globaltag = 'START53_V7N::All' # run dep MC
# print "[INFO] Using GT START53_V7G::All"
# process.GlobalTag.globaltag = 'START53_V7G::All' # suggested for analysis std. MC
else:
print("[INFO] Using GT FT_R_53_V21N::All")
process.GlobalTag.globaltag = 'FT_R_53_V21::All' #GR_P_V42B::All' # 5_3_3 Prompt
#process.GlobalTag.globaltag = 'FT_R_53_LV3::All' #21Jun rereco 53X 2011 data
#process.GlobalTag.globaltag = 'GR_R_53_V9F::All' # GT for 53 rereco (2011)
if(options.files==""):
process.source.fileNames=[ 'root://cms-xrd-global.cern.ch//store/data/Run2012A/DoubleElectron/AOD/22Jan2013-v1/20000/003EC246-5E67-E211-B103-00259059642E.root' ]
elif(re.match("CMSSW_6_1_.*",CMSSW_VERSION)):
if(MC):
print("[INFO] Using GT START61_V11::All")
process.GlobalTag.globaltag = 'START61_V11::All'
else:
process.GlobalTag.globaltag = 'GR_P_V42B::All' # 5_3_3 Prompt
elif(re.match("CMSSW_7_0_.*",CMSSW_VERSION)):
if(MC):
print("[INFO] Using GT POSTLS162_V5::All")
process.GlobalTag.globaltag = 'POSTLS162_V5::All'
else:
process.GlobalTag.globaltag = 'GR_R_62_V3::All'
if(options.files==""):
process.source.fileNames=[ 'root://cms-xrd-global.cern.ch//store/data/Run2012D/DoubleElectron/AOD/15Apr2014-v1/00000/0EA11D35-0CD5-E311-862E-0025905A6070.root' ]
elif(re.match("CMSSW_7_4_.*",CMSSW_VERSION)):
if(MC):
print("[INFO] Using GT POSTLS162_V5::All")
process.GlobalTag.globaltag = 'POSTLS162_V5::All'
else:
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_data', '')
if(options.files==""):
process.source.fileNames=[ 'root://cms-xrd-global.cern.ch//store/data/Run2012D/DoubleElectron/AOD/15Apr2014-v1/00000/0EA11D35-0CD5-E311-862E-0025905A6070.root' ]
else:
print("[ERROR]::Global Tag not set for CMSSW_VERSION: ", CMSSW_VERSION)
sys.exit(1)
if(re.match("CMSSW_7_.*",CMSSW_VERSION)):
myEleCollection = cms.InputTag("gedGsfElectrons")
else:
myEleCollection = cms.InputTag("gsfElectrons")
#Define the sequences
#
# particle flow isolation
#
process.pfIsoEgamma = cms.Sequence()
if((options.type=='ALCARECO' or options.type=='ALCARECOSIM' or options.type=='ALCARAW') and not re.match("CMSSW_7_.*_.*",CMSSW_VERSION)):
from CommonTools.ParticleFlow.Tools.pfIsolation import setupPFElectronIso, setupPFMuonIso
process.eleIsoSequence = setupPFElectronIso(process, 'gsfElectrons', 'PFIso')
process.pfIsoEgamma *= (process.pfParticleSelectionSequence + process.eleIsoSequence)
elif((options.type=='ALCARECO' or options.type=='ALCARECOSIM' or options.type=='ALCARAW') and re.match("CMSSW_7_.*_.*",CMSSW_VERSION)):
process.pfisoALCARECO = cms.Sequence() # remove any modules
###############################/
# Event filter sequence: process.filterSeq
# sanbox sequence: process.seqALCARECOEcalUncalElectron + process.alcarecoElectronTracksReducerSeq
# sandbox rereco sequence: process.sandboxRerecoSeq
# alcareco event reduction: process.alcarecoSeq
#
################################# FILTERING EVENTS
process.PUDumperSeq = cms.Sequence()
#process.load('Calibration.EcalAlCaRecoProducers.trackerDrivenFinder_cff')
if(MC):
# PUDumper
process.TFileService = cms.Service(
"TFileService",
fileName = cms.string("PUDumper.root")
)
process.PUDumperSeq *= process.PUDumper
if(re.match("CMSSW_5_.*", CMSSW_VERSION)):
process.load('Calibration.EcalAlCaRecoProducers.WZElectronSkims53X_cff')
else:
process.load('Calibration.EcalAlCaRecoProducers.WZElectronSkims_cff')
process.load('DPGAnalysis.Skims.ZmmgSkim_cff')
process.MinMuonNumberFilter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag("muons"),
minNumber = cms.uint32(2))
process.MinPhoNumberFilter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag("gedPhotons"),
minNumber = cms.uint32(1))
process.MinEleNumberFilter = cms.EDFilter("CandViewCountFilter",
src = myEleCollection,
minNumber = cms.uint32(1))
if (ZmmgSkim==True):
process.filterSeq = cms.Sequence(process.MinMuonNumberFilter * process.MinPhoNumberFilter)
else:
process.filterSeq = cms.Sequence(process.MinEleNumberFilter)
if (HLTFilter):
from HLTrigger.HLTfilters.hltHighLevel_cfi import *
process.ZEEHltFilter = copy.deepcopy(hltHighLevel)
process.ZEEHltFilter.throw = cms.bool(False)
process.ZEEHltFilter.HLTPaths = [ "HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_*"]
process.filterSeq *= process.ZEEHltFilter
from HLTrigger.HLTfilters.hltHighLevel_cfi import *
process.NtupleFilter = copy.deepcopy(hltHighLevel)
process.NtupleFilter.throw = cms.bool(False)
process.NtupleFilter.HLTPaths = [ 'pathALCARECOEcalUncalZElectron', 'pathALCARECOEcalUncalWElectron',
'pathALCARECOEcalCalZElectron', 'pathALCARECOEcalCalWElectron',
'pathALCARECOEcalUncalZSCElectron', 'pathALCARECOEcalCalZSCElectron',
'pathALCARECOEcalUncalSingleElectron', 'pathALCARECOEcalCalSingleElectron',
]
process.NtupleFilter.TriggerResultsTag = cms.InputTag("TriggerResults","","ALCARECO")
#
process.NtupleFilterSeq = cms.Sequence()
#process.NtupleFilterSeq = cms.Sequence(process.WZFilter)
if(ZSkim):
process.NtupleFilterSeq = cms.Sequence(process.WZFilter)
# process.NtupleFilterSeq= cms.Sequence(process.NtupleFilter)
process.NtupleFilter.HLTPaths = [ 'pathALCARECOEcalCalZElectron', 'pathALCARECOEcalUncalZElectron',
'pathALCARECOEcalCalZSCElectron', 'pathALCARECOEcalUncalZSCElectron',
]
elif(WSkim):
process.NtupleFilterSeq = cms.Sequence(process.WZFilter)
# process.NtupleFilterSeq= cms.Sequence(process.NtupleFilter)
process.NtupleFilter.HLTPaths = [ 'pathALCARECOEcalCalWElectron', 'pathALCARECOEcalUncalWElectron' ]
elif(ZmmgSkim):
process.NtupleFilterSeq = cms.Sequence(process.ZmmgSkimSeq)
process.NtupleFilter.HLTPaths = [ 'pathALCARECOEcalCalZmmgPhoton', 'pathALCARECOEcalUncalZmmgPhoton' ]
elif(options.skim=="no" or options.skim=="NO" or options.skim=="none" or options.skim=="NONE"):
process.NtupleFilterSeq = cms.Sequence()
if(options.skim=="partGun"):
process.zNtupleDumper.isPartGun = cms.bool(True)
###############################
# ECAL Recalibration
###############################
#============================== TO BE CHECKED FOR PRESHOWER
process.load("RecoEcal.EgammaClusterProducers.reducedRecHitsSequence_cff")
process.reducedEcalRecHitsES.scEtThreshold = cms.double(0.)
process.reducedEcalRecHitsES.EcalRecHitCollectionES = cms.InputTag('ecalPreshowerRecHit','EcalRecHitsES')
process.reducedEcalRecHitsES.noFlag = cms.bool(True)
process.reducedEcalRecHitsES.OutputLabel_ES = cms.string('alCaRecHitsES')
#==============================
try:
EcalTrivialConditionRetriever
except NameError:
#print "well, it WASN'T defined after all!"
process.trivialCond = cms.Sequence()
else:
print("** TrivialConditionRetriver defined")
process.trivialCond = cms.Sequence( EcalTrivialConditionRetriever )
if(re.match("CMSSW_6_.*", CMSSW_VERSION) or re.match("CMSSW_7_.*", CMSSW_VERSION)):
process.alcarerecoSeq=cms.Sequence( process.trivialCond * process.sandboxPFRerecoSeq * (process.seqALCARECOEcalCalElectronRECO + process.reducedEcalRecHitsES))
else:
process.alcarerecoSeq=cms.Sequence( process.trivialCond * process.sandboxRerecoSeq * (process.seqALCARECOEcalCalElectronRECO + process.reducedEcalRecHitsES))
process.rhoFastJetSeq = cms.Sequence()
process.jsonFilter = cms.Sequence()
if((not options.type=="ALCARERECO") ):
process.rhoFastJetSeq = cms.Sequence(process.kt6PFJetsForRhoCorrection)
if (options.skim=="ZmmgSkim"):
process.patSequence=cms.Sequence( (process.muonSelectionProducers * process.phoSelectionProducers) * process.patMuons * process.patPhotons )
process.patSequenceMC=cms.Sequence( process.muonMatch * process.photonMatch * (process.muonSelectionProducers * process.phoSelectionProducers ) * process.patMuons * process.patPhotons )
if(MC):
process.ntupleSeq = cms.Sequence(process.jsonFilter * process.patSequenceMC)
else:
process.ntupleSeq = cms.Sequence(process.jsonFilter * process.patSequence)
if(options.doTree==2 or options.doTree==4 or options.doTree==6 or options.doTree==8):
process.zNtupleDumper.doStandardTree = cms.bool(False)
if(options.doTree==2 or options.doTree==3 or options.doTree==6 or options.doTree==7 or options.doTree==10 or options.doTree==11 or options.doTree==14 or options.doTree==15): # it's a bit mask
process.zNtupleDumper.doExtraCalibTree=cms.bool(True)
if(options.doTree==4 or options.doTree==5 or options.doTree==6 or options.doTree==7 or options.doTree==12 or options.doTree==13 or options.doTree==14 or options.doTree==15): # it's a bit mask
process.zNtupleDumper.doEleIDTree=cms.bool(True)
if(MC and options.pdfSyst==1):
process.pdfWeightsSeq = cms.Sequence(process.pdfWeights + process.weakWeight + process.fsrWeight)
process.zNtupleDumper.pdfWeightCollections = cms.VInputTag(cms.InputTag('pdfWeights:cteq66'), cms.InputTag("pdfWeights:MRST2006nnlo"), cms.InputTag('pdfWeights:NNPDF10'))
else:
process.pdfWeightsSeq = cms.Sequence()
############################################################
# OUTPUT MODULES
##############################
fileName = cms.untracked.string(options.output)
process.outputALCARAW = cms.OutputModule("PoolOutputModule",
# after 5 GB split the file
maxSize = cms.untracked.int32(5120000),
outputCommands = process.OutALCARECOEcalUncalElectron.outputCommands,
#fileName = fileName,
fileName = cms.untracked.string('alcaraw.root'),
SelectEvents = process.OutALCARECOEcalUncalElectron.SelectEvents,
dataset = cms.untracked.PSet(
filterName = cms.untracked.string(''),
dataTier = cms.untracked.string('ALCARECO')
)
)
process.outputALCARECO = cms.OutputModule("PoolOutputModule",
# after 5 GB split the file
maxSize = cms.untracked.int32(5120000),
outputCommands = process.OutALCARECOEcalCalElectron.outputCommands,
fileName = cms.untracked.string('alcareco.root'),
SelectEvents = process.OutALCARECOEcalCalElectron.SelectEvents,
dataset = cms.untracked.PSet(
filterName = cms.untracked.string(''),
dataTier = cms.untracked.string('ALCARECO')
)
)
process.zNtupleDumper.SelectEvents = process.NtupleFilter.HLTPaths
process.outputALCARERECO = cms.OutputModule("PoolOutputModule",
# after 5 GB split the file
maxSize = cms.untracked.int32(5120000),
outputCommands = process.OutALCARECOEcalCalElectron.outputCommands,
fileName = cms.untracked.string('alcarereco.root'),
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARERECOEcalCalElectron')
),
dataset = cms.untracked.PSet(
filterName = cms.untracked.string(''),
dataTier = cms.untracked.string('ALCARECO')
)
)
process.outputRECO = cms.OutputModule("PoolOutputModule",
# after 5 GB split the file
maxSize = cms.untracked.int32(5120000),
outputCommands = cms.untracked.vstring('keep *'),
fileName = cms.untracked.string('RECO.root'),
SelectEvents = process.OutALCARECOEcalCalElectron.SelectEvents,
dataset = cms.untracked.PSet(
filterName = cms.untracked.string(''),
dataTier = cms.untracked.string('RECO')
)
)
#print "OUTPUTCOMMANDS"
#print process.outputALCARECO.outputCommands
# if(options.pdfSyst==1):
# process.TFileService = cms.Service("TFileService",
# fileName = cms.string("ntupleExtra.root"),
# closeFileFast = cms.untracked.bool(True)
# )
##############################################################
# Setting Path
################################
process.raw2digi_step = cms.Path(process.RawToDigi)
process.L1Reco_step = cms.Path(process.L1Reco)
process.reconstruction_step = cms.Path(process.reconstruction)
process.endjob_step = cms.EndPath(process.endOfProcess)
#process.endjob_step*=process.outputRECO
# Skim check paths to measure efficiency and purity of the skims
# reco efficiencies are not taken into account
# eff = N_skim/N_gen | after reco requirements and gen filter
# purity = N_gen/N_skim | after reco requirements and skim filter
process.GenSkimFilter = cms.EDFilter("SkimCheck",
type=cms.int32(0)
)
process.GenZSCSkimFilter = cms.EDFilter("SkimCheck",
type= cms.int32(2)
)
process.GenWSkimFilter = cms.EDFilter("SkimCheck",
type= cms.int32(1)
)
process.GenZmmgSkimFilter = cms.EDFilter("SkimCheck",
type= cms.int32(1)
)
process.pathZElectronSkimGen = cms.Path(process.filterSeq * process.FilterSeq *
process.GenSkimFilter *
process.ZeeFilter
)
process.pathZSCElectronSkimGen = cms.Path(process.filterSeq * process.FilterSeq * process.MinZSCNumberFilter *
process.GenZSCSkimFilter *
~process.ZeeFilter * process.ZSCFilter
)
process.pathWElectronSkimGen = cms.Path(process.filterSeq * process.FilterSeq *
process.GenWSkimFilter *
~process.ZeeFilter * ~process.ZSCFilter * process.WenuFilter
)
process.pathZElectronSkim = cms.Path(process.filterSeq * process.FilterSeq *
process.ZeeFilter
# process.GenSkimFilter
)
process.pathZmmgSkim = cms.Path(process.filterSeq * process.FilterMuSeq * process.ZmmgSkimSeq *
process.GenZmmgSkimFilter *
~process.ZeeFilter * ~process.ZSCFilter * ~process.WenuFilter * process.ZmmgSkimSeq
)
process.pathZSCElectronSkim = cms.Path(process.filterSeq * process.FilterSeq * process.MinZSCNumberFilter *
~process.ZeeFilter * process.ZSCFilter
# process.GenZSCSkimFilter
)
process.pathWElectronSkim = cms.Path(process.filterSeq * process.FilterSeq *
~process.ZeeFilter * ~process.ZSCFilter * process.WenuFilter
# process.GenWSkimFilter
)
process.pathZmmgSkim = cms.Path(process.filterSeq * process.ZmmgSkimSeq *
~process.ZeeFilter * ~process.ZSCFilter * ~process.WenuFilter * process.ZmmgSkimSeq
)
process.pathZElectronGen = cms.Path(process.filterSeq * process.FilterSeq *
process.GenSkimFilter
)
process.pathZSCElectronGen = cms.Path(process.filterSeq * process.FilterSeq * process.MinZSCNumberFilter *
process.GenZSCSkimFilter
)
process.pathWElectronGen = cms.Path(process.filterSeq * process.FilterSeq *
process.GenWSkimFilter
)
process.pathZmmgGen = cms.Path(process.filterSeq * process.FilterMuSeq * process.ZmmgSkimSeq *
process.GenZmmgSkimFilter
)
# ALCARAW
if (re.match("CMSSW_7_.*",CMSSW_VERSION)):
uncalibRecHitSeq = cms.Sequence( (ecalDigis + ecalPreshowerDigis) * ecalUncalibRecHitSequence) #containing the new local reco for 72X
process.pathALCARECOEcalUncalSingleElectron = cms.Path(process.PUDumperSeq * process.filterSeq *
process.pfIsoEgamma *
(process.ALCARECOEcalCalElectronPreSeq +
uncalibRecHitSeq ))
process.pathALCARECOEcalUncalZElectron = cms.Path( process.PUDumperSeq * process.filterSeq * process.FilterSeq *
process.pfIsoEgamma *
(process.ALCARECOEcalCalElectronPreSeq +
uncalibRecHitSeq ))
process.pathALCARECOEcalUncalZSCElectron = cms.Path( process.PUDumperSeq * process.filterSeq * process.FilterSeq *
process.pfIsoEgamma *
~process.ZeeFilter * process.ZSCFilter *
(process.ALCARECOEcalCalElectronPreSeq +
uncalibRecHitSeq ))
process.pathALCARECOEcalUncalWElectron = cms.Path( process.PUDumperSeq * process.filterSeq * process.FilterSeq *
process.pfIsoEgamma *
~process.ZeeFilter * ~process.ZSCFilter * process.WenuFilter *
(process.ALCARECOEcalCalElectronPreSeq +
uncalibRecHitSeq ))
process.pathALCARECOEcalUncalZmmgPhoton = cms.Path( process.PUDumperSeq * process.filterSeq * process.FilterMuSeq * process.ZmmgSkimSeq *
process.pfIsoEgamma *
~process.ZeeFilter * ~process.ZSCFilter * ~process.WenuFilter *
(process.ALCARECOEcalCalElectronPreSeq +
uncalibRecHitSeq ))
else:
process.pathALCARECOEcalUncalSingleElectron = cms.Path(process.PUDumperSeq * process.filterSeq *
process.pfIsoEgamma *
(process.ALCARECOEcalCalElectronPreSeq +
process.seqALCARECOEcalUncalElectron ))
process.pathALCARECOEcalUncalZElectron = cms.Path( process.PUDumperSeq * process.filterSeq * process.FilterSeq *
process.pfIsoEgamma *
(process.ALCARECOEcalCalElectronPreSeq +
process.seqALCARECOEcalUncalElectron ))
process.pathALCARECOEcalUncalZSCElectron = cms.Path( process.PUDumperSeq * process.filterSeq * process.FilterSeq *
process.pfIsoEgamma *
~process.ZeeFilter * process.ZSCFilter *
(process.ALCARECOEcalCalElectronPreSeq +
process.seqALCARECOEcalUncalElectron ))
process.pathALCARECOEcalUncalWElectron = cms.Path( process.PUDumperSeq * process.filterSeq * process.FilterSeq *
process.pfIsoEgamma *
~process.ZeeFilter * ~process.ZSCFilter * process.WenuFilter *
(process.ALCARECOEcalCalElectronPreSeq +
process.seqALCARECOEcalUncalElectron ))
process.pathALCARECOEcalCalZmmgPhoton = cms.Path( process.PUDumperSeq *
process.filterSeq * process.FilterMuSeq * process.ZmmgSkimSeq *
~process.ZeeFilter * ~process.ZSCFilter * ~process.WenuFilter *
process.pfIsoEgamma *
process.seqALCARECOEcalUncalElectron ) #* process.hltReporter)
# ALCARERECO
process.pathALCARERECOEcalCalElectron = cms.Path(process.alcarerecoSeq)
if(options.doTree>0):
process.pathALCARERECOEcalCalElectron+=cms.Sequence( process.pdfWeightsSeq * process.ntupleSeq)
# ALCARECO
process.pathALCARECOEcalCalSingleElectron = cms.Path(process.PUDumperSeq * process.filterSeq *
process.pfIsoEgamma *
process.seqALCARECOEcalCalElectron)
process.pathALCARECOEcalCalZElectron = cms.Path( process.PUDumperSeq * process.filterSeq * process.FilterSeq *
process.ZeeFilter *
process.pfIsoEgamma *
process.seqALCARECOEcalCalElectron)
process.pathALCARECOEcalCalWElectron = cms.Path( process.PUDumperSeq * process.filterSeq *
process.FilterSeq *
~process.ZeeFilter * ~process.ZSCFilter * process.WenuFilter *
process.pfIsoEgamma *
process.seqALCARECOEcalCalElectron)
process.pathALCARECOEcalCalZSCElectron = cms.Path( process.PUDumperSeq *
process.filterSeq * process.FilterSeq *
~process.ZeeFilter * process.ZSCFilter *
# process.ZSCHltFilter *
process.pfIsoEgamma *
process.seqALCARECOEcalCalElectron ) #* process.hltReporter)
process.pathALCARECOEcalCalZmmgPhoton = cms.Path( process.PUDumperSeq *
process.filterSeq * process.FilterMuSeq * process.ZmmgSkimSeq *
process.pfIsoEgamma *
process.seqALCARECOEcalCalPhoton ) #* process.hltReporter)
if (options.skim=="ZmmgSkim"):
process.NtuplePath = cms.Path(process.filterSeq * process.FilterMuSeq * process.NtupleFilterSeq
# * process.pfIsoEgamma
# * process.seqALCARECOEcalCalElectron
* process.pdfWeightsSeq * process.ntupleSeq)
else:
process.NtuplePath = cms.Path(process.filterSeq * process.FilterSeq * process.NtupleFilterSeq
# * process.pfIsoEgamma
# * process.seqALCARECOEcalCalElectron
* process.pdfWeightsSeq * process.ntupleSeq)
process.NtupleEndPath = cms.EndPath( process.zNtupleDumper)
if(not doTreeOnly):
process.ALCARECOoutput_step = cms.EndPath(process.outputALCARECO )
if(options.type=="ALCARERECO"):
process.ALCARERECOoutput_step = cms.EndPath(process.outputALCARERECO)
if(options.type=="ALCARAW"):
process.ALCARAWoutput_step = cms.EndPath(process.outputALCARAW)
############### JSON Filter
if((options.doTree>0 and options.doTreeOnly==0)):
# or (options.type=='ALCARECOSIM' and len(options.jsonFile)>0) ):
process.jsonFilter.jsonFileName = cms.string(options.jsonFile)
else:
if(len(options.jsonFile)>0):
# from CMSSW 5.0.0
import FWCore.PythonUtilities.LumiList as LumiList
process.source.lumisToProcess = LumiList.LumiList(filename = options.jsonFile).getVLuminosityBlockRange()
# from CMSSW 3.8.0
#import PhysicsTools.PythonAnalysis.LumiList as LumiList
#myLumis = LumiList.LumiList(filename = options.jsonFile).getCMSSWString().split(',')
#process.source.lumisToProcess = cms.untracked.VLuminosityBlockRange()
#process.source.lumisToProcess.extend(myLumis)
############################################################
# Schedule definition
##############################
if(options.skim=='WSkim'):
process.outputALCARAW.SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOEcalUncalWElectron')
)
process.outputALCARECO.SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOEcalCalWElectron')
)
elif(options.skim=='ZSkim'):
process.outputALCARAW.SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOEcalUncalZElectron', 'pathALCARECOEcalUncalZSCElectron')
)
process.outputALCARECO.SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOEcalCalZElectron', 'pathALCARECOEcalCalZSCElectron')
)
elif(options.skim=='ZmmgSkim'):
process.outputALCARAW.SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOEcalUncalZmmgPhoton')
)
process.outputALCARECO.SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOEcalCalZmmgPhoton')
)
else:
#if(options.skim=="" or options.skim=="none" or options.skim=="no" or options.skim=="partGun"):
process.outputALCARAW.SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOEcalUncalSingleElectron')
)
process.outputALCARECO.SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOEcalCalSingleElectron')
)
if(options.type=='ALCARAW'):
process.schedule = cms.Schedule(
#process.raw2digi_step,process.L1Reco_step,
#process.reconstruction_step,process.endjob_step,
process.pathALCARECOEcalUncalZElectron, process.pathALCARECOEcalUncalWElectron,
process.pathALCARECOEcalUncalZSCElectron,
process.pathALCARECOEcalUncalZmmgPhoton,
process.ALCARAWoutput_step,
process.pathALCARECOEcalCalZElectron, process.pathALCARECOEcalCalWElectron,
process.pathALCARECOEcalCalZSCElectron,
process.pathALCARECOEcalCalZmmgPhoton,
process.ALCARECOoutput_step, process.NtuplePath) # fix the output modules
elif(options.type=='ALCARERECO'):
if(doTreeOnly):
process.NtuplePath = cms.Path(process.pdfWeightsSeq * process.ntupleSeq)
process.schedule = cms.Schedule(process.NtuplePath, process.NtupleEndPath)
else:
process.pathALCARERECOEcalCalElectron += process.zNtupleDumper
process.schedule = cms.Schedule(process.pathALCARERECOEcalCalElectron, process.ALCARERECOoutput_step,
)
elif(options.type=='ALCARECO' or options.type=='ALCARECOSIM'):
if(doTreeOnly):
process.schedule = cms.Schedule(process.NtuplePath, process.NtupleEndPath)
else:
if(options.doTree==0):
process.schedule = cms.Schedule(process.pathALCARECOEcalCalZElectron, process.pathALCARECOEcalCalWElectron,
process.pathALCARECOEcalCalZSCElectron, process.pathALCARECOEcalCalZmmgPhoton,
process.ALCARECOoutput_step
) # fix the output modules
else:
process.schedule = cms.Schedule(process.pathALCARECOEcalCalZElectron, process.pathALCARECOEcalCalWElectron,
process.pathALCARECOEcalCalZSCElectron, process.pathALCARECOEcalCalZmmgPhoton,
process.ALCARECOoutput_step, process.NtuplePath, process.NtupleEndPath
) # fix the output modules
if(options.skim=="" or options.skim=="ZHLTSkim" or options.skim=="partGun"):
process.schedule += cms.Schedule(process.pathALCARECOEcalCalSingleElectron)
elif(options.type=='SKIMEFFTEST'):
process.schedule = cms.Schedule(process.pathWElectronSkimGen, process.pathZSCElectronSkimGen, process.pathZElectronSkimGen,
process.pathWElectronSkim, process.pathZSCElectronSkim, process.pathZElectronSkim,
process.pathWElectronGen, process.pathZSCElectronGen, process.pathZElectronGen,
)
process.zNtupleDumper.foutName=options.secondaryOutput
# this includes the sequence: patSequence
# patSequence=cms.Sequence( (eleSelectionProducers + eleNewEnergiesProducer ) * patElectrons)
if(options.isCrab==1):
pathPrefix=""
else:
pathPrefix=CMSSW_BASE+'/' #./src/Calibration/EleNewEnergiesProducer' #CMSSW_BASE+'/src/Calibration/EleNewEnergiesProducer/'
print("[INFO] Running locally: pathPrefix="+pathPrefix)
process.eleNewEnergiesProducer.regrPhoFile=pathPrefix+process.eleNewEnergiesProducer.regrPhoFile.value()
process.eleNewEnergiesProducer.regrEleFile=pathPrefix+process.eleNewEnergiesProducer.regrEleFile.value()
process.eleNewEnergiesProducer.regrEleFile_fra=pathPrefix+process.eleNewEnergiesProducer.regrEleFile_fra.value()
# Now files are on CERN EOS, files accessed via xrootd
#process.eleNewEnergiesProducer.regrEleJoshV4_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrEleJoshV4_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrEleJoshV5_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrEleJoshV5_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrPhoJoshV4_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrPhoJoshV4_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrPhoJoshV5_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrPhoJoshV5_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrEleJoshV6_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrEleJoshV6_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrPhoJoshV6_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrPhoJoshV6_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrEleJoshV7_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrEleJoshV7_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrPhoJoshV7_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrPhoJoshV7_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrEleJoshV8_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrEleJoshV8_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrPhoJoshV8_SemiParamFile = pathPrefix+process.eleNewEnergiesProducer.regrPhoJoshV8_SemiParamFile.value()
#process.eleNewEnergiesProducer.regrEleJoshV6_SemiParam7TeVtrainFile = pathPrefix+process.eleNewEnergiesProducer.regrEleJoshV6_SemiParam7TeVtrainFile.value()
#process.eleNewEnergiesProducer.regrPhoJoshV6_SemiParam7TeVtrainFile = pathPrefix+process.eleNewEnergiesProducer.regrPhoJoshV6_SemiParam7TeVtrainFile.value()
#process.eleNewEnergiesProducer.regrEleJoshV7_SemiParam7TeVtrainFile = pathPrefix+process.eleNewEnergiesProducer.regrEleJoshV7_SemiParam7TeVtrainFile.value()
#process.eleNewEnergiesProducer.regrPhoJoshV7_SemiParam7TeVtrainFile = pathPrefix+process.eleNewEnergiesProducer.regrPhoJoshV7_SemiParam7TeVtrainFile.value()
#process.eleNewEnergiesProducer.regrEleJoshV8_SemiParam7TeVtrainFile = pathPrefix+process.eleNewEnergiesProducer.regrEleJoshV8_SemiParam7TeVtrainFile.value()
#process.eleNewEnergiesProducer.regrPhoJoshV8_SemiParam7TeVtrainFile = pathPrefix+process.eleNewEnergiesProducer.regrPhoJoshV8_SemiParam7TeVtrainFile.value()
# process.eleRegressionEnergy.regressionInputFile = cms.string("EgammaAnalysis/ElectronTools/data/eleEnergyReg2012Weights_V1.root") #eleEnergyRegWeights_WithSubClusters_VApr15.root")
process.eleRegressionEnergy.energyRegressionType=cms.uint32(2)
if(re.match("CMSSW_4_4_.*", CMSSW_VERSION)):
process.eleRegressionEnergy.regressionInputFile = cms.string("EgammaAnalysis/ElectronTools/data/eleEnergyReg2011Weights_V1.root")
if(re.match("CMSSW_4_2_.*", CMSSW_VERSION)):
pathPrefix=CMSSW_BASE+'/src/Calibration/EleNewEnergiesProducer/'
print('[INFO] Using v2 regression for CMSSW_4_2_X')
process.eleNewEnergiesProducer.regrPhoFile=cms.string(pathPrefix+'data/gbrv2ph.root')
process.eleNewEnergiesProducer.regrEleFile=cms.string(pathPrefix+'data/gbrv2ele.root')
process.eleNewEnergiesProducer.regrEleFile_fra=cms.string('nocorrections')
#process.eleNewEnergiesProducer.regrEleFile_fra=cms.string(pathPrefix+'data/eleEnergyRegWeights_V1.root')
# process.load('Calibration.ValueMapTraslator.valuemaptraslator_cfi')
# process.sandboxRerecoSeq*=process.elPFIsoValueCharged03PFIdRecalib
# process.sandboxRerecoSeq*=process.elPFIsoValueGamma03PFIdRecalib
# process.sandboxRerecoSeq*=process.elPFIsoValueNeutral03PFIdRecalib
############################################################
# Setting collection names
##############################
process.selectedElectrons.src = myEleCollection
if(re.match("CMSSW_5_.*", CMSSW_VERSION)):
process.PassingVeryLooseId.src = myEleCollection
process.PassingMediumId.src = myEleCollection
process.PassingTightId.src = myEleCollection
else:
process.PassingVetoId.src = myEleCollection
process.PassingHLT.InputProducer = myEleCollection
process.eleRegressionEnergy.inputElectronsTag = myEleCollection
process.patElectrons.electronSource = myEleCollection
#process.eleSelectionProducers.electronCollection = myEleCollection
process.electronMatch.src = myEleCollection
process.eleNewEnergiesProducer.electronCollection = myEleCollection
process.alCaIsolatedElectrons.electronLabel = myEleCollection
if (options.skim=="ZmmgSkim"):
process.alCaIsolatedElectrons.photonLabel = cms.InputTag("gedPhotons")
process.alcaElectronTracksReducer.electronLabel = myEleCollection
# process.elPFIsoDepositChargedGsf.src = myEleCollection
# process.elPFIsoDepositGammaGsf.src = myEleCollection
# process.elPFIsoDepositChargedGsf.src = myEleCollection
# process.elPFIsoValueCharged03PFIdRecalib.oldreferenceCollection = myEleCollection
# process.elPFIsoValueGamma03PFIdRecalib.oldreferenceCollection = myEleCollection
# process.elPFIsoValueNeutral03PFIdRecalib.oldreferenceCollection = myEleCollection
process.electronRecalibSCAssociator.electronSrc = myEleCollection
#process.eleNewEnergiesProducer.recHitCollectionEB = cms.InputTag("alCaIsolatedElectrons", "alCaRecHitsEB")
#process.eleNewEnergiesProducer.recHitCollectionEE = cms.InputTag("alCaIsolatedElectrons", "alCaRecHitsEE")
process.eleNewEnergiesProducer.recHitCollectionEB = cms.InputTag("alCaIsolatedElectrons", "alcaBarrelHits")
process.eleNewEnergiesProducer.recHitCollectionEE = cms.InputTag("alCaIsolatedElectrons", "alcaEndcapHits")
if(options.type=="ALCARERECO"):
if(re.match("CMSSW_7_.*",CMSSW_VERSION)):
process.ecalRecHit.EBuncalibRecHitCollection = cms.InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEB")
process.ecalRecHit.EEuncalibRecHitCollection = cms.InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEE")
else:
process.ecalRecHit.EBuncalibRecHitCollection = cms.InputTag("ecalGlobalUncalibRecHit","EcalUncalibRecHitsEB")
process.ecalRecHit.EEuncalibRecHitCollection = cms.InputTag("ecalGlobalUncalibRecHit","EcalUncalibRecHitsEE")
process.correctedHybridSuperClusters.corectedSuperClusterCollection = 'recalibSC'
process.correctedMulti5x5SuperClustersWithPreshower.corectedSuperClusterCollection = 'endcapRecalibSC'
if(re.match("CMSSW_5_.*",CMSSW_VERSION) or re.match("CMSSW_6_.*", CMSSW_VERSION) or re.match("CMSSW_7_.*", CMSSW_VERSION)):
process.multi5x5PreshowerClusterShape.endcapSClusterProducer = "correctedMulti5x5SuperClustersWithPreshower:endcapRecalibSC"
# in sandboxRereco
process.reducedEcalRecHitsES.EndcapSuperClusterCollection= cms.InputTag('correctedMulti5x5SuperClustersWithPreshower','endcapRecalibSC',processName)
recalibElectronSrc = cms.InputTag("electronRecalibSCAssociator")
process.alCaIsolatedElectrons.electronLabel = recalibElectronSrc
process.alCaIsolatedElectrons.ebRecHitsLabel = cms.InputTag("ecalRecHit","EcalRecHitsEB")
process.alCaIsolatedElectrons.eeRecHitsLabel = cms.InputTag("ecalRecHit","EcalRecHitsEE")
process.alCaIsolatedElectrons.EESuperClusterCollection = process.reducedEcalRecHitsES.EndcapSuperClusterCollection
process.eleRegressionEnergy.inputElectronsTag = recalibElectronSrc
process.eleSelectionProducers.electronCollection = recalibElectronSrc
process.eleNewEnergiesProducer.electronCollection = recalibElectronSrc
process.patElectrons.electronSource = recalibElectronSrc
process.eleSelectionProducers.chIsoVals = cms.InputTag('elPFIsoValueCharged03PFIdRecalib')
process.eleSelectionProducers.emIsoVals = cms.InputTag('elPFIsoValueGamma03PFIdRecalib')
process.eleSelectionProducers.nhIsoVals = cms.InputTag('elPFIsoValueNeutral03PFIdRecalib')
process.outputALCARECO.outputCommands += sandboxRerecoOutputCommands
process.outputALCARECO.fileName=cms.untracked.string('alcarereco.root')
process.MinEleNumberFilter.src = recalibElectronSrc
process.zNtupleDumper.WZSkimResultsCollection = cms.InputTag('TriggerResults::ALCASKIM')
process.zNtupleDumper.SelectEvents = []
process.zNtupleDumper.EESuperClusterCollection = cms.InputTag('correctedMulti5x5SuperClustersWithPreshower','endcapRecalibSC', 'ALCARERECO')
process.patElectrons.reducedBarrelRecHitCollection = process.eleNewEnergiesProducer.recHitCollectionEB
process.patElectrons.reducedEndcapRecHitCollection = process.eleNewEnergiesProducer.recHitCollectionEE
process.zNtupleDumper.recHitCollectionEB = process.eleNewEnergiesProducer.recHitCollectionEB
process.zNtupleDumper.recHitCollectionEE = process.eleNewEnergiesProducer.recHitCollectionEE
process.eleRegressionEnergy.recHitCollectionEB = process.eleNewEnergiesProducer.recHitCollectionEB.value()
process.eleRegressionEnergy.recHitCollectionEE = process.eleNewEnergiesProducer.recHitCollectionEE.value()
############################
## Dump the output Python ##
############################
processDumpFile = open('processDump.py', 'w')
print(process.dumpPython(), file=processDumpFile)
| 25,032 |
2,068 | <filename>lib/src/main/java/com/app/annotation/apt/ApiFactory.java
package com.app.annotation.apt;
/**
* Created by baixiaokang on 16/12/28.
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface ApiFactory {
}
| 138 |
442 | <reponame>BestEggplant/ObEngine
#pragma once
namespace sol
{
class state_view;
};
namespace obe::Component::Bindings
{
void LoadClassComponentBase(sol::state_view state);
}; | 75 |
742 | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, <NAME>, Inc.
* 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 <NAME> nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <sound_play/sound_play.h>
#include <unistd.h>
void sleepok(int t, ros::NodeHandle &nh)
{
if (nh.ok())
sleep(t);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "sound_play_test");
ros::NodeHandle nh;
sound_play::SoundClient sc;
sleepok(1, nh);
while(nh.ok())
{
sc.say("Hello world!");
sleepok(2, nh);
const char *str1 = "I am annoying.";
sc.repeat(str1);
sleepok(4, nh);
sc.stopSaying(str1);
sc.playWave("/usr/share/xemacs21/xemacs-packages/etc/sounds/boing.wav");
sleepok(2, nh);
const char *str2 = "/usr/share/xemacs21/xemacs-packages/etc/sounds/piano-beep.wav";
sc.startWave(str2);
sleepok(4, nh);
sc.stopWave(str2);
sc.play(sound_play::SoundRequest::NEEDS_UNPLUGGING);
sleepok(2, nh);
sc.start(sound_play::SoundRequest::BACKINGUP);
sleepok(4, nh);
sc.stop(sound_play::SoundRequest::BACKINGUP);
sleepok(2, nh);
sound_play::Sound s1 = sc.waveSound("/usr/share/xemacs21/xemacs-packages/etc/sounds/boing.wav");
s1.repeat();
sleepok(1, nh);
s1.stop();
sleepok(2, nh);
sound_play::Sound s2 = sc.voiceSound("This is a really long sentence that will get cut off.");
s2.play();
sleepok(1, nh);
s2.stop();
sleepok(2, nh);
sound_play::Sound s3 = sc.builtinSound(sound_play::SoundRequest::NEEDS_UNPLUGGING_BADLY);
s3.play();
sleepok(1, nh);
s3.stop();
sleepok(2, nh);
sound_play::Sound s4 = sc.waveSoundFromPkg("sound_play", "sounds/BACKINGUP.ogg");
s4.play();
sleepok(1, nh);
s4.stop();
}
}
| 1,220 |
405 | #ifndef _MNIST_H_
#define _MNIST_H_
#include <string>
#include <fstream>
#include <array>
#include <vector>
#include <algorithm>
#include <random>
#include <iostream>
#include <assert.h>
#include "blob.h"
namespace cudl
{
#define MNIST_CLASS 10
class MNIST
{
public:
MNIST() : dataset_dir_("./") {}
MNIST(std::string dataset_dir) : dataset_dir_(dataset_dir) {}
~MNIST();
// load train dataset
void train(int batch_size = 1, bool shuffle = false);
// load test dataset
void test(int batch_size = 1);
// update shared batch data buffer at current step index
void get_batch();
// increase current step index
// optionally it updates shared buffer if input parameter is true.
int next();
// returns a pointer which has input batch data
Blob<float>* get_data() { return data_; }
// returns a pointer which has target batch data
Blob<float>* get_target() { return target_;}
private:
// predefined file names
std::string dataset_dir_;
#ifdef __linux__
std::string train_dataset_file_ = "train-images-idx3-ubyte";
std::string train_label_file_ = "train-labels-idx1-ubyte";
std::string test_dataset_file_ = "t10k-images-idx3-ubyte";
std::string test_label_file_ = "t10k-labels-idx1-ubyte";
#elif _WIN32
std::string train_dataset_file_ = "train-images.idx3-ubyte";
std::string train_label_file_ = "train-labels.idx1-ubyte";
std::string test_dataset_file_ = "t10k-images.idx3-ubyte";
std::string test_label_file_ = "t10k-labels.idx1-ubyte";
#endif
// container
std::vector<std::vector<float>> data_pool_;
std::vector<std::array<float, MNIST_CLASS>> target_pool_;
Blob<float>* data_ = nullptr;
Blob<float>* target_ = nullptr;
// data loader initialization
void load_data(std::string &image_file_path);
void load_target(std::string &label_file_path);
void normalize_data();
int to_int(uint8_t *ptr);
// data loader control
int step_ = -1;
bool shuffle_;
int batch_size_ = 1;
int channels_ = 1;
int height_ = 1;
int width_ = 1;
int num_classes_= 10;
int num_steps_ = 0;
void create_shared_space();
void shuffle_dataset();
};
} // namespace cudl
#endif // _MNIST_H_
| 945 |
335 | {
"word": "Technologically",
"definitions": [
"In a way that relates to or involves technology."
],
"parts-of-speech": "Adverb"
} | 62 |
1,083 | //===--- PILGen.h - Implements Lowering of ASTs -> PIL ----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#ifndef POLARPHP_PIL_GEN_PILGEN_H
#define POLARPHP_PIL_GEN_PILGEN_H
#include "polarphp/pil/gen/AstVisitor.h"
#include "polarphp/pil/gen/Cleanup.h"
#include "polarphp/ast/AstContext.h"
#include "polarphp/ast/AnyFunctionRef.h"
#include "polarphp/ast/DiagnosticEngine.h"
#include "polarphp/pil/lang/PILDebugScope.h"
#include "polarphp/pil/lang/PILFunction.h"
#include "polarphp/pil/lang/PILModule.h"
#include "polarphp/pil/lang/TypeLowering.h"
#include "llvm/ADT/DenseMap.h"
#include <deque>
namespace polar {
class PILBasicBlock;
namespace lowering {
class TypeConverter;
class PILGenFunction;
/// An enum to indicate whether a protocol method requirement is satisfied by
/// a free function, as for an operator requirement.
enum IsFreeFunctionWitness_t : bool {
IsNotFreeFunctionWitness = false,
IsFreeFunctionWitness = true,
};
/// An AstVisitor for generating PIL from top-level declarations in a module.
class LLVM_LIBRARY_VISIBILITY PILGenModule : public AstVisitor<PILGenModule> {
public:
/// The Module being constructed.
PILModule &M;
/// The type converter for the module.
TypeConverter &Types;
/// The Swift module we are visiting.
ModuleDecl *PolarphpModule;
/// TopLevelSGF - The PILGenFunction used to visit top-level code, or null if
/// the current source file is not a script source file.
PILGenFunction /*nullable*/ *TopLevelSGF;
/// Mapping from PILDeclRefs to emitted PILFunctions.
llvm::DenseMap<PILDeclRef, PILFunction*> emittedFunctions;
/// Mapping from InterfaceConformances to emitted PILWitnessTables.
llvm::DenseMap<NormalInterfaceConformance*, PILWitnessTable*> emittedWitnessTables;
struct DelayedFunction {
/// Insert the entity after the given function when it's emitted.
PILDeclRef insertAfter;
/// Code that generates the function.
std::function<void (PILFunction *)> emitter;
};
/// Mapping from PILDeclRefs to delayed PILFunction generators for
/// non-externally-visible symbols.
llvm::DenseMap<PILDeclRef, DelayedFunction> delayedFunctions;
/// Queue of delayed PILFunctions that need to be forced.
std::deque<std::pair<PILDeclRef, DelayedFunction>> forcedFunctions;
/// The most recent declaration we considered for emission.
PILDeclRef lastEmittedFunction;
/// Bookkeeping to ensure that useConformancesFrom{ObjectiveC,}Type() is
/// only called once for each unique type, as an optimization.
llvm::DenseSet<TypeBase *> usedConformancesFromTypes;
llvm::DenseSet<TypeBase *> usedConformancesFromObjectiveCTypes;
/// Queue of delayed conformances that need to be emitted.
std::deque<NormalInterfaceConformance *> pendingConformances;
/// Set of delayed conformances that have already been forced.
llvm::DenseSet<NormalInterfaceConformance *> forcedConformances;
PILFunction *emitTopLevelFunction(PILLocation Loc);
size_t anonymousSymbolCounter = 0;
Optional<PILDeclRef> StringToNSStringFn;
Optional<PILDeclRef> NSStringToStringFn;
Optional<PILDeclRef> ArrayToNSArrayFn;
Optional<PILDeclRef> NSArrayToArrayFn;
Optional<PILDeclRef> DictionaryToNSDictionaryFn;
Optional<PILDeclRef> NSDictionaryToDictionaryFn;
Optional<PILDeclRef> SetToNSSetFn;
Optional<PILDeclRef> NSSetToSetFn;
Optional<PILDeclRef> BoolToObjCBoolFn;
Optional<PILDeclRef> ObjCBoolToBoolFn;
Optional<PILDeclRef> BoolToDarwinBooleanFn;
Optional<PILDeclRef> DarwinBooleanToBoolFn;
Optional<PILDeclRef> NSErrorToErrorFn;
Optional<PILDeclRef> ErrorToNSErrorFn;
Optional<PILDeclRef> BoolToWindowsBoolFn;
Optional<PILDeclRef> WindowsBoolToBoolFn;
Optional<InterfaceDecl*> PointerInterface;
Optional<InterfaceDecl*> ObjectiveCBridgeable;
Optional<FuncDecl*> BridgeToObjectiveCRequirement;
Optional<FuncDecl*> UnconditionallyBridgeFromObjectiveCRequirement;
Optional<AssociatedTypeDecl*> BridgedObjectiveCType;
Optional<InterfaceDecl*> BridgedStoredNSError;
Optional<VarDecl*> NSErrorRequirement;
Optional<InterfaceConformance *> NSErrorConformanceToError;
public:
PILGenModule(PILModule &M, ModuleDecl *SM);
~PILGenModule();
PILGenModule(PILGenModule const &) = delete;
void operator=(PILGenModule const &) = delete;
AstContext &getAstContext() { return M.getAstContext(); }
static DeclName getMagicFunctionName(PILDeclRef ref);
static DeclName getMagicFunctionName(DeclContext *dc);
/// Get the function for a PILDeclRef, or return nullptr if it hasn't been
/// emitted yet.
PILFunction *getEmittedFunction(PILDeclRef constant,
ForDefinition_t forDefinition);
/// Get the function for a PILDeclRef, creating it if necessary.
PILFunction *getFunction(PILDeclRef constant,
ForDefinition_t forDefinition);
/// Get the dynamic dispatch thunk for a PILDeclRef.
PILFunction *getDynamicThunk(PILDeclRef constant,
CanPILFunctionType constantTy);
/// Emit a vtable thunk for a derived method if its natural abstraction level
/// diverges from the overridden base method. If no thunking is needed,
/// returns a static reference to the derived method.
Optional<PILVTable::Entry> emitVTableMethod(ClassDecl *theClass,
PILDeclRef derived,
PILDeclRef base);
/// True if a function has been emitted for a given PILDeclRef.
bool hasFunction(PILDeclRef constant);
/// Get or create the declaration of a reabstraction thunk with the
/// given signature.
PILFunction *getOrCreateReabstractionThunk(
CanPILFunctionType thunkType,
CanPILFunctionType fromType,
CanPILFunctionType toType,
CanType dynamicSelfType);
/// Determine whether the given class has any instance variables that
/// need to be destroyed.
bool hasNonTrivialIVars(ClassDecl *cd);
/// Determine whether we need to emit an ivar destroyer for the given class.
/// An ivar destroyer is needed if a superclass of this class may define a
/// failing designated initializer.
bool requiresIVarDestroyer(ClassDecl *cd);
//===--------------------------------------------------------------------===//
// Visitors for top-level forms
//===--------------------------------------------------------------------===//
// These are either not allowed at global scope or don't require
// code emission.
void visitImportDecl(ImportDecl *d) {}
void visitEnumCaseDecl(EnumCaseDecl *d) {}
void visitEnumElementDecl(EnumElementDecl *d) {}
void visitOperatorDecl(OperatorDecl *d) {}
void visitPrecedenceGroupDecl(PrecedenceGroupDecl *d) {}
void visitTypeAliasDecl(TypeAliasDecl *d) {}
void visitOpaqueTypeDecl(OpaqueTypeDecl *d) {}
void visitAbstractTypeParamDecl(AbstractTypeParamDecl *d) {}
void visitConstructorDecl(ConstructorDecl *d) {}
void visitDestructorDecl(DestructorDecl *d) {}
void visitModuleDecl(ModuleDecl *d) { }
void visitMissingMemberDecl(MissingMemberDecl *d) {}
// Emitted as part of its storage.
void visitAccessorDecl(AccessorDecl *ad) {}
void visitFuncDecl(FuncDecl *fd);
void visitPatternBindingDecl(PatternBindingDecl *vd);
void visitTopLevelCodeDecl(TopLevelCodeDecl *td);
void visitIfConfigDecl(IfConfigDecl *icd);
void visitPoundDiagnosticDecl(PoundDiagnosticDecl *PDD);
void visitNominalTypeDecl(NominalTypeDecl *ntd);
void visitExtensionDecl(ExtensionDecl *ed);
void visitVarDecl(VarDecl *vd);
void visitSubscriptDecl(SubscriptDecl *sd);
void emitAbstractFuncDecl(AbstractFunctionDecl *AFD);
/// Generate code for a source file of the module.
void emitSourceFile(SourceFile *sf);
/// Generates code for the given FuncDecl and adds the
/// PILFunction to the current PILModule under the name PILDeclRef(decl). For
/// curried functions, curried entry point Functions are also generated and
/// added to the current PILModule.
void emitFunction(FuncDecl *fd);
/// Generates code for the given closure expression and adds the
/// PILFunction to the current PILModule under the name PILDeclRef(ce).
PILFunction *emitClosure(AbstractClosureExpr *ce);
/// Generates code for the given ConstructorDecl and adds
/// the PILFunction to the current PILModule under the name PILDeclRef(decl).
void emitConstructor(ConstructorDecl *decl);
/// Generates code for the given class's destructor and adds
/// the PILFunction to the current PILModule under the name
/// PILDeclRef(cd, Destructor).
void emitDestructor(ClassDecl *cd, DestructorDecl *dd);
/// Generates the enum constructor for the given
/// EnumElementDecl under the name PILDeclRef(decl).
void emitEnumConstructor(EnumElementDecl *decl);
/// Emits the default argument generator with the given expression.
void emitDefaultArgGenerator(PILDeclRef constant, ParamDecl *param);
/// Emits the stored property initializer for the given pattern.
void emitStoredPropertyInitialization(PatternBindingDecl *pd, unsigned i);
/// Emits the backing initializer for a property with an attached wrapper.
void emitPropertyWrapperBackingInitializer(VarDecl *var);
/// Emits default argument generators for the given parameter list.
void emitDefaultArgGenerators(PILDeclRef::Loc decl,
ParameterList *paramList);
/// Emits the curry thunk between two uncurry levels of a function.
void emitCurryThunk(PILDeclRef thunk);
/// Emits a thunk from a foreign function to the native Swift convention.
void emitForeignToNativeThunk(PILDeclRef thunk);
/// Emits a thunk from a Swift function to the native Swift convention.
void emitNativeToForeignThunk(PILDeclRef thunk);
void preEmitFunction(PILDeclRef constant,
llvm::PointerUnion<ValueDecl *,
Expr *> astNode,
PILFunction *F,
PILLocation L);
void postEmitFunction(PILDeclRef constant, PILFunction *F);
/// Add a global variable to the PILModule.
void addGlobalVariable(VarDecl *global);
/// Emit the ObjC-compatible entry point for a method.
void emitObjCMethodThunk(FuncDecl *method);
/// Emit the ObjC-compatible getter and setter for a property.
void emitObjCPropertyMethodThunks(AbstractStorageDecl *prop);
/// Emit the ObjC-compatible entry point for a constructor.
void emitObjCConstructorThunk(ConstructorDecl *constructor);
/// Emit the ObjC-compatible entry point for a destructor (i.e., -dealloc).
void emitObjCDestructorThunk(DestructorDecl *destructor);
/// Get or emit the witness table for a protocol conformance.
PILWitnessTable *getWitnessTable(NormalInterfaceConformance *conformance);
/// Emit a protocol witness entry point.
PILFunction *
emitInterfaceWitness(InterfaceConformanceRef conformance, PILLinkage linkage,
IsSerialized_t isSerialized, PILDeclRef requirement,
PILDeclRef witnessRef, IsFreeFunctionWitness_t isFree,
Witness witness);
/// Emit the default witness table for a resilient protocol.
void emitDefaultWitnessTable(InterfaceDecl *protocol);
/// Emit the self-conformance witness table for a protocol.
void emitSelfConformanceWitnessTable(InterfaceDecl *protocol);
/// Emit the lazy initializer function for a global pattern binding
/// declaration.
PILFunction *emitLazyGlobalInitializer(StringRef funcName,
PatternBindingDecl *binding,
unsigned pbdEntry);
/// Emit the accessor for a global variable or stored static property.
///
/// This ensures the lazy initializer has been run before returning the
/// address of the variable.
void emitGlobalAccessor(VarDecl *global,
PILGlobalVariable *onceToken,
PILFunction *onceFunc);
// @todo
// /// True if the given function requires an entry point for ObjC method
// /// dispatch.
// bool requiresObjCMethodEntryPoint(FuncDecl *method);
//
// /// True if the given constructor requires an entry point for ObjC method
// /// dispatch.
// bool requiresObjCMethodEntryPoint(ConstructorDecl *constructor);
/// Emit a global initialization.
void emitGlobalInitialization(PatternBindingDecl *initializer, unsigned elt);
/// Should the self argument of the given method always be emitted as
/// an r-value (meaning that it can be borrowed only if that is not
/// semantically detectable), or it acceptable to emit it as a borrowed
/// storage reference?
bool shouldEmitSelfAsRValue(FuncDecl *method, CanType selfType);
/// Is the self method of the given nonmutating method passed indirectly?
bool isNonMutatingSelfIndirect(PILDeclRef method);
PILDeclRef getAccessorDeclRef(AccessorDecl *accessor);
bool canStorageUseStoredKeyPathComponent(AbstractStorageDecl *decl,
ResilienceExpansion expansion);
KeyPathPatternComponent
emitKeyPathComponentForDecl(PILLocation loc,
GenericEnvironment *genericEnv,
ResilienceExpansion expansion,
unsigned &baseOperand,
bool &needsGenericContext,
SubstitutionMap subs,
AbstractStorageDecl *storage,
ArrayRef<InterfaceConformanceRef> indexHashables,
CanType baseTy,
bool forPropertyDescriptor);
/// Known functions for bridging.
PILDeclRef getStringToNSStringFn();
PILDeclRef getNSStringToStringFn();
PILDeclRef getArrayToNSArrayFn();
PILDeclRef getNSArrayToArrayFn();
PILDeclRef getDictionaryToNSDictionaryFn();
PILDeclRef getNSDictionaryToDictionaryFn();
PILDeclRef getSetToNSSetFn();
PILDeclRef getNSSetToSetFn();
PILDeclRef getBoolToObjCBoolFn();
PILDeclRef getObjCBoolToBoolFn();
PILDeclRef getBoolToDarwinBooleanFn();
PILDeclRef getDarwinBooleanToBoolFn();
PILDeclRef getBoolToWindowsBoolFn();
PILDeclRef getWindowsBoolToBoolFn();
PILDeclRef getNSErrorToErrorFn();
PILDeclRef getErrorToNSErrorFn();
#define FUNC_DECL(NAME, ID) \
FuncDecl *get##NAME(PILLocation loc);
#include "polarphp/ast/KnownDeclsDef.h"
/// Retrieve the _ObjectiveCBridgeable protocol definition.
InterfaceDecl *getObjectiveCBridgeable(PILLocation loc);
/// Retrieve the _ObjectiveCBridgeable._bridgeToObjectiveC requirement.
FuncDecl *getBridgeToObjectiveCRequirement(PILLocation loc);
/// Retrieve the
/// _ObjectiveCBridgeable._unconditionallyBridgeFromObjectiveC
/// requirement.
FuncDecl *getUnconditionallyBridgeFromObjectiveCRequirement(PILLocation loc);
/// Retrieve the _ObjectiveCBridgeable._ObjectiveCType requirement.
AssociatedTypeDecl *getBridgedObjectiveCTypeRequirement(PILLocation loc);
/// Find the conformance of the given Swift type to the
/// _ObjectiveCBridgeable protocol.
InterfaceConformance *getConformanceToObjectiveCBridgeable(PILLocation loc,
Type type);
/// Retrieve the _BridgedStoredNSError protocol definition.
InterfaceDecl *getBridgedStoredNSError(PILLocation loc);
/// Retrieve the _BridgedStoredNSError._nsError requirement.
VarDecl *getNSErrorRequirement(PILLocation loc);
/// Find the conformance of the given Swift type to the
/// _BridgedStoredNSError protocol.
InterfaceConformanceRef getConformanceToBridgedStoredNSError(PILLocation loc,
Type type);
/// Retrieve the conformance of NSError to the Error protocol.
InterfaceConformance *getNSErrorConformanceToError();
PILFunction *getKeyPathProjectionCoroutine(bool isReadAccess,
KeyPathTypeKind typeKind);
/// Report a diagnostic.
template<typename...T, typename...U>
InFlightDiagnostic diagnose(SourceLoc loc, Diag<T...> diag,
U &&...args) {
return M.getAstContext().Diags.diagnose(loc, diag, std::forward<U>(args)...);
}
template<typename...T, typename...U>
InFlightDiagnostic diagnose(PILLocation loc, Diag<T...> diag,
U &&...args) {
return M.getAstContext().Diags.diagnose(loc.getSourceLoc(),
diag, std::forward<U>(args)...);
}
/// Get or create PILGlobalVariable for a given global VarDecl.
PILGlobalVariable *getPILGlobalVariable(VarDecl *gDecl,
ForDefinition_t forDef);
/// Emit all lazy conformances referenced from this function body.
void emitLazyConformancesForFunction(PILFunction *F);
/// Emit all lazy conformances referenced from this type's signature and
/// stored properties (or in the case of enums, associated values).
void emitLazyConformancesForType(NominalTypeDecl *NTD);
/// Mark a protocol conformance as used, so we know we need to emit it if
/// it's in our TU.
void useConformance(InterfaceConformanceRef conformance);
/// Mark protocol conformances from the given type as used.
void useConformancesFromType(CanType type);
/// Mark protocol conformances from the given set of substitutions as used.
void useConformancesFromSubstitutions(SubstitutionMap subs);
/// Mark _ObjectiveCBridgeable conformances as used for any imported types
/// mentioned by the given type.
void useConformancesFromObjectiveCType(CanType type);
/// Emit a `mark_function_escape` instruction for top-level code when a
/// function or closure at top level refers to script globals.
void emitMarkFunctionEscapeForTopLevelCodeGlobals(PILLocation loc,
CaptureInfo captureInfo);
/// Map the substitutions for the original declaration to substitutions for
/// the overridden declaration.
static SubstitutionMap mapSubstitutionsForWitnessOverride(
AbstractFunctionDecl *original,
AbstractFunctionDecl *overridden,
SubstitutionMap subs);
/// Emit a property descriptor for the given storage decl if it needs one.
void tryEmitPropertyDescriptor(AbstractStorageDecl *decl);
private:
/// Emit the deallocator for a class that uses the objc allocator.
void emitObjCAllocatorDestructor(ClassDecl *cd, DestructorDecl *dd);
};
} // end namespace lowering
} // end namespace polar
#endif // POLARPHP_PIL_GEN_PILGEN_H
| 6,802 |
688 | <reponame>zaferbozkurt/electrode-native
/*
* Copyright 2017 WalmartLabs
*
* 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 <Foundation/Foundation.h>
#if __has_include(<React/RCTBridgeDelegate.h>)
#import <React/RCTBridgeDelegate.h>
#elif __has_include("RCTBridgeDelegate.h")
#import "RCTBridgeDelegate.h"
#else
#import "React/RCTBridgeDelegate.h" // Required when used as a Pod in a Swift project
#endif
#import "ElectrodePluginConfig.h"
NS_ASSUME_NONNULL_BEGIN
@interface ElectrodeBridgeDelegate : NSObject <RCTBridgeDelegate>
@property(nonatomic, strong) NSURL *jsBundleURL;
- (instancetype)initWithModuleURL:(NSURL *)url extraModules:(NSArray *)modules;
- (instancetype)initWithContainerConfig:(id<ElectrodePluginConfig>)containerConfig
codePushConfig:(id<ElectrodePluginConfig>)codePushConfig;
- (void)setUp;
NS_ASSUME_NONNULL_END
@end
| 453 |
32,544 | <filename>testing-modules/testing-libraries/src/test/java/com/baeldung/cucumber/books/BookStoreIntegrationTest.java
package com.baeldung.cucumber.books;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:features/book-store.feature")
public class BookStoreIntegrationTest {
}
| 144 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Narbonne","circ":"2ème circonscription","dpt":"Aude","inscrits":38904,"abs":21284,"votants":17620,"blancs":357,"nuls":140,"exp":17123,"res":[{"nuance":"REM","nom":"<NAME>","voix":4884},{"nuance":"FN","nom":"<NAME>","voix":2901},{"nuance":"SOC","nom":"Mme <NAME>","voix":2822},{"nuance":"LR","nom":"<NAME>","voix":2561},{"nuance":"FI","nom":"<NAME>","voix":1980},{"nuance":"COM","nom":"<NAME>","voix":476},{"nuance":"ECO","nom":"Mme <NAME>","voix":468},{"nuance":"DLF","nom":"M. <NAME>","voix":233},{"nuance":"EXD","nom":"Mme <NAME>","voix":176},{"nuance":"DVG","nom":"<NAME>","voix":143},{"nuance":"DVD","nom":"<NAME>","voix":124},{"nuance":"DIV","nom":"M. <NAME>","voix":87},{"nuance":"EXG","nom":"Mme <NAME>","voix":86},{"nuance":"DIV","nom":"M. <NAME>","voix":76},{"nuance":"DIV","nom":"Mme <NAME>","voix":62},{"nuance":"EXD","nom":"M. <NAME>","voix":44},{"nuance":"DVD","nom":"Mme <NAME>","voix":0}]} | 382 |
945 | <filename>Modules/ThirdParty/VNL/src/vxl/v3p/netlib/datapac/camsun.h
/*: Computes the float cumulative distribution function value for the chi-squared distribution */
void v3p_netlib_chscdf_(
v3p_netlib_real v3p_netlib_const *x, /*!< (IN) value where the cumulative distribution must be evaluated */
v3p_netlib_integer v3p_netlib_const *nu, /*!< (IN) # degrees of freedom */
v3p_netlib_real *cdf /*!< (OUT) the function value */
);
/*: Computes the double cumulative distribution function value for the chi-squared distribution */
void v3p_netlib_dchscdf_(
v3p_netlib_doublereal v3p_netlib_const *x, /*!< (IN) value where the cumulative distribution must be evaluated */
v3p_netlib_integer v3p_netlib_const *nu, /*!< (IN) # degrees of freedom */
v3p_netlib_doublereal *cdf /*!< (OUT) the function value */
);
| 335 |
455 | <reponame>mattt21/zcoin
/* Copyright (c) 2001 <NAME>.
* Copyright (c) 2001-2004, <NAME>.
* Copyright (c) 2004-2006, <NAME>, <NAME>.
* Copyright (c) 2007-2019, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#ifndef TOR_COUNTRY_H
#define TOR_COUNTRY_H
#include "lib/cc/torint.h"
/** A signed integer representing a country code. */
typedef int16_t country_t;
#define COUNTRY_MAX INT16_MAX
#endif
| 153 |
545 | //
// Created by <NAME> on 2020/4/1.
//
#include "mm/fmm/fmm_app_config.hpp"
#include "util/debug.hpp"
#include "util/util.hpp"
using namespace FMM::CORE;
using namespace FMM::NETWORK;
using namespace FMM::CONFIG;
using namespace FMM::MM;
FMMAppConfig::FMMAppConfig(int argc, char **argv){
spdlog::set_pattern("[%^%l%$][%s:%-3#] %v");
if (argc==2) {
std::string configfile(argv[1]);
if (UTIL::check_file_extension(configfile,"xml,XML"))
load_xml(configfile);
else {
load_arg(argc,argv);
}
} else {
load_arg(argc,argv);
}
spdlog::set_level((spdlog::level::level_enum) log_level);
if (!help_specified)
print();
};
void FMMAppConfig::load_xml(const std::string &file){
SPDLOG_INFO("Start with reading FMM configuration {}",file);
// Create empty property tree object
boost::property_tree::ptree tree;
boost::property_tree::read_xml(file, tree);
network_config = NetworkConfig::load_from_xml(tree);
gps_config = GPSConfig::load_from_xml(tree);
result_config = CONFIG::ResultConfig::load_from_xml(tree);
fmm_config = FastMapMatchConfig::load_from_xml(tree);
// UBODT
ubodt_file = tree.get<std::string>("config.input.ubodt.file");
log_level = tree.get("config.other.log_level",2);
step = tree.get("config.other.step",100);
use_omp = !(!tree.get_child_optional("config.other.use_omp"));
SPDLOG_INFO("Finish with reading FMM xml configuration");
};
void FMMAppConfig::load_arg(int argc, char **argv){
SPDLOG_INFO("Start reading FMM configuration from arguments");
cxxopts::Options options("fmm_config", "Configuration parser of fmm");
NetworkConfig::register_arg(options);
GPSConfig::register_arg(options);
ResultConfig::register_arg(options);
FastMapMatchConfig::register_arg(options);
options.add_options()
("ubodt","Ubodt file name",
cxxopts::value<std::string>()->default_value(""))
("l,log_level","Log level",cxxopts::value<int>()->default_value("2"))
("s,step","Step report",cxxopts::value<int>()->default_value("100"))
("h,help","Help information")
("use_omp","Use parallel computing if specified");
if (argc==1) {
help_specified = true;
return;
}
auto result = options.parse(argc, argv);
network_config = NetworkConfig::load_from_arg(result);
gps_config = GPSConfig::load_from_arg(result);
result_config = CONFIG::ResultConfig::load_from_arg(result);
fmm_config = FastMapMatchConfig::load_from_arg(result);
ubodt_file = result["ubodt"].as<std::string>();
log_level = result["log_level"].as<int>();
step = result["step"].as<int>();
use_omp = result.count("use_omp")>0;
if (result.count("help")>0) {
help_specified = true;
}
SPDLOG_INFO("Finish with reading FMM arg configuration");
};
void FMMAppConfig::print_help(){
std::ostringstream oss;
oss<<"fmm argument lists:\n";
oss<<"--ubodt (required) <string>: Ubodt file name\n";
NetworkConfig::register_help(oss);
GPSConfig::register_help(oss);
ResultConfig::register_help(oss);
FastMapMatchConfig::register_help(oss);
oss<<"-l/--log_level (optional) <int>: log level (2)\n";
oss<<"-s/--step (optional) <int>: progress report step (100)\n";
oss<<"--use_omp: use OpenMP for multithreaded map matching\n";
oss<<"-h/--help:print help information\n";
oss<<"For xml configuration, check example folder\n";
std::cout<<oss.str();
};
void FMMAppConfig::print() const {
SPDLOG_INFO("---- Print configuration ----");
network_config.print();
gps_config.print();
result_config.print();
fmm_config.print();
SPDLOG_INFO("Log level {}",UTIL::LOG_LEVESLS[log_level]);
SPDLOG_INFO("Step {}",step);
SPDLOG_INFO("Use omp {}",(use_omp ? "true" : "false"));
SPDLOG_INFO("---- Print configuration done ----");
};
bool FMMAppConfig::validate() const
{
SPDLOG_DEBUG("Validating configuration");
if (log_level<0 || log_level>UTIL::LOG_LEVESLS.size()) {
SPDLOG_CRITICAL("Invalid log_level {}, which should be 0 - 6",log_level);
SPDLOG_CRITICAL("0-trace,1-debug,2-info,3-warn,4-err,5-critical,6-off");
return false;
}
if (!gps_config.validate()) {
return false;
}
if (!result_config.validate()) {
return false;
}
if (!network_config.validate()) {
return false;
}
if (!fmm_config.validate()) {
return false;
}
if (!UTIL::file_exists(ubodt_file)) {
SPDLOG_CRITICAL("UBODT file not exists {}", ubodt_file);
return false;
}
SPDLOG_DEBUG("Validating done");
return true;
};
| 1,680 |
591 | <reponame>zhiqiang-hu/apollo-DuerOS
/**
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.carlifevehicle.bluetooth;
import android.os.Message;
/**
* {@hide}
*
* The interface for implementing states in a {@link StateMachine}
*/
public interface IState {
/**
* Returned by processMessage to indicate the the message was processed.
*/
static final boolean HANDLED = true;
/**
* Returned by processMessage to indicate the the message was NOT processed.
*/
static final boolean NOT_HANDLED = false;
/**
* Called when a state is entered.
*/
void enter();
/**
* Called when a state is exited.
*/
void exit();
/**
* Called when a message is to be processed by the
* state machine.
*
* This routine is never reentered thus no synchronization
* is needed as only one processMessage method will ever be
* executing within a state machine at any given time. This
* does mean that processing by this routine must be completed
* as expeditiously as possible as no subsequent messages will
* be processed until this routine returns.
*
* @param msg to process
* @return HANDLED if processing has completed and NOT_HANDLED
* if the message wasn't processed.
*/
boolean processMessage(Message msg);
/**
* Name of State for debugging purposes.
*
* @return name of state.
*/
String getName();
}
| 649 |
308 | import os
import shutil
import pytest
import boto3
import random
import string
from moto import mock_s3
from aws_ir.libs import case
log_base = "{}/mock_s3".format(os.path.dirname(os.path.abspath(__file__)))
def setup_module():
if not os.path.exists(log_base):
os.mkdir(log_base)
def teardown_module():
shutil.rmtree(log_base, ignore_errors=True)
@pytest.fixture
def s3():
""" is a fixture the best place for this?"""
s3_mock = mock_s3()
s3_mock.start()
return s3_mock
def test_object_init(s3):
created_buckets = []
with s3:
# test init with no args
case_without_args = case.Case()
created_buckets.append(case_without_args.case_bucket)
assert case_without_args is not None
assert case_without_args.case_number is not None
assert case_without_args.case_bucket is not None
assert case_without_args.examiner_cidr_range == '0.0.0.0/0'
# test init with case number
case_with_number = case.Case(
case_number='cr-16-022605-3da6'
)
created_buckets.append(case_with_number.case_bucket)
assert case_with_number is not None
assert case_with_number.case_number == 'cr-16-022605-3da6'
assert case_with_number.case_bucket is not None
assert case_with_number.examiner_cidr_range == '0.0.0.0/0'
# test init with cidr_range
case_with_cidr = case.Case(
examiner_cidr_range='8.8.8.8/32'
)
created_buckets.append(case_with_cidr.case_bucket)
assert case_with_cidr is not None
assert case_with_cidr.case_number is not None
assert case_with_cidr.case_bucket is not None
assert case_with_cidr.examiner_cidr_range == '8.8.8.8/32'
def test_init_with_existing_bucket(s3):
created_buckets = []
s3_resource = boto3.resource(
service_name='s3',
region_name='us-west-2'
)
existing_bucket_name = "case-lib-test-{0}".format(
''.join(
random.choice(
string.ascii_lowercase + string.digits
)
for _ in range(10)
)
)
with s3:
s3_resource.Bucket(existing_bucket_name).create()
created_buckets.append(existing_bucket_name)
case_with_bucket = case.Case(
case_bucket=existing_bucket_name
)
assert case_with_bucket is not None
assert case_with_bucket.case_number is not None
assert case_with_bucket.case_bucket == existing_bucket_name
assert case_with_bucket.examiner_cidr_range == '0.0.0.0/0'
def test_rename_log_file():
# remove this test once we can test case.teardown
generic_case = case.Case()
test_log = "{0}/{1}-aws_ir.log".format(log_base, generic_case.case_number)
with open(test_log, 'w') as f:
f.write('test log data')
f.close()
# create test screenshot
test_jpg = "{0}/{1}-console.jpg".format(
log_base,
generic_case.case_number
)
with open(test_jpg, 'w') as f:
f.write('test jpg data')
f.close()
result = generic_case._rename_log_file(
generic_case.case_number,
'i-12345678',
base_dir=log_base
)
assert result is True
def test_copy_logs_to_s3(s3):
created_buckets = []
with s3:
s3_resource = boto3.resource(
service_name='s3',
region_name='us-west-2'
)
existing_bucket_name = "case-lib-test-{0}".format(
''.join(
random.choice(
string.ascii_lowercase + string.digits
)
for _ in range(10)
)
)
s3_resource.Bucket(existing_bucket_name).create()
created_buckets.append(existing_bucket_name)
# create a Case object for testing
generic_case = case.Case()
created_buckets.append(generic_case.case_bucket)
# create test files
test_log = "{0}/{1}-aws_ir.log".format(
log_base,
generic_case.case_number
)
renamed_test_log = "{0}/{1}-{2}-aws_ir.log".format(
log_base,
generic_case.case_number,
'i-12345678'
)
with open(test_log, 'w') as f:
f.write('test log data')
f.close()
# create test screenshot
test_jpg = "{0}/{1}-console.jpg".format(
log_base,
generic_case.case_number
)
with open(test_jpg, 'w') as f:
f.write('test jpg data')
f.close()
generic_case._rename_log_file(
generic_case.case_number,
'i-12345678',
base_dir=log_base
)
generic_case.copy_logs_to_s3(base_dir=log_base)
case_bucket = s3_resource.Bucket(generic_case.case_bucket)
uploaded_files = []
for obj in case_bucket.objects.all():
print(obj.key)
uploaded_files.append(obj.key)
test_log_key = renamed_test_log.split("/")[-1]
test_jpg_key = test_jpg.split("/")[-1]
assert test_log_key in uploaded_files
assert test_jpg_key in uploaded_files
| 2,581 |
879 | package org.zstack.core.externalservice;
public interface ExternalService {
String getName();
void start();
void stop();
void restart();
boolean isAlive();
}
| 62 |
691 | <reponame>kevcadieux/Sprout
/*=============================================================================
Copyright (c) 2011-2019 <NAME>
https://github.com/bolero-MURAKAMI/Sprout
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 SPROUT_TYPE_TRAITS_PROPERTY_HPP
#define SPROUT_TYPE_TRAITS_PROPERTY_HPP
#include <sprout/config.hpp>
// 20.10.4.3 Type properties
#include <sprout/type_traits/is_const.hpp>
#include <sprout/type_traits/is_volatile.hpp>
#include <sprout/type_traits/is_trivial.hpp>
#include <sprout/type_traits/is_trivially_copyable.hpp>
#include <sprout/type_traits/is_standard_layout.hpp>
#include <sprout/type_traits/is_pod.hpp>
#include <sprout/type_traits/is_literal_type.hpp>
#include <sprout/type_traits/has_unique_object_representations.hpp>
#include <sprout/type_traits/is_empty.hpp>
#include <sprout/type_traits/is_polymorphic.hpp>
#include <sprout/type_traits/is_abstract.hpp>
#include <sprout/type_traits/is_final.hpp>
#include <sprout/type_traits/is_aggregate.hpp>
#include <sprout/type_traits/is_signed.hpp>
#include <sprout/type_traits/is_unsigned.hpp>
#include <sprout/type_traits/is_constructible.hpp>
#include <sprout/type_traits/is_default_constructible.hpp>
#include <sprout/type_traits/is_copy_constructible.hpp>
#include <sprout/type_traits/is_move_constructible.hpp>
#include <sprout/type_traits/is_assignable.hpp>
#include <sprout/type_traits/is_copy_assignable.hpp>
#include <sprout/type_traits/is_move_assignable.hpp>
#include <sprout/type_traits/is_swappable_with.hpp>
#include <sprout/type_traits/is_swappable.hpp>
#include <sprout/type_traits/is_destructible.hpp>
#include <sprout/type_traits/is_trivially_constructible.hpp>
#include <sprout/type_traits/is_trivially_default_constructible.hpp>
#include <sprout/type_traits/is_trivially_copy_constructible.hpp>
#include <sprout/type_traits/is_trivially_move_constructible.hpp>
#include <sprout/type_traits/is_trivially_assignable.hpp>
#include <sprout/type_traits/is_trivially_copy_assignable.hpp>
#include <sprout/type_traits/is_trivially_move_assignable.hpp>
#include <sprout/type_traits/is_trivially_destructible.hpp>
#include <sprout/type_traits/is_nothrow_constructible.hpp>
#include <sprout/type_traits/is_nothrow_default_constructible.hpp>
#include <sprout/type_traits/is_nothrow_copy_constructible.hpp>
#include <sprout/type_traits/is_nothrow_move_constructible.hpp>
#include <sprout/type_traits/is_nothrow_assignable.hpp>
#include <sprout/type_traits/is_nothrow_copy_assignable.hpp>
#include <sprout/type_traits/is_nothrow_move_assignable.hpp>
#include <sprout/type_traits/is_nothrow_swappable_with.hpp>
#include <sprout/type_traits/is_nothrow_swappable.hpp>
#include <sprout/type_traits/is_nothrow_destructible.hpp>
#include <sprout/type_traits/has_virtual_destructor.hpp>
#include <sprout/type_traits/is_const_unqualified.hpp>
#include <sprout/type_traits/is_volatile_unqualified.hpp>
#include <sprout/type_traits/is_cv_unqualified.hpp>
#include <sprout/type_traits/is_sint.hpp>
#include <sprout/type_traits/is_uint.hpp>
#include <sprout/type_traits/is_char_type.hpp>
#include <sprout/type_traits/is_c_str.hpp>
#include <sprout/type_traits/has_type.hpp>
#include <sprout/type_traits/has_value.hpp>
#endif // #ifndef SPROUT_TYPE_TRAITS_PROPERTY_HPP
| 1,455 |
679 | /**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include <cstdio>
#include "document.hxx"
#include "docuno.hxx"
#include "sheetdata.hxx"
#include "xmlbodyi.hxx"
#include "xmltabi.hxx"
#include "xmlnexpi.hxx"
#include "xmldrani.hxx"
#include "xmlimprt.hxx"
#include "xmldpimp.hxx"
#include "xmlcvali.hxx"
#include "xmlstyli.hxx"
#include "xmllabri.hxx"
#include "XMLConsolidationContext.hxx"
#include "XMLDDELinksContext.hxx"
#include "XMLCalculationSettingsContext.hxx"
#include "XMLTrackedChangesContext.hxx"
#include "XMLEmptyContext.hxx"
#include "scerrors.hxx"
#include "tabprotection.hxx"
#include <xmloff/xmltkmap.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmluconv.hxx>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <sal/types.h>
#include <tools/debug.hxx>
#include <memory>
using rtl::OUString;
using namespace com::sun::star;
using namespace xmloff::token;
//------------------------------------------------------------------
ScXMLBodyContext::ScXMLBodyContext( ScXMLImport& rImport,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const uno::Reference<xml::sax::XAttributeList>& xAttrList ) :
SvXMLImportContext( rImport, nPrfx, rLName ),
sPassword(),
bProtected(sal_False),
bHadCalculationSettings(sal_False),
pChangeTrackingImportHelper(NULL)
{
ScDocument* pDoc = GetScImport().GetDocument();
if (pDoc)
{
// ODF 1.1 and earlier => GRAM_PODF; ODF 1.2 and later => GRAM_ODFF;
// no version => earlier than 1.2 => GRAM_PODF.
formula::FormulaGrammar::Grammar eGrammar = formula::FormulaGrammar::GRAM_ODFF;
OUString aVer( rImport.GetODFVersion());
sal_Int32 nLen = aVer.getLength();
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "\n ScXMLBodyContext ODFVersion: nLen: %d, str: %s\n",
(int)nLen, OUStringToOString( aVer, RTL_TEXTENCODING_UTF8).getStr());
#endif
if (!nLen)
eGrammar = formula::FormulaGrammar::GRAM_PODF;
else
{
// In case there was a micro version, e.g. "1.2.3", this would
// still yield major.minor, but pParsedEnd (5th parameter, not
// passed here) would point before string end upon return.
double fVer = ::rtl::math::stringToDouble( aVer, '.', 0, NULL, NULL);
if (fVer < 1.2)
eGrammar = formula::FormulaGrammar::GRAM_PODF;
}
pDoc->SetStorageGrammar( eGrammar);
}
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; ++i )
{
const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));
rtl::OUString aLocalName;
sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));
if (nPrefix == XML_NAMESPACE_TABLE)
{
if (IsXMLToken(aLocalName, XML_STRUCTURE_PROTECTED))
bProtected = IsXMLToken(sValue, XML_TRUE);
else if (IsXMLToken(aLocalName, XML_PROTECTION_KEY))
sPassword = sValue;
}
}
}
ScXMLBodyContext::~ScXMLBodyContext()
{
}
SvXMLImportContext *ScXMLBodyContext::CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
ScSheetSaveData* pSheetData = ScModelObj::getImplementation(GetScImport().GetModel())->GetSheetSaveData();
if ( pSheetData && pSheetData->HasStartPos() )
{
// stream part to copy ends before the next child element
sal_Int32 nEndOffset = GetScImport().GetByteOffset();
pSheetData->EndStreamPos( nEndOffset );
}
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetScImport().GetBodyElemTokenMap();
// sal_Bool bOrdered = sal_False;
// sal_Bool bHeading = sal_False;
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
// case XML_TOK_TEXT_H:
// bHeading = sal_True;
// case XML_TOK_TEXT_P:
// pContext = new SwXMLParaContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bHeading );
// break;
// case XML_TOK_TEXT_ORDERED_LIST:
// bOrdered = sal_True;
// case XML_TOK_TEXT_UNORDERED_LIST:
// pContext = new SwXMLListBlockContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bOrdered );
// break;
case XML_TOK_BODY_TRACKED_CHANGES :
{
pChangeTrackingImportHelper = GetScImport().GetChangeTrackingImportHelper();
if (pChangeTrackingImportHelper)
pContext = new ScXMLTrackedChangesContext( GetScImport(), nPrefix, rLocalName, xAttrList, pChangeTrackingImportHelper);
}
break;
case XML_TOK_BODY_CALCULATION_SETTINGS :
pContext = new ScXMLCalculationSettingsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
bHadCalculationSettings = sal_True;
break;
case XML_TOK_BODY_CONTENT_VALIDATIONS :
pContext = new ScXMLContentValidationsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_LABEL_RANGES:
pContext = new ScXMLLabelRangesContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_TABLE:
{
if (GetScImport().GetTables().GetCurrentSheet() >= MAXTAB)
{
GetScImport().SetRangeOverflowType(SCWARN_IMPORT_SHEET_OVERFLOW);
pContext = new ScXMLEmptyContext(GetScImport(), nPrefix, rLocalName);
}
else
{
pContext = new ScXMLTableContext( GetScImport(),nPrefix, rLocalName,
xAttrList );
}
}
break;
case XML_TOK_BODY_NAMED_EXPRESSIONS:
pContext = new ScXMLNamedExpressionsContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
static_cast<ScXMLNamedExpressionsContext*>(pContext)->SetScope( MAXTABCOUNT );//workbookname
break;
case XML_TOK_BODY_DATABASE_RANGES:
pContext = new ScXMLDatabaseRangesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATABASE_RANGE:
pContext = new ScXMLDatabaseRangeContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATA_PILOT_TABLES:
pContext = new ScXMLDataPilotTablesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_CONSOLIDATION:
pContext = new ScXMLConsolidationContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DDE_LINKS:
pContext = new ScXMLDDELinksContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
void ScXMLBodyContext::Characters( const OUString& )
{
ScSheetSaveData* pSheetData = ScModelObj::getImplementation(GetScImport().GetModel())->GetSheetSaveData();
if ( pSheetData && pSheetData->HasStartPos() )
{
// stream part to copy ends before any content (whitespace) within the spreadsheet element
sal_Int32 nEndOffset = GetScImport().GetByteOffset();
pSheetData->EndStreamPos( nEndOffset );
}
// otherwise ignore
}
void ScXMLBodyContext::EndElement()
{
ScSheetSaveData* pSheetData = ScModelObj::getImplementation(GetScImport().GetModel())->GetSheetSaveData();
if ( pSheetData && pSheetData->HasStartPos() )
{
// stream part to copy ends before the closing tag of spreadsheet element
sal_Int32 nEndOffset = GetScImport().GetByteOffset();
pSheetData->EndStreamPos( nEndOffset );
}
if ( pSheetData )
{
// store the loaded namespaces (for the office:spreadsheet element),
// so the prefixes in copied stream fragments remain valid
const SvXMLNamespaceMap& rNamespaces = GetImport().GetNamespaceMap();
pSheetData->StoreLoadedNamespaces( rNamespaces );
}
if (!bHadCalculationSettings)
{
// #111055#; set calculation settings defaults if there is no calculation settings element
SvXMLImportContext *pContext = new ScXMLCalculationSettingsContext( GetScImport(), XML_NAMESPACE_TABLE, GetXMLToken(XML_CALCULATION_SETTINGS), NULL );
pContext->EndElement();
}
GetScImport().LockSolarMutex();
ScMyImpDetectiveOpArray* pDetOpArray = GetScImport().GetDetectiveOpArray();
ScDocument* pDoc = GetScImport().GetDocument();
ScMyImpDetectiveOp aDetOp;
if (pDoc && GetScImport().GetModel().is())
{
if (pDetOpArray)
{
pDetOpArray->Sort();
while( pDetOpArray->GetFirstOp( aDetOp ) )
{
ScDetOpData aOpData( aDetOp.aPosition, aDetOp.eOpType );
pDoc->AddDetectiveOperation( aOpData );
}
}
if (pChangeTrackingImportHelper)
pChangeTrackingImportHelper->CreateChangeTrack(GetScImport().GetDocument());
#if 0
// #i57869# table styles are applied before the contents now
std::vector<rtl::OUString> aTableStyleNames(GetScImport().GetTableStyle());
uno::Reference <sheet::XSpreadsheetDocument> xSpreadDoc( GetScImport().GetModel(), uno::UNO_QUERY );
if ( xSpreadDoc.is() && !aTableStyleNames.empty())
{
uno::Reference <container::XIndexAccess> xIndex( xSpreadDoc->getSheets(), uno::UNO_QUERY );
if ( xIndex.is() )
{
sal_Int32 nTableCount = xIndex->getCount();
sal_Int32 nSize(aTableStyleNames.size());
DBG_ASSERT(nTableCount == nSize, "every table should have a style name");
for(sal_uInt32 i = 0; i < nTableCount; i++)
{
if (i < nSize)
{
uno::Reference <beans::XPropertySet> xProperties(xIndex->getByIndex(i), uno::UNO_QUERY);
if (xProperties.is())
{
rtl::OUString sTableStyleName(aTableStyleNames[i]);
XMLTableStylesContext *pStyles = (XMLTableStylesContext *)GetScImport().GetAutoStyles();
if ( pStyles && sTableStyleName.getLength() )
{
XMLTableStyleContext* pStyle = (XMLTableStyleContext *)pStyles->FindStyleChildContext(
XML_STYLE_FAMILY_TABLE_TABLE, sTableStyleName, sal_True);
if (pStyle)
pStyle->FillPropertySet(xProperties);
}
}
}
}
}
}
#endif
// #i37959# handle document protection after the sheet settings
if (bProtected)
{
::std::auto_ptr<ScDocProtection> pProtection(new ScDocProtection);
pProtection->setProtected(true);
uno::Sequence<sal_Int8> aPass;
if (sPassword.getLength())
{
SvXMLUnitConverter::decodeBase64(aPass, sPassword);
pProtection->setPasswordHash(aPass, PASSHASH_OOO);
}
pDoc->SetDocProtection(pProtection.get());
}
}
GetScImport().UnlockSolarMutex();
}
| 5,066 |
1,346 | <gh_stars>1000+
package com.ctrip.platform.dal.dao.datasource.cluster;
import com.ctrip.framework.dal.cluster.client.multihost.ClusterRouteStrategyConfig;
import com.ctrip.framework.dal.cluster.client.util.CaseInsensitiveProperties;
import com.ctrip.platform.dal.dao.datasource.cluster.strategy.RouteStrategy;
/**
* @author c7ch23en
*/
public class MultiHostClusterPropertiesAdapter implements MultiHostClusterProperties {
private final ClusterRouteStrategyConfig routeStrategyConfig;
public MultiHostClusterPropertiesAdapter(ClusterRouteStrategyConfig routeStrategyConfig, String clusterName) {
this.routeStrategyConfig = routeStrategyConfig;
setClusterName(clusterName);
}
private void setClusterName(String clusterName) {
if (this.routeStrategyConfig != null) {
CaseInsensitiveProperties properties = this.routeStrategyConfig.routeStrategyProperties();
if (properties != null) {
properties.set(CLUSTER_NAME, clusterName);
}
}
}
@Override
public String routeStrategyName() {
return routeStrategyConfig.routeStrategyName();
}
@Override
public boolean multiMaster() {
return routeStrategyConfig.multiMaster();
}
@Override
public CaseInsensitiveProperties routeStrategyProperties() {
return routeStrategyConfig.routeStrategyProperties();
}
@Override
public RouteStrategy generate() {
return routeStrategyConfig.generate();
}
}
| 540 |
1,647 | <filename>pythran/pythonic/numpy/where.hpp
#ifndef PYTHONIC_NUMPY_WHERE_HPP
#define PYTHONIC_NUMPY_WHERE_HPP
#include "pythonic/include/numpy/where.hpp"
#include "pythonic/numpy/asarray.hpp"
#include "pythonic/numpy/nonzero.hpp"
#include "pythonic/numpy/copy.hpp"
PYTHONIC_NS_BEGIN
namespace numpy
{
namespace impl
{
template <class E, class F, class G>
typename __combined<F, G>::type where(E const &cond, F const &true_,
G const &false_)
{
if (cond)
return true_;
else
return false_;
}
}
#define NUMPY_NARY_FUNC_NAME where
#define NUMPY_NARY_FUNC_SYM impl::where
#define NUMPY_NARY_RESHAPE_MODE reshape_type
#include "pythonic/types/numpy_nary_expr.hpp"
}
namespace types
{
template <>
struct Dereferencer<numpy::functor::where> {
template <class Ts>
auto operator()(Ts const &iters, utils::index_sequence<0, 1, 2>) ->
typename std::enable_if<
types::is_dtype<
typename std::remove_cv<typename std::remove_reference<
decltype(*std::get<0>(iters))>::type>::type>::value &&
types::is_dtype<
typename std::remove_cv<typename std::remove_reference<
decltype(*std::get<1>(iters))>::type>::type>::value &&
types::is_dtype<
typename std::remove_cv<typename std::remove_reference<
decltype(*std::get<2>(iters))>::type>::type>::value,
decltype(numpy::impl::where(*std::get<0>(iters),
*std::get<1>(iters),
*std::get<2>(iters)))>::type
{
if (*std::get<0>(iters))
return *std::get<1>(iters);
else
return *std::get<2>(iters);
}
template <class Ts, size_t... I>
auto operator()(Ts const &iters, utils::index_sequence<I...>, ...)
-> decltype(numpy::functor::where{}(*std::get<I>(iters)...))
{
return numpy::functor::where{}(*std::get<I>(iters)...);
}
};
}
PYTHONIC_NS_END
#endif
| 1,092 |
10,694 | <filename>okgo/src/main/java/com/lzy/okgo/callback/BitmapCallback.java
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.lzy.okgo.callback;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.lzy.okgo.convert.BitmapConvert;
import okhttp3.Response;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2016/1/12
* 描 述:返回图片的Bitmap,这里没有进行图片的缩放,可能会发生 OOM
* 修订历史:
* ================================================
*/
public abstract class BitmapCallback extends AbsCallback<Bitmap> {
private BitmapConvert convert;
public BitmapCallback() {
convert = new BitmapConvert();
}
public BitmapCallback(int maxWidth, int maxHeight) {
convert = new BitmapConvert(maxWidth, maxHeight);
}
public BitmapCallback(int maxWidth, int maxHeight, Bitmap.Config decodeConfig, ImageView.ScaleType scaleType) {
convert = new BitmapConvert(maxWidth, maxHeight, decodeConfig, scaleType);
}
@Override
public Bitmap convertResponse(Response response) throws Throwable {
Bitmap bitmap = convert.convertResponse(response);
response.close();
return bitmap;
}
}
| 675 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.