max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
348 | <filename>docs/data/leg-t2/071/07101226.json
{"nom":"Grevilly","circ":"1ère circonscription","dpt":"Saône-et-Loire","inscrits":35,"abs":10,"votants":25,"blancs":4,"nuls":2,"exp":19,"res":[{"nuance":"REM","nom":"<NAME>","voix":12},{"nuance":"LR","nom":"<NAME>","voix":7}]} | 114 |
13,006 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/lib/monitoring/gauge.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace monitoring {
namespace {
auto* gauge_with_labels = Gauge<int64, 1>::New(
"/tensorflow/test/gauge_with_labels", "Gauge with one label.", "MyLabel");
TEST(LabeledGaugeTest, InitializedWithZero) {
EXPECT_EQ(0, gauge_with_labels->GetCell("Empty")->value());
}
TEST(LabeledGaugeTest, GetCell) {
auto* cell = gauge_with_labels->GetCell("GetCellOp");
EXPECT_EQ(0, cell->value());
cell->Set(1);
EXPECT_EQ(1, cell->value());
auto* same_cell = gauge_with_labels->GetCell("GetCellOp");
EXPECT_EQ(1, same_cell->value());
same_cell->Set(10);
EXPECT_EQ(10, cell->value());
EXPECT_EQ(10, same_cell->value());
}
auto* gauge_without_labels = Gauge<int64, 0>::New(
"/tensorflow/test/gauge_without_labels", "Gauge without any labels.");
TEST(UnlabeledGaugeTest, InitializedWithZero) {
EXPECT_EQ(0, gauge_without_labels->GetCell()->value());
}
TEST(UnlabeledGaugeTest, GetCell) {
auto* cell = gauge_without_labels->GetCell();
EXPECT_EQ(0, cell->value());
cell->Set(1);
EXPECT_EQ(1, cell->value());
auto* same_cell = gauge_without_labels->GetCell();
EXPECT_EQ(1, same_cell->value());
same_cell->Set(10);
EXPECT_EQ(10, cell->value());
EXPECT_EQ(10, same_cell->value());
}
auto* string_gauge = Gauge<string, 0>::New("/tensorflow/test/string_gauge",
"Gauge of string value.");
TEST(GaugeOfStringValue, InitializedWithEmptyString) {
EXPECT_EQ("", string_gauge->GetCell()->value());
}
TEST(GaugeOfStringValue, GetCell) {
auto* cell = string_gauge->GetCell();
EXPECT_EQ("", cell->value());
cell->Set("foo");
EXPECT_EQ("foo", cell->value());
auto* same_cell = string_gauge->GetCell();
EXPECT_EQ("foo", cell->value());
same_cell->Set("bar");
EXPECT_EQ("bar", cell->value());
EXPECT_EQ("bar", same_cell->value());
}
auto* bool_gauge =
Gauge<bool, 0>::New("/tensorflow/test/bool_gauge", "Gauge of bool value.");
TEST(GaugeOfBoolValue, InitializedWithFalseValue) {
EXPECT_EQ(false, bool_gauge->GetCell()->value());
}
TEST(GaugeOfBoolValue, GetCell) {
auto* cell = bool_gauge->GetCell();
EXPECT_EQ(false, cell->value());
cell->Set(true);
EXPECT_EQ(true, cell->value());
auto* same_cell = bool_gauge->GetCell();
EXPECT_EQ(true, cell->value());
same_cell->Set(false);
EXPECT_EQ(false, cell->value());
EXPECT_EQ(false, same_cell->value());
}
} // namespace
} // namespace monitoring
} // namespace tensorflow
| 1,216 |
1,602 | <filename>third-party/qthread/qthread-src/include/qt_blocking_structs.h
#ifndef QT_BLOCKING_STRUCTS_H
#define QT_BLOCKING_STRUCTS_H
#include <stdlib.h> /* for malloc() and free() */
#include "qt_mpool.h"
#include "qt_shepherd_innards.h"
#include "qt_profiling.h"
#include "qt_debug.h"
typedef enum blocking_syscalls {
ACCEPT,
CONNECT,
NANOSLEEP,
POLL,
READ,
PREAD,
/*RECV,
* RECVFROM,*/
SELECT,
/*SEND,
* SENDTO,*/
/*SIGWAIT,*/
SLEEP,
SYSTEM,
USLEEP,
WAIT4,
WRITE,
PWRITE,
USER_DEFINED
} syscall_t;
typedef struct qthread_addrres_s {
aligned_t *addr; /* ptr to the memory NOT being blocked on */
qthread_t *waiter;
struct qthread_addrres_s *next;
} qthread_addrres_t;
typedef struct _qt_blocking_queue_node_s {
struct _qt_blocking_queue_node_s *next;
qthread_t *thread;
syscall_t op;
uintptr_t args[5];
ssize_t ret;
int err;
} qt_blocking_queue_node_t;
typedef struct qthread_addrstat_s {
QTHREAD_FASTLOCK_TYPE lock;
qthread_addrres_t *EFQ;
qthread_addrres_t *FEQ;
qthread_addrres_t *FFQ;
qthread_addrres_t *FFWQ;
#ifdef QTHREAD_FEB_PROFILING
qtimer_t empty_timer;
#endif
uint_fast8_t full;
uint_fast8_t valid;
} qthread_addrstat_t;
#ifdef UNPOOLED
# define UNPOOLED_ADDRSTAT
# define UNPOOLED_ADDRRES
#endif
#ifdef UNPOOLED_ADDRSTAT
# define ALLOC_ADDRSTAT() (qthread_addrstat_t *)MALLOC(sizeof(qthread_addrstat_t))
# define FREE_ADDRSTAT(t) FREE(t, sizeof(qthread_addrstat_t))
#else
extern qt_mpool generic_addrstat_pool;
# define ALLOC_ADDRSTAT() (qthread_addrstat_t *)qt_mpool_alloc(generic_addrstat_pool)
# define FREE_ADDRSTAT(t) qt_mpool_free(generic_addrstat_pool, t)
#endif // ifdef UNPOOLED_ADDRSTAT
#ifdef UNPOOLED_ADDRRES
# define ALLOC_ADDRRES() (qthread_addrres_t *)MALLOC(sizeof(qthread_addrres_t))
# define FREE_ADDRRES(t) FREE(t, sizeof(qthread_addrres_t))
#else
extern qt_mpool generic_addrres_pool;
static QINLINE qthread_addrres_t *ALLOC_ADDRRES(void)
{ /*{{{ */
qthread_addrres_t *tmp = (qthread_addrres_t *)qt_mpool_alloc(generic_addrres_pool);
return tmp;
} /*}}} */
static QINLINE void FREE_ADDRRES(qthread_addrres_t *t)
{ /*{{{ */
qt_mpool_free(generic_addrres_pool, t);
} /*}}} */
#endif // ifdef UNPOOLED_ADDRRES
#endif // ifndef QT_BLOCKING_STRUCTS_H
/* vim:set expandtab: */
| 1,445 |
658 | {
"name": "svelte-devtools",
"version": "1.3.0",
"description": "Browser devtools extension for debugging Svelte applications.",
"repository": "github:RedHatter/svelte-devtools",
"license": "MIT",
"scripts": {
"build:firefox": "cross-env TARGET=firefox rollup -c",
"build:chrome": "cross-env TARGET=chrome rollup -c",
"build:icon": "node ./scripts/buildIcons.mjs",
"dev": "http-serve test/public -p 8940 & web-ext run -s dest -u http://127.0.0.1:8940 -u about:debugging && kill $!",
"package:firefox": "yarpm run build:icon && yarpm run build:firefox && web-ext build -s dest",
"package:chrome": "yarpm run build:icon && yarpm run build:chrome && web-ext build -s dest"
},
"devDependencies": {
"cross-env": "^7.0.3",
"http-serve": "^1.0.1",
"postcss": "^8.2.2",
"postcss-sorting": "^6.0.0",
"prettier": "^2.2.1",
"prettier-plugin-svelte": "^2.3.0",
"rollup": "^2.35.1",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-jscc": "^2.0.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-transform-input": "git+https://github.com/RedHatter/rollup-plugin-transform-input.git",
"svelte": "^3.20.1",
"svelte-listener": "git+https://github.com/RedHatter/svelte-listener.git",
"svgexport": "^0.4.1",
"web-ext": "^6.1.0",
"yarpm": "^1.1.1"
},
"engines": {
"node": ">=11.14.0"
}
}
| 664 |
2,757 | <gh_stars>1000+
/** @file
The header file for Boot Script Executer module.
This driver is dispatched by Dxe core and the driver will reload itself to ACPI NVS memory
in the entry point. The functionality is to interpret and restore the S3 boot script
Copyright (c) 2013-2015 Intel Corporation.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef _SCRIPT_EXECUTE_H_
#define _SCRIPT_EXECUTE_H_
#include <PiDxe.h>
#include <Library/BaseLib.h>
#include <Library/UefiDriverEntryPoint.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/S3BootScriptLib.h>
#include <Library/PeCoffLib.h>
#include <Library/DxeServicesLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
#include <Library/PcdLib.h>
#include <Library/CacheMaintenanceLib.h>
#include <Library/TimerLib.h>
#include <Library/UefiLib.h>
#include <Library/DebugAgentLib.h>
#include <Library/LockBoxLib.h>
#include <Library/IntelQNCLib.h>
#include <Library/QNCAccessLib.h>
#include <Guid/AcpiS3Context.h>
#include <Guid/BootScriptExecutorVariable.h>
#include <Guid/EventGroup.h>
#include <IndustryStandard/Acpi.h>
/**
a ASM function to transfer control to OS.
@param S3WakingVector The S3 waking up vector saved in ACPI Facs table
@param AcpiLowMemoryBase a buffer under 1M which could be used during the transfer
**/
VOID
AsmTransferControl (
IN UINT32 S3WakingVector,
IN UINT32 AcpiLowMemoryBase
);
VOID
SetIdtEntry (
IN ACPI_S3_CONTEXT *AcpiS3Context
);
/**
Platform specific mechanism to transfer control to 16bit OS waking vector
@param[in] AcpiWakingVector The 16bit OS waking vector
@param[in] AcpiLowMemoryBase A buffer under 1M which could be used during the transfer
**/
VOID
PlatformTransferControl16 (
IN UINT32 AcpiWakingVector,
IN UINT32 AcpiLowMemoryBase
);
#endif //_SCRIPT_EXECUTE_H_
| 865 |
475 | <filename>data_hacking/min_hash/__init__.py
'''Package for Banded Min Hash based Similarity Calculations'''
from min_hash import *
| 41 |
852 | #include "CondFormats/CSCObjects/interface/CSCcrosstalk.h"
#include "FWCore/Utilities/interface/typelookup.h"
TYPELOOKUP_DATA_REG(CSCcrosstalk);
| 62 |
620 | #include <type_traits>
/* Type list */
template <typename... Args>
struct type_list;
template <typename Type>
struct type_list<Type> {
using head = Type;
};
template <typename Head, typename... Tail>
struct type_list<Head, Tail...> : type_list<Head> {
using tail = type_list<Tail...>;
};
/* OMG this awesome void_t metafunction will change your life */
template <typename...>
using void_t = void;
/* Type list metafunctions */
/* count */
template <typename T, typename = void>
struct count : std::integral_constant<int, 1> {};
template <typename T>
struct count<T, void_t<typename T::tail>> :
std::integral_constant<int, 1 + count<typename T::tail>()> {};
/* Alternate implementation uses fewer template instantiations */
template <typename... Elts>
struct different_count;
template <typename... Elts>
struct different_count<type_list<Elts...>> : std::integral_constant<int, sizeof...(Elts)> {};
/* has_tail predicate */
template <typename T>
struct has_tail : /* predicate */ /* if true */ /* if false */
std::conditional<(different_count<T>::value <= 1), std::false_type, std::true_type>::type {};
/* has_handler predicate */
template <typename Handler, typename Evt, typename = void>
struct has_handler : std::false_type {};
template <typename Handler, typename Evt>
struct has_handler<Handler, Evt, decltype( Handler::handle( std::declval<const Evt&>() ) )> :
std::true_type {};
/* Dispatcher */
template <typename Listeners>
class Dispatcher {
template <typename Evt, typename List, bool HasTail, bool HasHandler>
struct post_impl;
// Case 1: Has tail, has a handler
template <typename Evt, typename List>
struct post_impl<Evt, List, true, true>
{
static void call(const Evt& evt) {
List::head::handle(evt);
using Tail = typename List::tail;
constexpr bool has_tail_v = has_tail<Tail>::value;
constexpr bool has_handler_v = has_handler<typename Tail::head, Evt>::value;
post_impl<Evt, Tail, has_tail_v, has_handler_v>::call(evt);
}
};
// Case 2: Has no tail, has a handler
template <typename Evt, typename List>
struct post_impl<Evt, List, false, true>
{
static void call(const Evt& evt) {
List::head::handle(evt);
}
};
// Case 3: Has tail, has no handler
template <typename Evt, typename List>
struct post_impl<Evt, List, true, false>
{
static void call(const Evt& evt) {
using Tail = typename List::tail;
constexpr bool has_tail_v = has_tail<Tail>::value;
constexpr bool has_handler_v = has_handler<typename Tail::head, Evt>::value;
post_impl<Evt, Tail, has_tail_v, has_handler_v>::call(evt);
}
};
// Case 4: Has no tail, has no handler
template <typename Evt, typename List>
struct post_impl<Evt, List, false, false>
{
static void call(const Evt& evt) {
// do nothing.
}
};
public:
template <typename Evt>
static void post(const Evt& t) {
constexpr bool has_tail_v = has_tail<Listeners>::value;
constexpr bool has_handler_v = has_handler<typename Listeners::head, Evt>::value;
post_impl<Evt, Listeners, has_tail_v, has_handler_v>::call(t);
}
};
| 1,558 |
483 | <filename>nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/rocksdb/RocksDBStoreUtilsTest.java
/*
* Copyright (c) 2017-2021 Nitrite author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dizitart.no2.rocksdb;
import org.dizitart.no2.exceptions.InvalidOperationException;
import org.dizitart.no2.store.events.StoreEventListener;
import org.junit.Test;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
public class RocksDBStoreUtilsTest {
@Test
public void testOpenOrCreate() {
assertThrows(InvalidOperationException.class, () -> RocksDBStoreUtils.openOrCreate(new RocksDBConfig()));
}
@Test
public void testOpenOrCreate2() {
RocksDBConfig rocksDBConfig = new RocksDBConfig();
rocksDBConfig.addStoreEventListener(mock(StoreEventListener.class));
assertThrows(InvalidOperationException.class, () -> RocksDBStoreUtils.openOrCreate(rocksDBConfig));
}
}
| 496 |
1,707 | #pragma once
//------------------------------------------------------------------------------
/**
@class Oryol::_priv::winInputMgr
@ingroup _priv
@brief provide input for the Windows D3D-based ports
Input handling for the D3D ports is similar to GLFW (on purpose), most
of the window and input handling code has been copied from GLFW to ensure
same behaviour between the GL and D3D versions of Oryol.
*/
#include "Input/private/inputMgrBase.h"
namespace Oryol {
namespace _priv {
class winInputMgr : public inputMgrBase {
public:
/// constructor
winInputMgr();
/// destructor
~winInputMgr();
/// setup the window input manager
void setup(const InputSetup& setup);
/// discard the windows input manager
void discard();
/// setup the key mapping table
void setupKeyTable();
/// setup input callbacks
void setupCallbacks();
/// discard input callbacks
void discardCallbacks();
/// map winDisplayMgr keycode to Oryol keycode
Key::Code mapKey(int key) const;
/// key callback
static void keyCallback(int key, int scancode, int action, int mods);
/// char callback
static void charCallback(unsigned int unicode);
/// mouse button callback
static void mouseButtonCallback(int button, int action, int mods);
/// cursor position callback
static void cursorPosCallback(double x, double y);
/// cursor enter callback
static void cursorEnterCallback(int entered);
/// scroll callback
static void scrollCallback(double xOffset, double yOffset);
static winInputMgr* self;
int runLoopId;
};
} // namespace _priv
} // namespace Oryol | 507 |
9,724 | <reponame>yunku2002/emscripten
/*
* Copyright 2018 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <emscripten/emscripten.h>
#include <emscripten/html5.h>
#include <GLES2/gl2.h>
GLuint compile_shader(GLenum shaderType, const char *src)
{
GLuint shader = glCreateShader(shaderType);
glShaderSource(shader, 1, &src, NULL);
glCompileShader(shader);
GLint isCompiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
if (!isCompiled)
{
GLint maxLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
char *buf = (char*)malloc(maxLength);
glGetShaderInfoLog(shader, maxLength, NULL, buf);
printf("%s\n", buf);
free(buf);
return 0;
}
return shader;
}
GLuint create_program(GLuint vertexShader, GLuint fragmentShader)
{
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glBindAttribLocation(program, 0, "apos");
glBindAttribLocation(program, 1, "acolor");
glLinkProgram(program);
return program;
}
int main()
{
EmscriptenWebGLContextAttributes attr;
emscripten_webgl_init_context_attributes(&attr);
#ifdef EXPLICIT_SWAP
attr.explicitSwapControl = 1;
#endif
#ifdef DRAW_FROM_CLIENT_MEMORY
// This test verifies that drawing from client-side memory when enableExtensionsByDefault==false works.
attr.enableExtensionsByDefault = 0;
#endif
EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context("#canvas", &attr);
emscripten_webgl_make_context_current(ctx);
static const char vertex_shader[] =
"attribute vec4 apos;"
"attribute vec4 acolor;"
"varying vec4 color;"
"void main() {"
"color = acolor;"
"gl_Position = apos;"
"}";
GLuint vs = compile_shader(GL_VERTEX_SHADER, vertex_shader);
static const char fragment_shader[] =
"precision lowp float;"
"varying vec4 color;"
"void main() {"
"gl_FragColor = color;"
"}";
GLuint fs = compile_shader(GL_FRAGMENT_SHADER, fragment_shader);
GLuint program = create_program(vs, fs);
glUseProgram(program);
static const float pos_and_color[] = {
// x, y, r, g, b
-0.6f, -0.6f, 1, 0, 0,
0.6f, -0.6f, 0, 1, 0,
0.f, 0.6f, 0, 0, 1,
};
#ifdef DRAW_FROM_CLIENT_MEMORY
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 20, pos_and_color);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 20, (void*)(pos_and_color+2));
#else
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(pos_and_color), pos_and_color, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 20, 0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 20, (void*)8);
#endif
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glClearColor(0.3f,0.3f,0.3f,1);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
#ifdef EXPLICIT_SWAP
emscripten_webgl_commit_frame();
#endif
return 0;
}
| 1,320 |
348 | {"nom":"<NAME>","circ":"5ème circonscription","dpt":"Maine-et-Loire","inscrits":2533,"abs":1449,"votants":1084,"blancs":38,"nuls":23,"exp":1023,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":740},{"nuance":"DVD","nom":"M. <NAME>","voix":283}]} | 101 |
341 | <reponame>realulim/extentreports-java<gh_stars>100-1000
package com.aventstack.extentreports.config.external;
@FunctionalInterface
public interface ConfigLoadable<T> {
void apply();
}
| 64 |
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.php.editor.codegen.ui;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.TreeCellRenderer;
/**
*
* @author kuba
*/
public class CheckBoxTreeRenderer extends JPanel implements TreeCellRenderer {
protected JCheckBox check;
protected JLabel label;
private static final JList LIST_FOR_COLORS = new JList();
public CheckBoxTreeRenderer() {
setLayout(new BorderLayout());
setOpaque(true);
this.check = new JCheckBox();
this.label = new JLabel();
add(check, BorderLayout.WEST);
add(label, BorderLayout.CENTER);
check.setOpaque(false);
label.setOpaque(false);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean isSelected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
String stringValue = tree.convertValueToText(value, isSelected,
expanded, leaf, row, hasFocus);
setEnabled(tree.isEnabled());
if (value instanceof CheckNode) {
CheckNode n = (CheckNode) value;
check.setSelected(n.isSelected());
label.setIcon(new ImageIcon(n.getIcon())); // XXX Ask description directly
}
if (isSelected) {
label.setForeground(LIST_FOR_COLORS.getSelectionForeground());
setOpaque(true);
setBackground(LIST_FOR_COLORS.getSelectionBackground());
} else {
label.setForeground(tree.getForeground());
setOpaque(false);
}
label.setText(stringValue);
return this;
}
}
| 970 |
377 | /*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * 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.impetus.kundera.property.accessor;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import com.impetus.kundera.property.PropertyAccessor;
/**
* The Class CalendarAccessor.
*
* @author amresh.singh
*/
public class CalendarAccessor implements PropertyAccessor<Calendar>
{
/** The Constant DATE_FORMATTER. */
private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.ENGLISH);
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])
*/
@Override
public Calendar fromBytes(Class targetClass, byte[] b)
{
Calendar cal = Calendar.getInstance();
Date d = new Date();
if (b == null)
{
return null;
}
LongAccessor longAccessor = new LongAccessor();
d.setTime(longAccessor.fromBytes(targetClass, b));
cal.setTime(d);
return cal;
}
/*
* (non-Javadoc)
*
* @see
* com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)
*/
@Override
public byte[] toBytes(Object object)
{
if (object == null)
{
return null;
}
Calendar cal = (Calendar) object;
// return
// DateAccessor.getFormattedObect(cal.getTime().toString()).getBytes();
LongAccessor longAccessor = new LongAccessor();
return longAccessor.toBytes(cal.getTime().getTime());
}
/*
* (non-Javadoc)
*
* @see
* com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)
*/
@Override
public String toString(Object object)
{
Calendar calendar = (Calendar) object;
if (calendar == null)
{
return null;
}
return String.valueOf(calendar.getTime().getTime());
}
/*
* (non-Javadoc)
*
* @see
* com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String
* )
*/
@Override
public Calendar fromString(Class targetClass, String s)
{
if (s == null)
{
return null;
}
Calendar cal = Calendar.getInstance();
Date d;
// d = (Date)DATE_FORMATTER.parse(s);
d = DateAccessor.getDateByPattern(s);
cal.setTime(d);
return cal;
}
@Override
public Calendar getCopy(Object object)
{
if (object == null)
return null;
Calendar c = (Calendar) object;
Calendar copy = Calendar.getInstance();
copy.setTimeInMillis(c.getTimeInMillis());
return copy;
}
public Calendar getInstance(Class<?> clazz)
{
return Calendar.getInstance();
}
}
| 1,460 |
12,964 | /**
* An implementation of an indexed binary heap priority queue.
*
* <p>This implementation supports arbitrary keys with comparable values. To use arbitrary keys
* (such as strings or objects) first map all your keys to the integer domain [0, N) where N is the
* number of keys you have and then use the mapping with this indexed priority queue.
*
* <p>As convention, I denote 'ki' as the index value in the domain [0, N) associated with key k,
* therefore: ki = map[k]
*
* @author <NAME>, <EMAIL>
*/
package com.williamfiset.algorithms.datastructures.priorityqueue;
public class MinIndexedBinaryHeap<T extends Comparable<T>> extends MinIndexedDHeap<T> {
public MinIndexedBinaryHeap(int maxSize) {
super(2, maxSize);
}
}
| 220 |
5,169 | {
"name": "ACMediaFrame",
"version": "2.0.3",
"summary": "An easy way to display image or video form album or camera, and get more info of image or video to upload and so on.",
"homepage": "https://github.com/honeycao/ACMediaFrame",
"license": "MIT",
"authors": {
"ArthurCao": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/honeycao/ACMediaFrame.git",
"tag": "2.0.3"
},
"source_files": [
"ACMediaFrame/*.{h,m}",
"ACMediaFrame/Libraries/*.{h,m}"
],
"resources": "ACMediaFrame/ACMediaFrame.bundle",
"requires_arc": true,
"dependencies": {
"ACAlertController": [
"~> 1.0.0"
],
"TZImagePickerController": [
"~> 1.7.9"
],
"MWPhotoBrowser": [
"~>2.1.2"
]
}
}
| 355 |
2,479 | <reponame>ziransun/wpt
""" brain-dead simple parser for ini-style files.
(C) <NAME>, <NAME> -- MIT licensed
"""
__all__ = ['IniConfig', 'ParseError']
COMMENTCHARS = "#;"
class ParseError(Exception):
def __init__(self, path, lineno, msg):
Exception.__init__(self, path, lineno, msg)
self.path = path
self.lineno = lineno
self.msg = msg
def __str__(self):
return "%s:%s: %s" % (self.path, self.lineno+1, self.msg)
class SectionWrapper(object):
def __init__(self, config, name):
self.config = config
self.name = name
def lineof(self, name):
return self.config.lineof(self.name, name)
def get(self, key, default=None, convert=str):
return self.config.get(self.name, key,
convert=convert, default=default)
def __getitem__(self, key):
return self.config.sections[self.name][key]
def __iter__(self):
section = self.config.sections.get(self.name, [])
def lineof(key):
return self.config.lineof(self.name, key)
for name in sorted(section, key=lineof):
yield name
def items(self):
for name in self:
yield name, self[name]
class IniConfig(object):
def __init__(self, path, data=None):
self.path = str(path) # convenience
if data is None:
f = open(self.path)
try:
tokens = self._parse(iter(f))
finally:
f.close()
else:
tokens = self._parse(data.splitlines(True))
self._sources = {}
self.sections = {}
for lineno, section, name, value in tokens:
if section is None:
self._raise(lineno, 'no section header defined')
self._sources[section, name] = lineno
if name is None:
if section in self.sections:
self._raise(lineno, 'duplicate section %r' % (section, ))
self.sections[section] = {}
else:
if name in self.sections[section]:
self._raise(lineno, 'duplicate name %r' % (name, ))
self.sections[section][name] = value
def _raise(self, lineno, msg):
raise ParseError(self.path, lineno, msg)
def _parse(self, line_iter):
result = []
section = None
for lineno, line in enumerate(line_iter):
name, data = self._parseline(line, lineno)
# new value
if name is not None and data is not None:
result.append((lineno, section, name, data))
# new section
elif name is not None and data is None:
if not name:
self._raise(lineno, 'empty section name')
section = name
result.append((lineno, section, None, None))
# continuation
elif name is None and data is not None:
if not result:
self._raise(lineno, 'unexpected value continuation')
last = result.pop()
last_name, last_data = last[-2:]
if last_name is None:
self._raise(lineno, 'unexpected value continuation')
if last_data:
data = '%s\n%s' % (last_data, data)
result.append(last[:-1] + (data,))
return result
def _parseline(self, line, lineno):
# blank lines
if iscommentline(line):
line = ""
else:
line = line.rstrip()
if not line:
return None, None
# section
if line[0] == '[':
realline = line
for c in COMMENTCHARS:
line = line.split(c)[0].rstrip()
if line[-1] == "]":
return line[1:-1], None
return None, realline.strip()
# value
elif not line[0].isspace():
try:
name, value = line.split('=', 1)
if ":" in name:
raise ValueError()
except ValueError:
try:
name, value = line.split(":", 1)
except ValueError:
self._raise(lineno, 'unexpected line: %r' % line)
return name.strip(), value.strip()
# continuation
else:
return None, line.strip()
def lineof(self, section, name=None):
lineno = self._sources.get((section, name))
if lineno is not None:
return lineno + 1
def get(self, section, name, default=None, convert=str):
try:
return convert(self.sections[section][name])
except KeyError:
return default
def __getitem__(self, name):
if name not in self.sections:
raise KeyError(name)
return SectionWrapper(self, name)
def __iter__(self):
for name in sorted(self.sections, key=self.lineof):
yield SectionWrapper(self, name)
def __contains__(self, arg):
return arg in self.sections
def iscommentline(line):
c = line.lstrip()[:1]
return c in COMMENTCHARS
| 2,595 |
1,523 | <gh_stars>1000+
// 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.
#include "exec/cardinality-check-node.h"
#include "exec/exec-node-util.h"
#include "gen-cpp/PlanNodes_types.h"
#include "runtime/row-batch.h"
#include "runtime/runtime-state.h"
#include "util/runtime-profile-counters.h"
#include "common/names.h"
namespace impala {
CardinalityCheckNode::CardinalityCheckNode(
ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs)
: ExecNode(pool, tnode, descs),
display_statement_(tnode.cardinality_check_node.display_statement) {
}
Status CardinalityCheckNode::Prepare(RuntimeState* state) {
DCHECK(conjuncts_.empty());
DCHECK_EQ(limit_, 1);
SCOPED_TIMER(runtime_profile_->total_time_counter());
RETURN_IF_ERROR(ExecNode::Prepare(state));
return Status::OK();
}
Status CardinalityCheckNode::Open(RuntimeState* state) {
SCOPED_TIMER(runtime_profile_->total_time_counter());
ScopedOpenEventAdder ea(this);
RETURN_IF_ERROR(ExecNode::Open(state));
RETURN_IF_ERROR(child(0)->Open(state));
row_batch_.reset(new RowBatch(row_desc(), 1, mem_tracker()));
// Read rows from the child, raise error if there are more rows than one
RowBatch child_batch(child(0)->row_desc(), state->batch_size(), mem_tracker());
bool child_eos = false;
int rows_collected = 0;
do {
RETURN_IF_CANCELLED(state);
RETURN_IF_ERROR(QueryMaintenance(state));
RETURN_IF_ERROR(child(0)->GetNext(state, &child_batch, &child_eos));
rows_collected += child_batch.num_rows();
if (rows_collected > 1) {
return Status(Substitute("Subquery must not return more than one row: $0",
display_statement_));
}
if (child_batch.num_rows() != 0) child_batch.DeepCopyTo(row_batch_.get());
child_batch.Reset();
} while (!child_eos);
DCHECK(rows_collected == 0 || rows_collected == 1);
// If we are inside a subplan we can expect a call to Open()/GetNext()
// on the child again.
if (!IsInSubplan()) child(0)->Close(state);
return Status::OK();
}
Status CardinalityCheckNode::GetNext(
RuntimeState* state, RowBatch* output_row_batch, bool* eos) {
SCOPED_TIMER(runtime_profile_->total_time_counter());
ScopedGetNextEventAdder ea(this, eos);
RETURN_IF_ERROR(ExecDebugAction(TExecNodePhase::GETNEXT, state));
RETURN_IF_CANCELLED(state);
RETURN_IF_ERROR(QueryMaintenance(state));
DCHECK_LE(row_batch_->num_rows(), 1);
if (row_batch_->num_rows() == 1) {
TupleRow* src_row = row_batch_->GetRow(0);
TupleRow* dst_row = output_row_batch->GetRow(output_row_batch->AddRow());
output_row_batch->CopyRow(src_row, dst_row);
output_row_batch->CommitLastRow();
row_batch_->TransferResourceOwnership(output_row_batch);
num_rows_returned_ = 1;
COUNTER_SET(rows_returned_counter_, num_rows_returned_);
}
*eos = true;
row_batch_->Reset();
return Status::OK();
}
Status CardinalityCheckNode::Reset(RuntimeState* state, RowBatch* row_batch) {
row_batch_->Reset();
return ExecNode::Reset(state, row_batch);
}
void CardinalityCheckNode::Close(RuntimeState* state) {
if (is_closed()) return;
// Need to call destructor to release resources before calling ExecNode::Close().
row_batch_.reset();
ExecNode::Close(state);
}
}
| 1,385 |
369 | /**
* \file
*
* Copyright (c) 2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* 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. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
/*
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#ifndef _SAME70_USART2_INSTANCE_
#define _SAME70_USART2_INSTANCE_
/* ========== Register definition for USART2 peripheral ========== */
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_USART2_CR (0x4002C000U) /**< \brief (USART2) Control Register */
#define REG_USART2_MR (0x4002C004U) /**< \brief (USART2) Mode Register */
#define REG_USART2_IER (0x4002C008U) /**< \brief (USART2) Interrupt Enable Register */
#define REG_USART2_IDR (0x4002C00CU) /**< \brief (USART2) Interrupt Disable Register */
#define REG_USART2_IMR (0x4002C010U) /**< \brief (USART2) Interrupt Mask Register */
#define REG_USART2_CSR (0x4002C014U) /**< \brief (USART2) Channel Status Register */
#define REG_USART2_RHR (0x4002C018U) /**< \brief (USART2) Receive Holding Register */
#define REG_USART2_THR (0x4002C01CU) /**< \brief (USART2) Transmit Holding Register */
#define REG_USART2_BRGR (0x4002C020U) /**< \brief (USART2) Baud Rate Generator Register */
#define REG_USART2_RTOR (0x4002C024U) /**< \brief (USART2) Receiver Time-out Register */
#define REG_USART2_TTGR (0x4002C028U) /**< \brief (USART2) Transmitter Timeguard Register */
#define REG_USART2_MAN (0x4002C050U) /**< \brief (USART2) Manchester Configuration Register */
#define REG_USART2_LINMR (0x4002C054U) /**< \brief (USART2) LIN Mode Register */
#define REG_USART2_LINIR (0x4002C058U) /**< \brief (USART2) LIN Identifier Register */
#define REG_USART2_LINBRR (0x4002C05CU) /**< \brief (USART2) LIN Baud Rate Register */
#define REG_USART2_LONMR (0x4002C060U) /**< \brief (USART2) LON Mode Register */
#define REG_USART2_LONPR (0x4002C064U) /**< \brief (USART2) LON Preamble Register */
#define REG_USART2_LONDL (0x4002C068U) /**< \brief (USART2) LON Data Length Register */
#define REG_USART2_LONL2HDR (0x4002C06CU) /**< \brief (USART2) LON L2HDR Register */
#define REG_USART2_LONBL (0x4002C070U) /**< \brief (USART2) LON Backlog Register */
#define REG_USART2_LONB1TX (0x4002C074U) /**< \brief (USART2) LON Beta1 Tx Register */
#define REG_USART2_LONB1RX (0x4002C078U) /**< \brief (USART2) LON Beta1 Rx Register */
#define REG_USART2_LONPRIO (0x4002C07CU) /**< \brief (USART2) LON Priority Register */
#define REG_USART2_IDTTX (0x4002C080U) /**< \brief (USART2) LON IDT Tx Register */
#define REG_USART2_IDTRX (0x4002C084U) /**< \brief (USART2) LON IDT Rx Register */
#define REG_USART2_ICDIFF (0x4002C088U) /**< \brief (USART2) IC DIFF Register */
#define REG_USART2_WPMR (0x4002C0E4U) /**< \brief (USART2) Write Protection Mode Register */
#define REG_USART2_WPSR (0x4002C0E8U) /**< \brief (USART2) Write Protection Status Register */
#else
#define REG_USART2_CR (*(__O uint32_t*)0x4002C000U) /**< \brief (USART2) Control Register */
#define REG_USART2_MR (*(__IO uint32_t*)0x4002C004U) /**< \brief (USART2) Mode Register */
#define REG_USART2_IER (*(__O uint32_t*)0x4002C008U) /**< \brief (USART2) Interrupt Enable Register */
#define REG_USART2_IDR (*(__O uint32_t*)0x4002C00CU) /**< \brief (USART2) Interrupt Disable Register */
#define REG_USART2_IMR (*(__I uint32_t*)0x4002C010U) /**< \brief (USART2) Interrupt Mask Register */
#define REG_USART2_CSR (*(__I uint32_t*)0x4002C014U) /**< \brief (USART2) Channel Status Register */
#define REG_USART2_RHR (*(__I uint32_t*)0x4002C018U) /**< \brief (USART2) Receive Holding Register */
#define REG_USART2_THR (*(__O uint32_t*)0x4002C01CU) /**< \brief (USART2) Transmit Holding Register */
#define REG_USART2_BRGR (*(__IO uint32_t*)0x4002C020U) /**< \brief (USART2) Baud Rate Generator Register */
#define REG_USART2_RTOR (*(__IO uint32_t*)0x4002C024U) /**< \brief (USART2) Receiver Time-out Register */
#define REG_USART2_TTGR (*(__IO uint32_t*)0x4002C028U) /**< \brief (USART2) Transmitter Timeguard Register */
#define REG_USART2_MAN (*(__IO uint32_t*)0x4002C050U) /**< \brief (USART2) Manchester Configuration Register */
#define REG_USART2_LINMR (*(__IO uint32_t*)0x4002C054U) /**< \brief (USART2) LIN Mode Register */
#define REG_USART2_LINIR (*(__IO uint32_t*)0x4002C058U) /**< \brief (USART2) LIN Identifier Register */
#define REG_USART2_LINBRR (*(__I uint32_t*)0x4002C05CU) /**< \brief (USART2) LIN Baud Rate Register */
#define REG_USART2_LONMR (*(__IO uint32_t*)0x4002C060U) /**< \brief (USART2) LON Mode Register */
#define REG_USART2_LONPR (*(__IO uint32_t*)0x4002C064U) /**< \brief (USART2) LON Preamble Register */
#define REG_USART2_LONDL (*(__IO uint32_t*)0x4002C068U) /**< \brief (USART2) LON Data Length Register */
#define REG_USART2_LONL2HDR (*(__IO uint32_t*)0x4002C06CU) /**< \brief (USART2) LON L2HDR Register */
#define REG_USART2_LONBL (*(__I uint32_t*)0x4002C070U) /**< \brief (USART2) LON Backlog Register */
#define REG_USART2_LONB1TX (*(__IO uint32_t*)0x4002C074U) /**< \brief (USART2) LON Beta1 Tx Register */
#define REG_USART2_LONB1RX (*(__IO uint32_t*)0x4002C078U) /**< \brief (USART2) LON Beta1 Rx Register */
#define REG_USART2_LONPRIO (*(__IO uint32_t*)0x4002C07CU) /**< \brief (USART2) LON Priority Register */
#define REG_USART2_IDTTX (*(__IO uint32_t*)0x4002C080U) /**< \brief (USART2) LON IDT Tx Register */
#define REG_USART2_IDTRX (*(__IO uint32_t*)0x4002C084U) /**< \brief (USART2) LON IDT Rx Register */
#define REG_USART2_ICDIFF (*(__IO uint32_t*)0x4002C088U) /**< \brief (USART2) IC DIFF Register */
#define REG_USART2_WPMR (*(__IO uint32_t*)0x4002C0E4U) /**< \brief (USART2) Write Protection Mode Register */
#define REG_USART2_WPSR (*(__I uint32_t*)0x4002C0E8U) /**< \brief (USART2) Write Protection Status Register */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#endif /* _SAME70_USART2_INSTANCE_ */
| 3,659 |
848 |
#
# Copyright 2019 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import torch
from torch.nn.utils.rnn import PackedSequence, pad_packed_sequence, pack_padded_sequence
from .rnn_layer import QuantLstmLayer, QuantGruLayer
class StackedLstm(torch.nn.Module):
def __init__(self, input_sizes, hidden_sizes, memory_sizes, layers, stack_mode=None, batch_first=None):
super(StackedLstm, self).__init__()
self.stack_mode = stack_mode
self.num_layers = len(layers)
self.lstm_layers = []
self.batch_first = batch_first
for layer_index in range(len(layers)):
lstm_cell_pair = {}
for direction, layer in layers[layer_index].items():
layer = Lstm(input_sizes[layer_index], hidden_sizes[layer_index], memory_sizes[layer_index], layer, direction,
self.batch_first)
self.add_module(f"{direction}_layer_{layer_index}", layer)
lstm_cell_pair[direction] = layer
self.lstm_layers.append(lstm_cell_pair)
def forward(self, inputs, initial_state=None, **kwargs):
is_packed = isinstance(inputs, PackedSequence)
if self.stack_mode in ['bidirectional']:
if not initial_state:
hidden_states = [None] * len(self.lstm_layers) * len(
self.lstm_layers[0])
elif initial_state[0].size()[0] != len(self.lstm_layers) * len(
self.lstm_layers[0]):
raise ValueError(f"initial states does not match the number of layers.")
else:
hidden_states = list(
zip(initial_state[0].split(1, 0), initial_state[1].split(1, 0)))
else:
if not initial_state:
hidden_states = [None] * len(self.lstm_layers)
elif initial_state[0].size()[0] != len(self.lstm_layers):
raise ValueError(f"initial states does not match the number of layers.")
else:
hidden_states = list(
zip(initial_state[0].split(1, 0), initial_state[1].split(1, 0)))
# print(f"nndct_inputs:{inputs}")
output_sequence = inputs
if self.stack_mode in ['bidirectional']:
final_h = []
final_c = []
for i in range(len(self.lstm_layers)):
forward_layer = getattr(self, "forward_layer_{}".format(i))
backward_layer = getattr(self, "backward_layer_{}".format(i))
forward_output, final_forward_state = forward_layer(
output_sequence, hidden_states[i * 2])
if self.batch_first is not True:
output_sequence.transpose_(0, 1)
backward_output, final_backward_state = backward_layer(
output_sequence, hidden_states[i * 2 + 1])
if is_packed:
forward_output, lengths = pad_packed_sequence(
forward_output, batch_first=self.batch_first)
backward_output, _ = pad_packed_sequence(
backward_output, batch_first=self.batch_first)
# output_sequence = output_sequence.flip(1)
# backward_output = backward_output.flip(1)
output_sequence = torch.cat([forward_output, backward_output], -1)
if is_packed:
output_sequence = pack_padded_sequence(
output_sequence, lengths, batch_first=self.batch_first)
final_h.extend([final_forward_state[0], final_backward_state[0]])
final_c.extend([final_forward_state[1], final_backward_state[1]])
final_hidden_state = torch.cat(final_h, dim=0)
final_cell_state = torch.cat(final_c, dim=0)
else:
final_states = []
for i, state in enumerate(hidden_states):
if self.stack_mode == 'alternating':
layer = getattr(self,
f"forward_layer_{i}") if i % 2 == 0 else getattr(
self, f"backward_layer_{i}")
else:
layer = getattr(self, f"forward_layer_{i}")
output_sequence, final_state = layer(output_sequence, state)
# print(f"nndct_layer{i} output:{output_sequence}")
final_states.append(final_state)
final_hidden_state, final_cell_state = tuple(
torch.cat(state_list, 0) for state_list in zip(*final_states))
# print(f"nndct_final_output:{output_sequence}")
return output_sequence, (final_hidden_state, final_cell_state)
class Lstm(torch.nn.Module):
def __init__(self, input_size, hidden_size, memory_size, cell_module, direction, batch_first):
super(Lstm, self).__init__()
# self.cell_module = cell_module
# self.hidden_size = hidden_size
self.batch_first = batch_first
go_forward = True if direction == "forward" else False
self.layer = QuantLstmLayer(input_size,hidden_size, memory_size, cell_module, go_forward)
def _forward_packed(self, inputs, initial_state=None):
sequence_tensor, batch_lengths = pad_packed_sequence(
inputs, batch_first=self.batch_first)
if self.batch_first is not True:
sequence_tensor.transpose_(0, 1)
output, final_state = self.layer(sequence_tensor, initial_state, batch_lengths)
if self.batch_first is not True:
output.transpose_(0, 1)
output = pack_padded_sequence(
output, batch_lengths, batch_first=self.batch_first)
return output, final_state
def forward(self, inputs, initial_state=None):
if isinstance(inputs, PackedSequence):
return self._forward_packed(inputs, initial_state)
if self.batch_first is not True:
inputs.transpose_(0, 1)
output, final_state = self.layer(inputs, initial_state)
if self.batch_first is not True:
output.transpose_(0, 1)
return output, final_state
class StackedGru(torch.nn.Module):
def __init__(self,input_sizes, hidden_sizes, layers, stack_mode=None, batch_first=None):
super(StackedGru, self).__init__()
self.stack_mode = stack_mode
self.num_layers = len(layers)
self.lstm_layers = []
self.batch_first = batch_first
for layer_index in range(len(layers)):
lstm_cell_pair = {}
for direction, layer in layers[layer_index].items():
layer = Gru(input_sizes[layer_index], hidden_sizes[layer_index], layer, direction, self.batch_first)
self.add_module(f"{direction}_layer_{layer_index}", layer)
lstm_cell_pair[direction] = layer
self.lstm_layers.append(lstm_cell_pair)
def forward(self, inputs, initial_state=None, **kwargs):
is_packed = isinstance(inputs, PackedSequence)
if self.stack_mode in ['bidirectional']:
if initial_state is None:
hidden_states = [None] * len(self.lstm_layers) * len(self.lstm_layers[0])
elif initial_state.size()[0] != len(self.lstm_layers) * len(self.lstm_layers[0]):
raise ValueError(f"initial states does not match the number of layers.")
else:
hidden_states = list(zip(initial_state.split(1, 0), initial_state.split(1, 0)))
else:
if initial_state is None:
hidden_states = [None] * len(self.lstm_layers)
elif initial_state.size()[0] != len(self.lstm_layers):
raise ValueError(f"initial states does not match the number of layers.")
else:
hidden_states = list(zip(initial_state.split(1, 0), initial_state.split(1, 0)))
# print(f"nndct_inputs:{inputs}")
output_sequence = inputs
if self.stack_mode in ['bidirectional']:
final_h = []
for i in range(len(self.lstm_layers)):
forward_layer = getattr(self, "forward_layer_{}".format(i))
backward_layer = getattr(self, "backward_layer_{}".format(i))
forward_output, final_forward_state = forward_layer(output_sequence, hidden_states[2 * i])
if self.batch_first is not True:
output_sequence.transpose_(0,1)
backward_output, final_backward_state = backward_layer(output_sequence, hidden_states[2 * i + 1])
if is_packed:
forward_output, lengths = pad_packed_sequence(forward_output, batch_first=self.batch_first)
backward_output, _ = pad_packed_sequence(backward_output, batch_first=self.batch_first)
output_sequence = torch.cat([forward_output, backward_output], -1)
if is_packed:
output_sequence = pack_padded_sequence(output_sequence, lengths, batch_first=self.batch_first)
final_h.extend([final_forward_state[0], final_backward_state[0]])
final_hidden_state = torch.cat(final_h, dim=0)
else:
final_states = []
output_reversed = False
for i, state in enumerate(hidden_states):
if self.stack_mode == 'alternating':
layer = getattr(self, f"forward_layer_{i}") if i % 2 == 0 else getattr(self, f"backward_layer_{i}")
else:
layer = getattr(self, f"forward_layer_{i}")
output_sequence, final_state = layer(output_sequence, state)
# print(f"nndct_layer{i} output:{output_sequence}")
final_states.append(final_state)
final_hidden_state = tuple(
torch.cat(state_list, 0) for state_list in zip(*final_states)
)
# print(f"nndct_final_output:{output_sequence}")
return output_sequence, (final_hidden_state)
class Gru(torch.nn.Module):
def __init__(self, input_size, hidden_size, cell_module, direction, batch_first):
super(Gru, self).__init__()
# self.cell_module = cell_module
# self.hidden_size = hidden_size
self.batch_first = batch_first
go_forward = True if direction == "forward" else False
self.layer = QuantGruLayer(input_size,hidden_size, cell_module, go_forward)
def _forward_packed(self, inputs, initial_state=None):
sequence_tensor, batch_lengths = pad_packed_sequence(inputs, batch_first=self.batch_first)
if self.batch_first is not True:
sequence_tensor.transpose_(0, 1)
output, final_state = self.layer(sequence_tensor, initial_state, batch_lengths)
if self.batch_first is not True:
output.transpose_(0, 1)
output = pack_padded_sequence(
output, batch_lengths, batch_first=self.batch_first)
return output, final_state
def forward(self, inputs, initial_state=None):
if isinstance(inputs, PackedSequence):
return self._forward_packed(inputs, initial_state)
if self.batch_first is not True:
inputs.transpose_(0, 1)
output, final_state = self.layer(inputs, initial_state)
if self.batch_first is not True:
output.transpose_(0, 1)
return output, final_state
| 4,485 |
5,169 | {
"name": "FMBridgeJSOC",
"version": "0.0.1",
"summary": "FMBridgeJSOC is a Lib with support the js in web & objc in local communication in iOS dev.",
"description": "\"FMBridgeJSOC is a Lib with support the js in web & objc in local communication in iOS dev.\"",
"homepage": "https://github.com/acekiller",
"license": "MIT",
"authors": {
"Acekiller": "<EMAIL>"
},
"platforms": {
"ios": "7.0"
},
"source": {
"git": "https://github.com/acekiller/FMBridgeJSOC.git",
"tag": "0.0.1"
},
"source_files": [
"Classes",
"FMBridgeJSOC/JSBridge/*.{h,m}"
],
"exclude_files": "Classes/Exclude",
"requires_arc": true
}
| 264 |
634 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.openapi.options;
import com.intellij.util.text.UniqueNameGenerator;
import consulo.logging.Logger;
import consulo.util.pointers.Named;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
public abstract class AbstractSchemesManager<T extends Named, E extends ExternalizableScheme> extends SchemesManager<T, E> {
private static final Logger LOG = Logger.getInstance(AbstractSchemesManager.class);
protected final List<T> mySchemes = new ArrayList<T>();
private volatile T myCurrentScheme;
private String myCurrentSchemeName;
@Override
public void addNewScheme(@Nonnull T scheme, boolean replaceExisting) {
int toReplace = -1;
for (int i = 0; i < mySchemes.size(); i++) {
T existingScheme = mySchemes.get(i);
if (existingScheme.getName().equals(scheme.getName())) {
toReplace = i;
break;
}
}
if (toReplace == -1) {
mySchemes.add(scheme);
}
else if (replaceExisting || !(scheme instanceof ExternalizableScheme)) {
mySchemes.set(toReplace, scheme);
}
else {
//noinspection unchecked
renameScheme((ExternalizableScheme)scheme, UniqueNameGenerator.generateUniqueName(scheme.getName(), collectExistingNames(mySchemes)));
mySchemes.add(scheme);
}
schemeAdded(scheme);
checkCurrentScheme(scheme);
}
protected void checkCurrentScheme(@Nonnull Named scheme) {
if (myCurrentScheme == null && Objects.equals(scheme.getName(), myCurrentSchemeName)) {
//noinspection unchecked
myCurrentScheme = (T)scheme;
}
}
@Nonnull
private Collection<String> collectExistingNames(@Nonnull Collection<T> schemes) {
Set<String> result = new HashSet<String>(schemes.size());
for (T scheme : schemes) {
result.add(scheme.getName());
}
return result;
}
@Override
public void clearAllSchemes() {
for (T myScheme : mySchemes) {
schemeDeleted(myScheme);
}
mySchemes.clear();
}
@Override
@Nonnull
public List<T> getAllSchemes() {
return Collections.unmodifiableList(mySchemes);
}
@Override
@Nullable
public T findSchemeByName(@Nonnull String schemeName) {
for (T scheme : mySchemes) {
if (scheme.getName().equals(schemeName)) {
return scheme;
}
}
return null;
}
@Override
public void setCurrentSchemeName(@Nullable String schemeName) {
myCurrentSchemeName = schemeName;
myCurrentScheme = schemeName == null ? null : findSchemeByName(schemeName);
}
@Override
@Nullable
public T getCurrentScheme() {
T currentScheme = myCurrentScheme;
return currentScheme == null ? null : findSchemeByName(currentScheme.getName());
}
@Override
public void removeScheme(@Nonnull T scheme) {
for (int i = 0, n = mySchemes.size(); i < n; i++) {
T s = mySchemes.get(i);
if (scheme.getName().equals(s.getName())) {
schemeDeleted(s);
mySchemes.remove(i);
break;
}
}
}
protected void schemeDeleted(@Nonnull Named scheme) {
if (myCurrentScheme == scheme) {
myCurrentScheme = null;
}
}
@Override
@Nonnull
public Collection<String> getAllSchemeNames() {
List<String> names = new ArrayList<String>(mySchemes.size());
for (T scheme : mySchemes) {
names.add(scheme.getName());
}
return names;
}
protected abstract void schemeAdded(@Nonnull T scheme);
protected static void renameScheme(@Nonnull ExternalizableScheme scheme, @Nonnull String newName) {
if (!newName.equals(scheme.getName())) {
scheme.setName(newName);
LOG.assertTrue(newName.equals(scheme.getName()));
}
}
}
| 1,551 |
434 | {
"category" : "Seaside-GemStone-Continuation",
"classinstvars" : [
],
"classvars" : [
],
"commentStamp" : "JohanBrichau 06/27/2020 04:14",
"instvars" : [
"environment",
"value" ],
"name" : "WAGemStoneProcessEnvironmentWrapper",
"pools" : [
],
"super" : "Object",
"type" : "normal" }
| 139 |
1,217 | #include "OpenGLApplication.hpp"
#include <X11/Xlib-xcb.h>
#include <climits>
#include <cstdio>
#include <cstring>
#include "glad/glad_glx.h"
using namespace My;
using namespace std;
// Helper to check for extension string presence. Adapted from:
// http://www.opengl.org/resources/features/OGLextensions/
static bool isExtensionSupported(const char *extList, const char *extension) {
const char *start;
const char *where, *terminator;
/* Extension names should not have spaces. */
where = strchr(extension, ' ');
if (where || *extension == '\0') return false;
/* It takes a bit of care to be fool-proof about parsing the
OpenGL extensions string. Don't be fooled by sub-strings,
etc. */
for (start = extList;;) {
where = strstr(start, extension);
if (!where) break;
terminator = where + strlen(extension);
if (where == start || *(where - 1) == ' ')
if (*terminator == ' ' || *terminator == '\0') return true;
start = terminator;
}
return false;
}
static bool ctxErrorOccurred = false;
static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) {
ctxErrorOccurred = true;
return 0;
}
int OpenGLApplication::Initialize() {
BaseApplication::Initialize();
int result;
int default_screen;
GLXFBConfig *fb_configs;
int num_fb_configs = 0;
GLXWindow glxwindow;
// Get a matching FB config
static int visual_attribs[] = {
GLX_X_RENDERABLE, True, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
GLX_RED_SIZE, static_cast<int>(INT_MAX & m_Config.redBits),
GLX_GREEN_SIZE, static_cast<int>(INT_MAX & m_Config.greenBits),
GLX_BLUE_SIZE, static_cast<int>(INT_MAX & m_Config.blueBits),
GLX_ALPHA_SIZE, static_cast<int>(INT_MAX & m_Config.alphaBits),
GLX_DEPTH_SIZE, static_cast<int>(INT_MAX & m_Config.depthBits),
GLX_STENCIL_SIZE, static_cast<int>(INT_MAX & m_Config.stencilBits),
GLX_DOUBLEBUFFER, True,
// GLX_SAMPLE_BUFFERS , 1,
// GLX_SAMPLES , 4,
None};
/* Open Xlib Display */
m_pDisplay = XOpenDisplay(NULL);
if (!m_pDisplay) {
fprintf(stderr, "Can't open display\n");
return -1;
}
default_screen = DefaultScreen(m_pDisplay);
gladLoadGLX(m_pDisplay, default_screen);
/* Query framebuffer configurations */
fb_configs = glXChooseFBConfig(m_pDisplay, default_screen, visual_attribs,
&num_fb_configs);
if (!fb_configs || num_fb_configs == 0) {
fprintf(stderr, "glXGetFBConfigs failed\n");
return -1;
}
/* Pick the FB config/visual with the most samples per pixel */
{
int best_fbc = -1, worst_fbc = -1, best_num_samp = -1,
worst_num_samp = 999;
for (int i = 0; i < num_fb_configs; ++i) {
XVisualInfo *vi =
glXGetVisualFromFBConfig(m_pDisplay, fb_configs[i]);
if (vi) {
int samp_buf, samples;
glXGetFBConfigAttrib(m_pDisplay, fb_configs[i],
GLX_SAMPLE_BUFFERS, &samp_buf);
glXGetFBConfigAttrib(m_pDisplay, fb_configs[i], GLX_SAMPLES,
&samples);
printf(
" Matching fbconfig %d, visual ID 0x%lx: SAMPLE_BUFFERS = "
"%d,"
" SAMPLES = %d\n",
i, vi->visualid, samp_buf, samples);
if (best_fbc < 0 || (samp_buf && samples > best_num_samp))
best_fbc = i, best_num_samp = samples;
if (worst_fbc < 0 || !samp_buf || samples < worst_num_samp)
worst_fbc = i, worst_num_samp = samples;
}
XFree(vi);
}
fb_config = fb_configs[best_fbc];
}
/* Get a visual */
vi = glXGetVisualFromFBConfig(m_pDisplay, fb_config);
printf("Chosen visual ID = 0x%lx\n", vi->visualid);
/* establish connection to X server */
m_pConn = XGetXCBConnection(m_pDisplay);
if (!m_pConn) {
XCloseDisplay(m_pDisplay);
fprintf(stderr, "Can't get xcb connection from display\n");
return -1;
}
/* Acquire event queue ownership */
XSetEventQueueOwner(m_pDisplay, XCBOwnsEventQueue);
/* Find XCB screen */
xcb_screen_iterator_t screen_iter =
xcb_setup_roots_iterator(xcb_get_setup(m_pConn));
for (int screen_num = vi->screen; screen_iter.rem && screen_num > 0;
--screen_num, xcb_screen_next(&screen_iter))
;
m_pScreen = screen_iter.data;
m_nVi = vi->visualid;
return result;
}
void OpenGLApplication::CreateMainWindow() {
XcbApplication::CreateMainWindow();
const char *glxExts;
int default_screen = DefaultScreen(m_pDisplay);
/* Get the default screen's GLX extension list */
glxExts = glXQueryExtensionsString(m_pDisplay, default_screen);
/* Create OpenGL context */
ctxErrorOccurred = false;
int (*oldHandler)(Display *, XErrorEvent *) =
XSetErrorHandler(&ctxErrorHandler);
if (!isExtensionSupported(glxExts, "GLX_ARB_create_context") ||
!glXCreateContextAttribsARB) {
printf(
"glXCreateContextAttribsARB() not found"
" ... using old-style GLX context\n");
m_Context =
glXCreateNewContext(m_pDisplay, fb_config, GLX_RGBA_TYPE, 0, True);
if (!m_Context) {
fprintf(stderr, "glXCreateNewContext failed\n");
}
} else {
int context_attribs[] = {GLX_CONTEXT_MAJOR_VERSION_ARB,
4,
GLX_CONTEXT_MINOR_VERSION_ARB,
3,
#ifdef OPENGL_RHI_DEBUG
GLX_CONTEXT_FLAGS_ARB,
GLX_CONTEXT_DEBUG_BIT_ARB,
#endif
None};
printf("Creating context\n");
m_Context = glXCreateContextAttribsARB(m_pDisplay, fb_config, 0, True,
context_attribs);
XSync(m_pDisplay, False);
if (!ctxErrorOccurred && m_Context)
printf("Created GL 4.3 context\n");
else {
/* GLX_CONTEXT_MAJOR_VERSION_ARB = 1 */
context_attribs[1] = 1;
/* GLX_CONTEXT_MINOR_VERSION_ARB = 0 */
context_attribs[3] = 0;
ctxErrorOccurred = false;
printf(
"Failed to create GL 4.3 context"
" ... using old-style GLX context\n");
m_Context = glXCreateContextAttribsARB(m_pDisplay, fb_config, 0,
True, context_attribs);
}
}
XSync(m_pDisplay, False);
XSetErrorHandler(oldHandler);
if (ctxErrorOccurred || !m_Context) {
printf("Failed to create an OpenGL context\n");
}
/* Verifying that context is a direct context */
if (!glXIsDirect(m_pDisplay, m_Context)) {
printf("Indirect GLX rendering context obtained\n");
} else {
printf("Direct GLX rendering context obtained\n");
}
/* Create GLX Window */
GLXWindow glxwindow = glXCreateWindow(m_pDisplay, fb_config, m_Window, 0);
if (!glxwindow) {
xcb_destroy_window(m_pConn, m_Window);
glXDestroyContext(m_pDisplay, m_Context);
fprintf(stderr, "glxCreateWindow failed\n");
}
m_Drawable = glxwindow;
/* make OpenGL context current */
if (!glXMakeContextCurrent(m_pDisplay, m_Drawable, m_Drawable, m_Context)) {
xcb_destroy_window(m_pConn, m_Window);
glXDestroyContext(m_pDisplay, m_Context);
fprintf(stderr, "glXMakeContextCurrent failed\n");
}
XFree(vi);
}
void OpenGLApplication::Tick() {
XcbApplication::Tick();
glXSwapBuffers(m_pDisplay, m_Drawable);
}
| 3,882 |
392 | <filename>mcg/src/external/BSR/include/collections/abstract/multimap.hh
/*
* Abstract multimap.
*
* Multimaps associate each element of their domain with one or more elements
* of their range. Both the domain and range may contain multiple copies of
* the same element.
*
* Multimaps are not derived from the abstract collection class because
* elements must be added to a multimap as a pair (t -> u mapping). A
* collection view of the domain and range of a multimap is accessible via
* the domain() and range() methods.
*/
#ifndef COLLECTIONS__ABSTRACT__MULTIMAP_HH
#define COLLECTIONS__ABSTRACT__MULTIMAP_HH
#include "collections/abstract/collection.hh"
#include "collections/abstract/map.hh"
#include "collections/list.hh"
#include "lang/iterators/iterator.hh"
#include "lang/pointers/auto_ptr.hh"
namespace collections {
namespace abstract {
/*
* Imports.
*/
using lang::iterators::iterator;
using lang::pointers::auto_ptr;
/*
* Abstract base class for multimaps.
* T is the type of elements in the domain.
* U is the type of elements in the range.
*/
template <typename T, typename U>
class multimap {
public:
/*
* Destructor.
*/
virtual ~multimap() = 0;
/*
* Add the mapping t -> u.
* Return a reference to the multimap.
*/
virtual multimap<T,U>& add(T& /* t */, U& /* u */) = 0;
/*
* Add the mapping t -> u for corresponding elements of the collections.
* The collections must have the same size.
* Return a reference to the multimap.
*/
virtual multimap<T,U>& add(const collection<T>&, const collection<U>&) = 0;
/*
* Add all mappings in the given map/multimap to the current multimap.
* Return a reference to the multimap.
*/
virtual multimap<T,U>& add(const map<T,U>&) = 0;
virtual multimap<T,U>& add(const multimap<T,U>&) = 0;
/*
* Remove element(s) and their corresponding images from the multimap.
* Return a reference to the multimap.
*/
virtual multimap<T,U>& remove(const T&) = 0;
virtual multimap<T,U>& remove(const collection<T>&) = 0;
/*
* Remove all instances of the element(s) from the multimap.
* Return a reference to the multimap.
*/
virtual multimap<T,U>& remove_all(const T&) = 0;
virtual multimap<T,U>& remove_all(const collection<T>&) = 0;
/*
* Clear the multimap, resetting it to the empty multimap.
* Return a reference to the multimap.
*/
virtual multimap<T,U>& clear() = 0;
/*
* Search.
* Return an element in the domain matching the given element.
* Throw an exception (ex_not_found) when attempting to find an element not
* contained in the map.
*/
virtual bool contains(const T&) const = 0;
virtual T& find(const T&) const = 0;
/*
* Search.
* Return a list of all element(s) in the domain matching the given element.
*/
virtual collections::list<T> find_all(const T&) const = 0;
/*
* Search.
* Return an image of the given domain element under the multimap.
* Throw an exception (ex_not_found) when attempting to find the image of
* an element not contained in the multimap.
*/
virtual U& find_image(const T&) const = 0;
/*
* Search.
* Return a list of all element(s) in the range which are images of the
* given domain element.
*/
virtual collections::list<U> find_images(const T&) const = 0;
/*
* Size.
* Return the number of mappings.
*/
virtual unsigned long size() const = 0;
/*
* Return a list of elements in the domain of the multimap and a list of
* their corresponding images in the range. All mappings t -> u in the
* multimap appear as a pair of elements (t, u) at corresponding positions
* in the lists. Hence, both the domain and range list may have repeated
* elements.
*/
virtual collections::list<T> domain() const = 0;
virtual collections::list<U> range() const = 0;
/*
* Return lists of elements in the domain and range.
* This method allows one to atomically capture the contents of a multimap
* if there is a potential for the multimap to change between calls of the
* above domain() and range() methods.
*/
virtual void contents(
auto_ptr< collections::list<T> >&, /* domain */
auto_ptr< collections::list<U> >& /* range */
) const = 0;
/*
* Return iterator over elements in the domain.
*/
virtual auto_ptr< iterator<T> > iter_create() const = 0;
};
/*
* Pure virtual destructor.
*/
template <typename T, typename U>
multimap<T,U>::~multimap() { }
} /* namespace abstract */
} /* namespace collections */
#endif
| 1,592 |
430 | <reponame>chrismayemba/covid-19-open-data<gh_stars>100-1000
# Copyright 2020 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.
import re
from typing import Dict
from pandas import DataFrame, isna
from lib.cast import parse_google_sheets_date, safe_int_cast
from lib.data_source import DataSource
class Covid19LatinoAmericaDataSource(DataSource):
def parse_dataframes(
self, dataframes: Dict[str, DataFrame], aux: Dict[str, DataFrame], **parse_opts
) -> DataFrame:
# Read data from GitHub repo
data = {}
for name, df in dataframes.items():
df.rename(columns={"ISO 3166-2 Code": "key"}, inplace=True)
df.key = df.key.str.replace("-", "_")
data[name] = df.set_index("key")
value_columns = [f"total_{statistic}" for statistic in data.keys()]
# Transform the data from non-tabulated format to record format
records = []
for key in data["confirmed"].index.unique():
date_columns = list(data["confirmed"].columns)[4:]
for col in date_columns:
records.append(
{
**{"date": col, "key": key},
**{
f"total_{statistic}": safe_int_cast(df.loc[key, col])
for statistic, df in data.items()
},
}
)
# Zeroes can be considered NaN in this data
data = DataFrame.from_records(records).replace(0, None)
# Remove all data without a proper date
data = data.dropna(subset=["date"])
# Make sure date is in the appropriate format
date_expr = r"\d\d\d\d-\d\d-\d\d"
data["date"] = data["date"].apply(
lambda x: x if re.match(date_expr, x) else parse_google_sheets_date(x)
)
# Since it's cumsum data, we can forward fill relatively safely
data = data.sort_values(["key", "date"]).groupby("key").apply(lambda x: x.ffill())
# We already have AR, BR, CO, MX and PE data directly from the authoritative source
for country_code in ("AR", "BR", "CL", "CO", "MX", "PE"):
data = data[~data.key.str.startswith(f"{country_code}_")]
# Correct the French colonies since we are using something different to the ISO 3166-2 code
data.loc[data.key == "FR_GP", "key"] = "FR_GUA"
# VE_W are "external territories" of Venezuela, which can't be mapped to any particular
# geographical region and therefore we exclude them
data = data[data.key != "VE_W"]
# The data appears to be very unreliable prior to March 12
data.loc[data["date"] <= "2020-03-12", value_columns] = None
# In many cases, total counts go down dramatically; filter out all dates prior to that
# We lose a lot of data by setting such a low threshold, but this data source is unreliable
skip_threshold = 0
for key in data["key"].unique():
rm_date = "2020-01-01"
subset = data[data["key"] == key]
diffs = subset.set_index("date")[value_columns].diff()
for col in value_columns:
max_date = diffs.loc[diffs[col] < skip_threshold].index.max()
if not isna(max_date) and max_date > rm_date:
rm_date = max_date
data.loc[(data["key"] == key) & (data["date"] < rm_date), value_columns] = None
return data
| 1,681 |
698 | /*
* Copyright (C) Zhang,Yuexiang (xfeep)
*/
#include <ngx_config.h>
#include "ngx_http_clojure_jvm.h"
#if defined(_WIN32) || defined(WIN32)
#else
#include <dlfcn.h>
#endif
static JNIEnv *jvm_env = NULL;
static JavaVM *jvm = NULL;
int ngx_http_clojure_is_embeded_by_jse = 0;
int ngx_http_clojure_check_jvm() {
return jvm == NULL ? NGX_HTTP_CLOJURE_JVM_ERR : NGX_HTTP_CLOJURE_JVM_OK;
}
int ngx_http_clojure_get_env(JNIEnv **penv) {
*penv = jvm_env;
return ngx_http_clojure_check_jvm();
}
int ngx_http_clojure_get_jvm(JavaVM **pvm) {
*pvm = jvm;
return ngx_http_clojure_check_jvm();
}
int ngx_http_clojure_init_jvm(char *jvm_path, char * *opts, size_t len) {
void *libVM;
void *env;
JavaVMInitArgs vm_args;
JavaVMOption *options;
size_t i;
jni_createvm_pt jvm_creator;
if (jvm != NULL && jvm_env != NULL) {
return NGX_HTTP_CLOJURE_JVM_OK;
}
#if defined(_WIN32) || defined(WIN32)
if ((libVM = LoadLibrary(jvm_path)) == NULL) {
return NGX_HTTP_CLOJURE_JVM_ERR_LOAD_LIB;
}
jvm_creator = (jni_createvm_pt)GetProcAddress(libVM, "JNI_CreateJavaVM");
#else
/*append RTLD_GLOBAL flag for Alpine Linux on which OpenJDK 7 libjvm.so
*can not correctly handle cross symbol links from libjava.so, libverify.so*/
if ((libVM = dlopen(jvm_path, RTLD_LAZY | RTLD_GLOBAL)) == NULL) {
printf("can not open shared lib :%s,\n %s\n", jvm_path, dlerror());
return NGX_HTTP_CLOJURE_JVM_ERR_LOAD_LIB;
}
jvm_creator = dlsym(libVM, "JNI_CreateJavaVM");
if (jvm_creator == NULL) {
/*for macosx default jvm*/
jvm_creator = dlsym(libVM, "JNI_CreateJavaVM_Impl");
}
#endif
if (jvm_creator == NULL){
return NGX_HTTP_CLOJURE_JVM_ERR;
}
options = malloc(len * sizeof(JavaVMOption));
if (!options) {
return NGX_HTTP_CLOJURE_JVM_ERR_MALLOC;
}
for (i = 0; i < len; i++){
options[i].extraInfo = NULL;
options[i].optionString = opts[i];
}
vm_args.version = JNI_VERSION_1_6;
vm_args.ignoreUnrecognized = JNI_TRUE;
vm_args.options = options;
vm_args.nOptions = len;
if ((*jvm_creator)(&jvm, (void **)&env, (void *)&vm_args) < 0){
free(options);
return NGX_HTTP_CLOJURE_JVM_ERR;
}
free(options);
jvm_env = env;
return NGX_HTTP_CLOJURE_JVM_OK;
}
int ngx_http_clojure_init_by_jse_app(JNIEnv *env) {
ngx_http_clojure_is_embeded_by_jse = 1;
jvm_env = env;
return (*env)->GetJavaVM(env, &jvm);
}
int ngx_http_clojure_close_jvm() {
jclass systemClass = NULL;
jmethodID exitMethod = NULL;
if (jvm == NULL || jvm_env == NULL) {
return NGX_HTTP_CLOJURE_JVM_OK;
}
if (ngx_http_clojure_is_embeded_by_jse) {
jvm = NULL;
jvm_env = NULL;
ngx_http_clojure_is_embeded_by_jse = 0;
return NGX_HTTP_CLOJURE_JVM_OK;
}
systemClass = (*jvm_env)->FindClass(jvm_env, "java/lang/System");
exitMethod = (*jvm_env)->GetStaticMethodID(jvm_env, systemClass, "exit", "(I)V");
(*jvm_env)->CallStaticVoidMethod(jvm_env, systemClass, exitMethod, 0);
(*jvm)->DestroyJavaVM(jvm);
jvm_env = NULL;
jvm = NULL;
return NGX_HTTP_CLOJURE_JVM_OK;
}
| 1,400 |
305 | <filename>llvm-project/clang/test/OpenMP/target_map_codegen_31.cpp
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
///==========================================================================///
// RUN: %clang_cc1 -DUSE -DCK31A -verify -fopenmp -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefixes=CK31A,CK31A-64,CK31A-USE
// RUN: %clang_cc1 -DUSE -DCK31A -fopenmp -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -DUSE -fopenmp -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefixes=CK31A,CK31A-64,CK31A-USE
// RUN: %clang_cc1 -DUSE -DCK31A -verify -fopenmp -fopenmp-version=51 -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefixes=CK31A,CK31A-32,CK31A-USE
// RUN: %clang_cc1 -DUSE -DCK31A -fopenmp -fopenmp-version=51 -fopenmp-targets=i386-pc-linux-gnu -x c++ -std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -DUSE -fopenmp -fopenmp-version=51 -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefixes=CK31A,CK31A-32,CK31A-USE
// RUN: %clang_cc1 -DUSE -DCK31A -verify -fopenmp-simd -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY18 %s
// RUN: %clang_cc1 -DUSE -DCK31A -fopenmp-simd -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -DUSE -fopenmp-simd -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY18 %s
// RUN: %clang_cc1 -DUSE -DCK31A -verify -fopenmp-version=51 -fopenmp-simd -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY18 %s
// RUN: %clang_cc1 -DUSE -DCK31A -fopenmp-version=51 -fopenmp-simd -fopenmp-targets=i386-pc-linux-gnu -x c++ -std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -DUSE -fopenmp-simd -fopenmp-version=51 -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY18 %s
// RUN: %clang_cc1 -DCK31A -verify -fopenmp -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefixes=CK31A,CK31A-64,CK31A-NOUSE
// RUN: %clang_cc1 -DCK31A -fopenmp -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefixes=CK31A,CK31A-64,CK31A-NOUSE
// RUN: %clang_cc1 -DCK31A -verify -fopenmp -fopenmp-version=51 -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefixes=CK31A,CK31A-32,CK31A-NOUSE
// RUN: %clang_cc1 -DCK31A -fopenmp -fopenmp-version=51 -fopenmp-targets=i386-pc-linux-gnu -x c++ -std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=51 -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefixes=CK31A,CK31A-32,CK31A-NOUSE
// RUN: %clang_cc1 -DCK31A -verify -fopenmp-simd -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY18 %s
// RUN: %clang_cc1 -DCK31A -fopenmp-simd -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=51 -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY18 %s
// RUN: %clang_cc1 -DCK31A -verify -fopenmp-version=51 -fopenmp-simd -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY18 %s
// RUN: %clang_cc1 -DCK31A -fopenmp-version=51 -fopenmp-simd -fopenmp-targets=i386-pc-linux-gnu -x c++ -std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=51 -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY18 %s
// SIMD-ONLY18-NOT: {{__kmpc|__tgt}}
#ifdef CK31A
// CK31A: [[ST:%.+]] = type { i32, i32 }
struct ST {
int i;
int j;
};
// CK31A-LABEL: @.__omp_offloading_{{.*}}explicit_maps_single{{.*}}_l{{[0-9]+}}.region_id = weak constant i8 0
//
// PRESENT=0x1000 | TARGET_PARAM=0x20 = 0x1020
// CK31A-USE: [[MTYPE00:@.+]] = private {{.*}}constant [7 x i64] [i64 [[#0x1020]],
// CK31A-NOUSE: [[MTYPE00:@.+]] = private {{.*}}constant [7 x i64] [i64 [[#0x1000]],
//
// MEMBER_OF_1=0x1000000000000 | FROM=0x2 | TO=0x1 = 0x1000000000003
// MEMBER_OF_1=0x1000000000000 | PRESENT=0x1000 | FROM=0x2 | TO=0x1 = 0x1000000001003
// PRESENT=0x1000 | TARGET_PARAM=0x20 | FROM=0x2 | TO=0x1 = 0x1023
// CK31A-USE-SAME: {{^}} i64 [[#0x1000000000003]], i64 [[#0x1000000001003]], i64 [[#0x1023]],
// CK31A-NOUSE-SAME: {{^}} i64 [[#0x1000000000003]], i64 [[#0x1000000001003]], i64 [[#0x1003]],
//
// PRESENT=0x1000 | TARGET_PARAM=0x20 = 0x1020
// MEMBER_OF_5=0x5000000000000 | PRESENT=0x1000 | FROM=0x2 | TO=0x1 = 0x5000000001003
// MEMBER_OF_5=0x5000000000000 | FROM=0x2 | TO=0x1 = 0x5000000000003
// CK31A-USE-SAME: {{^}} i64 [[#0x1020]], i64 [[#0x5000000001003]], i64 [[#0x5000000000003]]]
// CK31A-NOUSE-SAME: {{^}} i64 [[#0x1000]], i64 [[#0x5000000001003]], i64 [[#0x5000000000003]]]
// CK31A-LABEL: @.__omp_offloading_{{.*}}explicit_maps_single{{.*}}_l{{[0-9]+}}.region_id = weak constant i8 0
// CK31A: [[SIZE01:@.+]] = private {{.*}}constant [1 x i[[Z:64|32]]] [i[[Z:64|32]] 4]
//
// PRESENT=0x1000 | CLOSE=0x400 | TARGET_PARAM=0x20 | ALWAYS=0x4 | FROM=0x2 | TO=0x1 = 0x1427
// CK31A-USE: [[MTYPE01:@.+]] = private {{.*}}constant [1 x i64] [i64 [[#0x1427]]]
// CK31A-NOUSE: [[MTYPE01:@.+]] = private {{.*}}constant [1 x i64] [i64 [[#0x1407]]]
// CK31A-LABEL: explicit_maps_single{{.*}}(
void explicit_maps_single (int ii){
// CK31A: alloca i32
// Map of a scalar.
// CK31A: [[A:%.+]] = alloca i32
int a = ii;
// CK31A: [[ST1:%.+]] = alloca [[ST]]
// CK31A: [[ST2:%.+]] = alloca [[ST]]
struct ST st1;
struct ST st2;
// Make sure the struct picks up present even if another element of the struct
// doesn't have present.
// Region 00
// CK31A: [[ST1_I:%.+]] = getelementptr inbounds [[ST]], [[ST]]* [[ST1]], i{{.+}} 0, i{{.+}} 0
// CK31A: [[ST1_J:%.+]] = getelementptr inbounds [[ST]], [[ST]]* [[ST1]], i{{.+}} 0, i{{.+}} 1
// CK31A: [[ST2_I:%.+]] = getelementptr inbounds [[ST]], [[ST]]* [[ST2]], i{{.+}} 0, i{{.+}} 0
// CK31A: [[ST2_J:%.+]] = getelementptr inbounds [[ST]], [[ST]]* [[ST2]], i{{.+}} 0, i{{.+}} 1
// CK31A-DAG: call i32 @__tgt_target_mapper(i64 {{[^,]+}}, i8* {{[^,]+}}, i32 7, i8** [[GEPBP:%[0-9]+]], i8** [[GEPP:%[0-9]+]], i64* [[GEPS:%.+]], i64* getelementptr {{.+}}[7 x i{{.+}}]* [[MTYPE00]]{{.+}})
// CK31A-DAG: [[GEPS]] = getelementptr inbounds [7 x i64], [7 x i64]* [[S:%.+]], i{{.+}} 0, i{{.+}} 0
// CK31A-DAG: [[GEPBP]] = getelementptr inbounds {{.+}}[[BP:%[^,]+]]
// CK31A-DAG: [[GEPP]] = getelementptr inbounds {{.+}}[[P:%[^,]+]]
// st1
// CK31A-DAG: [[BP0:%.+]] = getelementptr inbounds {{.+}}[[BP]], i{{.+}} 0, i{{.+}} 0
// CK31A-DAG: [[P0:%.+]] = getelementptr inbounds {{.+}}[[P]], i{{.+}} 0, i{{.+}} 0
// CK31A-DAG: [[S0:%.+]] = getelementptr inbounds {{.+}}[[S]], i{{.+}} 0, i{{.+}} 0
// CK31A-DAG: [[CBP0:%.+]] = bitcast i8** [[BP0]] to [[ST]]**
// CK31A-DAG: [[CP0:%.+]] = bitcast i8** [[P0]] to i32**
// CK31A-DAG: store [[ST]]* [[ST1]], [[ST]]** [[CBP0]]
// CK31A-DAG: store i32* [[ST1_I]], i32** [[CP0]]
// CK31A-DAG: store i64 %{{.+}}, i64* [[S0]]
// st1.i
// CK31A-DAG: [[BP1:%.+]] = getelementptr inbounds {{.+}}[[BP]], i{{.+}} 0, i{{.+}} 1
// CK31A-DAG: [[P1:%.+]] = getelementptr inbounds {{.+}}[[P]], i{{.+}} 0, i{{.+}} 1
// CK31A-DAG: [[S1:%.+]] = getelementptr inbounds {{.+}}[[S]], i{{.+}} 0, i{{.+}} 1
// CK31A-DAG: [[CBP1:%.+]] = bitcast i8** [[BP1]] to [[ST]]**
// CK31A-DAG: [[CP1:%.+]] = bitcast i8** [[P1]] to i32**
// CK31A-DAG: store [[ST]]* [[ST1]], [[ST]]** [[CBP1]]
// CK31A-DAG: store i32* [[ST1_I]], i32** [[CP1]]
// CK31A-DAG: store i64 4, i64* [[S1]]
// st1.j
// CK31A-DAG: [[BP2:%.+]] = getelementptr inbounds {{.+}}[[BP]], i{{.+}} 0, i{{.+}} 2
// CK31A-DAG: [[P2:%.+]] = getelementptr inbounds {{.+}}[[P]], i{{.+}} 0, i{{.+}} 2
// CK31A-DAG: [[S2:%.+]] = getelementptr inbounds {{.+}}[[S]], i{{.+}} 0, i{{.+}} 2
// CK31A-DAG: [[CBP2:%.+]] = bitcast i8** [[BP2]] to [[ST]]**
// CK31A-DAG: [[CP2:%.+]] = bitcast i8** [[P2]] to i32**
// CK31A-DAG: store [[ST]]* [[ST1]], [[ST]]** [[CBP2]]
// CK31A-DAG: store i32* [[ST1_J]], i32** [[CP2]]
// CK31A-DAG: store i64 4, i64* [[S2]]
// a
// CK31A-DAG: [[BP3:%.+]] = getelementptr inbounds {{.+}}[[BP]], i{{.+}} 0, i{{.+}} 3
// CK31A-DAG: [[P3:%.+]] = getelementptr inbounds {{.+}}[[P]], i{{.+}} 0, i{{.+}} 3
// CK31A-DAG: [[S3:%.+]] = getelementptr inbounds {{.+}}[[S]], i{{.+}} 0, i{{.+}} 3
// CK31A-DAG: [[CBP3:%.+]] = bitcast i8** [[BP3]] to i32**
// CK31A-DAG: [[CP3:%.+]] = bitcast i8** [[P3]] to i32**
// CK31A-DAG: store i32* [[A]], i32** [[CBP3]]
// CK31A-DAG: store i32* [[A]], i32** [[CP3]]
// CK31A-DAG: store i64 4, i64* [[S3]]
// st2
// CK31A-DAG: [[BP4:%.+]] = getelementptr inbounds {{.+}}[[BP]], i{{.+}} 0, i{{.+}} 4
// CK31A-DAG: [[P4:%.+]] = getelementptr inbounds {{.+}}[[P]], i{{.+}} 0, i{{.+}} 4
// CK31A-DAG: [[S4:%.+]] = getelementptr inbounds {{.+}}[[S]], i{{.+}} 0, i{{.+}} 4
// CK31A-DAG: [[CBP4:%.+]] = bitcast i8** [[BP4]] to [[ST]]**
// CK31A-DAG: [[CP4:%.+]] = bitcast i8** [[P4]] to i32**
// CK31A-DAG: store [[ST]]* [[ST2]], [[ST]]** [[CBP4]]
// CK31A-DAG: store i32* [[ST2_I]], i32** [[CP4]]
// CK31A-DAG: store i64 %{{.+}}, i64* [[S4]]
// st2.i
// CK31A-DAG: [[BP5:%.+]] = getelementptr inbounds {{.+}}[[BP]], i{{.+}} 0, i{{.+}} 5
// CK31A-DAG: [[P5:%.+]] = getelementptr inbounds {{.+}}[[P]], i{{.+}} 0, i{{.+}} 5
// CK31A-DAG: [[S5:%.+]] = getelementptr inbounds {{.+}}[[S]], i{{.+}} 0, i{{.+}} 5
// CK31A-DAG: [[CBP5:%.+]] = bitcast i8** [[BP5]] to [[ST]]**
// CK31A-DAG: [[CP5:%.+]] = bitcast i8** [[P5]] to i32**
// CK31A-DAG: store [[ST]]* [[ST2]], [[ST]]** [[CBP5]]
// CK31A-DAG: store i32* [[ST2_I]], i32** [[CP5]]
// CK31A-DAG: store i64 4, i64* [[S5]]
// st2.j
// CK31A-DAG: [[BP6:%.+]] = getelementptr inbounds {{.+}}[[BP]], i{{.+}} 0, i{{.+}} 6
// CK31A-DAG: [[P6:%.+]] = getelementptr inbounds {{.+}}[[P]], i{{.+}} 0, i{{.+}} 6
// CK31A-DAG: [[S6:%.+]] = getelementptr inbounds {{.+}}[[S]], i{{.+}} 0, i{{.+}} 6
// CK31A-DAG: [[CBP6:%.+]] = bitcast i8** [[BP6]] to [[ST]]**
// CK31A-DAG: [[CP6:%.+]] = bitcast i8** [[P6]] to i32**
// CK31A-DAG: store [[ST]]* [[ST2]], [[ST]]** [[CBP6]]
// CK31A-DAG: store i32* [[ST2_J]], i32** [[CP6]]
// CK31A-DAG: store i64 4, i64* [[S6]]
// CK31A-USE: call void [[CALL00:@.+]]([[ST]]* [[ST1]], i32* [[A]], [[ST]]* [[ST2]])
// CK31A-NOUSE: call void [[CALL00:@.+]]()
#pragma omp target map(tofrom: st1.i) map(present, tofrom: a, st1.j, st2.i) map(tofrom: st2.j)
{
#ifdef USE
st1.i++;
a++;
st1.j++;
st2.i++;
st2.j++;
#endif
}
// Always Close Present.
// Region 01
// CK31A-DAG: call i32 @__tgt_target_mapper(i64 {{[^,]+}}, i8* {{[^,]+}}, i32 1, i8** [[GEPBP:%.+]], i8** [[GEPP:%.+]], {{.+}}getelementptr {{.+}}[1 x i{{.+}}]* [[SIZE01]], {{.+}}getelementptr {{.+}}[1 x i{{.+}}]* [[MTYPE01]]{{.+}})
// CK31A-DAG: [[GEPBP]] = getelementptr inbounds {{.+}}[[BP:%[^,]+]]
// CK31A-DAG: [[GEPP]] = getelementptr inbounds {{.+}}[[P:%[^,]+]]
// CK31A-DAG: [[BP0:%.+]] = getelementptr inbounds {{.+}}[[BP]], i{{.+}} 0, i{{.+}} 0
// CK31A-DAG: [[P0:%.+]] = getelementptr inbounds {{.+}}[[P]], i{{.+}} 0, i{{.+}} 0
// CK31A-DAG: [[CBP0:%.+]] = bitcast i8** [[BP0]] to i32**
// CK31A-DAG: [[CP0:%.+]] = bitcast i8** [[P0]] to i32**
// CK31A-DAG: store i32* [[VAR0:%.+]], i32** [[CBP0]]
// CK31A-DAG: store i32* [[VAR0]], i32** [[CP0]]
// CK31A-USE: call void [[CALL01:@.+]](i32* {{[^,]+}})
// CK31A-NOUSE: call void [[CALL01:@.+]]()
#pragma omp target map(always close present tofrom: a)
{
#ifdef USE
a++;
#endif
}
}
// CK31A: define {{.+}}[[CALL00]]
// CK31A: define {{.+}}[[CALL01]]
#endif // CK31A
#endif
| 6,714 |
1,755 | /*=========================================================================
Program: Visualization Toolkit
Copyright (c) <NAME>, <NAME>, <NAME>
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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.
=========================================================================*/
/**
* @class vtkVRCamera
* @brief VR camera
*
* vtkVRCamera is a concrete implementation of the abstract class
* vtkCamera. vtkVRCamera interfaces to the VR rendering library.
*/
#ifndef vtkVRCamera_h
#define vtkVRCamera_h
#include "vtkOpenGLCamera.h"
#include "vtkRenderingVRModule.h" // For export macro
#include "vtkTransform.h" // ivars
class vtkMatrix4x4;
class VTKRENDERINGVR_EXPORT vtkVRCamera : public vtkOpenGLCamera
{
public:
vtkTypeMacro(vtkVRCamera, vtkOpenGLCamera);
/**
* Provides a matrix to go from absolute VR tracking coordinates
* to device coordinates. Used for rendering devices.
*/
virtual void GetTrackingToDCMatrix(vtkMatrix4x4*& TCDCMatrix) = 0;
protected:
vtkVRCamera() = default;
~vtkVRCamera() override = default;
private:
vtkVRCamera(const vtkVRCamera&) = delete;
void operator=(const vtkVRCamera&) = delete;
};
#endif
| 450 |
1,350 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.security.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* The target Event Hub to which event data will be exported. To learn more about Security Center continuous export
* capabilities, visit https://aka.ms/ASCExportLearnMore.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "actionType")
@JsonTypeName("EventHub")
@Fluent
public final class AutomationActionEventHub extends AutomationAction {
@JsonIgnore private final ClientLogger logger = new ClientLogger(AutomationActionEventHub.class);
/*
* The target Event Hub Azure Resource ID.
*/
@JsonProperty(value = "eventHubResourceId")
private String eventHubResourceId;
/*
* The target Event Hub SAS policy name.
*/
@JsonProperty(value = "sasPolicyName", access = JsonProperty.Access.WRITE_ONLY)
private String sasPolicyName;
/*
* The target Event Hub connection string (it will not be included in any
* response).
*/
@JsonProperty(value = "connectionString")
private String connectionString;
/**
* Get the eventHubResourceId property: The target Event Hub Azure Resource ID.
*
* @return the eventHubResourceId value.
*/
public String eventHubResourceId() {
return this.eventHubResourceId;
}
/**
* Set the eventHubResourceId property: The target Event Hub Azure Resource ID.
*
* @param eventHubResourceId the eventHubResourceId value to set.
* @return the AutomationActionEventHub object itself.
*/
public AutomationActionEventHub withEventHubResourceId(String eventHubResourceId) {
this.eventHubResourceId = eventHubResourceId;
return this;
}
/**
* Get the sasPolicyName property: The target Event Hub SAS policy name.
*
* @return the sasPolicyName value.
*/
public String sasPolicyName() {
return this.sasPolicyName;
}
/**
* Get the connectionString property: The target Event Hub connection string (it will not be included in any
* response).
*
* @return the connectionString value.
*/
public String connectionString() {
return this.connectionString;
}
/**
* Set the connectionString property: The target Event Hub connection string (it will not be included in any
* response).
*
* @param connectionString the connectionString value to set.
* @return the AutomationActionEventHub object itself.
*/
public AutomationActionEventHub withConnectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
@Override
public void validate() {
super.validate();
}
}
| 1,110 |
11,356 | <reponame>hixio-mh/libsnowflakeclient<gh_stars>1000+
/*
* Copyright 2010-2017 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.
*/
#include <aws/core/utils/crypto/MD5.h>
#include <aws/core/utils/Outcome.h>
#include <aws/core/utils/crypto/Factories.h>
using namespace Aws::Utils::Crypto;
MD5::MD5() :
m_hashImpl(CreateMD5Implementation())
{
}
MD5::~MD5()
{
}
HashResult MD5::Calculate(const Aws::String& str)
{
return m_hashImpl->Calculate(str);
}
HashResult MD5::Calculate(Aws::IStream& stream)
{
return m_hashImpl->Calculate(stream);
} | 376 |
4,812 | //===--------------------- PipelinePrinter.cpp ------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file implements the PipelinePrinter interface.
///
//===----------------------------------------------------------------------===//
#include "PipelinePrinter.h"
#include "Views/View.h"
namespace llvm {
namespace mca {
void PipelinePrinter::printReport(llvm::raw_ostream &OS) const {
for (const auto &V : Views)
V->printView(OS);
}
} // namespace mca.
} // namespace llvm
| 217 |
322 | ///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2019-2020, University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include "python/crocoddyl/core/core.hpp"
#include "crocoddyl/core/data/actuation.hpp"
namespace crocoddyl {
namespace python {
void exposeDataCollectorActuation() {
bp::class_<DataCollectorActuation, bp::bases<DataCollectorAbstract> >(
"DataCollectorActuation", "Actuation data collector.\n\n",
bp::init<boost::shared_ptr<ActuationDataAbstract> >(bp::args("self", "actuation"),
"Create actuation data collection.\n\n"
":param actuation: actuation data"))
.add_property(
"actuation",
bp::make_getter(&DataCollectorActuation::actuation, bp::return_value_policy<bp::return_by_value>()),
"actuation data");
}
} // namespace python
} // namespace crocoddyl
| 444 |
1,475 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache.partitioned.colocation;
import org.apache.geode.annotations.VisibleForTesting;
import org.apache.geode.internal.cache.PartitionedRegion;
class SingleThreadColocationLoggerFactory implements ColocationLoggerFactory {
@VisibleForTesting
static final String LOG_INTERVAL_PROPERTY =
"geode.SingleThreadColocationLoggerFactory.LOG_INTERVAL_MILLIS";
/**
* Sleep period (milliseconds) between posting log entries.
*/
@VisibleForTesting
static final long DEFAULT_LOG_INTERVAL = 30_000;
private final long logIntervalMillis;
private final SingleThreadColocationLoggerConstructor constructor;
SingleThreadColocationLoggerFactory() {
this(SingleThreadColocationLogger::new);
}
@VisibleForTesting
SingleThreadColocationLoggerFactory(SingleThreadColocationLoggerConstructor constructor) {
this(Long.getLong(LOG_INTERVAL_PROPERTY, DEFAULT_LOG_INTERVAL), constructor);
}
private SingleThreadColocationLoggerFactory(long logIntervalMillis,
SingleThreadColocationLoggerConstructor constructor) {
this.logIntervalMillis = logIntervalMillis;
this.constructor = constructor;
}
@Override
public ColocationLogger startColocationLogger(PartitionedRegion region) {
return constructor.create(region, logIntervalMillis / 2, logIntervalMillis).start();
}
}
| 588 |
8,428 | <gh_stars>1000+
"""Specific PyGrid exceptions."""
class PyGridError(Exception):
def __init__(self, message: str) -> None:
super().__init__(message)
class AuthorizationError(PyGridError):
def __init__(self, message: str = "") -> None:
if not message:
message = "User is not authorized for this operation!"
super().__init__(message)
class OwnerAlreadyExistsError(PyGridError):
def __init__(self, message: str = "") -> None:
if not message:
message = "This PyGrid domain already has an owner!"
super().__init__(message)
class RoleNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Role ID not found!"
super().__init__(message)
class ModelNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Model ID not found!"
super().__init__(message)
class CycleNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Cycle not found!"
super().__init__(message)
class PlanNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Plan ID not found!"
super().__init__(message)
class ProcessNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Not found any process related with this cycle and worker ID."
super().__init__(message)
class PlanInvalidError(PyGridError):
def __init__(self) -> None:
message = "Plan is not valid"
super().__init__(message)
class PlanTranslationError(PyGridError):
def __init__(self) -> None:
message = "Failed to translate a Plan"
super().__init__(message)
class WorkerNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Worker ID not found!"
super().__init__(message)
class ProtocolNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Protocol ID not found!"
super().__init__(message)
class FLProcessConflict(PyGridError):
def __init__(self) -> None:
message = "FL Process already exists."
super().__init__(message)
class MaxCycleLimitExceededError(PyGridError):
def __init__(self) -> None:
message = "There are no cycles remaining"
super().__init__(message)
class UserNotFoundError(PyGridError):
def __init__(self) -> None:
message = "User not found!"
super().__init__(message)
class EnvironmentNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Environment not found!"
super().__init__(message)
class SetupNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Setup not found!"
super().__init__(message)
class GroupNotFoundError(PyGridError):
def __init__(self, message: str) -> None:
super().__init__(message)
class InvalidRequestKeyError(PyGridError):
def __init__(self) -> None:
message = "Invalid request key!"
super().__init__(message)
class InvalidCredentialsError(PyGridError):
def __init__(self) -> None:
message = "Invalid credentials!"
super().__init__(message)
class MissingRequestKeyError(PyGridError):
def __init__(self, message: str = "") -> None:
if not message:
message = "Missing request key!"
super().__init__(message)
class AssociationRequestError(PyGridError):
def __init__(self) -> None:
message = "Association Request ID not found!"
super().__init__(message)
class AssociationError(PyGridError):
def __init__(self) -> None:
message = "Association ID not found!"
super().__init__(message)
class RequestError(PyGridError):
def __init__(self, message: str) -> None:
super().__init__(message)
class DatasetNotFoundError(PyGridError):
def __init__(self) -> None:
message = "Dataset ID not found!"
super().__init__(message)
class InvalidParameterValueError(PyGridError):
def __init__(self, message: str = "") -> None:
if not message:
message = "Passed paramater value not valid!"
super().__init__(message)
class AppInSleepyMode(PyGridError):
def __init__(self, message: str = "") -> None:
if not message:
message = (
"This app is in sleep mode. Please undergo the initial setup first"
)
super().__init__(message)
| 1,712 |
6,304 | #!/usr/bin/env python
#
# Copyright 2019 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
INFRA_GO = 'go.skia.org/infra'
WHICH = 'where' if sys.platform == 'win32' else 'which'
def check():
'''Verify that golang is properly installed. If not, exit with an error.'''
def _fail(msg):
print >> sys.stderr, msg
sys.exit(1)
try:
go_exe = subprocess.check_output([WHICH, 'go'])
except (subprocess.CalledProcessError, OSError):
go_exe = None
if not go_exe:
_fail('Unable to find Golang installation; see '
'https://golang.org/doc/install')
if not os.environ.get('GOPATH'):
_fail('GOPATH environment variable is not set; is Golang properly '
'installed?')
go_bin = os.path.join(os.environ['GOPATH'], 'bin')
for entry in os.environ.get('PATH', '').split(os.pathsep):
if entry == go_bin:
break
else:
_fail('%s not in PATH; is Golang properly installed?' % go_bin)
def get(pkg):
'''Obtain/update the given package/module via "go get".'''
check()
subprocess.check_call(['go', 'get', '-u', pkg])
def update_infra():
'''Update the local checkout of the Skia infra codebase.'''
get(INFRA_GO + '/...')
def mod_download(*pkgs):
'''Run "go mod download" to obtain the given package(s).'''
check()
subprocess.check_call(['go', 'mod', 'download']+list(pkgs))
def install(pkg):
'''"go install" the given package.'''
check()
subprocess.check_call(['go', 'install', pkg])
| 591 |
1,116 | <reponame>LegoYoda112/moveit<gh_stars>1000+
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, <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 copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT 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 <moveit/collision_detection/collision_common.h>
static const char LOGNAME[] = "collision_common";
constexpr size_t LOG_THROTTLE_PERIOD = 5;
namespace collision_detection
{
void CollisionResult::print() const
{
if (!contacts.empty())
{
ROS_WARN_STREAM_THROTTLE_NAMED(LOG_THROTTLE_PERIOD, LOGNAME,
"Objects in collision (printing 1st of "
<< contacts.size() << " pairs): " << contacts.begin()->first.first << ", "
<< contacts.begin()->first.second);
// Log all collisions at the debug level
ROS_DEBUG_STREAM_THROTTLE_NAMED(LOG_THROTTLE_PERIOD, LOGNAME, "Objects in collision:");
for (const auto& contact : contacts)
{
ROS_DEBUG_STREAM_THROTTLE_NAMED(LOG_THROTTLE_PERIOD, LOGNAME,
"\t" << contact.first.first << ", " << contact.first.second);
}
}
}
} // namespace collision_detection
| 972 |
1,168 | // Tests that tag declaration embedded in a declarator
// are properly parented.
//- @outer defines/binding Outer
struct outer {
//- @inner ref Inner
//- Inner.node/kind tnominal
//- Inner childof Outer
struct inner* array[1];
};
| 72 |
7,482 | /***********************************************************************
* Filename : sha256.h
* Description : sha256 header file
* Author(s) : Eric
* version : V1.0
* Modify date : 2020-07-09
***********************************************************************/
#ifndef __SHA256_H__
#define __SHA256_H__
#include "ACM32Fxx_HAL.h"
/**********************************************************
* structure
**********************************************************/
//SHA256 context
typedef struct {
UINT32 state[8]; //state (ABCD)
UINT32 count[2]; // number of bits, modulo 2^64 (msb first)
uint8_t buffer[64]; // input buffer
} SHA256_CTX;
/**********************************************************
* extern functions
***********************************************************/
void SHA_memcpy (uint8_t *output,uint8_t *input, UINT32 len);
void SHA_memset (uint8_t *output, int value, UINT32 len);
void SHA_encode (uint8_t *output, UINT32 *input, UINT32 len);
/**********************************************************
* extern variable
***********************************************************/
extern const unsigned char PADDING[128];
/**************************************************************************
* Function Name : HAL_SHA256_Init
* Description : SHA256 initialization. Begins an SHA1 operation, writing a new context.
* Input : None
* Output : - *context : the point of sha1 context
* Return : None
**************************************************************************/
void HAL_SHA256_Init(SHA256_CTX *context);
/**************************************************************************
* Function Name : HAL_SHA256_Update
* Description : SHA256 block update operation. Continues an SHA1 message-digest
* : operation, processing another message block, and updating the
* : context.
* Input : - *context : context before transform
* : - *input : input message
* : - inputlen : the byte length of input message
* Output : - *context : context after transform
* Return : None
**************************************************************************/
void HAL_SHA256_Update(SHA256_CTX *context, uint8_t *input,UINT32 inputLen);
/**************************************************************************
* Function Name : HAL_SHA256_Final
* Description : SHA256 finalization. Ends an SHA256 message-digest operation, writing the
* : the message digest and zeroizing the context.
* Input : - *context : context before transform
* Output : - *digest : message digest
* Return : None
**************************************************************************/
void HAL_SHA256_Final(uint8_t *digest, SHA256_CTX *context);
/**************************************************************************
* Function Name : HAL_SHA256_Hash
* Description : transform message to digest in SHA1 algorithm
* Input : - *pDataIn : input message to be tranformed;
: - DataLen : the byte length of message;
* Output : - *pDigest : output the digest;
* Return : None
**************************************************************************/
void HAL_SHA256_Hash(uint8_t *pDataIn,UINT32 DataLen,uint8_t *pDigest);
#endif
| 990 |
332 | /*
*
* Copyright 2020 WeBank
*
* 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.webank.wedatasphere.exchangis.project.controller;
import com.webank.wedatasphere.exchangis.common.auth.data.DataAuthScope;
import com.webank.wedatasphere.exchangis.auth.domain.UserRole;
import com.webank.wedatasphere.exchangis.common.constant.CodeConstant;
import com.webank.wedatasphere.exchangis.common.controller.AbstractGenericController;
import com.webank.wedatasphere.exchangis.common.controller.Response;
import com.webank.wedatasphere.exchangis.common.service.IBaseService;
import com.webank.wedatasphere.exchangis.group.service.GroupService;
import com.webank.wedatasphere.exchangis.job.domain.JobInfo;
import com.webank.wedatasphere.exchangis.job.query.JobInfoQuery;
import com.webank.wedatasphere.exchangis.job.service.impl.JobInfoServiceImpl;
import com.webank.wedatasphere.exchangis.project.domain.Project;
import com.webank.wedatasphere.exchangis.project.query.ProjectQuery;
import com.webank.wedatasphere.exchangis.project.service.ProjectService;
import com.webank.wedatasphere.exchangis.user.domain.UserInfo;
import com.webank.wedatasphere.exchangis.user.service.UserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
/**
* Project management
* Created by devendeng on 2018/9/20.
*/
@RestController
@RequestMapping("/api/v1/project")
public class ProjectController extends AbstractGenericController<Project, ProjectQuery> {
@Resource
private ProjectService projectService;
@Resource
private JobInfoServiceImpl jobInfoService;
@Override
public IBaseService<Project> getBaseService() {
return projectService;
}
@Resource
private GroupService groupService;
@Resource
private UserInfoService userInfoService;
@PostConstruct
public void init(){
security.registerUserExternalDataAuthGetter(Project.class, userName ->{
UserInfo userInfo = userInfoService.selectByUsername(userName);
if(userInfo.getUserType() >= UserRole.MANGER.getValue()){
//No limit
return null;
}
return groupService.queryGroupRefProjectsByUser(userName);
});
security.registerExternalDataAuthGetter(Project.class, project -> Collections.singletonList(String.valueOf(project.getId())));
security.registerExternalDataAuthScopeGetter(Project.class, project -> Arrays.asList(DataAuthScope.READ, DataAuthScope.WRITE, DataAuthScope.EXECUTE));
}
/**
* Get child projects
* @return
*/
@RequestMapping(value = "/{id:\\w+}/child", method = RequestMethod.GET)
public Response<Object> treeChild(@PathVariable("id")Long id, HttpServletRequest request){
List<Project> list = projectService.listChild(id, security.getUserName(request));
return new Response<>().successResponse(list);
}
@Override
public Response<Project> add(@Valid @RequestBody Project project, HttpServletRequest request) {
if(project.getParentId() == null){
project.setParentId(0);
}
if(project.getParentId() > 0) {
Project parent = projectService.get(project.getParentId());
if(null == parent){
return new Response<Project>().errorResponse(CodeConstant.PARAMETER_ERROR, null,
super.informationSwitch("exchange.project.not.exist"));
}
if(!hasDataAuth(Project.class, DataAuthScope.WRITE, request, parent)){
return new Response<Project>().errorResponse(CodeConstant.AUTH_ERROR, null, super.informationSwitch("exchange.project.no.operation.privilege"));
}
}
//No limit for adding
return super.add(project, request);
}
@Override
public Response<Project> update(@Valid @RequestBody Project project, HttpServletRequest request) {
Project storedProject = projectService.get(project.getId());
if(!hasDataAuth(Project.class, DataAuthScope.WRITE, request, storedProject)){
return new Response<Project>().errorResponse(CodeConstant.AUTH_ERROR, null, super.informationSwitch("exchange.project.no.operation.privilege"));
}
if(project.getParentId() == null){
project.setParentId(0);
}
if(project.getParentId() > 0){
Project parent = projectService.get(project.getParentId());
if(null == parent){
return new Response<Project>().errorResponse(CodeConstant.PARAMETER_ERROR, null, super.informationSwitch("exchange.project.not.exist"));
}else if (!hasDataAuth(Project.class, DataAuthScope.WRITE, request, parent)){
return new Response<Project>().errorResponse(CodeConstant.AUTH_ERROR, null, super.informationSwitch("exchange.project.no.operation.privilege"));
}
}
return super.update(project, request);
}
@Override
public Response<Project> delete(@PathVariable Long id, HttpServletRequest request) {
Project project = projectService.get(id);
if(!hasDataAuth(Project.class, DataAuthScope.DELETE, request, project)){
return new Response<Project>().errorResponse(CodeConstant.AUTH_ERROR, null, super.informationSwitch("exchange.project.no.operation.privilege"));
}
//Cascade delete
List<Object> ids = new ArrayList<>();
Queue<Project> queue = new LinkedList<>();
List<Project> stored = new ArrayList<>();
JobInfoQuery query = new JobInfoQuery();
queue.add(project);
stored.add(project);
while(!queue.isEmpty()){
project = queue.poll();
//Delete if there are no jobs under the project
query.setProjectId(project.getId());
List<JobInfo> jobs = jobInfoService.selectAllList(query);
if(!jobs.isEmpty()){
return new Response<Project>().errorResponse(CodeConstant.PARAMETER_ERROR, null,
super.informationSwitch("exchange.project.cannot.delete"));
}
ids.add(project.getId());
ProjectQuery pjQuery = new ProjectQuery();
pjQuery.setParentId(project.getId());
List<Project> projects = getBaseService().selectAllList(pjQuery);
queue.addAll(projects);
stored.addAll(projects);
}
boolean result = projectService.delete("", stored);
return result ? new Response<Project>().successResponse(null) : new Response<Project>().errorResponse(1, null, super.informationSwitch("exchange.project.tasks.delete.failed"));
}
@Override
public Response<Project> show(@PathVariable Long id, HttpServletRequest request) throws Exception {
Project project = projectService.get(id);
if(!hasDataAuth(Project.class, DataAuthScope.READ, request, project)){
return new Response<Project>().errorResponse(CodeConstant.AUTH_ERROR, null, super.informationSwitch("exchange.project.no.operation.privilege"));
}
return new Response<Project>().successResponse(project);
}
@RequestMapping(value = "/tree", method = RequestMethod.GET)
public Response<Object> tree(ProjectQuery query, HttpServletRequest request){
String username = security.getUserName(request);
if(StringUtils.isNotBlank(username)){
security.bindUserInfoAndDataAuth(query, request,
security.userExternalDataAuthGetter(getActualType()).get(username));
}
List<Project> data = getBaseService().selectAllList(query);
Map<String, Project> treeMap = new HashMap<>();
data.forEach(element -> {
//Bind authority scopes
treeMap.put(String.valueOf(element.getId()), element);
security.bindAuthScope(data, security.externalDataAuthScopeGetter(getActualType()).get(element));
});
//Build tree
for (Map.Entry<String, Project> entry : treeMap.entrySet()) {
Project value = entry.getValue();
if (null != value.getParentId()) {
Project parent = treeMap.get(String.valueOf(value.getParentId()));
if (null != parent) {
parent.getChildren().add(value);
value.setLevel(parent.getLevel() + 1);
data.remove(value);
}
}
}
return new Response<>().successResponse(data);
}
}
| 3,541 |
429 | /* vim: tabstop=4 shiftwidth=4 noexpandtab
* This file is part of ToaruOS and is released under the terms
* of the NCSA / University of Illinois License - see LICENSE.md
* Copyright (C) 2018 <NAME>
*
* tty - print terminal name
*/
#include <stdio.h>
#include <unistd.h>
int main(int argc, char * argv[]) {
if (!isatty(STDIN_FILENO)) {
fprintf(stdout, "not a tty\n");
return 1;
}
fprintf(stdout,"%s\n",ttyname(STDIN_FILENO));
return 0;
}
| 178 |
2,757 | <gh_stars>1000+
/*
* Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <openssl/crypto.h>
#define perror_line() perror_line1(__LINE__)
#define perror_line1(l) perror_line2(l)
#define perror_line2(l) perror("failed " #l)
int main(int argc, char **argv)
{
#if defined(OPENSSL_SYS_LINUX) || defined(OPENSSL_SYS_UNIX)
char *p = NULL, *q = NULL, *r = NULL, *s = NULL;
int i;
const int size = 64;
s = OPENSSL_secure_malloc(20);
/* s = non-secure 20 */
if (s == NULL) {
perror_line();
return 1;
}
if (CRYPTO_secure_allocated(s)) {
perror_line();
return 1;
}
r = OPENSSL_secure_malloc(20);
/* r = non-secure 20, s = non-secure 20 */
if (r == NULL) {
perror_line();
return 1;
}
if (!CRYPTO_secure_malloc_init(4096, 32)) {
perror_line();
return 1;
}
if (CRYPTO_secure_allocated(r)) {
perror_line();
return 1;
}
p = OPENSSL_secure_malloc(20);
/* r = non-secure 20, p = secure 20, s = non-secure 20 */
if (!CRYPTO_secure_allocated(p)) {
perror_line();
return 1;
}
/* 20 secure -> 32-byte minimum allocaton unit */
if (CRYPTO_secure_used() != 32) {
perror_line();
return 1;
}
q = OPENSSL_malloc(20);
/* r = non-secure 20, p = secure 20, q = non-secure 20, s = non-secure 20 */
if (CRYPTO_secure_allocated(q)) {
perror_line();
return 1;
}
OPENSSL_secure_clear_free(s, 20);
s = OPENSSL_secure_malloc(20);
/* r = non-secure 20, p = secure 20, q = non-secure 20, s = secure 20 */
if (!CRYPTO_secure_allocated(s)) {
perror_line();
return 1;
}
/* 2 * 20 secure -> 64 bytes allocated */
if (CRYPTO_secure_used() != 64) {
perror_line();
return 1;
}
OPENSSL_secure_clear_free(p, 20);
/* 20 secure -> 32 bytes allocated */
if (CRYPTO_secure_used() != 32) {
perror_line();
return 1;
}
OPENSSL_free(q);
/* should not complete, as secure memory is still allocated */
if (CRYPTO_secure_malloc_done()) {
perror_line();
return 1;
}
if (!CRYPTO_secure_malloc_initialized()) {
perror_line();
return 1;
}
OPENSSL_secure_free(s);
/* secure memory should now be 0, so done should complete */
if (CRYPTO_secure_used() != 0) {
perror_line();
return 1;
}
if (!CRYPTO_secure_malloc_done()) {
perror_line();
return 1;
}
if (CRYPTO_secure_malloc_initialized()) {
perror_line();
return 1;
}
fprintf(stderr, "Possible infinite loop: allocate more than available\n");
if (!CRYPTO_secure_malloc_init(32768, 16)) {
perror_line();
return 1;
}
if (OPENSSL_secure_malloc((size_t)-1) != NULL) {
perror_line();
return 1;
}
if (!CRYPTO_secure_malloc_done()) {
perror_line();
return 1;
}
/*
* If init fails, then initialized should be false, if not, this
* could cause an infinite loop secure_malloc, but we don't test it
*/
if (!CRYPTO_secure_malloc_init(16, 16) &&
CRYPTO_secure_malloc_initialized()) {
CRYPTO_secure_malloc_done();
perror_line();
return 1;
}
if (!CRYPTO_secure_malloc_init(32768, 16)) {
perror_line();
return 1;
}
/*
* Verify that secure memory gets zeroed properly.
*/
if ((p = OPENSSL_secure_malloc(size)) == NULL) {
perror_line();
return 1;
}
for (i = 0; i < size; i++)
if (p[i] != 0) {
perror_line();
fprintf(stderr, "iteration %d\n", i);
return 1;
}
for (i = 0; i < size; i++)
p[i] = (unsigned char)(i + ' ' + 1);
OPENSSL_secure_free(p);
/*
* A deliberate use after free here to verify that the memory has been
* cleared properly. Since secure free doesn't return the memory to
* libc's memory pool, it technically isn't freed. However, the header
* bytes have to be skipped and these consist of two pointers in the
* current implementation.
*/
for (i = sizeof(void *) * 2; i < size; i++)
if (p[i] != 0) {
perror_line();
fprintf(stderr, "iteration %d\n", i);
return 1;
}
if (!CRYPTO_secure_malloc_done()) {
perror_line();
return 1;
}
/*-
* There was also a possible infinite loop when the number of
* elements was 1<<31, as |int i| was set to that, which is a
* negative number. However, it requires minimum input values:
*
* CRYPTO_secure_malloc_init((size_t)1<<34, (size_t)1<<4);
*
* Which really only works on 64-bit systems, since it took 16 GB
* secure memory arena to trigger the problem. It naturally takes
* corresponding amount of available virtual and physical memory
* for test to be feasible/representative. Since we can't assume
* that every system is equipped with that much memory, the test
* remains disabled. If the reader of this comment really wants
* to make sure that infinite loop is fixed, they can enable the
* code below.
*/
# if 0
/*-
* On Linux and BSD this test has a chance to complete in minimal
* time and with minimum side effects, because mlock is likely to
* fail because of RLIMIT_MEMLOCK, which is customarily [much]
* smaller than 16GB. In other words Linux and BSD users can be
* limited by virtual space alone...
*/
if (sizeof(size_t) > 4) {
fprintf(stderr, "Possible infinite loop: 1<<31 limit\n");
if (CRYPTO_secure_malloc_init((size_t)1<<34, (size_t)1<<4) == 0) {
perror_line();
} else if (!CRYPTO_secure_malloc_done()) {
perror_line();
return 1;
}
}
# endif
/* this can complete - it was not really secure */
OPENSSL_secure_free(r);
#else
/* Should fail. */
if (CRYPTO_secure_malloc_init(4096, 32)) {
perror_line();
return 1;
}
#endif
return 0;
}
| 2,840 |
2,637 | <reponame>nateglims/amazon-freertos<gh_stars>1000+
/** @file crc_reg.h
*
* @brief This file contains automatically generated register structure
*
* (C) Copyright 2012-2019 Marvell International Ltd. All Rights Reserved
*
* MARVELL CONFIDENTIAL
* The source code contained or described herein and all documents related to
* the source code ("Material") are owned by Marvell International Ltd or its
* suppliers or licensors. Title to the Material remains with Marvell
* International Ltd or its suppliers and licensors. The Material contains
* trade secrets and proprietary and confidential information of Marvell or its
* suppliers and licensors. The Material is protected by worldwide copyright
* and trade secret laws and treaty provisions. No part of the Material may be
* used, copied, reproduced, modified, published, uploaded, posted,
* transmitted, distributed, or disclosed in any way without Marvell's prior
* express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or delivery
* of the Materials, either expressly, by implication, inducement, estoppel or
* otherwise. Any license under such intellectual property rights must be
* express and approved by Marvell in writing.
*
*/
/****************************************************************************//*
* @version V1.3.0
* @date 12-Aug-2013
* @author CE Application Team
******************************************************************************/
#ifndef _CRC_REG_H
#define _CRC_REG_H
struct crc_reg {
/* 0x00: Interrupt Status Register */
union {
struct {
uint32_t STATUS : 1; /* [0] r/o */
uint32_t RESERVED_31_1 : 31; /* [31:1] rsvd */
} BF;
uint32_t WORDVAL;
} ISR;
/* 0x04: Interrupt Raw Status Register */
union {
struct {
uint32_t STATUS_RAW : 1; /* [0] r/o */
uint32_t RESERVED_31_1 : 31; /* [31:1] rsvd */
} BF;
uint32_t WORDVAL;
} IRSR;
/* 0x08: Interrupt Clear Register */
union {
struct {
uint32_t CLEAR : 1; /* [0] w/o */
uint32_t RESERVED_31_1 : 31; /* [31:1] rsvd */
} BF;
uint32_t WORDVAL;
} ICR;
/* 0x0c: Interrupt Mask Register */
union {
struct {
uint32_t MASK : 1; /* [0] r/w */
uint32_t RESERVED_31_1 : 31; /* [31:1] rsvd */
} BF;
uint32_t WORDVAL;
} IMR;
/* 0x10: CRC Module Control Register */
union {
struct {
uint32_t ENABLE : 1; /* [0] r/w */
uint32_t MODE : 3; /* [3:1] r/w */
uint32_t RESERVED_31_4 : 28; /* [31:4] rsvd */
} BF;
uint32_t WORDVAL;
} CTRL;
/* 0x14: Stream Length Minus 1 Register */
union {
struct {
uint32_t LENGTH_M1 : 32; /* [31:0] r/w */
} BF;
uint32_t WORDVAL;
} STREAM_LEN_M1;
/* 0x18: Stream Input Register */
union {
struct {
uint32_t DATA : 32; /* [31:0] r/w */
} BF;
uint32_t WORDVAL;
} STREAM_IN;
/* 0x1c: CRC Calculation Result */
union {
struct {
uint32_t DATA : 32; /* [31:0] r/o */
} BF;
uint32_t WORDVAL;
} RESULT;
};
typedef volatile struct crc_reg crc_reg_t;
#ifdef CRC_IMPL
BEGIN_REG_SECTION(crc_registers)
crc_reg_t CRCREG;
END_REG_SECTION(crc_registers)
#else
extern crc_reg_t CRCREG;
#endif
#endif /* _CRC_REG_H */
| 1,594 |
954 | package ch.swissonid.design_lib_sample.fragments;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.Bind;
import ch.swissonid.design_lib_sample.R;
/**
* A simple {@link Fragment} subclass.
* Use the {@link FlexibleSpaceFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class FlexibleSpaceFragment extends BaseFragment {
@Bind(R.id.collapsing_toolbar)
CollapsingToolbarLayout mCollapsingToolbar;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment PinnedAppBarkFragment.
*/
public static FlexibleSpaceFragment newInstance() {
return new FlexibleSpaceFragment();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mCollapsingToolbar.setTitle(getString(getTitle()));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
if(view == null) return null;
return view;
}
public FlexibleSpaceFragment() {
// Required empty public constructor
}
@Override
protected int getTitle() {
return R.string.flexible_space_menu_title;
}
@Override
protected int getToolbarId() {
return R.id.toolbar_flexible_space;
}
@Override
public boolean hasCustomToolbar() {
return true;
}
@Override
protected int getLayout() {
return R.layout.fragment_flexible_space;
}
}
| 670 |
562 | import json
from textwrap import dedent
import pytest
import responses
from freight import checks
from freight.exceptions import CheckFailed, CheckPending
from freight.testutils import TestCase
class CloudbuilderCheckBase(TestCase):
def setUp(self):
self.check = checks.get("cloudbuilder")
self.user = self.create_user()
self.repo = self.create_repo()
self.app = self.create_app(repository=self.repo)
self.test_project = "mycoolproject"
self.test_sha = "0987654321"
self.test_token = "<PASSWORD>"
class CloudbuilderContextCheckTest(CloudbuilderCheckBase):
@responses.activate
def test_build_success(self):
test_id = "successful_build_id"
body = json.dumps(
{
"builds": [
{
"id": test_id,
"logUrl": f"https://console.cloud.google.com/gcr/builds/{test_id}?project={self.test_project}",
"logsBucket": f"gs://{self.test_project}.cloudbuild-logs.googleusercontent.com",
"status": "SUCCESS",
}
]
}
)
responses.add(
responses.GET,
f"https://cloudbuild.googleapis.com/v1/projects/{self.test_project}/builds",
body=body,
)
config = {"project": self.test_project, "oauth_token": self.test_token}
self.check.check(self.app, self.test_sha, config)
@responses.activate
def test_build_fail(self):
test_id = "failed_build_id"
body = json.dumps(
{
"builds": [
{
"id": test_id,
"logUrl": f"https://console.cloud.google.com/gcr/builds/{test_id}?project={self.test_project}",
"logsBucket": f"gs://{self.test_project}.cloudbuild-logs.googleusercontent.com",
"status": "FAILURE",
}
]
}
)
responses.add(
responses.GET,
f"https://cloudbuild.googleapis.com/v1/projects/{self.test_project}/builds",
body=body,
)
config = {"project": self.test_project, "oauth_token": self.test_token}
failed_log_text = """\
LOG TEXT HERE
THIS HERE IS A MOCK OF LOG.TEXT THAT WILL BE PRINTED
build build build build build build steps
MORE LOGS HERE.
"""
build_logs = "mycoolproject.cloudbuild-logs.googleusercontent.com"
build_id = "failed_build_id"
responses.add(
responses.GET,
f"https://storage.googleapis.com/{build_logs}/log-{build_id}.txt",
body=dedent(failed_log_text),
)
with pytest.raises(CheckFailed):
self.check.check(self.app, self.test_sha, config)
@responses.activate
def test_build_in_progress(self):
test_id = "WIP_build_id"
body = json.dumps(
{
"builds": [
{
"id": test_id,
"logUrl": f"https://console.cloud.google.com/gcr/builds/{test_id}?project={self.test_project}",
"logsBucket": f"gs://{self.test_project}.cloudbuild-logs.googleusercontent.com",
"status": "WORKING",
}
]
}
)
responses.add(
responses.GET,
f"https://cloudbuild.googleapis.com/v1/projects/{self.test_project}/builds",
body=body,
)
config = {"project": self.test_project, "oauth_token": self.test_token}
with pytest.raises(CheckPending):
self.check.check(self.app, self.test_sha, config)
@responses.activate
def test_build_status_unknown(self):
""" "STATUS_UNKNOWN": "Status of the build is unknown."""
test_id = "unknown_build_id"
body = json.dumps(
{
"builds": [
{
"id": test_id,
"logUrl": f"https://console.cloud.google.com/gcr/builds/{test_id}?project={self.test_project}",
"logsBucket": f"gs://{self.test_project}.cloudbuild-logs.googleusercontent.com",
"status": "STATUS_UNKNOWN",
}
]
}
)
responses.add(
responses.GET,
f"https://cloudbuild.googleapis.com/v1/projects/{self.test_project}/builds",
body=body,
)
config = {"project": self.test_project, "oauth_token": self.test_token}
with pytest.raises(CheckFailed) as exception_info:
self.check.check(self.app, self.test_sha, config)
@responses.activate
def test_build_status_queued(self):
"""QUEUED": "Build or step is queued; work has not yet begun."""
test_id = "build_id"
body = json.dumps(
{
"builds": [
{
"id": test_id,
"logUrl": f"https://console.cloud.google.com/gcr/builds/{test_id}?project={self.test_project}",
"logsBucket": f"gs://{self.test_project}.cloudbuild-logs.googleusercontent.com",
"status": "QUEUED",
}
]
}
)
responses.add(
responses.GET,
f"https://cloudbuild.googleapis.com/v1/projects/{self.test_project}/builds",
body=body,
)
config = {"project": self.test_project, "oauth_token": self.test_token}
with pytest.raises(CheckPending) as exception_info:
self.check.check(self.app, self.test_sha, config)
@responses.activate
def test_build_status_internal_error(self):
"""INTERNAL_ERROR": "Build or step failed due to an internal cause."""
test_id = "build_id"
body = json.dumps(
{
"builds": [
{
"id": test_id,
"logUrl": f"https://console.cloud.google.com/gcr/builds/{test_id}?project={self.test_project}",
"logsBucket": f"gs://{self.test_project}.cloudbuild-logs.googleusercontent.com",
"status": "INTERNAL_ERROR",
}
]
}
)
responses.add(
responses.GET,
f"https://cloudbuild.googleapis.com/v1/projects/{self.test_project}/builds",
body=body,
)
config = {"project": self.test_project, "oauth_token": self.test_token}
with pytest.raises(CheckFailed) as exception_info:
self.check.check(self.app, self.test_sha, config)
@responses.activate
def test_build_status_timeout(self):
"""[summary]
"TIMEOUT": "Build or step took longer than was allowed.",
Arguments:
self {[type]} -- [description]
"""
test_id = "build_id"
body = json.dumps(
{
"builds": [
{
"id": test_id,
"logUrl": f"https://console.cloud.google.com/gcr/builds/{test_id}?project={self.test_project}",
"logsBucket": f"gs://{self.test_project}.cloudbuild-logs.googleusercontent.com",
"status": "TIMEOUT",
}
]
}
)
responses.add(
responses.GET,
f"https://cloudbuild.googleapis.com/v1/projects/{self.test_project}/builds",
body=body,
)
config = {"project": self.test_project, "oauth_token": self.test_token}
with pytest.raises(CheckFailed) as exception_info:
self.check.check(self.app, self.test_sha, config)
@responses.activate
def test_build_status_cancelled(self):
"""[summary]
"CANCELLED": "Build or step was canceled by a user.",
"""
test_id = "build_id"
body = json.dumps(
{
"builds": [
{
"id": test_id,
"logUrl": f"https://console.cloud.google.com/gcr/builds/{test_id}?project={self.test_project}",
"logsBucket": f"gs://{self.test_project}.cloudbuild-logs.googleusercontent.com",
"status": "CANCELLED",
}
]
}
)
responses.add(
responses.GET,
f"https://cloudbuild.googleapis.com/v1/projects/{self.test_project}/builds",
body=body,
)
config = {"project": self.test_project, "oauth_token": self.test_token}
with pytest.raises(CheckFailed) as exception_info:
self.check.check(self.app, self.test_sha, config)
@responses.activate
def test_missing_body(self):
config = {"project": self.test_project, "oauth_token": self.test_token}
responses.add(
responses.GET,
f"https://cloudbuild.googleapis.com/v1/projects/{self.test_project}/builds",
status=400,
)
with pytest.raises(CheckFailed):
self.check.check(self.app, self.test_sha, config)
| 5,057 |
310 | <filename>gear/hardware/n/nuvi-1300.json
{
"name": "<NAME>",
"description": "A pocket GPS device.",
"url": "https://www.amazon.com/Garmin-Widescreen-Navigator-Discontinued-Manufacturer/dp/B001U0O7T4"
} | 84 |
340 | #!/usr/bin/env python
# encoding: utf-8
"""
@version: 1.0
@author: lizheming
@contact: <EMAIL>
@site: lizheming.top
@file: Zhuanlan.py
"""
from zhihu import headers, clear, error, session
from bs4 import BeautifulSoup
import re
import webbrowser
import termcolor
import requests
import json
import sys
class Zhuanlan:
url = None
zhuanlan = None
soup = None
originalurl = None
def __init__(self, url):
#https://zhuanlan.zhihu.com/p/20825292
self.originalurl = url
number = re.findall(r"(\d+)", url)[0]
self.url = "http://zhuanlan.zhihu.com/api/posts/" + str(number)
self.headers = headers.copy()
self.headers["Host"] = "zhuanlan.zhihu.com"
def parse(self):
self.se = requests.Session()
for cookie in session.cookies:
self.se.cookies.set_cookie(cookie)
n = 3
res = None
while n > 0:
try:
res = self.se.get(self.url, headers=self.headers, timeout=30)
break
except:
n -= 1
return False
if not res:
print termcolor.colored("网络故障,请检查您的网络设置", "red")
sys.exit()
self.zhuanlan = dict(res.json())
self.soup = BeautifulSoup(self.zhuanlan["content"], "html.parser")
return True
def open_in_browser(self):
webbrowser.open_new(self.originalurl)
def check(self):
if not self.soup:
self.parse()
def get_title(self):
self.check()
return termcolor.colored(self.zhuanlan["title"], "blue")
def get_content(self):
self.check()
from Answer import print_content
print_content(self.soup.contents)
def get_author_info(self):
self.check()
author = dict(self.zhuanlan["author"])
return author["profileUrl"]
def vote(self, type=1):
self.check()
url = self.url + "/rating"
data = {}
if type == 1:
data["value"] = "none"
try:
self.se.put(url, json.dumps(data), headers=self.headers, timeout=15)
except:
print termcolor.colored("网络故障,请检查您的网络设置", "yellow")
return
data["value"] = "like"
else:
data["value"] = "none"
self.headers['Content-Type'] = "application/json;charset=UTF-8"
self.headers["Referer"] = self.originalurl
self.headers["Origin"] = "https://zhuanlan.zhihu.com"
self.headers['X-XSRF-TOKEN'] = self.se.cookies['XSRF-TOKEN']
try:
res = self.se.put(url, json.dumps(data), headers=self.headers, timeout=15)
except:
print termcolor.colored("网络故障,请检查您的网络设置", "yellow")
return
if res.status_code == 204:
s = "取消赞同成功" if data["value"] == "none" else "赞同成功"
print termcolor.colored(s, "blue")
elif res.status_code == 404:
s = "还没有赞同过" if data["value"] == "none" else "已经赞同过了"
print termcolor.colored(s, "blue")
def operate(self):
if not self.parse():
return True
print self.get_title()
while True:
op = raw_input("zhuanlan$ ")
if op == "content":
self.get_content()
elif op == "author":
url = self.get_author_info()
if not url:
print termcolor.colored("当前用户为匿名用户", "red")
else:
from User import User
user = User(url)
if user.operate():
return True
elif op == "voteup":
self.vote(type=1)
elif op == "votecancle":
self.vote(type=2)
elif op == "pwd":
print self.get_title()
elif op == "browser":
self.open_in_browser()
elif op == "clear":
clear()
elif op == "break":
break
elif op == "help":
self.help()
elif op == "quit":
return True
else:
error()
def help(self):
info = "\n" \
"**********************************************************\n" \
"**\n" \
"** content: 查看内容\n" \
"** author: 查看作者\n" \
"** voteup: 赞同\n" \
"** votecancle: 取消赞同\n" \
"** pwd: 显示当前专栏\n" \
"** browser: 在默认浏览器中查看\n" \
"** break: 返回上级操作目录\n" \
"** clear: 清屏\n" \
"** quit: 退出系统\n" \
"**\n" \
"**********************************************************\n"
print termcolor.colored(info, "green") | 2,778 |
611 | <reponame>codajs/edge-diagnostics-adaptor
//
// Copyright (C) Microsoft. All rights reserved.
//
// The default CComTypeInfoHolder (atlcom.h) doesn't support having RegFree Dispatch implementations that
// have the TYPELIB embedded in the dll as anything other than the first one
// To get around this we need to change the GetTI function to use the correct TYPELIB index
// We cannot just derive from the existing CComTypeInfoHolder due to the way IDispatchImpl binds to the class
// So we use the existing implementation and change GetTI().
#pragma once
#include <atlcomcli.h>
using namespace ATL;
class CComTypeInfoHolderLib
{
// Should be 'protected' but can cause compiler to generate fat code.
public:
const GUID* m_pguid;
const GUID* m_plibid;
WORD m_wMajor;
WORD m_wMinor;
ITypeInfo* m_pInfo;
long m_dwRef;
struct stringdispid
{
CComBSTR bstr;
int nLen;
DISPID id;
stringdispid() : nLen(0), id(DISPID_UNKNOWN){}
};
stringdispid* m_pMap;
int m_nCount;
// Custom typelib index
int m_typelibIndex;
public:
HRESULT GetTI(
_In_ LCID lcid,
_Outptr_result_maybenull_ ITypeInfo** ppInfo)
{
ATLASSERT(ppInfo != NULL);
if (ppInfo == NULL)
return E_POINTER;
HRESULT hr = S_OK;
if (m_pInfo == NULL)
hr = GetTI(lcid);
*ppInfo = m_pInfo;
if (m_pInfo != NULL)
{
m_pInfo->AddRef();
hr = S_OK;
}
return hr;
}
HRESULT GetTI(_In_ LCID lcid);
HRESULT EnsureTI(_In_ LCID lcid)
{
HRESULT hr = S_OK;
if (m_pInfo == NULL || m_pMap == NULL)
hr = GetTI(lcid);
return hr;
}
// This function is called by the module on exit
// It is registered through _pAtlModule->AddTermFunc()
static void __stdcall Cleanup(_In_ DWORD_PTR dw);
HRESULT GetTypeInfo(
_In_ UINT itinfo,
_In_ LCID lcid,
_Outptr_result_maybenull_ ITypeInfo** pptinfo)
{
if (itinfo != 0)
{
return DISP_E_BADINDEX;
}
return GetTI(lcid, pptinfo);
}
HRESULT GetIDsOfNames(
_In_ REFIID /* riid */,
_In_reads_(cNames) LPOLESTR* rgszNames,
_In_range_(0,16384) UINT cNames,
LCID lcid,
_Out_ DISPID* rgdispid)
{
HRESULT hRes = EnsureTI(lcid);
_Analysis_assume_(m_pInfo != NULL || FAILED(hRes));
if (m_pInfo != NULL)
{
hRes = E_FAIL;
// Look in cache if
// cache is populated
// parameter names are not requested
if (m_pMap != NULL && cNames == 1)
{
int n = int( ocslen(rgszNames[0]) );
for (int j=m_nCount-1; j>=0; j--)
{
if ((n == m_pMap[j].nLen) &&
(memcmp(m_pMap[j].bstr, rgszNames[0], m_pMap[j].nLen * sizeof(OLECHAR)) == 0))
{
rgdispid[0] = m_pMap[j].id;
hRes = S_OK;
break;
}
}
}
// if cache is empty or name not in cache or parameter names are requested,
// delegate to ITypeInfo::GetIDsOfNames
if (FAILED(hRes))
{
hRes = m_pInfo->GetIDsOfNames(rgszNames, cNames, rgdispid);
}
}
return hRes;
}
_Check_return_ HRESULT Invoke(
_Inout_ IDispatch* p,
_In_ DISPID dispidMember,
_In_ REFIID /* riid */,
_In_ LCID lcid,
_In_ WORD wFlags,
_In_ DISPPARAMS* pdispparams,
_Out_opt_ VARIANT* pvarResult,
_Out_opt_ EXCEPINFO* pexcepinfo,
_Out_opt_ UINT* puArgErr)
{
HRESULT hRes = EnsureTI(lcid);
_Analysis_assume_(m_pInfo != NULL || FAILED(hRes));
if (m_pInfo != NULL)
hRes = m_pInfo->Invoke(p, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr);
return hRes;
}
_Check_return_ HRESULT LoadNameCache(_Inout_ ITypeInfo* pTypeInfo)
{
TYPEATTR* pta;
HRESULT hr = pTypeInfo->GetTypeAttr(&pta);
if (SUCCEEDED(hr))
{
stringdispid* pMap = NULL;
m_nCount = pta->cFuncs;
m_pMap = NULL;
if (m_nCount != 0)
{
pMap = _ATL_NEW stringdispid[m_nCount];
if (pMap == NULL)
{
pTypeInfo->ReleaseTypeAttr(pta);
return E_OUTOFMEMORY;
}
}
for (int i=0; i<m_nCount; i++)
{
FUNCDESC* pfd;
if (SUCCEEDED(pTypeInfo->GetFuncDesc(i, &pfd)))
{
CComBSTR bstrName;
if (SUCCEEDED(pTypeInfo->GetDocumentation(pfd->memid, &bstrName, NULL, NULL, NULL)))
{
pMap[i].bstr.Attach(bstrName.Detach());
pMap[i].nLen = SysStringLen(pMap[i].bstr);
pMap[i].id = pfd->memid;
}
pTypeInfo->ReleaseFuncDesc(pfd);
}
}
m_pMap = pMap;
pTypeInfo->ReleaseTypeAttr(pta);
}
return S_OK;
}
};
inline void __stdcall CComTypeInfoHolderLib::Cleanup(_In_ DWORD_PTR dw)
{
ATLASSERT(dw != 0);
if (dw == 0)
return;
CComTypeInfoHolderLib* p = (CComTypeInfoHolderLib*) dw;
if (p->m_pInfo != NULL)
p->m_pInfo->Release();
p->m_pInfo = NULL;
delete [] p->m_pMap;
p->m_pMap = NULL;
}
inline HRESULT CComTypeInfoHolderLib::GetTI(_In_ LCID lcid)
{
//If this assert occurs then most likely didn't initialize properly
ATLASSUME(m_plibid != NULL && m_pguid != NULL);
if (m_pInfo != NULL && m_pMap != NULL)
return S_OK;
CComCritSecLock<CComCriticalSection> lock(_pAtlModule->m_csStaticDataInitAndTypeInfo, false);
HRESULT hRes = lock.Lock();
if (FAILED(hRes))
{
ATLTRACE(atlTraceCOM, 0, _T("ERROR : Unable to lock critical section in CComTypeInfoHolderLib::GetTI\n"));
ATLASSERT(0);
return hRes;
}
hRes = E_FAIL;
if (m_pInfo == NULL)
{
ITypeLib* pTypeLib = NULL;
if (InlineIsEqualGUID(CAtlModule::m_libid, *m_plibid) && m_wMajor == 0xFFFF && m_wMinor == 0xFFFF)
{
TCHAR szFilePath[MAX_PATH];
DWORD dwFLen = ::GetModuleFileName(_AtlBaseModule.GetModuleInstance(), szFilePath, MAX_PATH);
if( dwFLen != 0 && dwFLen != MAX_PATH )
{
USES_CONVERSION_EX;
LPOLESTR pszFile = T2OLE_EX(szFilePath, _ATL_SAFE_ALLOCA_DEF_THRESHOLD);
#ifndef _UNICODE
if (pszFile == NULL)
return E_OUTOFMEMORY;
#endif
// Append the typelib index onto the file string
CString withIndex(pszFile);
withIndex.AppendFormat(L"\\%d", m_typelibIndex);
hRes = LoadTypeLib(withIndex, &pTypeLib);
}
}
else
{
ATLASSUME(!InlineIsEqualGUID(*m_plibid, GUID_NULL) && "Module LIBID not initialized. See DECLARE_LIBID documentation.");
hRes = LoadRegTypeLib(*m_plibid, m_wMajor, m_wMinor, lcid, &pTypeLib);
#ifdef _DEBUG
if (SUCCEEDED(hRes))
{
// Trace out an warning if the requested TypelibID is the same as the modules TypelibID
// and versions do not match.
//
// In most cases it is due to wrong version template parameters to IDispatchImpl,
// IProvideClassInfoImpl or IProvideClassInfo2Impl.
// Set major and minor versions to 0xFFFF if the modules type lib has to be loaded
// irrespective of its version.
//
// Get the module's file path
TCHAR szFilePath[MAX_PATH];
DWORD dwFLen = ::GetModuleFileName(_AtlBaseModule.GetModuleInstance(), szFilePath, MAX_PATH);
if( dwFLen != 0 && dwFLen != MAX_PATH )
{
USES_CONVERSION_EX;
CComPtr<ITypeLib> spTypeLibModule;
HRESULT hRes2 = S_OK;
LPOLESTR pszFile = T2OLE_EX(szFilePath, _ATL_SAFE_ALLOCA_DEF_THRESHOLD);
if (pszFile == NULL)
hRes2 = E_OUTOFMEMORY;
else
hRes2 = LoadTypeLib(pszFile, &spTypeLibModule);
if (SUCCEEDED(hRes2))
{
TLIBATTR* pLibAttr;
hRes2 = spTypeLibModule->GetLibAttr(&pLibAttr);
if (SUCCEEDED(hRes2))
{
if (InlineIsEqualGUID(pLibAttr->guid, *m_plibid) &&
(pLibAttr->wMajorVerNum != m_wMajor ||
pLibAttr->wMinorVerNum != m_wMinor))
{
ATLTRACE(atlTraceCOM, 0, _T("Warning : CComTypeInfoHolderLib::GetTI : Loaded typelib does not match the typelib in the module : %s\n"), szFilePath);
ATLTRACE(atlTraceCOM, 0, _T("\tSee IDispatchImpl overview help topic for more information\n"));
}
spTypeLibModule->ReleaseTLibAttr(pLibAttr);
}
}
}
}
else
{
ATLTRACE(atlTraceCOM, 0, _T("ERROR : Unable to load Typelibrary. (HRESULT = 0x%x)\n"), hRes);
ATLTRACE(atlTraceCOM, 0, _T("\tVerify TypelibID and major version specified with\n"));
ATLTRACE(atlTraceCOM, 0, _T("\tIDispatchImpl, CStockPropImpl, IProvideClassInfoImpl or IProvideCLassInfo2Impl\n"));
}
#endif
}
if (SUCCEEDED(hRes))
{
CComPtr<ITypeInfo> spTypeInfo;
hRes = pTypeLib->GetTypeInfoOfGuid(*m_pguid, &spTypeInfo);
if (SUCCEEDED(hRes))
{
CComPtr<ITypeInfo> spInfo(spTypeInfo);
CComPtr<ITypeInfo2> spTypeInfo2;
if (SUCCEEDED(spTypeInfo->QueryInterface(&spTypeInfo2)))
spInfo = spTypeInfo2;
m_pInfo = spInfo.Detach();
_pAtlModule->AddTermFunc(Cleanup, (DWORD_PTR)this);
}
pTypeLib->Release();
}
}
else
{
// Another thread has loaded the typeinfo so we're OK.
hRes = S_OK;
}
if (m_pInfo != NULL && m_pMap == NULL)
{
hRes=LoadNameCache(m_pInfo);
}
return hRes;
}
template <class T, const IID* piid, class tihclass = CComTypeInfoHolder>
class ATL_NO_VTABLE IDispatchExImpl :
public IDispatchImpl<T, piid, &CAtlModule::m_libid, 0xFFFF, 0xFFFF, tihclass>
{
public:
// IDispatchEx
STDMETHOD(GetDispID)(
_In_ BSTR bstrName,
_In_ DWORD /* grfdex */,
_Out_ DISPID* pid)
{
return this->GetIDsOfNames(
IID_NULL,
&bstrName,
1,
MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT),
pid);
}
STDMETHOD(InvokeEx)(
_In_ DISPID id,
_In_ LCID lcid,
_In_ WORD wFlags,
_In_ DISPPARAMS* pdp,
_Out_opt_ VARIANT* pvarRes,
_Out_opt_ EXCEPINFO* pei,
_In_opt_ IServiceProvider* pspCaller)
{
UNREFERENCED_PARAMETER(pspCaller);
UINT argError = 0;
return this->Invoke(id, IID_NULL, lcid, wFlags, pdp, pvarRes, pei, &argError);
}
STDMETHOD(DeleteMemberByName)(
_In_ BSTR /* bstrName */,
_In_ DWORD /* grfdex */)
{
return E_NOTIMPL;
}
STDMETHOD(DeleteMemberByDispID)(
_In_ DISPID /* id */)
{
return E_NOTIMPL;
}
STDMETHOD(GetMemberProperties)(
_In_ DISPID /* id */,
_In_ DWORD /* grfdexFetch */,
_Out_ DWORD* /* pgrfdex */)
{
return E_NOTIMPL;
}
STDMETHOD(GetMemberName)(
_In_ DISPID /* id */,
_Out_opt_ BSTR* /* pbstrName */)
{
return E_NOTIMPL;
}
STDMETHOD(GetNextDispID)(
_In_ DWORD /* grfdex */,
_In_ DISPID /* id */,
_Out_ DISPID* /* pid */)
{
return E_NOTIMPL;
}
STDMETHOD(GetNameSpaceParent)(
_Out_opt_ IUnknown** /* ppunk */)
{
return E_NOTIMPL;
}
};
template <class T, const IID* piid>
class ATL_NO_VTABLE IDispatchExImplLib :
public IDispatchExImpl<T, piid, CComTypeInfoHolderLib>
{
public:
static void SetTypeLibIndex(_In_ int index)
{
IDispatchExImpl<T, piid, CComTypeInfoHolderLib>::_tih.m_typelibIndex = index;
};
};
template <class T, const IID* piid>
class ATL_NO_VTABLE IDispatchImplLib :
public IDispatchImpl<T, piid, &CAtlModule::m_libid, /*wMajor=*/ 0xffff, /*wMinor=*/ 0xffff, CComTypeInfoHolderLib>
{
public:
static void SetTypeLibIndex(_In_ int index)
{
IDispatchImpl<T, piid, &CAtlModule::m_libid, 0xffff, /*wMinor =*/ 0xffff, CComTypeInfoHolderLib>::_tih.m_typelibIndex = index;
};
};
// Special function used for ensuring the LIB gets loaded when combined into a different dll
// And for setting the dispatch's TYPELIB index, to allow multiple IDispatchs to exist in that same dll.
template <class T>
void SetTypeLibIndexForDispatch(_In_ int typelibIndex)
{
T::SetTypeLibIndex(typelibIndex);
};
| 7,465 |
367 | # -*- coding: utf-8 -*-
from pip.req import InstallRequirement
from packaging.utils import canonicalize_name
from .dependency import Dependency
class PipDependency(Dependency):
def __init__(self, name, constraint, category='main', checksum=None):
# Normalizing name for easier dependencies resolving
name = canonicalize_name(name)
super(PipDependency, self).__init__(name, constraint, category=category)
self._checksum = checksum
@property
def checksum(self):
return self._checksum
@property
def normalized_name(self):
normalized_name = self._name
normalized_constraint = self.normalized_constraint
if normalized_constraint:
if self.is_vcs_dependency():
normalized_name = normalized_constraint
else:
normalized_name += normalized_constraint
return normalized_name
def as_requirement(self):
if self.is_vcs_dependency():
return InstallRequirement.from_editable(self.normalized_name)
return InstallRequirement.from_line(self.normalized_name)
def _normalize_vcs_constraint(self, constraint):
if 'git' in constraint:
repo = constraint['git']
if 'branch' in constraint:
revision = constraint['branch']
elif 'tag' in constraint:
revision = constraint['tag']
elif 'rev' in constraint:
revision = constraint['rev']
else:
revision = 'master'
if not repo.startswith('git+'):
repo = 'git+' + repo
return '{}@{}#egg={}'.format(repo, revision, self._name)
raise ValueError('Unsupported VCS.')
| 753 |
6,263 | import os
import re
from ._default import Process
STAT_PPID = 3
STAT_TTY = 6
def get_process_mapping():
"""Try to look up the process tree via the /proc interface.
"""
with open('/proc/{0}/stat'.format(os.getpid())) as f:
self_tty = f.read().split()[STAT_TTY]
processes = {}
for pid in os.listdir('/proc'):
if not pid.isdigit():
continue
try:
stat = '/proc/{0}/stat'.format(pid)
cmdline = '/proc/{0}/cmdline'.format(pid)
with open(stat) as fstat, open(cmdline) as fcmdline:
stat = re.findall(r'\(.+\)|\S+', fstat.read())
cmd = fcmdline.read().split('\x00')[:-1]
ppid = stat[STAT_PPID]
tty = stat[STAT_TTY]
if tty == self_tty:
processes[pid] = Process(
args=tuple(cmd), pid=pid, ppid=ppid,
)
except IOError:
# Process has disappeared - just ignore it.
continue
return processes
| 528 |
1,276 | #include <iostream>
using namespace std;
/*
prime = sieve [2..] where
sieve (x:xs) = x : sieve (filter (\y ->y `rem` x /= 0) xs)
*/
template<int Number, typename T>
struct List
{
static const int Data = Number;
typedef T Next;
};
struct ListEnd
{
};
////////////////////////////////////
template<typename T, int Divider>
struct FilterOutDivisable
{
typedef void Result;
};
template<int Number, typename T, int Divider>
struct FilterOutDivisable<List<Number, T>, Divider>
{
template<bool Divisable>
struct Internal
{
};
template<>
struct Internal<true>
{
typedef typename FilterOutDivisable<T, Divider>::Result Result;
};
template<>
struct Internal<false>
{
typedef List<Number, typename FilterOutDivisable<T, Divider>::Result> Result;
};
typedef typename Internal<Number%Divider == 0>::Result Result;
};
template<int Divider>
struct FilterOutDivisable<ListEnd, Divider>
{
typedef ListEnd Result;
};
////////////////////////////////////
template<typename T>
struct Sieve
{
typedef void Result;
};
template<int Number, typename T>
struct Sieve<List<Number, T>>
{
typedef typename List<Number, typename Sieve<typename FilterOutDivisable<T, Number>::Result>::Result> Result;
};
template<>
struct Sieve<ListEnd>
{
typedef ListEnd Result;
};
////////////////////////////////////
template<typename T, int Counter>
struct Count
{
static const int Result = -1;
};
template<int Number, typename T>
struct Count<List<Number, T>, 1>
{
static const int Result = Number;
};
template<int Number, typename T, int Counter>
struct Count<List<Number, T>, Counter>
{
static const int Result = Count<T, Counter - 1>::Result;
};
////////////////////////////////////
template<int First, int Last>
struct Parameter
{
typedef typename List<First, typename Parameter<First + 1, Last>::Result> Result;
};
template<int Last>
struct Parameter<Last, Last>
{
typedef ListEnd Result;
};
struct Primes
{
// typedef Sieve<Parameter<2, 80000000>::Result>::Result Result;
typedef Sieve<Parameter<2, 100>::Result>::Result Result;
};
////////////////////////////////////
int main()
{
// cout << Count<Primes::Result, 4263116>::Result << endl;
cout << Count<Primes::Result, 1>::Result << endl;
cout << Count<Primes::Result, 2>::Result << endl;
cout << Count<Primes::Result, 3>::Result << endl;
cout << Count<Primes::Result, 4>::Result << endl;
cout << Count<Primes::Result, 5>::Result << endl;
cout << Count<Primes::Result, 6>::Result << endl;
cout << Count<Primes::Result, 7>::Result << endl;
cout << Count<Primes::Result, 8>::Result << endl;
cout << Count<Primes::Result, 9>::Result << endl;
cout << Count<Primes::Result, 10>::Result << endl;
return 0;
} | 934 |
319 | /**
* Copyright (c) 2012, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton 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.
*/
package org.openimaj.twitter.collection;
import java.io.BufferedInputStream;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Scanner;
import org.openimaj.io.ReadWriteable;
import org.openimaj.twitter.collection.StreamJSONStatusList.ReadableWritableJSON;
import org.openimaj.util.list.AbstractStreamBackedList;
import com.google.gson.Gson;
/**
* A list of json maps
* @author <NAME> (<EMAIL>)
*
*/
public class StreamJSONStatusList extends AbstractStreamBackedList<ReadableWritableJSON> {
/**
* a readable json hashmap
* @author <NAME> (<EMAIL>)
*
*/
public static class ReadableWritableJSON extends HashMap<String,Object> implements ReadWriteable{
/**
*
*/
private static final long serialVersionUID = 6001988896541110142L;
/**
*
*/
public ReadableWritableJSON() {
}
private transient Gson gson = new Gson();
@Override
public void readASCII(Scanner in) throws IOException {
if(in == null) return;
ReadableWritableJSON inner = gson.fromJson(in.nextLine(), ReadableWritableJSON.class);
for (java.util.Map.Entry<String, Object> entry: inner.entrySet()) {
this.put(entry.getKey(), entry.getValue());
}
}
@Override
public String asciiHeader() {
return "";
}
@Override
public void readBinary(DataInput in) throws IOException {
ReadableWritableJSON inner = gson.fromJson(in.readUTF(), ReadableWritableJSON.class);
for (java.util.Map.Entry<String, Object> entry: inner.entrySet()) {
this.put(entry.getKey(), entry.getValue());
}
}
@Override
public byte[] binaryHeader() {
return "".getBytes();
}
@Override
public void writeASCII(PrintWriter out) throws IOException {
gson.toJson(this, out);
}
@Override
public void writeBinary(DataOutput out) throws IOException {
out.writeUTF(gson.toJson(this));
}
}
protected StreamJSONStatusList(InputStream stream, int size,boolean isBinary, int headerLength, int recordLength,String charset) throws IOException{
super(stream, size, isBinary, headerLength, recordLength,ReadableWritableJSON.class,charset);
}
/**
* Construct a new StreamTwitterStatusList from the given input stream.
*
* @param stream the input stream
* @param nTweets of tweets to read from this stream
*
* @return a new list
* @throws IOException if an error occurs reading from the stream
*/
public static StreamJSONStatusList read(InputStream stream, int nTweets) throws IOException {
return read(new BufferedInputStream(stream), nTweets);
}
/**
* Construct a new StreamTwitterStatusList from the given input stream.
*
* @param stream the input stream
*
* @return a new list
* @throws IOException if an error occurs reading from the stream
*/
public static StreamJSONStatusList read(InputStream stream) throws IOException {
return read(new BufferedInputStream(stream), -1);
}
/**
* Construct a new StreamTwitterStatusList from the given input stream.
*
* @param stream the input stream
* @param nTweets of tweets to read from this stream
* @param charset
*
* @return a new list
* @throws IOException if an error occurs reading from the stream
*/
public static StreamJSONStatusList read(InputStream stream, int nTweets,String charset) throws IOException {
return read(new BufferedInputStream(stream), nTweets,charset);
}
/**
* Construct a new StreamTwitterStatusList from the given input stream.
*
* @param stream the input stream
* @param charset the charset of the underlying stream
*
* @return a new list
* @throws IOException if an error occurs reading from the stream
*/
public static StreamJSONStatusList read(InputStream stream, String charset) throws IOException {
return read(new BufferedInputStream(stream), -1,charset);
}
/**
* Construct a new StreamTwitterStatusList from the given input stream.
*
* @param stream the input stream
* @param nTweets of tweets to read from this stream
* @return a new list
* @throws IOException if an error occurs reading from the stream
*/
public static StreamJSONStatusList read(BufferedInputStream stream, int nTweets) throws IOException {
boolean isBinary = false;
//read header
int size = nTweets;
int headerLength = 0;
int recordLength = -1;
return new StreamJSONStatusList(stream, size, isBinary, headerLength, recordLength,"UTF-8");
}
/**
* Construct a new StreamTwitterStatusList from the given input stream.
*
* @param stream the input stream
* @param nTweets of tweets to read from this stream
* @param charset the charset to read the stream as
*
* @return a new list
* @throws IOException if an error occurs reading from the stream
*/
public static StreamJSONStatusList read(BufferedInputStream stream, int nTweets, String charset) throws IOException {
boolean isBinary = false;
//read header
int size = nTweets;
int headerLength = 0;
int recordLength = -1;
return new StreamJSONStatusList(stream, size, isBinary, headerLength, recordLength,charset);
}
}
| 2,067 |
562 | #include <symengine/constants.h>
#include <symengine/expression.h>
#include <symengine/integer.h>
#include <symengine/mul.h>
#include <iostream>
int main() {
SymEngine::Expression pi_by_12 =
SymEngine::div(SymEngine::pi, SymEngine::integer(12));
std::cout << pi_by_12 << std::endl;
return 0;
}
| 122 |
848 | <filename>tensorflow/contrib/boosted_trees/lib/learner/common/stats/gradient-stats.h
// Copyright 2017 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#ifndef TENSORFLOW_CONTRIB_BOOSTED_TREES_LIB_LEARNER_COMMON_STATS_GRADIENT_STATS_H_
#define TENSORFLOW_CONTRIB_BOOSTED_TREES_LIB_LEARNER_COMMON_STATS_GRADIENT_STATS_H_
#include <math.h>
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_util.h"
namespace tensorflow {
namespace boosted_trees {
namespace learner {
namespace stochastic {
const double kEps = 1e-6;
// A data structure for accumulating a Tensor value.
struct TensorStat {
TensorStat() {}
explicit TensorStat(const float v) : t(DT_FLOAT, TensorShape({1})) {
t.flat<float>()(0) = v;
}
explicit TensorStat(const Tensor& rt) : t(tensor::DeepCopy(rt)) {}
TensorStat(const TensorStat& ts) : t(tensor::DeepCopy(ts.t)) {}
TensorStat& operator+=(const TensorStat& other) {
if (t.NumElements() == 0) {
t = tensor::DeepCopy(other.t);
return (*this);
}
CHECK(t.shape() == other.t.shape())
<< "My shape = " << t.shape().DebugString()
<< " Other shape = " << other.t.shape().DebugString();
auto me_flat = t.unaligned_flat<float>();
auto other_flat = other.t.unaligned_flat<float>();
for (int i = 0; i < me_flat.size(); i++) {
me_flat(i) += other_flat(i);
}
return (*this);
}
TensorStat& operator-=(const TensorStat& other) {
if (other.t.NumElements() == 0) {
return (*this);
}
CHECK(t.shape() == other.t.shape())
<< "My shape = " << t.shape().DebugString()
<< " Other shape = " << other.t.shape().DebugString();
auto me_flat = t.unaligned_flat<float>();
auto other_flat = other.t.unaligned_flat<float>();
for (int i = 0; i < me_flat.size(); i++) {
me_flat(i) -= other_flat(i);
}
return (*this);
}
TensorStat& operator*=(float value) {
auto me_flat = t.unaligned_flat<float>();
for (size_t i = 0; i < me_flat.size(); i++) {
me_flat(i) *= value;
}
return (*this);
}
bool IsZero() const {
auto me_flat = t.unaligned_flat<float>();
for (int i = 0; i < me_flat.size(); i++) {
if (me_flat(i) != 0.0f) {
return false;
}
}
return true;
}
// Checks if the L^2 magnitude of the tensor is less than eps.
bool IsAlmostZero(const float eps = kEps) const {
auto me_flat = t.unaligned_flat<float>();
double s = 0.0;
for (int i = 0; i < me_flat.size(); i++) {
s += me_flat(i) * me_flat(i);
if (s > eps * eps) {
return false;
}
}
return true;
}
float Magnitude() const {
auto me_flat = t.unaligned_flat<float>();
double s = 0.0;
for (int i = 0; i < me_flat.size(); i++) {
s += me_flat(i) * me_flat(i);
}
return sqrt(s);
}
string DebugString() const { return t.DebugString(); }
Tensor t;
};
// GradientStats holds first and second order gradient stats.
struct GradientStats {
GradientStats() {}
// Legacy constructor for tests
GradientStats(float g, float h) : first(g), second(h) {}
GradientStats(const Tensor& g, const Tensor& h) : first(g), second(h) {}
GradientStats(const Tensor& g, const Tensor& h, int64 example_index)
: first(g.Slice(example_index, example_index + 1)),
second(h.Slice(example_index, example_index + 1)) {}
GradientStats& operator+=(const GradientStats& other) {
first += other.first;
second += other.second;
return (*this);
}
GradientStats& operator*=(float value) {
first *= value;
second *= value;
return (*this);
}
GradientStats& operator-=(const GradientStats& other) {
first -= other.first;
second -= other.second;
return (*this);
}
bool IsZero() const { return first.IsZero() && second.IsZero(); }
bool IsAlmostZero(const float eps = kEps) const {
return first.IsAlmostZero(eps) && second.IsAlmostZero(eps);
}
float Magnitude() const { return second.Magnitude(); }
string DebugString() const {
return "First = " + first.DebugString() +
" Second = " + second.DebugString();
}
TensorStat first;
TensorStat second;
};
struct GradientStatsAccumulator {
void operator()(const GradientStats& from, GradientStats* to) const {
(*to) += from;
}
};
inline GradientStats operator+(const GradientStats& a, const GradientStats& b) {
GradientStats ret(a);
ret += b;
return ret;
}
inline GradientStats operator-(const GradientStats& a, const GradientStats& b) {
GradientStats ret(a);
ret -= b;
return ret;
}
// Helper macro to check gradient stats approximate equality.
#define EXPECT_GRADIENT_STATS_EQ(val1, val2) \
EXPECT_TRUE((val1 - val2).IsAlmostZero());
} // namespace stochastic
} // namespace learner
} // namespace boosted_trees
} // namespace tensorflow
#endif // TENSORFLOW_CONTRIB_BOOSTED_TREES_LIB_LEARNER_COMMON_STATS_GRADIENT_STATS_H_
| 2,114 |
892 | package com.cronutils.model;
import com.cronutils.mapper.CronMapper;
import com.cronutils.model.definition.CronConstraint;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.field.CronField;
import com.cronutils.model.field.CronFieldName;
import com.cronutils.model.field.expression.visitor.ValidationFieldExpressionVisitor;
import com.cronutils.utils.Preconditions;
import java.util.*;
public class SingleCron implements Cron {
private static final long serialVersionUID = 7487370826825439098L;
private final CronDefinition cronDefinition;
private final Map<CronFieldName, CronField> fields;
private String asString;
/**
* Creates a Cron with the iven cron definition and the given fields.
* @param cronDefinition the definition to use for this Cron
* @param fields the fields that should be used
*/
public SingleCron(final CronDefinition cronDefinition, final List<CronField> fields) {
this.cronDefinition = Preconditions.checkNotNull(cronDefinition, "CronDefinition must not be null");
Preconditions.checkNotNull(fields, "CronFields cannot be null");
this.fields = new EnumMap<>(CronFieldName.class);
for (final CronField field : fields) {
this.fields.put(field.getField(), field);
}
}
/**
* Retrieve value for cron field.
*
* @param name - cron field name.
* If null, a NullPointerException will be raised.
* @return CronField that corresponds to given CronFieldName
*/
public CronField retrieve(final CronFieldName name) {
return fields.get(Preconditions.checkNotNull(name, "CronFieldName must not be null"));
}
/**
* Retrieve all cron field values as map.
*
* @return unmodifiable Map with key CronFieldName and values CronField, never null
*/
public Map<CronFieldName, CronField> retrieveFieldsAsMap() {
return Collections.unmodifiableMap(fields);
}
public String asString() {
if (asString == null) {
final ArrayList<CronField> temporaryFields = new ArrayList<>(fields.values());
temporaryFields.sort(CronField.createFieldComparator());
final StringBuilder builder = new StringBuilder();
for (final CronField field : temporaryFields) {
builder.append(String.format("%s ", field.getExpression().asString()));
}
asString = builder.toString().trim();
}
return asString;
}
public CronDefinition getCronDefinition() {
return cronDefinition;
}
/**
* Validates this Cron instance by validating its cron expression.
*
* @return this Cron instance
* @throws IllegalArgumentException if the cron expression is invalid
*/
public Cron validate() {
for (final Map.Entry<CronFieldName, CronField> field : retrieveFieldsAsMap().entrySet()) {
final CronFieldName fieldName = field.getKey();
field.getValue().getExpression().accept(
new ValidationFieldExpressionVisitor(getCronDefinition().getFieldDefinition(fieldName).getConstraints())
);
}
for (final CronConstraint constraint : getCronDefinition().getCronConstraints()) {
if (!constraint.validate(this)) {
throw new IllegalArgumentException(String.format("Invalid cron expression: %s. %s", asString(), constraint.getDescription()));
}
}
return this;
}
/**
* Provides means to compare if two cron expressions are equivalent.
*
* @param cronMapper - maps 'cron' parameter to this instance definition;
* @param cron - any cron instance, never null
* @return boolean - true if equivalent; false otherwise.
*/
public boolean equivalent(final CronMapper cronMapper, final Cron cron) {
return asString().equals(cronMapper.map(cron).asString());
}
/**
* Provides means to compare if two cron expressions are equivalent.
* Assumes same cron definition.
*
* @param cron - any cron instance, never null
* @return boolean - true if equivalent; false otherwise.
*/
public boolean equivalent(final Cron cron) {
return asString().equals(cron.asString());
}
}
| 1,606 |
1,350 | <filename>sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ByteBufferOutputStream.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
/**
* {@link ByteArrayOutputStream#toByteArray()} copied data and is inefficient.
* This class provides a {@link ByteBufferOutputStream#toByteArray()}
*/
public class ByteBufferOutputStream extends ByteArrayOutputStream {
public ByteBufferOutputStream(int size) {
super(size);
}
public ByteBufferOutputStream() {
super();
}
/**
* wraps the buffer used by this {@link ByteArrayOutputStream} to a ByteBuffer.
*
* This is more efficient than
* {@link ByteArrayOutputStream#toByteArray()} as it doesn't copy data.
* @return ByteBuffer
*/
public ByteBuffer asByteBuffer() {
return ByteBuffer.wrap(super.buf, 0, super.count);
}
}
| 345 |
575 | <filename>third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_named_constructor_2.cc
// 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.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/interface.cc.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_named_constructor_2.h"
#include <algorithm>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h"
#include "third_party/blink/renderer/platform/bindings/v8_private_property.h"
#include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h"
#include "third_party/blink/renderer/platform/wtf/get_ptr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo v8_test_interface_named_constructor_2_wrapper_type_info = {
gin::kEmbedderBlink,
V8TestInterfaceNamedConstructor2::DomTemplate,
nullptr,
"TestInterfaceNamedConstructor2",
nullptr,
WrapperTypeInfo::kWrapperTypeObjectPrototype,
WrapperTypeInfo::kObjectClassId,
WrapperTypeInfo::kNotInheritFromActiveScriptWrappable,
};
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in TestInterfaceNamedConstructor2.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// platform/bindings/ScriptWrappable.h.
const WrapperTypeInfo& TestInterfaceNamedConstructor2::wrapper_type_info_ = v8_test_interface_named_constructor_2_wrapper_type_info;
// not [ActiveScriptWrappable]
static_assert(
!std::is_base_of<ActiveScriptWrappableBase, TestInterfaceNamedConstructor2>::value,
"TestInterfaceNamedConstructor2 inherits from ActiveScriptWrappable<>, but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
static_assert(
std::is_same<decltype(&TestInterfaceNamedConstructor2::HasPendingActivity),
decltype(&ScriptWrappable::HasPendingActivity)>::value,
"TestInterfaceNamedConstructor2 is overriding hasPendingActivity(), but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
namespace test_interface_named_constructor_2_v8_internal {
} // namespace test_interface_named_constructor_2_v8_internal
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo v8_test_interface_named_constructor_2_constructor_wrapper_type_info = {
gin::kEmbedderBlink,
V8TestInterfaceNamedConstructor2Constructor::DomTemplate,
nullptr,
"TestInterfaceNamedConstructor2",
nullptr,
WrapperTypeInfo::kWrapperTypeObjectPrototype,
WrapperTypeInfo::kObjectClassId,
WrapperTypeInfo::kNotInheritFromActiveScriptWrappable,
};
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic pop
#endif
static void V8TestInterfaceNamedConstructor2ConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestInterfaceNamedConstructor2_ConstructorCallback");
if (!info.IsConstructCall()) {
V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::ConstructorNotCallableAsFunction("Audio"));
return;
}
if (ConstructorMode::Current(info.GetIsolate()) == ConstructorMode::kWrapExistingObject) {
V8SetReturnValue(info, info.Holder());
return;
}
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToConstruct("TestInterfaceNamedConstructor2", ExceptionMessages::NotEnoughArguments(1, info.Length())));
return;
}
V8StringResource<> string_arg;
string_arg = info[0];
if (!string_arg.Prepare())
return;
TestInterfaceNamedConstructor2* impl = TestInterfaceNamedConstructor2::CreateForJSConstructor(string_arg);
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->AssociateWithWrapper(info.GetIsolate(), V8TestInterfaceNamedConstructor2Constructor::GetWrapperTypeInfo(), wrapper);
V8SetReturnValue(info, wrapper);
}
v8::Local<v8::FunctionTemplate> V8TestInterfaceNamedConstructor2Constructor::DomTemplate(
v8::Isolate* isolate, const DOMWrapperWorld& world) {
static int dom_template_key; // This address is used for a key to look up the dom template.
V8PerIsolateData* data = V8PerIsolateData::From(isolate);
v8::Local<v8::FunctionTemplate> result =
data->FindInterfaceTemplate(world, &dom_template_key);
if (!result.IsEmpty())
return result;
result = v8::FunctionTemplate::New(isolate, V8TestInterfaceNamedConstructor2ConstructorCallback);
v8::Local<v8::ObjectTemplate> instance_template = result->InstanceTemplate();
instance_template->SetInternalFieldCount(V8TestInterfaceNamedConstructor2::kInternalFieldCount);
result->SetClassName(V8AtomicString(isolate, "Audio"));
result->Inherit(V8TestInterfaceNamedConstructor2::DomTemplate(isolate, world));
data->SetInterfaceTemplate(world, &dom_template_key, result);
return result;
}
void V8TestInterfaceNamedConstructor2Constructor::NamedConstructorAttributeGetter(
v8::Local<v8::Name> property_name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::Local<v8::Context> creationContext = info.Holder()->CreationContext();
V8PerContextData* per_context_data = V8PerContextData::From(creationContext);
if (!per_context_data) {
// TODO(yukishiino): Return a valid named constructor even after the context is detached
return;
}
v8::Local<v8::Function> named_constructor =
per_context_data->ConstructorForType(V8TestInterfaceNamedConstructor2Constructor::GetWrapperTypeInfo());
// Set the prototype of named constructors to the regular constructor.
static const V8PrivateProperty::SymbolKey kPrivatePropertyInitialized;
auto private_property =
V8PrivateProperty::GetSymbol(
info.GetIsolate(), kPrivatePropertyInitialized);
v8::Local<v8::Context> current_context = info.GetIsolate()->GetCurrentContext();
v8::Local<v8::Value> private_value;
if (!private_property.GetOrUndefined(named_constructor).ToLocal(&private_value) ||
private_value->IsUndefined()) {
v8::Local<v8::Function> interface =
per_context_data->ConstructorForType(V8TestInterfaceNamedConstructor2::GetWrapperTypeInfo());
v8::Local<v8::Value> interface_prototype =
interface->Get(current_context, V8AtomicString(info.GetIsolate(), "prototype"))
.ToLocalChecked();
// https://heycam.github.io/webidl/#named-constructors
// 8. Perform ! DefinePropertyOrThrow(F, "prototype",
// PropertyDescriptor{[[Value]]: proto, [[Writable]]: false,
// [[Enumerable]]: false,
// [Configurable]]: false}).
const v8::PropertyAttribute prototype_attributes =
static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum | v8::DontDelete);
bool result = named_constructor->DefineOwnProperty(
current_context, V8AtomicString(info.GetIsolate(), "prototype"),
interface_prototype, prototype_attributes).ToChecked();
CHECK(result);
private_property.Set(named_constructor, v8::True(info.GetIsolate()));
}
V8SetReturnValue(info, named_constructor);
}
static void InstallV8TestInterfaceNamedConstructor2Template(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
// Initialize the interface object's template.
V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interface_template, V8TestInterfaceNamedConstructor2::GetWrapperTypeInfo()->interface_name, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceNamedConstructor2::kInternalFieldCount);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
// Custom signature
V8TestInterfaceNamedConstructor2::InstallRuntimeEnabledFeaturesOnTemplate(
isolate, world, interface_template);
}
void V8TestInterfaceNamedConstructor2::InstallRuntimeEnabledFeaturesOnTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
// Custom signature
}
v8::Local<v8::FunctionTemplate> V8TestInterfaceNamedConstructor2::DomTemplate(
v8::Isolate* isolate, const DOMWrapperWorld& world) {
return V8DOMConfiguration::DomClassTemplate(
isolate, world, const_cast<WrapperTypeInfo*>(V8TestInterfaceNamedConstructor2::GetWrapperTypeInfo()),
InstallV8TestInterfaceNamedConstructor2Template);
}
bool V8TestInterfaceNamedConstructor2::HasInstance(v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->HasInstance(V8TestInterfaceNamedConstructor2::GetWrapperTypeInfo(), v8_value);
}
v8::Local<v8::Object> V8TestInterfaceNamedConstructor2::FindInstanceInPrototypeChain(
v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain(
V8TestInterfaceNamedConstructor2::GetWrapperTypeInfo(), v8_value);
}
TestInterfaceNamedConstructor2* V8TestInterfaceNamedConstructor2::ToImplWithTypeCheck(
v8::Isolate* isolate, v8::Local<v8::Value> value) {
return HasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
}
} // namespace blink
| 3,899 |
326 | <gh_stars>100-1000
"""
Tests for grdfill.
"""
import os
import numpy as np
import pytest
import xarray as xr
from pygmt import grdfill, load_dataarray
from pygmt.datasets import load_earth_relief
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers import GMTTempFile
@pytest.fixture(scope="module", name="grid")
def fixture_grid():
"""
Load the grid data from the sample earth_relief file and set value(s) to
NaN.
"""
grid = load_earth_relief(registration="pixel", region=[125, 130, -25, -20])
grid[2:4, 1:3] = np.nan
grid[0:2, 2:4] = np.inf
return grid
@pytest.fixture(scope="module", name="expected_grid")
def fixture_grid_result():
"""
Load the expected grdfill grid result.
"""
return xr.DataArray(
data=[
[442.5, 439.0, np.inf, np.inf, 508.0],
[393.0, 364.5, np.inf, np.inf, 506.5],
[362.0, 20.0, 20.0, 373.5, 402.5],
[321.5, 20.0, 20.0, 356.0, 422.5],
[282.5, 318.0, 326.5, 379.5, 383.5],
],
coords=dict(
lon=[125.5, 126.5, 127.5, 128.5, 129.5],
lat=[-24.5, -23.5, -22.5, -21.5, -20.5],
),
dims=["lat", "lon"],
)
def test_grdfill_dataarray_out(grid, expected_grid):
"""
Test grdfill with a DataArray output.
"""
result = grdfill(grid=grid, mode="c20")
# check information of the output grid
assert isinstance(result, xr.DataArray)
assert result.gmt.gtype == 1 # Geographic grid
assert result.gmt.registration == 1 # Pixel registration
# check information of the output grid
xr.testing.assert_allclose(a=result, b=expected_grid)
def test_grdfill_file_out(grid, expected_grid):
"""
Test grdfill with an outgrid set.
"""
with GMTTempFile(suffix=".nc") as tmpfile:
result = grdfill(grid=grid, mode="c20", outgrid=tmpfile.name)
assert result is None # return value is None
assert os.path.exists(path=tmpfile.name) # check that outgrid exists
temp_grid = load_dataarray(tmpfile.name)
xr.testing.assert_allclose(a=temp_grid, b=expected_grid)
def test_grdfill_required_args(grid):
"""
Test that grdfill fails without arguments for `mode` and `L`.
"""
with pytest.raises(GMTInvalidInput):
grdfill(grid=grid)
| 1,027 |
3,269 | <filename>Algo and DSA/LeetCode-Solutions-master/Python/count-the-repetitions.py
# Time: O(s1 * min(s2, n1))
# Space: O(s2)
class Solution(object):
def getMaxRepetitions(self, s1, n1, s2, n2):
"""
:type s1: str
:type n1: int
:type s2: str
:type n2: int
:rtype: int
"""
repeat_count = [0] * (len(s2)+1)
lookup = {}
j, count = 0, 0
for k in xrange(1, n1+1):
for i in xrange(len(s1)):
if s1[i] == s2[j]:
j = (j + 1) % len(s2)
count += (j == 0)
if j in lookup: # cyclic
i = lookup[j]
prefix_count = repeat_count[i]
pattern_count = (count - repeat_count[i]) * ((n1 - i) // (k - i))
suffix_count = repeat_count[i + (n1 - i) % (k - i)] - repeat_count[i]
return (prefix_count + pattern_count + suffix_count) / n2
lookup[j] = k
repeat_count[k] = count
return repeat_count[n1] / n2 # not cyclic iff n1 <= s2
| 618 |
335 | {
"word": "Campus",
"definitions": [
"The grounds and buildings of a university or college.",
"The grounds of a school, hospital, or other institution."
],
"parts-of-speech": "Noun"
} | 83 |
383 | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2018, Locus Robotics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <fuse_core/async_publisher.h>
#include <ros/ros.h>
#include <gtest/gtest.h>
#include <set>
/**
* @brief Derived AsyncPublisher used to verify the functions get called when expected
*/
class MyPublisher : public fuse_core::AsyncPublisher
{
public:
MyPublisher() :
fuse_core::AsyncPublisher(1),
callback_processed(false),
initialized(false)
{
}
virtual ~MyPublisher() = default;
void notifyCallback(
fuse_core::Transaction::ConstSharedPtr /*transaction*/,
fuse_core::Graph::ConstSharedPtr /*graph*/)
{
ros::Duration(1.0).sleep();
callback_processed = true;
}
void onInit() override
{
initialized = true;
}
bool callback_processed;
bool initialized;
};
TEST(AsyncPublisher, OnInit)
{
MyPublisher publisher;
publisher.initialize("my_publisher");
EXPECT_TRUE(publisher.initialized);
}
TEST(AsyncPublisher, notifyCallback)
{
MyPublisher publisher;
publisher.initialize("my_publisher");
// Execute the notify() method in this thread. This should push a call to MyPublisher::notifyCallback()
// into MyPublisher's callback queue, which will get executed by MyPublisher's async spinner.
// There is a time delay there. So, this call should return almost immediately, then we have to wait
// a bit before the "callback_processed" flag gets flipped.
fuse_core::Transaction::ConstSharedPtr transaction; // nullptr...which is fine because we do not actually use it
fuse_core::Graph::ConstSharedPtr graph; // nullptr...which is fine because we do not actually use it
publisher.notify(transaction, graph);
EXPECT_FALSE(publisher.callback_processed);
ros::Time wait_time_elapsed = ros::Time::now() + ros::Duration(10.0);
while (!publisher.callback_processed && ros::Time::now() < wait_time_elapsed)
{
ros::Duration(0.1).sleep();
}
EXPECT_TRUE(publisher.callback_processed);
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "test_async_publisher");
ros::AsyncSpinner spinner(1);
spinner.start();
int ret = RUN_ALL_TESTS();
spinner.stop();
ros::shutdown();
return ret;
}
| 1,188 |
468 |
#ifndef __GLI_BITMAP_NOTEBOOK_H_
#define __GLI_BITMAP_NOTEBOOK_H_
#include <wx/wx.h>
#include <wx/notebook.h>
#include "GLIShaderDebug.h"
class GLIBitmapView;
//DT_TODO: Class/ comment checks
//@
// Summary:
// This class provides a notebook of bitmap images.
//
class GLIBitmapNotebook: public wxNotebook
{
DECLARE_EVENT_TABLE()
public:
enum ToolState
{
TS_Select, // Select a debug pixel tool
TS_Zoom // Zoom image tool
};
enum ImageFlags
{
IF_RED = (1 << 0), // Display red channel
IF_GREEN = (1 << 1), // Display green channel
IF_BLUE = (1 << 2), // Display blue channel
IF_ALPHA = (1 << 3), // Display alpha channel
IF_RGB = (IF_RED | IF_GREEN | IF_BLUE) // Combined red/green/blue
};
enum ImageState
{
IS_PreImage, // Display pre render image
IS_PostImage, // Display post render image
IS_DiffImage, // Display diff image
};
//@
// Summary:
// Constructor.
//
GLIBitmapNotebook(GLIShaderDebug *parentControl,
wxWindow* parent, wxWindowID id,
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = 0, const wxString& name = wxNotebookNameStr);
void AddBitmapPage(const FrameBufferData & newData);
void ResetAllPages();
// Get the zoom scale for displaying bitmaps
inline void GetZoomScale(uint &retScaleMultiply, uint &retScaleDivide) const;
// Get the current displayed image size
wxSize GetImageSize() const;
void SetToolState(ToolState newState);
inline ToolState GetToolState();
void SetImageDisplay(uint flags, ImageState newState, bool newNormalize);
inline uint GetImageFlags() const;
inline ImageState GetImageState() const;
inline bool GetImageNormalized() const;
void OnBitmapLeftClick(const wxPoint &bitmapPos);
void OnBitmapRightClick(const wxPoint &bitmapPos);
// Get the current bitmap selection coordinates. Negative if invalid
inline wxPoint GetBitmapSelectPoint() const;
// To set the new bitmap selection point
void SetSelectedPosition(const wxPoint &newPos);
// Get the current bitmap point data in a display string
wxString GetBitmapValueString() const;
// Get the display string for the currently selected point
inline const wxString & GetSelectPointString() const;
// Set if displying ints or floats
inline void SetValueTextFormat(bool displayInts);
// Get if displying ints or floats
inline bool GetValueTextFormat() const;
protected:
GLIShaderDebug *parentControl; // The controlling parent
std::vector<GLIBitmapView*> bitmapViews; // The array of bitmap views of the render buffers (contained within bitmapNotebook);
int preferedBufferTypeID; // The prefered selection buffer ID
int preferedDrawBufferID; // The prefered draw buffer ID
uint viewScaleMultiply; // The multiply part of the bitmap scale function
uint viewScaleDivide; // The divide part of the bitmap scale function
wxPoint selectPos; // The bitmap selection coordinates
ToolState toolState; // The current tool
uint imageFlags; // The render flags for the image display
ImageState imageState; // The state of the current image to render
bool imageNormalized; // The flag indicating if the image display should be "normalized".
bool valueTextFormatInts; // If displaying values in strings as ints or floats
//@
// Summary:
// Callback events to handle changes.
//
void OnPageChange(wxNotebookEvent &event);
//@
// Summary:
// To calculate a display name for the passed buffer
//
// Parameters:
// bufferData - The buffer to calculate a display name for.
//
// Returns:
// A display name is returned.
//
wxString GetBufferDisplayName(const FrameBufferData &bufferData) const;
//@
// Summary:
// To update the cursor display on the passed window to mat the current
// tool state.
//
// Parameters:
// updateWindow - The window to set the cursor on.
//
void UpdateCursorDisplay(wxWindow *updateWindow) const;
//@
// Summary:
// To zoom the contained bitmaps.
//
// Parameters:
// zoomIn - If zooming in or out.
//
// bitmapPos - The bitmap point to focus the zoom on.
//
void ZoomBitmap(bool zoomIn, const wxPoint &bitmapPos);
};
///////////////////////////////////////////////////////////////////////////////
//
inline GLIBitmapNotebook::ToolState GLIBitmapNotebook::GetToolState()
{
return toolState;
}
///////////////////////////////////////////////////////////////////////////////
//
inline uint GLIBitmapNotebook::GetImageFlags() const
{
return imageFlags;
}
///////////////////////////////////////////////////////////////////////////////
//
inline GLIBitmapNotebook::ImageState GLIBitmapNotebook::GetImageState() const
{
return imageState;
}
///////////////////////////////////////////////////////////////////////////////
//
inline bool GLIBitmapNotebook::GetImageNormalized() const
{
return imageNormalized;
}
///////////////////////////////////////////////////////////////////////////////
//
inline wxPoint GLIBitmapNotebook::GetBitmapSelectPoint() const
{
return selectPos;
}
///////////////////////////////////////////////////////////////////////////////
//
inline void GLIBitmapNotebook::GetZoomScale(uint &retScaleMultiply, uint &retScaleDivide) const
{
retScaleMultiply = viewScaleMultiply;
retScaleDivide = viewScaleDivide;
}
///////////////////////////////////////////////////////////////////////////////
//
void GLIBitmapNotebook::SetValueTextFormat(bool displayInts)
{
// Check if the state changed
if(valueTextFormatInts != displayInts)
{
valueTextFormatInts = displayInts;
// Update the selected color to the new display format
parentControl->UpdateSelectedColor();
}
}
///////////////////////////////////////////////////////////////////////////////
//
bool GLIBitmapNotebook::GetValueTextFormat() const
{
return valueTextFormatInts;
}
#endif // __GLI_BITMAP_NOTEBOOK_H_
| 2,118 |
1,091 | <filename>apps/openstackvtap/app/src/main/java/org/onosproject/openstackvtap/cli/OpenstackVtapListCommand.java<gh_stars>1000+
/*
* Copyright 2018-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.openstackvtap.cli;
import com.google.common.collect.ImmutableSet;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Completion;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.net.DeviceId;
import org.onosproject.openstacknode.api.OpenstackNode;
import org.onosproject.openstacknode.api.OpenstackNodeService;
import org.onosproject.openstackvtap.api.OpenstackVtap;
import org.onosproject.openstackvtap.api.OpenstackVtapService;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static org.onosproject.openstackvtap.util.OpenstackVtapUtil.getVtapTypeFromString;
/**
* Lists openstack vtap rules.
*/
@Service
@Command(scope = "onos", name = "openstack-vtap-list",
description = "OpenstackVtap list")
public class OpenstackVtapListCommand extends AbstractShellCommand {
private final OpenstackVtapService vtapService = get(OpenstackVtapService.class);
private final OpenstackNodeService osNodeService = get(OpenstackNodeService.class);
@Argument(index = 0, name = "type",
description = "vtap type [any|all|rx|tx]",
required = false, multiValued = false)
@Completion(VtapTypeCompleter.class)
String vtapType = "any";
private static final String FORMAT = "ID { %s }: type [%s], srcIP [%s], dstIP [%s]";
private static final String FORMAT_TX_NODES = " tx openstack nodes: %s";
private static final String FORMAT_RX_NODES = " rx openstack nodes: %s";
@Override
protected void doExecute() {
OpenstackVtap.Type type = getVtapTypeFromString(vtapType);
Set<OpenstackVtap> openstackVtaps = vtapService.getVtaps(type);
for (OpenstackVtap vtap : openstackVtaps) {
print(FORMAT,
vtap.id().toString(),
vtap.type().toString(),
vtap.vtapCriterion().srcIpPrefix().toString(),
vtap.vtapCriterion().dstIpPrefix().toString());
print(FORMAT_TX_NODES, osNodeNames(vtap.txDeviceIds()));
print(FORMAT_RX_NODES, osNodeNames(vtap.rxDeviceIds()));
}
}
private Set<String> osNodeNames(Set<DeviceId> deviceIds) {
if (deviceIds == null) {
return ImmutableSet.of();
} else {
return deviceIds.parallelStream()
.map(osNodeService::node)
.filter(Objects::nonNull)
.map(OpenstackNode::hostname)
.collect(Collectors.toSet());
}
}
}
| 1,338 |
5,422 | <filename>core/controllers/blog_admin.py
# Copyright 2021 The Oppia 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.
"""Controllers for the blog admin page"""
from __future__ import annotations
import logging
from core import feconf
from core.controllers import acl_decorators
from core.controllers import base
from core.controllers import domain_objects_validator as validation_method
from core.domain import blog_services
from core.domain import config_domain
from core.domain import config_services
from core.domain import role_services
from core.domain import user_services
BLOG_POST_EDITOR = feconf.ROLE_ID_BLOG_POST_EDITOR
BLOG_ADMIN = feconf.ROLE_ID_BLOG_ADMIN
class BlogAdminPage(base.BaseHandler):
"""Blog Admin Page Handler to render the frontend template."""
URL_PATH_ARGS_SCHEMAS = {}
HANDLER_ARGS_SCHEMAS = {
'GET': {}
}
@acl_decorators.can_access_blog_admin_page
def get(self):
"""Handles GET requests."""
self.render_template('blog-admin-page.mainpage.html')
class BlogAdminHandler(base.BaseHandler):
"""Handler for the blog admin page."""
GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON
URL_PATH_ARGS_SCHEMAS = {}
HANDLER_ARGS_SCHEMAS = {
'GET': {},
'POST': {
'action': {
'schema': {
'type': 'basestring',
'choices': [
'save_config_properties', 'revert_config_property']
}
},
'new_config_property_values': {
'schema': {
'type': 'object_dict',
'validation_method': (
validation_method.validate_new_config_property_values),
},
'default_value': None
},
'config_property_id': {
'schema': {
'type': 'basestring',
},
'default_value': None
},
}
}
@acl_decorators.can_access_blog_admin_page
def get(self) -> None:
"""Handles GET requests."""
config_properties = config_domain.Registry.get_config_property_schemas()
config_prop_for_blog_admin = {
'list_of_default_tags_for_blog_post': (
config_properties['list_of_default_tags_for_blog_post']),
'max_number_of_tags_assigned_to_blog_post': (
config_properties['max_number_of_tags_assigned_to_blog_post'])
}
role_to_action = role_services.get_role_actions()
self.render_json({
'config_properties': config_prop_for_blog_admin,
'role_to_actions': {
BLOG_POST_EDITOR: role_to_action[BLOG_POST_EDITOR],
BLOG_ADMIN: role_to_action[BLOG_ADMIN]
},
'updatable_roles': {
BLOG_POST_EDITOR: (
role_services.HUMAN_READABLE_ROLES[BLOG_POST_EDITOR]),
BLOG_ADMIN: role_services.HUMAN_READABLE_ROLES[BLOG_ADMIN]
}
})
@acl_decorators.can_access_blog_admin_page
def post(self) -> None:
"""Handles POST requests."""
result = {}
if self.normalized_payload.get(
'action') == 'save_config_properties':
new_config_property_values = self.normalized_payload.get(
'new_config_property_values')
for (name, value) in new_config_property_values.items():
config_services.set_property(self.user_id, name, value)
logging.info(
'[BLOG ADMIN] %s saved config property values: %s' %
(self.user_id, new_config_property_values))
elif self.normalized_payload.get(
'action') == 'revert_config_property':
config_property_id = (
self.normalized_payload.get('config_property_id'))
config_services.revert_property(
self.user_id, config_property_id)
logging.info(
'[BLOG ADMIN] %s reverted config property: %s' %
(self.user_id, config_property_id))
self.render_json(result)
class BlogAdminRolesHandler(base.BaseHandler):
"""Handler for the blog admin page."""
GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON
URL_PATH_ARGS_SCHEMAS = {}
HANDLER_ARGS_SCHEMAS = {
'POST': {
'role': {
'schema': {
'type': 'basestring',
'choices': [BLOG_ADMIN, BLOG_POST_EDITOR]
}
},
'username': {
'schema': {
'type': 'basestring'
}
},
},
'PUT': {
'username': {
'schema': {
'type': 'basestring'
}
},
}
}
@acl_decorators.can_manage_blog_post_editors
def post(self) -> None:
"""Handles POST requests."""
username = self.normalized_payload.get('username')
role = self.normalized_payload.get('role')
user_id = user_services.get_user_id_from_username(username)
if user_id is None:
raise self.InvalidInputException(
'User with given username does not exist.')
user_services.add_user_role(user_id, role)
role_services.log_role_query(
self.user_id, feconf.ROLE_ACTION_ADD, role=role,
username=username)
self.render_json({})
@acl_decorators.can_manage_blog_post_editors
def put(self) -> None:
"""Handles PUT requests."""
username = self.normalized_payload.get('username')
user_id = user_services.get_user_id_from_username(username)
if user_id is None:
raise self.InvalidInputException(
'Invalid username: %s' % username)
user_services.remove_user_role(user_id, feconf.ROLE_ID_BLOG_POST_EDITOR)
blog_services.deassign_user_from_all_blog_posts(user_id)
self.render_json({})
| 3,172 |
4,350 | package cc.mrbird.febs.system.service.impl;
import cc.mrbird.febs.system.entity.RoleMenu;
import cc.mrbird.febs.system.mapper.RoleMenuMapper;
import cc.mrbird.febs.system.service.IRoleMenuService;
import cc.mrbird.febs.system.service.IUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author MrBird
*/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {
private final IUserRoleService userRoleService;
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteRoleMenusByRoleId(List<String> roleIds) {
baseMapper.delete(new QueryWrapper<RoleMenu>().lambda().in(RoleMenu::getRoleId, roleIds));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteRoleMenusByMenuId(List<String> menuIds) {
baseMapper.delete(new QueryWrapper<RoleMenu>().lambda().in(RoleMenu::getMenuId, menuIds));
}
@Override
public Set<Long> findUserIdByMenuIds(List<String> menuIds) {
List<RoleMenu> roleMenus = baseMapper.selectList(new QueryWrapper<RoleMenu>().lambda().in(RoleMenu::getMenuId, menuIds));
if (CollectionUtils.isNotEmpty(roleMenus)) {
List<String> roleIds = roleMenus.stream().map(RoleMenu::getRoleId)
.map(String::valueOf)
.collect(Collectors.toList());
return userRoleService.findUserIdByRoleIds(roleIds);
}
return null;
}
}
| 756 |
14,668 | <filename>ios/chrome/browser/ui/first_run/welcome/checkbox_button.h
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_FIRST_RUN_WELCOME_CHECKBOX_BUTTON_H_
#define IOS_CHROME_BROWSER_UI_FIRST_RUN_WELCOME_CHECKBOX_BUTTON_H_
#import <UIKit/UIKit.h>
// A UIButton subclass for displaying a potentially multi-line label and a
// checkmark image that can be selected and deselected on button tap. The
// checkmark is right-aligned when in LTR and left-aligned when in RTL.
@interface CheckboxButton : UIButton
// String to use for the button's label.
@property(nonatomic, copy) NSString* labelText;
- (instancetype)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE;
@end
#endif // IOS_CHROME_BROWSER_UI_FIRST_RUN_WELCOME_CHECKBOX_BUTTON_H_
| 357 |
852 | <reponame>Purva-Chaudhari/cmssw
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/global/EDAnalyzer.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/StreamID.h"
#include <string>
namespace edmtest {
class UTC_Q1 : public edm::global::EDAnalyzer<> {
public:
explicit UTC_Q1(edm::ParameterSet const& p) {
identifier = p.getUntrackedParameter<int>("identifier", 99);
edm::GroupLogStatistics("timer"); // these lines would normally be in
edm::GroupLogStatistics("trace"); // whatever service knows that
// timer and trace should be groupd
// by moduels for statistics
}
void analyze(edm::StreamID, edm::Event const&, edm::EventSetup const&) const override;
private:
int identifier;
};
void UTC_Q1::analyze(edm::StreamID, edm::Event const&, edm::EventSetup const&) const {
edm::LogInfo("cat_A") << "Q1 with identifier " << identifier;
edm::LogInfo("timer") << "Q1 timer with identifier " << identifier;
edm::LogInfo("trace") << "Q1 trace with identifier " << identifier;
}
class UTC_Q2 : public edm::global::EDAnalyzer<> {
public:
explicit UTC_Q2(edm::ParameterSet const& p) { identifier = p.getUntrackedParameter<int>("identifier", 98); }
void analyze(edm::StreamID, edm::Event const&, edm::EventSetup const&) const override;
private:
int identifier;
};
void UTC_Q2::analyze(edm::StreamID, edm::Event const&, edm::EventSetup const&) const {
edm::LogInfo("cat_A") << "Q2 with identifier " << identifier;
edm::LogInfo("timer") << "Q2 timer with identifier " << identifier;
edm::LogInfo("trace") << "Q2 trace with identifier " << identifier;
}
} // namespace edmtest
using edmtest::UTC_Q1;
using edmtest::UTC_Q2;
DEFINE_FWK_MODULE(UTC_Q1);
DEFINE_FWK_MODULE(UTC_Q2);
| 784 |
1,882 | /*-
* <<
* task
* ==
* Copyright (C) 2019 - 2020 sia
* ==
* 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.sia.task.scheduler.job.triggers;
import com.sia.task.core.util.Constant;
import com.sia.task.core.util.DateFormatHelper;
import com.sia.task.quartz.core.SimpleScheduleBuilder;
import com.sia.task.quartz.job.trigger.Trigger;
import com.sia.task.quartz.job.trigger.TriggerBuilder;
import java.text.ParseException;
import java.util.Date;
/**
* @author: MAOZW
* @Description: FixRepeatTriggerImpl
* @date 2018/4/1910:21
*/
public class RepeatTriggerImpl extends AbstractTrigger {
private int repeatInterval;
private int setRepeatCount = 0;
private Date startTime;
private RepeatTriggerImpl(Date startTime, int setRepeatCount, int repeatInterval) {
this.repeatInterval = repeatInterval;
this.setRepeatCount = setRepeatCount;
this.startTime = startTime;
}
public RepeatTriggerImpl() {
}
/**
* triggerBuild
*
* @param jobName
* @param jobGroup
* @return
*/
public Trigger triggerBuild(String jobName, String jobGroup) {
Trigger trigger;
SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
simpleScheduleBuilder.withIntervalInSeconds(repeatInterval);
if (setRepeatCount > 0) {
simpleScheduleBuilder.withMisfireHandlingInstructionIgnoreMisfires();
simpleScheduleBuilder.withRepeatCount(setRepeatCount);
} else {
simpleScheduleBuilder.repeatForever();
}
trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).startAt(startTime).withSchedule(simpleScheduleBuilder).build();
return trigger;
}
private static Trigger buildFixRepeatTrigger(String jobKey, String jobGroup, String triggerValue) {
String[] triggerValues = triggerValue.split(Constant.REGEX_COMMA);
if (triggerValues.length == 0) {
throw new IndexOutOfBoundsException(Constant.LOG_PREFIX
+ "The trigger type of the current job is : TRIGGER_TYPE_FIXRATE ,but trigerValue.split(,).length is zero");
}
Date startTime;
try {
startTime = DateFormatHelper.parse(triggerValues[0]);
} catch (ParseException e) {
throw new IllegalArgumentException("The time format must be : yyyy-MM-dd HH:mm:ss");
}
int repeatCount = Integer.valueOf(triggerValues[1]);
int repeatInterval = Integer.valueOf(triggerValues[2]);
return new RepeatTriggerImpl(startTime, repeatCount, repeatInterval).triggerBuild(jobKey, jobGroup);
}
/**
*
* @param jobKey
* @param jobGroup
* @param triggerType
* @param triggerValue
* @return
*/
@Override
public Trigger build(String jobKey, String jobGroup, String triggerType, String triggerValue) {
return buildFixRepeatTrigger(jobKey, jobGroup, triggerValue);
}
}
| 1,264 |
5,169 | <gh_stars>1000+
{
"name": "CommunicationLib",
"version": "0.3.0",
"summary": "Call native communication package.",
"description": "One line of code calls a native communication package.",
"homepage": "https://github.com/ReverseScale/CommunicationLib",
"license": "MIT",
"authors": {
"ReverseScale": "<EMAIL>"
},
"source": {
"git": "https://github.com/ReverseScale/CommunicationLib.git",
"tag": "0.3.0"
},
"platforms": {
"ios": "8.0"
},
"source_files": "CommunicationLib/Classes/**/*"
}
| 201 |
665 | #
# generate_test.py
# Mich, 2016-06-16
# This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved.
#
import argparse
import subprocess
import datetime
import os
template = """#
# {filename}
# {author}, {date}
# This file is part of MLDB. Copyright {year} mldb.ai inc. All rights reserved.
#
from mldb import mldb, MldbUnitTest, ResponseException
class {classname}(MldbUnitTest): # noqa
@classmethod
def setUpClass(cls):
pass
def test_it(self):
pass
if __name__ == '__main__':
mldb.run_tests()"""
def get_filename_from_args():
parser = argparse.ArgumentParser(description=
"Create a test file skeleton and create the entry in the makefile.")
parser.add_argument('filename', help="The filename to create.")
args = parser.parse_args()
filename = args.filename
if not filename.endswith('.py'):
filename += '.py'
if os.path.isfile(filename):
raise Exception("File already exists")
return filename
def get_class_from_filename(filename):
capitalize_next = True
classname = ''
for c in filename:
if c == '.':
break
if c in ['_', '-']:
capitalize_next = True
else:
if capitalize_next:
classname += c.capitalize()
capitalize_next = False
else:
classname += c
return classname
def update_makefile(filename):
for mk_file, pro in [('testing.mk', False), ('pro_testing.mk', True)]:
if os.path.isfile(mk_file):
f = open(mk_file, 'at+')
break
else:
raise Exception("*.mk not found")
f.seek(-1, 2) # seek post last char
last_char = f.read()
if last_char != '\n':
f.write('\n')
if pro:
f.write("$(eval $(call mldb_unit_test,{},pro))"
.format(filename))
else:
f.write("$(eval $(call mldb_unit_test,{}))".format(filename))
f.close()
def do_it():
filename = get_filename_from_args()
author = \
subprocess.check_output(['git', 'config', '--get', 'user.name'])[:-1]
now = datetime.datetime.now().isoformat()
classname = get_class_from_filename(filename)
update_makefile(filename)
# create test file
f = open(filename, 'wt')
f.write(template.format(filename=filename,
author=author,
date=now[:10],
year=now[:4],
classname=classname))
f.close()
if __name__ == '__main__':
do_it()
| 1,169 |
839 | /**
* 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.cxf.ws.policy.builder.primitive;
import java.util.Collection;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
import org.apache.neethi.Assertion;
import org.apache.neethi.AssertionBuilderFactory;
import org.apache.neethi.builders.AssertionBuilder;
public class PrimitiveAssertionBuilder implements AssertionBuilder<Element> {
private QName[] knownElements = {};
public PrimitiveAssertionBuilder() {
}
public PrimitiveAssertionBuilder(Collection<QName> els) {
knownElements = els.toArray(new QName[0]);
}
public PrimitiveAssertionBuilder(QName[] els) {
knownElements = els;
}
public Assertion build(Element element, AssertionBuilderFactory fact) {
return new PrimitiveAssertion(element);
}
public QName[] getKnownElements() {
return knownElements;
}
public void setKnownElements(Collection<QName> k) {
knownElements = k.toArray(new QName[0]);
}
public void setKnownElements(QName[] k) {
knownElements = k;
}
}
| 597 |
2,184 | """Unsupervised clustering."""
from .clustream import CluStream
from .dbstream import DBSTREAM
from .denstream import DenStream
from .k_means import KMeans
from .streamkmeans import STREAMKMeans
__all__ = ["CluStream", "DBSTREAM", "DenStream", "KMeans", "STREAMKMeans"]
| 92 |
1,102 | <gh_stars>1000+
// Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// This source is available for distribution and/or modification
// only under the terms of the DOOM Source Code License as
// published by id Software. All rights reserved.
//
// The source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License
// for more details.
//
// $Log:$
//
// DESCRIPTION:
// Movement, collision handling.
// Shooting and aiming.
//
//-----------------------------------------------------------------------------
#include <stdlib.h>
#include <math.h>
#include "templates.h"
#include "m_bbox.h"
#include "m_random.h"
#include "i_system.h"
#include "c_dispatch.h"
#include "doomdef.h"
#include "p_local.h"
#include "p_lnspec.h"
#include "p_effect.h"
#include "p_terrain.h"
#include "p_trace.h"
#include "s_sound.h"
#include "decallib.h"
// State.
#include "doomstat.h"
#include "r_state.h"
#include "gi.h"
#include "a_sharedglobal.h"
#include "p_conversation.h"
#include "r_data/r_translate.h"
#include "g_level.h"
#include "r_sky.h"
CVAR(Bool, cl_bloodsplats, true, CVAR_ARCHIVE)
CVAR(Int, sv_smartaim, 0, CVAR_ARCHIVE | CVAR_SERVERINFO)
CVAR(Bool, cl_doautoaim, false, CVAR_ARCHIVE)
static void CheckForPushSpecial(line_t *line, int side, AActor *mobj, bool windowcheck);
static void SpawnShootDecal(AActor *t1, const FTraceResults &trace);
static void SpawnDeepSplash(AActor *t1, const FTraceResults &trace, AActor *puff,
fixed_t vx, fixed_t vy, fixed_t vz, fixed_t shootz, bool ffloor = false);
static FRandom pr_tracebleed("TraceBleed");
static FRandom pr_checkthing("CheckThing");
static FRandom pr_lineattack("LineAttack");
static FRandom pr_crunch("DoCrunch");
// keep track of special lines as they are hit,
// but don't process them until the move is proven valid
TArray<line_t *> spechit;
// Temporary holder for thing_sectorlist threads
msecnode_t* sector_list = NULL; // phares 3/16/98
//==========================================================================
//
// GetCoefficientClosestPointInLine24
//
// Formula: (dotProduct(ldv1 - tm, ld) << 24) / dotProduct(ld, ld)
// with: ldv1 = (ld->v1->x, ld->v1->y), tm = (tm.x, tm.y)
// and ld = (ld->dx, ld->dy)
// Returns truncated to range [0, 1 << 24].
//
//==========================================================================
static fixed_t GetCoefficientClosestPointInLine24(line_t *ld, FCheckPosition &tm)
{
// [EP] Use 64 bit integers in order to keep the exact result of the
// multiplication, because in the case the vertexes have both the
// distance coordinates equal to the map limit (32767 units, which is
// 2147418112 in fixed_t notation), the product result would occupy
// 62 bits and the sum of two products would occupy 63 bits
// in the worst case. If instead the vertexes are very close (1 in
// fixed_t notation, which is 1.52587890625e-05 in float notation), the
// product and the sum can be 1 in the worst case, which is very tiny.
SQWORD r_num = ((SQWORD(tm.x - ld->v1->x)*ld->dx) +
(SQWORD(tm.y - ld->v1->y)*ld->dy));
// The denominator is always positive. Use this to avoid useless
// calculations.
SQWORD r_den = (SQWORD(ld->dx)*ld->dx + SQWORD(ld->dy)*ld->dy);
if (r_num <= 0) {
// [EP] The numerator is less or equal to zero, hence the closest
// point on the line is the first vertex. Truncate the result to 0.
return 0;
}
if (r_num >= r_den) {
// [EP] The division is greater or equal to 1, hence the closest
// point on the line is the second vertex. Truncate the result to
// 1 << 24.
return (1 << 24);
}
// [EP] Deal with the limited bits. The original formula is:
// r = (r_num << 24) / r_den,
// but r_num might be big enough to make the shift overflow.
// Since the numerator can't be saved in a 128bit integer,
// the denominator must be right shifted. If the denominator is
// less than (1 << 24), there would be a division by zero.
// Thanks to the fact that in this code path the denominator is greater
// than the numerator, it's possible to avoid this bad situation by
// just checking the last 24 bits of the numerator.
if ((r_num >> (63-24)) != 0) {
// [EP] In fact, if the numerator is greater than
// (1 << (63-24)), the denominator must be greater than
// (1 << (63-24)), hence the denominator won't be zero after
// the right shift by 24 places.
return (fixed_t)(r_num/(r_den >> 24));
}
// [EP] Having the last 24 bits all zero allows left shifting
// the numerator by 24 bits without overflow.
return (fixed_t)((r_num << 24)/r_den);
}
//==========================================================================
//
// PIT_FindFloorCeiling
//
// only3d set means to only check against 3D floors and midtexes.
//
//==========================================================================
static bool PIT_FindFloorCeiling(line_t *ld, const FBoundingBox &box, FCheckPosition &tmf, int flags)
{
if (box.Right() <= ld->bbox[BOXLEFT]
|| box.Left() >= ld->bbox[BOXRIGHT]
|| box.Top() <= ld->bbox[BOXBOTTOM]
|| box.Bottom() >= ld->bbox[BOXTOP])
return true;
if (box.BoxOnLineSide(ld) != -1)
return true;
// A line has been hit
if (!ld->backsector)
{ // One sided line
return true;
}
fixed_t sx, sy;
FLineOpening open;
// set openrange, opentop, openbottom
if ((((ld->frontsector->floorplane.a | ld->frontsector->floorplane.b) |
(ld->backsector->floorplane.a | ld->backsector->floorplane.b) |
(ld->frontsector->ceilingplane.a | ld->frontsector->ceilingplane.b) |
(ld->backsector->ceilingplane.a | ld->backsector->ceilingplane.b)) == 0)
&& ld->backsector->e->XFloor.ffloors.Size() == 0 && ld->frontsector->e->XFloor.ffloors.Size() == 0)
{
P_LineOpening(open, tmf.thing, ld, sx = tmf.x, sy = tmf.y, tmf.x, tmf.y, flags);
}
else
{ // Find the point on the line closest to the actor's center, and use
// that to calculate openings
double dx = ld->dx;
double dy = ld->dy;
fixed_t r = xs_CRoundToInt(((double)(tmf.x - ld->v1->x) * dx +
(double)(tmf.y - ld->v1->y) * dy) /
(dx*dx + dy*dy) * 16777216.f);
if (r <= 0)
{
P_LineOpening(open, tmf.thing, ld, sx = ld->v1->x, sy = ld->v1->y, tmf.x, tmf.y, flags);
}
else if (r >= (1 << 24))
{
P_LineOpening(open, tmf.thing, ld, sx = ld->v2->x, sy = ld->v2->y, tmf.thing->X(), tmf.thing->Y(), flags);
}
else
{
P_LineOpening(open, tmf.thing, ld, sx = ld->v1->x + MulScale24(r, ld->dx),
sy = ld->v1->y + MulScale24(r, ld->dy), tmf.x, tmf.y, flags);
}
}
// adjust floor / ceiling heights
if (open.top < tmf.ceilingz)
{
tmf.ceilingz = open.top;
}
if (open.bottom > tmf.floorz)
{
tmf.floorz = open.bottom;
if (open.bottomsec != NULL) tmf.floorsector = open.bottomsec;
tmf.touchmidtex = open.touchmidtex;
tmf.abovemidtex = open.abovemidtex;
}
else if (open.bottom == tmf.floorz)
{
tmf.touchmidtex |= open.touchmidtex;
tmf.abovemidtex |= open.abovemidtex;
}
if (open.lowfloor < tmf.dropoffz)
tmf.dropoffz = open.lowfloor;
return true;
}
//==========================================================================
//
//
//
//==========================================================================
void P_GetFloorCeilingZ(FCheckPosition &tmf, int flags)
{
sector_t *sec;
if (!(flags & FFCF_ONLYSPAWNPOS))
{
sec = !(flags & FFCF_SAMESECTOR) ? P_PointInSector(tmf.x, tmf.y) : tmf.thing->Sector;
tmf.floorsector = sec;
tmf.ceilingsector = sec;
tmf.floorz = tmf.dropoffz = sec->floorplane.ZatPoint(tmf.x, tmf.y);
tmf.ceilingz = sec->ceilingplane.ZatPoint(tmf.x, tmf.y);
tmf.floorpic = sec->GetTexture(sector_t::floor);
tmf.floorterrain = sec->GetTerrain(sector_t::floor);
tmf.ceilingpic = sec->GetTexture(sector_t::ceiling);
}
else
{
sec = tmf.thing->Sector;
}
for (unsigned int i = 0; i<sec->e->XFloor.ffloors.Size(); i++)
{
F3DFloor* rover = sec->e->XFloor.ffloors[i];
if (!(rover->flags & FF_SOLID) || !(rover->flags & FF_EXISTS)) continue;
fixed_t ff_bottom = rover->bottom.plane->ZatPoint(tmf.x, tmf.y);
fixed_t ff_top = rover->top.plane->ZatPoint(tmf.x, tmf.y);
if (ff_top > tmf.floorz)
{
if (ff_top <= tmf.z || (!(flags & FFCF_3DRESTRICT) && (tmf.thing != NULL && ff_bottom < tmf.z && ff_top < tmf.z + tmf.thing->MaxStepHeight)))
{
tmf.dropoffz = tmf.floorz = ff_top;
tmf.floorpic = *rover->top.texture;
tmf.floorterrain = rover->model->GetTerrain(rover->top.isceiling);
}
}
if (ff_bottom <= tmf.ceilingz && ff_bottom > tmf.z + tmf.thing->height)
{
tmf.ceilingz = ff_bottom;
tmf.ceilingpic = *rover->bottom.texture;
}
}
}
//==========================================================================
//
// P_FindFloorCeiling
//
//==========================================================================
void P_FindFloorCeiling(AActor *actor, int flags)
{
FCheckPosition tmf;
tmf.thing = actor;
tmf.x = actor->X();
tmf.y = actor->Y();
tmf.z = actor->Z();
if (flags & FFCF_ONLYSPAWNPOS)
{
flags |= FFCF_3DRESTRICT;
}
if (!(flags & FFCF_ONLYSPAWNPOS))
{
P_GetFloorCeilingZ(tmf, flags);
}
else
{
tmf.ceilingsector = tmf.floorsector = actor->Sector;
tmf.floorz = tmf.dropoffz = actor->floorz;
tmf.ceilingz = actor->ceilingz;
tmf.floorpic = actor->floorpic;
tmf.floorterrain = actor->floorterrain;
tmf.ceilingpic = actor->ceilingpic;
P_GetFloorCeilingZ(tmf, flags);
}
actor->floorz = tmf.floorz;
actor->dropoffz = tmf.dropoffz;
actor->ceilingz = tmf.ceilingz;
actor->floorpic = tmf.floorpic;
actor->floorterrain = tmf.floorterrain;
actor->floorsector = tmf.floorsector;
actor->ceilingpic = tmf.ceilingpic;
actor->ceilingsector = tmf.ceilingsector;
FBoundingBox box(tmf.x, tmf.y, actor->radius);
tmf.touchmidtex = false;
tmf.abovemidtex = false;
validcount++;
FBlockLinesIterator it(box);
line_t *ld;
while ((ld = it.Next()))
{
PIT_FindFloorCeiling(ld, box, tmf, flags);
}
if (tmf.touchmidtex) tmf.dropoffz = tmf.floorz;
if (!(flags & FFCF_ONLYSPAWNPOS) || (tmf.abovemidtex && (tmf.floorz <= actor->Z())))
{
actor->floorz = tmf.floorz;
actor->dropoffz = tmf.dropoffz;
actor->ceilingz = tmf.ceilingz;
actor->floorpic = tmf.floorpic;
actor->floorterrain = tmf.floorterrain;
actor->floorsector = tmf.floorsector;
actor->ceilingpic = tmf.ceilingpic;
actor->ceilingsector = tmf.ceilingsector;
}
else
{
actor->floorsector = actor->ceilingsector = actor->Sector;
// [BB] Don't forget to update floorpic and ceilingpic.
if (actor->Sector != NULL)
{
actor->floorpic = actor->Sector->GetTexture(sector_t::floor);
actor->floorterrain = actor->Sector->GetTerrain(sector_t::floor);
actor->ceilingpic = actor->Sector->GetTexture(sector_t::ceiling);
}
}
}
//==========================================================================
//
// TELEPORT MOVE
//
//
// P_TeleportMove
//
// [RH] Added telefrag parameter: When true, anything in the spawn spot
// will always be telefragged, and the move will be successful.
// Added z parameter. Originally, the thing's z was set *after* the
// move was made, so the height checking I added for 1.13 could
// potentially erroneously indicate the move was okay if the thing
// was being teleported between two non-overlapping height ranges.
//
//==========================================================================
bool P_TeleportMove(AActor *thing, fixed_t x, fixed_t y, fixed_t z, bool telefrag, bool modifyactor)
{
FCheckPosition tmf;
sector_t *oldsec = thing->Sector;
// kill anything occupying the position
// The base floor/ceiling is from the subsector that contains the point.
// Any contacted lines the step closer together will adjust them.
tmf.thing = thing;
tmf.x = x;
tmf.y = y;
tmf.z = z;
tmf.touchmidtex = false;
tmf.abovemidtex = false;
P_GetFloorCeilingZ(tmf, 0);
spechit.Clear();
bool StompAlwaysFrags = ((thing->flags2 & MF2_TELESTOMP) || (level.flags & LEVEL_MONSTERSTELEFRAG) || telefrag) && !(thing->flags7 & MF7_NOTELESTOMP);
FBoundingBox box(x, y, thing->radius);
FBlockLinesIterator it(box);
line_t *ld;
// P_LineOpening requires the thing's z to be the destination z in order to work.
fixed_t savedz = thing->Z();
thing->SetZ(z);
while ((ld = it.Next()))
{
PIT_FindFloorCeiling(ld, box, tmf, 0);
}
thing->SetZ(savedz);
if (tmf.touchmidtex) tmf.dropoffz = tmf.floorz;
FBlockThingsIterator it2(FBoundingBox(x, y, thing->radius));
AActor *th;
while ((th = it2.Next()))
{
if (!(th->flags & MF_SHOOTABLE))
continue;
// don't clip against self
if (th == thing)
continue;
fixed_t blockdist = th->radius + tmf.thing->radius;
if (abs(th->X() - tmf.x) >= blockdist || abs(th->Y() - tmf.y) >= blockdist)
continue;
if ((th->flags2 | tmf.thing->flags2) & MF2_THRUACTORS)
continue;
if (tmf.thing->flags6 & MF6_THRUSPECIES && tmf.thing->GetSpecies() == th->GetSpecies())
continue;
// [RH] Z-Check
// But not if not MF2_PASSMOBJ or MF3_DONTOVERLAP are set!
// Otherwise those things would get stuck inside each other.
if ((thing->flags2 & MF2_PASSMOBJ || th->flags4 & MF4_ACTLIKEBRIDGE) && !(i_compatflags & COMPATF_NO_PASSMOBJ))
{
if (!(th->flags3 & thing->flags3 & MF3_DONTOVERLAP))
{
if (z > th->Top() || // overhead
z + thing->height < th->Z()) // underneath
continue;
}
}
// monsters don't stomp things except on boss level
// [RH] Some Heretic/Hexen monsters can telestomp
// ... and some items can never be telefragged while others will be telefragged by everything that teleports upon them.
if ((StompAlwaysFrags && !(th->flags6 & MF6_NOTELEFRAG)) || (th->flags7 & MF7_ALWAYSTELEFRAG))
{
// Don't actually damage if predicting a teleport
if (thing->player == NULL || !(thing->player->cheats & CF_PREDICTING))
P_DamageMobj(th, thing, thing, TELEFRAG_DAMAGE, NAME_Telefrag, DMG_THRUSTLESS);
continue;
}
return false;
}
if (modifyactor)
{
// the move is ok, so link the thing into its new position
thing->SetOrigin(x, y, z, false);
thing->floorz = tmf.floorz;
thing->ceilingz = tmf.ceilingz;
thing->floorsector = tmf.floorsector;
thing->floorpic = tmf.floorpic;
thing->floorterrain = tmf.floorterrain;
thing->ceilingsector = tmf.ceilingsector;
thing->ceilingpic = tmf.ceilingpic;
thing->dropoffz = tmf.dropoffz; // killough 11/98
thing->BlockingLine = NULL;
if (thing->flags2 & MF2_FLOORCLIP)
{
thing->AdjustFloorClip();
}
if (thing == players[consoleplayer].camera)
{
R_ResetViewInterpolation();
}
thing->PrevX = x;
thing->PrevY = y;
thing->PrevZ = z;
// If this teleport was caused by a move, P_TryMove() will handle the
// sector transition messages better than we can here.
if (!(thing->flags6 & MF6_INTRYMOVE))
{
thing->CheckSectorTransition(oldsec);
}
}
return true;
}
//==========================================================================
//
// [RH] P_PlayerStartStomp
//
// Like P_TeleportMove, but it doesn't move anything, and only monsters and other
// players get telefragged.
//
//==========================================================================
void P_PlayerStartStomp(AActor *actor, bool mononly)
{
AActor *th;
FBlockThingsIterator it(FBoundingBox(actor->X(), actor->Y(), actor->radius));
while ((th = it.Next()))
{
if (!(th->flags & MF_SHOOTABLE))
continue;
// don't clip against self, and don't kill your own voodoo dolls
if (th == actor || (th->player == actor->player && th->player != NULL))
continue;
if (!th->intersects(actor))
continue;
// only kill monsters and other players
if (th->player == NULL && !(th->flags3 & MF3_ISMONSTER))
continue;
if (th->player != NULL && mononly)
continue;
if (actor->Z() > th->Top())
continue; // overhead
if (actor->Top() < th->Z())
continue; // underneath
P_DamageMobj(th, actor, actor, TELEFRAG_DAMAGE, NAME_Telefrag);
}
}
//==========================================================================
//
//
//
//==========================================================================
inline fixed_t secfriction(const sector_t *sec, int plane = sector_t::floor)
{
if (sec->Flags & SECF_FRICTION) return sec->friction;
fixed_t friction = Terrains[sec->GetTerrain(plane)].Friction;
return friction != 0 ? friction : ORIG_FRICTION;
}
inline fixed_t secmovefac(const sector_t *sec, int plane = sector_t::floor)
{
if (sec->Flags & SECF_FRICTION) return sec->movefactor;
fixed_t movefactor = Terrains[sec->GetTerrain(plane)].MoveFactor;
return movefactor != 0 ? movefactor : ORIG_FRICTION_FACTOR;
}
//==========================================================================
//
// killough 8/28/98:
//
// P_GetFriction()
//
// Returns the friction associated with a particular mobj.
//
//==========================================================================
int P_GetFriction(const AActor *mo, int *frictionfactor)
{
int friction = ORIG_FRICTION;
int movefactor = ORIG_FRICTION_FACTOR;
fixed_t newfriction;
const msecnode_t *m;
const sector_t *sec;
if (mo->IsNoClip2())
{
// The default values are fine for noclip2 mode
}
else if (mo->flags2 & MF2_FLY && mo->flags & MF_NOGRAVITY)
{
friction = FRICTION_FLY;
}
else if ((!(mo->flags & MF_NOGRAVITY) && mo->waterlevel > 1) ||
(mo->waterlevel == 1 && mo->Z() > mo->floorz + 6 * FRACUNIT))
{
friction = secfriction(mo->Sector);
movefactor = secmovefac(mo->Sector) >> 1;
// Check 3D floors -- might be the source of the waterlevel
for (unsigned i = 0; i < mo->Sector->e->XFloor.ffloors.Size(); i++)
{
F3DFloor *rover = mo->Sector->e->XFloor.ffloors[i];
if (!(rover->flags & FF_EXISTS)) continue;
if (!(rover->flags & FF_SWIMMABLE)) continue;
if (mo->Z() > rover->top.plane->ZatPoint(mo) ||
mo->Z() < rover->bottom.plane->ZatPoint(mo))
continue;
newfriction = secfriction(rover->model, rover->top.isceiling);
if (newfriction < friction || friction == ORIG_FRICTION)
{
friction = newfriction;
movefactor = secmovefac(rover->model, rover->top.isceiling) >> 1;
}
}
}
else if (var_friction && !(mo->flags & (MF_NOCLIP | MF_NOGRAVITY)))
{ // When the object is straddling sectors with the same
// floor height that have different frictions, use the lowest
// friction value (muddy has precedence over icy).
for (m = mo->touching_sectorlist; m; m = m->m_tnext)
{
sec = m->m_sector;
// 3D floors must be checked, too
for (unsigned i = 0; i < sec->e->XFloor.ffloors.Size(); i++)
{
F3DFloor *rover = sec->e->XFloor.ffloors[i];
if (!(rover->flags & FF_EXISTS)) continue;
if (rover->flags & FF_SOLID)
{
// Must be standing on a solid floor
if (mo->Z() != rover->top.plane->ZatPoint(mo)) continue;
}
else if (rover->flags & FF_SWIMMABLE)
{
// Or on or inside a swimmable floor (e.g. in shallow water)
if (mo->Z() > rover->top.plane->ZatPoint(mo) ||
(mo->Top()) < rover->bottom.plane->ZatPoint(mo))
continue;
}
else
continue;
newfriction = secfriction(rover->model, rover->top.isceiling);
if (newfriction < friction || friction == ORIG_FRICTION)
{
friction = newfriction;
movefactor = secmovefac(rover->model, rover->top.isceiling);
}
}
if (!(sec->Flags & SECF_FRICTION) &&
Terrains[sec->GetTerrain(sector_t::floor)].Friction == 0)
{
continue;
}
newfriction = secfriction(sec);
if ((newfriction < friction || friction == ORIG_FRICTION) &&
(mo->Z() <= sec->floorplane.ZatPoint(mo) ||
(sec->GetHeightSec() != NULL &&
mo->Z() <= sec->heightsec->floorplane.ZatPoint(mo))))
{
friction = newfriction;
movefactor = secmovefac(sec);
}
}
}
if (mo->Friction != FRACUNIT)
{
friction = clamp(FixedMul(friction, mo->Friction), 0, FRACUNIT);
movefactor = FrictionToMoveFactor(friction);
}
if (frictionfactor)
*frictionfactor = movefactor;
return friction;
}
//==========================================================================
//
// phares 3/19/98
// P_GetMoveFactor() returns the value by which the x,y
// movements are multiplied to add to player movement.
//
// killough 8/28/98: rewritten
//
//==========================================================================
int P_GetMoveFactor(const AActor *mo, int *frictionp)
{
int movefactor, friction;
// If the floor is icy or muddy, it's harder to get moving. This is where
// the different friction factors are applied to 'trying to move'. In
// p_mobj.c, the friction factors are applied as you coast and slow down.
if ((friction = P_GetFriction(mo, &movefactor)) < ORIG_FRICTION)
{
// phares 3/11/98: you start off slowly, then increase as
// you get better footing
int velocity = P_AproxDistance(mo->velx, mo->vely);
if (velocity > MORE_FRICTION_VELOCITY << 2)
movefactor <<= 3;
else if (velocity > MORE_FRICTION_VELOCITY << 1)
movefactor <<= 2;
else if (velocity > MORE_FRICTION_VELOCITY)
movefactor <<= 1;
}
if (frictionp)
*frictionp = friction;
return movefactor;
}
//
// MOVEMENT ITERATOR FUNCTIONS
//
//==========================================================================
//
//
// PIT_CheckLine
// Adjusts tmfloorz and tmceilingz as lines are contacted
//
//
//==========================================================================
static // killough 3/26/98: make static
bool PIT_CheckLine(line_t *ld, const FBoundingBox &box, FCheckPosition &tm)
{
bool rail = false;
if (box.Right() <= ld->bbox[BOXLEFT]
|| box.Left() >= ld->bbox[BOXRIGHT]
|| box.Top() <= ld->bbox[BOXBOTTOM]
|| box.Bottom() >= ld->bbox[BOXTOP])
return true;
if (box.BoxOnLineSide(ld) != -1)
return true;
// A line has been hit
/*
=
= The moving thing's destination position will cross the given line.
= If this should not be allowed, return false.
= If the line is special, keep track of it to process later if the move
= is proven ok. NOTE: specials are NOT sorted by order, so two special lines
= that are only 8 pixels apart could be crossed in either order.
*/
if (!ld->backsector)
{ // One sided line
if (tm.thing->flags2 & MF2_BLASTED)
{
P_DamageMobj(tm.thing, NULL, NULL, tm.thing->Mass >> 5, NAME_Melee);
}
tm.thing->BlockingLine = ld;
CheckForPushSpecial(ld, 0, tm.thing, false);
return false;
}
// MBF bouncers are treated as missiles here.
bool Projectile = (tm.thing->flags & MF_MISSILE || tm.thing->BounceFlags & BOUNCE_MBF);
// MBF considers that friendly monsters are not blocked by monster-blocking lines.
// This is added here as a compatibility option. Note that monsters that are dehacked
// into being friendly with the MBF flag automatically gain MF3_NOBLOCKMONST, so this
// just optionally generalizes the behavior to other friendly monsters.
bool NotBlocked = ((tm.thing->flags3 & MF3_NOBLOCKMONST)
|| ((i_compatflags & COMPATF_NOBLOCKFRIENDS) && (tm.thing->flags & MF_FRIENDLY)));
fixedvec3 pos = tm.thing->PosRelative(ld);
if (!(Projectile) || (ld->flags & (ML_BLOCKEVERYTHING | ML_BLOCKPROJECTILE)))
{
if (ld->flags & ML_RAILING)
{
rail = true;
}
else if ((ld->flags & (ML_BLOCKING | ML_BLOCKEVERYTHING)) || // explicitly blocking everything
(!(NotBlocked) && (ld->flags & ML_BLOCKMONSTERS)) || // block monsters only
(tm.thing->player != NULL && (ld->flags & ML_BLOCK_PLAYERS)) || // block players
((Projectile) && (ld->flags & ML_BLOCKPROJECTILE)) || // block projectiles
((tm.thing->flags & MF_FLOAT) && (ld->flags & ML_BLOCK_FLOATERS))) // block floaters
{
if (tm.thing->flags2 & MF2_BLASTED)
{
P_DamageMobj(tm.thing, NULL, NULL, tm.thing->Mass >> 5, NAME_Melee);
}
tm.thing->BlockingLine = ld;
// Calculate line side based on the actor's original position, not the new one.
CheckForPushSpecial(ld, P_PointOnLineSide(pos.x, pos.y, ld), tm.thing, false);
return false;
}
}
// [RH] Steep sectors count as dropoffs (unless already in one)
if (!(tm.thing->flags & MF_DROPOFF) &&
!(tm.thing->flags & (MF_NOGRAVITY | MF_NOCLIP)))
{
secplane_t frontplane, backplane;
// Check 3D floors as well
frontplane = P_FindFloorPlane(ld->frontsector, pos.x, pos.y, tm.thing->floorz);
backplane = P_FindFloorPlane(ld->backsector, pos.x, pos.y, tm.thing->floorz);
if (frontplane.c < STEEPSLOPE || backplane.c < STEEPSLOPE)
{
const msecnode_t *node = tm.thing->touching_sectorlist;
bool allow = false;
int count = 0;
while (node != NULL)
{
count++;
if (node->m_sector->floorplane.c < STEEPSLOPE)
{
allow = true;
break;
}
node = node->m_tnext;
}
if (!allow)
{
return false;
}
}
}
fixed_t sx = 0, sy = 0;
FLineOpening open;
// set openrange, opentop, openbottom
if ((((ld->frontsector->floorplane.a | ld->frontsector->floorplane.b) |
(ld->backsector->floorplane.a | ld->backsector->floorplane.b) |
(ld->frontsector->ceilingplane.a | ld->frontsector->ceilingplane.b) |
(ld->backsector->ceilingplane.a | ld->backsector->ceilingplane.b)) == 0)
&& ld->backsector->e->XFloor.ffloors.Size() == 0 && ld->frontsector->e->XFloor.ffloors.Size() == 0)
{
P_LineOpening(open, tm.thing, ld, sx = tm.x, sy = tm.y, tm.x, tm.y);
}
else
{ // Find the point on the line closest to the actor's center, and use
// that to calculate openings
fixed_t r = GetCoefficientClosestPointInLine24(ld, tm);
/* Printf ("%d:%d: %d (%d %d %d %d) (%d %d %d %d)\n", level.time, ld-lines, r,
ld->frontsector->floorplane.a,
ld->frontsector->floorplane.b,
ld->frontsector->floorplane.c,
ld->frontsector->floorplane.ic,
ld->backsector->floorplane.a,
ld->backsector->floorplane.b,
ld->backsector->floorplane.c,
ld->backsector->floorplane.ic);*/
if (r <= 0)
{
P_LineOpening(open, tm.thing, ld, sx = ld->v1->x, sy = ld->v1->y, tm.x, tm.y);
}
else if (r >= (1 << 24))
{
P_LineOpening(open, tm.thing, ld, sx = ld->v2->x, sy = ld->v2->y, pos.x, pos.y);
}
else
{
P_LineOpening(open, tm.thing, ld, sx = ld->v1->x + MulScale24(r, ld->dx),
sy = ld->v1->y + MulScale24(r, ld->dy), tm.x, tm.y);
}
// the floorplane on both sides is identical with the current one
// so don't mess around with the z-position
if (ld->frontsector->floorplane == ld->backsector->floorplane &&
ld->frontsector->floorplane == tm.thing->Sector->floorplane &&
!ld->frontsector->e->XFloor.ffloors.Size() && !ld->backsector->e->XFloor.ffloors.Size() &&
!open.abovemidtex)
{
open.bottom = INT_MIN;
}
/* Printf (" %d %d %d\n", sx, sy, openbottom);*/
}
if (rail &&
// Eww! Gross! This check means the rail only exists if you stand on the
// high side of the rail. So if you're walking on the low side of the rail,
// it's possible to get stuck in the rail until you jump out. Unfortunately,
// there is an area on Strife MAP04 that requires this behavior. Still, it's
// better than Strife's handling of rails, which lets you jump into rails
// from either side. How long until somebody reports this as a bug and I'm
// forced to say, "It's not a bug. It's a feature?" Ugh.
(!(level.flags2 & LEVEL2_RAILINGHACK) ||
open.bottom == tm.thing->Sector->floorplane.ZatPoint(sx, sy)))
{
open.bottom += 32 * FRACUNIT;
}
// adjust floor / ceiling heights
if (open.top < tm.ceilingz)
{
tm.ceilingz = open.top;
tm.ceilingsector = open.topsec;
tm.ceilingpic = open.ceilingpic;
tm.ceilingline = ld;
tm.thing->BlockingLine = ld;
}
if (open.bottom > tm.floorz)
{
tm.floorz = open.bottom;
tm.floorsector = open.bottomsec;
tm.floorpic = open.floorpic;
tm.floorterrain = open.floorterrain;
tm.touchmidtex = open.touchmidtex;
tm.abovemidtex = open.abovemidtex;
tm.thing->BlockingLine = ld;
}
else if (open.bottom == tm.floorz)
{
tm.touchmidtex |= open.touchmidtex;
tm.abovemidtex |= open.abovemidtex;
}
if (open.lowfloor < tm.dropoffz)
tm.dropoffz = open.lowfloor;
// if contacted a special line, add it to the list
if (ld->special)
{
spechit.Push(ld);
}
return true;
}
//==========================================================================
//
// Isolated to keep the code readable and fix the logic
//
//==========================================================================
static bool CheckRipLevel(AActor *victim, AActor *projectile)
{
if (victim->RipLevelMin > 0 && projectile->RipperLevel < victim->RipLevelMin) return false;
if (victim->RipLevelMax > 0 && projectile->RipperLevel > victim->RipLevelMax) return false;
return true;
}
//==========================================================================
//
// Isolated to keep the code readable and allow reuse in other attacks
//
//==========================================================================
static bool CanAttackHurt(AActor *victim, AActor *shooter)
{
// players are never subject to infighting settings and are always allowed
// to harm / be harmed by anything.
if (!victim->player && !shooter->player)
{
int infight = G_SkillProperty(SKILLP_Infight);
if (infight < 0)
{
// -1: Monsters cannot hurt each other, but make exceptions for
// friendliness and hate status.
if (shooter->flags & MF_SHOOTABLE)
{
// Question: Should monsters be allowed to shoot barrels in this mode?
// The old code does not.
if (victim->flags3 & MF3_ISMONSTER)
{
// Monsters that are clearly hostile can always hurt each other
if (!victim->IsHostile(shooter))
{
// The same if the shooter hates the target
if (victim->tid == 0 || shooter->TIDtoHate != victim->tid)
{
return false;
}
}
}
}
}
else if (infight == 0)
{
// 0: Monsters cannot hurt same species except
// cases where they are clearly supposed to do that
if (victim->IsFriend(shooter))
{
// Friends never harm each other, unless the shooter has the HARMFRIENDS set.
if (!(shooter->flags7 & MF7_HARMFRIENDS)) return false;
}
else
{
if (victim->TIDtoHate != 0 && victim->TIDtoHate == shooter->TIDtoHate)
{
// [RH] Don't hurt monsters that hate the same victim as you do
return false;
}
if (victim->GetSpecies() == shooter->GetSpecies() && !(victim->flags6 & MF6_DOHARMSPECIES))
{
// Don't hurt same species or any relative -
// but only if the target isn't one's hostile.
if (!victim->IsHostile(shooter))
{
// Allow hurting monsters the shooter hates.
if (victim->tid == 0 || shooter->TIDtoHate != victim->tid)
{
return false;
}
}
}
}
}
// else if (infight==1) every shot hurts anything - no further tests needed
}
return true;
}
//==========================================================================
//
// PIT_CheckThing
//
//==========================================================================
bool PIT_CheckThing(AActor *thing, FCheckPosition &tm)
{
fixed_t topz;
bool solid;
int damage;
// don't clip against self
if (thing == tm.thing)
return true;
if (!((thing->flags & (MF_SOLID | MF_SPECIAL | MF_SHOOTABLE)) || thing->flags6 & MF6_TOUCHY))
return true; // can't hit thing
fixedvec3 thingpos = thing->PosRelative(tm.thing);
fixed_t blockdist = thing->radius + tm.thing->radius;
if (abs(thingpos.x - tm.x) >= blockdist || abs(thingpos.y - tm.y) >= blockdist)
return true;
if ((thing->flags2 | tm.thing->flags2) & MF2_THRUACTORS)
return true;
if ((tm.thing->flags6 & MF6_THRUSPECIES) && (tm.thing->GetSpecies() == thing->GetSpecies()))
return true;
tm.thing->BlockingMobj = thing;
topz = thing->Top();
if (!(i_compatflags & COMPATF_NO_PASSMOBJ) && !(tm.thing->flags & (MF_FLOAT | MF_MISSILE | MF_SKULLFLY | MF_NOGRAVITY)) &&
(thing->flags & MF_SOLID) && (thing->flags4 & MF4_ACTLIKEBRIDGE))
{
// [RH] Let monsters walk on actors as well as floors
if ((tm.thing->flags3 & MF3_ISMONSTER) &&
topz >= tm.floorz && topz <= tm.thing->Z() + tm.thing->MaxStepHeight)
{
// The commented-out if is an attempt to prevent monsters from walking off a
// thing further than they would walk off a ledge. I can't think of an easy
// way to do this, so I restrict them to only walking on bridges instead.
// Uncommenting the if here makes it almost impossible for them to walk on
// anything, bridge or otherwise.
// if (abs(thing->x - tmx) <= thing->radius &&
// abs(thing->y - tmy) <= thing->radius)
{
tm.stepthing = thing;
tm.floorz = topz;
}
}
}
// Both things overlap in x or y direction
bool unblocking = false;
if ((tm.FromPMove || tm.thing->player != NULL) && thing->flags&MF_SOLID)
{
// Both actors already overlap. To prevent them from remaining stuck allow the move if it
// takes them further apart or the move does not change the position (when called from P_ChangeSector.)
if (tm.x == tm.thing->X() && tm.y == tm.thing->Y())
{
unblocking = true;
}
else if (abs(thingpos.x - tm.thing->X()) < (thing->radius+tm.thing->radius) &&
abs(thingpos.y - tm.thing->Y()) < (thing->radius+tm.thing->radius))
{
fixed_t newdist = thing->AproxDistance(tm.x, tm.y, tm.thing);
fixed_t olddist = thing->AproxDistance(tm.thing);
if (newdist > olddist)
{
// ... but not if they did not overlap in z-direction before but would after the move.
unblocking = !((tm.thing->Z() >= topz && tm.z < topz) ||
(tm.thing->Top() <= thingpos.z && tm.thing->Top() > thingpos.z));
}
}
}
// [RH] If the other thing is a bridge, then treat the moving thing as if it had MF2_PASSMOBJ, so
// you can use a scrolling floor to move scenery items underneath a bridge.
if ((tm.thing->flags2 & MF2_PASSMOBJ || thing->flags4 & MF4_ACTLIKEBRIDGE) && !(i_compatflags & COMPATF_NO_PASSMOBJ))
{ // check if a mobj passed over/under another object
if (!(tm.thing->flags & MF_MISSILE) ||
!(tm.thing->flags2 & MF2_RIP) ||
(thing->flags5 & MF5_DONTRIP) ||
((tm.thing->flags6 & MF6_NOBOSSRIP) && (thing->flags2 & MF2_BOSS)))
{
if (tm.thing->flags3 & thing->flags3 & MF3_DONTOVERLAP)
{ // Some things prefer not to overlap each other, if possible
return unblocking;
}
if ((tm.thing->Z() >= topz) || (tm.thing->Top() <= thing->Z()))
return true;
}
}
if (tm.thing->player == NULL || !(tm.thing->player->cheats & CF_PREDICTING))
{
// touchy object is alive, toucher is solid
if (thing->flags6 & MF6_TOUCHY && tm.thing->flags & MF_SOLID && thing->health > 0 &&
// Thing is an armed mine or a sentient thing
(thing->flags6 & MF6_ARMED || thing->IsSentient()) &&
// either different classes or players
(thing->player || thing->GetClass() != tm.thing->GetClass()) &&
// or different species if DONTHARMSPECIES
(!(thing->flags6 & MF6_DONTHARMSPECIES) || thing->GetSpecies() != tm.thing->GetSpecies()) &&
// touches vertically
topz >= tm.thing->Z() && tm.thing->Z() + tm.thing->height >= thingpos.z &&
// prevents lost souls from exploding when fired by pain elementals
(thing->master != tm.thing && tm.thing->master != thing))
// Difference with MBF: MBF hardcodes the LS/PE check and lets actors of the same species
// but different classes trigger the touchiness, but that seems less straightforwards.
{
thing->flags6 &= ~MF6_ARMED; // Disarm
P_DamageMobj(thing, NULL, NULL, thing->health, NAME_None, DMG_FORCED); // kill object
return true;
}
// Check for MF6_BUMPSPECIAL
// By default, only players can activate things by bumping into them
if ((thing->flags6 & MF6_BUMPSPECIAL) && ((tm.thing->player != NULL)
|| ((thing->activationtype & THINGSPEC_MonsterTrigger) && (tm.thing->flags3 & MF3_ISMONSTER))
|| ((thing->activationtype & THINGSPEC_MissileTrigger) && (tm.thing->flags & MF_MISSILE))
) && (level.maptime > thing->lastbump)) // Leave the bumper enough time to go away
{
if (P_ActivateThingSpecial(thing, tm.thing))
thing->lastbump = level.maptime + TICRATE;
}
}
// Check for skulls slamming into things
if (tm.thing->flags & MF_SKULLFLY)
{
bool res = tm.thing->Slam(tm.thing->BlockingMobj);
tm.thing->BlockingMobj = NULL;
return res;
}
// [ED850] Player Prediction ends here. There is nothing else they could/should do.
if (tm.thing->player != NULL && (tm.thing->player->cheats & CF_PREDICTING))
{
solid = (thing->flags & MF_SOLID) &&
!(thing->flags & MF_NOCLIP) &&
((tm.thing->flags & MF_SOLID) || (tm.thing->flags6 & MF6_BLOCKEDBYSOLIDACTORS));
return !solid || unblocking;
}
// Check for blasted thing running into another
if ((tm.thing->flags2 & MF2_BLASTED) && (thing->flags & MF_SHOOTABLE))
{
if (!(thing->flags2 & MF2_BOSS) && (thing->flags3 & MF3_ISMONSTER) && !(thing->flags3 & MF3_DONTBLAST))
{
// ideally this should take the mass factor into account
thing->velx += tm.thing->velx;
thing->vely += tm.thing->vely;
if ((thing->velx + thing->vely) > 3 * FRACUNIT)
{
int newdam;
damage = (tm.thing->Mass / 100) + 1;
newdam = P_DamageMobj(thing, tm.thing, tm.thing, damage, tm.thing->DamageType);
P_TraceBleed(newdam > 0 ? newdam : damage, thing, tm.thing);
damage = (thing->Mass / 100) + 1;
newdam = P_DamageMobj(tm.thing, thing, thing, damage >> 2, tm.thing->DamageType);
P_TraceBleed(newdam > 0 ? newdam : damage, tm.thing, thing);
}
return false;
}
}
// Check for missile or non-solid MBF bouncer
if (tm.thing->flags & MF_MISSILE || ((tm.thing->BounceFlags & BOUNCE_MBF) && !(tm.thing->flags & MF_SOLID)))
{
// Check for a non-shootable mobj
if (thing->flags2 & MF2_NONSHOOTABLE)
{
return true;
}
// Check for passing through a ghost
if ((thing->flags3 & MF3_GHOST) && (tm.thing->flags2 & MF2_THRUGHOST))
{
return true;
}
if ((tm.thing->flags6 & MF6_MTHRUSPECIES)
&& tm.thing->target // NULL pointer check
&& (tm.thing->target->GetSpecies() == thing->GetSpecies()))
return true;
// Check for rippers passing through corpses
if ((thing->flags & MF_CORPSE) && (tm.thing->flags2 & MF2_RIP) && !(thing->flags & MF_SHOOTABLE))
{
return true;
}
int clipheight;
if (thing->projectilepassheight > 0)
{
clipheight = thing->projectilepassheight;
}
else if (thing->projectilepassheight < 0 && (i_compatflags & COMPATF_MISSILECLIP))
{
clipheight = -thing->projectilepassheight;
}
else
{
clipheight = thing->height;
}
// Check if it went over / under
if (tm.thing->Z() > thingpos.z + clipheight)
{ // Over thing
return true;
}
if (tm.thing->Top() < thingpos.z)
{ // Under thing
return true;
}
// [RH] What is the point of this check, again? In Hexen, it is unconditional,
// but here we only do it if the missile's damage is 0.
// MBF bouncer might have a non-0 damage value, but they must not deal damage on impact either.
if ((tm.thing->BounceFlags & BOUNCE_Actors) && (tm.thing->Damage == 0 || !(tm.thing->flags & MF_MISSILE)))
{
return (tm.thing->target == thing || !(thing->flags & MF_SOLID));
}
switch (tm.thing->SpecialMissileHit(thing))
{
case 0: return false;
case 1: return true;
default: break;
}
// [RH] Extend DeHacked infighting to allow for monsters
// to never fight each other
if (tm.thing->target != NULL)
{
if (thing == tm.thing->target)
{ // Don't missile self
return true;
}
if (!CanAttackHurt(thing, tm.thing->target))
{
return false;
}
}
if (!(thing->flags & MF_SHOOTABLE))
{ // Didn't do any damage
return !(thing->flags & MF_SOLID);
}
if ((thing->flags4 & MF4_SPECTRAL) && !(tm.thing->flags4 & MF4_SPECTRAL))
{
return true;
}
if ((tm.DoRipping && !(thing->flags5 & MF5_DONTRIP)) && CheckRipLevel(thing, tm.thing))
{
if (!(tm.thing->flags6 & MF6_NOBOSSRIP) || !(thing->flags2 & MF2_BOSS))
{
bool *check = tm.LastRipped.CheckKey(thing);
if (check == NULL || !*check)
{
tm.LastRipped[thing] = true;
if (!(thing->flags & MF_NOBLOOD) &&
!(thing->flags2 & MF2_REFLECTIVE) &&
!(tm.thing->flags3 & MF3_BLOODLESSIMPACT) &&
!(thing->flags2 & (MF2_INVULNERABLE | MF2_DORMANT)))
{ // Ok to spawn blood
P_RipperBlood(tm.thing, thing);
}
S_Sound(tm.thing, CHAN_BODY, "misc/ripslop", 1, ATTN_IDLE);
// Do poisoning (if using new style poison)
if (tm.thing->PoisonDamage > 0 && tm.thing->PoisonDuration != INT_MIN)
{
P_PoisonMobj(thing, tm.thing, tm.thing->target, tm.thing->PoisonDamage, tm.thing->PoisonDuration, tm.thing->PoisonPeriod, tm.thing->PoisonDamageType);
}
damage = tm.thing->GetMissileDamage(3, 2);
int newdam = P_DamageMobj(thing, tm.thing, tm.thing->target, damage, tm.thing->DamageType);
if (!(tm.thing->flags3 & MF3_BLOODLESSIMPACT))
{
P_TraceBleed(newdam > 0 ? newdam : damage, thing, tm.thing);
}
if (thing->flags2 & MF2_PUSHABLE
&& !(tm.thing->flags2 & MF2_CANNOTPUSH))
{ // Push thing
if (thing->lastpush != tm.PushTime)
{
thing->velx += FixedMul(tm.thing->velx, thing->pushfactor);
thing->vely += FixedMul(tm.thing->vely, thing->pushfactor);
thing->lastpush = tm.PushTime;
}
}
}
spechit.Clear();
return true;
}
}
// Do poisoning (if using new style poison)
if (tm.thing->PoisonDamage > 0 && tm.thing->PoisonDuration != INT_MIN)
{
P_PoisonMobj(thing, tm.thing, tm.thing->target, tm.thing->PoisonDamage, tm.thing->PoisonDuration, tm.thing->PoisonPeriod, tm.thing->PoisonDamageType);
}
// Do damage
damage = tm.thing->GetMissileDamage((tm.thing->flags4 & MF4_STRIFEDAMAGE) ? 3 : 7, 1);
if ((damage > 0) || (tm.thing->flags6 & MF6_FORCEPAIN) || (tm.thing->flags7 & MF7_CAUSEPAIN))
{
int newdam = P_DamageMobj(thing, tm.thing, tm.thing->target, damage, tm.thing->DamageType);
if (damage > 0)
{
if ((tm.thing->flags5 & MF5_BLOODSPLATTER) &&
!(thing->flags & MF_NOBLOOD) &&
!(thing->flags2 & MF2_REFLECTIVE) &&
!(thing->flags2 & (MF2_INVULNERABLE | MF2_DORMANT)) &&
!(tm.thing->flags3 & MF3_BLOODLESSIMPACT) &&
(pr_checkthing() < 192))
{
P_BloodSplatter(tm.thing->X(), tm.thing->Y(), tm.thing->Z(), thing);
}
if (!(tm.thing->flags3 & MF3_BLOODLESSIMPACT))
{
P_TraceBleed(newdam > 0 ? newdam : damage, thing, tm.thing);
}
}
}
else
{
P_GiveBody(thing, -damage);
}
if ((thing->flags7 & MF7_THRUREFLECT) && (thing->flags2 & MF2_REFLECTIVE) && (tm.thing->flags & MF_MISSILE))
{
if (tm.thing->flags2 & MF2_SEEKERMISSILE)
{
tm.thing->tracer = tm.thing->target;
}
tm.thing->target = thing;
return true;
}
return false; // don't traverse any more
}
if (thing->flags2 & MF2_PUSHABLE && !(tm.thing->flags2 & MF2_CANNOTPUSH))
{ // Push thing
if (thing->lastpush != tm.PushTime)
{
thing->velx += FixedMul(tm.thing->velx, thing->pushfactor);
thing->vely += FixedMul(tm.thing->vely, thing->pushfactor);
thing->lastpush = tm.PushTime;
}
}
solid = (thing->flags & MF_SOLID) &&
!(thing->flags & MF_NOCLIP) &&
((tm.thing->flags & MF_SOLID) || (tm.thing->flags6 & MF6_BLOCKEDBYSOLIDACTORS));
// Check for special pickup
if ((thing->flags & MF_SPECIAL) && (tm.thing->flags & MF_PICKUP)
// [RH] The next condition is to compensate for the extra height
// that gets added by P_CheckPosition() so that you cannot pick
// up things that are above your true height.
&& thingpos.z < tm.thing->Top() - tm.thing->MaxStepHeight)
{ // Can be picked up by tmthing
P_TouchSpecialThing(thing, tm.thing); // can remove thing
}
// killough 3/16/98: Allow non-solid moving objects to move through solid
// ones, by allowing the moving thing (tmthing) to move if it's non-solid,
// despite another solid thing being in the way.
// killough 4/11/98: Treat no-clipping things as not blocking
return !solid || unblocking;
// return !(thing->flags & MF_SOLID); // old code -- killough
}
/*
===============================================================================
MOVEMENT CLIPPING
===============================================================================
*/
//==========================================================================
//
// P_CheckPosition
// This is purely informative, nothing is modified
// (except things picked up and missile damage applied).
//
// in:
// a AActor (can be valid or invalid)
// a position to be checked
// (doesn't need to be related to the AActor->x,y)
//
// during:
// special things are touched if MF_PICKUP
// early out on solid lines?
//
// out:
// newsubsec
// floorz
// ceilingz
// tmdropoffz = the lowest point contacted (monsters won't move to a dropoff)
// speciallines[]
// numspeciallines
// AActor *BlockingMobj = pointer to thing that blocked position (NULL if not
// blocked, or blocked by a line).
//
//==========================================================================
bool P_CheckPosition(AActor *thing, fixed_t x, fixed_t y, FCheckPosition &tm, bool actorsonly)
{
sector_t *newsec;
AActor *thingblocker;
fixed_t realheight = thing->height;
tm.thing = thing;
tm.x = x;
tm.y = y;
newsec = P_PointInSector(x, y);
tm.ceilingline = thing->BlockingLine = NULL;
// The base floor / ceiling is from the subsector that contains the point.
// Any contacted lines the step closer together will adjust them.
tm.floorz = tm.dropoffz = newsec->floorplane.ZatPoint(x, y);
tm.ceilingz = newsec->ceilingplane.ZatPoint(x, y);
tm.floorpic = newsec->GetTexture(sector_t::floor);
tm.floorterrain = newsec->GetTerrain(sector_t::floor);
tm.floorsector = newsec;
tm.ceilingpic = newsec->GetTexture(sector_t::ceiling);
tm.ceilingsector = newsec;
tm.touchmidtex = false;
tm.abovemidtex = false;
//Added by MC: Fill the tmsector.
tm.sector = newsec;
//Check 3D floors
if (!thing->IsNoClip2() && newsec->e->XFloor.ffloors.Size())
{
F3DFloor* rover;
fixed_t delta1;
fixed_t delta2;
int thingtop = thing->Z() + (thing->height == 0 ? 1 : thing->height);
for (unsigned i = 0; i<newsec->e->XFloor.ffloors.Size(); i++)
{
rover = newsec->e->XFloor.ffloors[i];
if (!(rover->flags & FF_SOLID) || !(rover->flags & FF_EXISTS)) continue;
fixed_t ff_bottom = rover->bottom.plane->ZatPoint(x, y);
fixed_t ff_top = rover->top.plane->ZatPoint(x, y);
delta1 = thing->Z() - (ff_bottom + ((ff_top - ff_bottom) / 2));
delta2 = thingtop - (ff_bottom + ((ff_top - ff_bottom) / 2));
if (ff_top > tm.floorz && abs(delta1) < abs(delta2))
{
tm.floorz = tm.dropoffz = ff_top;
tm.floorpic = *rover->top.texture;
tm.floorterrain = rover->model->GetTerrain(rover->top.isceiling);
}
if (ff_bottom < tm.ceilingz && abs(delta1) >= abs(delta2))
{
tm.ceilingz = ff_bottom;
tm.ceilingpic = *rover->bottom.texture;
}
}
}
validcount++;
spechit.Clear();
if ((thing->flags & MF_NOCLIP) && !(thing->flags & MF_SKULLFLY))
return true;
// Check things first, possibly picking things up.
thing->BlockingMobj = NULL;
thingblocker = NULL;
if (thing->player)
{ // [RH] Fake taller height to catch stepping up into things.
thing->height = realheight + thing->MaxStepHeight;
}
tm.stepthing = NULL;
FBoundingBox box(x, y, thing->radius);
{
FBlockThingsIterator it2(box);
AActor *th;
while ((th = it2.Next()))
{
if (!PIT_CheckThing(th, tm))
{ // [RH] If a thing can be stepped up on, we need to continue checking
// other things in the blocks and see if we hit something that is
// definitely blocking. Otherwise, we need to check the lines, or we
// could end up stuck inside a wall.
AActor *BlockingMobj = thing->BlockingMobj;
if (BlockingMobj == NULL || (i_compatflags & COMPATF_NO_PASSMOBJ))
{ // Thing slammed into something; don't let it move now.
thing->height = realheight;
return false;
}
else if (!BlockingMobj->player && !(thing->flags & (MF_FLOAT | MF_MISSILE | MF_SKULLFLY)) &&
BlockingMobj->Top() - thing->Z() <= thing->MaxStepHeight)
{
if (thingblocker == NULL ||
BlockingMobj->Z() > thingblocker->Z())
{
thingblocker = BlockingMobj;
}
thing->BlockingMobj = NULL;
}
else if (thing->player &&
thing->Top() - BlockingMobj->Z() <= thing->MaxStepHeight)
{
if (thingblocker)
{ // There is something to step up on. Return this thing as
// the blocker so that we don't step up.
thing->height = realheight;
return false;
}
// Nothing is blocking us, but this actor potentially could
// if there is something else to step on.
thing->BlockingMobj = NULL;
}
else
{ // Definitely blocking
thing->height = realheight;
return false;
}
}
}
}
// check lines
// [RH] We need to increment validcount again, because a function above may
// have already set some lines to equal the current validcount.
//
// Specifically, when DehackedPickup spawns a new item in its TryPickup()
// function, that new actor will set the lines around it to match validcount
// when it links itself into the world. If we just leave validcount alone,
// that will give the player the freedom to walk through walls at will near
// a pickup they cannot get, because their validcount will prevent them from
// being considered for collision with the player.
validcount++;
thing->BlockingMobj = NULL;
thing->height = realheight;
if (actorsonly || (thing->flags & MF_NOCLIP))
return (thing->BlockingMobj = thingblocker) == NULL;
FBlockLinesIterator it(box);
line_t *ld;
fixed_t thingdropoffz = tm.floorz;
//bool onthing = (thingdropoffz != tmdropoffz);
tm.floorz = tm.dropoffz;
bool good = true;
while ((ld = it.Next()))
{
good &= PIT_CheckLine(ld, box, tm);
}
if (!good)
{
return false;
}
if (tm.ceilingz - tm.floorz < thing->height)
{
return false;
}
if (tm.touchmidtex)
{
tm.dropoffz = tm.floorz;
}
else if (tm.stepthing != NULL)
{
tm.dropoffz = thingdropoffz;
}
return (thing->BlockingMobj = thingblocker) == NULL;
}
bool P_CheckPosition(AActor *thing, fixed_t x, fixed_t y, bool actorsonly)
{
FCheckPosition tm;
return P_CheckPosition(thing, x, y, tm, actorsonly);
}
//----------------------------------------------------------------------------
//
// FUNC P_TestMobjLocation
//
// Returns true if the mobj is not blocked by anything at its current
// location, otherwise returns false.
//
//----------------------------------------------------------------------------
bool P_TestMobjLocation(AActor *mobj)
{
ActorFlags flags;
flags = mobj->flags;
mobj->flags &= ~MF_PICKUP;
if (P_CheckPosition(mobj, mobj->X(), mobj->Y()))
{ // XY is ok, now check Z
mobj->flags = flags;
if ((mobj->Z() < mobj->floorz) || (mobj->Top() > mobj->ceilingz))
{ // Bad Z
return false;
}
return true;
}
mobj->flags = flags;
return false;
}
//=============================================================================
//
// P_CheckOnmobj(AActor *thing)
//
// Checks if the new Z position is legal
//=============================================================================
AActor *P_CheckOnmobj(AActor *thing)
{
fixed_t oldz;
bool good;
AActor *onmobj;
oldz = thing->Z();
P_FakeZMovement(thing);
good = P_TestMobjZ(thing, false, &onmobj);
thing->SetZ(oldz);
return good ? NULL : onmobj;
}
//=============================================================================
//
// P_TestMobjZ
//
//=============================================================================
bool P_TestMobjZ(AActor *actor, bool quick, AActor **pOnmobj)
{
AActor *onmobj = NULL;
if (actor->flags & MF_NOCLIP)
{
if (pOnmobj) *pOnmobj = NULL;
return true;
}
FBlockThingsIterator it(FBoundingBox(actor->X(), actor->Y(), actor->radius));
AActor *thing;
while ((thing = it.Next()))
{
if (!thing->intersects(actor))
{
continue;
}
if ((actor->flags2 | thing->flags2) & MF2_THRUACTORS)
{
continue;
}
if ((actor->flags6 & MF6_THRUSPECIES) && (thing->GetSpecies() == actor->GetSpecies()))
{
continue;
}
if (!(thing->flags & MF_SOLID))
{ // Can't hit thing
continue;
}
if (thing->flags & (MF_SPECIAL | MF_NOCLIP))
{ // [RH] Specials and noclippers don't block moves
continue;
}
if (thing->flags & (MF_CORPSE))
{ // Corpses need a few more checks
if (!(actor->flags & MF_ICECORPSE))
continue;
}
if (!(thing->flags4 & MF4_ACTLIKEBRIDGE) && (actor->flags & MF_SPECIAL))
{ // [RH] Only bridges block pickup items
continue;
}
if (thing == actor)
{ // Don't clip against self
continue;
}
if ((actor->flags & MF_MISSILE) && (thing == actor->target))
{ // Don't clip against whoever shot the missile.
continue;
}
if (actor->Z() > thing->Top())
{ // over thing
continue;
}
else if (actor->Top() <= thing->Z())
{ // under thing
continue;
}
else if (!quick && onmobj != NULL && thing->Top() < onmobj->Top())
{ // something higher is in the way
continue;
}
onmobj = thing;
if (quick) break;
}
if (pOnmobj) *pOnmobj = onmobj;
return onmobj == NULL;
}
//=============================================================================
//
// P_FakeZMovement
//
// Fake the zmovement so that we can check if a move is legal
//=============================================================================
void P_FakeZMovement(AActor *mo)
{
//
// adjust height
//
mo->AddZ(mo->velz);
if ((mo->flags&MF_FLOAT) && mo->target)
{ // float down towards target if too close
if (!(mo->flags & MF_SKULLFLY) && !(mo->flags & MF_INFLOAT))
{
fixed_t dist = mo->AproxDistance(mo->target);
fixed_t delta = (mo->target->Z() + (mo->height >> 1)) - mo->Z();
if (delta < 0 && dist < -(delta * 3))
mo->AddZ(-mo->FloatSpeed);
else if (delta > 0 && dist < (delta * 3))
mo->AddZ(mo->FloatSpeed);
}
}
if (mo->player && mo->flags&MF_NOGRAVITY && (mo->Z() > mo->floorz) && !mo->IsNoClip2())
{
mo->AddZ(finesine[(FINEANGLES / 80 * level.maptime)&FINEMASK] / 8);
}
//
// clip movement
//
if (mo->Z() <= mo->floorz)
{ // hit the floor
mo->SetZ(mo->floorz);
}
if (mo->Top() > mo->ceilingz)
{ // hit the ceiling
mo->SetZ(mo->ceilingz - mo->height);
}
}
//===========================================================================
//
// CheckForPushSpecial
//
//===========================================================================
static void CheckForPushSpecial(line_t *line, int side, AActor *mobj, bool windowcheck)
{
if (line->special && !(mobj->flags6 & MF6_NOTRIGGER))
{
if (windowcheck && !(ib_compatflags & BCOMPATF_NOWINDOWCHECK) && line->backsector != NULL)
{ // Make sure this line actually blocks us and is not a window
// or similar construct we are standing inside of.
fixed_t fzt = line->frontsector->ceilingplane.ZatPoint(mobj);
fixed_t fzb = line->frontsector->floorplane.ZatPoint(mobj);
fixed_t bzt = line->backsector->ceilingplane.ZatPoint(mobj);
fixed_t bzb = line->backsector->floorplane.ZatPoint(mobj);
if (fzt >= mobj->Top() && bzt >= mobj->Top() &&
fzb <= mobj->Z() && bzb <= mobj->Z())
{
// we must also check if some 3D floor in the backsector may be blocking
for (unsigned int i = 0; i<line->backsector->e->XFloor.ffloors.Size(); i++)
{
F3DFloor* rover = line->backsector->e->XFloor.ffloors[i];
if (!(rover->flags & FF_SOLID) || !(rover->flags & FF_EXISTS)) continue;
fixed_t ff_bottom = rover->bottom.plane->ZatPoint(mobj);
fixed_t ff_top = rover->top.plane->ZatPoint(mobj);
if (ff_bottom < mobj->Top() && ff_top > mobj->Z())
{
goto isblocking;
}
}
return;
}
}
isblocking:
if (mobj->flags2 & MF2_PUSHWALL)
{
P_ActivateLine(line, mobj, side, SPAC_Push);
}
else if (mobj->flags2 & MF2_IMPACT)
{
if ((level.flags2 & LEVEL2_MISSILESACTIVATEIMPACT) ||
!(mobj->flags & MF_MISSILE) ||
(mobj->target == NULL))
{
P_ActivateLine(line, mobj, side, SPAC_Impact);
}
else
{
P_ActivateLine(line, mobj->target, side, SPAC_Impact);
}
}
}
}
//==========================================================================
//
// P_TryMove
// Attempt to move to a new position,
// crossing special lines unless MF_TELEPORT is set.
//
//==========================================================================
bool P_TryMove(AActor *thing, fixed_t x, fixed_t y,
int dropoff, // killough 3/15/98: allow dropoff as option
const secplane_t *onfloor, // [RH] Let P_TryMove keep the thing on the floor
FCheckPosition &tm,
bool missileCheck) // [GZ] Fired missiles ignore the drop-off test
{
fixedvec3 oldpos;
sector_t *oldsector;
fixed_t oldz;
int side;
int oldside;
line_t* ld;
sector_t* oldsec = thing->Sector; // [RH] for sector actions
sector_t* newsec;
tm.floatok = false;
oldz = thing->Z();
if (onfloor)
{
thing->SetZ(onfloor->ZatPoint(x, y));
}
thing->flags6 |= MF6_INTRYMOVE;
if (!P_CheckPosition(thing, x, y, tm))
{
AActor *BlockingMobj = thing->BlockingMobj;
// Solid wall or thing
if (!BlockingMobj || BlockingMobj->player || !thing->player)
{
goto pushline;
}
else
{
if (BlockingMobj->player || !thing->player)
{
goto pushline;
}
else if (BlockingMobj->Top() - thing->Z() > thing->MaxStepHeight
|| (BlockingMobj->Sector->ceilingplane.ZatPoint(x, y) - (BlockingMobj->Top()) < thing->height)
|| (tm.ceilingz - (BlockingMobj->Top()) < thing->height))
{
goto pushline;
}
}
if (!(tm.thing->flags2 & MF2_PASSMOBJ) || (i_compatflags & COMPATF_NO_PASSMOBJ))
{
thing->SetZ(oldz);
thing->flags6 &= ~MF6_INTRYMOVE;
return false;
}
}
if (thing->flags3 & MF3_FLOORHUGGER)
{
thing->SetZ(tm.floorz);
}
else if (thing->flags3 & MF3_CEILINGHUGGER)
{
thing->SetZ(tm.ceilingz - thing->height);
}
if (onfloor && tm.floorsector == thing->floorsector)
{
thing->SetZ(tm.floorz);
}
if (!(thing->flags & MF_NOCLIP))
{
if (tm.ceilingz - tm.floorz < thing->height)
{
goto pushline; // doesn't fit
}
tm.floatok = true;
if (!(thing->flags & MF_TELEPORT)
&& tm.ceilingz - thing->Z() < thing->height
&& !(thing->flags3 & MF3_CEILINGHUGGER)
&& (!(thing->flags2 & MF2_FLY) || !(thing->flags & MF_NOGRAVITY)))
{
goto pushline; // mobj must lower itself to fit
}
if (thing->flags2 & MF2_FLY && thing->flags & MF_NOGRAVITY)
{
#if 1
if (thing->Top() > tm.ceilingz)
goto pushline;
#else
// When flying, slide up or down blocking lines until the actor
// is not blocked.
if (thing->Top() > tm.ceilingz)
{
thing->velz = -8 * FRACUNIT;
goto pushline;
}
else if (thing->Z() < tm.floorz && tm.floorz - tm.dropoffz > thing->MaxDropOffHeight)
{
thing->velz = 8 * FRACUNIT;
goto pushline;
}
#endif
}
if (!(thing->flags & MF_TELEPORT) && !(thing->flags3 & MF3_FLOORHUGGER))
{
if ((thing->flags & MF_MISSILE) && !(thing->flags6 & MF6_STEPMISSILE) && tm.floorz > thing->Z())
{ // [RH] Don't let normal missiles climb steps
goto pushline;
}
if (tm.floorz - thing->Z() > thing->MaxStepHeight)
{ // too big a step up
goto pushline;
}
else if (thing->Z() < tm.floorz)
{ // [RH] Check to make sure there's nothing in the way for the step up
fixed_t savedz = thing->Z();
bool good;
thing->SetZ(tm.floorz);
good = P_TestMobjZ(thing);
thing->SetZ(savedz);
if (!good)
{
goto pushline;
}
if (thing->flags6 & MF6_STEPMISSILE)
{
thing->SetZ(tm.floorz);
// If moving down, cancel vertical component of the velocity
if (thing->velz < 0)
{
// If it's a bouncer, let it bounce off its new floor, too.
if (thing->BounceFlags & BOUNCE_Floors)
{
thing->FloorBounceMissile(tm.floorsector->floorplane);
}
else
{
thing->velz = 0;
}
}
}
}
}
// compatibility check: Doom originally did not allow monsters to cross dropoffs at all.
// If the compatibility flag is on, only allow this when the velocity comes from a scroller
if ((i_compatflags & COMPATF_CROSSDROPOFF) && !(thing->flags4 & MF4_SCROLLMOVE))
{
dropoff = false;
}
if (dropoff == 2 && // large jump down (e.g. dogs)
(tm.floorz - tm.dropoffz > 128 * FRACUNIT || thing->target == NULL || thing->target->Z() >tm.dropoffz))
{
dropoff = false;
}
// killough 3/15/98: Allow certain objects to drop off
if ((!dropoff && !(thing->flags & (MF_DROPOFF | MF_FLOAT | MF_MISSILE))) || (thing->flags5&MF5_NODROPOFF))
{
if (!(thing->flags5&MF5_AVOIDINGDROPOFF))
{
fixed_t floorz = tm.floorz;
// [RH] If the thing is standing on something, use its current z as the floorz.
// This is so that it does not walk off of things onto a drop off.
if (thing->flags2 & MF2_ONMOBJ)
{
floorz = MAX(thing->Z(), tm.floorz);
}
if (floorz - tm.dropoffz > thing->MaxDropOffHeight &&
!(thing->flags2 & MF2_BLASTED) && !missileCheck)
{ // Can't move over a dropoff unless it's been blasted
// [GZ] Or missile-spawned
thing->SetZ(oldz);
thing->flags6 &= ~MF6_INTRYMOVE;
return false;
}
}
else
{
// special logic to move a monster off a dropoff
// this intentionally does not check for standing on things.
if (thing->floorz - tm.floorz > thing->MaxDropOffHeight ||
thing->dropoffz - tm.dropoffz > thing->MaxDropOffHeight)
{
thing->flags6 &= ~MF6_INTRYMOVE;
return false;
}
}
}
if (thing->flags2 & MF2_CANTLEAVEFLOORPIC
&& (tm.floorpic != thing->floorpic
|| tm.floorz - thing->Z() != 0))
{ // must stay within a sector of a certain floor type
thing->SetZ(oldz);
thing->flags6 &= ~MF6_INTRYMOVE;
return false;
}
//Added by MC: To prevent bot from getting into dangerous sectors.
if (thing->player && thing->player->Bot != NULL && thing->flags & MF_SHOOTABLE)
{
if (tm.sector != thing->Sector
&& bglobal.IsDangerous(tm.sector))
{
thing->player->Bot->prev = thing->player->Bot->dest;
thing->player->Bot->dest = NULL;
thing->velx = 0;
thing->vely = 0;
thing->SetZ(oldz);
thing->flags6 &= ~MF6_INTRYMOVE;
return false;
}
}
}
// [RH] Check status of eyes against fake floor/ceiling in case
// it slopes or the player's eyes are bobbing in and out.
bool oldAboveFakeFloor, oldAboveFakeCeiling;
fixed_t viewheight;
viewheight = thing->player ? thing->player->viewheight : thing->height / 2;
oldAboveFakeFloor = oldAboveFakeCeiling = false; // pacify GCC
if (oldsec->heightsec)
{
fixed_t eyez = oldz + viewheight;
oldAboveFakeFloor = eyez > oldsec->heightsec->floorplane.ZatPoint(thing);
oldAboveFakeCeiling = eyez > oldsec->heightsec->ceilingplane.ZatPoint(thing);
}
// Borrowed from MBF:
if (thing->BounceFlags & BOUNCE_MBF && // killough 8/13/98
!(thing->flags & (MF_MISSILE | MF_NOGRAVITY)) &&
!thing->IsSentient() && tm.floorz - thing->Z() > 16 * FRACUNIT)
{ // too big a step up for MBF bouncers under gravity
thing->flags6 &= ~MF6_INTRYMOVE;
return false;
}
// the move is ok, so link the thing into its new position
thing->UnlinkFromWorld();
oldpos = thing->Pos();
oldsector = thing->Sector;
thing->floorz = tm.floorz;
thing->ceilingz = tm.ceilingz;
thing->dropoffz = tm.dropoffz; // killough 11/98: keep track of dropoffs
thing->floorpic = tm.floorpic;
thing->floorterrain = tm.floorterrain;
thing->floorsector = tm.floorsector;
thing->ceilingpic = tm.ceilingpic;
thing->ceilingsector = tm.ceilingsector;
thing->SetXY(x, y);
thing->LinkToWorld();
if (thing->flags2 & MF2_FLOORCLIP)
{
thing->AdjustFloorClip();
}
// if any special lines were hit, do the effect
if (!(thing->flags & (MF_TELEPORT | MF_NOCLIP)))
{
while (spechit.Pop(ld))
{
fixedvec3 thingpos = thing->PosRelative(ld);
fixedvec3 oldrelpos = PosRelative(oldpos, ld, oldsector);
// see if the line was crossed
side = P_PointOnLineSide(thingpos.x, thingpos.y, ld);
oldside = P_PointOnLineSide(oldrelpos.x, oldrelpos.y, ld);
if (side != oldside && ld->special && !(thing->flags6 & MF6_NOTRIGGER))
{
if (thing->player && (thing->player->cheats & CF_PREDICTING))
{
P_PredictLine(ld, thing, oldside, SPAC_Cross);
}
else if (thing->player)
{
P_ActivateLine(ld, thing, oldside, SPAC_Cross);
}
else if (thing->flags2 & MF2_MCROSS)
{
P_ActivateLine(ld, thing, oldside, SPAC_MCross);
}
else if (thing->flags2 & MF2_PCROSS)
{
P_ActivateLine(ld, thing, oldside, SPAC_PCross);
}
else if ((ld->special == Teleport ||
ld->special == Teleport_NoFog ||
ld->special == Teleport_Line))
{ // [RH] Just a little hack for BOOM compatibility
P_ActivateLine(ld, thing, oldside, SPAC_MCross);
}
else
{
P_ActivateLine(ld, thing, oldside, SPAC_AnyCross);
}
}
}
}
// [RH] Don't activate anything if just predicting
if (thing->player && (thing->player->cheats & CF_PREDICTING))
{
thing->flags6 &= ~MF6_INTRYMOVE;
return true;
}
// [RH] Check for crossing fake floor/ceiling
newsec = thing->Sector;
if (newsec->heightsec && oldsec->heightsec && newsec->SecActTarget)
{
const sector_t *hs = newsec->heightsec;
fixed_t eyez = thing->Z() + viewheight;
fixed_t fakez = hs->floorplane.ZatPoint(x, y);
if (!oldAboveFakeFloor && eyez > fakez)
{ // View went above fake floor
newsec->SecActTarget->TriggerAction(thing, SECSPAC_EyesSurface);
}
else if (oldAboveFakeFloor && eyez <= fakez)
{ // View went below fake floor
newsec->SecActTarget->TriggerAction(thing, SECSPAC_EyesDive);
}
if (!(hs->MoreFlags & SECF_FAKEFLOORONLY))
{
fakez = hs->ceilingplane.ZatPoint(x, y);
if (!oldAboveFakeCeiling && eyez > fakez)
{ // View went above fake ceiling
newsec->SecActTarget->TriggerAction(thing, SECSPAC_EyesAboveC);
}
else if (oldAboveFakeCeiling && eyez <= fakez)
{ // View went below fake ceiling
newsec->SecActTarget->TriggerAction(thing, SECSPAC_EyesBelowC);
}
}
}
// [RH] If changing sectors, trigger transitions
thing->CheckSectorTransition(oldsec);
thing->flags6 &= ~MF6_INTRYMOVE;
return true;
pushline:
thing->flags6 &= ~MF6_INTRYMOVE;
// [RH] Don't activate anything if just predicting
if (thing->player && (thing->player->cheats & CF_PREDICTING))
{
return false;
}
thing->SetZ(oldz);
if (!(thing->flags&(MF_TELEPORT | MF_NOCLIP)))
{
int numSpecHitTemp;
if (tm.thing->flags2 & MF2_BLASTED)
{
P_DamageMobj(tm.thing, NULL, NULL, tm.thing->Mass >> 5, NAME_Melee);
}
numSpecHitTemp = (int)spechit.Size();
while (numSpecHitTemp > 0)
{
// see which lines were pushed
ld = spechit[--numSpecHitTemp];
fixedvec3 pos = thing->PosRelative(ld);
side = P_PointOnLineSide(pos.x, pos.y, ld);
CheckForPushSpecial(ld, side, thing, true);
}
}
return false;
}
bool P_TryMove(AActor *thing, fixed_t x, fixed_t y,
int dropoff, // killough 3/15/98: allow dropoff as option
const secplane_t *onfloor) // [RH] Let P_TryMove keep the thing on the floor
{
FCheckPosition tm;
return P_TryMove(thing, x, y, dropoff, onfloor, tm);
}
//==========================================================================
//
// P_CheckMove
// Similar to P_TryMove but doesn't actually move the actor. Used for polyobject crushing
//
//==========================================================================
bool P_CheckMove(AActor *thing, fixed_t x, fixed_t y)
{
FCheckPosition tm;
fixed_t newz = thing->Z();
if (!P_CheckPosition(thing, x, y, tm))
{
return false;
}
if (thing->flags3 & MF3_FLOORHUGGER)
{
newz = tm.floorz;
}
else if (thing->flags3 & MF3_CEILINGHUGGER)
{
newz = tm.ceilingz - thing->height;
}
if (!(thing->flags & MF_NOCLIP))
{
if (tm.ceilingz - tm.floorz < thing->height)
{
return false;
}
if (!(thing->flags & MF_TELEPORT)
&& tm.ceilingz - newz < thing->height
&& !(thing->flags3 & MF3_CEILINGHUGGER)
&& (!(thing->flags2 & MF2_FLY) || !(thing->flags & MF_NOGRAVITY)))
{
return false;
}
if (thing->flags2 & MF2_FLY && thing->flags & MF_NOGRAVITY)
{
if (thing->Top() > tm.ceilingz)
return false;
}
if (!(thing->flags & MF_TELEPORT) && !(thing->flags3 & MF3_FLOORHUGGER))
{
if (tm.floorz - newz > thing->MaxStepHeight)
{ // too big a step up
return false;
}
else if ((thing->flags & MF_MISSILE) && !(thing->flags6 & MF6_STEPMISSILE) && tm.floorz > newz)
{ // [RH] Don't let normal missiles climb steps
return false;
}
else if (newz < tm.floorz)
{ // [RH] Check to make sure there's nothing in the way for the step up
fixed_t savedz = thing->Z();
thing->SetZ(newz = tm.floorz);
bool good = P_TestMobjZ(thing);
thing->SetZ(savedz);
if (!good)
{
return false;
}
}
}
if (thing->flags2 & MF2_CANTLEAVEFLOORPIC
&& (tm.floorpic != thing->floorpic
|| tm.floorz - newz != 0))
{ // must stay within a sector of a certain floor type
return false;
}
}
return true;
}
//==========================================================================
//
// SLIDE MOVE
// Allows the player to slide along any angled walls.
//
//==========================================================================
struct FSlide
{
fixed_t bestslidefrac;
fixed_t secondslidefrac;
line_t* bestslideline;
line_t* secondslideline;
AActor* slidemo;
fixed_t tmxmove;
fixed_t tmymove;
void HitSlideLine(line_t *ld);
void SlideTraverse(fixed_t startx, fixed_t starty, fixed_t endx, fixed_t endy);
void SlideMove(AActor *mo, fixed_t tryx, fixed_t tryy, int numsteps);
// The bouncing code uses the same data structure
bool BounceTraverse(fixed_t startx, fixed_t starty, fixed_t endx, fixed_t endy);
bool BounceWall(AActor *mo);
};
//==========================================================================
//
// P_HitSlideLine
// Adjusts the xmove / ymove
// so that the next move will slide along the wall.
// If the floor is icy, then you can bounce off a wall. // phares
//
//==========================================================================
void FSlide::HitSlideLine(line_t* ld)
{
int side;
angle_t lineangle;
angle_t moveangle;
angle_t deltaangle;
fixed_t movelen;
bool icyfloor; // is floor icy? // phares
// |
// Under icy conditions, if the angle of approach to the wall // V
// is more than 45 degrees, then you'll bounce and lose half
// your velocity. If less than 45 degrees, you'll slide along
// the wall. 45 is arbitrary and is believable.
// Check for the special cases of horz or vert walls.
// killough 10/98: only bounce if hit hard (prevents wobbling)
icyfloor =
(P_AproxDistance(tmxmove, tmymove) > 4 * FRACUNIT) &&
var_friction && // killough 8/28/98: calc friction on demand
slidemo->Z() <= slidemo->floorz &&
P_GetFriction(slidemo, NULL) > ORIG_FRICTION;
if (ld->dx == 0)
{ // ST_VERTICAL
if (icyfloor && (abs(tmxmove) > abs(tmymove)))
{
tmxmove = -tmxmove / 2; // absorb half the velocity
tmymove /= 2;
if (slidemo->player && slidemo->health > 0 && !(slidemo->player->cheats & CF_PREDICTING))
{
S_Sound(slidemo, CHAN_VOICE, "*grunt", 1, ATTN_IDLE); // oooff!// ^
}
} // |
else // phares
tmxmove = 0; // no more movement in the X direction
return;
}
if (ld->dy == 0)
{ // ST_HORIZONTAL
if (icyfloor && (abs(tmymove) > abs(tmxmove)))
{
tmxmove /= 2; // absorb half the velocity
tmymove = -tmymove / 2;
if (slidemo->player && slidemo->health > 0 && !(slidemo->player->cheats & CF_PREDICTING))
{
S_Sound(slidemo, CHAN_VOICE, "*grunt", 1, ATTN_IDLE); // oooff!
}
}
else
tmymove = 0; // no more movement in the Y direction
return;
}
// The wall is angled. Bounce if the angle of approach is // phares
// less than 45 degrees. // phares
fixedvec3 pos = slidemo->PosRelative(ld);
side = P_PointOnLineSide(pos.x, pos.y, ld);
lineangle = R_PointToAngle2(0, 0, ld->dx, ld->dy);
if (side == 1)
lineangle += ANG180;
moveangle = R_PointToAngle2(0, 0, tmxmove, tmymove);
moveangle += 10; // prevents sudden path reversal due to // phares
// rounding error // |
deltaangle = moveangle - lineangle; // V
movelen = P_AproxDistance(tmxmove, tmymove);
if (icyfloor && (deltaangle > ANG45) && (deltaangle < ANG90 + ANG45))
{
moveangle = lineangle - deltaangle;
movelen /= 2; // absorb
if (slidemo->player && slidemo->health > 0 && !(slidemo->player->cheats & CF_PREDICTING))
{
S_Sound(slidemo, CHAN_VOICE, "*grunt", 1, ATTN_IDLE); // oooff!
}
moveangle >>= ANGLETOFINESHIFT;
tmxmove = FixedMul(movelen, finecosine[moveangle]);
tmymove = FixedMul(movelen, finesine[moveangle]);
} // ^
else // |
{ // phares
// Doom's original algorithm here does not work well due to imprecisions of the sine table.
// However, keep it active if the wallrunning compatibility flag is on
if (i_compatflags & COMPATF_WALLRUN)
{
fixed_t newlen;
if (deltaangle > ANG180)
deltaangle += ANG180;
// I_Error ("SlideLine: ang>ANG180");
lineangle >>= ANGLETOFINESHIFT;
deltaangle >>= ANGLETOFINESHIFT;
newlen = FixedMul(movelen, finecosine[deltaangle]);
tmxmove = FixedMul(newlen, finecosine[lineangle]);
tmymove = FixedMul(newlen, finesine[lineangle]);
}
else
{
divline_t dll, dlv;
fixed_t inter1, inter2, inter3;
P_MakeDivline(ld, &dll);
dlv.x = pos.x;
dlv.y = pos.y;
dlv.dx = dll.dy;
dlv.dy = -dll.dx;
inter1 = P_InterceptVector(&dll, &dlv);
dlv.dx = tmxmove;
dlv.dy = tmymove;
inter2 = P_InterceptVector(&dll, &dlv);
inter3 = P_InterceptVector(&dlv, &dll);
if (inter3 != 0)
{
tmxmove = Scale(inter2 - inter1, dll.dx, inter3);
tmymove = Scale(inter2 - inter1, dll.dy, inter3);
}
else
{
tmxmove = tmymove = 0;
}
}
} // phares
}
//==========================================================================
//
// PTR_SlideTraverse
//
//==========================================================================
void FSlide::SlideTraverse(fixed_t startx, fixed_t starty, fixed_t endx, fixed_t endy)
{
FLineOpening open;
FPathTraverse it(startx, starty, endx, endy, PT_ADDLINES);
intercept_t *in;
while ((in = it.Next()))
{
line_t* li;
if (!in->isaline)
{
// should never happen
Printf("PTR_SlideTraverse: not a line?");
continue;
}
li = in->d.line;
if (!(li->flags & ML_TWOSIDED) || !li->backsector)
{
fixedvec3 pos = slidemo->PosRelative(li);
if (P_PointOnLineSide(pos.x, pos.y, li))
{
// don't hit the back side
continue;
}
goto isblocking;
}
if (li->flags & (ML_BLOCKING | ML_BLOCKEVERYTHING))
{
goto isblocking;
}
if (li->flags & ML_BLOCK_PLAYERS && slidemo->player != NULL)
{
goto isblocking;
}
if (li->flags & ML_BLOCKMONSTERS && !((slidemo->flags3 & MF3_NOBLOCKMONST)
|| ((i_compatflags & COMPATF_NOBLOCKFRIENDS) && (slidemo->flags & MF_FRIENDLY))))
{
goto isblocking;
}
// set openrange, opentop, openbottom
P_LineOpening(open, slidemo, li, it.Trace().x + FixedMul(it.Trace().dx, in->frac),
it.Trace().y + FixedMul(it.Trace().dy, in->frac));
if (open.range < slidemo->height)
goto isblocking; // doesn't fit
if (open.top - slidemo->Z() < slidemo->height)
goto isblocking; // mobj is too high
if (open.bottom - slidemo->Z() > slidemo->MaxStepHeight)
{
goto isblocking; // too big a step up
}
else if (slidemo->Z() < open.bottom)
{ // [RH] Check to make sure there's nothing in the way for the step up
fixed_t savedz = slidemo->Z();
slidemo->SetZ(open.bottom);
bool good = P_TestMobjZ(slidemo);
slidemo->SetZ(savedz);
if (!good)
{
goto isblocking;
}
}
// this line doesn't block movement
continue;
// the line does block movement,
// see if it is closer than best so far
isblocking:
if (in->frac < bestslidefrac)
{
secondslidefrac = bestslidefrac;
secondslideline = bestslideline;
bestslidefrac = in->frac;
bestslideline = li;
}
return; // stop
}
}
//==========================================================================
//
// P_SlideMove
//
// The velx / vely move is bad, so try to slide along a wall.
//
// Find the first line hit, move flush to it, and slide along it
//
// This is a kludgy mess.
//
//==========================================================================
void FSlide::SlideMove(AActor *mo, fixed_t tryx, fixed_t tryy, int numsteps)
{
fixed_t leadx, leady;
fixed_t trailx, traily;
fixed_t newx, newy;
fixed_t xmove, ymove;
const secplane_t * walkplane;
int hitcount;
hitcount = 3;
slidemo = mo;
if (mo->player && mo->player->mo == mo && mo->reactiontime > 0)
return; // player coming right out of a teleporter.
retry:
if (!--hitcount)
goto stairstep; // don't loop forever
// trace along the three leading corners
if (tryx > 0)
{
leadx = mo->X() + mo->radius;
trailx = mo->X() - mo->radius;
}
else
{
leadx = mo->X() - mo->radius;
trailx = mo->X() + mo->radius;
}
if (tryy > 0)
{
leady = mo->Y() + mo->radius;
traily = mo->Y() - mo->radius;
}
else
{
leady = mo->Y() - mo->radius;
traily = mo->Y() + mo->radius;
}
bestslidefrac = FRACUNIT + 1;
SlideTraverse(leadx, leady, leadx + tryx, leady + tryy);
SlideTraverse(trailx, leady, trailx + tryx, leady + tryy);
SlideTraverse(leadx, traily, leadx + tryx, traily + tryy);
// move up to the wall
if (bestslidefrac == FRACUNIT + 1)
{
// the move must have hit the middle, so stairstep
stairstep:
// killough 3/15/98: Allow objects to drop off ledges
xmove = 0, ymove = tryy;
walkplane = P_CheckSlopeWalk(mo, xmove, ymove);
if (!P_TryMove(mo, mo->X() + xmove, mo->Y() + ymove, true, walkplane))
{
xmove = tryx, ymove = 0;
walkplane = P_CheckSlopeWalk(mo, xmove, ymove);
P_TryMove(mo, mo->X() + xmove, mo->Y() + ymove, true, walkplane);
}
return;
}
// fudge a bit to make sure it doesn't hit
bestslidefrac -= FRACUNIT / 32;
if (bestslidefrac > 0)
{
newx = FixedMul(tryx, bestslidefrac);
newy = FixedMul(tryy, bestslidefrac);
// [BL] We need to abandon this function if we end up going through a teleporter
const fixed_t startvelx = mo->velx;
const fixed_t startvely = mo->vely;
// killough 3/15/98: Allow objects to drop off ledges
if (!P_TryMove(mo, mo->X() + newx, mo->Y() + newy, true))
goto stairstep;
if (mo->velx != startvelx || mo->vely != startvely)
return;
}
// Now continue along the wall.
bestslidefrac = FRACUNIT - (bestslidefrac + FRACUNIT / 32); // remainder
if (bestslidefrac > FRACUNIT)
bestslidefrac = FRACUNIT;
else if (bestslidefrac <= 0)
return;
tryx = tmxmove = FixedMul(tryx, bestslidefrac);
tryy = tmymove = FixedMul(tryy, bestslidefrac);
HitSlideLine(bestslideline); // clip the moves
mo->velx = tmxmove * numsteps;
mo->vely = tmymove * numsteps;
// killough 10/98: affect the bobbing the same way (but not voodoo dolls)
if (mo->player && mo->player->mo == mo)
{
if (abs(mo->player->velx) > abs(mo->velx))
mo->player->velx = mo->velx;
if (abs(mo->player->vely) > abs(mo->vely))
mo->player->vely = mo->vely;
}
walkplane = P_CheckSlopeWalk(mo, tmxmove, tmymove);
// killough 3/15/98: Allow objects to drop off ledges
if (!P_TryMove(mo, mo->X() + tmxmove, mo->Y() + tmymove, true, walkplane))
{
goto retry;
}
}
void P_SlideMove(AActor *mo, fixed_t tryx, fixed_t tryy, int numsteps)
{
FSlide slide;
slide.SlideMove(mo, tryx, tryy, numsteps);
}
//============================================================================
//
// P_CheckSlopeWalk
//
//============================================================================
const secplane_t * P_CheckSlopeWalk(AActor *actor, fixed_t &xmove, fixed_t &ymove)
{
static secplane_t copyplane;
if (actor->flags & MF_NOGRAVITY)
{
return NULL;
}
const secplane_t *plane = &actor->floorsector->floorplane;
fixed_t planezhere = plane->ZatPoint(actor);
for (unsigned int i = 0; i<actor->floorsector->e->XFloor.ffloors.Size(); i++)
{
F3DFloor * rover = actor->floorsector->e->XFloor.ffloors[i];
if (!(rover->flags & FF_SOLID) || !(rover->flags & FF_EXISTS)) continue;
fixed_t thisplanez = rover->top.plane->ZatPoint(actor);
if (thisplanez>planezhere && thisplanez <= actor->Z() + actor->MaxStepHeight)
{
copyplane = *rover->top.plane;
if (copyplane.c<0) copyplane.FlipVert();
plane = ©plane;
planezhere = thisplanez;
}
}
if (actor->floorsector != actor->Sector)
{
for (unsigned int i = 0; i<actor->Sector->e->XFloor.ffloors.Size(); i++)
{
F3DFloor * rover = actor->Sector->e->XFloor.ffloors[i];
if (!(rover->flags & FF_SOLID) || !(rover->flags & FF_EXISTS)) continue;
fixed_t thisplanez = rover->top.plane->ZatPoint(actor);
if (thisplanez>planezhere && thisplanez <= actor->Z() + actor->MaxStepHeight)
{
copyplane = *rover->top.plane;
if (copyplane.c<0) copyplane.FlipVert();
plane = ©plane;
planezhere = thisplanez;
}
}
}
if (actor->floorsector != actor->Sector)
{
// this additional check prevents sliding on sloped dropoffs
if (planezhere>actor->floorz + 4 * FRACUNIT)
return NULL;
}
if (actor->Z() - planezhere > FRACUNIT)
{ // not on floor
return NULL;
}
if ((plane->a | plane->b) != 0)
{
fixed_t destx, desty;
fixed_t t;
destx = actor->X() + xmove;
desty = actor->Y() + ymove;
t = TMulScale16(plane->a, destx, plane->b, desty, plane->c, actor->Z()) + plane->d;
if (t < 0)
{ // Desired location is behind (below) the plane
// (i.e. Walking up the plane)
if (plane->c < STEEPSLOPE)
{ // Can't climb up slopes of ~45 degrees or more
if (actor->flags & MF_NOCLIP)
{
return (actor->floorsector == actor->Sector) ? plane : NULL;
}
else
{
const msecnode_t *node;
bool dopush = true;
if (plane->c > STEEPSLOPE * 2 / 3)
{
for (node = actor->touching_sectorlist; node; node = node->m_tnext)
{
const sector_t *sec = node->m_sector;
if (sec->floorplane.c >= STEEPSLOPE)
{
if (sec->floorplane.ZatPoint(destx, desty) >= actor->Z() - actor->MaxStepHeight)
{
dopush = false;
break;
}
}
}
}
if (dopush)
{
xmove = actor->velx = plane->a * 2;
ymove = actor->vely = plane->b * 2;
}
return (actor->floorsector == actor->Sector) ? plane : NULL;
}
}
// Slide the desired location along the plane's normal
// so that it lies on the plane's surface
destx -= FixedMul(plane->a, t);
desty -= FixedMul(plane->b, t);
xmove = destx - actor->X();
ymove = desty - actor->Y();
return (actor->floorsector == actor->Sector) ? plane : NULL;
}
else if (t > 0)
{ // Desired location is in front of (above) the plane
if (planezhere == actor->Z())
{ // Actor's current spot is on/in the plane, so walk down it
// Same principle as walking up, except reversed
destx += FixedMul(plane->a, t);
desty += FixedMul(plane->b, t);
xmove = destx - actor->X();
ymove = desty - actor->Y();
return (actor->floorsector == actor->Sector) ? plane : NULL;
}
}
}
return NULL;
}
//============================================================================
//
// PTR_BounceTraverse
//
//============================================================================
bool FSlide::BounceTraverse(fixed_t startx, fixed_t starty, fixed_t endx, fixed_t endy)
{
FLineOpening open;
FPathTraverse it(startx, starty, endx, endy, PT_ADDLINES);
intercept_t *in;
while ((in = it.Next()))
{
line_t *li;
if (!in->isaline)
{
Printf("PTR_BounceTraverse: not a line?");
continue;
}
li = in->d.line;
assert(((size_t)li - (size_t)lines) % sizeof(line_t) == 0);
if (li->flags & ML_BLOCKEVERYTHING)
{
goto bounceblocking;
}
if (!(li->flags&ML_TWOSIDED) || !li->backsector)
{
if (P_PointOnLineSide(slidemo->X(), slidemo->Y(), li))
continue; // don't hit the back side
goto bounceblocking;
}
P_LineOpening(open, slidemo, li, it.Trace().x + FixedMul(it.Trace().dx, in->frac),
it.Trace().y + FixedMul(it.Trace().dy, in->frac)); // set openrange, opentop, openbottom
if (open.range < slidemo->height)
goto bounceblocking; // doesn't fit
if (open.top - slidemo->Z() < slidemo->height)
goto bounceblocking; // mobj is too high
if (open.bottom > slidemo->Z())
goto bounceblocking; // mobj is too low
continue; // this line doesn't block movement
// the line does block movement, see if it is closer than best so far
bounceblocking:
if (in->frac < bestslidefrac)
{
secondslidefrac = bestslidefrac;
secondslideline = bestslideline;
bestslidefrac = in->frac;
bestslideline = li;
}
return false; // stop
}
return true;
}
//============================================================================
//
// P_BounceWall
//
//============================================================================
bool FSlide::BounceWall(AActor *mo)
{
fixed_t leadx, leady;
int side;
angle_t lineangle, moveangle, deltaangle;
fixed_t movelen;
line_t *line;
if (!(mo->BounceFlags & BOUNCE_Walls))
{
return false;
}
slidemo = mo;
//
// trace along the three leading corners
//
if (mo->velx > 0)
{
leadx = mo->X() + mo->radius;
}
else
{
leadx = mo->X() - mo->radius;
}
if (mo->vely > 0)
{
leady = mo->Y() + mo->radius;
}
else
{
leady = mo->Y() - mo->radius;
}
bestslidefrac = FRACUNIT + 1;
bestslideline = mo->BlockingLine;
if (BounceTraverse(leadx, leady, leadx + mo->velx, leady + mo->vely) && mo->BlockingLine == NULL)
{ // Could not find a wall, so bounce off the floor/ceiling instead.
fixed_t floordist = mo->Z() - mo->floorz;
fixed_t ceildist = mo->ceilingz - mo->Z();
if (floordist <= ceildist)
{
mo->FloorBounceMissile(mo->Sector->floorplane);
return true;
}
else
{
mo->FloorBounceMissile(mo->Sector->ceilingplane);
return true;
}
}
line = bestslideline;
if (line->special == Line_Horizon)
{
mo->SeeSound = 0; // it might make a sound otherwise
mo->Destroy();
return true;
}
// The amount of bounces is limited
if (mo->bouncecount>0 && --mo->bouncecount == 0)
{
if (mo->flags & MF_MISSILE)
P_ExplodeMissile(mo, line, NULL);
else
mo->Die(NULL, NULL);
return true;
}
side = P_PointOnLineSide(mo->X(), mo->Y(), line);
lineangle = R_PointToAngle2(0, 0, line->dx, line->dy);
if (side == 1)
{
lineangle += ANG180;
}
moveangle = R_PointToAngle2(0, 0, mo->velx, mo->vely);
deltaangle = (2 * lineangle) - moveangle;
mo->angle = deltaangle;
deltaangle >>= ANGLETOFINESHIFT;
movelen = fixed_t(sqrt(double(mo->velx)*mo->velx + double(mo->vely)*mo->vely));
movelen = FixedMul(movelen, mo->wallbouncefactor);
FBoundingBox box(mo->X(), mo->Y(), mo->radius);
if (box.BoxOnLineSide(line) == -1)
{
fixedvec3 pos = mo->Vec3Offset(
FixedMul(mo->radius, finecosine[deltaangle]),
FixedMul(mo->radius, finesine[deltaangle]), 0);
mo->SetOrigin(pos, true);
}
if (movelen < FRACUNIT)
{
movelen = 2 * FRACUNIT;
}
mo->velx = FixedMul(movelen, finecosine[deltaangle]);
mo->vely = FixedMul(movelen, finesine[deltaangle]);
if (mo->BounceFlags & BOUNCE_UseBounceState)
{
FState *bouncestate = mo->FindState(NAME_Bounce, NAME_Wall);
if (bouncestate != NULL)
{
mo->SetState(bouncestate);
}
}
return true;
}
bool P_BounceWall(AActor *mo)
{
FSlide slide;
return slide.BounceWall(mo);
}
//==========================================================================
//
//
//
//==========================================================================
extern FRandom pr_bounce;
bool P_BounceActor(AActor *mo, AActor *BlockingMobj, bool ontop)
{
//Don't go through all of this if the actor is reflective and wants things to pass through them.
if (BlockingMobj && ((BlockingMobj->flags2 & MF2_REFLECTIVE) && (BlockingMobj->flags7 & MF7_THRUREFLECT))) return true;
if (mo && BlockingMobj && ((mo->BounceFlags & BOUNCE_AllActors)
|| ((mo->flags & MF_MISSILE) && (!(mo->flags2 & MF2_RIP)
|| (BlockingMobj->flags5 & MF5_DONTRIP)
|| ((mo->flags6 & MF6_NOBOSSRIP) && (BlockingMobj->flags2 & MF2_BOSS))) && (BlockingMobj->flags2 & MF2_REFLECTIVE))
|| ((BlockingMobj->player == NULL) && (!(BlockingMobj->flags3 & MF3_ISMONSTER)))))
{
if (mo->bouncecount > 0 && --mo->bouncecount == 0) return false;
if (mo->flags7 & MF7_HITTARGET) mo->target = BlockingMobj;
if (mo->flags7 & MF7_HITMASTER) mo->master = BlockingMobj;
if (mo->flags7 & MF7_HITTRACER) mo->tracer = BlockingMobj;
if (!ontop)
{
fixed_t speed;
angle_t angle = BlockingMobj->AngleTo(mo) + ANGLE_1*((pr_bounce() % 16) - 8);
speed = P_AproxDistance(mo->velx, mo->vely);
speed = FixedMul(speed, mo->wallbouncefactor); // [GZ] was 0.75, using wallbouncefactor seems more consistent
mo->angle = angle;
angle >>= ANGLETOFINESHIFT;
mo->velx = FixedMul(speed, finecosine[angle]);
mo->vely = FixedMul(speed, finesine[angle]);
mo->PlayBounceSound(true);
if (mo->BounceFlags & BOUNCE_UseBounceState)
{
FName names[] = { NAME_Bounce, NAME_Actor, NAME_Creature };
FState *bouncestate;
int count = 2;
if ((BlockingMobj->flags & MF_SHOOTABLE) && !(BlockingMobj->flags & MF_NOBLOOD))
{
count = 3;
}
bouncestate = mo->FindState(count, names);
if (bouncestate != NULL)
{
mo->SetState(bouncestate);
}
}
}
else
{
fixed_t dot = mo->velz;
if (mo->BounceFlags & (BOUNCE_HereticType | BOUNCE_MBF))
{
mo->velz -= MulScale15(FRACUNIT, dot);
if (!(mo->BounceFlags & BOUNCE_MBF)) // Heretic projectiles die, MBF projectiles don't.
{
mo->flags |= MF_INBOUNCE;
mo->SetState(mo->FindState(NAME_Death));
mo->flags &= ~MF_INBOUNCE;
return false;
}
else
{
mo->velz = FixedMul(mo->velz, mo->bouncefactor);
}
}
else // Don't run through this for MBF-style bounces
{
// The reflected velocity keeps only about 70% of its original speed
mo->velz = FixedMul(mo->velz - MulScale15(FRACUNIT, dot), mo->bouncefactor);
}
mo->PlayBounceSound(true);
if (mo->BounceFlags & BOUNCE_MBF) // Bring it to rest below a certain speed
{
if (abs(mo->velz) < (fixed_t)(mo->Mass * mo->GetGravity() / 64))
mo->velz = 0;
}
else if (mo->BounceFlags & (BOUNCE_AutoOff | BOUNCE_AutoOffFloorOnly))
{
if (!(mo->flags & MF_NOGRAVITY) && (mo->velz < 3 * FRACUNIT))
mo->BounceFlags &= ~BOUNCE_TypeMask;
}
}
return true;
}
return false;
}
//============================================================================
//
// Aiming
//
//============================================================================
struct aim_t
{
fixed_t aimpitch;
fixed_t attackrange;
fixed_t shootz; // Height if not aiming up or down
AActor* shootthing;
AActor* friender; // actor to check friendliness again
fixed_t toppitch, bottompitch;
AActor * linetarget;
AActor * thing_friend, *thing_other;
angle_t pitch_friend, pitch_other;
int flags;
sector_t * lastsector;
secplane_t * lastfloorplane;
secplane_t * lastceilingplane;
bool crossedffloors;
bool AimTraverse3DFloors(const divline_t &trace, intercept_t * in);
void AimTraverse(fixed_t startx, fixed_t starty, fixed_t endx, fixed_t endy, AActor *target = NULL);
};
//============================================================================
//
// AimTraverse3DFloors
//
//============================================================================
bool aim_t::AimTraverse3DFloors(const divline_t &trace, intercept_t * in)
{
sector_t * nextsector;
secplane_t * nexttopplane, *nextbottomplane;
line_t * li = in->d.line;
nextsector = NULL;
nexttopplane = nextbottomplane = NULL;
if (li->backsector == NULL) return true; // shouldn't really happen but crashed once for me...
if (li->frontsector->e->XFloor.ffloors.Size() || li->backsector->e->XFloor.ffloors.Size())
{
int frontflag;
F3DFloor* rover;
int highpitch, lowpitch;
fixed_t trX = trace.x + FixedMul(trace.dx, in->frac);
fixed_t trY = trace.y + FixedMul(trace.dy, in->frac);
fixed_t dist = FixedMul(attackrange, in->frac);
frontflag = P_PointOnLineSide(shootthing->X(), shootthing->Y(), li);
// 3D floor check. This is not 100% accurate but normally sufficient when
// combined with a final sight check
for (int i = 1; i <= 2; i++)
{
sector_t * s = i == 1 ? li->frontsector : li->backsector;
for (unsigned k = 0; k<s->e->XFloor.ffloors.Size(); k++)
{
crossedffloors = true;
rover = s->e->XFloor.ffloors[k];
if ((rover->flags & FF_SHOOTTHROUGH) || !(rover->flags & FF_EXISTS)) continue;
fixed_t ff_bottom = rover->bottom.plane->ZatPoint(trX, trY);
fixed_t ff_top = rover->top.plane->ZatPoint(trX, trY);
highpitch = -(int)R_PointToAngle2(0, shootz, dist, ff_top);
lowpitch = -(int)R_PointToAngle2(0, shootz, dist, ff_bottom);
if (highpitch <= toppitch)
{
// blocks completely
if (lowpitch >= bottompitch) return false;
// blocks upper edge of view
if (lowpitch>toppitch)
{
toppitch = lowpitch;
if (frontflag != i - 1)
{
nexttopplane = rover->bottom.plane;
}
}
}
else if (lowpitch >= bottompitch)
{
// blocks lower edge of view
if (highpitch<bottompitch)
{
bottompitch = highpitch;
if (frontflag != i - 1)
{
nextbottomplane = rover->top.plane;
}
}
}
// trace is leaving a sector with a 3d-floor
if (frontflag == i - 1)
{
if (s == lastsector)
{
// upper slope intersects with this 3d-floor
if (rover->bottom.plane == lastceilingplane && lowpitch > toppitch)
{
toppitch = lowpitch;
}
// lower slope intersects with this 3d-floor
if (rover->top.plane == lastfloorplane && highpitch < bottompitch)
{
bottompitch = highpitch;
}
}
}
if (toppitch >= bottompitch) return false; // stop
}
}
}
lastsector = nextsector;
lastceilingplane = nexttopplane;
lastfloorplane = nextbottomplane;
return true;
}
//============================================================================
//
// PTR_AimTraverse
// Sets linetaget and aimpitch when a target is aimed at.
//
//============================================================================
void aim_t::AimTraverse(fixed_t startx, fixed_t starty, fixed_t endx, fixed_t endy, AActor *target)
{
FPathTraverse it(startx, starty, endx, endy, PT_ADDLINES | PT_ADDTHINGS | PT_COMPATIBLE);
intercept_t *in;
while ((in = it.Next()))
{
line_t* li;
AActor* th;
fixed_t pitch;
fixed_t thingtoppitch;
fixed_t thingbottompitch;
fixed_t dist;
int thingpitch;
if (in->isaline)
{
li = in->d.line;
if (!(li->flags & ML_TWOSIDED) || (li->flags & ML_BLOCKEVERYTHING))
return; // stop
// Crosses a two sided line.
// A two sided line will restrict the possible target ranges.
FLineOpening open;
P_LineOpening(open, NULL, li, it.Trace().x + FixedMul(it.Trace().dx, in->frac),
it.Trace().y + FixedMul(it.Trace().dy, in->frac));
if (open.bottom >= open.top)
return; // stop
dist = FixedMul(attackrange, in->frac);
pitch = -(int)R_PointToAngle2(0, shootz, dist, open.bottom);
if (pitch < bottompitch)
bottompitch = pitch;
pitch = -(int)R_PointToAngle2(0, shootz, dist, open.top);
if (pitch > toppitch)
toppitch = pitch;
if (toppitch >= bottompitch)
return; // stop
if (!AimTraverse3DFloors(it.Trace(), in)) return;
continue; // shot continues
}
// shoot a thing
th = in->d.thing;
if (th == shootthing)
continue; // can't shoot self
if (target != NULL && th != target)
continue; // only care about target, and you're not it
// If we want to start a conversation anything that has one should be
// found, regardless of other settings.
if (!(flags & ALF_CHECKCONVERSATION) || th->Conversation == NULL)
{
if (!(flags & ALF_CHECKNONSHOOTABLE)) // For info CCMD, ignore stuff about GHOST and SHOOTABLE flags
{
if (!(th->flags&MF_SHOOTABLE))
continue; // corpse or something
// check for physical attacks on a ghost
if ((th->flags3 & MF3_GHOST) &&
shootthing->player && // [RH] Be sure shootthing is a player
shootthing->player->ReadyWeapon &&
(shootthing->player->ReadyWeapon->flags2 & MF2_THRUGHOST))
{
continue;
}
}
}
dist = FixedMul(attackrange, in->frac);
// Don't autoaim certain special actors
if (!cl_doautoaim && th->flags6 & MF6_NOTAUTOAIMED)
{
continue;
}
// we must do one last check whether the trace has crossed a 3D floor
if (lastsector == th->Sector && th->Sector->e->XFloor.ffloors.Size())
{
if (lastceilingplane)
{
fixed_t ff_top = lastceilingplane->ZatPoint(th);
fixed_t pitch = -(int)R_PointToAngle2(0, shootz, dist, ff_top);
// upper slope intersects with this 3d-floor
if (pitch > toppitch)
{
toppitch = pitch;
}
}
if (lastfloorplane)
{
fixed_t ff_bottom = lastfloorplane->ZatPoint(th);
fixed_t pitch = -(int)R_PointToAngle2(0, shootz, dist, ff_bottom);
// lower slope intersects with this 3d-floor
if (pitch < bottompitch)
{
bottompitch = pitch;
}
}
}
// check angles to see if the thing can be aimed at
thingtoppitch = -(int)R_PointToAngle2(0, shootz, dist, th->Z() + th->height);
if (thingtoppitch > bottompitch)
continue; // shot over the thing
thingbottompitch = -(int)R_PointToAngle2(0, shootz, dist, th->Z());
if (thingbottompitch < toppitch)
continue; // shot under the thing
if (crossedffloors)
{
// if 3D floors were in the way do an extra visibility check for safety
if (!P_CheckSight(shootthing, th, SF_IGNOREVISIBILITY | SF_IGNOREWATERBOUNDARY))
{
// the thing can't be seen so we can safely exclude its range from our aiming field
if (thingtoppitch<toppitch)
{
if (thingbottompitch>toppitch) toppitch = thingbottompitch;
}
else if (thingbottompitch>bottompitch)
{
if (thingtoppitch<bottompitch) bottompitch = thingtoppitch;
}
if (toppitch < bottompitch) continue;
else return;
}
}
// this thing can be hit!
if (thingtoppitch < toppitch)
thingtoppitch = toppitch;
if (thingbottompitch > bottompitch)
thingbottompitch = bottompitch;
thingpitch = thingtoppitch / 2 + thingbottompitch / 2;
if (flags & ALF_CHECK3D)
{
// We need to do a 3D distance check here because this is nearly always used in
// combination with P_LineAttack. P_LineAttack uses 3D distance but FPathTraverse
// only 2D. This causes some problems with Hexen's weapons that use different
// attack modes based on distance to target
fixed_t cosine = finecosine[thingpitch >> ANGLETOFINESHIFT];
if (cosine != 0)
{
fixed_t d3 = FixedDiv(FixedMul(P_AproxDistance(it.Trace().dx, it.Trace().dy), in->frac), cosine);
if (d3 > attackrange)
{
return;
}
}
}
if ((flags & ALF_NOFRIENDS) && th->IsFriend(friender))
{
continue;
}
else if (sv_smartaim != 0 && !(flags & ALF_FORCENOSMART))
{
// try to be a little smarter about what to aim at!
// In particular avoid autoaiming at friends and barrels.
if (th->IsFriend(friender))
{
if (sv_smartaim < 2)
{
// friends don't aim at friends (except players), at least not first
thing_friend = th;
pitch_friend = thingpitch;
}
}
else if (!(th->flags3 & MF3_ISMONSTER) && th->player == NULL)
{
if (sv_smartaim < 3)
{
// don't autoaim at barrels and other shootable stuff unless no monsters have been found
thing_other = th;
pitch_other = thingpitch;
}
}
else
{
linetarget = th;
aimpitch = thingpitch;
return;
}
}
else
{
linetarget = th;
aimpitch = thingpitch;
return;
}
}
}
//============================================================================
//
// P_AimLineAttack
//
//============================================================================
fixed_t P_AimLineAttack(AActor *t1, angle_t angle, fixed_t distance, AActor **pLineTarget, fixed_t vrange,
int flags, AActor *target, AActor *friender)
{
fixed_t x2;
fixed_t y2;
aim_t aim;
angle >>= ANGLETOFINESHIFT;
aim.flags = flags;
aim.shootthing = t1;
aim.friender = (friender == NULL) ? t1 : friender;
x2 = t1->X() + (distance >> FRACBITS)*finecosine[angle];
y2 = t1->Y() + (distance >> FRACBITS)*finesine[angle];
aim.shootz = t1->Z() + (t1->height >> 1) - t1->floorclip;
if (t1->player != NULL)
{
aim.shootz += FixedMul(t1->player->mo->AttackZOffset, t1->player->crouchfactor);
}
else
{
aim.shootz += 8 * FRACUNIT;
}
// can't shoot outside view angles
if (vrange == 0)
{
if (t1->player == NULL || !level.IsFreelookAllowed())
{
vrange = ANGLE_1 * 35;
}
else
{
// [BB] Disable autoaim on weapons with WIF_NOAUTOAIM.
AWeapon *weapon = t1->player->ReadyWeapon;
if (weapon && (weapon->WeaponFlags & WIF_NOAUTOAIM))
{
vrange = ANGLE_1 / 2;
}
else
{
// 35 degrees is approximately what Doom used. You cannot have a
// vrange of 0 degrees, because then toppitch and bottompitch will
// be equal, and PTR_AimTraverse will never find anything to shoot at
// if it crosses a line.
vrange = clamp(t1->player->userinfo.GetAimDist(), ANGLE_1 / 2, ANGLE_1 * 35);
}
}
}
aim.toppitch = t1->pitch - vrange;
aim.bottompitch = t1->pitch + vrange;
aim.attackrange = distance;
aim.linetarget = NULL;
// for smart aiming
aim.thing_friend = aim.thing_other = NULL;
// Information for tracking crossed 3D floors
aim.aimpitch = t1->pitch;
aim.crossedffloors = t1->Sector->e->XFloor.ffloors.Size() != 0;
aim.lastsector = t1->Sector;
aim.lastfloorplane = aim.lastceilingplane = NULL;
// set initial 3d-floor info
for (unsigned i = 0; i<t1->Sector->e->XFloor.ffloors.Size(); i++)
{
F3DFloor * rover = t1->Sector->e->XFloor.ffloors[i];
fixed_t bottomz = rover->bottom.plane->ZatPoint(t1);
if (bottomz >= t1->Top()) aim.lastceilingplane = rover->bottom.plane;
bottomz = rover->top.plane->ZatPoint(t1);
if (bottomz <= t1->Z()) aim.lastfloorplane = rover->top.plane;
}
aim.AimTraverse(t1->X(), t1->Y(), x2, y2, target);
if (!aim.linetarget)
{
if (aim.thing_other)
{
aim.linetarget = aim.thing_other;
aim.aimpitch = aim.pitch_other;
}
else if (aim.thing_friend)
{
aim.linetarget = aim.thing_friend;
aim.aimpitch = aim.pitch_friend;
}
}
if (pLineTarget)
{
*pLineTarget = aim.linetarget;
}
return aim.linetarget ? aim.aimpitch : t1->pitch;
}
//==========================================================================
//
//
//
//==========================================================================
struct Origin
{
AActor *Caller;
bool hitGhosts;
bool hitSameSpecies;
};
static ETraceStatus CheckForActor(FTraceResults &res, void *userdata)
{
if (res.HitType != TRACE_HitActor)
{
return TRACE_Stop;
}
Origin *data = (Origin *)userdata;
// check for physical attacks on spectrals
if (res.Actor->flags4 & MF4_SPECTRAL)
{
return TRACE_Skip;
}
if (data->hitSameSpecies && res.Actor->GetSpecies() == data->Caller->GetSpecies())
{
return TRACE_Skip;
}
if (data->hitGhosts && res.Actor->flags3 & MF3_GHOST)
{
return TRACE_Skip;
}
return TRACE_Stop;
}
//==========================================================================
//
// P_LineAttack
//
// if damage == 0, it is just a test trace that will leave linetarget set
//
//==========================================================================
AActor *P_LineAttack(AActor *t1, angle_t angle, fixed_t distance,
int pitch, int damage, FName damageType, const PClass *pufftype, int flags, AActor **victim, int *actualdamage)
{
fixed_t vx, vy, vz, shootz;
FTraceResults trace;
Origin TData;
TData.Caller = t1;
angle_t srcangle = angle;
int srcpitch = pitch;
bool killPuff = false;
AActor *puff = NULL;
int pflag = 0;
int puffFlags = (flags & LAF_ISMELEEATTACK) ? PF_MELEERANGE : 0;
if (flags & LAF_NORANDOMPUFFZ)
puffFlags |= PF_NORANDOMZ;
if (victim != NULL)
{
*victim = NULL;
}
if (actualdamage != NULL)
{
*actualdamage = 0;
}
angle >>= ANGLETOFINESHIFT;
pitch = (angle_t)(pitch) >> ANGLETOFINESHIFT;
vx = FixedMul(finecosine[pitch], finecosine[angle]);
vy = FixedMul(finecosine[pitch], finesine[angle]);
vz = -finesine[pitch];
shootz = t1->Z() - t1->floorclip + (t1->height >> 1);
if (t1->player != NULL)
{
shootz += FixedMul(t1->player->mo->AttackZOffset, t1->player->crouchfactor);
if (damageType == NAME_Melee || damageType == NAME_Hitscan)
{
// this is coming from a weapon attack function which needs to transfer information to the obituary code,
// We need to preserve this info from the damage type because the actual damage type can get overridden by the puff
pflag = DMG_PLAYERATTACK;
}
}
else
{
shootz += 8 * FRACUNIT;
}
// We need to check the defaults of the replacement here
AActor *puffDefaults = GetDefaultByType(pufftype->GetReplacement());
TData.hitGhosts = (t1->player != NULL &&
t1->player->ReadyWeapon != NULL &&
(t1->player->ReadyWeapon->flags2 & MF2_THRUGHOST)) ||
(puffDefaults && (puffDefaults->flags2 & MF2_THRUGHOST));
TData.hitSameSpecies = (puffDefaults && (puffDefaults->flags6 & MF6_MTHRUSPECIES));
// if the puff uses a non-standard damage type, this will override default, hitscan and melee damage type.
// All other explicitly passed damage types (currenty only MDK) will be preserved.
if ((damageType == NAME_None || damageType == NAME_Melee || damageType == NAME_Hitscan) &&
puffDefaults != NULL && puffDefaults->DamageType != NAME_None)
{
damageType = puffDefaults->DamageType;
}
int tflags;
if (puffDefaults != NULL && puffDefaults->flags6 & MF6_NOTRIGGER) tflags = TRACE_NoSky;
else tflags = TRACE_NoSky | TRACE_Impact;
if (!Trace(t1->X(), t1->Y(), shootz, t1->Sector, vx, vy, vz, distance,
MF_SHOOTABLE, ML_BLOCKEVERYTHING | ML_BLOCKHITSCAN, t1, trace,
tflags, CheckForActor, &TData))
{ // hit nothing
if (puffDefaults == NULL)
{
}
else if (puffDefaults->ActiveSound)
{ // Play miss sound
S_Sound(t1, CHAN_WEAPON, puffDefaults->ActiveSound, 1, ATTN_NORM);
}
if (puffDefaults != NULL && puffDefaults->flags3 & MF3_ALWAYSPUFF)
{ // Spawn the puff anyway
puff = P_SpawnPuff(t1, pufftype, trace.X, trace.Y, trace.Z, angle - ANG180, 2, puffFlags);
}
else
{
return NULL;
}
}
else
{
fixed_t hitx = 0, hity = 0, hitz = 0;
if (trace.HitType != TRACE_HitActor)
{
// position a bit closer for puffs
if (trace.HitType != TRACE_HitWall || trace.Line->special != Line_Horizon)
{
fixed_t closer = trace.Distance - 4 * FRACUNIT;
fixedvec2 pos = t1->Vec2Offset(FixedMul(vx, closer), FixedMul(vy, closer));
puff = P_SpawnPuff(t1, pufftype, pos.x, pos.y,
shootz + FixedMul(vz, closer), angle - ANG90, 0, puffFlags);
}
// [RH] Spawn a decal
if (trace.HitType == TRACE_HitWall && trace.Line->special != Line_Horizon && !(flags & LAF_NOIMPACTDECAL) && !(puffDefaults->flags7 & MF7_NODECAL))
{
// [TN] If the actor or weapon has a decal defined, use that one.
if (t1->DecalGenerator != NULL ||
(t1->player != NULL && t1->player->ReadyWeapon != NULL && t1->player->ReadyWeapon->DecalGenerator != NULL))
{
// [ZK] If puff has FORCEDECAL set, do not use the weapon's decal
if (puffDefaults->flags7 & MF7_FORCEDECAL && puff != NULL && puff->DecalGenerator)
SpawnShootDecal(puff, trace);
else
SpawnShootDecal(t1, trace);
}
// Else, look if the bulletpuff has a decal defined.
else if (puff != NULL && puff->DecalGenerator)
{
SpawnShootDecal(puff, trace);
}
else
{
SpawnShootDecal(t1, trace);
}
}
else if (puff != NULL &&
trace.CrossedWater == NULL &&
trace.Sector->heightsec == NULL &&
trace.HitType == TRACE_HitFloor)
{
// Using the puff's position is not accurate enough.
// Instead make it splash at the actual hit position
hitx = t1->X() + FixedMul(vx, trace.Distance);
hity = t1->Y() + FixedMul(vy, trace.Distance);
hitz = shootz + FixedMul(vz, trace.Distance);
P_HitWater(puff, P_PointInSector(hitx, hity), hitx, hity, hitz);
}
}
else
{
bool bloodsplatter = (t1->flags5 & MF5_BLOODSPLATTER) ||
(t1->player != NULL && t1->player->ReadyWeapon != NULL &&
(t1->player->ReadyWeapon->WeaponFlags & WIF_AXEBLOOD));
bool axeBlood = (t1->player != NULL &&
t1->player->ReadyWeapon != NULL &&
(t1->player->ReadyWeapon->WeaponFlags & WIF_AXEBLOOD));
// Hit a thing, so it could be either a puff or blood
fixed_t dist = trace.Distance;
// position a bit closer for puffs/blood if using compatibility mode.
if (i_compatflags & COMPATF_HITSCAN) dist -= 10 * FRACUNIT;
hitx = t1->X() + FixedMul(vx, dist);
hity = t1->Y() + FixedMul(vy, dist);
hitz = shootz + FixedMul(vz, dist);
// Spawn bullet puffs or blood spots, depending on target type.
if ((puffDefaults != NULL && puffDefaults->flags3 & MF3_PUFFONACTORS) ||
(trace.Actor->flags & MF_NOBLOOD) ||
(trace.Actor->flags2 & (MF2_INVULNERABLE | MF2_DORMANT)))
{
if (!(trace.Actor->flags & MF_NOBLOOD))
puffFlags |= PF_HITTHINGBLEED;
// We must pass the unreplaced puff type here
puff = P_SpawnPuff(t1, pufftype, hitx, hity, hitz, angle - ANG180, 2, puffFlags | PF_HITTHING, trace.Actor);
}
// Allow puffs to inflict poison damage, so that hitscans can poison, too.
if (puffDefaults != NULL && puffDefaults->PoisonDamage > 0 && puffDefaults->PoisonDuration != INT_MIN)
{
P_PoisonMobj(trace.Actor, puff ? puff : t1, t1, puffDefaults->PoisonDamage, puffDefaults->PoisonDuration, puffDefaults->PoisonPeriod, puffDefaults->PoisonDamageType);
}
// [GZ] If MF6_FORCEPAIN is set, we need to call P_DamageMobj even if damage is 0!
// Note: The puff may not yet be spawned here so we must check the class defaults, not the actor.
int newdam = damage;
if (damage || (puffDefaults != NULL && ((puffDefaults->flags6 & MF6_FORCEPAIN) || (puffDefaults->flags7 & MF7_CAUSEPAIN))))
{
int dmgflags = DMG_INFLICTOR_IS_PUFF | pflag;
// Allow MF5_PIERCEARMOR on a weapon as well.
if (t1->player != NULL && (dmgflags & DMG_PLAYERATTACK) && t1->player->ReadyWeapon != NULL &&
t1->player->ReadyWeapon->flags5 & MF5_PIERCEARMOR)
{
dmgflags |= DMG_NO_ARMOR;
}
if (puff == NULL)
{
// Since the puff is the damage inflictor we need it here
// regardless of whether it is displayed or not.
puff = P_SpawnPuff(t1, pufftype, hitx, hity, hitz, angle - ANG180, 2, puffFlags | PF_HITTHING | PF_TEMPORARY);
killPuff = true;
}
newdam = P_DamageMobj(trace.Actor, puff ? puff : t1, t1, damage, damageType, dmgflags);
if (actualdamage != NULL)
{
*actualdamage = newdam;
}
}
if (!(puffDefaults != NULL && puffDefaults->flags3&MF3_BLOODLESSIMPACT))
{
if (!bloodsplatter && !axeBlood &&
!(trace.Actor->flags & MF_NOBLOOD) &&
!(trace.Actor->flags2 & (MF2_INVULNERABLE | MF2_DORMANT)))
{
P_SpawnBlood(hitx, hity, hitz, angle - ANG180, newdam > 0 ? newdam : damage, trace.Actor);
}
if (damage)
{
if (bloodsplatter || axeBlood)
{
if (!(trace.Actor->flags&MF_NOBLOOD) &&
!(trace.Actor->flags2&(MF2_INVULNERABLE | MF2_DORMANT)))
{
if (axeBlood)
{
P_BloodSplatter2(hitx, hity, hitz, trace.Actor);
}
if (pr_lineattack() < 192)
{
P_BloodSplatter(hitx, hity, hitz, trace.Actor);
}
}
}
// [RH] Stick blood to walls
P_TraceBleed(newdam > 0 ? newdam : damage, trace.X, trace.Y, trace.Z,
trace.Actor, srcangle, srcpitch);
}
}
if (victim != NULL)
{
*victim = trace.Actor;
}
}
if (trace.Crossed3DWater || trace.CrossedWater)
{
if (puff == NULL)
{ // Spawn puff just to get a mass for the splash
puff = P_SpawnPuff(t1, pufftype, hitx, hity, hitz, angle - ANG180, 2, puffFlags | PF_HITTHING | PF_TEMPORARY);
killPuff = true;
}
SpawnDeepSplash(t1, trace, puff, vx, vy, vz, shootz, trace.Crossed3DWater != NULL);
}
}
if (killPuff && puff != NULL)
{
puff->Destroy();
puff = NULL;
}
return puff;
}
AActor *P_LineAttack(AActor *t1, angle_t angle, fixed_t distance,
int pitch, int damage, FName damageType, FName pufftype, int flags, AActor **victim, int *actualdamage)
{
const PClass * type = PClass::FindClass(pufftype);
if (victim != NULL)
{
*victim = NULL;
}
if (type == NULL)
{
Printf("Attempt to spawn unknown actor type '%s'\n", pufftype.GetChars());
}
else
{
return P_LineAttack(t1, angle, distance, pitch, damage, damageType, type, flags, victim, actualdamage);
}
return NULL;
}
//==========================================================================
//
// P_LinePickActor
//
//==========================================================================
AActor *P_LinePickActor(AActor *t1, angle_t angle, fixed_t distance, int pitch,
ActorFlags actorMask, DWORD wallMask)
{
fixed_t vx, vy, vz, shootz;
angle >>= ANGLETOFINESHIFT;
pitch = (angle_t)(pitch) >> ANGLETOFINESHIFT;
vx = FixedMul(finecosine[pitch], finecosine[angle]);
vy = FixedMul(finecosine[pitch], finesine[angle]);
vz = -finesine[pitch];
shootz = t1->Z() - t1->floorclip + (t1->height >> 1);
if (t1->player != NULL)
{
shootz += FixedMul(t1->player->mo->AttackZOffset, t1->player->crouchfactor);
}
else
{
shootz += 8 * FRACUNIT;
}
FTraceResults trace;
Origin TData;
TData.Caller = t1;
TData.hitGhosts = true;
if (Trace(t1->X(), t1->Y(), shootz, t1->Sector, vx, vy, vz, distance,
actorMask, wallMask, t1, trace, TRACE_NoSky, CheckForActor, &TData))
{
if (trace.HitType == TRACE_HitActor)
{
return trace.Actor;
}
}
return NULL;
}
//==========================================================================
//
//
//
//==========================================================================
void P_TraceBleed(int damage, fixed_t x, fixed_t y, fixed_t z, AActor *actor, angle_t angle, int pitch)
{
if (!cl_bloodsplats)
return;
const char *bloodType = "BloodSplat";
int count;
int noise;
if ((actor->flags & MF_NOBLOOD) ||
(actor->flags5 & MF5_NOBLOODDECALS) ||
(actor->flags2 & (MF2_INVULNERABLE | MF2_DORMANT)) ||
(actor->player && actor->player->cheats & CF_GODMODE))
{
return;
}
if (damage < 15)
{ // For low damages, there is a chance to not spray blood at all
if (damage <= 10)
{
if (pr_tracebleed() < 160)
{
return;
}
}
count = 1;
noise = 18;
}
else if (damage < 25)
{
count = 2;
noise = 19;
}
else
{ // For high damages, there is a chance to spray just one big glob of blood
if (pr_tracebleed() < 24)
{
bloodType = "BloodSmear";
count = 1;
noise = 20;
}
else
{
count = 3;
noise = 20;
}
}
for (; count; --count)
{
FTraceResults bleedtrace;
angle_t bleedang = (angle + ((pr_tracebleed() - 128) << noise)) >> ANGLETOFINESHIFT;
angle_t bleedpitch = (angle_t)(pitch + ((pr_tracebleed() - 128) << noise)) >> ANGLETOFINESHIFT;
fixed_t vx = FixedMul(finecosine[bleedpitch], finecosine[bleedang]);
fixed_t vy = FixedMul(finecosine[bleedpitch], finesine[bleedang]);
fixed_t vz = -finesine[bleedpitch];
if (Trace(x, y, z, actor->Sector,
vx, vy, vz, 172 * FRACUNIT, 0, ML_BLOCKEVERYTHING, actor,
bleedtrace, TRACE_NoSky))
{
if (bleedtrace.HitType == TRACE_HitWall)
{
PalEntry bloodcolor = actor->GetBloodColor();
if (bloodcolor != 0)
{
bloodcolor.r >>= 1; // the full color is too bright for blood decals
bloodcolor.g >>= 1;
bloodcolor.b >>= 1;
bloodcolor.a = 1;
}
DImpactDecal::StaticCreate(bloodType,
bleedtrace.X, bleedtrace.Y, bleedtrace.Z,
bleedtrace.Line->sidedef[bleedtrace.Side],
bleedtrace.ffloor,
bloodcolor);
}
}
}
}
void P_TraceBleed(int damage, AActor *target, angle_t angle, int pitch)
{
P_TraceBleed(damage, target->X(), target->Y(), target->Z() + target->height / 2,
target, angle, pitch);
}
//==========================================================================
//
//
//
//==========================================================================
void P_TraceBleed(int damage, AActor *target, AActor *missile)
{
int pitch;
if (target == NULL || missile->flags3 & MF3_BLOODLESSIMPACT)
{
return;
}
if (missile->velz != 0)
{
double aim;
aim = atan((double)missile->velz / (double)target->AproxDistance(missile));
pitch = -(int)(aim * ANGLE_180 / PI);
}
else
{
pitch = 0;
}
P_TraceBleed(damage, target->X(), target->Y(), target->Z() + target->height / 2,
target, missile->AngleTo(target),
pitch);
}
//==========================================================================
//
//
//
//==========================================================================
void P_TraceBleed(int damage, AActor *target)
{
if (target != NULL)
{
fixed_t one = pr_tracebleed() << 24;
fixed_t two = (pr_tracebleed() - 128) << 16;
P_TraceBleed(damage, target->X(), target->Y(), target->Z() + target->height / 2,
target, one, two);
}
}
//==========================================================================
//
// [RH] Rail gun stuffage
//
//==========================================================================
struct SRailHit
{
AActor *HitActor;
fixed_t Distance;
};
struct RailData
{
AActor *Caller;
TArray<SRailHit> RailHits;
bool StopAtOne;
bool StopAtInvul;
bool ThruSpecies;
};
static ETraceStatus ProcessRailHit(FTraceResults &res, void *userdata)
{
RailData *data = (RailData *)userdata;
if (res.HitType != TRACE_HitActor)
{
return TRACE_Stop;
}
// Invulnerable things completely block the shot
if (data->StopAtInvul && res.Actor->flags2 & MF2_INVULNERABLE)
{
return TRACE_Stop;
}
// Skip actors with the same species if the puff has MTHRUSPECIES.
if (data->ThruSpecies && res.Actor->GetSpecies() == data->Caller->GetSpecies())
{
return TRACE_Skip;
}
// Save this thing for damaging later, and continue the trace
SRailHit newhit;
newhit.HitActor = res.Actor;
newhit.Distance = res.Distance - 10 * FRACUNIT; // put blood in front
data->RailHits.Push(newhit);
return data->StopAtOne ? TRACE_Stop : TRACE_Continue;
}
//==========================================================================
//
//
//
//==========================================================================
void P_RailAttack(AActor *source, int damage, int offset_xy, fixed_t offset_z, int color1, int color2, double maxdiff, int railflags, const PClass *puffclass, angle_t angleoffset, angle_t pitchoffset, fixed_t distance, int duration, double sparsity, double drift, const PClass *spawnclass, int SpiralOffset)
{
fixed_t vx, vy, vz;
angle_t angle, pitch;
TVector3<double> start, end;
FTraceResults trace;
fixed_t shootz;
if (puffclass == NULL) puffclass = PClass::FindClass(NAME_BulletPuff);
pitch = ((angle_t)(-source->pitch) + pitchoffset) >> ANGLETOFINESHIFT;
angle = (source->angle + angleoffset) >> ANGLETOFINESHIFT;
vx = FixedMul(finecosine[pitch], finecosine[angle]);
vy = FixedMul(finecosine[pitch], finesine[angle]);
vz = finesine[pitch];
shootz = source->Z() - source->floorclip + (source->height >> 1) + offset_z;
if (!(railflags & RAF_CENTERZ))
{
if (source->player != NULL)
{
shootz += FixedMul(source->player->mo->AttackZOffset, source->player->crouchfactor);
}
else
{
shootz += 8 * FRACUNIT;
}
}
angle = ((source->angle + angleoffset) - ANG90) >> ANGLETOFINESHIFT;
fixedvec2 xy = source->Vec2Offset(offset_xy * finecosine[angle], offset_xy * finesine[angle]);
RailData rail_data;
rail_data.Caller = source;
rail_data.StopAtOne = !!(railflags & RAF_NOPIERCE);
start.X = FIXED2FLOAT(xy.x);
start.Y = FIXED2FLOAT(xy.y);
start.Z = FIXED2FLOAT(shootz);
int flags;
assert(puffclass != NULL); // Because we set it to a default above
AActor *puffDefaults = GetDefaultByType(puffclass->GetReplacement()); //Contains all the flags such as FOILINVUL, etc.
flags = (puffDefaults->flags6 & MF6_NOTRIGGER) ? 0 : TRACE_PCross | TRACE_Impact;
rail_data.StopAtInvul = (puffDefaults->flags3 & MF3_FOILINVUL) ? false : true;
rail_data.ThruSpecies = (puffDefaults->flags6 & MF6_MTHRUSPECIES) ? true : false;
Trace(xy.x, xy.y, shootz, source->Sector, vx, vy, vz,
distance, MF_SHOOTABLE, ML_BLOCKEVERYTHING, source, trace,
flags, ProcessRailHit, &rail_data);
// Hurt anything the trace hit
unsigned int i;
FName damagetype = (puffDefaults == NULL || puffDefaults->DamageType == NAME_None) ? FName(NAME_Railgun) : puffDefaults->DamageType;
// used as damage inflictor
AActor *thepuff = NULL;
if (puffclass != NULL) thepuff = Spawn(puffclass, source->Pos(), ALLOW_REPLACE);
for (i = 0; i < rail_data.RailHits.Size(); i++)
{
fixed_t x, y, z;
bool spawnpuff;
bool bleed = false;
int puffflags = PF_HITTHING;
AActor *hitactor = rail_data.RailHits[i].HitActor;
fixed_t hitdist = rail_data.RailHits[i].Distance;
x = xy.x + FixedMul(hitdist, vx);
y = xy.y + FixedMul(hitdist, vy);
z = shootz + FixedMul(hitdist, vz);
if ((hitactor->flags & MF_NOBLOOD) ||
(hitactor->flags2 & MF2_DORMANT || ((hitactor->flags2 & MF2_INVULNERABLE) && !(puffDefaults->flags3 & MF3_FOILINVUL))))
{
spawnpuff = (puffclass != NULL);
}
else
{
spawnpuff = (puffclass != NULL && puffDefaults->flags3 & MF3_ALWAYSPUFF);
puffflags |= PF_HITTHINGBLEED; // [XA] Allow for puffs to jump to XDeath state.
if (!(puffDefaults->flags3 & MF3_BLOODLESSIMPACT))
{
bleed = true;
}
}
if (spawnpuff)
{
P_SpawnPuff(source, puffclass, x, y, z, (source->angle + angleoffset) - ANG90, 1, puffflags, hitactor);
}
int dmgFlagPass = DMG_INFLICTOR_IS_PUFF;
if (puffDefaults != NULL) // is this even possible?
{
if (puffDefaults->PoisonDamage > 0 && puffDefaults->PoisonDuration != INT_MIN)
{
P_PoisonMobj(hitactor, thepuff ? thepuff : source, source, puffDefaults->PoisonDamage, puffDefaults->PoisonDuration, puffDefaults->PoisonPeriod, puffDefaults->PoisonDamageType);
}
if (puffDefaults->flags3 & MF3_FOILINVUL) dmgFlagPass |= DMG_FOILINVUL;
if (puffDefaults->flags7 & MF7_FOILBUDDHA) dmgFlagPass |= DMG_FOILBUDDHA;
}
int newdam = P_DamageMobj(hitactor, thepuff ? thepuff : source, source, damage, damagetype, dmgFlagPass);
if (bleed)
{
P_SpawnBlood(x, y, z, (source->angle + angleoffset) - ANG180, newdam > 0 ? newdam : damage, hitactor);
P_TraceBleed(newdam > 0 ? newdam : damage, x, y, z, hitactor, source->angle, pitch);
}
}
// Spawn a decal or puff at the point where the trace ended.
if (trace.HitType == TRACE_HitWall)
{
AActor* puff = NULL;
if (puffclass != NULL && puffDefaults->flags3 & MF3_ALWAYSPUFF)
{
puff = P_SpawnPuff(source, puffclass, trace.X, trace.Y, trace.Z, (source->angle + angleoffset) - ANG90, 1, 0);
if (puff && (trace.Line != NULL) && (trace.Line->special == Line_Horizon) && !(puff->flags3 & MF3_SKYEXPLODE))
puff->Destroy();
}
if (puff != NULL && puffDefaults->flags7 & MF7_FORCEDECAL && puff->DecalGenerator)
SpawnShootDecal(puff, trace);
else
SpawnShootDecal(source, trace);
}
if (trace.HitType == TRACE_HitFloor || trace.HitType == TRACE_HitCeiling)
{
AActor* puff = NULL;
if (puffclass != NULL && puffDefaults->flags3 & MF3_ALWAYSPUFF)
{
puff = P_SpawnPuff(source, puffclass, trace.X, trace.Y, trace.Z, (source->angle + angleoffset) - ANG90, 1, 0);
if (puff && !(puff->flags3 & MF3_SKYEXPLODE) &&
(((trace.HitType == TRACE_HitFloor) && (puff->floorpic == skyflatnum)) ||
((trace.HitType == TRACE_HitCeiling) && (puff->ceilingpic == skyflatnum))))
{
puff->Destroy();
}
}
}
if (thepuff != NULL)
{
if (trace.HitType == TRACE_HitFloor &&
trace.CrossedWater == NULL &&
trace.Sector->heightsec == NULL)
{
thepuff->SetOrigin(trace.X, trace.Y, trace.Z, false);
P_HitWater(thepuff, trace.Sector);
}
if (trace.Crossed3DWater || trace.CrossedWater)
{
SpawnDeepSplash(source, trace, thepuff, vx, vy, vz, shootz, trace.Crossed3DWater != NULL);
}
thepuff->Destroy();
}
// Draw the slug's trail.
end.X = FIXED2DBL(trace.X);
end.Y = FIXED2DBL(trace.Y);
end.Z = FIXED2DBL(trace.Z);
P_DrawRailTrail(source, start, end, color1, color2, maxdiff, railflags, spawnclass, source->angle + angleoffset, duration, sparsity, drift, SpiralOffset);
}
//==========================================================================
//
// [RH] P_AimCamera
//
//==========================================================================
CVAR(Float, chase_height, -8.f, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
CVAR(Float, chase_dist, 90.f, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
void P_AimCamera(AActor *t1, fixed_t &CameraX, fixed_t &CameraY, fixed_t &CameraZ, sector_t *&CameraSector)
{
fixed_t distance = (fixed_t)(clamp<double>(chase_dist, 0, 30000) * FRACUNIT);
angle_t angle = (t1->angle - ANG180) >> ANGLETOFINESHIFT;
angle_t pitch = (angle_t)(t1->pitch) >> ANGLETOFINESHIFT;
FTraceResults trace;
fixed_t vx, vy, vz, sz;
vx = FixedMul(finecosine[pitch], finecosine[angle]);
vy = FixedMul(finecosine[pitch], finesine[angle]);
vz = finesine[pitch];
sz = t1->Z() - t1->floorclip + t1->height + (fixed_t)(clamp<double>(chase_height, -1000, 1000) * FRACUNIT);
if (Trace(t1->X(), t1->Y(), sz, t1->Sector,
vx, vy, vz, distance, 0, 0, NULL, trace) &&
trace.Distance > 10 * FRACUNIT)
{
// Position camera slightly in front of hit thing
fixed_t dist = trace.Distance - 5 * FRACUNIT;
CameraX = t1->X() + FixedMul(vx, dist);
CameraY = t1->Y() + FixedMul(vy, dist);
CameraZ = sz + FixedMul(vz, dist);
}
else
{
CameraX = trace.X;
CameraY = trace.Y;
CameraZ = trace.Z;
}
CameraSector = trace.Sector;
}
//==========================================================================
//
// P_TalkFacing
//
// Looks for something within 5.625 degrees left or right of the player
// to talk to.
//
//==========================================================================
bool P_TalkFacing(AActor *player)
{
AActor *linetarget;
P_AimLineAttack(player, player->angle, TALKRANGE, &linetarget, ANGLE_1 * 35, ALF_FORCENOSMART | ALF_CHECKCONVERSATION);
if (linetarget == NULL)
{
P_AimLineAttack(player, player->angle + (ANGLE_90 >> 4), TALKRANGE, &linetarget, ANGLE_1 * 35, ALF_FORCENOSMART | ALF_CHECKCONVERSATION);
if (linetarget == NULL)
{
P_AimLineAttack(player, player->angle - (ANGLE_90 >> 4), TALKRANGE, &linetarget, ANGLE_1 * 35, ALF_FORCENOSMART | ALF_CHECKCONVERSATION);
if (linetarget == NULL)
{
return false;
}
}
}
// Dead things can't talk.
if (linetarget->health <= 0)
{
return false;
}
// Fighting things don't talk either.
if (linetarget->flags4 & MF4_INCOMBAT)
{
return false;
}
if (linetarget->Conversation != NULL)
{
// Give the NPC a chance to play a brief animation
linetarget->ConversationAnimation(0);
P_StartConversation(linetarget, player, true, true);
return true;
}
return false;
}
//==========================================================================
//
// USE LINES
//
//==========================================================================
bool P_UseTraverse(AActor *usething, fixed_t endx, fixed_t endy, bool &foundline)
{
FPathTraverse it(usething->X(), usething->Y(), endx, endy, PT_ADDLINES | PT_ADDTHINGS);
intercept_t *in;
while ((in = it.Next()))
{
// [RH] Check for things to talk with or use a puzzle item on
if (!in->isaline)
{
if (usething == in->d.thing)
continue;
// Check thing
// Check for puzzle item use or USESPECIAL flag
// Extended to use the same activationtype mechanism as BUMPSPECIAL does
if (in->d.thing->flags5 & MF5_USESPECIAL || in->d.thing->special == UsePuzzleItem)
{
if (P_ActivateThingSpecial(in->d.thing, usething))
return true;
}
continue;
}
FLineOpening open;
if (in->d.line->special == 0 || !(in->d.line->activation & (SPAC_Use | SPAC_UseThrough | SPAC_UseBack)))
{
blocked:
if (in->d.line->flags & (ML_BLOCKEVERYTHING | ML_BLOCKUSE))
{
open.range = 0;
}
else
{
P_LineOpening(open, NULL, in->d.line, it.Trace().x + FixedMul(it.Trace().dx, in->frac),
it.Trace().y + FixedMul(it.Trace().dy, in->frac));
}
if (open.range <= 0 ||
(in->d.line->special != 0 && (i_compatflags & COMPATF_USEBLOCKING)))
{
// [RH] Give sector a chance to intercept the use
sector_t * sec;
sec = usething->Sector;
if (sec->SecActTarget && sec->SecActTarget->TriggerAction(usething, SECSPAC_Use))
{
return true;
}
sec = P_PointOnLineSide(usething->X(), usething->Y(), in->d.line) == 0 ?
in->d.line->frontsector : in->d.line->backsector;
if (sec != NULL && sec->SecActTarget &&
sec->SecActTarget->TriggerAction(usething, SECSPAC_UseWall))
{
return true;
}
if (usething->player)
{
S_Sound(usething, CHAN_VOICE, "*usefail", 1, ATTN_IDLE);
}
return true; // can't use through a wall
}
foundline = true;
continue; // not a special line, but keep checking
}
if (P_PointOnLineSide(usething->X(), usething->Y(), in->d.line) == 1)
{
if (!(in->d.line->activation & SPAC_UseBack))
{
// [RH] continue traversal for two-sided lines
//return in->d.line->backsector != NULL; // don't use back side
goto blocked; // do a proper check for back sides of triggers
}
else
{
P_ActivateLine(in->d.line, usething, 1, SPAC_UseBack);
return true;
}
}
else
{
if ((in->d.line->activation & (SPAC_Use | SPAC_UseThrough | SPAC_UseBack)) == SPAC_UseBack)
{
goto blocked; // Line cannot be used from front side so treat it as a non-trigger line
}
P_ActivateLine(in->d.line, usething, 0, SPAC_Use);
//WAS can't use more than one special line in a row
//jff 3/21/98 NOW multiple use allowed with enabling line flag
//[RH] And now I've changed it again. If the line is of type
// SPAC_USE, then it eats the use. Everything else passes
// it through, including SPAC_USETHROUGH.
if (i_compatflags & COMPATF_USEBLOCKING)
{
if (in->d.line->activation & SPAC_UseThrough) continue;
else return true;
}
else
{
if (!(in->d.line->activation & SPAC_Use)) continue;
else return true;
}
}
}
return false;
}
//==========================================================================
//
// Returns false if a "oof" sound should be made because of a blocking
// linedef. Makes 2s middles which are impassable, as well as 2s uppers
// and lowers which block the player, cause the sound effect when the
// player tries to activate them. Specials are excluded, although it is
// assumed that all special linedefs within reach have been considered
// and rejected already (see P_UseLines).
//
// by <NAME>
//
//==========================================================================
bool P_NoWayTraverse(AActor *usething, fixed_t endx, fixed_t endy)
{
FPathTraverse it(usething->X(), usething->Y(), endx, endy, PT_ADDLINES);
intercept_t *in;
while ((in = it.Next()))
{
line_t *ld = in->d.line;
FLineOpening open;
// [GrafZahl] de-obfuscated. Was I the only one who was unable to make sense out of
// this convoluted mess?
if (ld->special) continue;
if (ld->flags&(ML_BLOCKING | ML_BLOCKEVERYTHING | ML_BLOCK_PLAYERS)) return true;
P_LineOpening(open, NULL, ld, it.Trace().x + FixedMul(it.Trace().dx, in->frac),
it.Trace().y + FixedMul(it.Trace().dy, in->frac));
if (open.range <= 0 ||
open.bottom > usething->Z() + usething->MaxStepHeight ||
open.top < usething->Top()) return true;
}
return false;
}
//==========================================================================
//
// P_UseLines
//
// Looks for special lines in front of the player to activate
//
//==========================================================================
void P_UseLines(player_t *player)
{
bool foundline = false;
// [NS] Now queries the Player's UseRange.
fixedvec2 end = player->mo->Vec2Angle(player->mo->UseRange, player->mo->angle, true);
// old code:
//
// P_PathTraverse ( x1, y1, x2, y2, PT_ADDLINES, PTR_UseTraverse );
//
// This added test makes the "oof" sound work on 2s lines -- killough:
if (!P_UseTraverse(player->mo, end.x, end.y, foundline))
{ // [RH] Give sector a chance to eat the use
sector_t *sec = player->mo->Sector;
int spac = SECSPAC_Use;
if (foundline) spac |= SECSPAC_UseWall;
if ((!sec->SecActTarget || !sec->SecActTarget->TriggerAction(player->mo, spac)) &&
P_NoWayTraverse(player->mo, end.x, end.y))
{
S_Sound(player->mo, CHAN_VOICE, "*usefail", 1, ATTN_IDLE);
}
}
}
//==========================================================================
//
// P_UsePuzzleItem
//
// Returns true if the puzzle item was used on a line or a thing.
//
//==========================================================================
bool P_UsePuzzleItem(AActor *PuzzleItemUser, int PuzzleItemType)
{
int angle;
fixed_t x1, y1, x2, y2, usedist;
angle = PuzzleItemUser->angle >> ANGLETOFINESHIFT;
x1 = PuzzleItemUser->X();
y1 = PuzzleItemUser->Y();
// [NS] If it's a Player, get their UseRange.
if (PuzzleItemUser->player)
usedist = PuzzleItemUser->player->mo->UseRange;
else
usedist = USERANGE;
x2 = x1 + FixedMul(usedist, finecosine[angle]);
y2 = y1 + FixedMul(usedist, finesine[angle]);
FPathTraverse it(x1, y1, x2, y2, PT_ADDLINES | PT_ADDTHINGS);
intercept_t *in;
while ((in = it.Next()))
{
AActor *mobj;
FLineOpening open;
if (in->isaline)
{ // Check line
if (in->d.line->special != UsePuzzleItem)
{
P_LineOpening(open, NULL, in->d.line, it.Trace().x + FixedMul(it.Trace().dx, in->frac),
it.Trace().y + FixedMul(it.Trace().dy, in->frac));
if (open.range <= 0)
{
return false; // can't use through a wall
}
continue;
}
if (P_PointOnLineSide(PuzzleItemUser->X(), PuzzleItemUser->Y(), in->d.line) == 1)
{ // Don't use back sides
return false;
}
if (PuzzleItemType != in->d.line->args[0])
{ // Item type doesn't match
return false;
}
int args[3] = { in->d.line->args[2], in->d.line->args[3], in->d.line->args[4] };
P_StartScript(PuzzleItemUser, in->d.line, in->d.line->args[1], NULL, args, 3, ACS_ALWAYS);
in->d.line->special = 0;
return true;
}
// Check thing
mobj = in->d.thing;
if (mobj->special != UsePuzzleItem)
{ // Wrong special
continue;
}
if (PuzzleItemType != mobj->args[0])
{ // Item type doesn't match
continue;
}
int args[3] = { mobj->args[2], mobj->args[3], mobj->args[4] };
P_StartScript(PuzzleItemUser, NULL, mobj->args[1], NULL, args, 3, ACS_ALWAYS);
mobj->special = 0;
return true;
}
return false;
}
//==========================================================================
//
// RADIUS ATTACK
//
//
//==========================================================================
// [RH] Damage scale to apply to thing that shot the missile.
static float selfthrustscale;
CUSTOM_CVAR(Float, splashfactor, 1.f, CVAR_SERVERINFO)
{
if (self <= 0.f)
self = 1.f;
else
selfthrustscale = 1.f / self;
}
//==========================================================================
//
// P_RadiusAttack
// Source is the creature that caused the explosion at spot.
//
//==========================================================================
void P_RadiusAttack(AActor *bombspot, AActor *bombsource, int bombdamage, int bombdistance, FName bombmod,
int flags, int fulldamagedistance)
{
if (bombdistance <= 0)
return;
fulldamagedistance = clamp<int>(fulldamagedistance, 0, bombdistance - 1);
double bombdistancefloat = 1.f / (double)(bombdistance - fulldamagedistance);
double bombdamagefloat = (double)bombdamage;
FBlockThingsIterator it(FBoundingBox(bombspot->X(), bombspot->Y(), bombdistance << FRACBITS));
AActor *thing;
if (flags & RADF_SOURCEISSPOT)
{ // The source is actually the same as the spot, even if that wasn't what we received.
bombsource = bombspot;
}
while ((thing = it.Next()))
{
// Vulnerable actors can be damaged by radius attacks even if not shootable
// Used to emulate MBF's vulnerability of non-missile bouncers to explosions.
if (!((thing->flags & MF_SHOOTABLE) || (thing->flags6 & MF6_VULNERABLE)))
continue;
// Boss spider and cyborg and Heretic's ep >= 2 bosses
// take no damage from concussion.
if (thing->flags3 & MF3_NORADIUSDMG && !(bombspot->flags4 & MF4_FORCERADIUSDMG))
continue;
if (!(flags & RADF_HURTSOURCE) && (thing == bombsource || thing == bombspot))
{ // don't damage the source of the explosion
continue;
}
// a much needed option: monsters that fire explosive projectiles cannot
// be hurt by projectiles fired by a monster of the same type.
// Controlled by the DONTHARMCLASS and DONTHARMSPECIES flags.
if ((bombsource && !thing->player) // code common to both checks
&& ( // Class check first
((bombsource->flags4 & MF4_DONTHARMCLASS) && (thing->GetClass() == bombsource->GetClass()))
|| // Nigh-identical species check second
((bombsource->flags6 & MF6_DONTHARMSPECIES) && (thing->GetSpecies() == bombsource->GetSpecies()))
)
) continue;
// Barrels always use the original code, since this makes
// them far too "active." BossBrains also use the old code
// because some user levels require they have a height of 16,
// which can make them near impossible to hit with the new code.
if ((flags & RADF_NODAMAGE) || !((bombspot->flags5 | thing->flags5) & MF5_OLDRADIUSDMG))
{
// [RH] New code. The bounding box only covers the
// height of the thing and not the height of the map.
double points;
double len;
fixed_t dx, dy;
double boxradius;
fixedvec2 vec = bombspot->Vec2To(thing);
dx = abs(vec.x);
dy = abs(vec.y);
boxradius = double(thing->radius);
// The damage pattern is square, not circular.
len = double(dx > dy ? dx : dy);
if (bombspot->Z() < thing->Z() || bombspot->Z() >= thing->Top())
{
double dz;
if (bombspot->Z() > thing->Z())
{
dz = double(bombspot->Z() - thing->Top());
}
else
{
dz = double(thing->Z() - bombspot->Z());
}
if (len <= boxradius)
{
len = dz;
}
else
{
len -= boxradius;
len = sqrt(len*len + dz*dz);
}
}
else
{
len -= boxradius;
if (len < 0.f)
len = 0.f;
}
len /= FRACUNIT;
len = clamp<double>(len - (double)fulldamagedistance, 0, len);
points = bombdamagefloat * (1.f - len * bombdistancefloat);
if (thing == bombsource)
{
points = points * splashfactor;
}
points *= thing->GetClass()->Meta.GetMetaFixed(AMETA_RDFactor, FRACUNIT) / (double)FRACUNIT;
// points and bombdamage should be the same sign
if (((points * bombdamage) > 0) && P_CheckSight(thing, bombspot, SF_IGNOREVISIBILITY | SF_IGNOREWATERBOUNDARY))
{ // OK to damage; target is in direct path
double velz;
double thrust;
int damage = abs((int)points);
int newdam = damage;
if (!(flags & RADF_NODAMAGE))
newdam = P_DamageMobj(thing, bombspot, bombsource, damage, bombmod);
else if (thing->player == NULL && (!(flags & RADF_NOIMPACTDAMAGE) && !(thing->flags7 & MF7_DONTTHRUST)))
thing->flags2 |= MF2_BLASTED;
if (!(thing->flags & MF_ICECORPSE))
{
if (!(flags & RADF_NODAMAGE) && !(bombspot->flags3 & MF3_BLOODLESSIMPACT))
P_TraceBleed(newdam > 0 ? newdam : damage, thing, bombspot);
if ((flags & RADF_NODAMAGE) || !(bombspot->flags2 & MF2_NODMGTHRUST))
{
if (bombsource == NULL || !(bombsource->flags2 & MF2_NODMGTHRUST))
{
if (!(thing->flags7 & MF7_DONTTHRUST))
{
thrust = points * 0.5f / (double)thing->Mass;
if (bombsource == thing)
{
thrust *= selfthrustscale;
}
velz = (double)(thing->Z() + (thing->height >> 1) - bombspot->Z()) * thrust;
if (bombsource != thing)
{
velz *= 0.5f;
}
else
{
velz *= 0.8f;
}
angle_t ang = bombspot->AngleTo(thing) >> ANGLETOFINESHIFT;
thing->velx += fixed_t(finecosine[ang] * thrust);
thing->vely += fixed_t(finesine[ang] * thrust);
if (!(flags & RADF_NODAMAGE))
thing->velz += (fixed_t)velz; // this really doesn't work well
}
}
}
}
}
}
else
{
// [RH] Old code just for barrels
fixed_t dx, dy, dist;
fixedvec2 vec = bombspot->Vec2To(thing);
dx = abs(vec.x);
dy = abs(vec.y);
dist = dx>dy ? dx : dy;
dist = (dist - thing->radius) >> FRACBITS;
if (dist < 0)
dist = 0;
if (dist >= bombdistance)
continue; // out of range
if (P_CheckSight(thing, bombspot, SF_IGNOREVISIBILITY | SF_IGNOREWATERBOUNDARY))
{ // OK to damage; target is in direct path
dist = clamp<int>(dist - fulldamagedistance, 0, dist);
int damage = Scale(bombdamage, bombdistance - dist, bombdistance);
damage = (int)((double)damage * splashfactor);
damage = Scale(damage, thing->GetClass()->Meta.GetMetaFixed(AMETA_RDFactor, FRACUNIT), FRACUNIT);
if (damage > 0)
{
int newdam = P_DamageMobj(thing, bombspot, bombsource, damage, bombmod);
P_TraceBleed(newdam > 0 ? newdam : damage, thing, bombspot);
}
}
}
}
}
//==========================================================================
//
// SECTOR HEIGHT CHANGING
// After modifying a sector's floor or ceiling height,
// call this routine to adjust the positions
// of all things that touch the sector.
//
// If anything doesn't fit anymore, true will be returned.
//
// [RH] If crushchange is non-negative, they will take the
// specified amount of damage as they are being crushed.
// If crushchange is negative, you should set the sector
// height back the way it was and call P_ChangeSector()
// again to undo the changes.
// Note that this is very different from the original
// true/false usage of crushchange! If you want regular
// DOOM crushing behavior set crushchange to 10 or -1
// if no crushing is desired.
//
//==========================================================================
struct FChangePosition
{
sector_t *sector;
int moveamt;
int crushchange;
bool nofit;
bool movemidtex;
};
TArray<AActor *> intersectors;
EXTERN_CVAR(Int, cl_bloodtype)
//=============================================================================
//
// P_AdjustFloorCeil
//
//=============================================================================
bool P_AdjustFloorCeil(AActor *thing, FChangePosition *cpos)
{
ActorFlags2 flags2 = thing->flags2 & MF2_PASSMOBJ;
FCheckPosition tm;
if ((thing->flags2 & MF2_PASSMOBJ) && (thing->flags3 & MF3_ISMONSTER))
{
tm.FromPMove = true;
}
if (cpos->movemidtex)
{
// From Eternity:
// ALL things must be treated as PASSMOBJ when moving
// 3DMidTex lines, otherwise you get stuck in them.
thing->flags2 |= MF2_PASSMOBJ;
}
bool isgood = P_CheckPosition(thing, thing->X(), thing->Y(), tm);
thing->floorz = tm.floorz;
thing->ceilingz = tm.ceilingz;
thing->dropoffz = tm.dropoffz; // killough 11/98: remember dropoffs
thing->floorpic = tm.floorpic;
thing->floorterrain = tm.floorterrain;
thing->floorsector = tm.floorsector;
thing->ceilingpic = tm.ceilingpic;
thing->ceilingsector = tm.ceilingsector;
// restore the PASSMOBJ flag but leave the other flags alone.
thing->flags2 = (thing->flags2 & ~MF2_PASSMOBJ) | flags2;
return isgood;
}
//=============================================================================
//
// P_FindAboveIntersectors
//
//=============================================================================
void P_FindAboveIntersectors(AActor *actor)
{
if (actor->flags & MF_NOCLIP)
return;
if (!(actor->flags & MF_SOLID))
return;
AActor *thing;
FBlockThingsIterator it(FBoundingBox(actor->X(), actor->Y(), actor->radius));
while ((thing = it.Next()))
{
if (!thing->intersects(actor))
{
continue;
}
if (!(thing->flags & MF_SOLID))
{ // Can't hit thing
continue;
}
if (thing->flags & (MF_SPECIAL))
{ // [RH] Corpses and specials don't block moves
continue;
}
if (thing->flags & (MF_CORPSE))
{ // Corpses need a few more checks
if (!(actor->flags & MF_ICECORPSE))
continue;
}
if (thing == actor)
{ // Don't clip against self
continue;
}
if (!((thing->flags2 | actor->flags2) & MF2_PASSMOBJ) && !((thing->flags3 | actor->flags3) & MF3_ISMONSTER))
{
// Don't bother if both things don't have MF2_PASSMOBJ set and aren't monsters.
// These things would always block each other which in nearly every situation is
// not what is wanted here.
continue;
}
if (thing->Z() >= actor->Z() &&
thing->Z() <= actor->Top())
{ // Thing intersects above the base
intersectors.Push(thing);
}
}
}
//=============================================================================
//
// P_FindBelowIntersectors
//
//=============================================================================
void P_FindBelowIntersectors(AActor *actor)
{
if (actor->flags & MF_NOCLIP)
return;
if (!(actor->flags & MF_SOLID))
return;
AActor *thing;
FBlockThingsIterator it(FBoundingBox(actor->X(), actor->Y(), actor->radius));
while ((thing = it.Next()))
{
if (!thing->intersects(actor))
{
continue;
}
if (!(thing->flags & MF_SOLID))
{ // Can't hit thing
continue;
}
if (thing->flags & (MF_SPECIAL))
{ // [RH] Corpses and specials don't block moves
continue;
}
if (thing->flags & (MF_CORPSE))
{ // Corpses need a few more checks
if (!(actor->flags & MF_ICECORPSE))
continue;
}
if (thing == actor)
{ // Don't clip against self
continue;
}
if (!((thing->flags2 | actor->flags2) & MF2_PASSMOBJ) && !((thing->flags3 | actor->flags3) & MF3_ISMONSTER))
{
// Don't bother if both things don't have MF2_PASSMOBJ set and aren't monsters.
// These things would always block each other which in nearly every situation is
// not what is wanted here.
continue;
}
if (thing->Top() <= actor->Top() &&
thing->Top() > actor->Z())
{ // Thing intersects below the base
intersectors.Push(thing);
}
}
}
//=============================================================================
//
// P_DoCrunch
//
//=============================================================================
void P_DoCrunch(AActor *thing, FChangePosition *cpos)
{
if (!(thing && thing->Grind(true) && cpos)) return;
cpos->nofit = true;
if ((cpos->crushchange > 0) && !(level.maptime & 3))
{
int newdam = P_DamageMobj(thing, NULL, NULL, cpos->crushchange, NAME_Crush);
// spray blood in a random direction
if (!(thing->flags2&(MF2_INVULNERABLE | MF2_DORMANT)))
{
if (!(thing->flags&MF_NOBLOOD))
{
PalEntry bloodcolor = thing->GetBloodColor();
const PClass *bloodcls = thing->GetBloodType();
P_TraceBleed(newdam > 0 ? newdam : cpos->crushchange, thing);
if (bloodcls != NULL)
{
AActor *mo;
mo = Spawn(bloodcls, thing->PosPlusZ(thing->height / 2), ALLOW_REPLACE);
mo->velx = pr_crunch.Random2() << 12;
mo->vely = pr_crunch.Random2() << 12;
if (bloodcolor != 0 && !(mo->flags2 & MF2_DONTTRANSLATE))
{
mo->Translation = TRANSLATION(TRANSLATION_Blood, bloodcolor.a);
}
if (!(cl_bloodtype <= 1)) mo->renderflags |= RF_INVISIBLE;
}
angle_t an;
an = (M_Random() - 128) << 24;
if (cl_bloodtype >= 1)
{
P_DrawSplash2(32, thing->X(), thing->Y(), thing->Z() + thing->height / 2, an, 2, bloodcolor);
}
}
if (thing->CrushPainSound != 0 && !S_GetSoundPlayingInfo(thing, thing->CrushPainSound))
{
S_Sound(thing, CHAN_VOICE, thing->CrushPainSound, 1.f, ATTN_NORM);
}
}
}
// keep checking (crush other things)
return;
}
//=============================================================================
//
// P_PushUp
//
// Returns 0 if thing fits, 1 if ceiling got in the way, or 2 if something
// above it didn't fit.
//=============================================================================
int P_PushUp(AActor *thing, FChangePosition *cpos)
{
unsigned int firstintersect = intersectors.Size();
unsigned int lastintersect;
int mymass = thing->Mass;
if (thing->Top() > thing->ceilingz)
{
return 1;
}
// [GZ] Skip thing intersect test for THRUACTORS things.
if (thing->flags2 & MF2_THRUACTORS)
return 0;
P_FindAboveIntersectors(thing);
lastintersect = intersectors.Size();
for (; firstintersect < lastintersect; firstintersect++)
{
AActor *intersect = intersectors[firstintersect];
// [GZ] Skip this iteration for THRUSPECIES things
// Should there be MF2_THRUGHOST / MF3_GHOST checks there too for consistency?
// Or would that risk breaking established behavior? THRUGHOST, like MTHRUSPECIES,
// is normally for projectiles which would have exploded by now anyway...
if (thing->flags6 & MF6_THRUSPECIES && thing->GetSpecies() == intersect->GetSpecies())
continue;
if ((thing->flags & MF_MISSILE) && (intersect->flags2 & MF2_REFLECTIVE) && (intersect->flags7 & MF7_THRUREFLECT))
continue;
if (!(intersect->flags2 & MF2_PASSMOBJ) ||
(!(intersect->flags3 & MF3_ISMONSTER) && intersect->Mass > mymass) ||
(intersect->flags4 & MF4_ACTLIKEBRIDGE)
)
{
// Can't push bridges or things more massive than ourself
return 2;
}
fixed_t oldz;
oldz = intersect->Z();
P_AdjustFloorCeil(intersect, cpos);
intersect->SetZ(thing->Top() + 1);
if (P_PushUp(intersect, cpos))
{ // Move blocked
P_DoCrunch(intersect, cpos);
intersect->SetZ(oldz);
return 2;
}
}
return 0;
}
//=============================================================================
//
// P_PushDown
//
// Returns 0 if thing fits, 1 if floor got in the way, or 2 if something
// below it didn't fit.
//=============================================================================
int P_PushDown(AActor *thing, FChangePosition *cpos)
{
unsigned int firstintersect = intersectors.Size();
unsigned int lastintersect;
int mymass = thing->Mass;
if (thing->Z() <= thing->floorz)
{
return 1;
}
P_FindBelowIntersectors(thing);
lastintersect = intersectors.Size();
for (; firstintersect < lastintersect; firstintersect++)
{
AActor *intersect = intersectors[firstintersect];
if (!(intersect->flags2 & MF2_PASSMOBJ) ||
(!(intersect->flags3 & MF3_ISMONSTER) && intersect->Mass > mymass) ||
(intersect->flags4 & MF4_ACTLIKEBRIDGE)
)
{
// Can't push bridges or things more massive than ourself
return 2;
}
fixed_t oldz = intersect->Z();
P_AdjustFloorCeil(intersect, cpos);
if (oldz > thing->Z() - intersect->height)
{ // Only push things down, not up.
intersect->SetZ(thing->Z() - intersect->height);
if (P_PushDown(intersect, cpos))
{ // Move blocked
P_DoCrunch(intersect, cpos);
intersect->SetZ(oldz);
return 2;
}
}
}
return 0;
}
//=============================================================================
//
// PIT_FloorDrop
//
//=============================================================================
void PIT_FloorDrop(AActor *thing, FChangePosition *cpos)
{
fixed_t oldfloorz = thing->floorz;
fixed_t oldz = thing->Z();
P_AdjustFloorCeil(thing, cpos);
if (oldfloorz == thing->floorz) return;
if (thing->flags4 & MF4_ACTLIKEBRIDGE) return; // do not move bridge things
if (thing->velz == 0 &&
(!(thing->flags & MF_NOGRAVITY) ||
(thing->Z() == oldfloorz && !(thing->flags & MF_NOLIFTDROP))))
{
fixed_t oldz = thing->Z();
if ((thing->flags & MF_NOGRAVITY) || (thing->flags5 & MF5_MOVEWITHSECTOR) ||
(((cpos->sector->Flags & SECF_FLOORDROP) || cpos->moveamt < 9 * FRACUNIT)
&& thing->Z() - thing->floorz <= cpos->moveamt))
{
thing->SetZ(thing->floorz);
P_CheckFakeFloorTriggers(thing, oldz);
}
}
else if ((thing->Z() != oldfloorz && !(thing->flags & MF_NOLIFTDROP)))
{
fixed_t oldz = thing->Z();
if ((thing->flags & MF_NOGRAVITY) && (thing->flags6 & MF6_RELATIVETOFLOOR))
{
thing->AddZ(-oldfloorz + thing->floorz);
P_CheckFakeFloorTriggers(thing, oldz);
}
}
if (thing->player && thing->player->mo == thing)
{
thing->player->viewz += thing->Z() - oldz;
}
}
//=============================================================================
//
// PIT_FloorRaise
//
//=============================================================================
void PIT_FloorRaise(AActor *thing, FChangePosition *cpos)
{
fixed_t oldfloorz = thing->floorz;
fixed_t oldz = thing->Z();
P_AdjustFloorCeil(thing, cpos);
if (oldfloorz == thing->floorz) return;
// Move things intersecting the floor up
if (thing->Z() <= thing->floorz)
{
if (thing->flags4 & MF4_ACTLIKEBRIDGE)
{
cpos->nofit = true;
return; // do not move bridge things
}
intersectors.Clear();
thing->SetZ(thing->floorz);
}
else
{
if ((thing->flags & MF_NOGRAVITY) && (thing->flags6 & MF6_RELATIVETOFLOOR))
{
intersectors.Clear();
thing->AddZ(-oldfloorz + thing->floorz);
}
else return;
}
switch (P_PushUp(thing, cpos))
{
default:
P_CheckFakeFloorTriggers(thing, oldz);
break;
case 1:
P_DoCrunch(thing, cpos);
P_CheckFakeFloorTriggers(thing, oldz);
break;
case 2:
P_DoCrunch(thing, cpos);
thing->SetZ(oldz);
break;
}
if (thing->player && thing->player->mo == thing)
{
thing->player->viewz += thing->Z() - oldz;
}
}
//=============================================================================
//
// PIT_CeilingLower
//
//=============================================================================
void PIT_CeilingLower(AActor *thing, FChangePosition *cpos)
{
bool onfloor;
fixed_t oldz = thing->Z();
onfloor = thing->Z() <= thing->floorz;
P_AdjustFloorCeil(thing, cpos);
if (thing->Top() > thing->ceilingz)
{
if (thing->flags4 & MF4_ACTLIKEBRIDGE)
{
cpos->nofit = true;
return; // do not move bridge things
}
intersectors.Clear();
fixed_t oldz = thing->Z();
if (thing->ceilingz - thing->height >= thing->floorz)
{
thing->SetZ(thing->ceilingz - thing->height);
}
else
{
thing->SetZ(thing->floorz);
}
switch (P_PushDown(thing, cpos))
{
case 2:
// intentional fall-through
case 1:
if (onfloor)
thing->SetZ(thing->floorz);
P_DoCrunch(thing, cpos);
P_CheckFakeFloorTriggers(thing, oldz);
break;
default:
P_CheckFakeFloorTriggers(thing, oldz);
break;
}
}
if (thing->player && thing->player->mo == thing)
{
thing->player->viewz += thing->Z() - oldz;
}
}
//=============================================================================
//
// PIT_CeilingRaise
//
//=============================================================================
void PIT_CeilingRaise(AActor *thing, FChangePosition *cpos)
{
bool isgood = P_AdjustFloorCeil(thing, cpos);
fixed_t oldz = thing->Z();
if (thing->flags4 & MF4_ACTLIKEBRIDGE) return; // do not move bridge things
// For DOOM compatibility, only move things that are inside the floor.
// (or something else?) Things marked as hanging from the ceiling will
// stay where they are.
if (thing->Z() < thing->floorz &&
thing->Top() >= thing->ceilingz - cpos->moveamt &&
!(thing->flags & MF_NOLIFTDROP))
{
fixed_t oldz = thing->Z();
thing->SetZ(thing->floorz);
if (thing->Top() > thing->ceilingz)
{
thing->SetZ(thing->ceilingz - thing->height);
}
P_CheckFakeFloorTriggers(thing, oldz);
}
else if ((thing->flags2 & MF2_PASSMOBJ) && !isgood && thing->Top() < thing->ceilingz)
{
AActor *onmobj;
if (!P_TestMobjZ(thing, true, &onmobj) && onmobj->Z() <= thing->Z())
{
thing->SetZ( MIN(thing->ceilingz - thing->height, onmobj->Top()));
}
}
if (thing->player && thing->player->mo == thing)
{
thing->player->viewz += thing->Z() - oldz;
}
}
//=============================================================================
//
// P_ChangeSector [RH] Was P_CheckSector in BOOM
//
// jff 3/19/98 added to just check monsters on the periphery
// of a moving sector instead of all in bounding box of the
// sector. Both more accurate and faster.
//
//=============================================================================
bool P_ChangeSector(sector_t *sector, int crunch, int amt, int floorOrCeil, bool isreset)
{
FChangePosition cpos;
void(*iterator)(AActor *, FChangePosition *);
void(*iterator2)(AActor *, FChangePosition *) = NULL;
msecnode_t *n;
cpos.nofit = false;
cpos.crushchange = crunch;
cpos.moveamt = abs(amt);
cpos.movemidtex = false;
cpos.sector = sector;
// Also process all sectors that have 3D floors transferred from the
// changed sector.
if (sector->e->XFloor.attached.Size())
{
unsigned i;
sector_t* sec;
// Use different functions for the four different types of sector movement.
// for 3D-floors the meaning of floor and ceiling is inverted!!!
if (floorOrCeil == 1)
{
iterator = (amt >= 0) ? PIT_FloorRaise : PIT_FloorDrop;
}
else
{
iterator = (amt >= 0) ? PIT_CeilingRaise : PIT_CeilingLower;
}
for (i = 0; i < sector->e->XFloor.attached.Size(); i++)
{
sec = sector->e->XFloor.attached[i];
P_Recalculate3DFloors(sec); // Must recalculate the 3d floor and light lists
// no thing checks for attached sectors because of heightsec
if (sec->heightsec == sector) continue;
for (n = sec->touching_thinglist; n; n = n->m_snext) n->visited = false;
do
{
for (n = sec->touching_thinglist; n; n = n->m_snext)
{
if (!n->visited)
{
n->visited = true;
if (!(n->m_thing->flags & MF_NOBLOCKMAP) || //jff 4/7/98 don't do these
(n->m_thing->flags5 & MF5_MOVEWITHSECTOR))
{
iterator(n->m_thing, &cpos);
}
break;
}
}
} while (n);
}
}
P_Recalculate3DFloors(sector); // Must recalculate the 3d floor and light lists
// [RH] Use different functions for the four different types of sector
// movement.
switch (floorOrCeil)
{
case 0:
// floor
iterator = (amt < 0) ? PIT_FloorDrop : PIT_FloorRaise;
break;
case 1:
// ceiling
iterator = (amt < 0) ? PIT_CeilingLower : PIT_CeilingRaise;
break;
case 2:
// 3dmidtex
// This must check both floor and ceiling
iterator = (amt < 0) ? PIT_FloorDrop : PIT_FloorRaise;
iterator2 = (amt < 0) ? PIT_CeilingLower : PIT_CeilingRaise;
cpos.movemidtex = true;
break;
default:
// invalid
assert(floorOrCeil > 0 && floorOrCeil < 2);
return false;
}
// killough 4/4/98: scan list front-to-back until empty or exhausted,
// restarting from beginning after each thing is processed. Avoids
// crashes, and is sure to examine all things in the sector, and only
// the things which are in the sector, until a steady-state is reached.
// Things can arbitrarily be inserted and removed and it won't mess up.
//
// killough 4/7/98: simplified to avoid using complicated counter
// Mark all things invalid
for (n = sector->touching_thinglist; n; n = n->m_snext)
n->visited = false;
do
{
for (n = sector->touching_thinglist; n; n = n->m_snext) // go through list
{
if (!n->visited) // unprocessed thing found
{
n->visited = true; // mark thing as processed
if (!(n->m_thing->flags & MF_NOBLOCKMAP) || //jff 4/7/98 don't do these
(n->m_thing->flags5 & MF5_MOVEWITHSECTOR))
{
iterator(n->m_thing, &cpos); // process it
if (iterator2 != NULL) iterator2(n->m_thing, &cpos);
}
break; // exit and start over
}
}
} while (n); // repeat from scratch until all things left are marked valid
if (!cpos.nofit && !isreset /* && sector->MoreFlags & (SECF_UNDERWATERMASK)*/)
{
// If this is a control sector for a deep water transfer, all actors in affected
// sectors need to have their waterlevel information updated and if applicable,
// execute appropriate sector actions.
// Only check if the sector move was successful.
TArray<sector_t *> & secs = sector->e->FakeFloor.Sectors;
for (unsigned i = 0; i < secs.Size(); i++)
{
sector_t * s = secs[i];
for (n = s->touching_thinglist; n; n = n->m_snext)
n->visited = false;
do
{
for (n = s->touching_thinglist; n; n = n->m_snext) // go through list
{
if (!n->visited && n->m_thing->Sector == s) // unprocessed thing found
{
n->visited = true; // mark thing as processed
n->m_thing->UpdateWaterLevel(n->m_thing->Z(), false);
P_CheckFakeFloorTriggers(n->m_thing, n->m_thing->Z() - amt);
}
}
} while (n); // repeat from scratch until all things left are marked valid
}
}
return cpos.nofit;
}
//=============================================================================
// phares 3/21/98
//
// Maintain a freelist of msecnode_t's to reduce memory allocs and frees.
//=============================================================================
msecnode_t *headsecnode = NULL;
//=============================================================================
//
// P_GetSecnode
//
// Retrieve a node from the freelist. The calling routine
// should make sure it sets all fields properly.
//
//=============================================================================
msecnode_t *P_GetSecnode()
{
msecnode_t *node;
if (headsecnode)
{
node = headsecnode;
headsecnode = headsecnode->m_snext;
}
else
{
node = (msecnode_t *)M_Malloc(sizeof(*node));
}
return node;
}
//=============================================================================
//
// P_PutSecnode
//
// Returns a node to the freelist.
//
//=============================================================================
void P_PutSecnode(msecnode_t *node)
{
node->m_snext = headsecnode;
headsecnode = node;
}
//=============================================================================
// phares 3/16/98
//
// P_AddSecnode
//
// Searches the current list to see if this sector is
// already there. If not, it adds a sector node at the head of the list of
// sectors this object appears in. This is called when creating a list of
// nodes that will get linked in later. Returns a pointer to the new node.
//
//=============================================================================
msecnode_t *P_AddSecnode(sector_t *s, AActor *thing, msecnode_t *nextnode)
{
msecnode_t *node;
if (s == 0)
{
I_FatalError("AddSecnode of 0 for %s\n", thing->_StaticType.TypeName.GetChars());
}
node = nextnode;
while (node)
{
if (node->m_sector == s) // Already have a node for this sector?
{
node->m_thing = thing; // Yes. Setting m_thing says 'keep it'.
return nextnode;
}
node = node->m_tnext;
}
// Couldn't find an existing node for this sector. Add one at the head
// of the list.
node = P_GetSecnode();
// killough 4/4/98, 4/7/98: mark new nodes unvisited.
node->visited = 0;
node->m_sector = s; // sector
node->m_thing = thing; // mobj
node->m_tprev = NULL; // prev node on Thing thread
node->m_tnext = nextnode; // next node on Thing thread
if (nextnode)
nextnode->m_tprev = node; // set back link on Thing
// Add new node at head of sector thread starting at s->touching_thinglist
node->m_sprev = NULL; // prev node on sector thread
node->m_snext = s->touching_thinglist; // next node on sector thread
if (s->touching_thinglist)
node->m_snext->m_sprev = node;
s->touching_thinglist = node;
return node;
}
//=============================================================================
//
// P_DelSecnode
//
// Deletes a sector node from the list of
// sectors this object appears in. Returns a pointer to the next node
// on the linked list, or NULL.
//
//=============================================================================
msecnode_t *P_DelSecnode(msecnode_t *node)
{
msecnode_t* tp; // prev node on thing thread
msecnode_t* tn; // next node on thing thread
msecnode_t* sp; // prev node on sector thread
msecnode_t* sn; // next node on sector thread
if (node)
{
// Unlink from the Thing thread. The Thing thread begins at
// sector_list and not from AActor->touching_sectorlist.
tp = node->m_tprev;
tn = node->m_tnext;
if (tp)
tp->m_tnext = tn;
if (tn)
tn->m_tprev = tp;
// Unlink from the sector thread. This thread begins at
// sector_t->touching_thinglist.
sp = node->m_sprev;
sn = node->m_snext;
if (sp)
sp->m_snext = sn;
else
node->m_sector->touching_thinglist = sn;
if (sn)
sn->m_sprev = sp;
// Return this node to the freelist
P_PutSecnode(node);
return tn;
}
return NULL;
} // phares 3/13/98
//=============================================================================
//
// P_DelSector_List
//
// Deletes the sector_list and NULLs it.
//
//=============================================================================
void P_DelSector_List()
{
if (sector_list != NULL)
{
P_DelSeclist(sector_list);
sector_list = NULL;
}
}
//=============================================================================
//
// P_DelSeclist
//
// Delete an entire sector list
//
//=============================================================================
void P_DelSeclist(msecnode_t *node)
{
while (node)
node = P_DelSecnode(node);
}
//=============================================================================
// phares 3/14/98
//
// P_CreateSecNodeList
//
// Alters/creates the sector_list that shows what sectors the object resides in
//
//=============================================================================
void P_CreateSecNodeList(AActor *thing, fixed_t x, fixed_t y)
{
msecnode_t *node;
// First, clear out the existing m_thing fields. As each node is
// added or verified as needed, m_thing will be set properly. When
// finished, delete all nodes where m_thing is still NULL. These
// represent the sectors the Thing has vacated.
node = sector_list;
while (node)
{
node->m_thing = NULL;
node = node->m_tnext;
}
FBoundingBox box(thing->X(), thing->Y(), thing->radius);
FBlockLinesIterator it(box);
line_t *ld;
while ((ld = it.Next()))
{
if (box.Right() <= ld->bbox[BOXLEFT] ||
box.Left() >= ld->bbox[BOXRIGHT] ||
box.Top() <= ld->bbox[BOXBOTTOM] ||
box.Bottom() >= ld->bbox[BOXTOP])
continue;
if (box.BoxOnLineSide(ld) != -1)
continue;
// This line crosses through the object.
// Collect the sector(s) from the line and add to the
// sector_list you're examining. If the Thing ends up being
// allowed to move to this position, then the sector_list
// will be attached to the Thing's AActor at touching_sectorlist.
sector_list = P_AddSecnode(ld->frontsector, thing, sector_list);
// Don't assume all lines are 2-sided, since some Things
// like MT_TFOG are allowed regardless of whether their radius takes
// them beyond an impassable linedef.
// killough 3/27/98, 4/4/98:
// Use sidedefs instead of 2s flag to determine two-sidedness.
if (ld->backsector)
sector_list = P_AddSecnode(ld->backsector, thing, sector_list);
}
// Add the sector of the (x,y) point to sector_list.
sector_list = P_AddSecnode(thing->Sector, thing, sector_list);
// Now delete any nodes that won't be used. These are the ones where
// m_thing is still NULL.
node = sector_list;
while (node)
{
if (node->m_thing == NULL)
{
if (node == sector_list)
sector_list = node->m_tnext;
node = P_DelSecnode(node);
}
else
{
node = node->m_tnext;
}
}
}
//==========================================================================
//
//
//
//==========================================================================
void SpawnShootDecal(AActor *t1, const FTraceResults &trace)
{
FDecalBase *decalbase = NULL;
if (t1->player != NULL && t1->player->ReadyWeapon != NULL)
{
decalbase = t1->player->ReadyWeapon->GetDefault()->DecalGenerator;
}
else
{
decalbase = t1->DecalGenerator;
}
if (decalbase != NULL)
{
DImpactDecal::StaticCreate(decalbase->GetDecal(),
trace.X, trace.Y, trace.Z, trace.Line->sidedef[trace.Side], trace.ffloor);
}
}
//==========================================================================
//
//
//
//==========================================================================
static void SpawnDeepSplash(AActor *t1, const FTraceResults &trace, AActor *puff,
fixed_t vx, fixed_t vy, fixed_t vz, fixed_t shootz, bool ffloor)
{
const secplane_t *plane;
if (ffloor && trace.Crossed3DWater)
plane = trace.Crossed3DWater->top.plane;
else if (trace.CrossedWater && trace.CrossedWater->heightsec)
plane = &trace.CrossedWater->heightsec->floorplane;
else return;
fixed_t num, den, hitdist;
den = TMulScale16(plane->a, vx, plane->b, vy, plane->c, vz);
if (den != 0)
{
num = TMulScale16(plane->a, t1->X(), plane->b, t1->Y(), plane->c, shootz) + plane->d;
hitdist = FixedDiv(-num, den);
if (hitdist >= 0 && hitdist <= trace.Distance)
{
fixed_t hitx = t1->X() + FixedMul(vx, hitdist);
fixed_t hity = t1->Y() + FixedMul(vy, hitdist);
fixed_t hitz = shootz + FixedMul(vz, hitdist);
P_HitWater(puff != NULL ? puff : t1, P_PointInSector(hitx, hity), hitx, hity, hitz);
}
}
}
//=============================================================================
//
// P_ActivateThingSpecial
//
// Handles the code for things activated by death, USESPECIAL or BUMPSPECIAL
//
//=============================================================================
bool P_ActivateThingSpecial(AActor * thing, AActor * trigger, bool death)
{
bool res = false;
// Target switching mechanism
if (thing->activationtype & THINGSPEC_ThingTargets) thing->target = trigger;
if (thing->activationtype & THINGSPEC_TriggerTargets) trigger->target = thing;
// State change mechanism. The thing needs to be not dead and to have at least one of the relevant flags
if (!death && (thing->activationtype & (THINGSPEC_Activate | THINGSPEC_Deactivate | THINGSPEC_Switch)))
{
// If a switchable thing does not know whether it should be activated
// or deactivated, the default is to activate it.
if ((thing->activationtype & THINGSPEC_Switch)
&& !(thing->activationtype & (THINGSPEC_Activate | THINGSPEC_Deactivate)))
{
thing->activationtype |= THINGSPEC_Activate;
}
// Can it be activated?
if (thing->activationtype & THINGSPEC_Activate)
{
thing->activationtype &= ~THINGSPEC_Activate; // Clear flag
if (thing->activationtype & THINGSPEC_Switch) // Set other flag if switching
thing->activationtype |= THINGSPEC_Deactivate;
thing->Activate(trigger);
res = true;
}
// If not, can it be deactivated?
else if (thing->activationtype & THINGSPEC_Deactivate)
{
thing->activationtype &= ~THINGSPEC_Deactivate; // Clear flag
if (thing->activationtype & THINGSPEC_Switch) // Set other flag if switching
thing->activationtype |= THINGSPEC_Activate;
thing->Deactivate(trigger);
res = true;
}
}
// Run the special, if any
if (thing->special)
{
res = !!P_ExecuteSpecial(thing->special, NULL,
// TriggerActs overrides the level flag, which only concerns thing activated by death
(((death && level.flags & LEVEL_ACTOWNSPECIAL && !(thing->activationtype & THINGSPEC_TriggerActs))
|| (thing->activationtype & THINGSPEC_ThingActs)) // Who triggers?
? thing : trigger),
false, thing->args[0], thing->args[1], thing->args[2], thing->args[3], thing->args[4]);
// Clears the special if it was run on thing's death or if flag is set.
if (death || (thing->activationtype & THINGSPEC_ClearSpecial && res)) thing->special = 0;
}
// Returns the result
return res;
}
| 74,712 |
1,467 | <gh_stars>1000+
{
"version": "2.7.14",
"date": "2019-07-29",
"entries": [
{
"type": "bugfix",
"category": "Netty NIO Http Client",
"description": "Update `HandlerRemovingChannelPool` to only remove per request handlers if the channel is open or registered to avoid the race condition when the DefaultChannelPipeline is trying to removing the handler at the same time, causing `NoSuchElementException`."
},
{
"type": "feature",
"category": "AWS CodeCommit",
"description": "This release supports better exception handling for merges."
}
]
} | 266 |
410 | <gh_stars>100-1000
// Copyright (c) 2014 <NAME><<EMAIL>>
package com.iwebpp.node;
import java.util.Hashtable;
import java.util.Map;
import android.net.Uri;
public final class Url
extends EventEmitter2 {
public static class UrlObj {
public String href = null;
public String protocol = null;
public boolean slashes = false;
public String host = null;
public String auth = null;
public String hostname = null;
public int port = -1;
public String pathname = null;
public String search = null;
public String path = null;
public String query = null;
public String hash = null;
public Map<String, String> queryParams;
public boolean parseQueryString = false;
public boolean slashesDenoteHost = false;
UrlObj() {
this.queryParams = new Hashtable<String, String>();
}
public String toString() {
try {
return Url.format(this);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
public static UrlObj parse(
String urlStr,
boolean parseQueryString,
boolean slashesDenoteHost) throws Exception {
UrlObj obj = new UrlObj();
Uri url = Uri.parse(urlStr).normalizeScheme();
obj.parseQueryString = parseQueryString;
obj.slashesDenoteHost = slashesDenoteHost;
obj.href = urlStr.toLowerCase();
obj.protocol = url.getScheme()!=null ? url.getScheme()+":" : null;
obj.slashes = slashesDenoteHost;
obj.hostname = url.getHost();
obj.port = url.getPort();
obj.auth = url.getUserInfo();
obj.pathname = url.getPath();
obj.query = url.getQuery();
obj.hash = url.getFragment()!=null ? "#"+url.getFragment() : null;
obj.search = obj.query!=null ? "?"+obj.query : null;
obj.host = obj.hostname!=null ? obj.hostname + (obj.port>0 ? ":"+obj.port : "") : null;
obj.path = obj.pathname!=null ? obj.pathname + (obj.search!=null ? obj.search : "") : null;
// only find first matched key
if (obj.parseQueryString && obj.query!=null)
for (String k : url.getQueryParameterNames())
obj.queryParams.put(k, url.getQueryParameter(k));
return obj;
}
public static UrlObj parse(String urlStr) throws Exception {
return parse(urlStr, true, true);
}
public static String format(UrlObj obj) throws Exception {
String str = "";
str += obj.protocol!=null ? obj.protocol : "http:";
str += obj.slashes ? "//" : "";
str += obj.auth!=null ? obj.auth+"@" : "";
if (obj.host != null) {
str += obj.host;
} else if (obj.hostname!=null) {
str += obj.hostname;
str += obj.port>0 ? ":"+obj.port : "";
} else {
throw new Exception("Miss URL hostname");
}
if (obj.path != null) {
str += obj.path;
} else if (obj.pathname != null) {
str += obj.pathname;
if (obj.search != null) {
str += obj.search;
} else if (obj.query != null) {
str += "?" + obj.query;
}
} else {
// TBD...
///str += "/";
if (obj.search != null) {
str += obj.search;
} else if (obj.query != null) {
str += "?" + obj.query;
}
}
str += obj.hash!=null ? obj.hash : "";
return str;
}
public static String resolve(String from, String to) {
return Uri.withAppendedPath(Uri.parse(from), to).toString();
}
}
| 1,412 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Violay","circ":"6ème circonscription","dpt":"Loire","inscrits":1013,"abs":541,"votants":472,"blancs":15,"nuls":3,"exp":454,"res":[{"nuance":"REM","nom":"<NAME>","voix":205},{"nuance":"LR","nom":"<NAME>","voix":95},{"nuance":"FN","nom":"Mme <NAME>","voix":77},{"nuance":"FI","nom":"Mme <NAME>","voix":36},{"nuance":"ECO","nom":"<NAME>","voix":14},{"nuance":"DLF","nom":"Mme <NAME>","voix":10},{"nuance":"DIV","nom":"<NAME>","voix":6},{"nuance":"DVD","nom":"M. <NAME>","voix":5},{"nuance":"EXG","nom":"Mme <NAME>","voix":4},{"nuance":"ECO","nom":"M. <NAME>","voix":1},{"nuance":"DIV","nom":"M. <NAME>","voix":1}]} | 270 |
1,857 | """Preprocess the Kgirl model
The model is available for download from
https://sketchfab.com/models/d2f946f58a8040ae993cda70c97b302c
The Python Imaging Library is required
pip install pillow
"""
from __future__ import print_function
import json
import os
import zipfile
from PIL import Image
from utils.gltf import dump_obj_data, dump_skin_ani_data
SRC_FILENAME = "kgirls01.zip"
DST_DIRECTORY = "../assets/kgirl"
OBJ_FILENAMES = [
"body.obj",
"hair.obj",
"face.obj",
"pupils.obj",
]
def process_meshes(zip_file):
gltf = json.loads(zip_file.read("scene.gltf"))
buffer = zip_file.read("scene.bin")
for mesh_index, obj_filename in enumerate(OBJ_FILENAMES):
obj_data = dump_obj_data(gltf, buffer, mesh_index, with_skin=True)
obj_filepath = os.path.join(DST_DIRECTORY, obj_filename)
with open(obj_filepath, "w") as f:
f.write(obj_data)
ani_data = dump_skin_ani_data(gltf, buffer)
ani_filepath = os.path.join(DST_DIRECTORY, "kgirl.ani")
with open(ani_filepath, "w") as f:
f.write(ani_data)
def load_image(zip_file, filename):
with zip_file.open(filename) as f:
image = Image.open(f)
image = image.transpose(Image.FLIP_TOP_BOTTOM)
return image
def save_image(image, filename, size=512):
if max(image.size) > size:
image = image.resize((size, size), Image.LANCZOS)
filepath = os.path.join(DST_DIRECTORY, filename)
image.save(filepath, rle=True)
def process_images(zip_file):
old_filename = "textures/01_-_Default_baseColor.png"
tga_filename = "kgirl_diffuse.tga"
image = load_image(zip_file, old_filename)
save_image(image, tga_filename)
def main():
if not os.path.exists(DST_DIRECTORY):
os.makedirs(DST_DIRECTORY)
with zipfile.ZipFile(SRC_FILENAME) as zip_file:
process_meshes(zip_file)
process_images(zip_file)
if __name__ == "__main__":
main()
| 846 |
2,607 | <filename>src/test/java/info/debatty/java/stringsimilarity/NormalizedLevenshteinTest.java
package info.debatty.java.stringsimilarity;
import info.debatty.java.stringsimilarity.testutil.NullEmptyTests;
import org.junit.Test;
import static org.junit.Assert.*;
public class NormalizedLevenshteinTest {
@Test
public final void testDistance() {
NormalizedLevenshtein instance = new NormalizedLevenshtein();
NullEmptyTests.testDistance(instance);
// TODO: regular (non-null/empty) distance tests
}
@Test
public final void testSimilarity() {
NormalizedLevenshtein instance = new NormalizedLevenshtein();
NullEmptyTests.testSimilarity(instance);
// TODO: regular (non-null/empty) similarity tests
}
} | 277 |
1,919 | /**
* Copyright (C) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.tools.jmx;
import com.google.inject.Binding;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import java.lang.annotation.Annotation;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
/**
* Provides a JMX interface to Guice.
*
* @author <EMAIL> (<NAME>)
*/
public class Manager {
/**
* Registers all the bindings of an Injector with the platform MBean server.
* Consider using the name of your root {@link Module} class as the domain.
*/
public static void manage(
String domain,
Injector injector) {
manage(ManagementFactory.getPlatformMBeanServer(), domain, injector);
}
/**
* Registers all the bindings of an Injector with the given MBean server.
* Consider using the name of your root {@link Module} class as the domain.
*/
public static void manage(MBeanServer server, String domain,
Injector injector) {
// Register each binding independently.
for (Binding<?> binding : injector.getBindings().values()) {
// Construct the name manually so we can ensure proper ordering of the
// key/value pairs.
StringBuilder name = new StringBuilder();
name.append(domain).append(":");
Key<?> key = binding.getKey();
name.append("type=").append(quote(key.getTypeLiteral().toString()));
Annotation annotation = key.getAnnotation();
if (annotation != null) {
name.append(",annotation=").append(quote(annotation.toString()));
}
else {
Class<? extends Annotation> annotationType = key.getAnnotationType();
if (annotationType != null) {
name.append(",annotation=")
.append(quote("@" + annotationType.getName()));
}
}
try {
server.registerMBean(new ManagedBinding(binding),
new ObjectName(name.toString()));
}
catch (MalformedObjectNameException e) {
throw new RuntimeException("Bad object name: " + name, e);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
static String quote(String value) {
// JMX seems to have a comma bug.
return ObjectName.quote(value).replace(',', ';');
}
/**
* Run with no arguments for usage instructions.
*/
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java -Dcom.sun.management.jmxremote "
+ Manager.class.getName() + " [module class name]");
System.err.println("Then run 'jconsole' to connect.");
System.exit(1);
}
Module module = (Module) Class.forName(args[0]).newInstance();
Injector injector = Guice.createInjector(module);
manage(args[0], injector);
System.out.println("Press Ctrl+C to exit...");
// Sleep forever.
Thread.sleep(Long.MAX_VALUE);
}
}
| 1,254 |
575 | <reponame>iridium-browser/iridium-browser
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/audio_service_util.h"
#include <string>
#include "base/feature_list.h"
#include "base/optional.h"
#include "base/values.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/policy_constants.h"
#include "content/public/common/content_features.h"
namespace {
#if defined(OS_WIN) || defined(OS_MAC) || \
(defined(OS_LINUX) && !BUILDFLAG(IS_CHROMEOS_LACROS))
bool GetPolicyOrFeature(const char* policy_name, const base::Feature& feature) {
const policy::PolicyMap& policies =
g_browser_process->browser_policy_connector()
->GetPolicyService()
->GetPolicies(policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
std::string()));
base::Optional<bool> policy_value;
if (const base::Value* value = policies.GetValue(policy_name)) {
policy_value.emplace();
value->GetAsBoolean(&policy_value.value());
}
return policy_value.value_or(base::FeatureList::IsEnabled(feature));
}
#endif
} // namespace
bool IsAudioServiceSandboxEnabled() {
// TODO(crbug.com/1052397): Remove !IS_CHROMEOS_LACROS once lacros starts being
// built with OS_CHROMEOS instead of OS_LINUX.
#if defined(OS_WIN) || defined(OS_MAC) || \
(defined(OS_LINUX) && !BUILDFLAG(IS_CHROMEOS_LACROS))
return GetPolicyOrFeature(policy::key::kAudioSandboxEnabled,
features::kAudioServiceSandbox);
#else
return base::FeatureList::IsEnabled(features::kAudioServiceSandbox);
#endif
}
#if defined(OS_WIN)
bool IsAudioProcessHighPriorityEnabled() {
return GetPolicyOrFeature(policy::key::kAudioProcessHighPriorityEnabled,
features::kAudioProcessHighPriorityWin);
}
#endif
| 826 |
518 | <filename>manifests/definitions/499.json
{
"name": "iZettle",
"category": "Admin & Back-office",
"start_url": "https://my.izettle.com/login",
"icons": [
{
"src": "https://cdn.filestackcontent.com/GspbYaH4SmGRnhKxhDHJ"
},
{
"src": "https://cdn.filestackcontent.com/o2J7mGSXiTSGzN8NXu2w",
"platform": "browserx"
}
],
"theme_color": "#34446e",
"scope": "https://my.izettle.com",
"bx_legacy_service_id": "izettle"
}
| 222 |
2,053 | <filename>scouter.agent.java/src/scouter/agent/plugin/AbstractCapture.java
/*
* Copyright 2015 the original author or authors.
* @https://github.com/scouter-project/scouter
*
* 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 scouter.agent.plugin;
import scouter.agent.trace.HookArgs;
import scouter.agent.trace.HookReturn;
abstract public class AbstractCapture extends AbstractPlugin {
abstract public void capArgs(WrContext ctx, HookArgs hook);
abstract public void capReturn(WrContext ctx, HookReturn hook);
abstract public void capThis(WrContext ctx, String className, String methodDesc, Object this1);
}
| 322 |
631 | <reponame>tradingsecret/beam_wallet<filename>3rdparty/ethash/test/unittests/progpow_test_vectors.hpp
// ethash: C/C++ implementation of Ethash, the Ethereum Proof of Work algorithm.
// Copyright 2018-2019 <NAME>.
// Licensed under the Apache License, Version 2.0.
/// @file
/// ProgPoW test vectors.
#pragma once
namespace // In anonymous namespace to allow including in multiple compilation units.
{
/// Defines a test case for ProgPoW hash() function.
struct progpow_hash_test_case
{
int block_number;
const char* header_hash_hex;
const char* nonce_hex;
const char* mix_hash_hex;
const char* final_hash_hex;
};
progpow_hash_test_case progpow_hash_test_cases[] = {
{0, "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000",
"f4ac202715ded4136e72887c39e63a4738331c57fd9eb79f6ec421c281aa8743",
"b3bad9ca6f7c566cf0377d1f8cce29d6516a96562c122d924626281ec948ef02"},
{49, "b3bad9ca6f7c566cf0377d1f8cce29d6516a96562c122d924626281ec948ef02", "0000000006ff2c47",
"7730596f128f675ef9a6bb7281f268e4077d302f2b9078da1ece4349248561dd",
"0b9ed0c11157f1365143e329a6e1cea4248d9d6cb44b9c6daf492c7a076654a4"},
{50, "0b9ed0c11157f1365143e329a6e1cea4248d9d6cb44b9c6daf492c7a076654a4", "00000000076e482e",
"<KEY>",
"<KEY>"},
{99, "<KEY>", "000000003917afab",
"deb3d8b45bdc596c56aa37a5eba456f478c82e60e5c028ce95f2e654e4bb7b57",
"9bdc2ad2286eaa051d6ca1f5196d2dd1c9a039f1d7ce3e1c856b793deed01778"},
{29950, "9bdc2ad2286eaa051d6ca1f5196d2dd1c9a039f1d7ce3e1c856b793deed01778", "<KEY>",
"<KEY>",
"de0d693e597cf2fd70a4cfaa73f6baafc29e1eee695a81295b278c1116580b72"},
{29999, "de0d693e597cf2fd70a4cfaa73f6baafc29e1eee695a81295b278c1116580b72", "005db5fa4c2a3d03",
"<KEY>",
"21ec5d1984a4fd4394b042aa96365085225d964727a45def245ceab326e28128"},
{30000, "21ec5d1984a4fd4394b042aa96365085225d964727a45def245ceab326e28128", "<KEY>",
"<KEY>",
"dc070b76cc311cd82267f98936acbbbd3ec1c1ab25b55e2c885af6474e1e6841"},
{30049, "dc070b76cc311cd82267f98936acbbbd3ec1c1ab25b55e2c885af6474e1e6841", "005e2e215a8ca2e7",
"6248ba0157d0f0592dacfe2963337948fffb37f67e7451a6862c1321d894cebe",
"6fdecf719e2547f585a6ee807d8237db8e9489f63d3f259ab5236451eaded433"},
{30050, "6fdecf719e2547f585a6ee807d8237db8e9489f63d3f259ab5236451eaded433", "005e30899481055e",
"512d8f2bb0441fcfa1764c67e8dbed2afcbe9141de4bbebc5b51e0661dede550",
"cb1587a1c372642cbd9ce4c1ba2f433985d44c571a676a032bc1e8c1ad066e24"},
{30099, "cb1587a1c372642cbd9ce4c1ba2f433985d44c571a676a032bc1e8c1ad066e24", "<KEY>",
"be0e7d6afa6edd483ccc304afa9bf0abaca5e0f037a4f05bf5550b9309d1d12c",
"78be18f20569a834d839dad48e0e51d6df6b6537575f0ad29898c7cf357f12cb"},
{59950, "78be18f20569a834d839dad48e0e51d6df6b6537575f0ad29898c7cf357f12cb", "02ebe0503bd7b1da",
"b85be51fce670aa437f28c02ea4fd7995fa8b6ac224e959b8dbfb5bdbc6f77ce",
"<KEY>"},
{59999, "<KEY>", "02edb6275bd221e3",
"ffe745a932c21c0704291bb416fe8bffec76621cd3434861885beab42cec1734",
"<KEY>"},
};
} // namespace
| 1,718 |
432 | from .rman_mesh_translator import RmanMeshTranslator
from ..rman_sg_nodes.rman_sg_curve import RmanSgCurve
from ..rfb_utils import object_utils
from ..rfb_utils import string_utils
from ..rfb_utils import property_utils
import bpy
import math
def get_bspline_curve(curve):
P = []
widths = []
nvertices = []
name = ''
num_curves = len(curve.splines)
index = []
for i, spline in enumerate(curve.splines):
width = []
for bp in spline.points:
P.append([bp.co[0], bp.co[1], bp.co[2]])
w = bp.radius * 0.01
if w < 0.01:
w = 0.01
width.extend( 3 * [w])
widths.append(width)
index.append(i)
nvertices.append(len(spline.points))
name = spline.id_data.name
return (P, num_curves, nvertices, widths, index, name)
def get_curve(curve):
P = []
widths = []
nvertices = []
name = ''
num_curves = len(curve.splines)
index = []
for i, spline in enumerate(curve.splines):
width = []
for bp in spline.points:
P.append([bp.co[0], bp.co[1], bp.co[2]])
w = bp.radius * 0.01
if w < 0.01:
w = 0.01
width.extend( 3 * [w])
widths.append(width)
index.append(i)
nvertices.append(len(spline.points))
name = spline.id_data.name
return (P, num_curves, nvertices, widths, index, name)
def get_bezier_curve(curve):
splines = []
for spline in curve.splines:
P = []
width = []
for bp in spline.bezier_points:
P.append(bp.handle_left)
P.append(bp.co)
P.append(bp.handle_right)
width.extend( 3 * [bp.radius * 0.01])
if spline.use_cyclic_u:
period = 'periodic'
# wrap the initial handle around to the end, to begin on the CV
P = P[1:] + P[:1]
else:
period = 'nonperiodic'
# remove the two unused handles
P = P[1:-1]
width = width[1:-1]
name = spline.id_data.name
splines.append((P, width, period, name))
return splines
def get_is_cyclic(curve):
if len(curve.splines) < 1:
return False
spline = curve.splines[0]
return (spline.use_cyclic_u or spline.use_cyclic_v)
def get_curve_type(curve):
if len(curve.splines) < 1:
return None
spline = curve.splines[0]
# enum in [‘POLY’, ‘BEZIER’, ‘BSPLINE’, ‘CARDINAL’, ‘NURBS’], default ‘POLY’
return spline.type
class RmanCurveTranslator(RmanMeshTranslator):
def __init__(self, rman_scene):
super().__init__(rman_scene)
self.bl_type = 'CURVE'
def export(self, ob, db_name):
sg_node = self.rman_scene.sg_scene.CreateGroup(db_name)
is_mesh = self._is_mesh(ob)
rman_sg_curve = RmanSgCurve(self.rman_scene, sg_node, db_name)
rman_sg_curve.is_mesh = is_mesh
if is_mesh and self.rman_scene.do_motion_blur:
rman_sg_curve.is_transforming = object_utils.is_transforming(ob)
rman_sg_curve.is_deforming = object_utils._is_deforming_(ob)
return rman_sg_curve
def _is_mesh(self, ob):
is_mesh = False
if len(ob.modifiers) > 0:
is_mesh = True
elif len(ob.data.splines) < 1:
is_mesh = True
else:
l = ob.data.extrude + ob.data.bevel_depth
if l > 0:
is_mesh = True
return is_mesh
def export_deform_sample(self, rman_sg_curve, ob, time_sample):
if rman_sg_curve.is_mesh:
super().export_deform_sample(rman_sg_curve, ob, time_sample, sg_node=rman_sg_curve.sg_mesh_node)
def export_object_primvars(self, ob, rman_sg_node):
if rman_sg_node.is_mesh:
super().export_object_primvars(ob, rman_sg_node, sg_node=rman_sg_node.sg_mesh_node)
def update(self, ob, rman_sg_curve):
for c in [ rman_sg_curve.sg_node.GetChild(i) for i in range(0, rman_sg_curve.sg_node.GetNumChildren())]:
rman_sg_curve.sg_node.RemoveChild(c)
self.rman_scene.sg_scene.DeleteDagNode(c)
rman_sg_curve.is_mesh = self._is_mesh(ob)
if rman_sg_curve.is_mesh:
rman_sg_curve.sg_mesh_node = self.rman_scene.sg_scene.CreateMesh('%s-MESH' % rman_sg_curve.db_name)
rman_sg_curve.sg_node.AddChild(rman_sg_curve.sg_mesh_node)
super().update(ob, rman_sg_curve, sg_node=rman_sg_curve.sg_mesh_node)
return True
curve_type = get_curve_type(ob.data)
if curve_type == 'BEZIER':
self.update_bezier_curve(ob, rman_sg_curve)
elif curve_type in ['BSPLINE', 'NURBS']:
self.update_bspline_curve(ob, rman_sg_curve)
else:
self.update_curve(ob, rman_sg_curve)
def update_bspline_curve(self, ob, rman_sg_curve):
P, num_curves, nvertices, widths, index, name = get_bspline_curve(ob.data)
num_pts = len(P)
curves_sg = self.rman_scene.sg_scene.CreateCurves(name)
curves_sg.Define(self.rman_scene.rman.Tokens.Rix.k_cubic, 'nonperiodic', "b-spline", num_curves, num_pts)
primvar = curves_sg.GetPrimVars()
primvar.SetPointDetail(self.rman_scene.rman.Tokens.Rix.k_P, P, "vertex")
primvar.SetIntegerDetail(self.rman_scene.rman.Tokens.Rix.k_Ri_nvertices, nvertices, "uniform")
if widths:
primvar.SetFloatDetail(self.rman_scene.rman.Tokens.Rix.k_width, widths, "vertex")
primvar.SetIntegerDetail("index", index, "uniform")
curves_sg.SetPrimVars(primvar)
rman_sg_curve.sg_node.AddChild(curves_sg)
def update_curve(self, ob, rman_sg_curve):
P, num_curves, nvertices, widths, index, name = get_curve(ob.data)
num_pts = len(P)
curves_sg = self.rman_scene.sg_scene.CreateCurves(name)
curves_sg.Define(self.rman_scene.rman.Tokens.Rix.k_linear, 'nonperiodic', "linear", num_curves, num_pts)
primvar = curves_sg.GetPrimVars()
primvar.SetPointDetail(self.rman_scene.rman.Tokens.Rix.k_P, P, "vertex")
primvar.SetIntegerDetail(self.rman_scene.rman.Tokens.Rix.k_Ri_nvertices, nvertices, "uniform")
if widths:
primvar.SetFloatDetail(self.rman_scene.rman.Tokens.Rix.k_width, widths, "vertex")
primvar.SetIntegerDetail("index", index, "uniform")
curves_sg.SetPrimVars(primvar)
rman_sg_curve.sg_node.AddChild(curves_sg)
def update_bezier_curve(self, ob, rman_sg_curve):
curves = get_bezier_curve(ob.data)
for P, width, period, name in curves:
num_pts = len(P)
if num_pts < 1:
continue
curves_sg = self.rman_scene.sg_scene.CreateCurves(name)
curves_sg.Define(self.rman_scene.rman.Tokens.Rix.k_cubic, period, "bezier", 1, num_pts)
primvar = curves_sg.GetPrimVars()
primvar.SetPointDetail(self.rman_scene.rman.Tokens.Rix.k_P, P, "vertex")
primvar.SetIntegerDetail(self.rman_scene.rman.Tokens.Rix.k_Ri_nvertices, [num_pts], "uniform")
if width:
primvar.SetFloatDetail(self.rman_scene.rman.Tokens.Rix.k_width, width, "vertex")
curves_sg.SetPrimVars(primvar)
rman_sg_curve.sg_node.AddChild(curves_sg) | 4,035 |
5,169 | {
"name": "TTProgressButton",
"version": "1.0.0",
"summary": "A custom UIButton which has a progress border indicator.",
"description": " A custom circular UIButton which has a progress border indicator. It is designed to animate an array of images while indicating the progress. You can set the speed of the image animation and change the appearance of the button. The example shows how the button can be used while sending a tweet.\n\n",
"homepage": "https://github.com/TriggerTrap/TTProgressButton",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/TriggerTrap/TTProgressButton.git",
"tag": "v1.0.0"
},
"platforms": {
"ios": "7.0"
},
"requires_arc": true,
"source_files": [
"Source",
"Source/**/*.{h,m}"
],
"resources": [
"Assets/*.png"
],
"resource_bundles": {
"Assets": [
"Assets/*.{png, jpg}"
]
}
}
| 339 |
3,442 | <gh_stars>1000+
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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 net.java.sip.communicator.impl.osdependent.systemtray.appindicator;
import java.awt.*;
import java.awt.TrayIcon.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.beans.*;
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.List;
import java.util.Timer;
import javax.accessibility.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import javax.print.attribute.standard.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.jitsi.util.*;
import org.jitsi.utils.logging.Logger;
import com.sun.jna.*;
import net.java.sip.communicator.impl.osdependent.*;
import net.java.sip.communicator.impl.osdependent.systemtray.*;
import net.java.sip.communicator.impl.osdependent.systemtray.TrayIcon;
import net.java.sip.communicator.impl.osdependent.systemtray.appindicator.Gobject.*;
import net.java.sip.communicator.util.*;
/**
* System tray icon implementation based on libappindicator1.
*
* @author <NAME>
*/
class AppIndicatorTrayIcon implements TrayIcon
{
private static final Logger logger =
Logger.getLogger(AppIndicatorTrayIcon.class);
// shortcuts
private static Gobject gobject = Gobject.INSTANCE;
private static Gtk gtk = Gtk.INSTANCE;
private static AppIndicator1 ai = AppIndicator1.INSTANCE;
// references to the root menu and the native icon
private ImageIcon mainIcon;
private String title;
private JPopupMenu popup;
private Map<String, String> extractedFiles = new HashMap<>();
private PopupMenuPeer popupPeer;
private AppIndicator1.AppIndicator appIndicator;
private PopupMenuPeer defaultMenuPeer;
public AppIndicatorTrayIcon(ImageIcon mainIcon, String title,
JPopupMenu popup)
{
this.mainIcon = mainIcon;
this.title = title;
this.popup = popup;
this.popupPeer = null;
}
/**
* Combines the references of each swing menu item with the GTK counterpart
*/
private class PopupMenuPeer implements ContainerListener
{
public PopupMenuPeer(PopupMenuPeer parent, Component em)
{
menuItem = em;
// if this menu item is a submenu, add ourselves as listener to
// add or remove the native counterpart
if (em instanceof JMenu)
{
((JMenu)em).getPopupMenu().addContainerListener(this);
((JMenu)em).addContainerListener(this);
}
}
@Override
protected void finalize() throws Throwable
{
super.finalize();
if (isDefaultMenuItem)
{
gobject.g_object_unref(gtkMenuItem);
}
}
public List<PopupMenuPeer> children = new ArrayList<>();
public Pointer gtkMenuItem;
public Pointer gtkMenu;
public Pointer gtkImage;
public Memory gtkImageBuffer;
public Pointer gtkPixbuf;
public Component menuItem;
public MenuItemSignalHandler signalHandler;
public long gtkSignalHandler;
public boolean isDefaultMenuItem;
@Override
public void componentAdded(ContainerEvent e)
{
AppIndicatorTrayIcon.this.printMenu(popup.getComponents(), 1);
gtk.gdk_threads_enter();
try
{
createGtkMenuItems(this, new Component[]{e.getChild()});
gtk.gtk_widget_show_all(popupPeer.gtkMenu);
}
finally
{
gtk.gdk_threads_leave();
}
}
@Override
public void componentRemoved(ContainerEvent e)
{
AppIndicatorTrayIcon.this.printMenu(popup.getComponents(), 1);
for (PopupMenuPeer c : children)
{
if (c.menuItem == e.getChild())
{
gtk.gdk_threads_enter();
try
{
cleanMenu(c);
}
finally
{
gtk.gdk_threads_leave();
}
children.remove(c);
break;
}
}
}
}
public void createTray()
{
gtk.gdk_threads_enter();
try
{
setupGtkMenu();
}
finally
{
gtk.gdk_threads_leave();
}
new Thread()
{
public void run()
{
gtk.gtk_main();
}
}.start();
}
private void setupGtkMenu()
{
File iconFile = new File(imageIconToPath(mainIcon));
appIndicator = ai.app_indicator_new_with_path(
"jitsi",
iconFile.getName().replaceFirst("[.][^.]+$", ""),
AppIndicator1.APP_INDICATOR_CATEGORY.COMMUNICATIONS.ordinal(),
iconFile.getParent());
ai.app_indicator_set_title(appIndicator, title);
ai.app_indicator_set_icon_full(
appIndicator,
iconFile.getAbsolutePath(),
"Jitsi");
// create root menu
popupPeer = new PopupMenuPeer(null, popup);
popupPeer.gtkMenu = gtk.gtk_menu_new();
// transfer everything in the swing menu to the gtk menu
createGtkMenuItems(popupPeer, popup.getComponents());
gtk.gtk_widget_show_all(popupPeer.gtkMenu);
// attach the menu to the indicator
ai.app_indicator_set_menu(appIndicator, popupPeer.gtkMenu);
ai.app_indicator_set_status(
appIndicator,
AppIndicator1.APP_INDICATOR_STATUS.ACTIVE.ordinal());
}
private void cleanMenu(PopupMenuPeer peer)
{
assert !peer.isDefaultMenuItem;
for (PopupMenuPeer p : peer.children)
{
cleanMenu(p);
}
// - the root menu is released when it's unset from the indicator
// - gtk auto-frees menu item, submenu, image, and pixbuf
// - the imagebuffer was jna allocated, GC should take care of freeing
if (peer.gtkSignalHandler > 0)
{
gobject.g_signal_handler_disconnect(
peer.gtkMenuItem,
peer.gtkSignalHandler);
}
gtk.gtk_widget_destroy(peer.gtkMenuItem);
peer.gtkImageBuffer = null;
if (peer.menuItem instanceof JMenu)
{
((JMenu)peer.menuItem).removeContainerListener(peer);
((JMenu)peer.menuItem).getPopupMenu().removeContainerListener(peer);
}
}
private void createGtkMenuItems(
PopupMenuPeer parent,
Component[] components)
{
for (Component em : components)
{
PopupMenuPeer peer = new PopupMenuPeer(parent, em);
if (em instanceof JPopupMenu.Separator)
{
logger.debug("Creating separator");
peer.gtkMenuItem = gtk.gtk_separator_menu_item_new();
}
if (em instanceof JMenuItem)
{
createGtkMenuItem(peer);
}
if (em instanceof JMenu && peer.gtkMenuItem != null)
{
JMenu m = (JMenu)em;
logger.debug("Creating submenu on " + m.getText());
peer.gtkMenu = gtk.gtk_menu_new();
createGtkMenuItems(peer, m.getMenuComponents());
gtk.gtk_menu_item_set_submenu(peer.gtkMenuItem, peer.gtkMenu);
}
if (peer.gtkMenuItem != null)
{
parent.children.add(peer);
gtk.gtk_menu_shell_append(parent.gtkMenu, peer.gtkMenuItem);
}
}
}
private void createGtkMenuItem(PopupMenuPeer peer)
{
JMenuItem m = (JMenuItem)peer.menuItem;
logger.debug("Creating item for " + m.getClass().getName() + ": "
+ m.getText());
if (m instanceof JCheckBoxMenuItem)
{
peer.gtkMenuItem = gtk.gtk_check_menu_item_new_with_label(
m.getText());
JCheckBoxMenuItem cb = (JCheckBoxMenuItem)m;
gtk.gtk_check_menu_item_set_active(
peer.gtkMenuItem,
cb.isSelected() ? 1 : 0);
}
else
{
peer.gtkMenuItem = gtk.gtk_image_menu_item_new_with_label(
m.getText());
if (m.getIcon() instanceof ImageIcon)
{
ImageIcon ii = ((ImageIcon) m.getIcon());
imageIconToGtkWidget(peer, ii);
if (peer.gtkImage != null)
{
gtk.gtk_image_menu_item_set_image(
peer.gtkMenuItem,
peer.gtkImage);
gtk.gtk_image_menu_item_set_always_show_image(
peer.gtkMenuItem,
1);
}
}
}
if (peer.gtkMenuItem == null)
{
logger.debug("Could not create menu item for " + m.getText());
return;
}
MenuItemChangeListener micl = new MenuItemChangeListener(peer);
m.addPropertyChangeListener(micl);
m.addChangeListener(micl);
// skip GTK events if it's a submenu
if (!(m instanceof JMenu))
{
gtk.gtk_widget_set_sensitive(
peer.gtkMenuItem,
m.isEnabled() ? 1 : 0);
peer.signalHandler = new MenuItemSignalHandler(peer);
peer.gtkSignalHandler = gobject.g_signal_connect_data(
peer.gtkMenuItem,
"activate",
peer.signalHandler,
null,
null,
0);
}
}
private String imageIconToPath(ImageIcon ii)
{
if (ii.getDescription() != null)
{
String path = extractedFiles.get(ii.getDescription());
if (path != null)
{
return path;
}
}
try
{
File f = File.createTempFile("jitsi-appindicator", ".png");
f.deleteOnExit();
try (FileImageOutputStream fios = new FileImageOutputStream(f))
{
if (!ImageIO.write(getBufferedImage(ii), "png", fios))
{
return null;
}
if (ii.getDescription() != null)
{
extractedFiles.put(
ii.getDescription(),
f.getAbsolutePath());
}
return f.getAbsolutePath();
}
}
catch (IOException e)
{
logger.debug("Failed to extract image: " + ii.getDescription(), e);
}
return null;
}
BufferedImage getBufferedImage(ImageIcon ii)
{
Image img = ii.getImage();
if (img == null)
{
return null;
}
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
BufferedImage bi = new BufferedImage(
img.getWidth(null),
img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
return bi;
}
private void imageIconToGtkWidget(PopupMenuPeer peer, ImageIcon ii)
{
BufferedImage bi = getBufferedImage(ii);
if (bi == null)
{
return;
}
int[] pixels = bi.getRGB(
0,
0,
bi.getWidth(),
bi.getHeight(),
null,
0,
bi.getWidth());
peer.gtkImageBuffer = new Memory(pixels.length * 4);
for (int i = 0; i < pixels.length; i++)
{
// convert from argb (big endian) -> rgba (little endian) => abgr
peer.gtkImageBuffer.setInt(i * 4, (pixels[i] & 0xFF000000) |
(pixels[i] << 16) |
(pixels[i] & 0xFF00) |
(pixels[i] >>> 16 & 0xFF));
}
peer.gtkPixbuf = gtk.gdk_pixbuf_new_from_data(
peer.gtkImageBuffer,
0,
1,
8,
bi.getWidth(),
bi.getHeight(),
bi.getWidth() * 4,
null,
null);
peer.gtkImage = gtk.gtk_image_new_from_pixbuf(peer.gtkPixbuf);
// Now that the image ref's the buffer, we can release our own ref and
// the buffer will be free'd along with the image
gobject.g_object_unref(peer.gtkPixbuf);
}
private static class MenuItemChangeListener
implements PropertyChangeListener, ChangeListener
{
private PopupMenuPeer peer;
private JMenuItem menu;
public MenuItemChangeListener(PopupMenuPeer peer)
{
this.peer = peer;
this.menu = (JMenuItem)peer.menuItem;
}
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if (logger.isDebugEnabled())
{
logger.debug(menu.getText() + "::" + evt.getPropertyName());
}
switch (evt.getPropertyName())
{
case JMenuItem.TEXT_CHANGED_PROPERTY:
gtk.gdk_threads_enter();
try
{
gtk.gtk_menu_item_set_label(
peer.gtkMenuItem,
evt.getNewValue().toString());
}
finally
{
gtk.gdk_threads_leave();
}
break;
// case JMenuItem.ICON_CHANGED_PROPERTY:
// gtk.gtk_image_menu_item_set_image(gtkMenuItem, image);
// break;
case AccessibleContext.ACCESSIBLE_STATE_PROPERTY:
gtk.gdk_threads_enter();
try
{
gtk.gtk_widget_set_sensitive(
peer.gtkMenuItem,
AccessibleState.ENABLED.equals(
evt.getNewValue()) ? 1 : 0);
}
finally
{
gtk.gdk_threads_leave();
}
break;
}
}
@Override
public void stateChanged(ChangeEvent e)
{
logger.debug(menu.getText() + " -> " + menu.isSelected());
gtk.gdk_threads_enter();
try
{
gtk.gtk_check_menu_item_set_active(
peer.gtkMenuItem,
menu.isSelected() ? 1 : 0);
}
finally
{
gtk.gdk_threads_leave();
}
}
}
private static class MenuItemSignalHandler
implements SignalHandler, Runnable
{
private PopupMenuPeer peer;
MenuItemSignalHandler(PopupMenuPeer peer)
{
this.peer = peer;
}
@Override
public void signal(Pointer widget, Pointer data)
{
SwingUtilities.invokeLater(this);
}
@Override
public void run()
{
JMenuItem menu = (JMenuItem)peer.menuItem;
if (menu instanceof JCheckBoxMenuItem)
{
// Ignore GTK callback events if the menu state is
// already the same. Setting the selected state on the
// GTK sends the "activate" event, and would cause
// a loop
logger.debug("Checking selected state on: " + menu.getText());
if (menu.isSelected() == isGtkSelected())
{
return;
}
}
for (ActionListener l : menu.getActionListeners())
{
logger.debug("Invoking " + l + " on " + menu.getText());
l.actionPerformed(new ActionEvent(menu, 0, "activate"));
}
}
private boolean isGtkSelected()
{
gtk.gdk_threads_enter();
try
{
return gtk.gtk_check_menu_item_get_active(peer.gtkMenuItem) == 1;
}
finally
{
gtk.gdk_threads_leave();
}
}
}
@Override
public void setDefaultAction(Object menuItem)
{
// It shouldn't be necessary that we hold a reference to the
// default item, it is contained in the menu. It might even create
// a memory leak. But if not set, the indicator loses track of it
// (at least on Debian). Unref an existing item, then ref the newly
// set
if (defaultMenuPeer != null)
{
gobject.g_object_unref(defaultMenuPeer.gtkMenuItem);
}
PopupMenuPeer peer = findMenuItem(popupPeer, menuItem);
if (peer != null && peer.gtkMenuItem != null)
{
gtk.gdk_threads_enter();
try
{
defaultMenuPeer = peer;
gobject.g_object_ref(peer.gtkMenuItem);
ai.app_indicator_set_secondary_activate_target(
appIndicator,
peer.gtkMenuItem);
}
finally
{
gtk.gdk_threads_leave();
}
}
}
private PopupMenuPeer findMenuItem(PopupMenuPeer peer, Object menuItem)
{
if (peer.menuItem == menuItem)
{
logger.debug("Setting default action to: "
+ ((JMenuItem)menuItem).getText()
+ " @" + peer.gtkMenuItem);
return peer;
}
for (PopupMenuPeer p : peer.children)
{
PopupMenuPeer found = findMenuItem(p, menuItem);
if (found != null)
{
return found;
}
}
return null;
}
@Override
public void addBalloonActionListener(ActionListener listener)
{
// not supported
}
@Override
public void displayMessage(String caption, String text,
MessageType messageType)
{
// not supported
}
@Override
public void setIcon(ImageIcon icon) throws NullPointerException
{
mainIcon = icon;
if (appIndicator != null)
{
gtk.gdk_threads_enter();
try
{
ai.app_indicator_set_icon(
appIndicator,
imageIconToPath(icon));
}
finally
{
gtk.gdk_threads_leave();
}
}
}
@Override
public void setIconAutoSize(boolean autoSize)
{
// nothing to do
}
private void printMenu(Component[] components, int indent)
{
if (!logger.isDebugEnabled())
{
return;
}
String p = String.format("%0" + indent * 4 + "d", 0).replace('0', ' ');
for (Component em : components)
{
if (em instanceof JPopupMenu.Separator)
{
logger.debug(p + "-----------------------");
}
if (em instanceof JMenuItem)
{
JMenuItem m = (JMenuItem) em;
logger.debug(p + em.getClass().getName() + ": " + m.getText());
}
if (em instanceof JMenu)
{
JMenu m = (JMenu) em;
printMenu(m.getMenuComponents(), indent + 1);
}
}
}
}; | 10,733 |
3,055 | <reponame>kaidegit/u8g2
/*
Fontname: streamline_coding_apps_websites
Copyright: <EMAIL>
Glyphs: 27/27
BBX Build Mode: 0
*/
const uint8_t u8g2_font_streamline_coding_apps_websites_t[1787] U8G2_FONT_SECTION("u8g2_font_streamline_coding_apps_websites_t") =
"\33\0\3\2\5\5\3\3\6\25\25\0\0\25\0\25\0\4X\0\0\6\336\60<\65\322\265\353HN\34"
"r\70\315\201\234\222\355H\216EI\66\353@\26\347P\16H\321\224II\230\205I\224di\226\224\262"
"\244\251\62Hi\64h\221\262\210\225u\213\207\203\226\3\317\0\61B\263\226\265r\70\315\301\34\210\6)"
"\207T\35\312\241\34\210\206!\212\23eQ\322h\70\205\71\234\15\37\224:\234(\71\234(\71\234(\71"
"\234(\71\234$:\254\345p\232\203\71 M:T\211rP\223\1\62>\265\222u\206\37\222\234\252\3"
"\212\16\350H\35Q\243)U\223,I\345a\210\345a\210\305u\224\227Y^fuH\206T\215\246T"
"\247\16\177\320\251:\65\31~\310\221\64\207s G\207\63\0\63P\265\222u\206\37\222\234\252\14\37\24"
"e\370\240X\262$K\134\372\342\322\27\227,\311\22\313\360A\261%Y\222\270\364\305\245/nI\226$"
"\226\341\203\242\14\311\60$C\242\14\312\240\14\212\62(\203\62(\312\220h\312\220(\303\7E\247&\303"
"\17\11\0\64\62\365\361\365\206\257a\216\205u,L\224Pl\33\262p\230\206)\34\246\60\12Ka\24"
"\326\242,L\224Pl\62\205\303\22'\321\360\207\234\232\14\77$\0\65E\265\222u\206\17ZN\213\222"
"v\60\312i\321\360C\224\323\242,I\223,\12s \214\262$M\342\34\330\261\70\313\241\234\34\17\237"
"\262\311\245\344i\212LK\226\14\17J\26\306\331\60dq\226fq\66\14Y\234\1\66<t\262\265\207"
"A\207vd\324\11JN\334I\313\216\15\343\360!\321\261aHtl\30\322\303\240\243C\242\354P\66"
"\16\227a\321\261aHtl\30\322\303\222\243\203\266CC\16<\244\0\67@\225\262\365\1\35\323Y\207"
"A\63\345H\16&q\16&q\16\246C\30\347H\230\204\341\220\216\345$\315\346\251;\22)\321\60G"
"I\26%q\224\16\331\60(Y\35\316\206\254\224\15\212N\310\311:\5\70I\265\222\365\201!\247\210:"
"\250\205:\22&i\34fi\30\15\331\220\225r(k\7\302,\14\207S\230\345P\222E\232\242iI"
"i\30\242$\213\242a\210\252\331\240Ei\70&\331\220\246\303\230c\71\66\210\71\251NLr\252\4\71"
"E\224\262\265\206\17\331p\310\201d\70\350\310\360\216\14\7\35\32\224A\315\6e\210\263\341\220c\303\35"
"\34\6\35\35\6\35\35\16:\64\34thP\6\61\34\226AJ\207!\234\207wdx\310\201d\70\310"
"\331\360!\2:O\265\222\365\261\235\226\344\224(\311v\244)\251cI\30\245a\363\222)\265\60\311\224"
"(Q\63e\210\222\64\34\222\60\316\224-G\244!\322\31\207dX\206eX\206eXt\6eP\206"
"e\30\222A\31\226Ag\30\224a\31\224aH\206eP\4;:u\262\365\241\235\244\351\250\16\350P"
"\70\346@f\313\241\34\310\301l\313\341,\347\247\341\207d\370\203\262\264IC\262\264\14\321\220,m\303"
"\240,-\303!Kl\303\177\31~H\0<\77\265\222\365\11w\302\264\303\311\220\344p\35N\242$\207"
"\353p\22%\311\360\20\331\321X\253D\261\24F\311p\11+\303\22\25\243\70K\262r\16\307\303\347\34"
"\316\201\17\71\232\345\224\64'\34r\14=\64\62\326\365\21\235\62\344\240d\7\206p\10#\247$\321\206"
"L\321$\233*\251:\240\3:\222\3:\222\3:\222\3I\16\304\231\32\312Z\244c\312N\320\21\0"
">L\265\222u\206\37\222\234\252\14\37\24%\247$J\16\254\211\22Gi\242DY\42U\224(R\225"
"D\211r\250\242$:\42%JNI\224\234\222(\303\7E\247\352H\216iI\244%\231T\232JZ"
"\22iI\246#\71\246S\223\341\207\4\77@\264\222u\206w`P\242A\316\206-\316\321\70G\343D"
"\262\304\211d\211s\64\316\251\211$\355@\42I\345\34\312\322\34+&Z\230U\244\61\213\342Z\222\23"
"\62\35\215\222:\232E\303\203\16|\7@C\265\222\365\301\34\313!\235\232\344\340\30\345P\226\15Z\65"
"\207\246\64\307\252\311\60\344@\26\245\71\262\245\71!\315\201\37\302\341 N\303\343\360%\34\262\34\11\343"
"\34\11\343\34\11\343\34\11\343\34\11\343\341\33\0AD\265\222u\206\17ZN\213\222v\60\312i\321\360"
"C\224\323\242\234\26%\303\16DuP\12s,Z\242d\30\242\304\226\203\303\240\344P\322E\31\206h"
"\30\244\34U\264\34L\326\341\220\205\71)g\213%\347\234\4B:u\262u\206\37\222\234\252\264\303:"
"u\370\203N\325\251\322\360I\32>I\313p\220\244!\31\16\221\64(\342$\15\311p\210\244e\70H"
"\322\360I\32>\351T\235\232\14\77$\0CM\265\222\265s \207\323\234\62\350\320\226fcT\211\312"
"Q\16D\261\62\134t$\207rhX\206\35I\266%\36\226\312\60&CR\31\222h\31\264A\31\225"
"\213\216T,u`y\36\206d\30\342d\251,q\266l\71\220)Z\216\344`\10DD\225\262\365\201"
",\311\341\60\312\301v(\255Ca\35\214\302\34\312\222\254\232\344`\222E\71\30\265\203Q\22\345p$"
"\345p\244\351\220&\325\201(\222\262\64\213\222(k\252EY\224U\263\64L\263\264\226f\31\0EC"
"\224\262\265\7\35Vu,\207r$S\264\70\212\246j\224dI\24\206\303\20f\341\60\204Y\264NY"
"\270\214Y\270\214\245!\31\242\64\212\246r\16\316\71\64\310\352\240\350\300 \15\211N\30\222\234\62\350\244"
"\5F\77\225\262\365\321\235\224\264\3C\224dIZ\207\302\70\232\322PR$-\314:J\212\244\305\321"
"\224\326\241\60N\262$\315\201\244\71\207\266p\320\241-\247E\71-\311\221\35\321\251\303\37\222\341\207\4"
"GJ\261\232u\207!Gt@\224\206!R\42\35P\226\34L\224\34L\224pL\224\254E\311Z\224"
"h\30\242D\211\226)Q\242eJ\224h\30\242D\211\206!J\232\6)\211\222\34J\262$\7\222\64"
"\321\224\34\210\246\34\322tt\7H\62\222\266\365\21\235\22\345p\230\243a\216\14\361\220\345\204$'\351"
"$\235\64\344\204,\207\303\34\15s\64\313\341!'\350$\235\244\223\222\234\220\15\17\22\0I=\265\222"
"u\206\37\222\234\252\264\303:u\370\203N\325\251\322\360I\312\261(\222\22U\213\244DS#)\315\201"
"H\32>\351T\235*\15\203\66D:U\32\6m\210t\252NM\206\37\22\0J:\224\262\265\7\35"
"Vu,\207r$\7\343\34Ns\70\254%aV\214\262RX\312JaVL\262\260\16\247\71\134\7"
"\347\34\32duPt`\220\206D'\14IN\31t\322\2\0\0\0\4\377\377\0";
| 3,201 |
318 | /*
* Copyright Beijing 58 Information Technology Co.,Ltd.
*
* 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 com.bj58.spat.gaea.server.core.communication.tcp;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import com.bj58.spat.gaea.server.contract.context.Global;
import com.bj58.spat.gaea.server.contract.log.ILog;
import com.bj58.spat.gaea.server.contract.log.LogFactory;
import com.bj58.spat.gaea.server.contract.server.IServer;
import com.bj58.spat.gaea.server.core.proxy.IInvokerHandle;
/**
* start netty server
*
* @author Service Platform Architecture Team (<EMAIL>)
*/
public class SocketServer implements IServer {
public SocketServer() {
}
static ILog logger = LogFactory.getLogger(SocketServer.class);
/**
* netty ServerBootstrap
*/
static final ServerBootstrap bootstrap = new ServerBootstrap();
/**
* record all channel
*/
static final ChannelGroup allChannels = new DefaultChannelGroup("Gaea-SockerServer");
/**
* invoker handle
*/
static IInvokerHandle invokerHandle = null;
/**
* start netty server
*/
@Override
public void start() throws Exception {
logger.info("loading invoker...");
String invoker = Global.getSingleton().getServiceConfig().getString("gaea.proxy.invoker.implement");
invokerHandle = (IInvokerHandle) Class.forName(invoker).newInstance();
logger.info("initing server...");
initSocketServer();
}
/**
* stop netty server
*/
@Override
public void stop() throws Exception {
logger.info("----------------------------------------------------");
logger.info("-- socket server closing...");
logger.info("-- channels count : " + allChannels.size());
ChannelGroupFuture future = allChannels.close();
logger.info("-- closing all channels...");
future.awaitUninterruptibly();
logger.info("-- closed all channels...");
bootstrap.getFactory().releaseExternalResources();
logger.info("-- released external resources");
logger.info("-- close success !");
logger.info("----------------------------------------------------");
}
/**
* 初始化socket server
* @throws Exception
*/
private void initSocketServer() throws Exception {
final boolean tcpNoDelay = true;
logger.info("-- socket server config --");
logger.info("-- listen ip: "
+ Global.getSingleton().getServiceConfig().getString("gaea.server.tcp.listenIP"));
logger.info("-- port: "
+ Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.listenPort"));
logger.info("-- tcpNoDelay: " + tcpNoDelay);
logger.info("-- receiveBufferSize: "
+ Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.receiveBufferSize"));
logger.info("-- sendBufferSize: "
+ Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.sendBufferSize"));
logger.info("-- frameMaxLength: "
+ Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.frameMaxLength"));
logger.info("-- worker thread count: "
+ Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.workerCount"));
logger.info("--------------------------");
logger.info(Global.getSingleton().getServiceConfig().getString("gaea.service.name")
+ " SocketServer starting...");
bootstrap.setFactory(new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool(),
Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.workerCount")
)
);
SocketHandler handler = new SocketHandler();
bootstrap.setPipelineFactory(new SocketPipelineFactory(handler,
Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.frameMaxLength")));
bootstrap.setOption("child.tcpNoDelay", tcpNoDelay);
bootstrap.setOption("child.receiveBufferSize",
Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.receiveBufferSize"));
bootstrap.setOption("child.sendBufferSize",
Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.sendBufferSize"));
try {
InetSocketAddress socketAddress = null;
socketAddress = new InetSocketAddress(Global.getSingleton().getServiceConfig().getString("gaea.server.tcp.listenIP"),
Global.getSingleton().getServiceConfig().getInt("gaea.server.tcp.listenPort"));
Channel channel = bootstrap.bind(socketAddress);
allChannels.add(channel);
} catch (Exception e) {
logger.error("init socket server error", e);
System.exit(1);
}
}
} | 2,215 |
1,198 | <gh_stars>1000+
/*
Copyright 2017-2019 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 "lullaby/systems/render/next/render_target.h"
#include "lullaby/systems/render/next/gl_helpers.h"
namespace {
const int kRgbaStride = 4;
} // namespace
namespace lull {
RenderTarget::RenderTarget(const RenderTargetCreateParams& create_params)
: dimensions_(create_params.dimensions),
num_mip_levels_(create_params.num_mip_levels) {
GLint original_frame_buffer = 0;
GLint original_render_buffer = 0;
GL_CALL(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &original_frame_buffer));
GL_CALL(glGetIntegerv(GL_RENDERBUFFER_BINDING, &original_render_buffer));
GLuint gl_framebuffer_id = 0;
GL_CALL(glGenFramebuffers(1, &gl_framebuffer_id));
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, gl_framebuffer_id));
frame_buffer_ = gl_framebuffer_id;
const bool is_depth_texture =
(create_params.texture_format == TextureFormat_Depth16 ||
create_params.texture_format == TextureFormat_Depth32F);
if (create_params.texture_format != TextureFormat_None) {
const GLenum target =
is_depth_texture ? GL_DEPTH_ATTACHMENT : GL_COLOR_ATTACHMENT0;
GLuint gl_texture_id = 0;
GL_CALL(glGenTextures(1, &gl_texture_id));
GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_texture_id));
GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0,
GetGlInternalFormat(create_params.texture_format),
create_params.dimensions.x, create_params.dimensions.y,
0, GetGlFormat(create_params.texture_format),
GetGlType(create_params.texture_format), nullptr));
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GetGlTextureFiltering(create_params.mag_filter)));
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GetGlTextureFiltering(create_params.min_filter)));
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GetGlTextureWrap(create_params.wrap_s)));
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GetGlTextureWrap(create_params.wrap_t)));
GL_CALL(glFramebufferTexture2D(GL_FRAMEBUFFER, target, GL_TEXTURE_2D,
gl_texture_id, 0));
texture_ = gl_texture_id;
if (num_mip_levels_ == 0) {
glGenerateMipmap(GL_TEXTURE_2D);
} else if (num_mip_levels_ > 1) {
LOG(ERROR)
<< "Manually specified number of mipmaps is currently not supported.";
}
if (is_depth_texture) {
const GLenum draw_buffers = GL_NONE;
GL_CALL(glDrawBuffers(1, &draw_buffers));
GL_CALL(glReadBuffer(GL_NONE));
}
}
if (create_params.depth_stencil_format != DepthStencilFormat_None &&
!is_depth_texture) {
GLuint gl_depthbuffer_id = 0;
GL_CALL(glGenRenderbuffers(1, &gl_depthbuffer_id));
GL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, gl_depthbuffer_id));
GL_CALL(glRenderbufferStorage(
GL_RENDERBUFFER,
GetGlInternalFormat(create_params.depth_stencil_format),
create_params.dimensions.x, create_params.dimensions.y));
GL_CALL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, gl_depthbuffer_id));
depth_buffer_ = gl_depthbuffer_id;
}
DCHECK(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, original_frame_buffer));
GL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, original_render_buffer));
}
RenderTarget::~RenderTarget() {
if (frame_buffer_) {
GLuint handle = *frame_buffer_;
GL_CALL(glDeleteFramebuffers(1, &handle));
}
if (depth_buffer_) {
GLuint handle = *depth_buffer_;
GL_CALL(glDeleteRenderbuffers(1, &handle));
}
if (texture_) {
GLuint handle = *texture_;
GL_CALL(glDeleteTextures(1, &handle));
}
}
void RenderTarget::Bind() const {
if (frame_buffer_) {
GL_CALL(glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &prev_frame_buffer_));
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, *frame_buffer_));
GL_CALL(glViewport(0, 0, dimensions_.x, dimensions_.y));
}
}
void RenderTarget::Unbind() const {
if (texture_ && num_mip_levels_ == 0) {
GLuint current_texture_id;
GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D,
reinterpret_cast<GLint*>(¤t_texture_id)));
GL_CALL(glBindTexture(GL_TEXTURE_2D, *texture_));
GL_CALL(glGenerateMipmap(GL_TEXTURE_2D));
GL_CALL(glBindTexture(GL_TEXTURE_2D, current_texture_id));
}
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, prev_frame_buffer_));
prev_frame_buffer_ = 0;
}
ImageData RenderTarget::GetFrameBufferData() const {
if (!frame_buffer_) {
LOG(WARNING) << "No Framebuffer!";
return ImageData();
}
// Save previous OpenGL state.
GLint viewport[4];
GL_CALL(glGetIntegerv(GL_VIEWPORT, viewport));
GLint prev_frame_buffer;
GL_CALL(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_frame_buffer));
GLint prev_read_buffer;
GL_CALL(glGetIntegerv(GL_READ_BUFFER, &prev_read_buffer));
Bind();
const int size = dimensions_.x * dimensions_.y * kRgbaStride;
DataContainer container = DataContainer::CreateHeapDataContainer(size);
uint8_t* pixels = container.GetAppendPtr(size);
GL_CALL(glReadBuffer(GL_COLOR_ATTACHMENT0));
GL_CALL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL_CALL(glReadPixels(0, 0, dimensions_.x, dimensions_.y, GL_RGBA,
GL_UNSIGNED_BYTE, pixels));
// Restore OpenGL state.
GL_CALL(glViewport(viewport[0], viewport[1], viewport[2], viewport[3]));
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, prev_frame_buffer));
GL_CALL(glReadBuffer(prev_read_buffer));
return ImageData(ImageData::kRgba8888, dimensions_, std::move(container));
}
} // namespace lull
| 2,687 |
341 | package org.myproject.ms.monitoring.mtc;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("spring.sleuth.metric")
public class SMProp {
private boolean enabled = true;
private Span span = new Span();
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Span getSpan() {
return this.span;
}
public void setSpan(Span span) {
this.span = span;
}
public static class Span {
private String acceptedName = "counter.span.accepted";
private String droppedName = "counter.span.dropped";
public String getAcceptedName() {
return this.acceptedName;
}
public void setAcceptedName(String acceptedName) {
this.acceptedName = acceptedName;
}
public String getDroppedName() {
return this.droppedName;
}
public void setDroppedName(String droppedName) {
this.droppedName = droppedName;
}
}
}
| 321 |
340 | {
"name": "react-spa",
"version": "0.0.1",
"homepage": "https://github.com/WRidder/react-spa",
"authors": [
"<NAME> <<EMAIL>>"
],
"description": "Community site SPA Proof of Concept based on ReactJS",
"main": "client/src/app.js",
"moduleType": [
"amd"
],
"keywords": [
"reactjs",
"immutable-js",
"reflux",
"react-router",
"isomorphic"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"foundation": "5.5.0",
"foundation-icons": "*",
"mdi": "~0.9.21-alpha"
},
"resolutions": {
"mdi": "~0.9.21-alpha"
}
}
| 315 |
363 | <reponame>ajisaka/ai-research-keyphrase-extraction
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from codecs import open
from setuptools import setup, find_packages
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(
name='swisscom_ai.research_keyphrase',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='0.9.5',
description='Swisscom AI Research Keyphrase Extraction',
url='https://github.com/swisscom/ai-research-keyphrase-extraction',
author='Swisscom (Schweiz) AG',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Programming Language :: Python :: 3.6',
],
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
package_data={'swisscom_ai.research_keyphrase': []},
include_package_data=True,
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=required,
# List additional groups of dependencies here (e.g. development
# dependencies). You can install these using the following syntax,
# for example:
# $ pip install -e .[dev,test]
extras_require={
'dev': [],
'test': [],
},
)
| 598 |
5,169 | <reponame>Gantios/Specs<gh_stars>1000+
{
"name": "PaylevenFramework",
"version": "1.1.2",
"summary": "This project provides an SDK for iOS. It allows use case categorisation, prioritisation and tokenization of payment instruments, which are retrieved using the user token created | Payleven",
"homepage": "https://current-developer.payleven.com/docs/In-App/index.html",
"license": {
"type": "Copyright",
"file": "LICENSE"
},
"authors": "Payleven",
"source": {
"git": "https://github.com/conichiGMBH/PaylevenFramework-iOS-CocoaPod.git",
"tag": "1.1.2"
},
"platforms": {
"ios": "7.0"
},
"source_files": "PaylevenInAppSDK.framework/Versions/A/Headers/*.h",
"requires_arc": true,
"ios": {
"vendored_frameworks": "PaylevenInAppSDK.framework"
},
"xcconfig": {
"FRAMEWORK_SEARCH_PATHS": "$(inherited)"
},
"preserve_paths": "PaylevenInAppSDK.framework"
}
| 365 |
945 | <reponame>arobert01/ITK
/*=========================================================================
Program: GDCM (Grassroots DICOM). A DICOM library
Copyright (c) 2006-2011 <NAME>
All rights reserved.
See Copyright.txt or http://gdcm.sourceforge.net/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.
=========================================================================*/
#include "gdcmObject.h"
namespace gdcm
{
// Don't ask why, but this is EXTREMELY important on Win32
// Apparently the compiler is doing something special the first time it compiles
// this instanciation unit
// If this fake file is not present I get an unresolved symbol for each function
// of the gdcm::Object class
}
| 234 |
2,603 | <filename>FreeRTOS/Demo/T-HEAD_CB2201_CDK/csi/csi_core/csi_core_dummy.c
/*
* Copyright (C) 2017 C-SKY Microsystems Co., Ltd. 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 csi_core_dummy.c
* @brief CSI Core Layer Source File
* @version V1.0
* @date 02. June 2017
******************************************************************************/
#include "csi_core.h"
#define _WEAK_ __attribute__((weak))
/* ################################## NVIC function ############################################ */
_WEAK_ void drv_nvic_init(uint32_t prio_bits)
{
return;
}
_WEAK_ void drv_nvic_enable_irq(int32_t irq_num)
{
return;
}
_WEAK_ void drv_nvic_disable_irq(int32_t irq_num)
{
return;
}
_WEAK_ uint32_t drv_nvic_get_pending_irq(int32_t irq_num)
{
return 0;
}
_WEAK_ void drv_nvic_set_pending_irq(int32_t irq_num)
{
return;
}
_WEAK_ void drv_nvic_clear_pending_irq(int32_t irq_num)
{
return;
}
_WEAK_ uint32_t drv_nvic_get_active(int32_t irq_num)
{
return 0;
}
_WEAK_ void drv_nvic_set_prio(int32_t irq_num, uint32_t priority)
{
return;
}
_WEAK_ uint32_t drv_nvic_get_prio(int32_t irq_num)
{
return 0;
}
/* ########################## Cache functions #################################### */
_WEAK_ void drv_icache_enable(void)
{
return;
}
_WEAK_ void drv_icache_disable(void)
{
return;
}
_WEAK_ void drv_icache_invalid(void)
{
return;
}
_WEAK_ void drv_dcache_enable(void)
{
return;
}
_WEAK_ void drv_dcache_disable(void)
{
return;
}
_WEAK_ void drv_dcache_invalid(void)
{
return;
}
_WEAK_ void drv_dcache_clean(void)
{
return;
}
_WEAK_ void drv_dcache_clean_invalid(void)
{
return;
}
_WEAK_ void drv_dcache_invalid_range(uint32_t *addr, int32_t dsize)
{
return;
}
_WEAK_ void drv_dcache_clean_range(uint32_t *addr, int32_t dsize)
{
return;
}
_WEAK_ void drv_dcache_clean_invalid_range(uint32_t *addr, int32_t dsize)
{
return;
}
_WEAK_ void drv_cache_set_range(uint32_t index, uint32_t baseAddr, uint32_t size, uint32_t enable)
{
return;
}
_WEAK_ void drv_cache_enable_profile(void)
{
return;
}
_WEAK_ void drv_cache_disable_profile(void)
{
return;
}
_WEAK_ void drv_cache_reset_profile(void)
{
return;
}
_WEAK_ uint32_t drv_cache_get_access_time(void)
{
return 0;
}
_WEAK_ uint32_t drv_cache_get_miss_time(void)
{
return 0;
}
/* ################################## SysTick function ############################################ */
_WEAK_ uint32_t drv_coret_config(uint32_t ticks, int32_t irq_num)
{
return 0;
}
| 1,276 |
401 | /*
* Copyright 2017 <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 com.mtramin.rxfingerprint;
import static com.mtramin.rxfingerprint.CryptoData.SEPARATOR;
/**
* Exception thrown when CryptoData is invalid
*/
class CryptoDataException extends Exception {
static final String ERROR_MSG = "Invalid input given for decryption operation. Make sure you provide a string that was previously encrypted by RxFingerprint. empty: %s, correct format: %s";
private CryptoDataException(String message) {
super(message);
}
static CryptoDataException fromCryptoDataString(String input) {
boolean isEmpty = input.isEmpty();
boolean containsSeparator = input.contains(SEPARATOR);
String message = String.format(ERROR_MSG, isEmpty, containsSeparator);
return new CryptoDataException(message);
}
}
| 364 |
522 | <reponame>timgates42/mako<filename>src/map/hashtab.c
/*!
* hashtab.c - hash table for mako
* Copyright (c) 2021, <NAME> (MIT License).
* https://github.com/chjj/mako
*/
#include <mako/map.h>
#include "map.h"
/*
* Hash Table
*/
DEFINE_HASH_MAP(btc_hashtab, int64_t, -1, MAP_EXTERN)
| 127 |
954 | /**
* Copyright 2003-2006 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 event 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.jdon.strutsutil.file;
import com.jdon.controller.model.Model;
public class UploadFile extends Model {
/**
*
*/
private static final long serialVersionUID = -36456540301820716L;
private String id;
private String name;
private String description;
private byte[] data;
private String contentType;
private int size;
//所属父ID
private String parentId;
private String tempId;
public byte[] getData() {
return data;
}
public String getName() {
return name;
}
public void setData(byte[] data) {
this.data = data;
}
public void setName(String name) {
this.name = name;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getTempId() {
return tempId;
}
public void setTempId(String tempId) {
this.tempId = tempId;
}
/**
* @return Returns the description.
*/
public String getDescription() {
return description;
}
/**
* @param description
* The description to set.
*/
public void setDescription(String description) {
this.description = description;
}
}
| 991 |
2,151 | // Copyright 2016 The SwiftShader 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.
// utilities.cpp: Conversion functions and other utility routines.
#include "utilities.h"
#include "mathutil.h"
#include "Context.h"
#include "common/debug.h"
#include <limits>
#include <stdio.h>
namespace gl
{
unsigned int UniformComponentCount(GLenum type)
{
switch(type)
{
case GL_BOOL:
case GL_FLOAT:
case GL_INT:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
return 1;
case GL_BOOL_VEC2:
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
return 2;
case GL_INT_VEC3:
case GL_FLOAT_VEC3:
case GL_BOOL_VEC3:
return 3;
case GL_BOOL_VEC4:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_FLOAT_MAT2:
return 4;
case GL_FLOAT_MAT3:
return 9;
case GL_FLOAT_MAT4:
return 16;
default:
UNREACHABLE(type);
}
return 0;
}
GLenum UniformComponentType(GLenum type)
{
switch(type)
{
case GL_BOOL:
case GL_BOOL_VEC2:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
return GL_BOOL;
case GL_FLOAT:
case GL_FLOAT_VEC2:
case GL_FLOAT_VEC3:
case GL_FLOAT_VEC4:
case GL_FLOAT_MAT2:
case GL_FLOAT_MAT3:
case GL_FLOAT_MAT4:
return GL_FLOAT;
case GL_INT:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_INT_VEC4:
return GL_INT;
default:
UNREACHABLE(type);
}
return GL_NONE;
}
size_t UniformTypeSize(GLenum type)
{
switch(type)
{
case GL_BOOL: return sizeof(GLboolean);
case GL_FLOAT: return sizeof(GLfloat);
case GL_INT: return sizeof(GLint);
}
return UniformTypeSize(UniformComponentType(type)) * UniformComponentCount(type);
}
int VariableRowCount(GLenum type)
{
switch(type)
{
case GL_NONE:
return 0;
case GL_BOOL:
case GL_FLOAT:
case GL_INT:
case GL_BOOL_VEC2:
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_FLOAT_VEC3:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
return 1;
case GL_FLOAT_MAT2:
return 2;
case GL_FLOAT_MAT3:
return 3;
case GL_FLOAT_MAT4:
return 4;
default:
UNREACHABLE(type);
}
return 0;
}
int VariableColumnCount(GLenum type)
{
switch(type)
{
case GL_NONE:
return 0;
case GL_BOOL:
case GL_FLOAT:
case GL_INT:
return 1;
case GL_BOOL_VEC2:
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
case GL_FLOAT_MAT2:
return 2;
case GL_INT_VEC3:
case GL_FLOAT_VEC3:
case GL_BOOL_VEC3:
case GL_FLOAT_MAT3:
return 3;
case GL_BOOL_VEC4:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_FLOAT_MAT4:
return 4;
default:
UNREACHABLE(type);
}
return 0;
}
int AllocateFirstFreeBits(unsigned int *bits, unsigned int allocationSize, unsigned int bitsSize)
{
ASSERT(allocationSize <= bitsSize);
unsigned int mask = std::numeric_limits<unsigned int>::max() >> (std::numeric_limits<unsigned int>::digits - allocationSize);
for(unsigned int i = 0; i < bitsSize - allocationSize + 1; i++)
{
if((*bits & mask) == 0)
{
*bits |= mask;
return i;
}
mask <<= 1;
}
return -1;
}
GLsizei ComputePitch(GLsizei width, GLenum format, GLenum type, GLint alignment)
{
ASSERT(alignment > 0 && isPow2(alignment));
GLsizei rawPitch = ComputePixelSize(format, type) * width;
return (rawPitch + alignment - 1) & ~(alignment - 1);
}
GLsizei ComputeCompressedPitch(GLsizei width, GLenum format)
{
return ComputeCompressedSize(width, 1, format);
}
GLsizei ComputeCompressedSize(GLsizei width, GLsizei height, GLenum format)
{
switch(format)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return 8 * (GLsizei)ceil((float)width / 4.0f) * (GLsizei)ceil((float)height / 4.0f);
case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return 16 * (GLsizei)ceil((float)width / 4.0f) * (GLsizei)ceil((float)height / 4.0f);
default:
return 0;
}
}
bool IsCompressed(GLenum format)
{
return format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT ||
format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ||
format == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT ||
format == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
}
bool IsDepthTexture(GLenum format)
{
return format == GL_DEPTH_COMPONENT ||
format == GL_DEPTH_STENCIL_EXT;
}
bool IsStencilTexture(GLenum format)
{
return format == GL_STENCIL_INDEX ||
format == GL_DEPTH_STENCIL_EXT;
}
// Returns the size, in bytes, of a single texel in an Image
int ComputePixelSize(GLenum format, GLenum type)
{
switch(type)
{
case GL_UNSIGNED_BYTE:
switch(format)
{
case GL_ALPHA: return sizeof(unsigned char);
case GL_LUMINANCE: return sizeof(unsigned char);
case GL_LUMINANCE_ALPHA: return sizeof(unsigned char) * 2;
case GL_RGB: return sizeof(unsigned char) * 3;
case GL_RGBA: return sizeof(unsigned char) * 4;
case GL_BGRA_EXT: return sizeof(unsigned char) * 4;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_UNSIGNED_SHORT:
return sizeof(unsigned short);
case GL_UNSIGNED_INT:
case GL_UNSIGNED_INT_24_8_EXT:
case GL_UNSIGNED_INT_8_8_8_8_REV:
return sizeof(unsigned int);
case GL_FLOAT:
switch(format)
{
case GL_ALPHA: return sizeof(float);
case GL_LUMINANCE: return sizeof(float);
case GL_DEPTH_COMPONENT: return sizeof(float);
case GL_LUMINANCE_ALPHA: return sizeof(float) * 2;
case GL_RGB: return sizeof(float) * 3;
case GL_RGBA: return sizeof(float) * 4;
default: UNREACHABLE(format);
}
break;
case GL_HALF_FLOAT:
switch(format)
{
case GL_ALPHA: return sizeof(unsigned short);
case GL_LUMINANCE: return sizeof(unsigned short);
case GL_LUMINANCE_ALPHA: return sizeof(unsigned short) * 2;
case GL_RGB: return sizeof(unsigned short) * 3;
case GL_RGBA: return sizeof(unsigned short) * 4;
default: UNREACHABLE(format);
}
break;
default: UNREACHABLE(type);
}
return 0;
}
bool IsCubemapTextureTarget(GLenum target)
{
return (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z);
}
int CubeFaceIndex(GLenum cubeFace)
{
switch(cubeFace)
{
case GL_TEXTURE_CUBE_MAP:
case GL_TEXTURE_CUBE_MAP_POSITIVE_X: return 0;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: return 1;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: return 2;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: return 3;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: return 4;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: return 5;
default: UNREACHABLE(cubeFace); return 0;
}
}
bool IsTextureTarget(GLenum target)
{
return target == GL_TEXTURE_2D || IsCubemapTextureTarget(target);
}
// Verify that format/type are one of the combinations from table 3.4.
bool CheckTextureFormatType(GLenum format, GLenum type)
{
switch(type)
{
case GL_UNSIGNED_BYTE:
switch(format)
{
case GL_RGBA:
case GL_BGRA_EXT:
case GL_RGB:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
return true;
default:
return false;
}
case GL_FLOAT:
case GL_HALF_FLOAT:
switch(format)
{
case GL_RGBA:
case GL_RGB:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
return true;
default:
return false;
}
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
return (format == GL_RGBA);
case GL_UNSIGNED_SHORT_5_6_5:
return (format == GL_RGB);
case GL_UNSIGNED_INT:
return (format == GL_DEPTH_COMPONENT);
case GL_UNSIGNED_INT_24_8_EXT:
return (format == GL_DEPTH_STENCIL_EXT);
case GL_UNSIGNED_INT_8_8_8_8_REV:
return (format == GL_BGRA);
default:
return false;
}
}
bool IsColorRenderable(GLenum internalformat)
{
switch(internalformat)
{
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_EXT:
case GL_RGBA8_EXT:
return true;
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_EXT:
return false;
default:
UNIMPLEMENTED();
}
return false;
}
bool IsDepthRenderable(GLenum internalformat)
{
switch(internalformat)
{
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH24_STENCIL8_EXT:
return true;
case GL_STENCIL_INDEX8:
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_EXT:
case GL_RGBA8_EXT:
return false;
default:
UNIMPLEMENTED();
}
return false;
}
bool IsStencilRenderable(GLenum internalformat)
{
switch(internalformat)
{
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_EXT:
return true;
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_EXT:
case GL_RGBA8_EXT:
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
return false;
default:
UNIMPLEMENTED();
}
return false;
}
}
namespace es2sw
{
sw::DepthCompareMode ConvertDepthComparison(GLenum comparison)
{
switch(comparison)
{
case GL_NEVER: return sw::DEPTH_NEVER;
case GL_ALWAYS: return sw::DEPTH_ALWAYS;
case GL_LESS: return sw::DEPTH_LESS;
case GL_LEQUAL: return sw::DEPTH_LESSEQUAL;
case GL_EQUAL: return sw::DEPTH_EQUAL;
case GL_GREATER: return sw::DEPTH_GREATER;
case GL_GEQUAL: return sw::DEPTH_GREATEREQUAL;
case GL_NOTEQUAL: return sw::DEPTH_NOTEQUAL;
default: UNREACHABLE(comparison);
}
return sw::DEPTH_ALWAYS;
}
sw::StencilCompareMode ConvertStencilComparison(GLenum comparison)
{
switch(comparison)
{
case GL_NEVER: return sw::STENCIL_NEVER;
case GL_ALWAYS: return sw::STENCIL_ALWAYS;
case GL_LESS: return sw::STENCIL_LESS;
case GL_LEQUAL: return sw::STENCIL_LESSEQUAL;
case GL_EQUAL: return sw::STENCIL_EQUAL;
case GL_GREATER: return sw::STENCIL_GREATER;
case GL_GEQUAL: return sw::STENCIL_GREATEREQUAL;
case GL_NOTEQUAL: return sw::STENCIL_NOTEQUAL;
default: UNREACHABLE(comparison);
}
return sw::STENCIL_ALWAYS;
}
sw::Color<float> ConvertColor(gl::Color color)
{
return sw::Color<float>(color.red, color.green, color.blue, color.alpha);
}
sw::BlendFactor ConvertBlendFunc(GLenum blend)
{
switch(blend)
{
case GL_ZERO: return sw::BLEND_ZERO;
case GL_ONE: return sw::BLEND_ONE;
case GL_SRC_COLOR: return sw::BLEND_SOURCE;
case GL_ONE_MINUS_SRC_COLOR: return sw::BLEND_INVSOURCE;
case GL_DST_COLOR: return sw::BLEND_DEST;
case GL_ONE_MINUS_DST_COLOR: return sw::BLEND_INVDEST;
case GL_SRC_ALPHA: return sw::BLEND_SOURCEALPHA;
case GL_ONE_MINUS_SRC_ALPHA: return sw::BLEND_INVSOURCEALPHA;
case GL_DST_ALPHA: return sw::BLEND_DESTALPHA;
case GL_ONE_MINUS_DST_ALPHA: return sw::BLEND_INVDESTALPHA;
case GL_CONSTANT_COLOR: return sw::BLEND_CONSTANT;
case GL_ONE_MINUS_CONSTANT_COLOR: return sw::BLEND_INVCONSTANT;
case GL_CONSTANT_ALPHA: return sw::BLEND_CONSTANTALPHA;
case GL_ONE_MINUS_CONSTANT_ALPHA: return sw::BLEND_INVCONSTANTALPHA;
case GL_SRC_ALPHA_SATURATE: return sw::BLEND_SRCALPHASAT;
default: UNREACHABLE(blend);
}
return sw::BLEND_ZERO;
}
sw::BlendOperation ConvertBlendOp(GLenum blendOp)
{
switch(blendOp)
{
case GL_FUNC_ADD: return sw::BLENDOP_ADD;
case GL_FUNC_SUBTRACT: return sw::BLENDOP_SUB;
case GL_FUNC_REVERSE_SUBTRACT: return sw::BLENDOP_INVSUB;
case GL_MIN_EXT: return sw::BLENDOP_MIN;
case GL_MAX_EXT: return sw::BLENDOP_MAX;
default: UNREACHABLE(blendOp);
}
return sw::BLENDOP_ADD;
}
sw::LogicalOperation ConvertLogicalOperation(GLenum logicalOperation)
{
switch(logicalOperation)
{
case GL_CLEAR: return sw::LOGICALOP_CLEAR;
case GL_SET: return sw::LOGICALOP_SET;
case GL_COPY: return sw::LOGICALOP_COPY;
case GL_COPY_INVERTED: return sw::LOGICALOP_COPY_INVERTED;
case GL_NOOP: return sw::LOGICALOP_NOOP;
case GL_INVERT: return sw::LOGICALOP_INVERT;
case GL_AND: return sw::LOGICALOP_AND;
case GL_NAND: return sw::LOGICALOP_NAND;
case GL_OR: return sw::LOGICALOP_OR;
case GL_NOR: return sw::LOGICALOP_NOR;
case GL_XOR: return sw::LOGICALOP_XOR;
case GL_EQUIV: return sw::LOGICALOP_EQUIV;
case GL_AND_REVERSE: return sw::LOGICALOP_AND_REVERSE;
case GL_AND_INVERTED: return sw::LOGICALOP_AND_INVERTED;
case GL_OR_REVERSE: return sw::LOGICALOP_OR_REVERSE;
case GL_OR_INVERTED: return sw::LOGICALOP_OR_INVERTED;
default: UNREACHABLE(logicalOperation);
}
return sw::LOGICALOP_COPY;
}
sw::StencilOperation ConvertStencilOp(GLenum stencilOp)
{
switch(stencilOp)
{
case GL_ZERO: return sw::OPERATION_ZERO;
case GL_KEEP: return sw::OPERATION_KEEP;
case GL_REPLACE: return sw::OPERATION_REPLACE;
case GL_INCR: return sw::OPERATION_INCRSAT;
case GL_DECR: return sw::OPERATION_DECRSAT;
case GL_INVERT: return sw::OPERATION_INVERT;
case GL_INCR_WRAP: return sw::OPERATION_INCR;
case GL_DECR_WRAP: return sw::OPERATION_DECR;
default: UNREACHABLE(stencilOp);
}
return sw::OPERATION_KEEP;
}
sw::AddressingMode ConvertTextureWrap(GLenum wrap)
{
switch(wrap)
{
case GL_CLAMP: return sw::ADDRESSING_CLAMP;
case GL_REPEAT: return sw::ADDRESSING_WRAP;
case GL_CLAMP_TO_EDGE: return sw::ADDRESSING_CLAMP;
case GL_MIRRORED_REPEAT: return sw::ADDRESSING_MIRROR;
default: UNREACHABLE(wrap);
}
return sw::ADDRESSING_WRAP;
}
sw::CullMode ConvertCullMode(GLenum cullFace, GLenum frontFace)
{
switch(cullFace)
{
case GL_FRONT:
return (frontFace == GL_CCW ? sw::CULL_CLOCKWISE : sw::CULL_COUNTERCLOCKWISE);
case GL_BACK:
return (frontFace == GL_CCW ? sw::CULL_COUNTERCLOCKWISE : sw::CULL_CLOCKWISE);
case GL_FRONT_AND_BACK:
return sw::CULL_NONE; // culling will be handled during draw
default: UNREACHABLE(cullFace);
}
return sw::CULL_COUNTERCLOCKWISE;
}
unsigned int ConvertColorMask(bool red, bool green, bool blue, bool alpha)
{
return (red ? 0x00000001 : 0) |
(green ? 0x00000002 : 0) |
(blue ? 0x00000004 : 0) |
(alpha ? 0x00000008 : 0);
}
sw::MipmapType ConvertMipMapFilter(GLenum minFilter)
{
switch(minFilter)
{
case GL_NEAREST:
case GL_LINEAR:
return sw::MIPMAP_NONE;
break;
case GL_NEAREST_MIPMAP_NEAREST:
case GL_LINEAR_MIPMAP_NEAREST:
return sw::MIPMAP_POINT;
break;
case GL_NEAREST_MIPMAP_LINEAR:
case GL_LINEAR_MIPMAP_LINEAR:
return sw::MIPMAP_LINEAR;
break;
default:
UNREACHABLE(minFilter);
return sw::MIPMAP_NONE;
}
}
sw::FilterType ConvertTextureFilter(GLenum minFilter, GLenum magFilter, float maxAnisotropy)
{
if(maxAnisotropy > 1.0f)
{
return sw::FILTER_ANISOTROPIC;
}
switch(minFilter)
{
case GL_NEAREST:
case GL_NEAREST_MIPMAP_NEAREST:
case GL_NEAREST_MIPMAP_LINEAR:
return (magFilter == GL_NEAREST) ? sw::FILTER_POINT : sw::FILTER_MIN_POINT_MAG_LINEAR;
case GL_LINEAR:
case GL_LINEAR_MIPMAP_NEAREST:
case GL_LINEAR_MIPMAP_LINEAR:
return (magFilter == GL_NEAREST) ? sw::FILTER_MIN_LINEAR_MAG_POINT : sw::FILTER_LINEAR;
default:
UNREACHABLE(minFilter);
return sw::FILTER_LINEAR;
}
}
bool ConvertPrimitiveType(GLenum primitiveType, GLsizei elementCount, gl::PrimitiveType &swPrimitiveType, int &primitiveCount)
{
switch(primitiveType)
{
case GL_POINTS:
swPrimitiveType = gl::DRAW_POINTLIST;
primitiveCount = elementCount;
break;
case GL_LINES:
swPrimitiveType = gl::DRAW_LINELIST;
primitiveCount = elementCount / 2;
break;
case GL_LINE_LOOP:
swPrimitiveType = gl::DRAW_LINELOOP;
primitiveCount = elementCount;
break;
case GL_LINE_STRIP:
swPrimitiveType = gl::DRAW_LINESTRIP;
primitiveCount = elementCount - 1;
break;
case GL_TRIANGLES:
swPrimitiveType = gl::DRAW_TRIANGLELIST;
primitiveCount = elementCount / 3;
break;
case GL_TRIANGLE_STRIP:
swPrimitiveType = gl::DRAW_TRIANGLESTRIP;
primitiveCount = elementCount - 2;
break;
case GL_TRIANGLE_FAN:
swPrimitiveType = gl::DRAW_TRIANGLEFAN;
primitiveCount = elementCount - 2;
break;
case GL_QUADS:
swPrimitiveType = gl::DRAW_QUADLIST;
primitiveCount = (elementCount / 4) * 2;
break;
default:
return false;
}
return true;
}
sw::Format ConvertRenderbufferFormat(GLenum format)
{
switch(format)
{
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGBA8_EXT: return sw::FORMAT_A8R8G8B8;
case GL_RGB565: return sw::FORMAT_R5G6B5;
case GL_RGB8_EXT: return sw::FORMAT_X8R8G8B8;
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_EXT: return sw::FORMAT_D24S8;
default: UNREACHABLE(format); return sw::FORMAT_A8R8G8B8;
}
}
}
namespace sw2es
{
unsigned int GetStencilSize(sw::Format stencilFormat)
{
switch(stencilFormat)
{
case sw::FORMAT_D24FS8:
case sw::FORMAT_D24S8:
case sw::FORMAT_D32FS8_TEXTURE:
return 8;
// case sw::FORMAT_D24X4S4:
// return 4;
// case sw::FORMAT_D15S1:
// return 1;
// case sw::FORMAT_D16_LOCKABLE:
case sw::FORMAT_D32:
case sw::FORMAT_D24X8:
case sw::FORMAT_D32F_LOCKABLE:
case sw::FORMAT_D16:
return 0;
// case sw::FORMAT_D32_LOCKABLE: return 0;
// case sw::FORMAT_S8_LOCKABLE: return 8;
default:
return 0;
}
}
unsigned int GetAlphaSize(sw::Format colorFormat)
{
switch(colorFormat)
{
case sw::FORMAT_A16B16G16R16F:
return 16;
case sw::FORMAT_A32B32G32R32F:
return 32;
case sw::FORMAT_A2R10G10B10:
return 2;
case sw::FORMAT_A8R8G8B8:
return 8;
case sw::FORMAT_A1R5G5B5:
return 1;
case sw::FORMAT_X8R8G8B8:
case sw::FORMAT_R5G6B5:
return 0;
default:
return 0;
}
}
unsigned int GetRedSize(sw::Format colorFormat)
{
switch(colorFormat)
{
case sw::FORMAT_A16B16G16R16F:
return 16;
case sw::FORMAT_A32B32G32R32F:
return 32;
case sw::FORMAT_A2R10G10B10:
return 10;
case sw::FORMAT_A8R8G8B8:
case sw::FORMAT_X8R8G8B8:
return 8;
case sw::FORMAT_A1R5G5B5:
case sw::FORMAT_R5G6B5:
return 5;
default:
return 0;
}
}
unsigned int GetGreenSize(sw::Format colorFormat)
{
switch(colorFormat)
{
case sw::FORMAT_A16B16G16R16F:
return 16;
case sw::FORMAT_A32B32G32R32F:
return 32;
case sw::FORMAT_A2R10G10B10:
return 10;
case sw::FORMAT_A8R8G8B8:
case sw::FORMAT_X8R8G8B8:
return 8;
case sw::FORMAT_A1R5G5B5:
return 5;
case sw::FORMAT_R5G6B5:
return 6;
default:
return 0;
}
}
unsigned int GetBlueSize(sw::Format colorFormat)
{
switch(colorFormat)
{
case sw::FORMAT_A16B16G16R16F:
return 16;
case sw::FORMAT_A32B32G32R32F:
return 32;
case sw::FORMAT_A2R10G10B10:
return 10;
case sw::FORMAT_A8R8G8B8:
case sw::FORMAT_X8R8G8B8:
return 8;
case sw::FORMAT_A1R5G5B5:
case sw::FORMAT_R5G6B5:
return 5;
default:
return 0;
}
}
unsigned int GetDepthSize(sw::Format depthFormat)
{
switch(depthFormat)
{
// case sw::FORMAT_D16_LOCKABLE: return 16;
case sw::FORMAT_D32: return 32;
// case sw::FORMAT_D15S1: return 15;
case sw::FORMAT_D24S8: return 24;
case sw::FORMAT_D24X8: return 24;
// case sw::FORMAT_D24X4S4: return 24;
case sw::FORMAT_D16: return 16;
case sw::FORMAT_D32F_LOCKABLE: return 32;
case sw::FORMAT_D24FS8: return 24;
// case sw::FORMAT_D32_LOCKABLE: return 32;
// case sw::FORMAT_S8_LOCKABLE: return 0;
case sw::FORMAT_D32FS8_TEXTURE: return 32;
default: return 0;
}
}
GLenum ConvertBackBufferFormat(sw::Format format)
{
switch(format)
{
case sw::FORMAT_A4R4G4B4: return GL_RGBA4;
case sw::FORMAT_A8R8G8B8: return GL_RGBA8_EXT;
case sw::FORMAT_A1R5G5B5: return GL_RGB5_A1;
case sw::FORMAT_R5G6B5: return GL_RGB565;
case sw::FORMAT_X8R8G8B8: return GL_RGB8_EXT;
default:
UNREACHABLE(format);
}
return GL_RGBA4;
}
GLenum ConvertDepthStencilFormat(sw::Format format)
{
switch(format)
{
case sw::FORMAT_D16:
return GL_DEPTH_COMPONENT16;
case sw::FORMAT_D32:
return GL_DEPTH_COMPONENT32;
case sw::FORMAT_D24X8:
return GL_DEPTH_COMPONENT24;
case sw::FORMAT_D24S8:
return GL_DEPTH24_STENCIL8_EXT;
default:
UNREACHABLE(format);
}
return GL_DEPTH24_STENCIL8_EXT;
}
}
| 10,202 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.