max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
|---|---|---|
56,632
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2021 Intel Corporation
#ifndef OPENCV_GAPI_PYTHON_API_HPP
#define OPENCV_GAPI_PYTHON_API_HPP
#include <opencv2/gapi/gkernel.hpp> // GKernelPackage
#include <opencv2/gapi/own/exports.hpp> // GAPI_EXPORTS
namespace cv {
namespace gapi {
/**
* @brief This namespace contains G-API Python backend functions,
* structures, and symbols.
*
* This functionality is required to enable G-API custom operations
* and kernels when using G-API from Python, no need to use it in the
* C++ form.
*/
namespace python {
GAPI_EXPORTS cv::gapi::GBackend backend();
struct GPythonContext
{
const cv::GArgs &ins;
const cv::GMetaArgs &in_metas;
const cv::GTypesInfo &out_info;
};
using Impl = std::function<cv::GRunArgs(const GPythonContext&)>;
class GAPI_EXPORTS GPythonKernel
{
public:
GPythonKernel() = default;
GPythonKernel(Impl run);
cv::GRunArgs operator()(const GPythonContext& ctx);
private:
Impl m_run;
};
class GAPI_EXPORTS GPythonFunctor : public cv::gapi::GFunctor
{
public:
using Meta = cv::GKernel::M;
GPythonFunctor(const char* id, const Meta &meta, const Impl& impl);
GKernelImpl impl() const override;
gapi::GBackend backend() const override;
private:
GKernelImpl impl_;
};
} // namespace python
} // namespace gapi
} // namespace cv
#endif // OPENCV_GAPI_PYTHON_API_HPP
| 576
|
4,047
|
#!/usr/bin/env python3
from storer import Storer
s = Storer()
if s.get_value() != 0:
raise SystemExit('Initial value incorrect.')
s.set_value(42)
if s.get_value() != 42:
raise SystemExit('Setting value failed.')
try:
s.set_value('not a number')
raise SystemExit('Using wrong argument type did not fail.')
except TypeError:
pass
| 130
|
1,424
|
import datetime
import nose.tools
import rdflib
from rdflib.plugins.sparql import operators
from rdflib.plugins.sparql import sparql
def test_date_cast():
now = datetime.datetime.now()
today = now.date()
literal = rdflib.Literal(now)
result = operators.date(literal)
assert isinstance(result, datetime.date)
assert result == today
literal = rdflib.Literal(today)
result = operators.date(literal)
assert isinstance(result, datetime.date)
assert result == today
def test_datetime_cast():
now = datetime.datetime.now()
literal = rdflib.Literal(now)
result = operators.datetime(literal)
assert isinstance(result, datetime.datetime)
assert result == now
@nose.tools.raises(sparql.SPARQLError)
def test_datetime_cast_type_error():
literal = rdflib.Literal("2020-01-02")
operators.date(literal)
| 331
|
372
|
#define LSH_TIME_HOST 1970
#define LSH_DEFAULT_TICKET_LIFE 1971
| 27
|
2,151
|
<reponame>fugu-helper/android_external_swiftshader
//===-- PTXBaseInfo.h - Top level definitions for PTX -------- --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains small standalone helper functions and enum definitions for
// the PTX target useful for the compiler back-end and the MC libraries.
// As such, it deliberately does not include references to LLVM core
// code gen types, passes, etc..
//
//===----------------------------------------------------------------------===//
#ifndef PTXBASEINFO_H
#define PTXBASEINFO_H
#include "PTXMCTargetDesc.h"
namespace llvm {
namespace PTXStateSpace {
enum {
Global = 0, // default to global state space
Constant = 1,
Local = 2,
Parameter = 3,
Shared = 4
};
} // namespace PTXStateSpace
namespace PTXPredicate {
enum {
Normal = 0,
Negate = 1,
None = 2
};
} // namespace PTXPredicate
/// Namespace to hold all target-specific flags.
namespace PTXRoundingMode {
// Instruction Flags
enum {
// Rounding Mode Flags
RndMask = 15,
RndDefault = 0, // ---
RndNone = 1, // <NONE>
RndNearestEven = 2, // .rn
RndTowardsZero = 3, // .rz
RndNegInf = 4, // .rm
RndPosInf = 5, // .rp
RndApprox = 6, // .approx
RndNearestEvenInt = 7, // .rni
RndTowardsZeroInt = 8, // .rzi
RndNegInfInt = 9, // .rmi
RndPosInfInt = 10 // .rpi
};
} // namespace PTXII
} // namespace llvm
#endif
| 754
|
1,207
|
package android.marshon.likequanmintv.librarys.mvpbase;
import android.marshon.likequanmintv.base.APP;
import android.marshon.likequanmintv.librarys.utils.LogUtil;
import android.marshon.likequanmintv.librarys.utils.NetUtil;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
/**
* Created by It.Marshon on 2016/11/21 0021 13:10
*/
public class BaseInteractor {
protected Gson mGson=new Gson();
//检测网络转改
protected boolean hasNetWork(){
if (!NetUtil.isNetWorkConnectted()){
Toast.makeText(APP.getContext(), "请连接网络或稍后重试...", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
protected void exceptionHandler(Throwable e){
LogUtil.e("error!!:"+e.toString());
}
public <T> List<T> convertList(String jsonStr) {
Type token =new TypeToken<List<T>>(){}.getType();
return mGson.fromJson(jsonStr,token);
}
}
| 455
|
956
|
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2020 Inspur Corporation
*/
#include "gso_common.h"
#include "gso_tunnel_udp4.h"
#define IPV4_HDR_MF_BIT (1U << 13)
static void
update_tunnel_ipv4_udp_headers(struct rte_mbuf *pkt, struct rte_mbuf **segs,
uint16_t nb_segs)
{
struct rte_ipv4_hdr *ipv4_hdr;
uint16_t outer_id, inner_id, tail_idx, i, length;
uint16_t outer_ipv4_offset, inner_ipv4_offset;
uint16_t outer_udp_offset;
uint16_t frag_offset = 0, is_mf;
outer_ipv4_offset = pkt->outer_l2_len;
outer_udp_offset = outer_ipv4_offset + pkt->outer_l3_len;
inner_ipv4_offset = outer_udp_offset + pkt->l2_len;
/* Outer IPv4 header. */
ipv4_hdr = (struct rte_ipv4_hdr *)(rte_pktmbuf_mtod(pkt, char *) +
outer_ipv4_offset);
outer_id = rte_be_to_cpu_16(ipv4_hdr->packet_id);
/* Inner IPv4 header. */
ipv4_hdr = (struct rte_ipv4_hdr *)(rte_pktmbuf_mtod(pkt, char *) +
inner_ipv4_offset);
inner_id = rte_be_to_cpu_16(ipv4_hdr->packet_id);
tail_idx = nb_segs - 1;
for (i = 0; i < nb_segs; i++) {
update_ipv4_header(segs[i], outer_ipv4_offset, outer_id);
update_udp_header(segs[i], outer_udp_offset);
update_ipv4_header(segs[i], inner_ipv4_offset, inner_id);
/* For the case inner packet is UDP, we must keep UDP
* datagram boundary, it must be handled as IP fragment.
*
* Set IP fragment offset for inner IP header.
*/
ipv4_hdr = (struct rte_ipv4_hdr *)
(rte_pktmbuf_mtod(segs[i], char *) +
inner_ipv4_offset);
is_mf = i < tail_idx ? IPV4_HDR_MF_BIT : 0;
ipv4_hdr->fragment_offset =
rte_cpu_to_be_16(frag_offset | is_mf);
length = segs[i]->pkt_len - inner_ipv4_offset - pkt->l3_len;
frag_offset += (length >> 3);
outer_id++;
}
}
int
gso_tunnel_udp4_segment(struct rte_mbuf *pkt,
uint16_t gso_size,
struct rte_mempool *direct_pool,
struct rte_mempool *indirect_pool,
struct rte_mbuf **pkts_out,
uint16_t nb_pkts_out)
{
struct rte_ipv4_hdr *inner_ipv4_hdr;
uint16_t pyld_unit_size, hdr_offset, frag_off;
int ret;
hdr_offset = pkt->outer_l2_len + pkt->outer_l3_len + pkt->l2_len;
inner_ipv4_hdr = (struct rte_ipv4_hdr *)(rte_pktmbuf_mtod(pkt, char *) +
hdr_offset);
/*
* Don't process the packet whose MF bit or offset in the inner
* IPv4 header are non-zero.
*/
frag_off = rte_be_to_cpu_16(inner_ipv4_hdr->fragment_offset);
if (unlikely(IS_FRAGMENTED(frag_off)))
return 0;
hdr_offset += pkt->l3_len;
/* Don't process the packet without data */
if ((hdr_offset + pkt->l4_len) >= pkt->pkt_len)
return 0;
/* pyld_unit_size must be a multiple of 8 because frag_off
* uses 8 bytes as unit.
*/
pyld_unit_size = (gso_size - hdr_offset) & ~7U;
/* Segment the payload */
ret = gso_do_segment(pkt, hdr_offset, pyld_unit_size, direct_pool,
indirect_pool, pkts_out, nb_pkts_out);
if (ret > 1)
update_tunnel_ipv4_udp_headers(pkt, pkts_out, ret);
return ret;
}
| 1,380
|
329
|
import pytest
from rest_framework.authtoken.models import Token
from rest_registration.auth_token_managers import RestFrameworkAuthTokenManager
from rest_registration.exceptions import AuthTokenError
@pytest.fixture()
def auth_token_manager():
return RestFrameworkAuthTokenManager()
def test_when_token_created_then_revoke_token_succeeds(
user, user_token_obj, auth_token_manager):
auth_token_manager.revoke_token(user)
assert_token_keys_equals(user, [])
def test_when_no_token_then_revoke_token_fails(
user, auth_token_manager):
with pytest.raises(AuthTokenError):
auth_token_manager.revoke_token(user)
assert_token_keys_equals(user, [])
def test_when_token_created_then_revoke_token_fails_with_another_token(
user, user_token_obj, auth_token_manager):
token_key = user_token_obj.key
another_token_key = token_key + 'x'
with pytest.raises(AuthTokenError):
auth_token_manager.revoke_token(user, token=another_token_key)
assert_token_keys_equals(user, [token_key])
def assert_token_keys_equals(user, expected_token_keys):
assert [
t.key for t in Token.objects.filter(user=user)
] == expected_token_keys
| 454
|
2,338
|
<filename>compiler-rt/lib/dfsan/dfsan_flags.h
//===-- dfsan_flags.h -------------------------------------------*- 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
//
//===----------------------------------------------------------------------===//
//
// This file is a part of DataFlowSanitizer.
//
// DFSan flags.
//===----------------------------------------------------------------------===//
#ifndef DFSAN_FLAGS_H
#define DFSAN_FLAGS_H
namespace __dfsan {
struct Flags {
#define DFSAN_FLAG(Type, Name, DefaultValue, Description) Type Name;
#include "dfsan_flags.inc"
#undef DFSAN_FLAG
void SetDefaults();
};
extern Flags flags_data;
inline Flags &flags() { return flags_data; }
} // namespace __dfsan
#endif // DFSAN_FLAGS_H
| 281
|
404
|
# Python Tools for Visual Studio
# Copyright(c) Microsoft Corporation
# 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
#
# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
# IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
# MERCHANTABILITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
from __future__ import absolute_import, print_function
"""Automatically selects REPL support for Jupyter/IPython"""
__author__ = "<NAME> <<EMAIL>>"
__version__ = "3.2.1.0"
def is_version_at_least(ver_str, *version):
try:
for v1, v2 in zip(version, ver_str.split('.')):
i1, i2 = int(v1), int(v2)
if i1 != i2:
return i1 < i2
except ValueError:
# Versions matched as far as we could go
return True
return True
USE_JUPYTER_CLIENT = False
try:
import jupyter_client
if is_version_at_least(jupyter_client.__version__, 5, 1):
USE_JUPYTER_CLIENT = True
except ImportError:
pass
if USE_JUPYTER_CLIENT:
from .jupyter_client import JupyterClientBackend
IPythonBackend = IPythonBackendWithoutPyLab = JupyterClientBackend
else:
from .ipython_client import IPythonBackend, IPythonBackendWithoutPyLab
| 593
|
409
|
<filename>KITE-Example-Test/src/main/java/org/webrtc/kite/example/pages/GmailSignInPage.java
package org.webrtc.kite.example.pages;
import io.cosmosoftware.kite.exception.KiteInteractionException;
import io.cosmosoftware.kite.interfaces.Runner;
import io.cosmosoftware.kite.pages.BasePage;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import static io.cosmosoftware.kite.entities.Timeouts.THREE_SECOND_INTERVAL;
public class GmailSignInPage extends BasePage {
private final static String GMAIL_PAGE = "https://accounts.google.com/signin/v2/identifier?continue=https%3A%2F%2F" +
"mail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin";
@FindBy(className = "RveJvd snByac")
WebElement confirmButton;
@FindBy(id = "identifierId")
WebElement credentialField;
@FindBy(xpath = "//input[@type='password']")
WebElement passwordField;
public GmailSignInPage(Runner runner) {
super(runner);
}
public void confirmInformation() throws KiteInteractionException {
try {
waitUntilVisibilityOf(confirmButton, THREE_SECOND_INTERVAL);
} catch (Exception e) {
logger.info("No confirmation needed");
return;
}
click(confirmButton);
}
public static String getURL() {
return GMAIL_PAGE;
}
public void inputCredential(String credential) throws KiteInteractionException {
waitUntilVisibilityOf(credentialField, THREE_SECOND_INTERVAL);
sendKeys(credentialField, credential);
}
public void inputPassword(String password) throws KiteInteractionException {
waitUntilVisibilityOf(passwordField, THREE_SECOND_INTERVAL);
sendKeys(passwordField, password);
}
public void open() {
webDriver.get(GMAIL_PAGE);
}
}
| 643
|
645
|
/**
* Copyright 2019 LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.tony;
import com.google.common.annotations.VisibleForTesting;
import com.linkedin.tony.models.JobContainerRequest;
import com.linkedin.tony.util.Utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.client.api.AMRMClient;
import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync;
public class TaskScheduler {
private static final Log LOG = LogFactory.getLog(TaskScheduler.class);
private TonySession session;
private AMRMClientAsync<AMRMClient.ContainerRequest> amRMClient;
private FileSystem resourceFs;
private Configuration tonyConf;
// job with dependency -> (dependent job name, number of instances for that job)
private Map<JobContainerRequest, Map<String, Integer>> taskDependencyMap = new HashMap<>();
private Map<String, LocalResource> localResources;
private Map<String, List<AMRMClient.ContainerRequest>> jobTypeToContainerRequestsMap = new HashMap<>();
private Map<String, Map<String, LocalResource>> jobTypeToContainerResources;
boolean dependencyCheckPassed = true;
public TaskScheduler(TonySession session, AMRMClientAsync<AMRMClient.ContainerRequest> amRMClient, Map<String, LocalResource> localResources,
FileSystem resourceFs, Configuration tonyConf, Map<String, Map<String, LocalResource>> jobTypeToContainerResources) {
this.session = session;
this.amRMClient = amRMClient;
this.localResources = localResources;
this.resourceFs = resourceFs;
this.tonyConf = tonyConf;
this.jobTypeToContainerResources = jobTypeToContainerResources;
}
public void scheduleTasks() {
final List<JobContainerRequest> requests = session.getContainersRequests();
if (!isDAG(requests)) {
LOG.error("TonY execution graph does not form a DAG, exiting.");
session.setFinalStatus(FinalApplicationStatus.FAILED, "App failed due to it not being a DAG.");
dependencyCheckPassed = false;
return;
}
buildTaskDependencyGraph(requests);
// start/schedule jobs that have no dependency requirements
for (JobContainerRequest request : requests) {
if (checkDependencySatisfied(request)) {
scheduleJob(request);
}
}
}
private void buildTaskDependencyGraph(List<JobContainerRequest> requests) {
for (JobContainerRequest request : requests) {
for (String dependsOn : request.getDependsOn()) {
if (!dependsOn.isEmpty()) {
taskDependencyMap.putIfAbsent(request, new HashMap<>());
Map<String, Integer> dependenciesForTask = taskDependencyMap.get(request);
dependenciesForTask.put(dependsOn, session.getContainerRequestForType(dependsOn).getNumInstances());
taskDependencyMap.put(request, dependenciesForTask);
}
}
}
}
@VisibleForTesting
boolean checkDependencySatisfied(JobContainerRequest request) {
return taskDependencyMap.get(request) == null || taskDependencyMap.get(request).isEmpty();
}
private void scheduleJob(JobContainerRequest request) {
AMRMClient.ContainerRequest containerAsk = Utils.setupContainerRequestForRM(request);
String jobName = request.getJobName();
if (!jobTypeToContainerRequestsMap.containsKey(jobName)) {
jobTypeToContainerRequestsMap.put(jobName, new ArrayList<>());
jobTypeToContainerResources.put(jobName, getContainerResources(jobName));
}
jobTypeToContainerRequestsMap.get(request.getJobName()).add(containerAsk);
for (int i = 0; i < request.getNumInstances(); i++) {
amRMClient.addContainerRequest(containerAsk);
}
session.addNumExpectedTask(request.getNumInstances());
}
private Map<String, LocalResource> getContainerResources(String jobName) {
Map<String, LocalResource> containerResources = new ConcurrentHashMap<>(localResources);
String[] resources = tonyConf.getStrings(TonyConfigurationKeys.getResourcesKey(jobName));
Utils.addResources(resources, containerResources, tonyConf);
// All resources available to all containers
resources = tonyConf.getStrings(TonyConfigurationKeys.getContainerResourcesKey());
Utils.addResources(resources, containerResources, tonyConf);
return containerResources;
}
synchronized void registerDependencyCompleted(String jobName) {
taskDependencyMap.forEach((k, v) -> {
if (v.containsKey(jobName)) {
int numContainersLeft = v.get(jobName);
numContainersLeft--;
if (numContainersLeft == 0) {
v.remove(jobName);
} else {
v.put(jobName, numContainersLeft);
}
}
});
Iterator<JobContainerRequest> waitingRequestItr = taskDependencyMap.keySet().iterator();
while (waitingRequestItr.hasNext()) {
JobContainerRequest waitingRequest = waitingRequestItr.next();
if (checkDependencySatisfied((waitingRequest))) {
waitingRequestItr.remove();
scheduleJob(waitingRequest);
}
}
}
static boolean isDAG(final List<JobContainerRequest> containersRequests) {
Set<JobContainerRequest> visited = new HashSet<>();
for (JobContainerRequest containerRequest : containersRequests) {
if (!visited.contains(containerRequest) && !isSubgraphDAG(containerRequest, new ArrayList<>(), containersRequests, visited)) {
return false;
}
}
return true;
}
static boolean isSubgraphDAG(JobContainerRequest node, List<JobContainerRequest> pathTrace,
final List<JobContainerRequest> containerRequests, Set<JobContainerRequest> visited) {
if (pathTrace.contains(node)) {
return false;
}
if (visited.contains(node)) {
return true;
}
pathTrace.add(node);
visited.add(node);
List<JobContainerRequest> dependencies = containerRequests.stream()
.filter(x -> node.getDependsOn().contains(x.getJobName()))
.collect(Collectors.toList());
for (JobContainerRequest dependency : dependencies) {
if (!isSubgraphDAG(dependency, pathTrace, containerRequests, visited)) {
return false;
}
}
pathTrace.remove(node);
return true;
}
}
| 2,256
|
348
|
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Bischheim","circ":"3ème circonscription","dpt":"Bas-Rhin","inscrits":9659,"abs":5647,"votants":4012,"blancs":35,"nuls":21,"exp":3956,"res":[{"nuance":"REM","nom":"<NAME>","voix":1343},{"nuance":"LR","nom":"<NAME>","voix":575},{"nuance":"FI","nom":"Mme <NAME>","voix":538},{"nuance":"FN","nom":"Mme <NAME>","voix":510},{"nuance":"REG","nom":"Mme <NAME>","voix":250},{"nuance":"ECO","nom":"Mme <NAME>","voix":233},{"nuance":"SOC","nom":"M. <NAME>","voix":212},{"nuance":"DIV","nom":"Mme <NAME>","voix":67},{"nuance":"COM","nom":"M. <NAME>","voix":48},{"nuance":"DIV","nom":"<NAME>","voix":47},{"nuance":"DLF","nom":"Mme <NAME>","voix":38},{"nuance":"EXD","nom":"M. <NAME>","voix":35},{"nuance":"DIV","nom":"Mme <NAME>","voix":31},{"nuance":"EXG","nom":"Mme <NAME>","voix":26},{"nuance":"DIV","nom":"M. <NAME>","voix":3}]}
| 351
|
649
|
package net.serenitybdd.screenplay.waits;
import net.serenitybdd.screenplay.Question;
import org.hamcrest.Matcher;
import java.util.concurrent.Callable;
public class Wait {
public static WaitWithTimeout until(Question question, Matcher matcher) {
return new WaitOnQuestion(question, matcher);
}
public static WaitWithTimeout until(Callable<Boolean> expectedState) {
return new WaitOnSupplier(expectedState);
}
}
| 153
|
13,006
|
<reponame>mjlorenzo305/deeplearning4j
/*******************************************************************************
* Copyright (c) 2015-2019 Skymind, Inc.
* Copyright (c) 2020 <NAME>.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.rl4j.learning.sync.qlearning;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.deeplearning4j.rl4j.learning.configuration.QLearningConfiguration;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class QLearningConfigurationTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void serialize() throws Exception {
ObjectMapper mapper = new ObjectMapper();
QLearningConfiguration qLearningConfiguration = QLearningConfiguration.builder()
.build();
// Should not throw..
String json = mapper.writeValueAsString(qLearningConfiguration);
QLearningConfiguration cnf = mapper.readValue(json, QLearningConfiguration.class);
}
}
| 467
|
986
|
<reponame>exNTLDR/audacity
/*
** Copyright (C) 1999-2019 <NAME> <<EMAIL>>
**
** 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 author nor the names of any 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sndfile.h>
#include "common.h"
typedef struct
{ char *infilename, *outfilename ;
SF_INFO infileinfo, outfileinfo ;
} OptionData ;
static void copy_metadata (SNDFILE *outfile, SNDFILE *infile, int channels) ;
static void
usage_exit (const char *progname)
{
printf ("\nUsage : %s [options] [encoding] <input file> <output file>\n", progname) ;
puts ("\n"
" where [option] may be:\n\n"
" -override-sample-rate=X : force sample rate of input to X\n"
" -endian=little : force output file to little endian data\n"
" -endian=big : force output file to big endian data\n"
" -endian=cpu : force output file same endian-ness as the CPU\n"
" -normalize : normalize the data in the output file\n"
) ;
puts (
" where [encoding] may be one of the following:\n\n"
" -pcms8 : signed 8 bit pcm\n"
" -pcmu8 : unsigned 8 bit pcm\n"
" -pcm16 : 16 bit pcm\n"
" -pcm24 : 24 bit pcm\n"
" -pcm32 : 32 bit pcm\n"
" -float32 : 32 bit floating point\n"
" -float64 : 64 bit floating point\n"
" -ulaw : ULAW\n"
" -alaw : ALAW\n"
" -alac16 : 16 bit ALAC (CAF only)\n"
" -alac20 : 20 bit ALAC (CAF only)\n"
" -alac24 : 24 bit ALAC (CAF only)\n"
" -alac32 : 32 bit ALAC (CAF only)\n"
" -ima-adpcm : IMA ADPCM (WAV only)\n"
" -ms-adpcm : MS ADPCM (WAV only)\n"
" -gsm610 : GSM6.10 (WAV only)\n"
" -dwvw12 : 12 bit DWVW (AIFF only)\n"
" -dwvw16 : 16 bit DWVW (AIFF only)\n"
" -dwvw24 : 24 bit DWVW (AIFF only)\n"
" -vorbis : Vorbis (OGG only)\n"
" -opus : Opus (OGG only)\n"
) ;
puts (
" If no encoding is specified, the program will try to use the encoding\n"
" of the input file in the output file. This will not always work as\n"
" most container formats (eg WAV, AIFF etc) only support a small subset\n"
" of codec formats (eg 16 bit PCM, a-law, Vorbis etc).\n"
) ;
puts (
" The format of the output file is determined by the file extension of the\n"
" output file name. The following extensions are currently understood:\n"
) ;
sfe_dump_format_map () ;
puts ("") ;
exit (1) ;
} /* usage_exit */
static void
report_format_error_exit (const char * argv0, SF_INFO * sfinfo)
{ int old_format = sfinfo->format ;
int endian = sfinfo->format & SF_FORMAT_ENDMASK ;
int channels = sfinfo->channels ;
sfinfo->format = old_format & (SF_FORMAT_TYPEMASK | SF_FORMAT_SUBMASK) ;
if (endian && sf_format_check (sfinfo))
{ printf ("Error : output file format does not support %s endian-ness.\n", sfe_endian_name (endian)) ;
exit (1) ;
} ;
sfinfo->channels = 1 ;
if (sf_format_check (sfinfo))
{ printf ("Error : output file format does not support %d channels.\n", channels) ;
exit (1) ;
} ;
printf ("\n"
"Error : output file format is invalid.\n"
"The '%s' container does not support '%s' codec data.\n"
"Run '%s --help' for clues.\n\n",
sfe_container_name (sfinfo->format), sfe_codec_name (sfinfo->format), program_name (argv0)) ;
exit (1) ;
} /* report_format_error_exit */
int
main (int argc, char * argv [])
{ const char *progname, *infilename, *outfilename ;
SNDFILE *infile = NULL, *outfile = NULL ;
SF_INFO sfinfo ;
int k, outfilemajor, outfileminor = 0, infileminor ;
int override_sample_rate = 0 ; /* assume no sample rate override. */
int endian = SF_ENDIAN_FILE, normalize = SF_FALSE ;
progname = program_name (argv [0]) ;
if (argc < 3 || argc > 5)
usage_exit (progname) ;
infilename = argv [argc-2] ;
outfilename = argv [argc-1] ;
if (strcmp (infilename, outfilename) == 0)
{ printf ("Error : Input and output filenames are the same.\n\n") ;
usage_exit (progname) ;
} ;
if (strlen (infilename) > 1 && infilename [0] == '-')
{ printf ("Error : Input filename (%s) looks like an option.\n\n", infilename) ;
usage_exit (progname) ;
} ;
if (outfilename [0] == '-')
{ printf ("Error : Output filename (%s) looks like an option.\n\n", outfilename) ;
usage_exit (progname) ;
} ;
for (k = 1 ; k < argc - 2 ; k++)
{ if (! strcmp (argv [k], "-pcms8"))
{ outfileminor = SF_FORMAT_PCM_S8 ;
continue ;
} ;
if (! strcmp (argv [k], "-pcmu8"))
{ outfileminor = SF_FORMAT_PCM_U8 ;
continue ;
} ;
if (! strcmp (argv [k], "-pcm16"))
{ outfileminor = SF_FORMAT_PCM_16 ;
continue ;
} ;
if (! strcmp (argv [k], "-pcm24"))
{ outfileminor = SF_FORMAT_PCM_24 ;
continue ;
} ;
if (! strcmp (argv [k], "-pcm32"))
{ outfileminor = SF_FORMAT_PCM_32 ;
continue ;
} ;
if (! strcmp (argv [k], "-float32"))
{ outfileminor = SF_FORMAT_FLOAT ;
continue ;
} ;
if (! strcmp (argv [k], "-float64"))
{ outfileminor = SF_FORMAT_DOUBLE ;
continue ;
} ;
if (! strcmp (argv [k], "-ulaw"))
{ outfileminor = SF_FORMAT_ULAW ;
continue ;
} ;
if (! strcmp (argv [k], "-alaw"))
{ outfileminor = SF_FORMAT_ALAW ;
continue ;
} ;
if (! strcmp (argv [k], "-alac16"))
{ outfileminor = SF_FORMAT_ALAC_16 ;
continue ;
} ;
if (! strcmp (argv [k], "-alac20"))
{ outfileminor = SF_FORMAT_ALAC_20 ;
continue ;
} ;
if (! strcmp (argv [k], "-alac24"))
{ outfileminor = SF_FORMAT_ALAC_24 ;
continue ;
} ;
if (! strcmp (argv [k], "-alac32"))
{ outfileminor = SF_FORMAT_ALAC_32 ;
continue ;
} ;
if (! strcmp (argv [k], "-ima-adpcm"))
{ outfileminor = SF_FORMAT_IMA_ADPCM ;
continue ;
} ;
if (! strcmp (argv [k], "-ms-adpcm"))
{ outfileminor = SF_FORMAT_MS_ADPCM ;
continue ;
} ;
if (! strcmp (argv [k], "-gsm610"))
{ outfileminor = SF_FORMAT_GSM610 ;
continue ;
} ;
if (! strcmp (argv [k], "-dwvw12"))
{ outfileminor = SF_FORMAT_DWVW_12 ;
continue ;
} ;
if (! strcmp (argv [k], "-dwvw16"))
{ outfileminor = SF_FORMAT_DWVW_16 ;
continue ;
} ;
if (! strcmp (argv [k], "-dwvw24"))
{ outfileminor = SF_FORMAT_DWVW_24 ;
continue ;
} ;
if (! strcmp (argv [k], "-vorbis"))
{ outfileminor = SF_FORMAT_VORBIS ;
continue ;
} ;
if (! strcmp (argv [k], "-opus"))
{ outfileminor = SF_FORMAT_OPUS ;
continue ;
} ;
if (strstr (argv [k], "-override-sample-rate=") == argv [k])
{ const char *ptr ;
ptr = argv [k] + strlen ("-override-sample-rate=") ;
override_sample_rate = atoi (ptr) ;
continue ;
} ;
if (! strcmp (argv [k], "-endian=little"))
{ endian = SF_ENDIAN_LITTLE ;
continue ;
} ;
if (! strcmp (argv [k], "-endian=big"))
{ endian = SF_ENDIAN_BIG ;
continue ;
} ;
if (! strcmp (argv [k], "-endian=cpu"))
{ endian = SF_ENDIAN_CPU ;
continue ;
} ;
if (! strcmp (argv [k], "-endian=file"))
{ endian = SF_ENDIAN_FILE ;
continue ;
} ;
if (! strcmp (argv [k], "-normalize"))
{ normalize = SF_TRUE ;
continue ;
} ;
printf ("Error : Not able to decode argunment '%s'.\n", argv [k]) ;
exit (1) ;
} ;
memset (&sfinfo, 0, sizeof (sfinfo)) ;
if ((infile = sf_open (infilename, SFM_READ, &sfinfo)) == NULL)
{ printf ("Not able to open input file %s.\n", infilename) ;
puts (sf_strerror (NULL)) ;
return 1 ;
} ;
/* Update sample rate if forced to something else. */
if (override_sample_rate)
sfinfo.samplerate = override_sample_rate ;
infileminor = sfinfo.format & SF_FORMAT_SUBMASK ;
if ((sfinfo.format = sfe_file_type_of_ext (outfilename, sfinfo.format)) == 0)
{ printf ("Error : Not able to determine output file type for %s.\n", outfilename) ;
return 1 ;
} ;
outfilemajor = sfinfo.format & (SF_FORMAT_TYPEMASK | SF_FORMAT_ENDMASK) ;
if (outfileminor == 0)
outfileminor = sfinfo.format & SF_FORMAT_SUBMASK ;
if (outfileminor != 0)
sfinfo.format = outfilemajor | outfileminor ;
else
sfinfo.format = outfilemajor | (sfinfo.format & SF_FORMAT_SUBMASK) ;
sfinfo.format |= endian ;
if ((sfinfo.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_XI)
switch (sfinfo.format & SF_FORMAT_SUBMASK)
{ case SF_FORMAT_PCM_16 :
sfinfo.format = outfilemajor | SF_FORMAT_DPCM_16 ;
break ;
case SF_FORMAT_PCM_S8 :
case SF_FORMAT_PCM_U8 :
sfinfo.format = outfilemajor | SF_FORMAT_DPCM_8 ;
break ;
} ;
if (sf_format_check (&sfinfo) == 0)
{ sf_close (infile) ;
report_format_error_exit (argv [0], &sfinfo) ;
} ;
if ((sfinfo.format & SF_FORMAT_SUBMASK) == SF_FORMAT_GSM610 && sfinfo.samplerate != 8000)
{ printf (
"WARNING: GSM 6.10 data format only supports 8kHz sample rate. The converted\n"
"ouput file will contain the input data converted to the GSM 6.10 data format\n"
"but not re-sampled.\n"
) ;
} ;
/* Open the output file. */
if ((outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)) == NULL)
{ printf ("Not able to open output file %s : %s\n", outfilename, sf_strerror (NULL)) ;
return 1 ;
} ;
/* Copy the metadata */
copy_metadata (outfile, infile, sfinfo.channels) ;
if (normalize
|| (outfileminor == SF_FORMAT_DOUBLE) || (outfileminor == SF_FORMAT_FLOAT)
|| (infileminor == SF_FORMAT_DOUBLE) || (infileminor == SF_FORMAT_FLOAT)
|| (infileminor == SF_FORMAT_OPUS) || (outfileminor == SF_FORMAT_OPUS)
|| (infileminor == SF_FORMAT_VORBIS) || (outfileminor == SF_FORMAT_VORBIS))
sfe_copy_data_fp (outfile, infile, sfinfo.channels, normalize) ;
else
sfe_copy_data_int (outfile, infile, sfinfo.channels) ;
sf_close (infile) ;
sf_close (outfile) ;
return 0 ;
} /* main */
static void
copy_metadata (SNDFILE *outfile, SNDFILE *infile, int channels)
{ SF_INSTRUMENT inst ;
SF_CUES cues ;
SF_BROADCAST_INFO_2K binfo ;
const char *str ;
int k, chanmap [256] ;
for (k = SF_STR_FIRST ; k <= SF_STR_LAST ; k++)
{ str = sf_get_string (infile, k) ;
if (str != NULL)
sf_set_string (outfile, k, str) ;
} ;
memset (&inst, 0, sizeof (inst)) ;
memset (&cues, 0, sizeof (cues)) ;
memset (&binfo, 0, sizeof (binfo)) ;
if (channels < ARRAY_LEN (chanmap))
{ size_t size = channels * sizeof (chanmap [0]) ;
if (sf_command (infile, SFC_GET_CHANNEL_MAP_INFO, chanmap, size) == SF_TRUE)
sf_command (outfile, SFC_SET_CHANNEL_MAP_INFO, chanmap, size) ;
} ;
if (sf_command (infile, SFC_GET_CUE, &cues, sizeof (cues)) == SF_TRUE)
sf_command (outfile, SFC_SET_CUE, &cues, sizeof (cues)) ;
if (sf_command (infile, SFC_GET_INSTRUMENT, &inst, sizeof (inst)) == SF_TRUE)
sf_command (outfile, SFC_SET_INSTRUMENT, &inst, sizeof (inst)) ;
if (sf_command (infile, SFC_GET_BROADCAST_INFO, &binfo, sizeof (binfo)) == SF_TRUE)
sf_command (outfile, SFC_SET_BROADCAST_INFO, &binfo, sizeof (binfo)) ;
} /* copy_metadata */
| 5,455
|
1,007
|
##
# Exploit Title: Doubble OpenNamespace Denial of Service
# Date: 12/28/2020
# Exploit Author: <NAME>
# CVE : CVE-2020-5801
# Advisory: https://www.tenable.com/security/research/tra-2020-71
##
import sys, socket, argparse, struct
import re, random, hexdump
def block(data, pad=False):
dlen = len(data)
if (pad and dlen % 4):
data += b'\x00' * (4 - dlen % 4)
return struct.pack('<L', len(data)) + data
def rna_msg(hdr, data):
header = ''
for k, v in sorted(hdr.items()):
if v is None: v = ''
header += '{}={}\x00'.format(k, v)
msg = b'rna\xF2' + block(header.encode(), True) + block(data)
return msg
def dump(title, data):
print('[--- %s ---]' % (title))
hexdump.hexdump(data)
# MAIN
#
descr = 'This script attempts to terminate RSLinxNG.exe.'
parser = argparse.ArgumentParser(description=descr)
parser.add_argument('host', help='Target host')
parser.add_argument('-p', '--port', type=int, default=4241, help='Target port, default: %(default)s')
args = parser.parse_args()
host = args.host
port = args.port
hdr = {}
hdr['command'] = 'XmlCommand'
hdr['transid'] = 1
hdr['session-id'] = None
nspath = 'RNA://$Global/SomeApp/SomeServer';
data = '\r\n<OpenNamespace xmlns="http://FactoryTalk.net/schemas/LiveData/server/2" '
data += 'namespacePath="' + nspath
data += '" leaseTime="300" clientMachineInfo="localhost" securityToken="Token">'
data += '\r\n<requestService>http://FactoryTalk.net/schemas/LiveData/server/NamespaceBrowse/1</requestService>'
data += '\r\n<requestService>http://FactoryTalk.net/schemas/LiveData/server/Configuration/1</requestService></OpenNamespace>\x00'
data = data.encode()
open_namespace = rna_msg(hdr, data)
#dump('OpenNamespace', open_namespace)
for i in range(200):
print('Making connection %04d...' % (i + 1))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((host, port))
print('Sending attack packets...')
try:
s.sendall(open_namespace)
res = s.recv(4096)
#dump('OpenNampespaceResponse', res)
m = re.match(b'rna\xF2.*session-id=(\d+).*', res, re.DOTALL)
if m is None:
s.close()
sys.exit('Failed to get a sessiond id.')
# Send second OpenNamespace with session-id in it
sid = int(m.group(1))
hdr['transid'] = 2
hdr['session-id'] = sid
open_namespace2 = rna_msg(hdr, data)
#dump('OpenNamespace', open_namespace2)
s.sendall(open_namespace2)
s.recv(4096)
except:
pass
s.close()
| 1,000
|
1,931
|
<filename>tests/test_visitors/test_ast/test_statements/test_parameters_indentation/test_call_indentation.py
import pytest
from wemake_python_styleguide.visitors.ast.statements import (
ParametersIndentationViolation,
WrongParametersIndentationVisitor,
)
# Correct:
correct_single_line_call = 'print(1, 2, 3)'
correct_multi_line_call = """
print(
1,
2,
3,
)
"""
correct_multi_line_call_with_keywords = """
print(
1,
2,
3,
end='',
)
"""
correct_next_line_call = """
print([
1, 2, 3,
])
"""
correct_next_line_call_with_keywords = """
print(
[1, 2, 3],
end='',
)
"""
correct_call_with_multi_line_tuple = """
print((
1,
2,
3,
))
"""
correct_call_with_next_line_parameter = """
print(0, [
1, 2, 3,
])
"""
correct_call_with_multi_line_parameter = """
print(0, [
1,
2,
3,
])
"""
correct_call_all_multi_line = """
print(
0,
[
1,
2,
3,
],
end='',
)
"""
# Wrong:
wrong_call_indentation1 = """
print(1,
2, 3)
"""
wrong_call_indentation2 = """
print(1, 2,
3)
"""
wrong_call_indentation3 = """
print(
1,
2, 3,
)
"""
wrong_call_indentation4 = """
print(
1, 2,
3,
)
"""
wrong_call_indentation5 = """
print(
1,
2,
3, end='',
)
"""
wrong_call_indentation6 = """
print(
1,
2, 3, end='',
)
"""
wrong_call_indentation7 = """
print(0, [
1,
2,
3,
], end='')
"""
@pytest.mark.parametrize('code', [
correct_single_line_call,
correct_multi_line_call,
correct_multi_line_call_with_keywords,
correct_next_line_call,
correct_next_line_call_with_keywords,
correct_call_with_multi_line_tuple,
correct_call_with_next_line_parameter,
correct_call_with_multi_line_parameter,
correct_call_all_multi_line,
])
def test_correct_call_indentation(
assert_errors,
parse_ast_tree,
code,
default_options,
):
"""Testing that correctly indented function calls work."""
tree = parse_ast_tree(code)
visitor = WrongParametersIndentationVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [])
@pytest.mark.parametrize('code', [
wrong_call_indentation1,
wrong_call_indentation2,
wrong_call_indentation3,
wrong_call_indentation4,
wrong_call_indentation5,
wrong_call_indentation6,
wrong_call_indentation7,
])
def test_wrong_call_indentation(
assert_errors,
parse_ast_tree,
code,
default_options,
):
"""Testing that poorly indented function calls do not work."""
tree = parse_ast_tree(code)
visitor = WrongParametersIndentationVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [ParametersIndentationViolation])
| 1,214
|
2,151
|
<reponame>prometheansacrifice/esy-vpx
/*
* Copyright (c) 2017 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <arm_neon.h>
#include "./vpx_config.h"
#include "./vpx_dsp_rtcd.h"
#include "vpx_dsp/txfm_common.h"
#include "vpx_dsp/arm/mem_neon.h"
#include "vpx_dsp/arm/transpose_neon.h"
// Most gcc 4.9 distributions outside of Android do not generate correct code
// for this function.
#if !defined(__clang__) && !defined(__ANDROID__) && defined(__GNUC__) && \
__GNUC__ == 4 && __GNUC_MINOR__ <= 9
void vpx_fdct32x32_neon(const int16_t *input, tran_low_t *output, int stride) {
vpx_fdct32x32_c(input, output, stride);
}
void vpx_fdct32x32_rd_neon(const int16_t *input, tran_low_t *output,
int stride) {
vpx_fdct32x32_rd_c(input, output, stride);
}
#else
#define LOAD_INCREMENT(src, stride, dest, index) \
do { \
dest[index] = vld1q_s16(src); \
src += stride; \
} while (0)
#define ADD_S16(src, index0, index1, dest, index3) \
do { \
dest[index3] = vaddq_s16(src[index0], src[index1]); \
} while (0)
#define ADD_SHIFT_S16(src, index0, index1) \
do { \
src[index1] = vshlq_n_s16(vsubq_s16(src[index0], src[index1]), 2); \
} while (0)
// Load, cross, and multiply by 4. Load the first 8 and last 8, then the
// middle
// 16. Doing sets of 16 at a time. Maybe sets of 8 would be better?
static INLINE void load(const int16_t *a, int stride, int16x8_t *b) {
const int16_t *a_end = a + 24 * stride;
int16x8_t c[8];
LOAD_INCREMENT(a, stride, b, 0);
LOAD_INCREMENT(a, stride, b, 1);
LOAD_INCREMENT(a, stride, b, 2);
LOAD_INCREMENT(a, stride, b, 3);
LOAD_INCREMENT(a, stride, b, 4);
LOAD_INCREMENT(a, stride, b, 5);
LOAD_INCREMENT(a, stride, b, 6);
LOAD_INCREMENT(a, stride, b, 7);
LOAD_INCREMENT(a_end, stride, b, 24);
LOAD_INCREMENT(a_end, stride, b, 25);
LOAD_INCREMENT(a_end, stride, b, 26);
LOAD_INCREMENT(a_end, stride, b, 27);
LOAD_INCREMENT(a_end, stride, b, 28);
LOAD_INCREMENT(a_end, stride, b, 29);
LOAD_INCREMENT(a_end, stride, b, 30);
LOAD_INCREMENT(a_end, stride, b, 31);
ADD_S16(b, 0, 31, c, 0);
ADD_S16(b, 1, 30, c, 1);
ADD_S16(b, 2, 29, c, 2);
ADD_S16(b, 3, 28, c, 3);
ADD_S16(b, 4, 27, c, 4);
ADD_S16(b, 5, 26, c, 5);
ADD_S16(b, 6, 25, c, 6);
ADD_S16(b, 7, 24, c, 7);
ADD_SHIFT_S16(b, 7, 24);
ADD_SHIFT_S16(b, 6, 25);
ADD_SHIFT_S16(b, 5, 26);
ADD_SHIFT_S16(b, 4, 27);
ADD_SHIFT_S16(b, 3, 28);
ADD_SHIFT_S16(b, 2, 29);
ADD_SHIFT_S16(b, 1, 30);
ADD_SHIFT_S16(b, 0, 31);
b[0] = vshlq_n_s16(c[0], 2);
b[1] = vshlq_n_s16(c[1], 2);
b[2] = vshlq_n_s16(c[2], 2);
b[3] = vshlq_n_s16(c[3], 2);
b[4] = vshlq_n_s16(c[4], 2);
b[5] = vshlq_n_s16(c[5], 2);
b[6] = vshlq_n_s16(c[6], 2);
b[7] = vshlq_n_s16(c[7], 2);
LOAD_INCREMENT(a, stride, b, 8);
LOAD_INCREMENT(a, stride, b, 9);
LOAD_INCREMENT(a, stride, b, 10);
LOAD_INCREMENT(a, stride, b, 11);
LOAD_INCREMENT(a, stride, b, 12);
LOAD_INCREMENT(a, stride, b, 13);
LOAD_INCREMENT(a, stride, b, 14);
LOAD_INCREMENT(a, stride, b, 15);
LOAD_INCREMENT(a, stride, b, 16);
LOAD_INCREMENT(a, stride, b, 17);
LOAD_INCREMENT(a, stride, b, 18);
LOAD_INCREMENT(a, stride, b, 19);
LOAD_INCREMENT(a, stride, b, 20);
LOAD_INCREMENT(a, stride, b, 21);
LOAD_INCREMENT(a, stride, b, 22);
LOAD_INCREMENT(a, stride, b, 23);
ADD_S16(b, 8, 23, c, 0);
ADD_S16(b, 9, 22, c, 1);
ADD_S16(b, 10, 21, c, 2);
ADD_S16(b, 11, 20, c, 3);
ADD_S16(b, 12, 19, c, 4);
ADD_S16(b, 13, 18, c, 5);
ADD_S16(b, 14, 17, c, 6);
ADD_S16(b, 15, 16, c, 7);
ADD_SHIFT_S16(b, 15, 16);
ADD_SHIFT_S16(b, 14, 17);
ADD_SHIFT_S16(b, 13, 18);
ADD_SHIFT_S16(b, 12, 19);
ADD_SHIFT_S16(b, 11, 20);
ADD_SHIFT_S16(b, 10, 21);
ADD_SHIFT_S16(b, 9, 22);
ADD_SHIFT_S16(b, 8, 23);
b[8] = vshlq_n_s16(c[0], 2);
b[9] = vshlq_n_s16(c[1], 2);
b[10] = vshlq_n_s16(c[2], 2);
b[11] = vshlq_n_s16(c[3], 2);
b[12] = vshlq_n_s16(c[4], 2);
b[13] = vshlq_n_s16(c[5], 2);
b[14] = vshlq_n_s16(c[6], 2);
b[15] = vshlq_n_s16(c[7], 2);
}
#undef LOAD_INCREMENT
#undef ADD_S16
#undef ADD_SHIFT_S16
#define STORE_S16(src, index, dest) \
do { \
store_s16q_to_tran_low(dest, src[index]); \
dest += 8; \
} while (0);
// Store 32 16x8 values, assuming stride == 32.
// Slight twist: store horizontally in blocks of 8.
static INLINE void store(tran_low_t *a, const int16x8_t *b) {
STORE_S16(b, 0, a);
STORE_S16(b, 8, a);
STORE_S16(b, 16, a);
STORE_S16(b, 24, a);
STORE_S16(b, 1, a);
STORE_S16(b, 9, a);
STORE_S16(b, 17, a);
STORE_S16(b, 25, a);
STORE_S16(b, 2, a);
STORE_S16(b, 10, a);
STORE_S16(b, 18, a);
STORE_S16(b, 26, a);
STORE_S16(b, 3, a);
STORE_S16(b, 11, a);
STORE_S16(b, 19, a);
STORE_S16(b, 27, a);
STORE_S16(b, 4, a);
STORE_S16(b, 12, a);
STORE_S16(b, 20, a);
STORE_S16(b, 28, a);
STORE_S16(b, 5, a);
STORE_S16(b, 13, a);
STORE_S16(b, 21, a);
STORE_S16(b, 29, a);
STORE_S16(b, 6, a);
STORE_S16(b, 14, a);
STORE_S16(b, 22, a);
STORE_S16(b, 30, a);
STORE_S16(b, 7, a);
STORE_S16(b, 15, a);
STORE_S16(b, 23, a);
STORE_S16(b, 31, a);
}
#undef STORE_S16
// fdct_round_shift((a +/- b) * c)
static INLINE void butterfly_one_coeff(const int16x8_t a, const int16x8_t b,
const tran_high_t constant,
int16x8_t *add, int16x8_t *sub) {
const int32x4_t a0 = vmull_n_s16(vget_low_s16(a), constant);
const int32x4_t a1 = vmull_n_s16(vget_high_s16(a), constant);
const int32x4_t sum0 = vmlal_n_s16(a0, vget_low_s16(b), constant);
const int32x4_t sum1 = vmlal_n_s16(a1, vget_high_s16(b), constant);
const int32x4_t diff0 = vmlsl_n_s16(a0, vget_low_s16(b), constant);
const int32x4_t diff1 = vmlsl_n_s16(a1, vget_high_s16(b), constant);
const int16x4_t rounded0 = vqrshrn_n_s32(sum0, DCT_CONST_BITS);
const int16x4_t rounded1 = vqrshrn_n_s32(sum1, DCT_CONST_BITS);
const int16x4_t rounded2 = vqrshrn_n_s32(diff0, DCT_CONST_BITS);
const int16x4_t rounded3 = vqrshrn_n_s32(diff1, DCT_CONST_BITS);
*add = vcombine_s16(rounded0, rounded1);
*sub = vcombine_s16(rounded2, rounded3);
}
// fdct_round_shift(a * c0 +/- b * c1)
static INLINE void butterfly_two_coeff(const int16x8_t a, const int16x8_t b,
const tran_coef_t constant0,
const tran_coef_t constant1,
int16x8_t *add, int16x8_t *sub) {
const int32x4_t a0 = vmull_n_s16(vget_low_s16(a), constant0);
const int32x4_t a1 = vmull_n_s16(vget_high_s16(a), constant0);
const int32x4_t a2 = vmull_n_s16(vget_low_s16(a), constant1);
const int32x4_t a3 = vmull_n_s16(vget_high_s16(a), constant1);
const int32x4_t sum0 = vmlal_n_s16(a2, vget_low_s16(b), constant0);
const int32x4_t sum1 = vmlal_n_s16(a3, vget_high_s16(b), constant0);
const int32x4_t diff0 = vmlsl_n_s16(a0, vget_low_s16(b), constant1);
const int32x4_t diff1 = vmlsl_n_s16(a1, vget_high_s16(b), constant1);
const int16x4_t rounded0 = vqrshrn_n_s32(sum0, DCT_CONST_BITS);
const int16x4_t rounded1 = vqrshrn_n_s32(sum1, DCT_CONST_BITS);
const int16x4_t rounded2 = vqrshrn_n_s32(diff0, DCT_CONST_BITS);
const int16x4_t rounded3 = vqrshrn_n_s32(diff1, DCT_CONST_BITS);
*add = vcombine_s16(rounded0, rounded1);
*sub = vcombine_s16(rounded2, rounded3);
}
// Add 2 if positive, 1 if negative, and shift by 2.
// In practice, subtract the sign bit, then shift with rounding.
static INLINE int16x8_t sub_round_shift(const int16x8_t a) {
const uint16x8_t a_u16 = vreinterpretq_u16_s16(a);
const uint16x8_t a_sign_u16 = vshrq_n_u16(a_u16, 15);
const int16x8_t a_sign_s16 = vreinterpretq_s16_u16(a_sign_u16);
return vrshrq_n_s16(vsubq_s16(a, a_sign_s16), 2);
}
static void dct_body_first_pass(const int16x8_t *in, int16x8_t *out) {
int16x8_t a[32];
int16x8_t b[32];
// Stage 1: Done as part of the load.
// Stage 2.
// Mini cross. X the first 16 values and the middle 8 of the second half.
a[0] = vaddq_s16(in[0], in[15]);
a[1] = vaddq_s16(in[1], in[14]);
a[2] = vaddq_s16(in[2], in[13]);
a[3] = vaddq_s16(in[3], in[12]);
a[4] = vaddq_s16(in[4], in[11]);
a[5] = vaddq_s16(in[5], in[10]);
a[6] = vaddq_s16(in[6], in[9]);
a[7] = vaddq_s16(in[7], in[8]);
a[8] = vsubq_s16(in[7], in[8]);
a[9] = vsubq_s16(in[6], in[9]);
a[10] = vsubq_s16(in[5], in[10]);
a[11] = vsubq_s16(in[4], in[11]);
a[12] = vsubq_s16(in[3], in[12]);
a[13] = vsubq_s16(in[2], in[13]);
a[14] = vsubq_s16(in[1], in[14]);
a[15] = vsubq_s16(in[0], in[15]);
a[16] = in[16];
a[17] = in[17];
a[18] = in[18];
a[19] = in[19];
butterfly_one_coeff(in[27], in[20], cospi_16_64, &a[27], &a[20]);
butterfly_one_coeff(in[26], in[21], cospi_16_64, &a[26], &a[21]);
butterfly_one_coeff(in[25], in[22], cospi_16_64, &a[25], &a[22]);
butterfly_one_coeff(in[24], in[23], cospi_16_64, &a[24], &a[23]);
a[28] = in[28];
a[29] = in[29];
a[30] = in[30];
a[31] = in[31];
// Stage 3.
b[0] = vaddq_s16(a[0], a[7]);
b[1] = vaddq_s16(a[1], a[6]);
b[2] = vaddq_s16(a[2], a[5]);
b[3] = vaddq_s16(a[3], a[4]);
b[4] = vsubq_s16(a[3], a[4]);
b[5] = vsubq_s16(a[2], a[5]);
b[6] = vsubq_s16(a[1], a[6]);
b[7] = vsubq_s16(a[0], a[7]);
b[8] = a[8];
b[9] = a[9];
butterfly_one_coeff(a[13], a[10], cospi_16_64, &b[13], &b[10]);
butterfly_one_coeff(a[12], a[11], cospi_16_64, &b[12], &b[11]);
b[14] = a[14];
b[15] = a[15];
b[16] = vaddq_s16(in[16], a[23]);
b[17] = vaddq_s16(in[17], a[22]);
b[18] = vaddq_s16(in[18], a[21]);
b[19] = vaddq_s16(in[19], a[20]);
b[20] = vsubq_s16(in[19], a[20]);
b[21] = vsubq_s16(in[18], a[21]);
b[22] = vsubq_s16(in[17], a[22]);
b[23] = vsubq_s16(in[16], a[23]);
b[24] = vsubq_s16(in[31], a[24]);
b[25] = vsubq_s16(in[30], a[25]);
b[26] = vsubq_s16(in[29], a[26]);
b[27] = vsubq_s16(in[28], a[27]);
b[28] = vaddq_s16(in[28], a[27]);
b[29] = vaddq_s16(in[29], a[26]);
b[30] = vaddq_s16(in[30], a[25]);
b[31] = vaddq_s16(in[31], a[24]);
// Stage 4.
a[0] = vaddq_s16(b[0], b[3]);
a[1] = vaddq_s16(b[1], b[2]);
a[2] = vsubq_s16(b[1], b[2]);
a[3] = vsubq_s16(b[0], b[3]);
a[4] = b[4];
butterfly_one_coeff(b[6], b[5], cospi_16_64, &a[6], &a[5]);
a[7] = b[7];
a[8] = vaddq_s16(b[8], b[11]);
a[9] = vaddq_s16(b[9], b[10]);
a[10] = vsubq_s16(b[9], b[10]);
a[11] = vsubq_s16(b[8], b[11]);
a[12] = vsubq_s16(b[15], b[12]);
a[13] = vsubq_s16(b[14], b[13]);
a[14] = vaddq_s16(b[14], b[13]);
a[15] = vaddq_s16(b[15], b[12]);
a[16] = b[16];
a[17] = b[17];
butterfly_two_coeff(b[29], b[18], cospi_24_64, cospi_8_64, &a[29], &a[18]);
butterfly_two_coeff(b[28], b[19], cospi_24_64, cospi_8_64, &a[28], &a[19]);
butterfly_two_coeff(b[27], b[20], -cospi_8_64, cospi_24_64, &a[27], &a[20]);
butterfly_two_coeff(b[26], b[21], -cospi_8_64, cospi_24_64, &a[26], &a[21]);
a[22] = b[22];
a[23] = b[23];
a[24] = b[24];
a[25] = b[25];
a[30] = b[30];
a[31] = b[31];
// Stage 5.
butterfly_one_coeff(a[0], a[1], cospi_16_64, &b[0], &b[1]);
butterfly_two_coeff(a[3], a[2], cospi_24_64, cospi_8_64, &b[2], &b[3]);
b[4] = vaddq_s16(a[4], a[5]);
b[5] = vsubq_s16(a[4], a[5]);
b[6] = vsubq_s16(a[7], a[6]);
b[7] = vaddq_s16(a[7], a[6]);
b[8] = a[8];
butterfly_two_coeff(a[14], a[9], cospi_24_64, cospi_8_64, &b[14], &b[9]);
butterfly_two_coeff(a[13], a[10], -cospi_8_64, cospi_24_64, &b[13], &b[10]);
b[11] = a[11];
b[12] = a[12];
b[15] = a[15];
b[16] = vaddq_s16(a[19], a[16]);
b[17] = vaddq_s16(a[18], a[17]);
b[18] = vsubq_s16(a[17], a[18]);
b[19] = vsubq_s16(a[16], a[19]);
b[20] = vsubq_s16(a[23], a[20]);
b[21] = vsubq_s16(a[22], a[21]);
b[22] = vaddq_s16(a[21], a[22]);
b[23] = vaddq_s16(a[20], a[23]);
b[24] = vaddq_s16(a[27], a[24]);
b[25] = vaddq_s16(a[26], a[25]);
b[26] = vsubq_s16(a[25], a[26]);
b[27] = vsubq_s16(a[24], a[27]);
b[28] = vsubq_s16(a[31], a[28]);
b[29] = vsubq_s16(a[30], a[29]);
b[30] = vaddq_s16(a[29], a[30]);
b[31] = vaddq_s16(a[28], a[31]);
// Stage 6.
a[0] = b[0];
a[1] = b[1];
a[2] = b[2];
a[3] = b[3];
butterfly_two_coeff(b[7], b[4], cospi_28_64, cospi_4_64, &a[4], &a[7]);
butterfly_two_coeff(b[6], b[5], cospi_12_64, cospi_20_64, &a[5], &a[6]);
a[8] = vaddq_s16(b[8], b[9]);
a[9] = vsubq_s16(b[8], b[9]);
a[10] = vsubq_s16(b[11], b[10]);
a[11] = vaddq_s16(b[11], b[10]);
a[12] = vaddq_s16(b[12], b[13]);
a[13] = vsubq_s16(b[12], b[13]);
a[14] = vsubq_s16(b[15], b[14]);
a[15] = vaddq_s16(b[15], b[14]);
a[16] = b[16];
a[19] = b[19];
a[20] = b[20];
a[23] = b[23];
a[24] = b[24];
a[27] = b[27];
a[28] = b[28];
a[31] = b[31];
butterfly_two_coeff(b[30], b[17], cospi_28_64, cospi_4_64, &a[30], &a[17]);
butterfly_two_coeff(b[29], b[18], -cospi_4_64, cospi_28_64, &a[29], &a[18]);
butterfly_two_coeff(b[26], b[21], cospi_12_64, cospi_20_64, &a[26], &a[21]);
butterfly_two_coeff(b[25], b[22], -cospi_20_64, cospi_12_64, &a[25], &a[22]);
// Stage 7.
b[0] = a[0];
b[1] = a[1];
b[2] = a[2];
b[3] = a[3];
b[4] = a[4];
b[5] = a[5];
b[6] = a[6];
b[7] = a[7];
butterfly_two_coeff(a[15], a[8], cospi_30_64, cospi_2_64, &b[8], &b[15]);
butterfly_two_coeff(a[14], a[9], cospi_14_64, cospi_18_64, &b[9], &b[14]);
butterfly_two_coeff(a[13], a[10], cospi_22_64, cospi_10_64, &b[10], &b[13]);
butterfly_two_coeff(a[12], a[11], cospi_6_64, cospi_26_64, &b[11], &b[12]);
b[16] = vaddq_s16(a[16], a[17]);
b[17] = vsubq_s16(a[16], a[17]);
b[18] = vsubq_s16(a[19], a[18]);
b[19] = vaddq_s16(a[19], a[18]);
b[20] = vaddq_s16(a[20], a[21]);
b[21] = vsubq_s16(a[20], a[21]);
b[22] = vsubq_s16(a[23], a[22]);
b[23] = vaddq_s16(a[23], a[22]);
b[24] = vaddq_s16(a[24], a[25]);
b[25] = vsubq_s16(a[24], a[25]);
b[26] = vsubq_s16(a[27], a[26]);
b[27] = vaddq_s16(a[27], a[26]);
b[28] = vaddq_s16(a[28], a[29]);
b[29] = vsubq_s16(a[28], a[29]);
b[30] = vsubq_s16(a[31], a[30]);
b[31] = vaddq_s16(a[31], a[30]);
// Final stage.
// Also compute partial rounding shift:
// output[j * 32 + i] = (temp_out[j] + 1 + (temp_out[j] > 0)) >> 2;
out[0] = sub_round_shift(b[0]);
out[16] = sub_round_shift(b[1]);
out[8] = sub_round_shift(b[2]);
out[24] = sub_round_shift(b[3]);
out[4] = sub_round_shift(b[4]);
out[20] = sub_round_shift(b[5]);
out[12] = sub_round_shift(b[6]);
out[28] = sub_round_shift(b[7]);
out[2] = sub_round_shift(b[8]);
out[18] = sub_round_shift(b[9]);
out[10] = sub_round_shift(b[10]);
out[26] = sub_round_shift(b[11]);
out[6] = sub_round_shift(b[12]);
out[22] = sub_round_shift(b[13]);
out[14] = sub_round_shift(b[14]);
out[30] = sub_round_shift(b[15]);
butterfly_two_coeff(b[31], b[16], cospi_31_64, cospi_1_64, &a[1], &a[31]);
out[1] = sub_round_shift(a[1]);
out[31] = sub_round_shift(a[31]);
butterfly_two_coeff(b[30], b[17], cospi_15_64, cospi_17_64, &a[17], &a[15]);
out[17] = sub_round_shift(a[17]);
out[15] = sub_round_shift(a[15]);
butterfly_two_coeff(b[29], b[18], cospi_23_64, cospi_9_64, &a[9], &a[23]);
out[9] = sub_round_shift(a[9]);
out[23] = sub_round_shift(a[23]);
butterfly_two_coeff(b[28], b[19], cospi_7_64, cospi_25_64, &a[25], &a[7]);
out[25] = sub_round_shift(a[25]);
out[7] = sub_round_shift(a[7]);
butterfly_two_coeff(b[27], b[20], cospi_27_64, cospi_5_64, &a[5], &a[27]);
out[5] = sub_round_shift(a[5]);
out[27] = sub_round_shift(a[27]);
butterfly_two_coeff(b[26], b[21], cospi_11_64, cospi_21_64, &a[21], &a[11]);
out[21] = sub_round_shift(a[21]);
out[11] = sub_round_shift(a[11]);
butterfly_two_coeff(b[25], b[22], cospi_19_64, cospi_13_64, &a[13], &a[19]);
out[13] = sub_round_shift(a[13]);
out[19] = sub_round_shift(a[19]);
butterfly_two_coeff(b[24], b[23], cospi_3_64, cospi_29_64, &a[29], &a[3]);
out[29] = sub_round_shift(a[29]);
out[3] = sub_round_shift(a[3]);
}
#define PASS_THROUGH(src, dst, element) \
do { \
dst##_lo[element] = src##_lo[element]; \
dst##_hi[element] = src##_hi[element]; \
} while (0)
#define ADD_S16_S32(a, left_index, right_index, b, b_index) \
do { \
b##_lo[b_index] = \
vaddl_s16(vget_low_s16(a[left_index]), vget_low_s16(a[right_index])); \
b##_hi[b_index] = vaddl_s16(vget_high_s16(a[left_index]), \
vget_high_s16(a[right_index])); \
} while (0)
#define SUB_S16_S32(a, left_index, right_index, b, b_index) \
do { \
b##_lo[b_index] = \
vsubl_s16(vget_low_s16(a[left_index]), vget_low_s16(a[right_index])); \
b##_hi[b_index] = vsubl_s16(vget_high_s16(a[left_index]), \
vget_high_s16(a[right_index])); \
} while (0)
#define ADDW_S16_S32(a, a_index, b, b_index, c, c_index) \
do { \
c##_lo[c_index] = vaddw_s16(a##_lo[a_index], vget_low_s16(b[b_index])); \
c##_hi[c_index] = vaddw_s16(a##_hi[a_index], vget_high_s16(b[b_index])); \
} while (0)
#define SUBW_S16_S32(a, a_index, b, b_index, temp, temp_index, c, c_index) \
do { \
temp##_lo[temp_index] = vmovl_s16(vget_low_s16(a[a_index])); \
temp##_hi[temp_index] = vmovl_s16(vget_high_s16(a[a_index])); \
c##_lo[c_index] = vsubq_s32(temp##_lo[temp_index], b##_lo[b_index]); \
c##_hi[c_index] = vsubq_s32(temp##_hi[temp_index], b##_hi[b_index]); \
} while (0)
#define ADD_S32(a, left_index, right_index, b, b_index) \
do { \
b##_lo[b_index] = vaddq_s32(a##_lo[left_index], a##_lo[right_index]); \
b##_hi[b_index] = vaddq_s32(a##_hi[left_index], a##_hi[right_index]); \
} while (0)
#define SUB_S32(a, left_index, right_index, b, b_index) \
do { \
b##_lo[b_index] = vsubq_s32(a##_lo[left_index], a##_lo[right_index]); \
b##_hi[b_index] = vsubq_s32(a##_hi[left_index], a##_hi[right_index]); \
} while (0)
// Like butterfly_one_coeff, but don't narrow results.
static INLINE void butterfly_one_coeff_s16_s32(
const int16x8_t a, const int16x8_t b, const tran_high_t constant,
int32x4_t *add_lo, int32x4_t *add_hi, int32x4_t *sub_lo,
int32x4_t *sub_hi) {
const int32x4_t a0 = vmull_n_s16(vget_low_s16(a), constant);
const int32x4_t a1 = vmull_n_s16(vget_high_s16(a), constant);
const int32x4_t sum0 = vmlal_n_s16(a0, vget_low_s16(b), constant);
const int32x4_t sum1 = vmlal_n_s16(a1, vget_high_s16(b), constant);
const int32x4_t diff0 = vmlsl_n_s16(a0, vget_low_s16(b), constant);
const int32x4_t diff1 = vmlsl_n_s16(a1, vget_high_s16(b), constant);
*add_lo = vrshrq_n_s32(sum0, DCT_CONST_BITS);
*add_hi = vrshrq_n_s32(sum1, DCT_CONST_BITS);
*sub_lo = vrshrq_n_s32(diff0, DCT_CONST_BITS);
*sub_hi = vrshrq_n_s32(diff1, DCT_CONST_BITS);
}
#define BUTTERFLY_ONE_S16_S32(a, left_index, right_index, constant, b, \
add_index, sub_index) \
do { \
butterfly_one_coeff_s16_s32(a[left_index], a[right_index], constant, \
&b##_lo[add_index], &b##_hi[add_index], \
&b##_lo[sub_index], &b##_hi[sub_index]); \
} while (0)
// Like butterfly_one_coeff, but with s32.
static INLINE void butterfly_one_coeff_s32(
const int32x4_t a_lo, const int32x4_t a_hi, const int32x4_t b_lo,
const int32x4_t b_hi, const int32_t constant, int32x4_t *add_lo,
int32x4_t *add_hi, int32x4_t *sub_lo, int32x4_t *sub_hi) {
const int32x4_t a_lo_0 = vmulq_n_s32(a_lo, constant);
const int32x4_t a_hi_0 = vmulq_n_s32(a_hi, constant);
const int32x4_t sum0 = vmlaq_n_s32(a_lo_0, b_lo, constant);
const int32x4_t sum1 = vmlaq_n_s32(a_hi_0, b_hi, constant);
const int32x4_t diff0 = vmlsq_n_s32(a_lo_0, b_lo, constant);
const int32x4_t diff1 = vmlsq_n_s32(a_hi_0, b_hi, constant);
*add_lo = vrshrq_n_s32(sum0, DCT_CONST_BITS);
*add_hi = vrshrq_n_s32(sum1, DCT_CONST_BITS);
*sub_lo = vrshrq_n_s32(diff0, DCT_CONST_BITS);
*sub_hi = vrshrq_n_s32(diff1, DCT_CONST_BITS);
}
#define BUTTERFLY_ONE_S32(a, left_index, right_index, constant, b, add_index, \
sub_index) \
do { \
butterfly_one_coeff_s32(a##_lo[left_index], a##_hi[left_index], \
a##_lo[right_index], a##_hi[right_index], \
constant, &b##_lo[add_index], &b##_hi[add_index], \
&b##_lo[sub_index], &b##_hi[sub_index]); \
} while (0)
// Like butterfly_two_coeff, but with s32.
static INLINE void butterfly_two_coeff_s32(
const int32x4_t a_lo, const int32x4_t a_hi, const int32x4_t b_lo,
const int32x4_t b_hi, const int32_t constant0, const int32_t constant1,
int32x4_t *add_lo, int32x4_t *add_hi, int32x4_t *sub_lo,
int32x4_t *sub_hi) {
const int32x4_t a0 = vmulq_n_s32(a_lo, constant0);
const int32x4_t a1 = vmulq_n_s32(a_hi, constant0);
const int32x4_t a2 = vmulq_n_s32(a_lo, constant1);
const int32x4_t a3 = vmulq_n_s32(a_hi, constant1);
const int32x4_t sum0 = vmlaq_n_s32(a2, b_lo, constant0);
const int32x4_t sum1 = vmlaq_n_s32(a3, b_hi, constant0);
const int32x4_t diff0 = vmlsq_n_s32(a0, b_lo, constant1);
const int32x4_t diff1 = vmlsq_n_s32(a1, b_hi, constant1);
*add_lo = vrshrq_n_s32(sum0, DCT_CONST_BITS);
*add_hi = vrshrq_n_s32(sum1, DCT_CONST_BITS);
*sub_lo = vrshrq_n_s32(diff0, DCT_CONST_BITS);
*sub_hi = vrshrq_n_s32(diff1, DCT_CONST_BITS);
}
#define BUTTERFLY_TWO_S32(a, left_index, right_index, left_constant, \
right_constant, b, add_index, sub_index) \
do { \
butterfly_two_coeff_s32(a##_lo[left_index], a##_hi[left_index], \
a##_lo[right_index], a##_hi[right_index], \
left_constant, right_constant, &b##_lo[add_index], \
&b##_hi[add_index], &b##_lo[sub_index], \
&b##_hi[sub_index]); \
} while (0)
// Add 1 if positive, 2 if negative, and shift by 2.
// In practice, add 1, then add the sign bit, then shift without rounding.
static INLINE int16x8_t add_round_shift_s32(const int32x4_t a_lo,
const int32x4_t a_hi) {
const int32x4_t one = vdupq_n_s32(1);
const uint32x4_t a_lo_u32 = vreinterpretq_u32_s32(a_lo);
const uint32x4_t a_lo_sign_u32 = vshrq_n_u32(a_lo_u32, 31);
const int32x4_t a_lo_sign_s32 = vreinterpretq_s32_u32(a_lo_sign_u32);
const int16x4_t b_lo =
vshrn_n_s32(vqaddq_s32(vqaddq_s32(a_lo, a_lo_sign_s32), one), 2);
const uint32x4_t a_hi_u32 = vreinterpretq_u32_s32(a_hi);
const uint32x4_t a_hi_sign_u32 = vshrq_n_u32(a_hi_u32, 31);
const int32x4_t a_hi_sign_s32 = vreinterpretq_s32_u32(a_hi_sign_u32);
const int16x4_t b_hi =
vshrn_n_s32(vqaddq_s32(vqaddq_s32(a_hi, a_hi_sign_s32), one), 2);
return vcombine_s16(b_lo, b_hi);
}
static void dct_body_second_pass(const int16x8_t *in, int16x8_t *out) {
int16x8_t a[32];
int16x8_t b[32];
int32x4_t c_lo[32];
int32x4_t c_hi[32];
int32x4_t d_lo[32];
int32x4_t d_hi[32];
// Stage 1. Done as part of the load for the first pass.
a[0] = vaddq_s16(in[0], in[31]);
a[1] = vaddq_s16(in[1], in[30]);
a[2] = vaddq_s16(in[2], in[29]);
a[3] = vaddq_s16(in[3], in[28]);
a[4] = vaddq_s16(in[4], in[27]);
a[5] = vaddq_s16(in[5], in[26]);
a[6] = vaddq_s16(in[6], in[25]);
a[7] = vaddq_s16(in[7], in[24]);
a[8] = vaddq_s16(in[8], in[23]);
a[9] = vaddq_s16(in[9], in[22]);
a[10] = vaddq_s16(in[10], in[21]);
a[11] = vaddq_s16(in[11], in[20]);
a[12] = vaddq_s16(in[12], in[19]);
a[13] = vaddq_s16(in[13], in[18]);
a[14] = vaddq_s16(in[14], in[17]);
a[15] = vaddq_s16(in[15], in[16]);
a[16] = vsubq_s16(in[15], in[16]);
a[17] = vsubq_s16(in[14], in[17]);
a[18] = vsubq_s16(in[13], in[18]);
a[19] = vsubq_s16(in[12], in[19]);
a[20] = vsubq_s16(in[11], in[20]);
a[21] = vsubq_s16(in[10], in[21]);
a[22] = vsubq_s16(in[9], in[22]);
a[23] = vsubq_s16(in[8], in[23]);
a[24] = vsubq_s16(in[7], in[24]);
a[25] = vsubq_s16(in[6], in[25]);
a[26] = vsubq_s16(in[5], in[26]);
a[27] = vsubq_s16(in[4], in[27]);
a[28] = vsubq_s16(in[3], in[28]);
a[29] = vsubq_s16(in[2], in[29]);
a[30] = vsubq_s16(in[1], in[30]);
a[31] = vsubq_s16(in[0], in[31]);
// Stage 2.
b[0] = vaddq_s16(a[0], a[15]);
b[1] = vaddq_s16(a[1], a[14]);
b[2] = vaddq_s16(a[2], a[13]);
b[3] = vaddq_s16(a[3], a[12]);
b[4] = vaddq_s16(a[4], a[11]);
b[5] = vaddq_s16(a[5], a[10]);
b[6] = vaddq_s16(a[6], a[9]);
b[7] = vaddq_s16(a[7], a[8]);
b[8] = vsubq_s16(a[7], a[8]);
b[9] = vsubq_s16(a[6], a[9]);
b[10] = vsubq_s16(a[5], a[10]);
b[11] = vsubq_s16(a[4], a[11]);
b[12] = vsubq_s16(a[3], a[12]);
b[13] = vsubq_s16(a[2], a[13]);
b[14] = vsubq_s16(a[1], a[14]);
b[15] = vsubq_s16(a[0], a[15]);
b[16] = a[16];
b[17] = a[17];
b[18] = a[18];
b[19] = a[19];
butterfly_one_coeff(a[27], a[20], cospi_16_64, &b[27], &b[20]);
butterfly_one_coeff(a[26], a[21], cospi_16_64, &b[26], &b[21]);
butterfly_one_coeff(a[25], a[22], cospi_16_64, &b[25], &b[22]);
butterfly_one_coeff(a[24], a[23], cospi_16_64, &b[24], &b[23]);
b[28] = a[28];
b[29] = a[29];
b[30] = a[30];
b[31] = a[31];
// Stage 3. With extreme values for input this calculation rolls over int16_t.
// The sources for b[0] get added multiple times and, through testing, have
// been shown to overflow starting here.
ADD_S16_S32(b, 0, 7, c, 0);
ADD_S16_S32(b, 1, 6, c, 1);
ADD_S16_S32(b, 2, 5, c, 2);
ADD_S16_S32(b, 3, 4, c, 3);
SUB_S16_S32(b, 3, 4, c, 4);
SUB_S16_S32(b, 2, 5, c, 5);
SUB_S16_S32(b, 1, 6, c, 6);
SUB_S16_S32(b, 0, 7, c, 7);
a[8] = b[8];
a[9] = b[9];
BUTTERFLY_ONE_S16_S32(b, 13, 10, cospi_16_64, c, 13, 10);
BUTTERFLY_ONE_S16_S32(b, 12, 11, cospi_16_64, c, 12, 11);
a[14] = b[14];
a[15] = b[15];
ADD_S16_S32(b, 16, 23, c, 16);
ADD_S16_S32(b, 17, 22, c, 17);
ADD_S16_S32(b, 18, 21, c, 18);
ADD_S16_S32(b, 19, 20, c, 19);
SUB_S16_S32(b, 19, 20, c, 20);
SUB_S16_S32(b, 18, 21, c, 21);
SUB_S16_S32(b, 17, 22, c, 22);
SUB_S16_S32(b, 16, 23, c, 23);
SUB_S16_S32(b, 31, 24, c, 24);
SUB_S16_S32(b, 30, 25, c, 25);
SUB_S16_S32(b, 29, 26, c, 26);
SUB_S16_S32(b, 28, 27, c, 27);
ADD_S16_S32(b, 28, 27, c, 28);
ADD_S16_S32(b, 29, 26, c, 29);
ADD_S16_S32(b, 30, 25, c, 30);
ADD_S16_S32(b, 31, 24, c, 31);
// Stage 4.
ADD_S32(c, 0, 3, d, 0);
ADD_S32(c, 1, 2, d, 1);
SUB_S32(c, 1, 2, d, 2);
SUB_S32(c, 0, 3, d, 3);
PASS_THROUGH(c, d, 4);
BUTTERFLY_ONE_S32(c, 6, 5, cospi_16_64, d, 6, 5);
PASS_THROUGH(c, d, 7);
ADDW_S16_S32(c, 11, a, 8, d, 8);
ADDW_S16_S32(c, 10, a, 9, d, 9);
SUBW_S16_S32(a, 9, c, 10, c, 9, d, 10);
SUBW_S16_S32(a, 8, c, 11, c, 8, d, 11);
SUBW_S16_S32(a, 15, c, 12, c, 15, d, 12);
SUBW_S16_S32(a, 14, c, 13, c, 14, d, 13);
ADDW_S16_S32(c, 13, b, 14, d, 14);
ADDW_S16_S32(c, 12, b, 15, d, 15);
PASS_THROUGH(c, d, 16);
PASS_THROUGH(c, d, 17);
BUTTERFLY_TWO_S32(c, 29, 18, cospi_24_64, cospi_8_64, d, 29, 18);
BUTTERFLY_TWO_S32(c, 28, 19, cospi_24_64, cospi_8_64, d, 28, 19);
BUTTERFLY_TWO_S32(c, 27, 20, -cospi_8_64, cospi_24_64, d, 27, 20);
BUTTERFLY_TWO_S32(c, 26, 21, -cospi_8_64, cospi_24_64, d, 26, 21);
PASS_THROUGH(c, d, 22);
PASS_THROUGH(c, d, 23);
PASS_THROUGH(c, d, 24);
PASS_THROUGH(c, d, 25);
PASS_THROUGH(c, d, 30);
PASS_THROUGH(c, d, 31);
// Stage 5.
BUTTERFLY_ONE_S32(d, 0, 1, cospi_16_64, c, 0, 1);
BUTTERFLY_TWO_S32(d, 3, 2, cospi_24_64, cospi_8_64, c, 2, 3);
ADD_S32(d, 4, 5, c, 4);
SUB_S32(d, 4, 5, c, 5);
SUB_S32(d, 7, 6, c, 6);
ADD_S32(d, 7, 6, c, 7);
PASS_THROUGH(d, c, 8);
BUTTERFLY_TWO_S32(d, 14, 9, cospi_24_64, cospi_8_64, c, 14, 9);
BUTTERFLY_TWO_S32(d, 13, 10, -cospi_8_64, cospi_24_64, c, 13, 10);
PASS_THROUGH(d, c, 11);
PASS_THROUGH(d, c, 12);
PASS_THROUGH(d, c, 15);
ADD_S32(d, 16, 19, c, 16);
ADD_S32(d, 17, 18, c, 17);
SUB_S32(d, 17, 18, c, 18);
SUB_S32(d, 16, 19, c, 19);
SUB_S32(d, 23, 20, c, 20);
SUB_S32(d, 22, 21, c, 21);
ADD_S32(d, 22, 21, c, 22);
ADD_S32(d, 23, 20, c, 23);
ADD_S32(d, 24, 27, c, 24);
ADD_S32(d, 25, 26, c, 25);
SUB_S32(d, 25, 26, c, 26);
SUB_S32(d, 24, 27, c, 27);
SUB_S32(d, 31, 28, c, 28);
SUB_S32(d, 30, 29, c, 29);
ADD_S32(d, 30, 29, c, 30);
ADD_S32(d, 31, 28, c, 31);
// Stage 6.
PASS_THROUGH(c, d, 0);
PASS_THROUGH(c, d, 1);
PASS_THROUGH(c, d, 2);
PASS_THROUGH(c, d, 3);
BUTTERFLY_TWO_S32(c, 7, 4, cospi_28_64, cospi_4_64, d, 4, 7);
BUTTERFLY_TWO_S32(c, 6, 5, cospi_12_64, cospi_20_64, d, 5, 6);
ADD_S32(c, 8, 9, d, 8);
SUB_S32(c, 8, 9, d, 9);
SUB_S32(c, 11, 10, d, 10);
ADD_S32(c, 11, 10, d, 11);
ADD_S32(c, 12, 13, d, 12);
SUB_S32(c, 12, 13, d, 13);
SUB_S32(c, 15, 14, d, 14);
ADD_S32(c, 15, 14, d, 15);
PASS_THROUGH(c, d, 16);
PASS_THROUGH(c, d, 19);
PASS_THROUGH(c, d, 20);
PASS_THROUGH(c, d, 23);
PASS_THROUGH(c, d, 24);
PASS_THROUGH(c, d, 27);
PASS_THROUGH(c, d, 28);
PASS_THROUGH(c, d, 31);
BUTTERFLY_TWO_S32(c, 30, 17, cospi_28_64, cospi_4_64, d, 30, 17);
BUTTERFLY_TWO_S32(c, 29, 18, -cospi_4_64, cospi_28_64, d, 29, 18);
BUTTERFLY_TWO_S32(c, 26, 21, cospi_12_64, cospi_20_64, d, 26, 21);
BUTTERFLY_TWO_S32(c, 25, 22, -cospi_20_64, cospi_12_64, d, 25, 22);
// Stage 7.
PASS_THROUGH(d, c, 0);
PASS_THROUGH(d, c, 1);
PASS_THROUGH(d, c, 2);
PASS_THROUGH(d, c, 3);
PASS_THROUGH(d, c, 4);
PASS_THROUGH(d, c, 5);
PASS_THROUGH(d, c, 6);
PASS_THROUGH(d, c, 7);
BUTTERFLY_TWO_S32(d, 15, 8, cospi_30_64, cospi_2_64, c, 8, 15);
BUTTERFLY_TWO_S32(d, 14, 9, cospi_14_64, cospi_18_64, c, 9, 14);
BUTTERFLY_TWO_S32(d, 13, 10, cospi_22_64, cospi_10_64, c, 10, 13);
BUTTERFLY_TWO_S32(d, 12, 11, cospi_6_64, cospi_26_64, c, 11, 12);
ADD_S32(d, 16, 17, c, 16);
SUB_S32(d, 16, 17, c, 17);
SUB_S32(d, 19, 18, c, 18);
ADD_S32(d, 19, 18, c, 19);
ADD_S32(d, 20, 21, c, 20);
SUB_S32(d, 20, 21, c, 21);
SUB_S32(d, 23, 22, c, 22);
ADD_S32(d, 23, 22, c, 23);
ADD_S32(d, 24, 25, c, 24);
SUB_S32(d, 24, 25, c, 25);
SUB_S32(d, 27, 26, c, 26);
ADD_S32(d, 27, 26, c, 27);
ADD_S32(d, 28, 29, c, 28);
SUB_S32(d, 28, 29, c, 29);
SUB_S32(d, 31, 30, c, 30);
ADD_S32(d, 31, 30, c, 31);
// Final stage.
// Roll rounding into this function so we can pass back int16x8.
out[0] = add_round_shift_s32(c_lo[0], c_hi[0]);
out[16] = add_round_shift_s32(c_lo[1], c_hi[1]);
out[8] = add_round_shift_s32(c_lo[2], c_hi[2]);
out[24] = add_round_shift_s32(c_lo[3], c_hi[3]);
out[4] = add_round_shift_s32(c_lo[4], c_hi[4]);
out[20] = add_round_shift_s32(c_lo[5], c_hi[5]);
out[12] = add_round_shift_s32(c_lo[6], c_hi[6]);
out[28] = add_round_shift_s32(c_lo[7], c_hi[7]);
out[2] = add_round_shift_s32(c_lo[8], c_hi[8]);
out[18] = add_round_shift_s32(c_lo[9], c_hi[9]);
out[10] = add_round_shift_s32(c_lo[10], c_hi[10]);
out[26] = add_round_shift_s32(c_lo[11], c_hi[11]);
out[6] = add_round_shift_s32(c_lo[12], c_hi[12]);
out[22] = add_round_shift_s32(c_lo[13], c_hi[13]);
out[14] = add_round_shift_s32(c_lo[14], c_hi[14]);
out[30] = add_round_shift_s32(c_lo[15], c_hi[15]);
BUTTERFLY_TWO_S32(c, 31, 16, cospi_31_64, cospi_1_64, d, 1, 31);
out[1] = add_round_shift_s32(d_lo[1], d_hi[1]);
out[31] = add_round_shift_s32(d_lo[31], d_hi[31]);
BUTTERFLY_TWO_S32(c, 30, 17, cospi_15_64, cospi_17_64, d, 17, 15);
out[17] = add_round_shift_s32(d_lo[17], d_hi[17]);
out[15] = add_round_shift_s32(d_lo[15], d_hi[15]);
BUTTERFLY_TWO_S32(c, 29, 18, cospi_23_64, cospi_9_64, d, 9, 23);
out[9] = add_round_shift_s32(d_lo[9], d_hi[9]);
out[23] = add_round_shift_s32(d_lo[23], d_hi[23]);
BUTTERFLY_TWO_S32(c, 28, 19, cospi_7_64, cospi_25_64, d, 25, 7);
out[25] = add_round_shift_s32(d_lo[25], d_hi[25]);
out[7] = add_round_shift_s32(d_lo[7], d_hi[7]);
BUTTERFLY_TWO_S32(c, 27, 20, cospi_27_64, cospi_5_64, d, 5, 27);
out[5] = add_round_shift_s32(d_lo[5], d_hi[5]);
out[27] = add_round_shift_s32(d_lo[27], d_hi[27]);
BUTTERFLY_TWO_S32(c, 26, 21, cospi_11_64, cospi_21_64, d, 21, 11);
out[21] = add_round_shift_s32(d_lo[21], d_hi[21]);
out[11] = add_round_shift_s32(d_lo[11], d_hi[11]);
BUTTERFLY_TWO_S32(c, 25, 22, cospi_19_64, cospi_13_64, d, 13, 19);
out[13] = add_round_shift_s32(d_lo[13], d_hi[13]);
out[19] = add_round_shift_s32(d_lo[19], d_hi[19]);
BUTTERFLY_TWO_S32(c, 24, 23, cospi_3_64, cospi_29_64, d, 29, 3);
out[29] = add_round_shift_s32(d_lo[29], d_hi[29]);
out[3] = add_round_shift_s32(d_lo[3], d_hi[3]);
}
// Add 1 if positive, 2 if negative, and shift by 2.
// In practice, add 1, then add the sign bit, then shift without rounding.
static INLINE int16x8_t add_round_shift_s16(const int16x8_t a) {
const int16x8_t one = vdupq_n_s16(1);
const uint16x8_t a_u16 = vreinterpretq_u16_s16(a);
const uint16x8_t a_sign_u16 = vshrq_n_u16(a_u16, 15);
const int16x8_t a_sign_s16 = vreinterpretq_s16_u16(a_sign_u16);
return vshrq_n_s16(vaddq_s16(vaddq_s16(a, a_sign_s16), one), 2);
}
static void dct_body_second_pass_rd(const int16x8_t *in, int16x8_t *out) {
int16x8_t a[32];
int16x8_t b[32];
// Stage 1. Done as part of the load for the first pass.
a[0] = vaddq_s16(in[0], in[31]);
a[1] = vaddq_s16(in[1], in[30]);
a[2] = vaddq_s16(in[2], in[29]);
a[3] = vaddq_s16(in[3], in[28]);
a[4] = vaddq_s16(in[4], in[27]);
a[5] = vaddq_s16(in[5], in[26]);
a[6] = vaddq_s16(in[6], in[25]);
a[7] = vaddq_s16(in[7], in[24]);
a[8] = vaddq_s16(in[8], in[23]);
a[9] = vaddq_s16(in[9], in[22]);
a[10] = vaddq_s16(in[10], in[21]);
a[11] = vaddq_s16(in[11], in[20]);
a[12] = vaddq_s16(in[12], in[19]);
a[13] = vaddq_s16(in[13], in[18]);
a[14] = vaddq_s16(in[14], in[17]);
a[15] = vaddq_s16(in[15], in[16]);
a[16] = vsubq_s16(in[15], in[16]);
a[17] = vsubq_s16(in[14], in[17]);
a[18] = vsubq_s16(in[13], in[18]);
a[19] = vsubq_s16(in[12], in[19]);
a[20] = vsubq_s16(in[11], in[20]);
a[21] = vsubq_s16(in[10], in[21]);
a[22] = vsubq_s16(in[9], in[22]);
a[23] = vsubq_s16(in[8], in[23]);
a[24] = vsubq_s16(in[7], in[24]);
a[25] = vsubq_s16(in[6], in[25]);
a[26] = vsubq_s16(in[5], in[26]);
a[27] = vsubq_s16(in[4], in[27]);
a[28] = vsubq_s16(in[3], in[28]);
a[29] = vsubq_s16(in[2], in[29]);
a[30] = vsubq_s16(in[1], in[30]);
a[31] = vsubq_s16(in[0], in[31]);
// Stage 2.
// For the "rd" version, all the values are rounded down after stage 2 to keep
// the values in 16 bits.
b[0] = add_round_shift_s16(vaddq_s16(a[0], a[15]));
b[1] = add_round_shift_s16(vaddq_s16(a[1], a[14]));
b[2] = add_round_shift_s16(vaddq_s16(a[2], a[13]));
b[3] = add_round_shift_s16(vaddq_s16(a[3], a[12]));
b[4] = add_round_shift_s16(vaddq_s16(a[4], a[11]));
b[5] = add_round_shift_s16(vaddq_s16(a[5], a[10]));
b[6] = add_round_shift_s16(vaddq_s16(a[6], a[9]));
b[7] = add_round_shift_s16(vaddq_s16(a[7], a[8]));
b[8] = add_round_shift_s16(vsubq_s16(a[7], a[8]));
b[9] = add_round_shift_s16(vsubq_s16(a[6], a[9]));
b[10] = add_round_shift_s16(vsubq_s16(a[5], a[10]));
b[11] = add_round_shift_s16(vsubq_s16(a[4], a[11]));
b[12] = add_round_shift_s16(vsubq_s16(a[3], a[12]));
b[13] = add_round_shift_s16(vsubq_s16(a[2], a[13]));
b[14] = add_round_shift_s16(vsubq_s16(a[1], a[14]));
b[15] = add_round_shift_s16(vsubq_s16(a[0], a[15]));
b[16] = add_round_shift_s16(a[16]);
b[17] = add_round_shift_s16(a[17]);
b[18] = add_round_shift_s16(a[18]);
b[19] = add_round_shift_s16(a[19]);
butterfly_one_coeff(a[27], a[20], cospi_16_64, &b[27], &b[20]);
butterfly_one_coeff(a[26], a[21], cospi_16_64, &b[26], &b[21]);
butterfly_one_coeff(a[25], a[22], cospi_16_64, &b[25], &b[22]);
butterfly_one_coeff(a[24], a[23], cospi_16_64, &b[24], &b[23]);
b[20] = add_round_shift_s16(b[20]);
b[21] = add_round_shift_s16(b[21]);
b[22] = add_round_shift_s16(b[22]);
b[23] = add_round_shift_s16(b[23]);
b[24] = add_round_shift_s16(b[24]);
b[25] = add_round_shift_s16(b[25]);
b[26] = add_round_shift_s16(b[26]);
b[27] = add_round_shift_s16(b[27]);
b[28] = add_round_shift_s16(a[28]);
b[29] = add_round_shift_s16(a[29]);
b[30] = add_round_shift_s16(a[30]);
b[31] = add_round_shift_s16(a[31]);
// Stage 3.
a[0] = vaddq_s16(b[0], b[7]);
a[1] = vaddq_s16(b[1], b[6]);
a[2] = vaddq_s16(b[2], b[5]);
a[3] = vaddq_s16(b[3], b[4]);
a[4] = vsubq_s16(b[3], b[4]);
a[5] = vsubq_s16(b[2], b[5]);
a[6] = vsubq_s16(b[1], b[6]);
a[7] = vsubq_s16(b[0], b[7]);
a[8] = b[8];
a[9] = b[9];
butterfly_one_coeff(b[13], b[10], cospi_16_64, &a[13], &a[10]);
butterfly_one_coeff(b[12], b[11], cospi_16_64, &a[12], &a[11]);
a[14] = b[14];
a[15] = b[15];
a[16] = vaddq_s16(b[16], b[23]);
a[17] = vaddq_s16(b[17], b[22]);
a[18] = vaddq_s16(b[18], b[21]);
a[19] = vaddq_s16(b[19], b[20]);
a[20] = vsubq_s16(b[19], b[20]);
a[21] = vsubq_s16(b[18], b[21]);
a[22] = vsubq_s16(b[17], b[22]);
a[23] = vsubq_s16(b[16], b[23]);
a[24] = vsubq_s16(b[31], b[24]);
a[25] = vsubq_s16(b[30], b[25]);
a[26] = vsubq_s16(b[29], b[26]);
a[27] = vsubq_s16(b[28], b[27]);
a[28] = vaddq_s16(b[28], b[27]);
a[29] = vaddq_s16(b[29], b[26]);
a[30] = vaddq_s16(b[30], b[25]);
a[31] = vaddq_s16(b[31], b[24]);
// Stage 4.
b[0] = vaddq_s16(a[0], a[3]);
b[1] = vaddq_s16(a[1], a[2]);
b[2] = vsubq_s16(a[1], a[2]);
b[3] = vsubq_s16(a[0], a[3]);
b[4] = a[4];
butterfly_one_coeff(a[6], a[5], cospi_16_64, &b[6], &b[5]);
b[7] = a[7];
b[8] = vaddq_s16(a[8], a[11]);
b[9] = vaddq_s16(a[9], a[10]);
b[10] = vsubq_s16(a[9], a[10]);
b[11] = vsubq_s16(a[8], a[11]);
b[12] = vsubq_s16(a[15], a[12]);
b[13] = vsubq_s16(a[14], a[13]);
b[14] = vaddq_s16(a[14], a[13]);
b[15] = vaddq_s16(a[15], a[12]);
b[16] = a[16];
b[17] = a[17];
butterfly_two_coeff(a[29], a[18], cospi_24_64, cospi_8_64, &b[29], &b[18]);
butterfly_two_coeff(a[28], a[19], cospi_24_64, cospi_8_64, &b[28], &b[19]);
butterfly_two_coeff(a[27], a[20], -cospi_8_64, cospi_24_64, &b[27], &b[20]);
butterfly_two_coeff(a[26], a[21], -cospi_8_64, cospi_24_64, &b[26], &b[21]);
b[22] = a[22];
b[23] = a[23];
b[24] = a[24];
b[25] = a[25];
b[30] = a[30];
b[31] = a[31];
// Stage 5.
butterfly_one_coeff(b[0], b[1], cospi_16_64, &a[0], &a[1]);
butterfly_two_coeff(b[3], b[2], cospi_24_64, cospi_8_64, &a[2], &a[3]);
a[4] = vaddq_s16(b[4], b[5]);
a[5] = vsubq_s16(b[4], b[5]);
a[6] = vsubq_s16(b[7], b[6]);
a[7] = vaddq_s16(b[7], b[6]);
a[8] = b[8];
butterfly_two_coeff(b[14], b[9], cospi_24_64, cospi_8_64, &a[14], &a[9]);
butterfly_two_coeff(b[13], b[10], -cospi_8_64, cospi_24_64, &a[13], &a[10]);
a[11] = b[11];
a[12] = b[12];
a[15] = b[15];
a[16] = vaddq_s16(b[19], b[16]);
a[17] = vaddq_s16(b[18], b[17]);
a[18] = vsubq_s16(b[17], b[18]);
a[19] = vsubq_s16(b[16], b[19]);
a[20] = vsubq_s16(b[23], b[20]);
a[21] = vsubq_s16(b[22], b[21]);
a[22] = vaddq_s16(b[21], b[22]);
a[23] = vaddq_s16(b[20], b[23]);
a[24] = vaddq_s16(b[27], b[24]);
a[25] = vaddq_s16(b[26], b[25]);
a[26] = vsubq_s16(b[25], b[26]);
a[27] = vsubq_s16(b[24], b[27]);
a[28] = vsubq_s16(b[31], b[28]);
a[29] = vsubq_s16(b[30], b[29]);
a[30] = vaddq_s16(b[29], b[30]);
a[31] = vaddq_s16(b[28], b[31]);
// Stage 6.
b[0] = a[0];
b[1] = a[1];
b[2] = a[2];
b[3] = a[3];
butterfly_two_coeff(a[7], a[4], cospi_28_64, cospi_4_64, &b[4], &b[7]);
butterfly_two_coeff(a[6], a[5], cospi_12_64, cospi_20_64, &b[5], &b[6]);
b[8] = vaddq_s16(a[8], a[9]);
b[9] = vsubq_s16(a[8], a[9]);
b[10] = vsubq_s16(a[11], a[10]);
b[11] = vaddq_s16(a[11], a[10]);
b[12] = vaddq_s16(a[12], a[13]);
b[13] = vsubq_s16(a[12], a[13]);
b[14] = vsubq_s16(a[15], a[14]);
b[15] = vaddq_s16(a[15], a[14]);
b[16] = a[16];
b[19] = a[19];
b[20] = a[20];
b[23] = a[23];
b[24] = a[24];
b[27] = a[27];
b[28] = a[28];
b[31] = a[31];
butterfly_two_coeff(a[30], a[17], cospi_28_64, cospi_4_64, &b[30], &b[17]);
butterfly_two_coeff(a[29], a[18], -cospi_4_64, cospi_28_64, &b[29], &b[18]);
butterfly_two_coeff(a[26], a[21], cospi_12_64, cospi_20_64, &b[26], &b[21]);
butterfly_two_coeff(a[25], a[22], -cospi_20_64, cospi_12_64, &b[25], &b[22]);
// Stage 7.
a[0] = b[0];
a[1] = b[1];
a[2] = b[2];
a[3] = b[3];
a[4] = b[4];
a[5] = b[5];
a[6] = b[6];
a[7] = b[7];
butterfly_two_coeff(b[15], b[8], cospi_30_64, cospi_2_64, &a[8], &a[15]);
butterfly_two_coeff(b[14], b[9], cospi_14_64, cospi_18_64, &a[9], &a[14]);
butterfly_two_coeff(b[13], b[10], cospi_22_64, cospi_10_64, &a[10], &a[13]);
butterfly_two_coeff(b[12], b[11], cospi_6_64, cospi_26_64, &a[11], &a[12]);
a[16] = vaddq_s16(b[16], b[17]);
a[17] = vsubq_s16(b[16], b[17]);
a[18] = vsubq_s16(b[19], b[18]);
a[19] = vaddq_s16(b[19], b[18]);
a[20] = vaddq_s16(b[20], b[21]);
a[21] = vsubq_s16(b[20], b[21]);
a[22] = vsubq_s16(b[23], b[22]);
a[23] = vaddq_s16(b[23], b[22]);
a[24] = vaddq_s16(b[24], b[25]);
a[25] = vsubq_s16(b[24], b[25]);
a[26] = vsubq_s16(b[27], b[26]);
a[27] = vaddq_s16(b[27], b[26]);
a[28] = vaddq_s16(b[28], b[29]);
a[29] = vsubq_s16(b[28], b[29]);
a[30] = vsubq_s16(b[31], b[30]);
a[31] = vaddq_s16(b[31], b[30]);
// Final stage.
out[0] = a[0];
out[16] = a[1];
out[8] = a[2];
out[24] = a[3];
out[4] = a[4];
out[20] = a[5];
out[12] = a[6];
out[28] = a[7];
out[2] = a[8];
out[18] = a[9];
out[10] = a[10];
out[26] = a[11];
out[6] = a[12];
out[22] = a[13];
out[14] = a[14];
out[30] = a[15];
butterfly_two_coeff(a[31], a[16], cospi_31_64, cospi_1_64, &out[1], &out[31]);
butterfly_two_coeff(a[30], a[17], cospi_15_64, cospi_17_64, &out[17],
&out[15]);
butterfly_two_coeff(a[29], a[18], cospi_23_64, cospi_9_64, &out[9], &out[23]);
butterfly_two_coeff(a[28], a[19], cospi_7_64, cospi_25_64, &out[25], &out[7]);
butterfly_two_coeff(a[27], a[20], cospi_27_64, cospi_5_64, &out[5], &out[27]);
butterfly_two_coeff(a[26], a[21], cospi_11_64, cospi_21_64, &out[21],
&out[11]);
butterfly_two_coeff(a[25], a[22], cospi_19_64, cospi_13_64, &out[13],
&out[19]);
butterfly_two_coeff(a[24], a[23], cospi_3_64, cospi_29_64, &out[29], &out[3]);
}
#undef PASS_THROUGH
#undef ADD_S16_S32
#undef SUB_S16_S32
#undef ADDW_S16_S32
#undef SUBW_S16_S32
#undef ADD_S32
#undef SUB_S32
#undef BUTTERFLY_ONE_S16_S32
#undef BUTTERFLY_ONE_S32
#undef BUTTERFLY_TWO_S32
// Transpose 8x8 to a new location. Don't use transpose_neon.h because those
// are all in-place.
// TODO(johannkoenig): share with other fdcts.
static INLINE void transpose_8x8(const int16x8_t *a, int16x8_t *b) {
// Swap 16 bit elements.
const int16x8x2_t c0 = vtrnq_s16(a[0], a[1]);
const int16x8x2_t c1 = vtrnq_s16(a[2], a[3]);
const int16x8x2_t c2 = vtrnq_s16(a[4], a[5]);
const int16x8x2_t c3 = vtrnq_s16(a[6], a[7]);
// Swap 32 bit elements.
const int32x4x2_t d0 = vtrnq_s32(vreinterpretq_s32_s16(c0.val[0]),
vreinterpretq_s32_s16(c1.val[0]));
const int32x4x2_t d1 = vtrnq_s32(vreinterpretq_s32_s16(c0.val[1]),
vreinterpretq_s32_s16(c1.val[1]));
const int32x4x2_t d2 = vtrnq_s32(vreinterpretq_s32_s16(c2.val[0]),
vreinterpretq_s32_s16(c3.val[0]));
const int32x4x2_t d3 = vtrnq_s32(vreinterpretq_s32_s16(c2.val[1]),
vreinterpretq_s32_s16(c3.val[1]));
// Swap 64 bit elements
const int16x8x2_t e0 = vpx_vtrnq_s64_to_s16(d0.val[0], d2.val[0]);
const int16x8x2_t e1 = vpx_vtrnq_s64_to_s16(d1.val[0], d3.val[0]);
const int16x8x2_t e2 = vpx_vtrnq_s64_to_s16(d0.val[1], d2.val[1]);
const int16x8x2_t e3 = vpx_vtrnq_s64_to_s16(d1.val[1], d3.val[1]);
b[0] = e0.val[0];
b[1] = e1.val[0];
b[2] = e2.val[0];
b[3] = e3.val[0];
b[4] = e0.val[1];
b[5] = e1.val[1];
b[6] = e2.val[1];
b[7] = e3.val[1];
}
void vpx_fdct32x32_neon(const int16_t *input, tran_low_t *output, int stride) {
int16x8_t temp0[32];
int16x8_t temp1[32];
int16x8_t temp2[32];
int16x8_t temp3[32];
int16x8_t temp4[32];
int16x8_t temp5[32];
// Process in 8x32 columns.
load(input, stride, temp0);
dct_body_first_pass(temp0, temp1);
load(input + 8, stride, temp0);
dct_body_first_pass(temp0, temp2);
load(input + 16, stride, temp0);
dct_body_first_pass(temp0, temp3);
load(input + 24, stride, temp0);
dct_body_first_pass(temp0, temp4);
// Generate the top row by munging the first set of 8 from each one together.
transpose_8x8(&temp1[0], &temp0[0]);
transpose_8x8(&temp2[0], &temp0[8]);
transpose_8x8(&temp3[0], &temp0[16]);
transpose_8x8(&temp4[0], &temp0[24]);
dct_body_second_pass(temp0, temp5);
transpose_s16_8x8(&temp5[0], &temp5[1], &temp5[2], &temp5[3], &temp5[4],
&temp5[5], &temp5[6], &temp5[7]);
transpose_s16_8x8(&temp5[8], &temp5[9], &temp5[10], &temp5[11], &temp5[12],
&temp5[13], &temp5[14], &temp5[15]);
transpose_s16_8x8(&temp5[16], &temp5[17], &temp5[18], &temp5[19], &temp5[20],
&temp5[21], &temp5[22], &temp5[23]);
transpose_s16_8x8(&temp5[24], &temp5[25], &temp5[26], &temp5[27], &temp5[28],
&temp5[29], &temp5[30], &temp5[31]);
store(output, temp5);
// Second row of 8x32.
transpose_8x8(&temp1[8], &temp0[0]);
transpose_8x8(&temp2[8], &temp0[8]);
transpose_8x8(&temp3[8], &temp0[16]);
transpose_8x8(&temp4[8], &temp0[24]);
dct_body_second_pass(temp0, temp5);
transpose_s16_8x8(&temp5[0], &temp5[1], &temp5[2], &temp5[3], &temp5[4],
&temp5[5], &temp5[6], &temp5[7]);
transpose_s16_8x8(&temp5[8], &temp5[9], &temp5[10], &temp5[11], &temp5[12],
&temp5[13], &temp5[14], &temp5[15]);
transpose_s16_8x8(&temp5[16], &temp5[17], &temp5[18], &temp5[19], &temp5[20],
&temp5[21], &temp5[22], &temp5[23]);
transpose_s16_8x8(&temp5[24], &temp5[25], &temp5[26], &temp5[27], &temp5[28],
&temp5[29], &temp5[30], &temp5[31]);
store(output + 8 * 32, temp5);
// Third row of 8x32
transpose_8x8(&temp1[16], &temp0[0]);
transpose_8x8(&temp2[16], &temp0[8]);
transpose_8x8(&temp3[16], &temp0[16]);
transpose_8x8(&temp4[16], &temp0[24]);
dct_body_second_pass(temp0, temp5);
transpose_s16_8x8(&temp5[0], &temp5[1], &temp5[2], &temp5[3], &temp5[4],
&temp5[5], &temp5[6], &temp5[7]);
transpose_s16_8x8(&temp5[8], &temp5[9], &temp5[10], &temp5[11], &temp5[12],
&temp5[13], &temp5[14], &temp5[15]);
transpose_s16_8x8(&temp5[16], &temp5[17], &temp5[18], &temp5[19], &temp5[20],
&temp5[21], &temp5[22], &temp5[23]);
transpose_s16_8x8(&temp5[24], &temp5[25], &temp5[26], &temp5[27], &temp5[28],
&temp5[29], &temp5[30], &temp5[31]);
store(output + 16 * 32, temp5);
// Final row of 8x32.
transpose_8x8(&temp1[24], &temp0[0]);
transpose_8x8(&temp2[24], &temp0[8]);
transpose_8x8(&temp3[24], &temp0[16]);
transpose_8x8(&temp4[24], &temp0[24]);
dct_body_second_pass(temp0, temp5);
transpose_s16_8x8(&temp5[0], &temp5[1], &temp5[2], &temp5[3], &temp5[4],
&temp5[5], &temp5[6], &temp5[7]);
transpose_s16_8x8(&temp5[8], &temp5[9], &temp5[10], &temp5[11], &temp5[12],
&temp5[13], &temp5[14], &temp5[15]);
transpose_s16_8x8(&temp5[16], &temp5[17], &temp5[18], &temp5[19], &temp5[20],
&temp5[21], &temp5[22], &temp5[23]);
transpose_s16_8x8(&temp5[24], &temp5[25], &temp5[26], &temp5[27], &temp5[28],
&temp5[29], &temp5[30], &temp5[31]);
store(output + 24 * 32, temp5);
}
void vpx_fdct32x32_rd_neon(const int16_t *input, tran_low_t *output,
int stride) {
int16x8_t temp0[32];
int16x8_t temp1[32];
int16x8_t temp2[32];
int16x8_t temp3[32];
int16x8_t temp4[32];
int16x8_t temp5[32];
// Process in 8x32 columns.
load(input, stride, temp0);
dct_body_first_pass(temp0, temp1);
load(input + 8, stride, temp0);
dct_body_first_pass(temp0, temp2);
load(input + 16, stride, temp0);
dct_body_first_pass(temp0, temp3);
load(input + 24, stride, temp0);
dct_body_first_pass(temp0, temp4);
// Generate the top row by munging the first set of 8 from each one together.
transpose_8x8(&temp1[0], &temp0[0]);
transpose_8x8(&temp2[0], &temp0[8]);
transpose_8x8(&temp3[0], &temp0[16]);
transpose_8x8(&temp4[0], &temp0[24]);
dct_body_second_pass_rd(temp0, temp5);
transpose_s16_8x8(&temp5[0], &temp5[1], &temp5[2], &temp5[3], &temp5[4],
&temp5[5], &temp5[6], &temp5[7]);
transpose_s16_8x8(&temp5[8], &temp5[9], &temp5[10], &temp5[11], &temp5[12],
&temp5[13], &temp5[14], &temp5[15]);
transpose_s16_8x8(&temp5[16], &temp5[17], &temp5[18], &temp5[19], &temp5[20],
&temp5[21], &temp5[22], &temp5[23]);
transpose_s16_8x8(&temp5[24], &temp5[25], &temp5[26], &temp5[27], &temp5[28],
&temp5[29], &temp5[30], &temp5[31]);
store(output, temp5);
// Second row of 8x32.
transpose_8x8(&temp1[8], &temp0[0]);
transpose_8x8(&temp2[8], &temp0[8]);
transpose_8x8(&temp3[8], &temp0[16]);
transpose_8x8(&temp4[8], &temp0[24]);
dct_body_second_pass_rd(temp0, temp5);
transpose_s16_8x8(&temp5[0], &temp5[1], &temp5[2], &temp5[3], &temp5[4],
&temp5[5], &temp5[6], &temp5[7]);
transpose_s16_8x8(&temp5[8], &temp5[9], &temp5[10], &temp5[11], &temp5[12],
&temp5[13], &temp5[14], &temp5[15]);
transpose_s16_8x8(&temp5[16], &temp5[17], &temp5[18], &temp5[19], &temp5[20],
&temp5[21], &temp5[22], &temp5[23]);
transpose_s16_8x8(&temp5[24], &temp5[25], &temp5[26], &temp5[27], &temp5[28],
&temp5[29], &temp5[30], &temp5[31]);
store(output + 8 * 32, temp5);
// Third row of 8x32
transpose_8x8(&temp1[16], &temp0[0]);
transpose_8x8(&temp2[16], &temp0[8]);
transpose_8x8(&temp3[16], &temp0[16]);
transpose_8x8(&temp4[16], &temp0[24]);
dct_body_second_pass_rd(temp0, temp5);
transpose_s16_8x8(&temp5[0], &temp5[1], &temp5[2], &temp5[3], &temp5[4],
&temp5[5], &temp5[6], &temp5[7]);
transpose_s16_8x8(&temp5[8], &temp5[9], &temp5[10], &temp5[11], &temp5[12],
&temp5[13], &temp5[14], &temp5[15]);
transpose_s16_8x8(&temp5[16], &temp5[17], &temp5[18], &temp5[19], &temp5[20],
&temp5[21], &temp5[22], &temp5[23]);
transpose_s16_8x8(&temp5[24], &temp5[25], &temp5[26], &temp5[27], &temp5[28],
&temp5[29], &temp5[30], &temp5[31]);
store(output + 16 * 32, temp5);
// Final row of 8x32.
transpose_8x8(&temp1[24], &temp0[0]);
transpose_8x8(&temp2[24], &temp0[8]);
transpose_8x8(&temp3[24], &temp0[16]);
transpose_8x8(&temp4[24], &temp0[24]);
dct_body_second_pass_rd(temp0, temp5);
transpose_s16_8x8(&temp5[0], &temp5[1], &temp5[2], &temp5[3], &temp5[4],
&temp5[5], &temp5[6], &temp5[7]);
transpose_s16_8x8(&temp5[8], &temp5[9], &temp5[10], &temp5[11], &temp5[12],
&temp5[13], &temp5[14], &temp5[15]);
transpose_s16_8x8(&temp5[16], &temp5[17], &temp5[18], &temp5[19], &temp5[20],
&temp5[21], &temp5[22], &temp5[23]);
transpose_s16_8x8(&temp5[24], &temp5[25], &temp5[26], &temp5[27], &temp5[28],
&temp5[29], &temp5[30], &temp5[31]);
store(output + 24 * 32, temp5);
}
#endif // !defined(__clang__) && !defined(__ANDROID__) && defined(__GNUC__) &&
// __GNUC__ == 4 && __GNUC_MINOR__ <= 9
| 30,400
|
485
|
<filename>indexr-segment/src/benchmark/java/io/indexr/compress/bh/BHCompressBenchmark.java
package io.indexr.compress.bh;
import com.google.common.base.Preconditions;
import com.sun.jna.NativeLibrary;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.spark.unsafe.types.UTF8String;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import io.indexr.io.ByteSlice;
import io.indexr.segment.pack.DataPack;
@State(Scope.Thread)
@Fork(2)
@Measurement(iterations = 5)
@Warmup(iterations = 1)
public class BHCompressBenchmark {
static {
NativeLibrary.addSearchPath("bhcompress", "lib");
}
@Param({"65536"})
public int objCount;
@Param({"1024", "15536"})
public int cardinality;
private byte maxByte = 0;
private ByteSlice byteData;
private ByteSlice byteCmpData;
private short maxShort = 0;
private ByteSlice shortData;
private ByteSlice shortCmpData;
private int maxInt = 0;
private ByteSlice intData;
private ByteSlice intCmpData;
private long maxLong = 0;
private ByteSlice longData;
private ByteSlice longCmpData;
private ByteSlice strData;
private ByteSlice strCmpData;
@Setup(Level.Trial)
public void setup() {
byteData = ByteSlice.allocateDirect(objCount);
shortData = ByteSlice.allocateDirect(objCount << 1);
intData = ByteSlice.allocateDirect(objCount << 2);
longData = ByteSlice.allocateDirect(objCount << 3);
Random random = new Random();
List<UTF8String> uniqueStrs = new ArrayList<>();
for (int i = 0; i < cardinality; i++) {
String string = RandomStringUtils.random(random.nextInt(50));
uniqueStrs.add(UTF8String.fromString(string));
}
List<UTF8String> stringValues = new ArrayList<>();
for (int i = 0; i < objCount; i++) {
byte bv = (byte) random.nextInt(Byte.MAX_VALUE);
byteData.put(i, bv);
maxByte = (byte) Math.max(bv, maxByte);
short sv = (short) random.nextInt(Short.MAX_VALUE);
shortData.putShort(i << 1, sv);
maxShort = (short) Math.max(sv, maxShort);
int iv = random.nextInt(cardinality);
intData.putInt(i << 2, iv);
maxInt = Math.max(iv, maxInt);
long lv = ((long) random.nextInt(cardinality)) << (random.nextBoolean() ? 31 : 0);
longData.putLong(i << 3, lv);
maxLong = Math.max(lv, maxLong);
stringValues.add(uniqueStrs.get(random.nextInt(uniqueStrs.size())));
}
strData = _from_v1(stringValues);
byteCmpData = BHCompressor.compressByte(byteData, objCount, maxByte);
shortCmpData = BHCompressor.compressShort(shortData, objCount, maxShort);
intCmpData = BHCompressor.compressInt(intData, objCount, maxInt);
longCmpData = BHCompressor.compressLong(longData, objCount, maxLong);
strCmpData = BHCompressor.compressIndexedStr_v1(strData, objCount);
}
private static ByteSlice _from_v1(List<UTF8String> strings) {
int size = strings.size();
Preconditions.checkArgument(size > 0 && size <= DataPack.MAX_COUNT);
int strTotalLen = 0;
for (UTF8String s : strings) {
int byteCount = s.numBytes();
strTotalLen += byteCount;
}
int indexLen = (size + 1) << 2;
ByteSlice data = ByteSlice.allocateDirect(indexLen + strTotalLen);
int offset = 0;
for (int i = 0; i < size; i++) {
UTF8String s = strings.get(i);
byte[] bytes = s.getBytes();
int byteLen = bytes.length;
int start = offset;
int end = start + byteLen;
data.putInt(i << 2, start);
data.putInt((i + 1) << 2, end);
data.put(indexLen + start, bytes);
offset = end;
}
return data;
}
@TearDown(Level.Trial)
public void tearDown() {
byteData.free();
byteCmpData.free();
shortData.free();
shortCmpData.free();
intData.free();
intCmpData.free();
longData.free();
longCmpData.free();
}
@Benchmark
public void compressByte() {
BHCompressor.compressByte(byteData, objCount, maxByte).free();
}
@Benchmark
public void decompressByte() {
BHCompressor.decompressByte(byteCmpData, objCount, maxByte).free();
}
@Benchmark
public void compressShort() {
BHCompressor.compressShort(shortData, objCount, maxShort).free();
}
@Benchmark
public void decompressShort() {
BHCompressor.decompressShort(shortCmpData, objCount, maxShort).free();
}
@Benchmark
public void compressInt() {
BHCompressor.compressInt(intData, objCount, maxInt).free();
}
@Benchmark
public void decompressInt() {
BHCompressor.decompressInt(intCmpData, objCount, maxInt).free();
}
@Benchmark
public void compressLong() {
BHCompressor.compressLong(longData, objCount, maxLong).free();
}
@Benchmark
public void decompressLong() {
BHCompressor.decompressLong(longCmpData, objCount, maxLong).free();
}
@Benchmark
public void compressString() {
BHCompressor.compressIndexedStr_v1(strData, objCount).free();
}
@Benchmark
public void decompressString() {
BHCompressor.decompressIndexedStr_v1(strCmpData, objCount).free();
}
public static void main(String[] args) {
BHCompressBenchmark b = new BHCompressBenchmark();
b.objCount = 65536;
b.cardinality = 15536;
b.setup();
b.compressByte();
b.compressShort();
b.compressInt();
b.compressLong();
b.compressString();
b.decompressByte();
b.decompressShort();
b.decompressInt();
b.decompressLong();
b.decompressString();
b.tearDown();
}
}
| 2,830
|
1,144
|
/*****************************************************************************
**
** Name: app_manager.h
**
** Description: Bluetooth Manager application
**
** Copyright (c) 2010-2014, Broadcom Corp., All Rights Reserved.
** Broadcom Bluetooth Core. Proprietary and confidential.
**
*****************************************************************************/
#ifndef __APP_MANAGER_H__
#define __APP_MANAGER_H__
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <glib.h>
#include <wordexp.h>
#include <sys/time.h>
#include <hardware/bt_common.h>
#include <bluetooth/bluetooth.h>
#include "lib/mgmt.h"
#include "shared/mgmt.h"
#include "shared/util.h"
#include "gdbus/gdbus.h"
//#include "client/display.h"
#include "lib/uuid.h"
#include "client/agent.h"
#include "client/gatt.h"
#include "client/advertising.h"
#include "app_common.h"
#include "ble_server.h"
#include "a2dp_sink.h"
#include "a2dp.h"
#define VERSION "bluez-5.48"
DBusConnection *dbus_conn;
typedef int (*connect_fail_cb) (void *userdata, int status);
struct manager_proxy
{
GDBusProxy *agent_manager;
GDBusProxy *GattManager;
struct adapter *default_ctrl;
GDBusProxy *default_dev;
GDBusProxy *default_attr;
};
struct manager_cxt_t
{
bool init;
bool powered;
struct mgmt *mgmt;
GList *ctrl_list;
struct manager_proxy proxy;
int disconnect_completed;
void *caller;
BTDevice default_device;
BT_disc_device discovery_devs[BT_DISC_NB_DEVICES];
char bt_name[249];
bool disc_start;
void *disc_listener_handle;
discovery_cb_t disc_listener;
void *manage_listener_handle;
manage_callbacks_t manage_listener;
A2dpCtx *a2dp_ctx;
A2dpSink *a2dp_sink;
BleServer *ble_ctx;
//HFP_HS *hs_ctx;
pthread_mutex_t mutex;
};
typedef struct manager_cxt_t manager_cxt;
gboolean check_default_ctrl(manager_cxt *manager);
unsigned int send_cmd(struct mgmt *mgmt, uint16_t op, uint16_t id,
uint16_t len, const void *param);
void set_default_attribute(manager_cxt *manager, GDBusProxy *proxy);
void show_devices(manager_cxt *manager);
int get_paired_devices(manager_cxt *manager, BTDevice *dev_array, int arr_len);
int set_remove_device(manager_cxt *manager, const char *addr);
int set_power(manager_cxt *manager, bool on);
int set_pairable(manager_cxt *manager, bool on);
int set_discoverable(manager_cxt *manager, bool on);
int set_scan(manager_cxt *manager, bool start);
int set_pair_device(manager_cxt *manager, const char *addr);
int set_trust_device(manager_cxt *manager, const char *addr, bool trusted);
int connect_addr(manager_cxt *manager, const char *addr);
int connect_addr_array(manager_cxt *manager, BTAddr addr);
int connect_profile_addr_array(manager_cxt *manager, BTAddr addr, const char *uuid, connect_fail_cb cb, void *userdata);
void disconnect_device(manager_cxt *manager, GDBusProxy *proxy);
int disconn_addr(manager_cxt *manager, const char *address);
int disconn_addr_array(manager_cxt *manager, BTAddr addr);
gboolean service_is_child(manager_cxt *manager, GDBusProxy *service);
int set_system_alias(manager_cxt *manager, const char *arg);
int app_get_module_addr(manager_cxt *manager, BTAddr addr);
manager_cxt *manager_create(void);
int manager_init(manager_cxt *manager);
int manager_deinit(manager_cxt *manager);
int manager_destroy(manager_cxt *manager);
int bt_set_visibility(manager_cxt *manager, bool discoverable, bool connectable);
int bt_set_name(manager_cxt *manager, const char *name);
#endif /* __APP_MANAGER_H__ */
| 1,367
|
751
|
/*
* Copyright (c) 2012 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SRC_VPPINFRA_FLOWHASH_8_8_H_
#define SRC_VPPINFRA_FLOWHASH_8_8_H_
#ifdef __included_flowhash_template_h__
#undef __included_flowhash_template_h__
#endif
#include <vppinfra/clib.h>
#include <vppinfra/xxhash.h>
#include <vppinfra/crc32.h>
typedef struct {
u64 as_u64[1];
} flowhash_skey_8_8_t;
typedef struct {
u64 as_u64[1];
} flowhash_lkey_8_8_t;
typedef struct {
u64 as_u64[1];
} flowhash_value_8_8_t;
#define FLOWHASH_TYPE _8_8
#include <vppinfra/flowhash_template.h>
#undef FLOWHASH_TYPE
static_always_inline
u32 flowhash_hash_8_8(flowhash_lkey_8_8_t *k)
{
#ifdef clib_crc32c_uses_intrinsics
return clib_crc32c ((u8 *) &k->as_u64[0], 8);
#else
return clib_xxhash (k->as_u64[0]);
#endif
}
static_always_inline
u8 flowhash_cmp_key_8_8(flowhash_skey_8_8_t *a,
flowhash_lkey_8_8_t *b)
{
return a->as_u64[0] != b->as_u64[0];
}
static_always_inline
void flowhash_cpy_key_8_8(flowhash_skey_8_8_t *dst,
flowhash_lkey_8_8_t *src)
{
dst->as_u64[0] = src->as_u64[0];
}
#endif /* SRC_VPPINFRA_FLOWHASH_8_8_H_ */
| 754
|
825
|
//===--- Mutex.h - Lockables ------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Mutex, Condition, and Scoped lock abstractions for use in Swift runtime.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_RUNTIME_MUTEX_H
#define SWIFT_RUNTIME_MUTEX_H
#if (defined(__APPLE__) || defined(__linux__) || defined(__CYGWIN__) || defined(__FreeBSD__))
#define SWIFT_RUNTIME_MUTEX_HAVE_PHTREADS
#else
#error "Must implement the following if your platform doesn't support phtreads."
#endif
#ifdef SWIFT_RUNTIME_MUTEX_HAVE_PHTREADS
#include <pthread.h>
#endif
namespace swift {
/// A Condition that works with Mutex to allow -- as an example -- multi-threaded
/// producers and consumers to signal each other in a safe way.
class Condition {
friend class MutexImpl;
public:
explicit Condition();
~Condition();
Condition(const Condition &) = delete;
Condition &operator=(const Condition &) = delete;
Condition(Condition &&) = delete;
Condition &operator=(Condition &&) = delete;
public:
/// Notifies one waiter (if any exists) that the condition has been met.
///
/// Note: To avoid missed notification it is best hold the related mutex
// lock when calling notifyOne.
void notifyOne();
/// Notifies all waiters (if any exists) that the condition has been met.
///
/// Note: To avoid missed notification it is best hold the related mutex
// lock when calling notifyAll.
void notifyAll();
private:
#ifdef SWIFT_RUNTIME_MUTEX_HAVE_PHTREADS
pthread_cond_t PThreadCond;
#endif
};
/// Internal (private) implementation of mutex functionality.
/// Use Mutex instead (see below).
class MutexImpl {
friend class Mutex;
public:
MutexImpl() = delete;
~MutexImpl();
MutexImpl(const MutexImpl &) = delete;
MutexImpl &operator=(const MutexImpl &) = delete;
MutexImpl(MutexImpl &&) = delete;
MutexImpl &operator=(MutexImpl &&) = delete;
public:
void lock();
void unlock();
bool try_lock();
void wait(Condition &condition);
private:
explicit MutexImpl(bool checked);
#ifdef SWIFT_RUNTIME_MUTEX_HAVE_PHTREADS
pthread_mutex_t PThreadMutex;
#endif
};
/// Internal (private) implementation of scoped locking functionality.
/// Use ScopedLock instead (see below).
class ScopedLockImpl {
friend class Mutex;
friend class ScopedLock;
public:
ScopedLockImpl() = delete;
~ScopedLockImpl() { Impl.unlock(); }
ScopedLockImpl(const ScopedLockImpl &) = delete;
ScopedLockImpl &operator=(const ScopedLockImpl &) = delete;
ScopedLockImpl(ScopedLockImpl &&) = delete;
ScopedLockImpl &operator=(ScopedLockImpl &&) = delete;
private:
ScopedLockImpl(MutexImpl &impl) : Impl(impl) { Impl.lock(); }
MutexImpl &Impl;
};
/// Internal (private) implementation of scoped unlocking functionality.
/// Use ScopedUnlock instead (see below).
class ScopedUnlockImpl {
friend class Mutex;
friend class ScopedUnlock;
public:
ScopedUnlockImpl() = delete;
~ScopedUnlockImpl() { Impl.lock(); }
ScopedUnlockImpl(const ScopedUnlockImpl &) = delete;
ScopedUnlockImpl &operator=(const ScopedUnlockImpl &) = delete;
ScopedUnlockImpl(ScopedUnlockImpl &&) = delete;
ScopedUnlockImpl &operator=(ScopedUnlockImpl &&) = delete;
private:
ScopedUnlockImpl(MutexImpl &impl) : Impl(impl) { Impl.unlock(); }
MutexImpl &Impl;
};
/// A Mutex object that supports `BasicLockable` and `Lockable` C++ concepts.
/// See http://en.cppreference.com/w/cpp/concept/BasicLockable
/// See http://en.cppreference.com/w/cpp/concept/Lockable
///
/// This is NOT a recursive mutex.
class Mutex {
friend class ScopedLock;
friend class ScopedUnlock;
Mutex(const Mutex &) = delete;
Mutex &operator=(const Mutex &) = delete;
Mutex(Mutex &&) = delete;
Mutex &operator=(Mutex &&) = delete;
public:
/// Constructs a non-recursive mutex.
///
/// If `checked` is true the mutex will attempt to check for misuse and
/// fatalError when detected. If `checked` is false (the default) the
/// mutex will make little to no effort to check for misuse (e.g. efficient).
explicit Mutex(bool checked = false) : Impl(checked) {}
public:
/// The method lock() has the following properties:
/// - Behaves as an atomic operation.
/// - Blocks the calling thread until exclusive ownership of the mutex
/// can be obtained.
/// - Prior m.unlock() operations on the same mutex synchronize-with
/// this lock operation.
/// - The behavior is undefined if the calling thread already owns
/// the mutex (likely a deadlock).
/// - Does not throw exceptions but will halt on error (fatalError).
void lock() { Impl.lock(); }
/// The method unlock() has the following properties:
/// - Behaves as an atomic operation.
/// - Releases the calling thread's ownership of the mutex and
/// synchronizes-with the subsequent successful lock operations on
/// the same object.
/// - The behavior is undefined if the calling thread does not own
/// the mutex.
/// - Does not throw exceptions but will halt on error (fatalError).
void unlock() { Impl.unlock(); }
/// The method lock() has the following properties:
/// - Behaves as an atomic operation.
/// - Attempts to obtain exclusive ownership of the mutex for the calling
/// thread without blocking. If ownership is not obtained, returns
/// immediately. The function is allowed to spuriously fail and return
/// even if the mutex is not currently owned by another thread.
/// - If try_lock() succeeds, prior unlock() operations on the same object
/// synchronize-with this operation. lock() does not synchronize with a
/// failed try_lock()
/// - The behavior is undefined if the calling thread already owns
/// the mutex (likely a deadlock)?
/// - Does not throw exceptions but will halt on error (fatalError).
bool try_lock() { return Impl.try_lock(); }
public:
/// Releases lock, waits on supplied condition, and relocks before returning.
///
/// Precondition: Mutex locked by this thread, undefined otherwise.
void wait(Condition &condition) { Impl.wait(condition); }
public:
/// Acquires lock before calling the supplied critical section and release
/// lock on return from critical section.
///
/// For example the following mutates value while holding the mutex lock.
///
/// mutex.lock([&value] { value++; });
///
/// Precondition: Mutex unlocked by this thread, undefined otherwise.
template <typename CriticalSection>
void lock(CriticalSection criticalSection) {
ScopedLockImpl guard(Impl);
criticalSection();
}
/// Acquires lock before calling the supplied critical section. If critical
/// section returns `true` then it will wait on the supplied condition and
/// call critical section again when wait returns (again holding the lock).
/// If critical section returns `false` it will no longer wait, it will
/// release the lock and return (e.g. lockOrWait returns).
///
/// For example the following will loop waiting on condition until
/// `value > 0`. It will then "consume" that value and stop looping.
/// ...all while being correctly protected by mutex.
///
/// mutex.lockOrWait(condition, [&value] {
/// if (value > 0) {
/// value--;
/// return false;
/// }
/// return true;
/// });
///
/// Precondition: Mutex unlocked by this thread, undefined otherwise.
template <typename CriticalSection>
void lockOrWait(Condition &condition, CriticalSection criticalSection) {
ScopedLockImpl guard(Impl);
while (criticalSection()) {
Impl.wait(condition);
}
}
/// Acquires lock before calling the supplied critical section and on return
/// from critical section it notifies one waiter of supplied condition and
/// then releases the lock.
///
/// For example the following mutates value while holding the mutex lock and
/// then notifies one condition waiter about this change.
///
/// mutex.lockAndNotifyOne([&value] { value++; });
///
/// Precondition: Mutex unlocked by this thread, undefined otherwise.
template <typename CriticalSection>
void lockAndNotifyOne(Condition &condition, CriticalSection criticalSection) {
ScopedLockImpl guard(Impl);
criticalSection();
condition.notifyOne();
}
/// Acquires lock before calling the supplied critical section and on return
/// from critical section it notifies all waiters of supplied condition and
/// then releases the lock.
///
/// For example the following mutates value while holding the mutex lock and
/// then notifies all condition waiters about this change.
///
/// mutex.lockAndNotifyAll([&value] { value++; });
///
/// Precondition: Mutex unlocked by this thread, undefined otherwise.
template <typename CriticalSection>
void lockAndNotifyAll(Condition &condition, CriticalSection criticalSection) {
ScopedLockImpl guard(Impl);
criticalSection();
condition.notifyAll();
}
private:
MutexImpl Impl;
};
/// A stack based object that locks the supplied mutex on construction
/// and unlock it on destruction.
///
/// Precondition: Mutex unlocked by this thread, undefined otherwise.
class ScopedLock : ScopedLockImpl {
public:
explicit ScopedLock(Mutex &mutex) : ScopedLockImpl(mutex.Impl) {}
ScopedLock(const ScopedLock &) = delete;
ScopedLock &operator=(const ScopedLock &) = delete;
ScopedLock(ScopedLock &&) = delete;
ScopedLock &operator=(ScopedLock &&) = delete;
};
/// A stack based object that unlocks the supplied mutex on construction
/// and relocks it on destruction.
///
/// Precondition: Mutex locked by this thread, undefined otherwise.
class ScopedUnlock : ScopedUnlockImpl {
public:
explicit ScopedUnlock(Mutex &mutex) : ScopedUnlockImpl(mutex.Impl) {}
ScopedUnlock(const ScopedUnlock &) = delete;
ScopedUnlock &operator=(const ScopedUnlock &) = delete;
ScopedUnlock(ScopedUnlock &&) = delete;
ScopedUnlock &operator=(ScopedUnlock &&) = delete;
};
}
#endif
| 3,040
|
578
|
// Copyright (c) 2019 <NAME> <EMAIL>
// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.
// This notice and the license may not be removed or altered from any source distribution.
#ifdef TWO_MODULES
module;
#include <gfx/Cpp20.h>
module TWO2(gfx, pbr);
#else
#include <stl/algorithm.h>
#include <pool/ObjectPool.hpp>
#include <math/Math.h>
#include <math/Axes.h>
#include <geom/Geom.hpp>
#include <geom/Intersect.h>
#include <gfx/Item.h>
#include <gfx/Shot.h>
#include <gfx/Frustum.h>
#include <gfx/Camera.h>
#include <gfx/Model.h>
#include <gfx/Program.h>
#include <gfx/Filter.h>
#include <gfx/Pipeline.h>
#include <gfx/Scene.h>
#include <gfx/RenderTarget.h>
#include <gfx/GfxSystem.h>
#include <gfx-pbr/Types.h>
#include <gfx-pbr/Shadow.h>
#include <gfx-pbr/Lighting.h>
#include <gfx-pbr/Gpu/Light.hpp>
#endif
#include <cstdio>
#define DEBUG_ATLAS 0
#define DEBUG_ATLAS_DEPTH 0
#define DEBUG_ATLAS_COLOR 0
namespace two
{
GpuState<GpuShadow> GpuState<GpuShadow>::me;
float snap_step(float value, float step)
{
return std::floor(value / step + 0.5f) * step;
}
vec4 target_rect(const LightShadow& shadow)
{
vec4 rect = shadow.m_rect;
if(bgfx::getCaps()->originBottomLeft)
rect.y = 1.f - rect.y - rect.height;
return rect;
}
vec4 csm_pass_rect(const vec4& atlas_rect, Light& light, size_t pass)
{
vec4 pass_rect = atlas_rect;
if(light.m_shadow_num_splits == 4)
{
pass_rect.width /= 2.f;
pass_rect.height /= 2.f;
pass_rect.x += pass % 2 == 0 ? 0.f : pass_rect.width;
pass_rect.y += pass < 2 ? 0.f : pass_rect.height;
}
else if(light.m_shadow_num_splits == 2)
{
pass_rect.height /= 2.f;
pass_rect.y += pass == 0 ? 0.f : pass_rect.height;
}
return pass_rect;
}
template <class T_Filter>
vector<Item*> filter_cull(Scene& scene, T_Filter filter, bool nofilter = false)
{
vector<Item*> culled;
scene.m_pool->pool<Item>().iterate([&](Item& item) {
if(nofilter || filter(item))
{
culled.push_back(&item);
}
});
return culled;
}
template <class T_Filter>
vector<Item*> frustum_cull(Scene& scene, const Plane6& frustum_planes, T_Filter filter, bool nofilter = false)
{
vector<Item*> culled;
scene.m_pool->pool<Item>().iterate([&](Item& item) {
if(nofilter || filter(item))
{
if(frustum_aabb_intersection(frustum_planes, item.m_aabb))
culled.push_back(&item);
}
});
return culled;
}
void cull_shadow_render(Render& render, vector<Item*>& result, const Plane6& planes)
{
auto filter = [](Item& item) { return item.m_visible && item.m_model->m_geometry[PrimitiveType::Triangles] && (item.m_flags & ItemFlag::Shadows) != 0; };
result = filter_cull(*render.m_scene, filter);
//result = frustum_cull(items, planes, filter);
for(Item* item : result)
item->m_depth = distance(planes.m_near, item->m_aabb.m_center);
}
void cull_shadow_render(Render& render, vector<Item*>& result, const mat4& projection, const mat4& transform)
{
Plane6 planes = frustum_planes(projection, transform);
cull_shadow_render(render, result, planes);
}
#if 0
void BlockShadow::light_shadow_block(Light& light, const uvec4& shadow_rect, const mat4& projection, const mat4& transform)
{
vec4 shadow_tex_rect = vec4(shadow_rect) / float(m_shadow_atlases[0].m_size);
light.m_shadow_blocks.push_back({ shadow_tex_rect, projection, transform, {} });
}
#endif
LightBounds light_slice_bounds(const Frustum& slice, const mat4& light_transform)
{
LightBounds bounds;
for(uint i = 0; i < 8; i++)
{
// Transform to light space.
vec3 corner_light = vec3(light_transform * vec4(slice.m_corners[i], 1.f));
bounds.min = min(bounds.min, corner_light);
bounds.max = max(bounds.max, corner_light);
}
return bounds;
}
void light_slice_sphere_bounds(const FrustumSlice& slice, const mat4& light_transform, LightBounds& light_bounds, float texture_size)
{
float zmax = light_bounds.max.z;
float radius = slice.m_frustum.m_radius * texture_size / (texture_size - 2.f);
vec3 slice_center = vec3(light_transform * vec4(slice.m_frustum.m_center, 0.f));
light_bounds.min = slice_center - radius;
light_bounds.max = slice_center + radius;
light_bounds.max.z = zmax;
}
void light_slice_cull(Render& render, Light& light, LightBounds& light_bounds, vector<Item*>& result)
{
vec3 x = light.m_node->axis(x3);
vec3 y = light.m_node->axis(y3);
vec3 z = light.m_node->axis(z3);
Plane6 light_frustum_planes =
{
{ x, light_bounds.max.x },
{ -x, -light_bounds.min.x },
{ y, light_bounds.max.y },
{ -y, -light_bounds.min.y },
{ z, light_bounds.max.z + 1e6f },
{ -z, -light_bounds.min.z }
};
cull_shadow_render(render, result, light_frustum_planes);
for(Item* item : result)
{
vec2 min_max = project_aabb_in_plane(Plane{ z, 0 }, item->m_aabb);
float z_max = min_max[1];
light_bounds.max.z = max(light_bounds.max.z, z_max);
}
}
void stabilize_light_bounds(const FrustumSlice& slice, LightBounds& light_bounds, float texture_size)
{
float radius = slice.m_frustum.m_radius * texture_size / (texture_size - 2.f);
float unit = radius * 2.0f / texture_size;
light_bounds.max.x = snap_step(light_bounds.max.x, unit);
light_bounds.min.x = snap_step(light_bounds.min.x, unit);
light_bounds.max.y = snap_step(light_bounds.max.y, unit);
light_bounds.min.y = snap_step(light_bounds.min.y, unit);
}
mat4 crop_shrink_light_proj(Light& light, const LightBounds& light_bounds, const mat4& light_proj, float texture_size)
{
vec2 minproj = vec2(bxmulh(light_proj, light_bounds.min));
vec2 maxproj = vec2(bxmulh(light_proj, light_bounds.max));
// total projection scale divided by actual projected bounds
vec2 scale = 2.0f / (maxproj - minproj);
if((light.m_shadow_flags & CSM_Stabilize) != 0)
{
const float quantizer = 64.0f;
scale = quantizer / ceil(quantizer / scale);
}
vec2 offset = 0.5f * (maxproj + minproj) * scale;
if((light.m_shadow_flags & CSM_Stabilize) != 0)
{
const float half_size = texture_size * 0.5f;
offset = ceil(offset * half_size) / half_size;
}
vec4 rect = { offset, scale };
mat4 light_crop = rect_mat(rect);
// in the absence of stabilisation this is roughly equivalent to
// return bxortho(maxproj.x, minproj.x, maxproj.y, minproj.y, -light.m_shadow_range, light.m_shadow_range, 0.0f, bgfx::getCaps()->homogeneousDepth);
return light_proj * light_crop;
}
void update_csm_slice(Render& render, Light& light, const mat4& light_transform, const mat4& light_proj,
CSMSlice& slice, CSMShadow& csm, const vec4& atlas_rect, uint csm_size)
{
slice.m_light = &light;
slice.m_rect = csm_pass_rect(atlas_rect, light, slice.m_index);
slice.m_light_bounds = light_slice_bounds(slice.m_frustum, light_transform);
slice.m_items = render.m_shot.m_items;
light_slice_cull(render, light, slice.m_light_bounds, slice.m_items);
if(false)//light.m_shadow_flags == CSM_Stabilize)
{
const float texture_size = float(slice.m_rect.width);
light_slice_sphere_bounds(slice, light_transform, slice.m_light_bounds, texture_size);
stabilize_light_bounds(slice, slice.m_light_bounds, texture_size);
}
slice.m_proj = crop_shrink_light_proj(light, slice.m_light_bounds, light_proj, float(csm_size));
slice.m_transform = light_transform;
auto* caps = bgfx::getCaps();
mat4 crop_matrix = rect_mat(slice.m_rect) * bias_mat_bgfx(caps->originBottomLeft, caps->homogeneousDepth);
slice.m_shadow_matrix = crop_matrix * slice.m_proj * slice.m_transform;
slice.m_bias_scale = slice.m_index == 0 ? 1.f : slice.m_frustum.m_radius / csm.m_slices[0].m_frustum.m_radius;
slice.m_frustum_slice = slice;
}
void BlockShadow::update_csm(Render& render, Light& light, CSMShadow& csm)
{
csm.m_light = &light;
csm.m_slices.resize(light.m_shadow_num_splits);
vector<FrustumSlice*> slices;
for(CSMSlice& slice : csm.m_slices)
slices.push_back(&slice);
split_frustum_slices(*render.m_camera, slices, light.m_shadow_num_splits, light.m_shadow_split_distribution);
const mat4 light_transform = bxlookat(-light.m_node->direction(), vec3(0.f));
const mat4 light_proj = bxortho(1.0f, -1.0f, 1.0f, -1.0f, -light.m_shadow_range, light.m_shadow_range, 0.0f, bgfx::getCaps()->homogeneousDepth);
const ShadowAtlas::Slot& slot = m_atlas.light_slot(light);
for(size_t i = 0; i < csm.m_slices.size(); ++i)
{
CSMSlice& slice = csm.m_slices[i];
update_csm_slice(render, light, light_transform, light_proj, slice, csm, slot.m_rect, slot.m_trect.width);
slice.m_fbo = &m_atlas.m_fbo;
slice.m_depth_method = depth_method();
//slice.m_depth_method = DepthMethod::DepthPacked;
}
}
void Shadowmap::create(const uvec2& size, DepthMethod method)
{
//*this = {};
m_size = size;
m_depth_method = method;
if(method == DepthMethod::Depth)
{
m_depth = { size, false, TextureFormat::D24S8, BGFX_TEXTURE_RT | TEXTURE_CLAMP | TEXTURE_DEPTH };
m_fbo = { m_depth };
}
else if(method == DepthMethod::Distance
|| method == DepthMethod::DepthPacked)
{
m_color = { size, false, TextureFormat::RGBA8, BGFX_TEXTURE_RT | TEXTURE_CLAMP | TEXTURE_POINT };
m_color.m_is_depth_packed = true;
m_fbo = { m_color };
}
}
void ShadowmapCube::create(uint32_t size)
{
const uint64_t flags = BGFX_TEXTURE_RT | TEXTURE_CLAMP3 | TEXTURE_DEPTH;
if(!bgfx::isTextureValid(0, false, 1, bgfx::TextureFormat::D24S8, flags))
return;
m_size = size;
m_depth = { uvec2(size), false, TextureFormat::D24S8, flags, true };
for(int i = 0; i < 6; i++)
{
bgfx::Attachment attach = { bgfx::Access::Write, m_depth, 0, uint16_t(i), 1, BGFX_RESOLVE_AUTO_GEN_MIPS };
m_fbos[i] = { uvec2(size), m_depth, { attach } };
}
}
BlockShadow::BlockShadow(GfxSystem& gfx, BlockDepth& block_depth, BlockLight& block_light)
: DrawBlock(gfx, type<BlockShadow>())
, m_block_depth(block_depth)
, m_block_light(block_light)
{
m_options = { "SHADOWS", "SHADOWS_PACKED", "SHADOWS_COMPARE" }; // TODO "CSM_BLEND"
m_modes = { "PCF_LEVEL" };
//m_pcf_level = PCF_HARD;
m_pcf_level = PCF_NONE;
}
void BlockShadow::init_block()
{
u_shadow.createUniforms();
GpuState<GpuShadow>::me.init();
}
void BlockShadow::begin_frame(const RenderFrame& frame)
{
m_atlas.begin_frame(frame);
}
void BlockShadow::begin_render(Render& render)
{
UNUSED(render);
for(Light* light : render.m_shot.m_lights)
if(light->m_shadows)
{
if(m_atlas.m_side == 0)
m_atlas = { 1024U, 4U };
m_atlas.render_update(render, *light);
}
this->setup_shadows(render);
#if DEBUG_ATLAS
m_gfx.m_copy->debug_show_texture(render, m_atlas.m_depth, vec4(vec2(0.f), vec2(0.25f)));
m_gfx.m_copy->debug_show_texture(render, m_atlas.m_color, vec4(vec2(0.f, 0.25f), vec2(0.25f)));
//m_gfx.m_copy->debug_show_texture(render, m_atlas.texture(depth_method()), vec4(0.f));
#endif
#if DEBUG_ATLAS_DEPTH
m_gfx.m_copy->debug_show_texture(render, m_atlas.m_depth, vec4(0.f));
#endif
#if DEBUG_ATLAS_COLOR
m_gfx.m_copy->debug_show_texture(render, m_atlas.m_color, vec4(0.f));
#endif
}
void BlockShadow::setup_shadows(Render& render)
{
span<Light*> lights = render.m_shot.m_lights;
lights.m_count = min(lights.m_count, size_t(c_max_forward_lights));
m_csm_shadows.clear();
m_shadows.clear();
for(size_t index = 0; index < lights.size(); ++index)
{
Light& light = *lights[index];
if(!light.m_shadows) continue;
if(light.m_type == LightType::Direct)
{
CSMShadow& csm = push(m_csm_shadows);
if(m_atlas.m_size != uvec2(0U))
this->update_csm(render, light, csm);
}
else if(light.m_type == LightType::Point)
{
if(light.m_shadow_index.slice == UINT8_MAX)
continue;
const ShadowAtlas::Slot& slot = m_atlas.light_slot(light);
const vec4 atlas_rect = slot.m_rect;
const vec2 slot_coord = { atlas_rect.x, atlas_rect.y };
const vec2 slot_size = { atlas_rect.width, atlas_rect.height };
const mat4 projection = bxproj(90.f, 1.f, 0.01f, light.m_range, bgfx::getCaps()->homogeneousDepth);
// These viewports map a cube-map onto a 2D texture with the
// following orientation:
// xzXZ
// y Y
const table<SignedAxis, vec2> offsets =
{
slot_coord + vec2(2.f, 0.f) * slot_size, // positive X
slot_coord + vec2(0.f, 0.f) * slot_size, // negative X
slot_coord + vec2(3.f, 1.f) * slot_size, // positive Y
slot_coord + vec2(1.f, 1.f) * slot_size, // negative Y
slot_coord + vec2(3.f, 0.f) * slot_size, // positive Z
slot_coord + vec2(1.f, 0.f) * slot_size, // negative Z
};
m_block_light.m_gpu_lights[index].shadow.atlas_slot = slot_coord;
m_block_light.m_gpu_lights[index].shadow.atlas_subdiv = slot_size;
for(SignedAxis axis : c_signed_axes)
{
// up stays up for all sides of the cube except when looking down (where it's forward aka -Z) or up (back aka Z)
static const table<SignedAxis, vec3> view_up = { y3, y3, z3, -z3, y3, y3 };
LightShadow& shadow = push(m_shadows);
shadow.m_light = &light;
shadow.m_rect = { offsets[axis], slot_size };
shadow.m_far = light.m_range;
shadow.m_depth_method = DepthMethod::Distance;
const vec3& position = light.m_node->position();
shadow.m_transform = bxlookat(position, position + to_vec3(axis), view_up[axis]);
shadow.m_proj = projection;
//shadow.m_light_bounds =
shadow.m_items = render.m_shot.m_items;
cull_shadow_render(render, shadow.m_items, shadow.m_proj, shadow.m_transform);
shadow.m_fbo = &m_atlas.m_fbo;
shadow.m_shadow_matrix = bxtranslation(-position);
}
}
else if(light.m_type == LightType::Spot)
{
LightShadow& shadow = push(m_shadows);
shadow.m_light = &light;
shadow.m_rect = m_atlas.render_update(render, light);
shadow.m_depth_method = depth_method();
shadow.m_proj = bxproj(light.m_spot_angle * 2.f, 1.f, 0.01f, light.m_range, bgfx::getCaps()->homogeneousDepth);
shadow.m_transform = light.m_node->m_transform;
shadow.m_items = render.m_shot.m_items;
cull_shadow_render(render, shadow.m_items, shadow.m_proj, shadow.m_transform);
shadow.m_fbo = &m_atlas.m_fbo;
shadow.m_shadow_matrix = light.m_node->m_transform;
//m_block_light.m_gpu_shadows[index].matrix = m_shadows.size() - 1;
}
}
}
void BlockShadow::commit_shadows(Render& render, const mat4& view)
{
UNUSED(render);
const mat4 inverse_view = inverse(view);
size_t index = 0;
m_shadow_matrices.resize(m_csm_shadows.size() * 4 + m_shadows.size());
for(const CSMShadow& csm : m_csm_shadows)
{
uint32_t i = 0;
for(const CSMSlice& slice : csm.m_slices)
{
GpuCSMShadow& gpu = m_block_light.m_gpu_lights[slice.m_light->m_index].csm;
m_shadow_matrices[index] = slice.m_shadow_matrix * inverse_view;
gpu.num_slices = slice.m_light->m_shadow_num_splits;
gpu.matrices[i] = float(index);
gpu.splits[i] = slice.m_frustum.m_far;
index++; i++;
}
}
for(const LightShadow& shadow : m_shadows)
{
GpuShadow& gpu = m_block_light.m_gpu_lights[shadow.m_light->m_index].shadow;
m_shadow_matrices[index] = shadow.m_shadow_matrix * inverse_view;
gpu.matrix = float(index);
gpu.bias = shadow.m_light->m_shadow_bias;
gpu.radius = 1.f;
gpu.range = shadow.m_far;
index++;
}
m_block_light.upload_lights(render);
}
void BlockShadow::upload_shadows(Render& render, const Pass& pass) const
{
UNUSED(render);
GpuState<GpuShadow>::me.upload(pass, const_cast<BlockShadow*>(this)->m_shadow_matrices);
}
void BlockShadow::options(Render& render, const DrawElement& element, ProgramVersion& program) const
{
UNUSED(render); UNUSED(element);
bool shadow_sampler = SHADOW_SAMPLER; // m_pcf_level != PCF_HARD
program.set_mode(m_index, PCF_LEVEL, uint8_t(m_pcf_level));
const bool shadows = !m_csm_shadows.empty() || !m_shadows.empty();
program.set_option(m_index, SHADOWS, shadows);
program.set_option(m_index, SHADOWS_COMPARE, shadow_sampler);
if (shadows)
{
DepthMethod depth_method;
if (!m_shadows.empty())
depth_method = m_shadows[0].m_depth_method;
else if (!m_csm_shadows.empty())
depth_method = m_csm_shadows[0].m_slices[0].m_depth_method;
const bool shadows_packed = depth_method == DepthMethod::DepthPacked
|| depth_method == DepthMethod::Distance;
program.set_option(m_index, SHADOWS_PACKED, shadows_packed);
//program.set_option(m_index, CSM_BLEND, light->m_shadow_blend_splits);
}
}
void BlockShadow::submit(Render& render, const Pass& pass) const
{
UNUSED(render);
this->upload_shadows(render, pass);
uint32_t shadow_atlas = uint32_t(TextureSampler::Shadow);
bgfx::setViewUniform(pass.m_index, u_shadow.s_shadow_atlas, &shadow_atlas);
if(true) //direct && light->m_shadows)
{
vec4 csm_p0 = { 1.f / vec2(m_atlas.m_size), vec2(0.f) };
bgfx::setViewUniform(pass.m_index, u_shadow.u_csm_p0, &csm_p0);
vec2 pcf_offset = { 1.f, 1.f };
vec4 pcf_p0 = { pcf_offset, vec2(0.f) };
bgfx::setViewUniform(pass.m_index, u_shadow.u_pcf_p0, &pcf_p0);
}
if(!m_shadows.empty())
{
vec4 atlas_p0 = { vec2(m_atlas.m_size), vec2(1.f) / float(m_atlas.m_side) };
bgfx::setViewUniform(pass.m_index, u_shadow.u_shadow_atlas, &atlas_p0);
}
}
void BlockShadow::submit(Render& render, const DrawElement& element, const Pass& pass) const
{
UNUSED(render); UNUSED(element); UNUSED(pass);
bgfx::Encoder& encoder = *pass.m_encoder;
bool shadow_sampler = SHADOW_SAMPLER; // m_pcf_level != PCF_HARD
uint32_t shadow_flags = shadow_sampler ? BGFX_SAMPLER_COMPARE_LESS : TEXTURE_POINT;
// @todo for now normal shadows and direct shadows are incompatible because we use color for the former and depth for the latter
// we should be able to switch the distance shader to write to the depth buffer
if(!m_shadows.empty())
{
DepthMethod depth_method = m_shadows[0].m_depth_method;
encoder.setTexture(uint8_t(TextureSampler::Shadow), m_atlas.texture(depth_method), shadow_flags);
}
if(!m_csm_shadows.empty())
{
DepthMethod depth_method = m_csm_shadows[0].m_slices[0].m_depth_method;
encoder.setTexture(uint8_t(TextureSampler::Shadow), m_atlas.texture(depth_method), shadow_flags);
}
}
void pass_shadowmaps(GfxSystem& gfx, Render& render)
{
static BlockShadow& block_shadow = *gfx.m_renderer.block<BlockShadow>();
auto setup_block = [&](Light& light, DepthMethod depth_method, float bias_scale = 1.f)
{
block_shadow.m_depth_method = depth_method;
block_shadow.m_distance_params.m_eye = light.m_node->position();
block_shadow.m_distance_params.m_near = 0.01f;
block_shadow.m_distance_params.m_far = light.m_range;
block_shadow.m_depth_params.m_depth_bias = light.m_shadow_bias * bias_scale;
block_shadow.m_depth_params.m_depth_normal_bias = light.m_shadow_normal_bias;
block_shadow.m_depth_params.m_depth_z_far = light.m_shadow_range;
};
auto render_shadow = [&](LightShadow& shadow, const vec4& rect)
{
Camera camera = Camera(shadow.m_transform, shadow.m_proj);
Viewport viewport = Viewport(camera, *render.m_scene, rect);
Render shadow_render = { Shading::Volume, viewport, *render.m_target, *shadow.m_fbo, *render.m_frame };
shadow_render.m_shot.m_lights = render.m_shot.m_lights;
shadow_render.m_shot.m_items = shadow.m_items;
setup_block(*shadow.m_light, shadow.m_depth_method, shadow.m_bias_scale);
RenderFunc renderer = gfx.renderer(Shading::Volume);
gfx.m_renderer.subrender(render, shadow_render, renderer);
};
for(CSMShadow& csm : block_shadow.m_csm_shadows)
{
if(!block_shadow.m_atlas.m_fbo.valid())
continue;
for(LightShadow& slice : csm.m_slices)
render_shadow(slice, target_rect(slice));
}
for(LightShadow& shadow : block_shadow.m_shadows)
{
render_shadow(shadow, shadow.m_rect);
}
}
void pass_shadow(GfxSystem& gfx, Render& render)
{
static BlockDepth& block_depth = *gfx.m_renderer.block<BlockDepth>();
static BlockShadow& block_shadow = *gfx.m_renderer.block<BlockShadow>();
Pass pass = render.next_pass("shadow", PassType::Shadow);
block_depth.m_depth_method = block_shadow.m_depth_method;
block_depth.m_depth_params = block_shadow.m_depth_params;
block_depth.m_distance_params = block_shadow.m_distance_params;
block_depth.submit(render, pass);
//block_shadow.submit(render, pass);
pass_depth(gfx, render, pass, false);
auto queue_draw_element = [](GfxSystem& gfx, Render& render, Pass& pass, DrawElement& element)
{
const Program& program = *element.m_program.m_program;
if(!program.m_blocks[MaterialBlock::Lit] || element.m_material->m_alpha.m_is_alpha)
return false;
return queue_depth(gfx, render, pass, element);
};
gfx.m_renderer.pass(render, pass, queue_draw_element);
}
}
| 8,982
|
3,508
|
<gh_stars>1000+
package com.fishercoder;
import com.fishercoder.solutions._1243;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import static junit.framework.TestCase.assertTrue;
public class _1243Test {
private static _1243.Solution1 solution1;
private static int[] arr;
@BeforeClass
public static void setup() {
solution1 = new _1243.Solution1();
}
@Test
public void test1() {
arr = new int[]{6, 2, 3, 4};
assertTrue(solution1.transformArray(arr).equals(Arrays.asList(6, 3, 3, 4)));
}
@Test
public void test2() {
arr = new int[]{1, 6, 3, 4, 3, 5};
assertTrue(solution1.transformArray(arr).equals(Arrays.asList(1, 4, 4, 4, 4, 5)));
}
}
| 324
|
684
|
<filename>examples/TestInRange.cpp
#include <deepstate/DeepState.hpp>
#include <cmath>
using namespace deepstate;
using namespace std;
TEST(DeepState, RangeAPIs) {
int v, low, high, mv;
char cv, clow, chigh;
double dv, dlow, dhigh;
low = DeepState_Int();
high = DeepState_Int();
if (low > high) {
int temp = low;
low = high;
high = temp;
}
v = DeepState_IntInRange(low, high);
LOG(TRACE) << "low = " << low << ", high = " << high << ", v = " << v;
ASSERT ((low <= v) && (v <= high)) << "low = " << low << ", high = " << high << ", v = " << v;
clow = DeepState_Char();
chigh = DeepState_Char();
if (clow > chigh) {
char temp = clow;
clow = chigh;
chigh = temp;
}
cv = DeepState_CharInRange(clow, chigh);
LOG(TRACE) << "clow = " << clow << ", chigh = " << chigh << ", cv = " << cv;
ASSERT ((clow <= cv) && (cv <= chigh)) << "clow = " << clow << ", chigh = " << chigh << " cv = " << cv;
mv = DeepState_IntInRange(2, 45);
ASSIGN_SATISFYING(v, DeepState_Int(), (v % mv) == 0);
ASSERT ((v % mv) == 0) << "mv = " << mv << ", v = " << v;
dlow = DeepState_Double();
assume(!isnan(dlow));
dhigh = DeepState_Double();
assume(!isnan(dhigh));
if (dlow > dhigh) {
double temp = dlow;
dlow = dhigh;
dhigh = temp;
}
dv = DeepState_DoubleInRange(dlow, dhigh);
assume(!isnan(v));
LOG(TRACE) << "dlow = " << dlow << ", dhigh = " << dhigh << ", dv = " << dv;
ASSERT ((dlow <= dv) && (dv <= dhigh)) << "dlow = " << dlow << ", dhigh = " << dhigh << " dv = " << dv;
low = DeepState_Int();
high = DeepState_Int();
if (low > high) {
int temp = low;
low = high;
high = temp;
}
mv = DeepState_IntInRange(2, 45);
LOG(TRACE) << "low = " << low << ", high = " << high << ", mv = " << mv;
ASSIGN_SATISFYING_IN_RANGE(v, DeepState_IntInRange(low, high), low, high, (v % mv) == 0);
LOG(TRACE) << "v = " << v;
ASSERT ((v % mv) == 0) << "v = " << v << ", mv = " << mv;
ASSERT ((low <= v) && (v <= high)) << "low = " << low << ", high = " << high << " v = " << v;
}
| 889
|
375
|
package io.lumify.web.routes.vertex;
import com.google.inject.Inject;
import io.lumify.core.config.Configuration;
import io.lumify.core.ingest.ArtifactDetectedObject;
import io.lumify.core.model.SourceInfo;
import io.lumify.core.model.audit.AuditAction;
import io.lumify.core.model.audit.AuditRepository;
import io.lumify.core.model.ontology.Concept;
import io.lumify.core.model.ontology.OntologyRepository;
import io.lumify.core.model.properties.LumifyProperties;
import io.lumify.core.model.termMention.TermMentionRepository;
import io.lumify.core.model.user.UserRepository;
import io.lumify.core.model.workQueue.WorkQueueRepository;
import io.lumify.core.model.workspace.Workspace;
import io.lumify.core.model.workspace.WorkspaceRepository;
import io.lumify.core.security.LumifyVisibility;
import io.lumify.core.security.VisibilityTranslator;
import io.lumify.core.user.User;
import io.lumify.core.util.ClientApiConverter;
import io.lumify.core.util.GraphUtil;
import io.lumify.core.util.LumifyLogger;
import io.lumify.core.util.LumifyLoggerFactory;
import io.lumify.miniweb.HandlerChain;
import io.lumify.web.BaseRequestHandler;
import io.lumify.web.clientapi.model.ClientApiElement;
import io.lumify.web.clientapi.model.VisibilityJson;
import org.securegraph.*;
import org.securegraph.mutation.ElementMutation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ResolveDetectedObject extends BaseRequestHandler {
private static final LumifyLogger LOGGER = LumifyLoggerFactory.getLogger(ResolveDetectedObject.class);
private static final String MULTI_VALUE_KEY_PREFIX = ResolveDetectedObject.class.getName();
private final Graph graph;
private final AuditRepository auditRepository;
private final OntologyRepository ontologyRepository;
private final WorkQueueRepository workQueueRepository;
private final VisibilityTranslator visibilityTranslator;
private final WorkspaceRepository workspaceRepository;
private final TermMentionRepository termMentionRepository;
private String artifactContainsImageOfEntityIri;
@Inject
public ResolveDetectedObject(
final Graph graphRepository,
final AuditRepository auditRepository,
final OntologyRepository ontologyRepository,
final UserRepository userRepository,
final Configuration configuration,
final WorkQueueRepository workQueueRepository,
final VisibilityTranslator visibilityTranslator,
final WorkspaceRepository workspaceRepository,
final TermMentionRepository termMentionRepository
) {
super(userRepository, workspaceRepository, configuration);
this.graph = graphRepository;
this.auditRepository = auditRepository;
this.ontologyRepository = ontologyRepository;
this.workQueueRepository = workQueueRepository;
this.visibilityTranslator = visibilityTranslator;
this.workspaceRepository = workspaceRepository;
this.termMentionRepository = termMentionRepository;
this.artifactContainsImageOfEntityIri = ontologyRepository.getRelationshipIRIByIntent("artifactContainsImageOfEntity");
if (this.artifactContainsImageOfEntityIri == null) {
LOGGER.warn("'artifactContainsImageOfEntity' intent has not been defined. Please update your ontology.");
}
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception {
if (this.artifactContainsImageOfEntityIri == null) {
this.artifactContainsImageOfEntityIri = ontologyRepository.getRequiredRelationshipIRIByIntent("artifactContainsImageOfEntity");
}
final String artifactId = getRequiredParameter(request, "artifactId");
final String title = getRequiredParameter(request, "title");
final String conceptId = getRequiredParameter(request, "conceptId");
final String visibilitySource = getRequiredParameter(request, "visibilitySource");
final String graphVertexId = getOptionalParameter(request, "graphVertexId");
final String justificationText = getOptionalParameter(request, "justificationText");
final String sourceInfoString = getOptionalParameter(request, "sourceInfo");
String originalPropertyKey = getOptionalParameter(request, "originalPropertyKey");
double x1 = Double.parseDouble(getRequiredParameter(request, "x1"));
double x2 = Double.parseDouble(getRequiredParameter(request, "x2"));
double y1 = Double.parseDouble(getRequiredParameter(request, "y1"));
double y2 = Double.parseDouble(getRequiredParameter(request, "y2"));
User user = getUser(request);
String workspaceId = getActiveWorkspaceId(request);
Workspace workspace = workspaceRepository.findById(workspaceId, user);
Authorizations authorizations = getAuthorizations(request, user);
if (!graph.isVisibilityValid(new Visibility(visibilitySource), authorizations)) {
LOGGER.warn("%s is not a valid visibility for %s user", visibilitySource, user.getDisplayName());
respondWithBadRequest(response, "visibilitySource", getString(request, "visibility.invalid"));
chain.next(request, response);
return;
}
VisibilityJson visibilityJson = GraphUtil.updateVisibilitySourceAndAddWorkspaceId(null, visibilitySource, workspaceId);
LumifyVisibility lumifyVisibility = visibilityTranslator.toVisibility(visibilityJson);
Concept concept = ontologyRepository.getConceptByIRI(conceptId);
Vertex artifactVertex = graph.getVertex(artifactId, authorizations);
ElementMutation<Vertex> resolvedVertexMutation;
Metadata metadata = new Metadata();
LumifyProperties.VISIBILITY_JSON.setMetadata(metadata, visibilityJson, visibilityTranslator.getDefaultVisibility());
Vertex resolvedVertex;
if (graphVertexId == null || graphVertexId.equals("")) {
resolvedVertexMutation = graph.prepareVertex(lumifyVisibility.getVisibility());
LumifyProperties.CONCEPT_TYPE.setProperty(resolvedVertexMutation, concept.getIRI(), metadata, lumifyVisibility.getVisibility());
LumifyProperties.TITLE.setProperty(resolvedVertexMutation, title, metadata, lumifyVisibility.getVisibility());
resolvedVertex = resolvedVertexMutation.save(authorizations);
auditRepository.auditVertexElementMutation(AuditAction.UPDATE, resolvedVertexMutation, resolvedVertex, "", user, lumifyVisibility.getVisibility());
SourceInfo sourceInfo = SourceInfo.fromString(sourceInfoString);
termMentionRepository.addJustification(resolvedVertex, justificationText, sourceInfo, lumifyVisibility, authorizations);
resolvedVertex = resolvedVertexMutation.save(authorizations);
auditRepository.auditVertexElementMutation(AuditAction.UPDATE, resolvedVertexMutation, resolvedVertex, "", user, lumifyVisibility.getVisibility());
LumifyProperties.VISIBILITY_JSON.setProperty(resolvedVertexMutation, visibilityJson, metadata, lumifyVisibility.getVisibility());
graph.flush();
workspaceRepository.updateEntityOnWorkspace(workspace, resolvedVertex.getId(), null, null, user);
} else {
resolvedVertex = graph.getVertex(graphVertexId, authorizations);
resolvedVertexMutation = resolvedVertex.prepareMutation();
}
Edge edge = graph.addEdge(artifactVertex, resolvedVertex, artifactContainsImageOfEntityIri, lumifyVisibility.getVisibility(), authorizations);
LumifyProperties.VISIBILITY_JSON.setProperty(edge, visibilityJson, metadata, lumifyVisibility.getVisibility(), authorizations);
auditRepository.auditRelationship(AuditAction.CREATE, artifactVertex, resolvedVertex, edge, "", "", user, lumifyVisibility.getVisibility());
ArtifactDetectedObject artifactDetectedObject = new ArtifactDetectedObject(
x1,
y1,
x2,
y2,
concept.getIRI(),
"user",
edge.getId(),
resolvedVertex.getId(),
originalPropertyKey);
String propertyKey = artifactDetectedObject.getMultivalueKey(MULTI_VALUE_KEY_PREFIX);
LumifyProperties.DETECTED_OBJECT.addPropertyValue(artifactVertex, propertyKey, artifactDetectedObject, lumifyVisibility.getVisibility(), authorizations);
resolvedVertexMutation.addPropertyValue(resolvedVertex.getId(), LumifyProperties.ROW_KEY.getPropertyName(), propertyKey, lumifyVisibility.getVisibility());
resolvedVertexMutation.save(authorizations);
graph.flush();
workQueueRepository.pushElement(edge);
workQueueRepository.pushGraphPropertyQueue(artifactVertex, propertyKey, LumifyProperties.DETECTED_OBJECT.getPropertyName());
ClientApiElement result = ClientApiConverter.toClientApi(artifactVertex, workspaceId, authorizations);
respondWithClientApiObject(response, result);
}
}
| 3,239
|
480
|
import unittest
from nlu import *
class TestSentiment(unittest.TestCase):
def test_sentiment_model(self):
pipe = nlu.load('sentiment',verbose=True)
df = pipe.predict(['I love pancaces. I hate Mondays', 'I love Fridays'], output_level='document',drop_irrelevant_cols=False, metadata=True, )
for c in df.columns: print(df[c])
def test_sentiment_detector_model(self):
pipe = nlu.load('sentiment.imdb',verbose=True)
df = pipe.predict(['I love pancaces. I hate Mondays', 'I love Fridays'], output_level='sentence')
for c in df.columns: print(df[c])
df = pipe.predict(['I love pancaces. I hate Mondays', 'I love Fridays'], output_level='document')
for c in df.columns: print(df[c])
def test_sentiment_vivk_model(self):
pipe = nlu.load('sentiment.vivekn',verbose=True)
df = pipe.predict(['I love pancaces. I hate Mondays', 'I love Fridays'], output_level='sentence')
print(df.columns)
for c in df.columns: print(df[c])
df = pipe.predict(['I love pancaces. I hate Mondays', 'I love Fridays'], output_level='document')
for c in df.columns: print(df[c])
if __name__ == '__main__':
unittest.main()
| 501
|
386
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2013, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#ifndef IECOREGL_RENDERERIMPLEMENTATION_H
#define IECOREGL_RENDERERIMPLEMENTATION_H
#include "IECoreGL/TypeIds.h"
#include "IECoreScene/Renderer.h"
#include "IECore/Data.h"
#include "IECore/Export.h"
#include "IECore/InternedString.h"
#include "IECore/RunTimeTyped.h"
IECORE_PUSH_DEFAULT_VISIBILITY
#include "OpenEXR/ImathMatrix.h"
IECORE_POP_DEFAULT_VISIBILITY
namespace IECoreGL
{
IE_CORE_FORWARDDECLARE( StateComponent );
IE_CORE_FORWARDDECLARE( Primitive );
IE_CORE_FORWARDDECLARE( Camera );
IE_CORE_FORWARDDECLARE( Display );
IE_CORE_FORWARDDECLARE( Group );
/// RendererImplementation classes are used by the Renderer
/// class to do some of it's work.
class RendererImplementation : public IECore::RunTimeTyped
{
public :
IE_CORE_DECLARERUNTIMETYPEDEXTENSION( RendererImplementation, RendererImplementationTypeId, IECore::RunTimeTyped )
RendererImplementation();
~RendererImplementation() override;
/// Guaranteed to be called at least once before worldBegin(),
/// and never after worldBegin().
virtual void addCamera( CameraPtr camera ) = 0;
/// Never called after worldBegin().
virtual void addDisplay( ConstDisplayPtr display ) = 0;
virtual void worldBegin() = 0;
virtual void worldEnd() = 0;
/// Transform calls guaranteed only to be called after worldBegin().
virtual void transformBegin() = 0;
virtual void transformEnd() = 0;
virtual void setTransform( const Imath::M44f &m ) = 0;
virtual Imath::M44f getTransform() const = 0;
virtual void concatTransform( const Imath::M44f &matrix ) = 0;
virtual void attributeBegin() = 0;
virtual void attributeEnd() = 0;
virtual void addState( StateComponentPtr state ) = 0;
virtual StateComponent *getState( IECore::TypeId type ) = 0;
template <class T>
T *getState();
// Set a custom state
virtual void addUserAttribute( const IECore::InternedString &name, IECore::DataPtr value ) = 0;
// Get a custom state or 0 if not defined.
virtual IECore::Data *getUserAttribute( const IECore::InternedString &name ) = 0;
// Get a casted custom state or 0 if not present or incompatible type.
template <class T>
T *getUserAttribute( const IECore::InternedString &name );
virtual void addPrimitive( ConstPrimitivePtr primitive ) = 0;
virtual void addProcedural( IECoreScene::Renderer::ProceduralPtr proc, IECoreScene::RendererPtr renderer ) = 0;
virtual void addInstance( IECoreGL::GroupPtr grp ) = 0;
};
IE_CORE_DECLAREPTR( RendererImplementation );
} // namespace IECoreGL
#include "IECoreGL/private/RendererImplementation.inl"
#endif // IECOREGL_RENDERERIMPLEMENTATION_H
| 1,404
|
317
|
<gh_stars>100-1000
#ifndef EDYN_COMP_GRAVITY_HPP
#define EDYN_COMP_GRAVITY_HPP
#include "edyn/math/vector3.hpp"
namespace edyn {
struct gravity : public vector3 {
gravity & operator=(const vector3 &v) {
vector3::operator=(v);
return *this;
}
};
}
#endif // EDYN_COMP_GRAVITY_HPP
| 144
|
5,279
|
<reponame>charithe/beam
/*
* 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.beam.sdk.transforms;
import java.io.Serializable;
/**
* A function that computes an output value of type {@code OutputT} from an input value of type
* {@code InputT}, is {@link Serializable}, and does not allow checked exceptions to be declared.
*
* <p>To allow checked exceptions, implement the superinterface {@link ProcessFunction} instead. To
* allow more robust {@link org.apache.beam.sdk.coders.Coder Coder} inference, see {@link
* InferableFunction}.
*
* @param <InputT> input value type
* @param <OutputT> output value type
*/
@FunctionalInterface
public interface SerializableFunction<InputT, OutputT>
extends ProcessFunction<InputT, OutputT>, Serializable {
/** Returns the result of invoking this function on the given input. */
@Override
OutputT apply(InputT input);
}
| 437
|
742
|
/*
* Copyright (C) 2008, <NAME> and <NAME>, Inc.
*
* 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 names of Stanford University or <NAME>, Inc. 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.
*/
#ifndef ROSCPP_SUBSCRIBER_LINK_H
#define ROSCPP_SUBSCRIBER_LINK_H
#include "ros/common.h"
#include <boost/thread/mutex.hpp>
#include <boost/shared_array.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <queue>
namespace ros
{
class Header;
class Message;
class Publication;
typedef boost::shared_ptr<Publication> PublicationPtr;
typedef boost::weak_ptr<Publication> PublicationWPtr;
class Connection;
typedef boost::shared_ptr<Connection> ConnectionPtr;
class ROSCPP_DECL SubscriberLink : public boost::enable_shared_from_this<SubscriberLink>
{
public:
class Stats
{
public:
uint64_t bytes_sent_, message_data_sent_, messages_sent_;
Stats()
: bytes_sent_(0), message_data_sent_(0), messages_sent_(0) { }
};
SubscriberLink();
virtual ~SubscriberLink();
const std::string& getTopic() const { return topic_; }
const Stats &getStats() { return stats_; }
const std::string &getDestinationCallerID() const { return destination_caller_id_; }
int getConnectionID() const { return connection_id_; }
/**
* \brief Queue up a message for publication. Throws out old messages if we've reached our Publication's max queue size
*/
virtual void enqueueMessage(const SerializedMessage& m, bool ser, bool nocopy) = 0;
virtual void drop() = 0;
virtual const ConnectionPtr& getConnection() = 0;
virtual std::string getTransportType() = 0;
virtual std::string getTransportInfo() = 0;
virtual bool isIntraprocess() { return false; }
virtual void getPublishTypes(bool& ser, bool& nocopy, const std::type_info& ti) { (void)ti; ser = true; nocopy = false; }
const std::string& getMD5Sum();
const std::string& getDataType();
const std::string& getMessageDefinition();
void setDefaultTransport(bool default_transport);
bool getDefaultTransport();
void setRospy(bool rospy);
bool getRospy ();
protected:
bool verifyDatatype(const std::string &datatype);
PublicationWPtr parent_;
unsigned int connection_id_;
std::string destination_caller_id_;
Stats stats_;
std::string topic_;
bool default_transport_ ;
bool rospy_;
};
} // namespace ros
#endif // ROSCPP_SUBSCRIBER_LINK_H
| 1,188
|
2,577
|
<gh_stars>1000+
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.test.bpmn.scripttask;
import static org.junit.Assert.fail;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.test.util.PluggableProcessEngineTest;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.junit.After;
public abstract class AbstractScriptTaskTest extends PluggableProcessEngineTest {
private List<String> deploymentIds = new ArrayList<>();
@After
public void tearDown() throws Exception {
deploymentIds.forEach(deploymentId -> repositoryService.deleteDeployment(deploymentId, true));
}
protected void deployProcess(BpmnModelInstance process) {
Deployment deployment = repositoryService.createDeployment()
.addModelInstance("testProcess.bpmn", process)
.deploy();
deploymentIds.add(deployment.getId());
}
protected void deployProcess(String scriptFormat, String scriptText) {
BpmnModelInstance process = createProcess(scriptFormat, scriptText);
deployProcess(process);
}
protected BpmnModelInstance createProcess(String scriptFormat, String scriptText) {
return Bpmn.createExecutableProcess("testProcess")
.startEvent()
.scriptTask()
.scriptFormat(scriptFormat)
.scriptText(scriptText)
.userTask()
.endEvent()
.done();
}
protected String getNormalizedResourcePath(String classPathResource) {
try {
return Paths.get(getClass().getResource(classPathResource).toURI()).toString().replace('\\', '/');
} catch (Exception e) {
fail("Cannot read path of '" + classPathResource + "': " + e.getMessage());
return null;
}
}
}
| 808
|
2,637
|
/*
* Copyright 2017 NXP
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o 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 "fsl_spifi.h"
#include "mflash_drv.h"
#include "pin_mux.h"
#include <stdbool.h>
/* Command ID */
#define COMMAND_NUM (6)
#define READ (0)
#define PROGRAM_PAGE (1)
#define GET_STATUS (2)
#define ERASE_SECTOR (3)
#define WRITE_ENABLE (4)
#define WRITE_REGISTER (5)
//#ifdef XIP_IMAGE
//#warning NOTE: MFLASH driver expects that application runs from XIP
//#else
//#warning NOTE: MFLASH driver expects that application runs from SRAM
//#endif
#if !defined(FLASHDRV_SMART_UPDATE) && (MFLASH_SECTOR_SIZE / MFLASH_PAGE_SIZE <= 32)
#define FLASHDRV_SMART_UPDATE 1
#endif
/* Temporary sector storage. Use uint32_t type to force 4B alignment and
* improve copy operation */
static uint32_t g_flashm_sector[MFLASH_SECTOR_SIZE / sizeof(uint32_t)];
/* Commands definition, taken from SPIFI demo */
static spifi_command_t command[COMMAND_NUM] = {
/* read */
{MFLASH_PAGE_SIZE, false, kSPIFI_DataInput, 1, kSPIFI_CommandAllSerial, kSPIFI_CommandOpcodeAddrThreeBytes, 0x0B},
/* program */
{MFLASH_PAGE_SIZE, false, kSPIFI_DataOutput, 0, kSPIFI_CommandAllSerial, kSPIFI_CommandOpcodeAddrThreeBytes, 0x2},
/* status */
{1, false, kSPIFI_DataInput, 0, kSPIFI_CommandAllSerial, kSPIFI_CommandOpcodeOnly, 0x05},
/* erase */
{0, false, kSPIFI_DataOutput, 0, kSPIFI_CommandAllSerial, kSPIFI_CommandOpcodeAddrThreeBytes, 0x20},
/* write enable */
{0, false, kSPIFI_DataOutput, 0, kSPIFI_CommandAllSerial, kSPIFI_CommandOpcodeOnly, 0x06},
/* write register */
{4, false, kSPIFI_DataOutput, 0, kSPIFI_CommandAllSerial, kSPIFI_CommandOpcodeOnly, 0x01}
};
/* Wait until command finishes */
static inline void mflash_drv_check_if_finish(void)
{
uint8_t val = 0;
do
{
SPIFI_SetCommand(MFLASH_SPIFI, &command[GET_STATUS]);
while ((MFLASH_SPIFI->STAT & SPIFI_STAT_INTRQ_MASK) == 0U)
{
}
val = SPIFI_ReadDataByte(MFLASH_SPIFI);
} while (val & 0x1);
}
/* return offset from sector */
static void mflash_drv_read_mode(void)
{
/* Switch back to read mode */
SPIFI_ResetCommand(MFLASH_SPIFI);
SPIFI_SetMemoryCommand(MFLASH_SPIFI, &command[READ]);
}
/* Initialize SPIFI & flash peripheral,
* cannot be invoked directly, requires calling wrapper in non XIP memory */
static int32_t mflash_drv_init_internal(void)
{
/* NOTE: Multithread access is not supported for SRAM target.
* XIP target MUST be protected by disabling global interrupts
* since all ISR (and API that is used inside) is placed at XIP.
* It is necessary to place at least "mflash_drv_drv.o", "fsl_spifi.o" to SRAM */
/* disable interrupts when running from XIP
* TODO: store/restore previous PRIMASK on stack to avoid
* failure in case of nested critical sections !! */
uint32_t primask = __get_PRIMASK();
__asm("cpsid i");
spifi_config_t config = {0};
#ifndef XIP_IMAGE
uint32_t sourceClockFreq;
BOARD_InitSPIFI();
/* Reset peripheral */
RESET_PeripheralReset(kSPIFI_RST_SHIFT_RSTn);
/* Set SPIFI clock source */
CLOCK_AttachClk(kFRO_HF_to_SPIFI_CLK);
sourceClockFreq = CLOCK_GetSpifiClkFreq();
/* Set the clock divider */
CLOCK_SetClkDiv(kCLOCK_DivSpifiClk, sourceClockFreq / MFLASH_BAUDRATE, false);
/* Enable SPIFI clock */
CLOCK_EnableClock(kCLOCK_Spifi);
#endif
SPIFI_GetDefaultConfig(&config);
config.dualMode = kSPIFI_DualMode;
#ifdef XIP_IMAGE
config.disablePrefetch = false; // true;
config.disableCachePrefech = false; // true;
#else
config.disablePrefetch = false; // true;
config.disableCachePrefech = false; // true;
#endif
/* Reset the Command register */
SPIFI_ResetCommand(MFLASH_SPIFI);
/* Set time delay parameter */
MFLASH_SPIFI->CTRL = SPIFI_CTRL_TIMEOUT(config.timeout) | SPIFI_CTRL_CSHIGH(config.csHighTime) |
SPIFI_CTRL_D_PRFTCH_DIS(config.disablePrefetch) | SPIFI_CTRL_MODE3(config.spiMode) |
SPIFI_CTRL_PRFTCH_DIS(config.disableCachePrefech) | SPIFI_CTRL_DUAL(config.dualMode) |
SPIFI_CTRL_RFCLK(config.isReadFullClockCycle) | SPIFI_CTRL_FBCLK(config.isFeedbackClock);
mflash_drv_read_mode();
if (primask == 0)
{
__asm("cpsie i");
}
return 0;
}
/* API - initialize 'mflash' */
int32_t mflash_drv_init(void)
{
volatile int32_t result;
/* Necessary to have double wrapper call in non_xip memory */
result = mflash_drv_init_internal();
return result;
}
/* Internal - erase single sector */
static int32_t mflash_drv_sector_erase(uint32_t sector_addr)
{
uint32_t primask = __get_PRIMASK();
__asm("cpsid i");
/* Reset the SPIFI to switch to command mode */
SPIFI_ResetCommand(MFLASH_SPIFI);
/* Write enable */
SPIFI_SetCommand(MFLASH_SPIFI, &command[WRITE_ENABLE]);
/* Set address */
SPIFI_SetCommandAddress(MFLASH_SPIFI, sector_addr);
/* Erase sector */
SPIFI_SetCommand(MFLASH_SPIFI, &command[ERASE_SECTOR]);
/* Check if finished */
mflash_drv_check_if_finish();
/* Switch to read mode to enable interrupts as soon ass possible */
mflash_drv_read_mode();
if (primask == 0)
{
__asm("cpsie i");
}
/* Flush pipeline to allow pending interrupts take place */
__ISB();
return 0;
}
/* Internal - write single page */
static int32_t mflash_drv_page_program(uint32_t page_addr, const uint32_t *page_data)
{
uint32_t primask = __get_PRIMASK();
__asm("cpsid i");
/* Program page */
SPIFI_ResetCommand(MFLASH_SPIFI);
SPIFI_SetCommand(MFLASH_SPIFI, &command[WRITE_ENABLE]);
SPIFI_SetCommandAddress(MFLASH_SPIFI, page_addr);
SPIFI_SetCommand(MFLASH_SPIFI, &command[PROGRAM_PAGE]);
/* Store 4B in each loop. Sector has always 4B alignment and size multiple of 4 */
for (uint32_t i = 0; i < MFLASH_PAGE_SIZE/sizeof(page_data[0]); i++)
{
SPIFI_WriteData(MFLASH_SPIFI, page_data[i]);
}
mflash_drv_check_if_finish();
/* Switch to read mode to enable interrupts as soon ass possible */
mflash_drv_read_mode();
if (primask == 0)
{
__asm("cpsie i");
}
/* Flush pipeline to allow pending interrupts take place */
__ISB();
return 0;
}
#if !defined(FLASHDRV_SMART_UPDATE) || (FLASHDRV_SMART_UPDATE == 0)
/* Internal - write whole sector */
static int32_t mflash_drv_sector_program(uint32_t sector_addr, const uint32_t *sector_data)
{
if (false == mflash_drv_is_sector_aligned((uint32_t)sector_addr))
return -1;
uint32_t max_page = MFLASH_SECTOR_SIZE / MFLASH_PAGE_SIZE;
uint32_t page_addr = sector_addr;
const uint32_t *page_data = sector_data;
for (uint32_t page_idx = 0; page_idx < max_page; page_idx++)
{
mflash_drv_page_program(page_addr, page_data);
page_addr += MFLASH_PAGE_SIZE;
page_data += MFLASH_PAGE_SIZE/sizeof(page_data[0]);
}
return 0;
}
#endif
/* Internal - write data of 'data_len' to single sector 'sector_addr', starting from 'sect_off' */
static int32_t mflash_drv_sector_update(uint32_t sector_addr, uint32_t sect_off, const uint8_t *data, uint32_t data_len)
{
#if FLASHDRV_SMART_UPDATE
int sector_erase_req = 0;
uint32_t page_program_map = 0; /* Current implementation is limited to 32 pages per sector */
#endif
/* Address not aligned to sector boundary */
if (false == mflash_drv_is_sector_aligned((uint32_t)sector_addr))
return -1;
/* Offset + length exceeed sector size */
if (sect_off + data_len > MFLASH_SECTOR_SIZE)
return -1;
/* Switch back to read mode */
mflash_drv_read_mode();
/* Copy old sector data by 4B in each loop to buffer */
for (uint32_t i = 0; i < sizeof(g_flashm_sector)/sizeof(g_flashm_sector[0]); i++)
{
g_flashm_sector[i] = *((uint32_t*)(sector_addr) + i);
}
#if FLASHDRV_SMART_UPDATE /* Perform only the erase/program operations that are necessary */
/* Copy custom data (1B in each loop) to buffer at specific position */
for (uint32_t i = 0; i < data_len; i++)
{
/* Unless it was already decided to erase the whole sector, evaluate differences between current and new data */
if (0 == sector_erase_req)
{
uint8_t cur_value = ((uint8_t*)(g_flashm_sector))[sect_off + i];
uint8_t new_value = data[i];
/* Check the the bit transitions */
if ((cur_value | new_value) != cur_value)
{
sector_erase_req = 1; /* A bit needs to be flipped from 0 to 1, the sector has to be erased */
}
else if ((cur_value & new_value) != cur_value)
{
page_program_map |= 1 << ((sect_off + i) / MFLASH_PAGE_SIZE); /* A bit needs to be flipped from 1 to 0, the page has to be programmed */
}
}
/* Copy data over to the buffer */
((uint8_t*)g_flashm_sector)[sect_off + i] = data[i];
}
/* Erase the sector if required */
if (0 != sector_erase_req)
{
if (0 != mflash_drv_sector_erase(sector_addr))
{
return -2;
}
/* Update page program map according to non-blank areas in the buffer */
for (int page_idx = 0; page_idx < MFLASH_SECTOR_SIZE / MFLASH_PAGE_SIZE; page_idx++)
{
int page_word_start = page_idx * (MFLASH_PAGE_SIZE / sizeof(g_flashm_sector[0]));
int page_word_end = page_word_start + (MFLASH_PAGE_SIZE / sizeof(g_flashm_sector[0]));
for (int i = page_word_start; i < page_word_end ; i++)
{
if (g_flashm_sector[i] != 0xFFFFFFFF)
{
/* Mark the page for programming and go for next one */
page_program_map |= (1 << page_idx);
break;
}
}
}
}
/* Program the pages */
for (int page_idx = 0; page_idx < MFLASH_SECTOR_SIZE / MFLASH_PAGE_SIZE; page_idx++)
{
/* Skip programming of blank pages */
if (0 == (page_program_map & (1 << page_idx)))
{
continue; /* The page needs not be programmed, skip it */
}
mflash_drv_page_program(sector_addr + page_idx * MFLASH_PAGE_SIZE, g_flashm_sector + page_idx * (MFLASH_PAGE_SIZE / sizeof(g_flashm_sector[0])));
}
#else /* Erase the sector and all the pages unconditionally */
/* Copy custom data (1B in each loop) to buffer at specific position */
for (uint32_t i = 0; i < data_len; i++)
{
((uint8_t*)g_flashm_sector)[sect_off + i] = data[i];
}
/* Erase the sector */
if (0 != mflash_drv_sector_erase(sector_addr))
{
return -2;
}
/* Program whole sector */
if (0 != mflash_drv_sector_program(sector_addr, g_flashm_sector))
{
return -2;
}
#endif /* FLASHDRV_SMART_UPDATE */
/* Switch back to read mode */
mflash_drv_read_mode();
return 0;
}
/* Erase area of flash, cannot be invoked directly, requires calling wrapper in non XIP memory */
int32_t mflash_drv_erase_internal(void *addr, uint32_t len)
{
uint32_t sector_addr;
/* Address not aligned to sector boundary */
if (false == mflash_drv_is_sector_aligned((uint32_t)addr))
return -1;
/* Length is not aligned to sector size */
if (0 != len % MFLASH_SECTOR_SIZE)
return -1;
sector_addr = (uint32_t)addr;
while (len)
{
/* Perform blank-check of the sector and erase it if necessary */
for (uint32_t i = 0; i < MFLASH_SECTOR_SIZE / sizeof(uint32_t); i++)
{
if (0xFFFFFFFF != *((uint32_t*)(sector_addr) + i))
{
mflash_drv_sector_erase(sector_addr);
break;
}
}
sector_addr += MFLASH_SECTOR_SIZE;
len -= MFLASH_SECTOR_SIZE;
}
return 0;
}
/* Write data to flash, cannot be invoked directly, requires calling wrapper in non XIP memory */
int32_t mflash_drv_write_internal(void *any_addr, const uint8_t *data, uint32_t data_len)
{
uint32_t sect_size = MFLASH_SECTOR_SIZE;
/* Interval <0, sector_size) */
uint32_t to_write = 0;
/* Interval (data_len, 0> */
uint32_t to_remain = data_len;
int32_t result = 0;
for (
/* Calculate address of first sector */
uint32_t sect_a = mflash_drv_addr_to_sector_addr((uint32_t)any_addr),
/* and first sector offset */
sect_of = mflash_drv_addr_to_sector_of((uint32_t)any_addr),
/* and set first data offset to 0*/
data_of = 0;
/* Continue until sector address exceed target adddress + data_length */
sect_a < ((uint32_t)any_addr) + data_len;
/* Move to next sector */
sect_a += sect_size,
/* and move pointer to data */
data_of += to_write
)
{
/* If remaining data is exceed 'sector_size', write 'sector_size' length */
if (to_remain > sect_size - sect_of)
{
to_write = sect_size - sect_of;
to_remain = to_remain - to_write;
}
/* else write remaining data length */
else
{
to_write = to_remain;
to_remain = 0;
}
/* Write at 'sect_a' sector, starting at 'sect_of' using '&data[data_of]' of length 'to_write' */
result = mflash_drv_sector_update(sect_a, sect_of, data + data_of, to_write);
if (0 != result)
return -1;
/* Only first sector is allowed to have an offset */
sect_of = 0;
}
return 0;
}
/* Calling wrapper for 'mflash_drv_write_internal'.
* Write 'data' of 'data_len' to 'any_addr' - which doesn't have to be sector aligned.
* NOTE: Don't try to store constant data that are located in XIP !!
*/
int32_t mflash_drv_write(void *any_addr, const uint8_t *data, uint32_t data_len)
{
volatile int32_t result;
result = mflash_drv_write_internal(any_addr, data, data_len);
return result;
}
#if 0
/* Dummy test to prove functionality */
volatile uint32_t lock2 = 1;
char * tmp_string = "Curabitur sit amet justo ac velit consectetur lobortis. Donec porttitor, eros sed sollicitudin viverra, massa enim placerat sapien, et vestibulum lacus quam et leo. Proin gravida";
void mflash_drv_do_test(void)
{
lock2 = 1;
while (lock2);
// place to SRAM !!!
#ifndef XIP_IMAGE
BOARD_InitSPIFI();
#endif
/* Reset peripheral */
lock2 = 1;
while (lock2);
mflash_drv_init();
lock2 = 1;
while (lock2)
mflash_drv_write((void*)(0x10800010), tmp_string, 30);//TODO force read to recover
lock2 = 1;
while (lock2);
}
#endif
| 6,932
|
348
|
{"nom":"Abos","circ":"3ème circonscription","dpt":"Pyrénées-Atlantiques","inscrits":462,"abs":166,"votants":296,"blancs":5,"nuls":0,"exp":291,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":107},{"nuance":"SOC","nom":"<NAME>","voix":93},{"nuance":"FI","nom":"<NAME>","voix":22},{"nuance":"LR","nom":"M. <NAME>","voix":20},{"nuance":"FN","nom":"Mme <NAME>","voix":16},{"nuance":"UDI","nom":"M. <NAME>","voix":15},{"nuance":"COM","nom":"Mme <NAME>","voix":4},{"nuance":"EXG","nom":"M. <NAME>","voix":4},{"nuance":"ECO","nom":"Mme <NAME>","voix":3},{"nuance":"ECO","nom":"M. <NAME>","voix":2},{"nuance":"DVG","nom":"M. <NAME>","voix":2},{"nuance":"REG","nom":"M. <NAME>","voix":1},{"nuance":"DIV","nom":"Mme <NAME>","voix":1},{"nuance":"EXG","nom":"M. <NAME>","voix":1}]}
| 317
|
5,937
|
<reponame>txlos/wpf
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 7.00.0498 */
/* Compiler settings for pentypes.idl:
Oicf, W1, Zp8, env=Win32 (32b run)
protocol : dce , ms_ext, c_ext, robust
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING( )
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 500
#endif
/* verify that the <rpcsal.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCSAL_H_VERSION__
#define __REQUIRED_RPCSAL_H_VERSION__ 100
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__
#ifndef __pentypes_h__
#define __pentypes_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
/* header files for imported files */
#include "oaidl.h"
#include "ocidl.h"
#ifdef __cplusplus
extern "C"{
#endif
/* interface __MIDL_itf_pentypes_0000_0000 */
/* [local] */
#include "tpcshrd.h"
#define TCXO_MARGIN 0x00000001
#define TCXO_PREHOOK 0x00000002
#define TCXO_CURSOR_STATE 0x00000004
#define TCXO_NO_CURSOR_DOWN 0x00000008
#define TCXO_NON_INTEGRATED 0x00000010
#define TCXO_POSTHOOK 0x00000020
#define TCXO_DONT_SHOW_CURSOR 0x00000080
#define TCXO_DONT_VALIDATE_TCS 0x00000100
#define TCXO_REPORT_RECT_MAPPING_CHANGE 0x00000200
#define TCXO_ALLOW_FLICKS 0x00000400
#define TCXO_ALLOW_FEEDBACK_TAPS 0x00000800
#define TCXO_ALLOW_FEEDBACK_BARREL 0x00001000
#define TCXO_ALLOW_ALL_TOUCH 0x00002000
#define TCXO_ALL (TCXO_MARGIN | TCXO_PREHOOK | TCXO_CURSOR_STATE | TCXO_NO_CURSOR_DOWN | TCXO_NON_INTEGRATED | TCXO_POSTHOOK | TCXO_DONT_SHOW_CURSOR | TCXO_DONT_VALIDATE_TCS | TCXO_REPORT_RECT_MAPPING_CHANGE | TCXO_ALLOW_FLICKS | TCXO_ALLOW_FEEDBACK_TAPS | TCXO_ALLOW_FEEDBACK_BARREL | TCXO_ALLOW_ALL_TOUCH)
#define TCXO_HOOK (TCXO_PREHOOK | TCXO_POSTHOOK)
#define TCXS_DISABLED 0x00000001
#define THWC_INTEGRATED 0x00000001
#define THWC_CSR_MUST_TOUCH 0x00000002
#define THWC_HARD_PROXIMITY 0x00000004
#define THWC_PHYSID_CSRS 0x00000008
#define IP_CURSOR_DOWN 0x00000001
#define IP_INVERTED 0x00000002
#define IP_MARGIN 0x00000004
#define IP_BARREL_DOWN 0x00000008
#define IP_RECT_MAPPING_CHANGED 0x00000010
#define IP_ALL_STATUS_BITS (IP_CURSOR_DOWN | IP_INVERTED | IP_MARGIN | IP_BARREL_DOWN | IP_RECT_MAPPING_CHANGED)
#define TAB_SETTING_LINEARIZATION 0x00000001
#define TAB_SETTING_PORTRAIT_USERTILT 0x00000002
#define TAB_SETTING_LANDSCAPE_USERTILT 0x00000004
#define TAB_SETTING_DISPLAY_ORIENTATION_DEFAULT_USERTILT 0x00000008
#define TAB_SETTING_DISPLAY_ORIENTATION_90_USERTILT 0x00000010
#define TAB_SETTING_DISPLAY_ORIENTATION_180_USERTILT 0x00000100
#define TAB_SETTING_DISPLAY_ORIENTATION_270_USERTILT 0x00001000
#define SE_TAP 0x00000010
#define SE_DBL_TAP 0x00000011
#define SE_RIGHT_TAP 0x00000012
#define SE_DRAG 0x00000013
#define SE_RIGHT_DRAG 0x00000014
#define SE_HOLD_ENTER 0x00000015
#define SE_HOLD_LEAVE 0x00000016
#define SE_HOVER_ENTER 0x00000017
#define SE_HOVER_LEAVE 0x00000018
#define SE_MIDDLE_CLICK 0x00000019
#define SE_KEY 0x0000001A
#define SE_MODIFIER_KEY 0x0000001B
#define SE_GESTURE_MODE 0x0000001C
#define SE_CURSOR 0x0000001D
#define SE_FLICK 0x0000001F
#define SE_MODIFIER_CTRL 0x00000001
#define SE_MODIFIER_ALT 0x00000002
#define SE_MODIFIER_SHIFT 0x00000004
#define SE_NORMAL_CURSOR 0x00000001
#define SE_ERASER_CURSOR 0x00000002
#define SE_SYSTEMEVENT 0x00000001
#define SE_TYPE_MOUSE 0x00000000
#define SE_TYPE_KEYBOARD 0x00000001
#define SE_DELAY_PACKET 0x0000000F
#define SE_PRE_TAPDRAG 0x0000001E
#define WM_TABLET_DEFBASE 0x02C0
#define WM_TABLET_MAXOFFSET 0x20
#define WM_TABLET_CONTEXTCREATE (WM_TABLET_DEFBASE + 0)
#define WM_TABLET_CONTEXTDESTROY (WM_TABLET_DEFBASE + 1)
#define WM_TABLET_CURSORNEW (WM_TABLET_DEFBASE + 2)
#define WM_TABLET_CURSORINRANGE (WM_TABLET_DEFBASE + 3)
#define WM_TABLET_CURSOROUTOFRANGE (WM_TABLET_DEFBASE + 4)
#define WM_TABLET_CURSORDOWN (WM_TABLET_DEFBASE + 5)
#define WM_TABLET_CURSORUP (WM_TABLET_DEFBASE + 6)
#define WM_TABLET_PACKET (WM_TABLET_DEFBASE + 7)
#define WM_TABLET_ADDED (WM_TABLET_DEFBASE + 8)
#define WM_TABLET_DELETED (WM_TABLET_DEFBASE + 9)
#define WM_TABLET_SYSTEMEVENT (WM_TABLET_DEFBASE + 10)
#define WM_TABLET_MAX (WM_TABLET_DEFBASE + WM_TABLET_MAXOFFSET)
#define TABLET_MESSAGE_EXTRA_INFO_MASK_PEN_OR_TOUCH 0xFF515700
#define TABLET_MESSAGE_EXTRA_INFO_MASK_TOUCH 0xFF515780
#define TABLET_MESSAGE_EXTRA_INFO_MASK_TIP 0xFF575100
#define MICROSOFT_TABLETPENSERVICE_PROPERTY _T("MicrosoftTabletPenServiceProperty")
#define TABLET_DISABLE_PRESSANDHOLD 0x00000001
#define TABLET_DISABLE_PENTAPFEEDBACK 0x00000008
#define TABLET_DISABLE_PENBARRELFEEDBACK 0x00000010
#define TABLET_DISABLE_TOUCHUIFORCEON 0x00000100
#define TABLET_DISABLE_TOUCHUIFORCEOFF 0x00000200
#define TABLET_DISABLE_TOUCHSWITCH 0x00008000
#define TABLET_DISABLE_FLICKS 0x00010000
#define TABLET_ENABLE_FLICKSONCONTEXT 0x00020000
#define TABLET_ENABLE_FLICKLEARNINGMODE 0x00040000
#define TABLET_DISABLE_SMOOTHSCROLLING 0x00080000
#define WISP_WINTAB_ERROR MAKE_HRESULT(1, FACILITY_ITF, 0x201)
#define WISP_PACKET_BUFFER_TOO_SMALL MAKE_HRESULT(1, FACILITY_ITF, 0x211)
#define WISP_NO_DEFAULT_TABLET MAKE_HRESULT(1, FACILITY_ITF, 0x212)
#define WISP_TABLET_CONTEXT_NOT_FOUND MAKE_HRESULT(1, FACILITY_ITF, 0x213)
#define WISP_CURSOR_NOT_FOUND MAKE_HRESULT(1, FACILITY_ITF, 0x214)
#define WISP_INVALID_TABLET_INDEX MAKE_HRESULT(1, FACILITY_ITF, 0x215)
#define WISP_INVALID_TABLET_CONTEXT_INDEX MAKE_HRESULT(1, FACILITY_ITF, 0x216)
#define WISP_INVALID_CURSOR_INDEX MAKE_HRESULT(1, FACILITY_ITF, 0x217)
#define WISP_INVALID_BUTTON_INDEX MAKE_HRESULT(1, FACILITY_ITF, 0x218)
#define WISP_INVALID_PACKET_SERIAL_NUM MAKE_HRESULT(1, FACILITY_ITF, 0x219)
#define WISP_INVALID_WINDOW_HANDLE MAKE_HRESULT(1, FACILITY_ITF, 0x21a)
#define WISP_INVALID_INPUT_RECT MAKE_HRESULT(1, FACILITY_ITF, 0x21b)
#define WISP_INVALID_TABLET_CONTEXT_SETTINGS MAKE_HRESULT(1, FACILITY_ITF, 0x21c)
#define WISP_UNKNOWN_PROPERTY MAKE_HRESULT(1, FACILITY_ITF, 0x21d)
#define WISP_UNITS_CONVERSION_UNDEFINED MAKE_HRESULT(1, FACILITY_ITF, 0x21e)
#define SZ_REGKEY_PERSIST TEXT("Software\\Microsoft\\Wisp\\Pen\\Persist")
#define SZ_REGVAL_TYPE TEXT("type")
#define SZ_REGVAL_WINTABDEVICEID TEXT("WintabDeviceId")
#define SZ_REGVAL_HIDDEVICEPATH TEXT("HidDevicePath")
#define SZ_REGVAL_WINTABCURSORTYPE TEXT("WintabCursorType")
#define SZ_REGVAL_WINTABCURSORPHYSID TEXT("WintabCursorPhysid")
#define SZ_REGVAL_HIDCURSORID TEXT("HidCursorId")
#define SZ_REGVAL_HIDDEVICE TEXT("HidDevice")
#define SZ_REGVAL_NAME TEXT("Name")
typedef
enum _CONTEXT_ENABLE_TYPE
{ CONTEXT_ENABLE = 1,
CONTEXT_DISABLE = 2
} CONTEXT_ENABLE_TYPE;
typedef enum _CONTEXT_ENABLE_TYPE *PCONTEXT_ENABLE_TYPE;
typedef struct _TABLET_CONTEXT_SETTINGS
{
ULONG cPktProps;
GUID *pguidPktProps;
ULONG cPktBtns;
GUID *pguidPktBtns;
DWORD *pdwBtnDnMask;
DWORD *pdwBtnUpMask;
LONG lXMargin;
LONG lYMargin;
} TABLET_CONTEXT_SETTINGS;
typedef /* [unique] */ __RPC_unique_pointer TABLET_CONTEXT_SETTINGS *PTABLET_CONTEXT_SETTINGS;
#define SZ_EVENT_TABLETHARDWAREPRESENT TEXT("Global\\TabletHardwarePresent")
extern RPC_IF_HANDLE __MIDL_itf_pentypes_0000_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_pentypes_0000_0000_v0_0_s_ifspec;
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
| 4,316
|
310
|
import torch.nn as nn
from torch.autograd import Variable
import torch
import time
from torch.nn.functional import cosine_similarity
from module_utils import *
class FullMatchLay(nn.Module):
def __init__(self, mp_dim, cont_dim):
super().__init__()
self.cont_dim = cont_dim
self.mp_dim = mp_dim
self.register_parameter("weight", nn.Parameter(torch.Tensor(mp_dim, cont_dim)))
self.weight.data.uniform_(-1., 1.)
def forward(self, cont_repres, other_cont_first):
"""
Args:
cont_repres - [batch_size, this_len, context_lstm_dim]
other_cont_first - [batch_size, context_lstm_dim]
Return:
size - [batch_size, this_len, mp_dim]
"""
def expand(context, weight):
"""
Args:
[batch_size, this_len, context_lstm_dim]
[mp_dim, context_lstm_dim]
Return:
[batch_size, this_len, mp_dim, context_lstm_dim]
"""
# [1, 1, mp_dim, context_lstm_dim]
weight = weight.unsqueeze(0)
weight = weight.unsqueeze(0)
# [batch_size, this_len, 1, context_lstm_dim]
context = context.unsqueeze(2)
return torch.mul(context, weight)
cont_repres = expand(cont_repres, self.weight)
other_cont_first = multi_perspective_expand_for_2D(other_cont_first, self.weight)
# [batch_size, 1, mp_dim, context_lstm_dim]
other_cont_first = other_cont_first.unsqueeze(1)
return cosine_similarity(cont_repres, other_cont_first, cont_repres.dim()-1)
class MaxpoolMatchLay(nn.Module):
def __init__(self, mp_dim, cont_dim):
super().__init__()
self.cont_dim = cont_dim
self.mp_dim = mp_dim
self.register_parameter("weight", nn.Parameter(torch.Tensor(mp_dim, cont_dim)))
self.weight.data.uniform_(-1., 1.)
def forward(self, cont_repres, other_cont_repres):
"""
Args:
cont_repres - [batch_size, this_len, context_lstm_dim]
other_cont_repres - [batch_size, other_len, context_lstm_dim]
Return:
size - [bsz, this_len, mp_dim*2]
"""
bsz = cont_repres.size(0)
this_len = cont_repres.size(1)
other_len = other_cont_repres.size(1)
cont_repres = cont_repres.view(-1, self.cont_dim)
other_cont_repres = other_cont_repres.view(-1, self.cont_dim)
cont_repres = multi_perspective_expand_for_2D(cont_repres, self.weight)
other_cont_repres = multi_perspective_expand_for_2D(other_cont_repres, self.weight)
cont_repres = cont_repres.view(bsz, this_len, self.mp_dim, self.cont_dim)
other_cont_repres = other_cont_repres.view(bsz, other_len, self.mp_dim, self.cont_dim)
# [bsz, this_len, 1, self.mp_dim, self.cont_dim]
cont_repres = cont_repres.unsqueeze(2)
# [bsz, 1, other_len, self.mp_dim, self.cont_dim]
other_cont_repres = other_cont_repres.unsqueeze(1)
# [bsz, this_len, other_len, self.mp_dim]fanruan
simi = cosine_similarity(cont_repres, other_cont_repres, cont_repres.dim()-1)
t_max, _ = simi.max(2)
t_mean = simi.mean(2)
return torch.cat((t_max, t_mean), 2)
class AtteMatchLay(nn.Module):
def __init__(self, mp_dim, cont_dim):
super(AtteMatchLay, self).__init__()
self.cont_dim = cont_dim
self.mp_dim = mp_dim
self.register_parameter("weight", nn.Parameter(torch.Tensor(mp_dim, cont_dim)))
self.weight.data.uniform_(-1., 1.)
def forward(self, repres, max_att):
"""
Args:
repres - [bsz, a_len|q_len, cont_dim]
max_att - [bsz, q_len|a_len, cont_dim]
Return:
size - [bsz, sentence_len, mp_dim]
"""
bsz = repres.size(0)
sent_len = repres.size(1)
repres = repres.view(-1, self.cont_dim)
max_att = max_att.view(-1, self.cont_dim)
repres = multi_perspective_expand_for_2D(repres, self.weight)
max_att = multi_perspective_expand_for_2D(max_att, self.weight)
temp = cosine_similarity(repres, max_att, repres.dim()-1)
return temp.view(bsz, sent_len, self.mp_dim)
| 2,131
|
1,618
|
package com.xiaojuchefu.prism.behavior.model;
import com.google.gson.annotations.SerializedName;
public class Rule {
@SerializedName("ruleId")
public long ruleId;
@SerializedName("cityId")
public int cityId;
@SerializedName("period")
public int period;
@SerializedName("effectiveTime")
public long effectiveTime;
@SerializedName("cycleTrigger")
public int cycleTrigger;
@SerializedName("containHistory")
public int containHistory;
@SerializedName("triggerMoment")
public int triggerMoment;
@SerializedName("triggerDelay")
public int triggerDelay;
@SerializedName("ruleContent")
public RuleContent ruleContent;
public RuleContent basePoint;
public boolean basePointTriggered;
public boolean triggered;
}
| 266
|
1,104
|
<reponame>Zorghts/roll20-character-sheets<gh_stars>1000+
{
"list-skills": "manipulation,tromperie,combat,rafistolage,investigation,poursuite,endurance,larcin",
"list-domains": "académie,crime,commerce,haute-société,prolétariat,occultisme,ordre,religion,technologie",
"spire-the-city-must-fall": "Spire - Le soulèvement",
"profile": "Personnage",
"stress": "Stress",
"roll": "Lancer",
"character-name": "Nom du Personnage :",
"class": "Classe :",
"durance": "Corvée",
"skills": "Compétences",
"compel": "Manipulation",
"deceive": "Tromperie",
"fight": "Combat",
"fix": "Rafistolage",
"investigate": "Investigation",
"pursue": "Poursuite",
"resist": "Endurance",
"sneak": "Furtivité",
"steal": "Larcin",
"domains": "Domaines",
"academia": "Académie",
"crime": "Crime",
"commerce": "Commerce",
"high-society": "Haute Société",
"low-society": "Prolétariat",
"occult": "Occultisme",
"order": "Ordre",
"religion": "Religion",
"technology": "Technologie",
"advances": "Capacités",
"refresh": "Restauration",
"equipment": "Équipement",
"bonds": "Attaches",
"fallout": "Contrecoup",
"free-slots": "Emplacements supplémentaires",
"resistances": "Résistances",
"current": "Actuel",
"armor": "Armure",
"blood": "Sang",
"mind": "Esprit",
"silver": "Argent",
"shadow": "Ombre",
"reputation": "Réputation",
"tries-to": "tente de",
"with": "avec"
}
| 597
|
2,151
|
<filename>chrome/browser/sessions/tab_loader.cc<gh_stars>1000+
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sessions/tab_loader.h"
#include <algorithm>
#include <string>
#include "base/memory/memory_coordinator_client_registry.h"
#include "base/memory/memory_coordinator_proxy.h"
#include "base/memory/memory_pressure_monitor.h"
#include "base/metrics/histogram_macros.h"
#include "build/build_config.h"
#include "chrome/browser/sessions/session_restore_stats_collector.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "components/favicon/content/content_favicon_driver.h"
#include "components/variations/variations_associated_data.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "services/resource_coordinator/public/cpp/resource_coordinator_features.h"
using content::NavigationController;
using content::RenderWidgetHost;
using content::WebContents;
namespace {
size_t g_max_loaded_tab_count_for_testing = 0;
} // namespace
void TabLoader::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_WEB_CONTENTS_DESTROYED: {
WebContents* web_contents = content::Source<WebContents>(source).ptr();
HandleTabClosedOrLoaded(&web_contents->GetController());
break;
}
case content::NOTIFICATION_LOAD_STOP: {
DCHECK(!resource_coordinator::IsPageAlmostIdleSignalEnabled());
NavigationController* controller =
content::Source<NavigationController>(source).ptr();
HandleTabClosedOrLoaded(controller);
break;
}
default:
NOTREACHED() << "Unknown notification received:" << type;
}
// Delete ourselves when we are done.
if (tabs_loading_.empty() && tabs_to_load_.empty())
this_retainer_ = nullptr;
}
void TabLoader::OnPageAlmostIdle(content::WebContents* web_contents) {
auto* controller = &web_contents->GetController();
// The |web_contents| is not managed by TabLoader.
if (tabs_loading_.find(controller) == tabs_loading_.end() &&
!base::ContainsValue(tabs_to_load_, controller)) {
return;
}
HandleTabClosedOrLoaded(controller);
}
void TabLoader::SetTabLoadingEnabled(bool enable_tab_loading) {
// TODO(chrisha): Make the SessionRestoreStatsCollector aware that tab loading
// was explicitly stopped or restarted. This can make be used to invalidate
// various metrics.
if (enable_tab_loading == loading_enabled_)
return;
loading_enabled_ = enable_tab_loading;
if (loading_enabled_) {
LoadNextTab();
} else {
force_load_timer_.Stop();
}
}
// static
void TabLoader::RestoreTabs(const std::vector<RestoredTab>& tabs,
const base::TimeTicks& restore_started) {
if (!shared_tab_loader_)
shared_tab_loader_ = new TabLoader(restore_started);
shared_tab_loader_->stats_collector_->TrackTabs(tabs);
shared_tab_loader_->StartLoading(tabs);
}
// static
void TabLoader::SetMaxLoadedTabCountForTest(size_t value) {
g_max_loaded_tab_count_for_testing = value;
}
TabLoader::TabLoader(base::TimeTicks restore_started)
: memory_pressure_listener_(
base::Bind(&TabLoader::OnMemoryPressure, base::Unretained(this))),
force_load_delay_multiplier_(1),
loading_enabled_(true),
started_to_load_count_(0),
restore_started_(restore_started) {
stats_collector_ = new SessionRestoreStatsCollector(
restore_started,
std::make_unique<
SessionRestoreStatsCollector::UmaStatsReportingDelegate>());
shared_tab_loader_ = this;
this_retainer_ = this;
base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
if (auto* page_signal_receiver =
resource_coordinator::PageSignalReceiver::GetInstance()) {
page_signal_receiver->AddObserver(this);
}
}
TabLoader::~TabLoader() {
DCHECK(tabs_loading_.empty() && tabs_to_load_.empty());
DCHECK(shared_tab_loader_ == this);
shared_tab_loader_ = nullptr;
if (auto* page_signal_receiver =
resource_coordinator::PageSignalReceiver::GetInstance()) {
page_signal_receiver->RemoveObserver(this);
}
base::MemoryCoordinatorClientRegistry::GetInstance()->Unregister(this);
SessionRestore::OnTabLoaderFinishedLoadingTabs();
}
void TabLoader::StartLoading(const std::vector<RestoredTab>& tabs) {
// Add the tabs to the list of tabs loading/to load and register them for
// notifications. Also, restore the favicons of the background tabs (the title
// has already been set by now).This avoids having blank icons in case the
// restore is halted due to memory pressure. Also, when multiple tabs are
// restored to a single window, the title may not appear, and the user will
// have no way of finding out which tabs corresponds to which page if the icon
// is a generic grey one.
for (auto& restored_tab : tabs) {
if (!restored_tab.is_active()) {
tabs_to_load_.push_back(&restored_tab.contents()->GetController());
favicon::ContentFaviconDriver* favicon_driver =
favicon::ContentFaviconDriver::FromWebContents(
restored_tab.contents());
// |favicon_driver| might be null when testing.
if (favicon_driver) {
favicon_driver->FetchFavicon(favicon_driver->GetActiveURL(),
/*is_same_document=*/false);
}
} else {
++started_to_load_count_;
tabs_loading_.insert(&restored_tab.contents()->GetController());
}
RegisterForNotifications(&restored_tab.contents()->GetController());
}
// When multiple profiles are using the same TabLoader, another profile might
// already have started loading. In that case, the tabs scheduled for loading
// by this profile are already in the loading queue, and they will get loaded
// eventually.
if (delegate_)
return;
// Create a TabLoaderDelegate which will allow OS specific behavior for tab
// loading.
if (!delegate_) {
delegate_ = TabLoaderDelegate::Create(this);
// There is already at least one tab loading (the active tab). As such we
// only have to start the timeout timer here. But, don't restore background
// tabs if the system is under memory pressure.
if (ShouldStopLoadingTabs()) {
StopLoadingTabs();
return;
}
StartFirstTimer();
}
}
void TabLoader::LoadNextTab() {
// LoadNextTab should only get called after we have started the tab
// loading.
CHECK(delegate_);
// Abort if loading is not enabled.
if (!loading_enabled_)
return;
if (!tabs_to_load_.empty()) {
// Check the memory pressure before restoring the next tab, and abort if
// there is pressure. This is important on the Mac because of the sometimes
// large delay between a memory pressure event and receiving a notification
// of that event (in that case tab restore can trigger memory pressure but
// will complete before the notification arrives).
if (ShouldStopLoadingTabs()) {
StopLoadingTabs();
return;
}
stats_collector_->OnWillLoadNextTab(!force_load_timer_.IsRunning());
NavigationController* controller = tabs_to_load_.front();
DCHECK(controller);
++started_to_load_count_;
tabs_loading_.insert(controller);
tabs_to_load_.pop_front();
controller->LoadIfNecessary();
content::WebContents* contents = controller->GetWebContents();
if (contents) {
Browser* browser = chrome::FindBrowserWithWebContents(contents);
if (browser &&
browser->tab_strip_model()->GetActiveWebContents() != contents) {
// By default tabs are marked as visible. As only the active tab is
// visible we need to explicitly tell non-active tabs they are hidden.
// Without this call non-active tabs are not marked as backgrounded.
//
// NOTE: We need to do this here rather than when the tab is added to
// the Browser as at that time not everything has been created, so that
// the call would do nothing.
contents->WasHidden();
}
}
}
if (!tabs_to_load_.empty())
StartTimer();
}
void TabLoader::StartFirstTimer() {
force_load_timer_.Stop();
force_load_timer_.Start(FROM_HERE,
delegate_->GetFirstTabLoadingTimeout(),
this, &TabLoader::ForceLoadTimerFired);
}
void TabLoader::StartTimer() {
force_load_timer_.Stop();
force_load_timer_.Start(FROM_HERE,
delegate_->GetTimeoutBeforeLoadingNextTab() *
force_load_delay_multiplier_,
this, &TabLoader::ForceLoadTimerFired);
}
void TabLoader::RemoveTab(NavigationController* controller) {
registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
content::Source<WebContents>(controller->GetWebContents()));
if (!resource_coordinator::IsPageAlmostIdleSignalEnabled()) {
registrar_.Remove(this, content::NOTIFICATION_LOAD_STOP,
content::Source<NavigationController>(controller));
}
TabsLoading::iterator i = tabs_loading_.find(controller);
if (i != tabs_loading_.end())
tabs_loading_.erase(i);
TabsToLoad::iterator j =
find(tabs_to_load_.begin(), tabs_to_load_.end(), controller);
if (j != tabs_to_load_.end())
tabs_to_load_.erase(j);
}
void TabLoader::ForceLoadTimerFired() {
force_load_delay_multiplier_ *= 2;
LoadNextTab();
}
void TabLoader::RegisterForNotifications(NavigationController* controller) {
registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
content::Source<WebContents>(controller->GetWebContents()));
// When page almost idle signal is enabled, we don't use onload to help start
// loading next tab, we use page almost idle signal instead.
if (resource_coordinator::IsPageAlmostIdleSignalEnabled())
return;
registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
content::Source<NavigationController>(controller));
}
void TabLoader::HandleTabClosedOrLoaded(NavigationController* controller) {
RemoveTab(controller);
if (delegate_)
LoadNextTab();
}
bool TabLoader::ShouldStopLoadingTabs() const {
if (g_max_loaded_tab_count_for_testing != 0 &&
started_to_load_count_ >= g_max_loaded_tab_count_for_testing)
return true;
if (base::FeatureList::IsEnabled(features::kMemoryCoordinator))
return base::MemoryCoordinatorProxy::GetInstance()->GetCurrentMemoryState()
!= base::MemoryState::NORMAL;
if (base::MemoryPressureMonitor::Get()) {
return base::MemoryPressureMonitor::Get()->GetCurrentPressureLevel() !=
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE;
}
return false;
}
void TabLoader::OnMemoryPressure(
base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
if (ShouldStopLoadingTabs())
StopLoadingTabs();
}
void TabLoader::OnMemoryStateChange(base::MemoryState state) {
switch (state) {
case base::MemoryState::NORMAL:
break;
case base::MemoryState::THROTTLED:
StopLoadingTabs();
break;
case base::MemoryState::SUSPENDED:
// Note that SUSPENDED never occurs in the main browser process so far.
// Fall through.
case base::MemoryState::UNKNOWN:
NOTREACHED();
break;
}
}
void TabLoader::StopLoadingTabs() {
// When receiving a resource pressure level warning, we stop pre-loading more
// tabs since we are running in danger of loading more tabs by throwing out
// old ones.
if (tabs_to_load_.empty())
return;
// Stop the timer and suppress any tab loads while we clean the list.
SetTabLoadingEnabled(false);
while (!tabs_to_load_.empty()) {
NavigationController* tab = tabs_to_load_.front();
tabs_to_load_.pop_front();
RemoveTab(tab);
// Notify the stats collector that a tab's loading has been deferred due to
// memory pressure.
stats_collector_->DeferTab(tab);
}
// By calling |LoadNextTab| explicitly, we make sure that the
// |NOTIFICATION_SESSION_RESTORE_DONE| event gets sent.
LoadNextTab();
}
// static
TabLoader* TabLoader::shared_tab_loader_ = nullptr;
| 4,469
|
4,054
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/gbdt.h>
#include <vespa/eval/eval/vm_forest.h>
#include <vespa/eval/eval/llvm/deinline_forest.h>
#include <vespa/eval/eval/llvm/compiled_function.h>
#include <vespa/eval/eval/function.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/vespalib/util/stringfmt.h>
#include "model.cpp"
using namespace vespalib::eval;
using namespace vespalib::eval::nodes;
using namespace vespalib::eval::gbdt;
double budget = 2.0;
//-----------------------------------------------------------------------------
struct CompileStrategy {
virtual const char *name() const = 0;
virtual const char *code_name() const = 0;
virtual CompiledFunction compile(const Function &function) const = 0;
virtual CompiledFunction compile_lazy(const Function &function) const = 0;
bool is_same(const CompileStrategy &rhs) const {
return (this == &rhs);
}
virtual ~CompileStrategy() {}
};
struct NullStrategy : CompileStrategy {
const char *name() const override {
return "none";
}
const char *code_name() const override {
return "Optimize::none";
}
CompiledFunction compile(const Function &function) const override {
return CompiledFunction(function, PassParams::ARRAY, Optimize::none);
}
CompiledFunction compile_lazy(const Function &function) const override {
return CompiledFunction(function, PassParams::LAZY, Optimize::none);
}
};
NullStrategy none;
struct VMForestStrategy : CompileStrategy {
const char *name() const override {
return "vm-forest";
}
const char *code_name() const override {
return "VMForest::optimize_chain";
}
CompiledFunction compile(const Function &function) const override {
return CompiledFunction(function, PassParams::ARRAY, VMForest::optimize_chain);
}
CompiledFunction compile_lazy(const Function &function) const override {
return CompiledFunction(function, PassParams::LAZY, VMForest::optimize_chain);
}
};
VMForestStrategy vm_forest;
struct DeinlineForestStrategy : CompileStrategy {
const char *name() const override {
return "deinline-forest";
}
const char *code_name() const override {
return "DeinlineForest::optimize_chain";
}
CompiledFunction compile(const Function &function) const override {
return CompiledFunction(function, PassParams::ARRAY, DeinlineForest::optimize_chain);
}
CompiledFunction compile_lazy(const Function &function) const override {
return CompiledFunction(function, PassParams::LAZY, DeinlineForest::optimize_chain);
}
};
DeinlineForestStrategy deinline_forest;
//-----------------------------------------------------------------------------
struct Option {
size_t id;
const CompileStrategy &strategy;
bool is_same(const Option &rhs) const { return strategy.is_same(rhs.strategy); }
const char *name() const { return strategy.name(); }
CompiledFunction compile(const Function &function) const { return strategy.compile(function); }
CompiledFunction compile_lazy(const Function &function) const { return strategy.compile_lazy(function); }
const char *code_name() const { return strategy.code_name(); }
};
std::vector<Option> all_options({{0, none},{1, vm_forest}});
//-----------------------------------------------------------------------------
struct Result {
double us;
size_t opt_idx;
bool operator<(const Result &rhs) const {
return (us < rhs.us);
}
};
struct Segment {
double min;
Option option;
vespalib::string build() const {
return vespalib::make_string("{%g, %zu}", min, option.id);
}
};
struct Plan {
std::vector<Segment> segments;
void add(const Segment &seg) {
if (segments.empty()) {
segments.push_back(seg);
} else {
if (!segments.back().option.is_same(seg.option)) {
segments.push_back(seg);
}
}
}
vespalib::string build() const {
vespalib::string plan;
plan.append("{");
for (size_t i = 0; i < segments.size(); ++i) {
if (i > 0) {
plan.append(", ");
}
plan += segments[i].build();
}
plan.append("}");
return plan;
}
};
//-----------------------------------------------------------------------------
bool crop(const std::vector<Option> &options, const Option &opt, size_t &end) {
for (size_t i = 0; i < end; ++i) {
if (options[i].is_same(opt)) {
end = i;
return true;
}
}
return false;
}
std::vector<Option> keep_contested(const std::vector<Option> &a,
const std::vector<Option> &b)
{
size_t end = b.size();
std::vector<Option> ret;
for (size_t i = 0; (i < a.size()) && (end > 0); ++i) {
if (crop(b, a[i], end)) {
ret.push_back(a[i]);
}
}
return ret;
}
std::vector<Option> find_order(const ForestParams ¶ms,
const std::vector<Option> &options,
size_t num_trees)
{
std::vector<Result> results;
auto forest = make_forest(params, num_trees);
for (size_t i = 0; i < options.size(); ++i) {
CompiledFunction compiled_function = options[i].compile(*forest);
CompiledFunction compiled_function_lazy = options[i].compile_lazy(*forest);
std::vector<double> inputs(compiled_function.num_params(), 0.5);
results.push_back({compiled_function.estimate_cost_us(inputs, budget), i});
double lazy_time = compiled_function_lazy.estimate_cost_us(inputs, budget);
double lazy_factor = lazy_time / results.back().us;
fprintf(stderr, " %20s@%6zu: %16g us (inputs: %zu) [lazy: %g us, factor: %g]\n",
options[i].name(), num_trees, results.back().us,
inputs.size(), lazy_time, lazy_factor);
}
std::sort(results.begin(), results.end());
std::vector<Option> ret;
for (auto result: results) {
ret.push_back(options[result.opt_idx]);
}
return ret;
}
double expected_path(const ForestParams ¶ms, size_t num_trees) {
return ForestStats(extract_trees(make_forest(params, num_trees)->root())).total_expected_path_length;
}
void explore_segment(const ForestParams ¶ms,
const std::vector<Option> &min_order,
const std::vector<Option> &max_order,
size_t min_trees, size_t max_trees,
Plan &plan_out)
{
assert(min_trees != max_trees);
std::vector<Option> options = keep_contested(min_order, max_order);
assert(!options.empty());
if (options.size() == 1) {
plan_out.add(Segment{expected_path(params, min_trees), options[0]});
} else {
if ((max_trees - min_trees) == 1) {
plan_out.add(Segment{expected_path(params, min_trees), min_order[0]});
plan_out.add(Segment{expected_path(params, max_trees), max_order[0]});
} else {
size_t num_trees = (min_trees + max_trees) / 2;
std::vector<Option> order = find_order(params, options, num_trees);
explore_segment(params, min_order, order, min_trees, num_trees, plan_out);
explore_segment(params, order, max_order, num_trees, max_trees, plan_out);
}
}
}
Plan find_plan(const ForestParams ¶ms, std::initializer_list<size_t> limits) {
Plan plan;
auto num_trees = limits.begin();
size_t min_trees = *num_trees++;
std::vector<Option> min_order = find_order(params, all_options, min_trees);
while (num_trees != limits.end()) {
size_t max_trees = *num_trees++;
std::vector<Option> max_order = find_order(params, all_options, max_trees);
explore_segment(params, min_order, max_order, min_trees, max_trees, plan);
std::swap(min_trees, max_trees);
std::swap(min_order, max_order);
}
return plan;
}
//-----------------------------------------------------------------------------
void dump_options(const std::vector<Option> &options) {
fprintf(stdout, "std::vector<Optimize::Chain> options({");
for (size_t i = 0; i < options.size(); ++i) {
if (i > 0) {
fprintf(stdout, ", ");
}
fprintf(stdout, "%s", options[i].code_name());
}
fprintf(stdout, "});\n");
fflush(stdout);
}
void dump_param_values(const char *name, const std::vector<size_t> &values) {
fprintf(stdout, "std::vector<size_t> %s({", name);
for (size_t i = 0; i < values.size(); ++i) {
if (i > 0) {
fprintf(stdout, ", ");
}
fprintf(stdout, "%zu", values[i]);
}
fprintf(stdout, "});\n");
fflush(stdout);
}
void dump_plan(const ForestParams ¶ms, const Plan &plan) {
fprintf(stdout, "{{%zu, %zu}, %s}",
params.less_percent, params.tree_size,
plan.build().c_str());
}
//-----------------------------------------------------------------------------
TEST("find optimization plans") {
std::vector<size_t> less_percent_values({90, 100});
std::vector<size_t> tree_size_values(
{2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16,
18, 20, 22, 24, 26, 28, 30, 32,
36, 40, 44, 48, 52, 56, 60, 64,
72, 80, 88, 96, 104, 112, 120, 128});
dump_options(all_options);
dump_param_values("less_percent_values", less_percent_values);
dump_param_values("tree_size_values", tree_size_values);
size_t num_plans = 0;
fprintf(stdout, "std::map<Params,Plan> plan_repo({");
for (size_t less_percent: less_percent_values) {
for (size_t tree_size: tree_size_values) {
ForestParams params(1234u, less_percent, tree_size);
fprintf(stdout, "%s\n", (num_plans++ == 0) ? "" : ",");
fflush(stdout);
fprintf(stdout, " ");
Plan plan = find_plan(params, {8, 512});
dump_plan(params, plan);
}
}
fprintf(stdout, "});\n");
}
//-----------------------------------------------------------------------------
TEST_MAIN() { TEST_RUN_ALL(); }
| 4,355
|
1,103
|
<reponame>Branlala/docker-sickbeardfr
PACKAGE = "hachoir-metadata"
VERSION = "1.3.3"
WEBSITE = "http://bitbucket.org/haypo/hachoir/wiki/hachoir-metadata"
LICENSE = "GNU GPL v2"
| 81
|
529
|
from dataclasses import dataclass, field
from typing import List, Optional
from ansimarkup import ansiprint
from django.db import connections, transaction
from .config import PostgresPartitioningConfig
from .constants import AUTO_PARTITIONED_COMMENT
from .partition import PostgresPartition
@dataclass
class PostgresModelPartitioningPlan:
"""Describes the partitions that are going to be created/deleted for a
particular partitioning config.
A "partitioning config" applies to one model.
"""
config: PostgresPartitioningConfig
creations: List[PostgresPartition] = field(default_factory=list)
deletions: List[PostgresPartition] = field(default_factory=list)
def apply(self, using: Optional[str]) -> None:
"""Applies this partitioning plan by creating and deleting the planned
partitions.
Applying the plan runs in a transaction.
Arguments:
using:
Name of the database connection to use.
"""
connection = connections[using or "default"]
with transaction.atomic():
with connection.schema_editor() as schema_editor:
for partition in self.creations:
partition.create(
self.config.model,
schema_editor,
comment=AUTO_PARTITIONED_COMMENT,
)
for partition in self.deletions:
partition.delete(self.config.model, schema_editor)
def print(self) -> None:
"""Prints this model plan to the terminal in a readable format."""
ansiprint(f"<b><white>{self.config.model.__name__}:</white></b>")
for partition in self.deletions:
ansiprint("<b><red> - %s</red></b>" % partition.name())
for key, value in partition.deconstruct().items():
ansiprint(f"<white> <b>{key}</b>: {value}</white>")
for partition in self.creations:
ansiprint("<b><green> + %s</green></b>" % partition.name())
for key, value in partition.deconstruct().items():
ansiprint(f"<white> <b>{key}</b>: {value}</white>")
@dataclass
class PostgresPartitioningPlan:
"""Describes the partitions that are going to be created/deleted."""
model_plans: List[PostgresModelPartitioningPlan]
@property
def creations(self) -> List[PostgresPartition]:
"""Gets a complete flat list of the partitions that are going to be
created."""
creations = []
for model_plan in self.model_plans:
creations.extend(model_plan.creations)
return creations
@property
def deletions(self) -> List[PostgresPartition]:
"""Gets a complete flat list of the partitions that are going to be
deleted."""
deletions = []
for model_plan in self.model_plans:
deletions.extend(model_plan.deletions)
return deletions
def apply(self, using: Optional[str] = None) -> None:
"""Applies this plan by creating/deleting all planned partitions."""
for model_plan in self.model_plans:
model_plan.apply(using=using)
def print(self) -> None:
"""Prints this plan to the terminal in a readable format."""
for model_plan in self.model_plans:
model_plan.print()
print("")
create_count = len(self.creations)
delete_count = len(self.deletions)
ansiprint(
f"<b><red>{delete_count} partitions will be deleted</red></b>"
)
ansiprint(
f"<b><green>{create_count} partitions will be created</green></b>"
)
__all__ = ["PostgresPartitioningPlan", "PostgresModelPartitioningPlan"]
| 1,563
|
400
|
package org.ofdrw.core.basicStructure.res.resources;
import org.junit.jupiter.api.Test;
import org.ofdrw.TestTool;
import org.ofdrw.core.basicStructure.res.CT_MultiMediaTest;
import static org.junit.jupiter.api.Assertions.*;
public class MultiMediasTest {
public static MultiMedias multiMediasCase(){
return new MultiMedias()
.addMultiMedia(CT_MultiMediaTest.multiMediaCase());
}
@Test
public void gen() throws Exception {
TestTool.genXml("MultiMedias", multiMediasCase());
}
}
| 210
|
190,993
|
<gh_stars>1000+
/* Copyright 2019 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_LITE_TOOLS_EVALUATION_STAGES_UTILS_IMAGE_METRICS_H_
#define TENSORFLOW_LITE_TOOLS_EVALUATION_STAGES_UTILS_IMAGE_METRICS_H_
#include <stdint.h>
#include <vector>
namespace tflite {
namespace evaluation {
namespace image {
struct Box2D {
struct Interval {
float min = 0;
float max = 0;
Interval(float x, float y) {
min = x;
max = y;
}
Interval() {}
};
Interval x;
Interval y;
static float Length(const Interval& a);
static float Intersection(const Interval& a, const Interval& b);
float Area() const;
float Intersection(const Box2D& other) const;
float Union(const Box2D& other) const;
// Intersection of this box and the given box normalized over the union of
// this box and the given box.
float IoU(const Box2D& other) const;
// Intersection of this box and the given box normalized over the area of
// this box.
float Overlap(const Box2D& other) const;
};
// If the value is:
// - kDontIgnore: The object is included in this evaluation.
// - kIgnoreOneMatch: the first matched prediction bbox will be ignored. This
// is useful when this groundtruth object is not intended to be evaluated.
// - kIgnoreAllMatches: all matched prediction bbox will be ignored. Typically
// it is used to mark an area that has not been labeled.
enum IgnoreType {
kDontIgnore = 0,
kIgnoreOneMatch = 1,
kIgnoreAllMatches = 2,
};
struct Detection {
public:
bool difficult = false;
int64_t imgid = 0;
float score = 0;
Box2D box;
IgnoreType ignore = IgnoreType::kDontIgnore;
Detection() {}
Detection(bool d, int64_t id, float s, Box2D b)
: difficult(d), imgid(id), score(s), box(b) {}
Detection(bool d, int64_t id, float s, Box2D b, IgnoreType i)
: difficult(d), imgid(id), score(s), box(b), ignore(i) {}
};
// Precision and recall.
struct PR {
float p = 0;
float r = 0;
PR(const float p_, const float r_) : p(p_), r(r_) {}
};
class AveragePrecision {
public:
// iou_threshold: A predicted box matches a ground truth box if and only if
// IoU between these two are larger than this iou_threshold. Default: 0.5.
// num_recall_points: AP is computed as the average of maximum precision at (1
// + num_recall_points) recall levels. E.g., if num_recall_points is 10,
// recall levels are 0., 0.1, 0.2, ..., 0.9, 1.0.
// Default: 100. If num_recall_points < 0, AveragePrecision of 0 is returned.
struct Options {
float iou_threshold = 0.5;
int num_recall_points = 100;
};
AveragePrecision() : AveragePrecision(Options()) {}
explicit AveragePrecision(const Options& opts) : opts_(opts) {}
// Given a sequence of precision-recall points ordered by the recall in
// non-increasing order, returns the average of maximum precisions at
// different recall values (0.0, 0.1, 0.2, ..., 0.9, 1.0).
// The p-r pairs at these fixed recall points will be written to pr_out, if
// it is not null_ptr.
float FromPRCurve(const std::vector<PR>& pr,
std::vector<PR>* pr_out = nullptr);
// An axis aligned bounding box for an image with id 'imageid'. Score
// indicates its confidence.
//
// 'difficult' is a special bit specific to Pascal VOC dataset and tasks using
// the data. If 'difficult' is true, by convention, the box is often ignored
// during the AP calculation. I.e., if a predicted box matches a 'difficult'
// ground box, this predicted box is ignored as if the model does not make
// such a prediction.
// Given the set of ground truth boxes and a set of predicted boxes, returns
// the average of the maximum precisions at different recall values.
float FromBoxes(const std::vector<Detection>& groundtruth,
const std::vector<Detection>& prediction,
std::vector<PR>* pr_out = nullptr);
private:
Options opts_;
};
} // namespace image
} // namespace evaluation
} // namespace tflite
#endif // TENSORFLOW_LITE_TOOLS_EVALUATION_STAGES_UTILS_IMAGE_METRICS_H_
| 1,560
|
714
|
package com.mcxiaoke.minicat.api.rest;
import com.mcxiaoke.minicat.api.ApiException;
import org.oauthsimple.model.OAuthToken;
import java.io.IOException;
/**
* @author mcxiaoke
* @version 1.1 2012.02.27
*/
public interface OAuthMethods {
public String getAccount();
public void setAccount(String account);
public OAuthToken getOAuthRequestToken() throws ApiException;
public OAuthToken getOAuthAccessToken(String username, String password)
throws IOException, ApiException;
public void setAccessToken(OAuthToken token);
}
| 188
|
677
|
from __future__ import division
try:
import cPickle as pickle
except ImportError:
import pickle
import io
import os
import random
from collections import Counter, defaultdict
from magpie.base.document import Document
def save_to_disk(path_to_disk, obj, overwrite=False):
""" Pickle an object to disk """
dirname = os.path.dirname(path_to_disk)
if not os.path.exists(dirname):
raise ValueError("Path " + dirname + " does not exist")
if not overwrite and os.path.exists(path_to_disk):
raise ValueError("File " + path_to_disk + "already exists")
pickle.dump(obj, open(path_to_disk, 'wb'))
def load_from_disk(path_to_disk):
""" Load a pickle from disk to memory """
if not os.path.exists(path_to_disk):
raise ValueError("File " + path_to_disk + " does not exist")
return pickle.load(open(path_to_disk, 'rb'))
def get_documents(data_dir, as_generator=True, shuffle=False):
"""
Extract documents from *.txt files in a given directory
:param data_dir: path to the directory with .txt files
:param as_generator: flag whether to return a document generator or a list
:param shuffle: flag whether to return the documents
in a shuffled vs sorted order
:return: generator or a list of Document objects
"""
files = list({filename[:-4] for filename in os.listdir(data_dir)})
files.sort()
if shuffle:
random.shuffle(files)
generator = (Document(doc_id, os.path.join(data_dir, f + '.txt'))
for doc_id, f in enumerate(files))
return generator if as_generator else list(generator)
def get_all_answers(data_dir, filtered_by=None):
"""
Extract ground truth answers from *.lab files in a given directory
:param data_dir: path to the directory with .lab files
:param filtered_by: whether to filter the answers.
:return: dictionary of the form e.g. {'101231': set('lab1', 'lab2') etc.}
"""
answers = dict()
files = {filename[:-4] for filename in os.listdir(data_dir)}
for f in files:
answers[f] = get_answers_for_doc(f + '.txt',
data_dir,
filtered_by=filtered_by)
return answers
def get_answers_for_doc(doc_name, data_dir, filtered_by=None):
"""
Read ground_truth answers from a .lab file corresponding to the doc_name
:param doc_name: the name of the document, should end with .txt
:param data_dir: directory in which the documents and answer files are
:param filtered_by: whether to filter the answers.
:return: set of unicodes containing answers for this particular document
"""
filename = os.path.join(data_dir, doc_name[:-4] + '.lab')
if not os.path.exists(filename):
raise ValueError("Answer file " + filename + " does not exist")
with io.open(filename, 'r') as f:
answers = {line.rstrip('\n') for line in f}
if filtered_by:
answers = {kw for kw in answers if kw in filtered_by}
return answers
def calculate_label_distribution(data_dir, filtered_by=None):
"""
Calculate the distribution of labels in a directory. Function can be used
to find the most frequent and not used labels, so that the target
vocabulary can be trimmed accordingly.
:param data_dir: directory path with the .lab files
:param filtered_by: a set of labels that defines the vocabulary
:return: list of KV pairs of the form (14, ['lab1', 'lab2']), which means
that both lab1 and lab2 were labels in 14 documents
"""
answers = [kw for v in get_all_answers(data_dir, filtered_by=filtered_by).values()
for kw in v]
counts = Counter(answers)
histogram = defaultdict(list)
for kw, cnt in counts.items():
histogram[cnt].append(kw)
return histogram
def calculate_number_of_labels_distribution(data_dir, filtered_by=None):
""" Look how many papers are there with 3 labels, 4 labels etc.
Return a histogram. """
answers = get_all_answers(data_dir, filtered_by=filtered_by).values()
lengths = [len(ans_set) for ans_set in answers]
return Counter(lengths).items()
def get_coverage_ratio_for_label_subset(no_of_labels, hist=None):
"""
Compute fraction of the samples we would be able to predict, if we reduce
the number of labels to a certain subset of the size no_of_labels.
:param no_of_labels: the number of labels that we limit the ontology to
:param hist: histogram of the samples.
Result of calculate_label_distribution function
:return: number of labels that we need to consider, coverage ratio
"""
hist = hist or calculate_label_distribution()
hist = sorted([(k, len(v)) for k, v in hist.items()])
total_shots = sum([x[0] * x[1] for x in hist])
labels_collected = 0
hits_collected = 0
for docs, label_count in reversed(hist):
hits_collected += docs * label_count
labels_collected += label_count
if labels_collected >= no_of_labels:
return labels_collected, hits_collected / float(total_shots)
return -1
def get_top_n_labels(n, hist=None):
"""
Return the n most popular labels
:param n: number of labels to return
:param hist: histogram, result of calculate_label_distribution() function
:return: sorted list of strings
"""
hist = hist or calculate_label_distribution()
labels = sorted([(k, v) for k, v in hist.items()], reverse=True)
answer = []
for _count, kws in labels:
answer.extend(kws)
if len(answer) >= n:
break
return answer[:n]
| 2,088
|
5,169
|
<gh_stars>1000+
{
"name": "MUKContentFetch",
"version": "1.2.0",
"summary": "Retrieve data and transform it to content objects",
"description": "A simple infrastracture to retrieve requested data and transform it to content object",
"homepage": "https://github.com/muccy/MUKContentFetch",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/muccy/MUKContentFetch.git",
"tag": "1.2.0"
},
"platforms": {
"ios": "7.0"
},
"requires_arc": true,
"source_files": "Classes/**/*.{h,m}"
}
| 225
|
1,877
|
package com.stepstone.stepper.sample.test.spoon;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;
import static android.graphics.Bitmap.CompressFormat.PNG;
import static android.graphics.Bitmap.Config.ARGB_8888;
import static com.stepstone.stepper.sample.test.spoon.Chmod.chmodPlusR;
import static com.stepstone.stepper.sample.test.spoon.Chmod.chmodPlusRWX;
/**
* Copied from <a href="https://github.com/square/spoon/blob/parent-1.2.0/spoon-client/src/main/java/com/squareup/spoon/Spoon.java">Github</a>.
* Changed the path where to save the screenshots.
* <p>
* Utility class for capturing screenshots for Spoon.
*/
public final class Spoon {
@SuppressLint("SdCardPath")
private static String REPORTS_DIRECTORY = "/sdcard/material-stepper-screenshots";
private static final String SPOON_SCREENSHOTS = "spoon-screenshots";
private static final String SPOON_FILES = "spoon-files";
private static final String TEST_CASE_CLASS_JUNIT_3 = "android.test.InstrumentationTestCase";
private static final String TEST_CASE_METHOD_JUNIT_3 = "runMethod";
private static final String TEST_CASE_CLASS_JUNIT_4 = "org.junit.runners.model.FrameworkMethod$1";
private static final String TEST_CASE_METHOD_JUNIT_4 = "runReflectiveCall";
private static final String EXTENSION = ".png";
private static final String TAG = "Spoon";
/**
* Take a screenshot with the specified tag. This version allows the caller to manually specify
* the test class name and method name. This is necessary when the screenshot is not called in
* the traditional manner.
*
* @param activity Activity with which to capture a screenshot.
* @param tag Unique tag to further identify the screenshot. Must match [a-zA-Z0-9_-]+.
* @return the image file that was created
*/
public static File screenshot(Activity activity, String tag, String testClassName) {
try {
File screenshotDirectory =
obtainScreenshotDirectory(testClassName);
String screenshotName = tag + EXTENSION;
File screenshotFile = new File(screenshotDirectory, screenshotName);
takeScreenshot(screenshotFile, activity);
Log.d(TAG, "Captured screenshot '" + tag + "'.");
return screenshotFile;
} catch (Exception e) {
Log.d(TAG, "Unable to capture screenshot.", e);
return null;
//throw new RuntimeException("Unable to capture screenshot.", e);
}
}
private static void takeScreenshot(File file, final Activity activity) throws IOException {
View view = activity.getWindow().getDecorView();
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), ARGB_8888);
if (Looper.myLooper() == Looper.getMainLooper()) {
// On main thread already, Just Do It™.
drawDecorViewToBitmap(activity, bitmap);
} else {
// On a background thread, post to main.
final CountDownLatch latch = new CountDownLatch(1);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
drawDecorViewToBitmap(activity, bitmap);
} finally {
latch.countDown();
}
}
});
try {
latch.await();
} catch (InterruptedException e) {
String msg = "Unable to get screenshot " + file.getAbsolutePath();
Log.e(TAG, msg, e);
throw new RuntimeException(msg, e);
}
}
OutputStream fos = null;
try {
fos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(PNG, 100 /* quality */, fos);
chmodPlusR(file);
} finally {
bitmap.recycle();
if (fos != null) {
fos.close();
}
}
}
private static void drawDecorViewToBitmap(Activity activity, Bitmap bitmap) {
Canvas canvas = new Canvas(bitmap);
activity.getWindow().getDecorView().draw(canvas);
}
private static File obtainScreenshotDirectory(String testClassName) throws IllegalAccessException {
return filesDirectory(SPOON_SCREENSHOTS, testClassName);
}
/**
* Alternative to {@link #save(Context, File)}
*
* @param context Context used to access files.
* @param path Path to the file you want to save.
* @return the copy that was created.
*/
public static File save(final Context context, final String path) {
return save(context, new File(path));
}
/**
* Save a file from this test run. The file will be saved under the current class & method.
* The file will be copied to, so make sure all the data you want have been
* written to the file before calling save.
*
* @param context Context used to access files.
* @param file The file to save.
* @return the copy that was created.
*/
public static File save(final Context context, final File file) {
StackTraceElement testClass = findTestClassTraceElement(Thread.currentThread().getStackTrace());
String className = testClass.getClassName().replaceAll("[^A-Za-z0-9._-]", "_");
String methodName = testClass.getMethodName();
return save(className, methodName, file);
}
private static File save(String className, String methodName, File file) {
File filesDirectory = null;
try {
filesDirectory = filesDirectory(SPOON_FILES, className);
if (!file.exists()) {
throw new RuntimeException("Can't find any file at: " + file);
}
File target = new File(filesDirectory, file.getName());
copy(file, target);
Log.d(TAG, "Saved " + file);
return target;
} catch (IllegalAccessException e) {
throw new RuntimeException(("Unable to save file: " + file));
} catch (IOException e) {
throw new RuntimeException("Couldn't copy file " + file + " to " + filesDirectory);
}
}
private static void copy(File source, File target) throws IOException {
Log.d(TAG, "Will copy " + source + " to " + target);
target.createNewFile();
chmodPlusR(target);
final BufferedInputStream is = new BufferedInputStream(new FileInputStream(source));
final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(target));
byte[] buffer = new byte[4096];
while (is.read(buffer) > 0) {
os.write(buffer);
}
is.close();
os.close();
}
private static File filesDirectory(String directoryType, String testClassName) throws IllegalAccessException {
File directory;
directory = new File(REPORTS_DIRECTORY, "app_" + directoryType);
File dirClass = new File(directory, testClassName);
createDir(dirClass);
return dirClass;
}
/**
* Returns the test class element by looking at the method InstrumentationTestCase invokes.
*/
static StackTraceElement findTestClassTraceElement(StackTraceElement[] trace) {
for (int i = trace.length - 1; i >= 0; i--) {
StackTraceElement element = trace[i];
if (TEST_CASE_CLASS_JUNIT_3.equals(element.getClassName()) //
&& TEST_CASE_METHOD_JUNIT_3.equals(element.getMethodName())) {
return trace[i - 3];
}
if (TEST_CASE_CLASS_JUNIT_4.equals(element.getClassName()) //
&& TEST_CASE_METHOD_JUNIT_4.equals(element.getMethodName())) {
return trace[i - 3];
}
}
throw new IllegalArgumentException("Could not find test class!");
}
private static void createDir(File dir) throws IllegalAccessException {
File parent = dir.getParentFile();
if (!parent.exists()) {
createDir(parent);
}
if (!dir.exists() && !dir.mkdirs()) {
throw new IllegalAccessException("Unable to create output dir: " + dir.getAbsolutePath());
}
chmodPlusRWX(dir);
}
private Spoon() {
// No instances.
}
}
| 3,584
|
1,091
|
/*
* Copyright 2016-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.bgpio.types;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onlab.packet.IpPrefix;
import org.onosproject.bgpio.exceptions.BgpParseException;
import org.onosproject.bgpio.util.Constants;
import org.onosproject.bgpio.util.Validation;
import java.nio.ByteBuffer;
import java.util.Objects;
/**
* Provides implementation of IPv4AddressTlv.
*/
public class BgpFsSourcePrefix implements BgpValueType {
public static final byte FLOW_SPEC_TYPE = Constants.BGP_FLOWSPEC_SRC_PREFIX;
public static final int BYTE_IN_BITS = 8;
private byte length;
private IpPrefix ipPrefix;
/**
* Constructor to initialize parameters.
*
* @param length length of the prefix
* @param ipPrefix ip prefix
*/
public BgpFsSourcePrefix(byte length, IpPrefix ipPrefix) {
this.ipPrefix = Preconditions.checkNotNull(ipPrefix);
this.length = length;
}
/**
* Reads the channel buffer and returns object of IPv4AddressTlv.
*
* @param cb channelBuffer
* @return object of flow spec source prefix
* @throws BgpParseException while parsing BgpFsSourcePrefix
*/
public static BgpFsSourcePrefix read(ChannelBuffer cb) throws BgpParseException {
IpPrefix ipPrefix;
int length = cb.readByte();
if (length == 0) {
byte[] prefix = new byte[]{0};
ipPrefix = Validation.bytesToPrefix(prefix, length);
return new BgpFsSourcePrefix((byte) ipPrefix.prefixLength(), ipPrefix);
}
int len = length / BYTE_IN_BITS;
int reminder = length % BYTE_IN_BITS;
if (reminder > 0) {
len = len + 1;
}
if (cb.readableBytes() < len) {
Validation.validateLen(BgpErrorType.UPDATE_MESSAGE_ERROR,
BgpErrorType.MALFORMED_ATTRIBUTE_LIST, cb.readableBytes());
}
byte[] prefix = new byte[len];
cb.readBytes(prefix, 0, len);
ipPrefix = Validation.bytesToPrefix(prefix, length);
return new BgpFsSourcePrefix((byte) ipPrefix.prefixLength(), ipPrefix);
}
/**
* Returns object of this class with specified values.
*
* @param ipPrefix ip prefix
* @param length length of ip prefix
* @return object of this class
*/
public static BgpFsSourcePrefix of(final IpPrefix ipPrefix, final byte length) {
return new BgpFsSourcePrefix(length, ipPrefix);
}
/**
* Returns ip prefix.
*
* @return ipPrefix ip prefix
*/
public IpPrefix ipPrefix() {
return ipPrefix;
}
@Override
public short getType() {
return this.FLOW_SPEC_TYPE;
}
@Override
public int hashCode() {
return Objects.hash(ipPrefix);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof BgpFsSourcePrefix) {
BgpFsSourcePrefix other = (BgpFsSourcePrefix) obj;
return Objects.equals(this.ipPrefix, other.ipPrefix) && Objects.equals(this.length, other.length);
}
return false;
}
@Override
public int write(ChannelBuffer cb) {
int iLenStartIndex = cb.writerIndex();
cb.writeByte(FLOW_SPEC_TYPE);
cb.writeByte(length);
cb.writeInt(ipPrefix.getIp4Prefix().address().toInt());
return cb.writerIndex() - iLenStartIndex;
}
@Override
public int compareTo(Object o) {
if (this.equals(o)) {
return 0;
}
if (o instanceof BgpFsSourcePrefix) {
BgpFsSourcePrefix that = (BgpFsSourcePrefix) o;
if (this.ipPrefix().prefixLength() == that.ipPrefix().prefixLength()) {
ByteBuffer value1 = ByteBuffer.wrap(this.ipPrefix.address().toOctets());
ByteBuffer value2 = ByteBuffer.wrap(that.ipPrefix.address().toOctets());
return value1.compareTo(value2);
}
if (this.ipPrefix().prefixLength() > that.ipPrefix().prefixLength()) {
return 1;
} else if (this.ipPrefix().prefixLength() < that.ipPrefix().prefixLength()) {
return -1;
}
}
return 1;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("FLOW_SPEC_TYPE", FLOW_SPEC_TYPE).add("length", length)
.add("ipPrefix", ipPrefix).toString();
}
}
| 2,177
|
5,169
|
<filename>Specs/b/0/f/gitExample/0.0.1/gitExample.podspec.json<gh_stars>1000+
{
"name": "gitExample",
"version": "0.0.1",
"summary": "gitExample.",
"description": "gitExample描述文件描述文件描述文件",
"homepage": "https://github.com/wangyucuia/gitExample",
"license": "MIT",
"authors": {
"ayilimi": "<EMAIL>"
},
"source": {
"git": "https://github.com/wangyucuia/gitExample.git",
"tag": "0.0.1"
},
"source_files": [
"Classess",
"Classess/*.{h,m}"
],
"exclude_files": "Classes/Exclude",
"platforms": {
"osx": null,
"ios": null,
"tvos": null,
"watchos": null
}
}
| 300
|
18,336
|
<filename>locust/util/rounding.py
def proper_round(val, digits=0):
return round(val + 10 ** (-len(str(val)) - 1), digits)
| 48
|
432
|
<reponame>TGTang/ballcat<filename>ballcat-starters/ballcat-spring-boot-starter-log/src/main/java/com/hccake/ballcat/autoconfigure/log/annotation/EnableOperationLog.java
package com.hccake.ballcat.autoconfigure.log.annotation;
import com.hccake.ballcat.autoconfigure.log.OperationLogAutoConfiguration;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
/**
* @author Hccake
* @version 1.0
* @date 2019/10/15 18:11
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({ OperationLogAutoConfiguration.class })
public @interface EnableOperationLog {
}
| 208
|
729
|
package com.chinalwb.are.demo;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import com.chinalwb.are.AREditText;
import com.chinalwb.are.AREditor;
import com.chinalwb.are.models.AtItem;
import com.chinalwb.are.strategies.AtStrategy;
import com.chinalwb.are.strategies.VideoStrategy;
import com.chinalwb.are.styles.toolbar.ARE_Toolbar;
import com.chinalwb.are.styles.toolbar.ARE_ToolbarDefault;
import com.chinalwb.are.styles.toolbar.IARE_Toolbar;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_AlignmentCenter;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_AlignmentLeft;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_AlignmentRight;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_At;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Bold;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Hr;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Image;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Italic;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Link;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_ListBullet;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_ListNumber;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Quote;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Strikethrough;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Subscript;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Superscript;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Underline;
import com.chinalwb.are.styles.toolitems.ARE_ToolItem_Video;
import com.chinalwb.are.styles.toolitems.IARE_ToolItem;
import static com.chinalwb.are.demo.TextViewActivity.HTML_TEXT;
/**
* All Rights Reserved.
*
* @author <NAME>
*
*/
public class MainActivity extends AppCompatActivity {
private static boolean useOption1 = true;
private static final int REQ_WRITE_EXTERNAL_STORAGE = 10000;
private AREditor arEditor;
private IARE_Toolbar mToolbar;
private AREditText mEditText;
private boolean scrollerAtEnd;
private AtStrategy mAtStrategy = new AtStrategy() {
@Override
public void openAtPage() {
Intent intent = new Intent(MainActivity.this, AtActivity.class);
startActivityForResult(intent, ARE_Toolbar.REQ_AT);
}
@Override
public boolean onItemSelected(AtItem item) {
return false;
}
};
private VideoStrategy mVideoStrategy = new VideoStrategy() {
@Override
public String uploadVideo(Uri uri) {
try {
Thread.sleep(3000); // Do upload here
} catch (Exception e) {
e.printStackTrace();
}
return "http://www.xx.com/x.mp4";
}
@Override
public String uploadVideo(String videoPath) {
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
return "http://www.xx.com/x.mp4";
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
if (useOption1) {
option1();
} else {
option2();
}
String html = "<html><body><p><b>aaaa</b></p><p><i>bbbb</i></p>\n" +
" <p><u>cccc</u></p>\n" +
" <p><span style=\"text-decoration:line-through;\">dddd</span></p>\n" +
" <p style=\"text-align:start;\">Alignleft</p>\n" +
" <p style=\"text-align:center;\">Align center</p>\n" +
" <p style=\"text-align:end;\">Align right</p>\n" +
" <p style=\"text-align:start;\">Align left</p>\n" +
" <p style=\"text-align:start;\">Hello left<span style=\"background-color:#FFFF00;\"> good?</span> yes</p>\n" +
" <p style=\"text-align:start;\">Text color <span style=\"color:#FF5722;\">red </span><span style=\"color:#4CAF50;\">green </span><span style=\"color:#2196F3;\">blue </span><span style=\"color:#9C27B0;\">purple</span><span style=\"color:#000000;\"> normal black</span></p>\n" +
" <br>\n" +
" <p style=\"text-align:start;\">Click to open <a href=\"http://www.qq.com\">QQ</a> website</p>\n" +
" <br><br>\n" +
" <blockquote><p style=\"text-align:start;\">Quote</p>\n" +
" <p style=\"text-align:start;\">Quote 2nd line</p>\n" +
" <br>\n" +
" </blockquote>\n" +
" <br><br>\n" +
" <p style=\"text-align:start;\">2X<sub>1</sub><sup>2 </sup>+3X<sub>1</sub><sup>2</sup>=5X<sub>1</sub><sup>2</sup></p>\n" +
" <br>\n" +
" <br>\n" +
" <p style=\"text-align:start;\"><hr /> </p>\n" +
" <p style=\"text-align:start;\">Text <span style=\"font-size:32px\";>SIZE </span><span style=\"font-size:18px\";><span style=\"font-size:21px\";>normal</span></span></p>\n" +
" <br>\n" +
" <p style=\"text-align:center;\"><img src=\"emoji|" + R.drawable.wx_d_8 + "\"></p>\n" +
" <p style=\"text-align:start;\">Image:</p>\n" +
" <p style=\"text-align:start;\"><img src=\"http://d.hiphotos.baidu.com/image/pic/item/6159252dd42a2834171827b357b5c9ea14cebfcf.jpg\" /></p>\n" +
" <p style=\"text-align:start;\"></p>\n" +
" <p><a href=\"#\" ukey=\"2131230814\" uname=\"<NAME>\" style=\"color:#FF00FF;\">@<NAME></a>, <a href=\"#\" ukey=\"2131230815\" uname=\"<NAME>\" style=\"color:#0000FF;\"><NAME></a>, how are you?</p>" +
" <p style=\"text-align:start;\"><emoji src=\"2131230915\" /><emoji src=\"2131230936\" /><emoji src=\"2131230929\" /></p>" +
" <ul>" +
" <li>aa</li>" +
" <li>bb</li>\n" +
" <li>dd</li>\n" +
" <li>eea</li>\n" +
" </ul>" +
" <ol>\n" +
" <li>ddasdf</li>\n" +
" <li>sdf</li>\n" +
" <li>cc</li>\n" +
" </ol>" +
" <p style=\"text-align:center;\"><video src=\"http://ivi.bupt.edu.cn/hls/cctv6hd.m3u8\" controls=\"controls\"></video></p>" +
" <p style=\"text-align:start;\"><img src=\"http://a.hiphotos.baidu.com/image/h%3D300/sign=13dc7fee3512b31bd86ccb29b6193674/730e0cf3d7ca7bcb6a172486b2096b63f624a82f.jpg\" /></p>" +
" </body></html>";
if (useOption1) {
// mEditText.fromHtml(html);
} else {
arEditor.fromHtml(html);
}
}
private void option2() {
this.arEditor = this.findViewById(R.id.areditor);
// this.arEditor.setHideToolbar(false);
// this.arEditor.setExpandMode(AREditor.ExpandMode.FULL);
// this.arEditor.setToolbarAlignment(AREditor.ToolbarAlignment.BOTTOM);
this.arEditor.setAtStrategy(mAtStrategy);
this.arEditor.setVideoStrategy(mVideoStrategy);
}
private void option1() {
mToolbar = this.findViewById(R.id.areToolbar);
IARE_ToolItem bold = new ARE_ToolItem_Bold();
IARE_ToolItem italic = new ARE_ToolItem_Italic();
IARE_ToolItem underline = new ARE_ToolItem_Underline();
IARE_ToolItem strikethrough = new ARE_ToolItem_Strikethrough();
IARE_ToolItem quote = new ARE_ToolItem_Quote();
IARE_ToolItem listNumber = new ARE_ToolItem_ListNumber();
IARE_ToolItem listBullet = new ARE_ToolItem_ListBullet();
IARE_ToolItem hr = new ARE_ToolItem_Hr();
IARE_ToolItem link = new ARE_ToolItem_Link();
IARE_ToolItem subscript = new ARE_ToolItem_Subscript();
IARE_ToolItem superscript = new ARE_ToolItem_Superscript();
IARE_ToolItem left = new ARE_ToolItem_AlignmentLeft();
IARE_ToolItem center = new ARE_ToolItem_AlignmentCenter();
IARE_ToolItem right = new ARE_ToolItem_AlignmentRight();
IARE_ToolItem image = new ARE_ToolItem_Image();
IARE_ToolItem video = new ARE_ToolItem_Video();
IARE_ToolItem at = new ARE_ToolItem_At();
mToolbar.addToolbarItem(bold);
mToolbar.addToolbarItem(italic);
mToolbar.addToolbarItem(underline);
mToolbar.addToolbarItem(strikethrough);
mToolbar.addToolbarItem(quote);
mToolbar.addToolbarItem(listNumber);
mToolbar.addToolbarItem(listBullet);
mToolbar.addToolbarItem(hr);
mToolbar.addToolbarItem(link);
mToolbar.addToolbarItem(subscript);
mToolbar.addToolbarItem(superscript);
mToolbar.addToolbarItem(left);
mToolbar.addToolbarItem(center);
mToolbar.addToolbarItem(right);
mToolbar.addToolbarItem(image);
mToolbar.addToolbarItem(video);
mToolbar.addToolbarItem(at);
mEditText = this.findViewById(R.id.yView);
mEditText.setToolbar(mToolbar);
initToolbarArrow();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(com.chinalwb.are.R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int menuId = item.getItemId();
if (menuId == com.chinalwb.are.R.id.action_save) {
if (useOption1) {
String html = this.mEditText.getHtml();
DemoUtil.saveHtml(this, html);
} else {
String html = this.arEditor.getHtml();
DemoUtil.saveHtml(this, html);
}
return true;
}
if (menuId == R.id.action_show_tv) {
String html = "";
if (useOption1) {
html = this.mEditText.getHtml();
} else {
html = this.arEditor.getHtml();
}
Intent intent = new Intent(this, TextViewActivity.class);
intent.putExtra(HTML_TEXT, html);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private void initToolbarArrow() {
final ImageView imageView = this.findViewById(R.id.arrow);
if (this.mToolbar instanceof ARE_ToolbarDefault) {
((ARE_ToolbarDefault) mToolbar).getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
int scrollX = ((ARE_ToolbarDefault) mToolbar).getScrollX();
int scrollWidth = ((ARE_ToolbarDefault) mToolbar).getWidth();
int fullWidth = ((ARE_ToolbarDefault) mToolbar).getChildAt(0).getWidth();
if (scrollX + scrollWidth < fullWidth) {
imageView.setImageResource(R.drawable.arrow_right);
scrollerAtEnd = false;
} else {
imageView.setImageResource(R.drawable.arrow_left);
scrollerAtEnd = true;
}
}
});
}
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (scrollerAtEnd) {
((ARE_ToolbarDefault) mToolbar).smoothScrollBy(-Integer.MAX_VALUE, 0);
scrollerAtEnd = false;
} else {
int hsWidth = ((ARE_ToolbarDefault) mToolbar).getChildAt(0).getWidth();
((ARE_ToolbarDefault) mToolbar).smoothScrollBy(hsWidth, 0);
scrollerAtEnd = true;
}
}
});
}
/**
* The layout file.
*/
private int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_WRITE_EXTERNAL_STORAGE) {
String html = this.arEditor.getHtml();
DemoUtil.saveHtml(this, html);
return;
}
if (useOption1) {
mToolbar.onActivityResult(requestCode, resultCode, data);
} else {
this.arEditor.onActivityResult(requestCode, resultCode, data);
}
}
}
| 6,234
|
478
|
<reponame>sbt-tbs/owr_with_oculus
/*
* Copyright 2007 Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* on the rights to use, copy, modify, merge, publish, distribute, sub
* license, and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* Author: <NAME> <<EMAIL>> */
#include "edid.h"
#include <stdint.h>
#include <math.h>
#include <memory.h>
#include <X11/Xatom.h>
static int get_bit(int in, int bit) {
return (in & (1 << bit)) >> bit;
}
static int get_bits(int in, int begin, int end) {
int mask = (1 << (end - begin + 1)) - 1;
return (in >> begin) & mask;
}
static bool decode_header(const uint8_t *edid) {
if (memcmp(edid, "\x00\xff\xff\xff\xff\xff\xff\x00", 8) == 0)
return true;
return false;
}
static int decode_vendor_and_product_identification(const uint8_t *edid, MonitorInfo *info) {
/* Manufacturer Code */
info->manufacturer_code[0] = get_bits(edid[0x08], 2, 6);
info->manufacturer_code[1] = get_bits(edid[0x08], 0, 1) << 3;
info->manufacturer_code[1] |= get_bits(edid[0x09], 5, 7);
info->manufacturer_code[2] = get_bits(edid[0x09], 0, 4);
info->manufacturer_code[3] = '\0';
info->manufacturer_code[0] += 'A' - 1;
info->manufacturer_code[1] += 'A' - 1;
info->manufacturer_code[2] += 'A' - 1;
/* Product Code */
info->product_code = edid[0x0b] << 8 | edid[0x0a];
/* Serial Number */
info->serial_number = edid[0x0c] | edid[0x0d] << 8 | edid[0x0e] << 16 | edid[0x0f] << 24;
/* Week and Year */
bool is_model_year = false;
switch (edid[0x10]) {
case 0x00:
info->production_week = -1;
break;
case 0xff:
info->production_week = -1;
is_model_year = true;
break;
default:
info->production_week = edid[0x10];
break;
}
if (is_model_year) {
info->production_year = -1;
info->model_year = 1990 + edid[0x11];
} else {
info->production_year = 1990 + edid[0x11];
info->model_year = -1;
}
return true;
}
static bool decode_edid_version(const uint8_t *edid, MonitorInfo *info) {
info->major_version = edid[0x12];
info->minor_version = edid[0x13];
return true;
}
static bool decode_display_parameters(const uint8_t *edid, MonitorInfo *info) {
/* Digital vs Analog */
info->is_digital = get_bit(edid[0x14], 7);
if (info->is_digital) {
static const int bit_depth[8] = { -1, 6, 8, 10, 12, 14, 16, -1 };
static const Interface interfaces[6] = { UNDEFINED, DVI, HDMI_A, HDMI_B, MDDI, DISPLAY_PORT };
int bits = get_bits(edid[0x14], 4, 6);
info->connector.digital.bits_per_primary = bit_depth[bits];
bits = get_bits(edid[0x14], 0, 3);
if (bits <= 5)
info->connector.digital.interface = interfaces[bits];
else
info->connector.digital.interface = UNDEFINED;
} else {
int bits = get_bits(edid[0x14], 5, 6);
static const double levels[][3] = { //
{ 0.7, 0.3, 1.0 }, //
{ 0.714, 0.286, 1.0 }, //
{ 1.0, 0.4, 1.4 }, //
{ 0.7, 0.0, 0.7 }, //
};
info->connector.analog.video_signal_level = levels[bits][0];
info->connector.analog.sync_signal_level = levels[bits][1];
info->connector.analog.total_signal_level = levels[bits][2];
info->connector.analog.blank_to_black = get_bit(edid[0x14], 4);
info->connector.analog.separate_hv_sync = get_bit(edid[0x14], 3);
info->connector.analog.composite_sync_on_h = get_bit(edid[0x14], 2);
info->connector.analog.composite_sync_on_green = get_bit(edid[0x14], 1);
info->connector.analog.serration_on_vsync = get_bit(edid[0x14], 0);
}
/* Screen Size / Aspect Ratio */
if (edid[0x15] == 0 && edid[0x16] == 0) {
info->width_mm = -1;
info->height_mm = -1;
info->aspect_ratio = -1.0;
} else if (edid[0x16] == 0) {
info->width_mm = -1;
info->height_mm = -1;
info->aspect_ratio = 100.0 / (edid[0x15] + 99);
} else if (edid[0x15] == 0) {
info->width_mm = -1;
info->height_mm = -1;
info->aspect_ratio = 100.0 / (edid[0x16] + 99);
info->aspect_ratio = 1 / info->aspect_ratio; /* portrait */
} else {
info->width_mm = 10 * edid[0x15];
info->height_mm = 10 * edid[0x16];
}
/* Gamma */
if (edid[0x17] == 0xFF)
info->gamma = -1.0;
else
info->gamma = (edid[0x17] + 100.0) / 100.0;
/* Features */
info->standby = get_bit(edid[0x18], 7);
info->suspend = get_bit(edid[0x18], 6);
info->active_off = get_bit(edid[0x18], 5);
if (info->is_digital) {
info->connector.digital.rgb444 = 1;
if (get_bit(edid[0x18], 3))
info->connector.digital.ycrcb444 = 1;
if (get_bit(edid[0x18], 4))
info->connector.digital.ycrcb422 = 1;
} else {
int bits = get_bits(edid[0x18], 3, 4);
ColorType color_type[4] = { MONOCHROME, RGB, OTHER_COLOR, UNDEFINED_COLOR };
info->connector.analog.color_type = color_type[bits];
}
info->srgb_is_standard = get_bit(edid[0x18], 2);
/* In 1.3 this is called "has preferred timing" */
info->preferred_timing_includes_native = get_bit(edid[0x18], 1);
/* FIXME: In 1.3 this indicates whether the monitor accepts GTF */
info->continuous_frequency = get_bit(edid[0x18], 0);
return true;
}
static double decode_fraction(int high, int low) {
double result = 0.0;
high = (high << 2) | low;
for (int i = 0; i < 10; ++i)
result += get_bit(high, i) * pow(2, i - 10);
return result;
}
static bool decode_color_characteristics(const uint8_t *edid, MonitorInfo *info) {
info->red_x = decode_fraction(edid[0x1b], get_bits(edid[0x19], 6, 7));
info->red_y = decode_fraction(edid[0x1c], get_bits(edid[0x19], 5, 4));
info->green_x = decode_fraction(edid[0x1d], get_bits(edid[0x19], 2, 3));
info->green_y = decode_fraction(edid[0x1e], get_bits(edid[0x19], 0, 1));
info->blue_x = decode_fraction(edid[0x1f], get_bits(edid[0x1a], 6, 7));
info->blue_y = decode_fraction(edid[0x20], get_bits(edid[0x1a], 4, 5));
info->white_x = decode_fraction(edid[0x21], get_bits(edid[0x1a], 2, 3));
info->white_y = decode_fraction(edid[0x22], get_bits(edid[0x1a], 0, 1));
return true;
}
static bool decode_established_timings(const uint8_t *edid, MonitorInfo *info) {
static const Timing established[][8] = { //
{ { 800, 600, 60 }, { 800, 600, 56 }, //
{ 640, 480, 75 }, { 640, 480, 72 }, //
{ 640, 480, 67 }, { 640, 480, 60 }, //
{ 720, 400, 88 }, { 720, 400, 70 } }, //
{ { 1280, 1024, 75 }, { 1024, 768, 75 }, //
{ 1024, 768, 70 }, { 1024, 768, 60 }, //
{ 1024, 768, 87 }, { 832, 624, 75 }, //
{ 800, 600, 75 }, { 800, 600, 72 } }, //
{ { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, //
{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 1152, 870, 75 } }, //
};
int idx = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 8; ++j) {
int byte = edid[0x23 + i];
if (get_bit(byte, j) && established[i][j].frequency != 0)
info->established[idx++] = established[i][j];
}
}
return true;
}
static bool decode_standard_timings(const uint8_t *edid, MonitorInfo *info) {
int i;
for (i = 0; i < 8; i++) {
int first = edid[0x26 + 2 * i];
int second = edid[0x27 + 2 * i];
if (first != 0x01 && second != 0x01) {
int w = 8 * (first + 31);
int h = 0;
switch (get_bits(second, 6, 7)) {
case 0x00:
h = (w / 16) * 10;
break;
case 0x01:
h = (w / 4) * 3;
break;
case 0x02:
h = (w / 5) * 4;
break;
case 0x03:
h = (w / 16) * 9;
break;
}
info->standard[i].width = w;
info->standard[i].height = h;
info->standard[i].frequency = get_bits(second, 0, 5) + 60;
}
}
return true;
}
static void decode_lf_string(const uint8_t *s, int n_chars, char *result) {
int i;
for (i = 0; i < n_chars; ++i) {
if (s[i] == 0x0a) {
*result++ = '\0';
break;
} else if (s[i] == 0x00) {
/* Convert embedded 0's to spaces */
*result++ = ' ';
} else {
*result++ = s[i];
}
}
}
static void decode_display_descriptor(const uint8_t *desc, MonitorInfo *info) {
switch (desc[0x03]) {
case 0xFC:
decode_lf_string(desc + 5, 13, info->dsc_product_name);
break;
case 0xFF:
decode_lf_string(desc + 5, 13, info->dsc_serial_number);
break;
case 0xFE:
decode_lf_string(desc + 5, 13, info->dsc_string);
break;
case 0xFD:
/* Range Limits */
break;
case 0xFB:
/* Color Point */
break;
case 0xFA:
/* Timing Identifications */
break;
case 0xF9:
/* Color Management */
break;
case 0xF8:
/* Timing Codes */
break;
case 0xF7:
/* Established Timings */
break;
case 0x10:
break;
}
}
static void decode_detailed_timing(const uint8_t *timing, DetailedTiming *detailed) {
int bits;
StereoType stereo[] = { //
NO_STEREO, NO_STEREO, //
FIELD_RIGHT, FIELD_LEFT, //
TWO_WAY_RIGHT_ON_EVEN, TWO_WAY_LEFT_ON_EVEN, //
FOUR_WAY_INTERLEAVED, //
SIDE_BY_SIDE //
};
detailed->pixel_clock = (timing[0x00] | timing[0x01] << 8) * 10000;
detailed->h_addr = timing[0x02] | ((timing[0x04] & 0xf0) << 4);
detailed->h_blank = timing[0x03] | ((timing[0x04] & 0x0f) << 8);
detailed->v_addr = timing[0x05] | ((timing[0x07] & 0xf0) << 4);
detailed->v_blank = timing[0x06] | ((timing[0x07] & 0x0f) << 8);
detailed->h_front_porch = timing[0x08] | get_bits(timing[0x0b], 6, 7) << 8;
detailed->h_sync = timing[0x09] | get_bits(timing[0x0b], 4, 5) << 8;
detailed->v_front_porch = get_bits(timing[0x0a], 4, 7) | get_bits(timing[0x0b], 2, 3) << 4;
detailed->v_sync = get_bits(timing[0x0a], 0, 3) | get_bits(timing[0x0b], 0, 1) << 4;
detailed->width_mm = timing[0x0c] | get_bits(timing[0x0e], 4, 7) << 8;
detailed->height_mm = timing[0x0d] | get_bits(timing[0x0e], 0, 3) << 8;
detailed->right_border = timing[0x0f];
detailed->top_border = timing[0x10];
detailed->interlaced = get_bit(timing[0x11], 7);
/* Stereo */
bits = get_bits(timing[0x11], 5, 6) << 1 | get_bit(timing[0x11], 0);
detailed->stereo = stereo[bits];
/* Sync */
bits = timing[0x11];
detailed->digital_sync = get_bit(bits, 4);
if (detailed->digital_sync) {
detailed->connector.digital.composite = !get_bit(bits, 3);
if (detailed->connector.digital.composite) {
detailed->connector.digital.serrations = get_bit(bits, 2);
detailed->connector.digital.negative_vsync = 0;
} else {
detailed->connector.digital.serrations = 0;
detailed->connector.digital.negative_vsync = !get_bit(bits, 2);
}
detailed->connector.digital.negative_hsync = !get_bit(bits, 0);
} else {
detailed->connector.analog.bipolar = get_bit(bits, 3);
detailed->connector.analog.serrations = get_bit(bits, 2);
detailed->connector.analog.sync_on_green = !get_bit(bits, 1);
}
}
static bool decode_descriptors(const uint8_t *edid, MonitorInfo *info) {
int timing_idx = 0;
for (int i = 0; i < 4; ++i) {
int index = 0x36 + i * 18;
if (edid[index + 0] == 0x00 && edid[index + 1] == 0x00) {
decode_display_descriptor(edid + index, info);
} else {
decode_detailed_timing(edid + index, &(info->detailed_timings[timing_idx++]));
}
}
info->n_detailed_timings = timing_idx;
return true;
}
static void decode_check_sum(const uint8_t *edid, MonitorInfo *info) {
uint8_t check = 0;
for (int i = 0; i < 128; ++i)
check += edid[i];
info->checksum = check;
}
MonitorInfo * decode_edid(const uint8_t *edid) {
MonitorInfo *info = new MonitorInfo();
decode_check_sum(edid, info);
if (decode_header(edid) && //
decode_vendor_and_product_identification(edid, info) && //
decode_edid_version(edid, info) && //
decode_display_parameters(edid, info) && //
decode_color_characteristics(edid, info) && //
decode_established_timings(edid, info) && //
decode_standard_timings(edid, info) && //
decode_descriptors(edid, info)) {
return info;
} else {
delete info;
return 0;
}
}
static uint8_t * get_property(Display *dpy, RROutput output, Atom atom, int *len) {
unsigned char *prop;
int actual_format;
unsigned long nitems, bytes_after;
Atom actual_type;
uint8_t *result = NULL;
XRRGetOutputProperty(dpy, output, atom, 0, 100, False, False,
AnyPropertyType, &actual_type, &actual_format, &nitems, &bytes_after, &prop);
if (actual_type == XA_INTEGER && actual_format == 8) {
result = new uint8_t[nitems];
memcpy(result, prop, nitems);
if (len)
*len = nitems;
}
XFree(prop);
return result;
}
MonitorInfo * read_edid_data(Display * disp, RROutput id) {
int len;
Atom edid_atom = XInternAtom(disp, "EDID", false);
uint8_t *edid = get_property(disp, id, edid_atom, &len);
if (!edid) {
edid_atom = XInternAtom(disp, "EDID_DATA", false);
edid = get_property(disp, id, edid_atom, &len);
}
MonitorInfo * result = 0;
if (edid) {
if (len % 128 == 0) {
result = decode_edid(edid);
}
delete[] edid;
}
return result;
}
| 7,163
|
313
|
<reponame>timgates42/mps<gh_stars>100-1000
/* shield.c: SHIELD IMPLEMENTATION
*
* $Id$
* Copyright (c) 2001-2020 Ravenbrook Limited. See end of file for license.
*
* See: idea.shield, <design/shield>.
*
* IMPORTANT: HERE BE DRAGONS! This code is subtle and
* critical. Ensure you have read and understood <design/shield>
* before you touch it.
*/
#include "mpm.h"
SRCID(shield, "$Id$");
void ShieldInit(Shield shield)
{
shield->inside = FALSE;
shield->suspended = FALSE;
shield->queuePending = FALSE;
shield->queue = NULL;
shield->length = 0;
shield->next = 0;
shield->limit = 0;
shield->depth = 0;
shield->unsynced = 0;
shield->holds = 0;
shield->sig = ShieldSig;
}
void ShieldDestroyQueue(Shield shield, Arena arena)
{
AVER(shield->limit == 0); /* queue must be empty */
if (shield->length != 0) {
AVER(shield->queue != NULL);
ControlFree(arena, shield->queue,
shield->length * sizeof shield->queue[0]);
shield->queue = NULL;
shield->length = 0;
}
}
void ShieldFinish(Shield shield)
{
/* The queue should already have been destroyed by
GlobalsPrepareToDestroy calling ShieldDestroyQueue. */
AVER(shield->length == 0);
AVER(shield->limit == 0);
AVER(shield->queue == NULL);
AVER(shield->depth == 0);
AVER(shield->unsynced == 0);
AVER(shield->holds == 0);
shield->sig = SigInvalid;
}
static Bool SegIsSynced(Seg seg);
Bool ShieldCheck(Shield shield)
{
CHECKS(Shield, shield);
/* Can't check Boolean bitfields <design/type#.bool.bitfield.check> */
CHECKL(shield->queue == NULL || shield->length > 0);
CHECKL(shield->limit <= shield->length);
CHECKL(shield->next <= shield->limit);
/* The mutator is not suspended while outside the shield
<design/shield#.inv.outside.running>. */
CHECKL(shield->inside || !shield->suspended);
/* If any segment is not synced, the mutator is suspended
<design/shield#.inv.unsynced.suspended>. */
CHECKL(shield->unsynced == 0 || shield->suspended);
/* The total depth is zero while outside the shield
<design/shield#.inv.outside.depth>. */
CHECKL(shield->inside || shield->depth == 0);
/* There are no unsynced segments when we're outside the shield. */
CHECKL(shield->inside || shield->unsynced == 0);
/* Every unsynced segment should be on the queue, because we have to
remember to sync it before we return to the mutator. */
CHECKL(shield->limit + shield->queuePending >= shield->unsynced);
/* The mutator is suspeneded if there are any holds. */
CHECKL(shield->holds == 0 || shield->suspended);
/* This is too expensive to check all the time since we have an
expanding shield queue that often has 16K elements instead of
16. */
#if defined(AVER_AND_CHECK_ALL)
{
Count unsynced = 0;
Index i;
for (i = 0; i < shield->limit; ++i) {
Seg seg = shield->queue[i];
CHECKD(Seg, seg);
if (!SegIsSynced(seg))
++unsynced;
}
CHECKL(unsynced + shield->queuePending == shield->unsynced);
}
#endif
return TRUE;
}
Res ShieldDescribe(Shield shield, mps_lib_FILE *stream, Count depth)
{
Res res;
res = WriteF(stream, depth,
"Shield $P {\n", (WriteFP)shield,
" ", shield->inside ? "inside" : "outside", " shield\n",
" suspended $S\n", WriteFYesNo(shield->suspended),
" depth $U\n", (WriteFU)shield->depth,
" next $U\n", (WriteFU)shield->next,
" length $U\n", (WriteFU)shield->length,
" unsynced $U\n", (WriteFU)shield->unsynced,
" holds $U\n", (WriteFU)shield->holds,
"} Shield $P\n", (WriteFP)shield,
NULL);
if (res != ResOK)
return res;
return ResOK;
}
/* SHIELD_AVER -- transgressive argument checking
*
* .trans.check: A number of shield functions cannot do normal
* argument checking with AVERT because (for example) SegCheck checks
* the shield invariants, and it is these functions that are enforcing
* them. Instead, we AVER(TESTT(Seg, seg)) to check the type
* signature but not the contents.
*/
#define SHIELD_AVERT(type, exp) AVER(TESTT(type, exp))
#define SHIELD_AVERT_CRITICAL(type, exp) AVER_CRITICAL(TESTT(type, exp))
/* SegIsSynced -- is a segment synced?
*
* <design/shield#.def.synced>.
*/
static Bool SegIsSynced(Seg seg)
{
SHIELD_AVERT_CRITICAL(Seg, seg);
return SegSM(seg) == SegPM(seg);
}
/* shieldSetSM -- set shield mode, maintaining sync count */
static void shieldSetSM(Shield shield, Seg seg, AccessSet mode)
{
if (SegSM(seg) != mode) {
if (SegIsSynced(seg)) {
SegSetSM(seg, mode);
++shield->unsynced;
} else {
SegSetSM(seg, mode);
if (SegIsSynced(seg)) {
AVER(shield->unsynced > 0);
--shield->unsynced;
}
}
}
}
/* shieldSetPM -- set protection mode, maintaining sync count */
static void shieldSetPM(Shield shield, Seg seg, AccessSet mode)
{
if (SegPM(seg) != mode) {
if (SegIsSynced(seg)) {
SegSetPM(seg, mode);
++shield->unsynced;
} else {
SegSetPM(seg, mode);
if (SegIsSynced(seg)) {
AVER(shield->unsynced > 0);
--shield->unsynced;
}
}
}
}
/* SegIsExposed -- is a segment exposed?
*
* <design/shield#.def.exposed>.
*/
static Bool SegIsExposed(Seg seg)
{
SHIELD_AVERT_CRITICAL(Seg, seg);
return seg->depth > 0;
}
/* shieldSync -- synchronize a segment's protection
*
* <design/shield#.inv.prot.shield>.
*/
static void shieldSync(Shield shield, Seg seg)
{
SHIELD_AVERT_CRITICAL(Seg, seg);
if (!SegIsSynced(seg)) {
shieldSetPM(shield, seg, SegSM(seg));
ProtSet(SegBase(seg), SegLimit(seg), SegPM(seg));
}
}
/* shieldSuspend -- suspend the mutator
*
* Called from inside <code/shield.c> when any segment is not synced, in
* order to provide exclusive access to the segment by the MPS. See
* .inv.unsynced.suspended.
*/
static void shieldSuspend(Arena arena)
{
Shield shield;
AVERT(Arena, arena);
shield = ArenaShield(arena);
AVER(shield->inside);
if (!shield->suspended) {
ThreadRingSuspend(ArenaThreadRing(arena), ArenaDeadRing(arena));
shield->suspended = TRUE;
}
}
/* ShieldHold -- suspend mutator access to the unprotectable
*
* From outside <code/shield.c>, this is used when we really need to
* lock everything against the mutator -- for example, during flip
* when we must scan all thread registers at once.
*/
void (ShieldHold)(Arena arena)
{
AVERT(Arena, arena);
shieldSuspend(arena);
++ArenaShield(arena)->holds;
}
/* ShieldRelease -- declare mutator could be resumed
*
* In practice, we don't resume the mutator until ShieldLeave, but
* this marks the earliest point at which we could resume.
*/
void (ShieldRelease)(Arena arena)
{
Shield shield;
AVERT(Arena, arena);
shield = ArenaShield(arena);
AVER(shield->inside);
AVER(shield->suspended);
AVER(shield->holds > 0);
--shield->holds;
/* It is only correct to actually resume the mutator here if
shield->depth is 0, shield->unsycned is 0, and the queue is
empty. */
/* See <design/shield#.improv.resume> for a discussion of when it
might be a good idea to resume the mutator early. */
}
/* shieldProtLower -- reduce protection on a segment
*
* This ensures actual prot mode does not include mode.
*/
static void shieldProtLower(Shield shield, Seg seg, AccessSet mode)
{
/* <design/trace#.fix.noaver> */
SHIELD_AVERT_CRITICAL(Seg, seg);
AVERT_CRITICAL(AccessSet, mode);
if (BS_INTER(SegPM(seg), mode) != AccessSetEMPTY) {
shieldSetPM(shield, seg, BS_DIFF(SegPM(seg), mode));
ProtSet(SegBase(seg), SegLimit(seg), SegPM(seg));
}
}
/* shieldDequeue -- remove a segment from the shield queue */
static Seg shieldDequeue(Shield shield, Index i)
{
Seg seg;
AVER(i < shield->limit);
seg = shield->queue[i];
AVERT(Seg, seg);
AVER(seg->queued);
shield->queue[i] = NULL; /* to ensure it can't get re-used */
seg->queued = FALSE;
return seg;
}
/* shieldFlushEntry -- flush a single entry from the queue
*
* If the segment is exposed we can simply dequeue it, because later
* there will be a call to ShieldCover that will put it back on the
* queue. If the segment is not exposed, we can sync its protection.
* (And if it does not have the shield raised any more, that will do
* nothing.)
*/
static void shieldFlushEntry(Shield shield, Index i)
{
Seg seg = shieldDequeue(shield, i);
if (!SegIsExposed(seg))
shieldSync(shield, seg);
}
/* shieldQueueReset -- reset shield queue pointers */
static void shieldQueueReset(Shield shield)
{
AVER(shield->depth == 0); /* overkill: implies no segs are queued */
AVER(shield->unsynced == 0);
shield->next = 0;
shield->limit = 0;
}
/* shieldQueueEntryCompare -- comparison for queue sorting */
static Compare shieldAddrCompare(Addr left, Addr right)
{
if (left < right)
return CompareLESS;
else if (left == right)
return CompareEQUAL;
else
return CompareGREATER;
}
static Compare shieldQueueEntryCompare(void *left, void *right, void *closure)
{
Seg segA = left, segB = right;
/* These checks are not critical in a hot build, but slow down cool
builds quite a bit, so just check the signatures. */
AVER(TESTT(Seg, segA));
AVER(TESTT(Seg, segB));
UNUSED(closure);
return shieldAddrCompare(SegBase(segA), SegBase(segB));
}
/* shieldFlushEntries -- flush queue coalescing protects
*
* Sort the shield queue into address order, then iterate over it
* coalescing protection work, in order to reduce the number of system
* calls to a minimum. This is very important on macOS, where
* protection calls are extremely inefficient, but has no net gain on
* Windows.
*
* TODO: Could we keep extending the outstanding area over memory
* that's *not* in the queue but has the same protection mode? Might
* require <design/shield#.improve.noseg>.
*/
static void shieldFlushEntries(Shield shield)
{
Addr base = NULL, limit;
AccessSet mode;
Index i;
if (shield->length == 0) {
AVER(shield->queue == NULL);
return;
}
QuickSort((void *)shield->queue, shield->limit,
shieldQueueEntryCompare, UNUSED_POINTER,
&shield->sortStruct);
mode = AccessSetEMPTY;
limit = NULL;
for (i = 0; i < shield->limit; ++i) {
Seg seg = shieldDequeue(shield, i);
if (!SegIsSynced(seg)) {
shieldSetPM(shield, seg, SegSM(seg));
if (SegSM(seg) != mode || SegBase(seg) != limit) {
if (base != NULL) {
AVER(base < limit);
ProtSet(base, limit, mode);
}
base = SegBase(seg);
mode = SegSM(seg);
}
limit = SegLimit(seg);
}
}
if (base != NULL) {
AVER(base < limit);
ProtSet(base, limit, mode);
}
shieldQueueReset(shield);
}
/* shieldQueue -- consider adding a segment to the queue
*
* If the segment is out of sync, either sync it, or ensure it is
* queued and the mutator is suspended.
*/
static void shieldQueue(Arena arena, Seg seg)
{
Shield shield;
/* <design/trace#.fix.noaver> */
AVERT_CRITICAL(Arena, arena);
shield = ArenaShield(arena);
SHIELD_AVERT_CRITICAL(Seg, seg);
if (SegIsSynced(seg) || seg->queued)
return;
if (SegIsExposed(seg)) {
/* This can occur if the mutator isn't suspended, we expose a
segment, then raise the shield on it. In this case, the
mutator isn't allowed to see the segment, but we don't need to
queue it until its covered. */
shieldSuspend(arena);
return;
}
/* Allocate or extend the shield queue if necessary. */
if (shield->next >= shield->length) {
void *p;
Res res;
Count length;
AVER(shield->next == shield->length);
if (shield->length == 0)
length = ShieldQueueLENGTH;
else
length = shield->length * 2;
res = ControlAlloc(&p, arena, length * sizeof shield->queue[0]);
if (res != ResOK) {
AVER(ResIsAllocFailure(res));
/* Carry on with the existing queue. */
} else {
if (shield->length > 0) {
Size oldSize = shield->length * sizeof shield->queue[0];
AVER(shield->queue != NULL);
mps_lib_memcpy(p, shield->queue, oldSize);
ControlFree(arena, shield->queue, oldSize);
}
shield->queue = p;
shield->length = length;
}
}
/* Queue unavailable, so synchronize now. Or if the mutator is not
yet suspended and the code raises the shield on a covered
segment, protect it now, because that's probably better than
suspending the mutator. */
if (shield->length == 0 || !shield->suspended) {
shieldSync(shield, seg);
return;
}
AVER_CRITICAL(shield->limit <= shield->length);
AVER_CRITICAL(shield->next <= shield->limit);
/* If we failed to extend the shield queue array, degrade to an LRU
circular buffer. */
if (shield->next >= shield->length)
shield->next = 0;
AVER_CRITICAL(shield->next < shield->length);
AVER_CRITICAL(shield->length > 0);
/* If the limit is less than the length, then the queue array has
yet to be filled, and next is an uninitialized entry.
Otherwise it's the tail end from last time around, and needs to
be flushed. */
if (shield->limit >= shield->length) {
AVER_CRITICAL(shield->limit == shield->length);
shieldFlushEntry(shield, shield->next);
}
shield->queue[shield->next] = seg;
++shield->next;
seg->queued = TRUE;
if (shield->next >= shield->limit)
shield->limit = shield->next;
}
/* ShieldRaise -- declare segment should be protected from mutator
*
* Does not immediately protect the segment, unless the segment is
* covered and the shield queue is unavailable.
*/
void (ShieldRaise)(Arena arena, Seg seg, AccessSet mode)
{
Shield shield;
SHIELD_AVERT(Arena, arena);
SHIELD_AVERT(Seg, seg);
AVERT(AccessSet, mode);
shield = ArenaShield(arena);
AVER(!shield->queuePending);
shield->queuePending = TRUE;
/* <design/shield#.inv.prot.shield> preserved */
shieldSetSM(ArenaShield(arena), seg, BS_UNION(SegSM(seg), mode));
/* Ensure <design/shield#.inv.unsynced.suspended> and
<design/shield#.inv.unsynced.depth> */
shieldQueue(arena, seg);
shield->queuePending = FALSE;
/* Check queue and segment consistency. */
AVERT(Arena, arena);
AVERT(Seg, seg);
}
/* ShieldLower -- declare segment may be accessed by mutator */
void (ShieldLower)(Arena arena, Seg seg, AccessSet mode)
{
Shield shield;
AVERT(Arena, arena);
shield = ArenaShield(arena);
SHIELD_AVERT(Seg, seg);
AVERT(AccessSet, mode);
/* SegIsSynced(seg) is not changed by the following preserving
<design/shield#.inv.unsynced.suspended> and
<design/shield#.inv.prot.shield>. */
shieldSetSM(shield, seg, BS_DIFF(SegSM(seg), mode));
/* TODO: Do we need to promptly call shieldProtLower here? It
loses the opportunity to coalesce the protection call. It would
violate <design/shield#.prop.inside.access>. */
/* shieldQueue(arena, seg); */
shieldProtLower(shield, seg, mode);
/* Check queue and segment consistency. */
AVERT(Arena, arena);
AVERT(Seg, seg);
}
/* ShieldEnter -- enter the shield, allowing exposes */
void (ShieldEnter)(Arena arena)
{
Shield shield;
AVERT(Arena, arena);
shield = ArenaShield(arena);
AVER(!shield->inside);
AVER(shield->depth == 0);
AVER(!shield->suspended);
shieldQueueReset(shield);
shield->inside = TRUE;
}
/* shieldDebugCheck -- expensive consistency check
*
* While developing the shield it is very easy to make a consistency
* mistake that causes random corruption of the heap, usually because
* all the attempts to avoid protection and suspension end up failing
* to enforce <design/shield#.prop.mutator.access>. In these cases,
* try enabling SHIELD_DEBUG and extending this code as necessary.
*
* The basic idea is to iterate over *all* segments and check
* consistency with the arena and shield queue.
*/
#if defined(SHIELD_DEBUG)
static void shieldDebugCheck(Arena arena)
{
Shield shield;
Seg seg;
Count queued = 0;
Count depth = 0;
AVERT(Arena, arena);
shield = ArenaShield(arena);
AVER(shield->inside || shield->limit == 0);
if (SegFirst(&seg, arena))
do {
depth += SegDepth(seg);
if (shield->limit == 0) {
AVER(!seg->queued);
AVER(SegIsSynced(seg));
/* You can directly set protections here to see if it makes a
difference. */
/* ProtSet(SegBase(seg), SegLimit(seg), SegPM(seg)); */
} else {
if (seg->queued)
++queued;
}
} while(SegNext(&seg, arena, seg));
AVER(depth == shield->depth);
AVER(queued == shield->limit);
}
#endif
/* ShieldFlush -- empty the shield queue
*
* .shield.flush: Flush empties the shield queue. This needs to be
* called before queued segments are destroyed, to remove them from
* the queue. We flush the whole queue because finding the entry is
* O(n) and we're very likely reclaiming and destroying loads of
* segments. See also <design/shield#.improv.resume>.
*
* The memory for the segment may become spare, and not released back
* to the operating system. Since we keep track of protection on
* segments and not grains we have no way of keeping track of the
* protection state of spare grains. We therefore flush the protection
* to get it back into the default state (unprotected). See also
* <design/shield#.improv.noseg>.
*/
void (ShieldFlush)(Arena arena)
{
Shield shield;
AVERT(Arena, arena);
shield = ArenaShield(arena);
#ifdef SHIELD_DEBUG
shieldDebugCheck(arena);
#endif
shieldFlushEntries(shield);
AVER(shield->unsynced == 0); /* everything back in sync */
#ifdef SHIELD_DEBUG
shieldDebugCheck(arena);
#endif
}
/* ShieldLeave -- leave the shield, protect segs from mutator */
void (ShieldLeave)(Arena arena)
{
Shield shield;
AVERT(Arena, arena);
shield = ArenaShield(arena);
AVER(shield->inside);
AVER(shield->depth == 0); /* no pending covers */
AVER(shield->holds == 0);
ShieldFlush(arena);
AVER(shield->unsynced == 0); /* everything back in sync */
/* Ensuring the mutator is running at this point guarantees
.inv.outside.running */
if (shield->suspended) {
ThreadRingResume(ArenaThreadRing(arena), ArenaDeadRing(arena));
shield->suspended = FALSE;
}
shield->inside = FALSE;
}
/* ShieldExpose -- allow the MPS access to a segment while denying the mutator
*
* The first expose of a shielded segment suspends the mutator to
* ensure the MPS has exclusive access.
*/
void (ShieldExpose)(Arena arena, Seg seg)
{
Shield shield;
AccessSet mode = AccessREAD | AccessWRITE;
/* <design/trace#.fix.noaver> */
AVERT_CRITICAL(Arena, arena);
shield = ArenaShield(arena);
AVER_CRITICAL(shield->inside);
SegSetDepth(seg, SegDepth(seg) + 1);
AVER_CRITICAL(SegDepth(seg) > 0); /* overflow */
++shield->depth;
AVER_CRITICAL(shield->depth > 0); /* overflow */
if (BS_INTER(SegPM(seg), mode) != AccessSetEMPTY)
shieldSuspend(arena);
/* Ensure <design/shield#.inv.expose.prot>. */
/* TODO: Mass exposure -- see
<design/shield#.improv.mass-expose>. */
shieldProtLower(shield, seg, mode);
}
/* ShieldCover -- declare MPS no longer needs access to seg */
void (ShieldCover)(Arena arena, Seg seg)
{
Shield shield;
/* <design/trace#.fix.noaver> */
AVERT_CRITICAL(Arena, arena);
shield = ArenaShield(arena);
AVERT_CRITICAL(Seg, seg);
AVER_CRITICAL(SegPM(seg) == AccessSetEMPTY);
AVER_CRITICAL(SegDepth(seg) > 0);
SegSetDepth(seg, SegDepth(seg) - 1);
AVER_CRITICAL(shield->depth > 0);
--shield->depth;
/* Ensure <design/shield#.inv.unsynced.depth>. */
shieldQueue(arena, seg);
}
/* C. COPYRIGHT AND LICENSE
*
* Copyright (C) 2001-2020 Ravenbrook Limited <https://www.ravenbrook.com/>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE 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.
*/
| 7,524
|
678
|
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/iPodUI.framework/iPodUI
*/
#import <iPodUI/IUMediaQueriesDataSource.h>
@interface IUAudioBookTracksDataSource : IUMediaQueriesDataSource {
}
+ (int)mediaEntityType; // 0x3ab49
- (id)viewControllerContextForIndex:(unsigned)index; // 0x3ae75
- (void)createGlobalContexts; // 0x3ab69
- (Class)cellConfigurationClassForEntity:(id)entity; // 0x3ab4d
@end
| 165
|
1,144
|
<filename>backend/vertical-healthcare_ch/forum_datenaustausch_ch.invoice_base/src/main/java/de/metas/vertical/healthcare_ch/forum_datenaustausch_ch/base/imp/InvoiceRejectionDetailRepo.java
package de.metas.vertical.healthcare_ch.forum_datenaustausch_ch.base.imp;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.model.InterfaceWrapperHelper;
import org.compiere.model.I_C_Invoice_Rejection_Detail;
import org.springframework.stereotype.Repository;
/*
* #%L
* metasfresh-pharma
* %%
* Copyright (C) 2018 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import com.google.common.base.Joiner;
import de.metas.attachments.AttachmentEntryCreateRequest;
import de.metas.attachments.AttachmentEntryService;
import de.metas.attachments.AttachmentTags;
import de.metas.invoice_gateway.spi.model.imp.ImportedInvoiceResponse;
import de.metas.invoice_gateway.spi.model.imp.ImportedInvoiceResponse.Status;
import lombok.NonNull;
@Repository
public class InvoiceRejectionDetailRepo
{
private static final String REASON_SEPARATOR = "\n";
private final AttachmentEntryService attachmentEntryService;
public InvoiceRejectionDetailRepo(@NonNull final AttachmentEntryService attachmentEntryService)
{
this.attachmentEntryService = attachmentEntryService;
}
private I_C_Invoice_Rejection_Detail of(@NonNull final ImportedInvoiceResponse response)
{
final I_C_Invoice_Rejection_Detail rejectionDetail = InterfaceWrapperHelper.newInstance(I_C_Invoice_Rejection_Detail.class);
rejectionDetail.setIsDone(false);
rejectionDetail.setInvoiceNumber(response.getDocumentNumber());
if (response.getInvoiceId() != null)
{
rejectionDetail.setC_Invoice_ID(response.getInvoiceId().getRepoId());
}
rejectionDetail.setClient(response.getClient());
rejectionDetail.setInvoiceRecipient(response.getInvoiceRecipient());
rejectionDetail.setReason(Joiner.on(REASON_SEPARATOR).join(response.getReason()));
rejectionDetail.setExplanation(response.getExplanation());
rejectionDetail.setResponsiblePerson(response.getResponsiblePerson());
rejectionDetail.setPhone(response.getPhone());
rejectionDetail.setEMail(response.getEmail());
final Status status = response.getStatus();
if (status == null)
{
throw new AdempiereException("The given response has no status. Probably support for this type of response is not implemented yet")
.appendParametersToMessage()
.setParameter("response", response);
}
rejectionDetail.setStatus(status.name());
rejectionDetail.setAD_Org_ID(response.getBillerOrg());
return rejectionDetail;
}
public InvoiceRejectionDetailId save(@NonNull final ImportedInvoiceResponse importedInvoiceResponse)
{
final I_C_Invoice_Rejection_Detail invoiceRejectionDetail = of(importedInvoiceResponse);
InterfaceWrapperHelper.saveRecord(invoiceRejectionDetail);
attachFileToInvoiceRejectionDetail(importedInvoiceResponse, invoiceRejectionDetail);
return InvoiceRejectionDetailId.ofRepoId(invoiceRejectionDetail.getC_Invoice_Rejection_Detail_ID());
}
private void attachFileToInvoiceRejectionDetail(
@NonNull final ImportedInvoiceResponse response,
@NonNull final I_C_Invoice_Rejection_Detail invoiceRejectionDetail)
{
final AttachmentEntryCreateRequest attachmentEntryCreateRequest = AttachmentEntryCreateRequest
.builderFromByteArray(response.getRequest().getFileName(), response.getRequest().getData())
.tags(AttachmentTags.ofMap(response.getAdditionalTags()))
.build();
attachmentEntryService.createNewAttachment(invoiceRejectionDetail, attachmentEntryCreateRequest);
}
}
| 1,338
|
946
|
<filename>core/src/builders/terrain/ExteriorGenerator.hpp
#ifndef BUILDERS_TERRAIN_EXTERIORGENERATOR_HPP_DEFINED
#define BUILDERS_TERRAIN_EXTERIORGENERATOR_HPP_DEFINED
#include "builders/terrain/TerraGenerator.hpp"
#include <memory>
namespace utymap {
namespace builders {
/// Generates meshes outside terrain surface, e.g. tunnels, roads above ground, etc.
class ExteriorGenerator final : public TerraGenerator {
public:
ExteriorGenerator(const BuilderContext &context,
const utymap::mapcss::Style &style,
const utymap::math::IntPath &tileRect);
void onNewRegion(const std::string &type,
const utymap::entities::Element &element,
const utymap::mapcss::Style &style,
const std::shared_ptr<Region> ®ion) override;
void generateFrom(const std::vector<Layer> &layers) override;
~ExteriorGenerator();
protected:
void addGeometry(int level, utymap::math::Polygon &polygon, const RegionContext ®ionContext) override;
private:
class ExteriorGeneratorImpl;
std::unique_ptr<ExteriorGeneratorImpl> p_impl;
};
}
}
#endif // BUILDERS_TERRAIN_EXTERIORGENERATOR_HPP_DEFINED
| 457
|
1,144
|
package de.metas.ui.web.material.cockpit.rowfactory;
import java.math.BigDecimal;
import java.time.LocalDate;
import org.compiere.util.TimeUtil;
import de.metas.material.cockpit.model.I_MD_Cockpit;
import de.metas.material.cockpit.model.I_MD_Stock;
import de.metas.product.ProductId;
import lombok.NonNull;
import lombok.Value;
/*
* #%L
* metasfresh-webui-api
* %%
* Copyright (C) 2017 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
@Value
public class MainRowBucketId
{
public static MainRowBucketId createInstanceForCockpitRecord(
@NonNull final I_MD_Cockpit dataRecord)
{
return new MainRowBucketId(
ProductId.ofRepoId(dataRecord.getM_Product_ID()),
TimeUtil.asLocalDate(dataRecord.getDateGeneral()));
}
public static MainRowBucketId createInstanceForStockRecord(
@NonNull final I_MD_Stock stockRecord,
@NonNull final LocalDate date)
{
return new MainRowBucketId(
ProductId.ofRepoId(stockRecord.getM_Product_ID()),
date);
}
public static MainRowBucketId createPlainInstance(@NonNull final ProductId productId, @NonNull final LocalDate date)
{
return new MainRowBucketId(productId, date);
}
ProductId productId;
LocalDate date;
private BigDecimal pmmQtyPromised = BigDecimal.ZERO;
private BigDecimal qtyReserved = BigDecimal.ZERO;
private BigDecimal qtyOrdered = BigDecimal.ZERO;
private BigDecimal qtyMaterialentnahme = BigDecimal.ZERO;
private BigDecimal qtyMrp = BigDecimal.ZERO;
private BigDecimal qtyPromised = BigDecimal.ZERO;
private BigDecimal qtyOnHand = BigDecimal.ZERO;
private MainRowBucketId(
@NonNull final ProductId productId,
@NonNull final LocalDate date)
{
this.productId = productId;
this.date = date;
}
}
| 799
|
1,073
|
<filename>mobius-core/src/main/java/com/spotify/mobius/runners/ImmediateWorkRunner.java<gh_stars>1000+
/*
* -\-\-
* Mobius
* --
* Copyright (c) 2017-2020 Spotify AB
* --
* 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.spotify.mobius.runners;
/**
* A {@link WorkRunner} that immediately invokes the {@link Runnable} you post on the thread you
* posted from.
*/
public class ImmediateWorkRunner implements WorkRunner {
private boolean disposed;
@Override
public synchronized void post(Runnable runnable) {
if (disposed) return;
runnable.run();
}
@Override
public synchronized void dispose() {
disposed = true;
}
}
| 348
|
312
|
#include "clar_libgit2.h"
#include "posix.h"
static void
cleanup__remove_file(void *_file)
{
cl_must_pass(p_unlink((char *)_file));
}
/* test retrieving OID from a file apart from the ODB */
void test_status_single__hash_single_file(void)
{
static const char file_name[] = "new_file";
static const char file_contents[] = "new_file\n";
static const char file_hash[] = "d4fa8600b4f37d7516bef4816ae2c64dbf029e3a";
git_oid expected_id, actual_id;
/* initialization */
git_oid_fromstr(&expected_id, file_hash);
cl_git_mkfile(file_name, file_contents);
cl_set_cleanup(&cleanup__remove_file, (void *)file_name);
cl_git_pass(git_odb_hashfile(&actual_id, file_name, GIT_OBJECT_BLOB));
cl_assert_equal_oid(&expected_id, &actual_id);
}
/* test retrieving OID from an empty file apart from the ODB */
void test_status_single__hash_single_empty_file(void)
{
static const char file_name[] = "new_empty_file";
static const char file_contents[] = "";
static const char file_hash[] = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";
git_oid expected_id, actual_id;
/* initialization */
git_oid_fromstr(&expected_id, file_hash);
cl_git_mkfile(file_name, file_contents);
cl_set_cleanup(&cleanup__remove_file, (void *)file_name);
cl_git_pass(git_odb_hashfile(&actual_id, file_name, GIT_OBJECT_BLOB));
cl_assert_equal_oid(&expected_id, &actual_id);
}
| 531
|
17,810
|
<filename>code/9/9.1.noexcept.cpp
//
// 9.1.noexcept.cpp
// chapter 09 others
// modern c++ tutorial
//
// created by changkun at changkun.de
// https://github.com/changkun/modern-cpp-tutorial
//
#include <iostream>
void may_throw() {
throw true;
}
auto non_block_throw = []{
may_throw();
};
void no_throw() noexcept {
return;
}
auto block_throw = []() noexcept {
no_throw();
};
int main()
{
std::cout << std::boolalpha
<< "may_throw() noexcept? " << noexcept(may_throw()) << std::endl
<< "no_throw() noexcept? " << noexcept(no_throw()) << std::endl
<< "lmay_throw() noexcept? " << noexcept(non_block_throw()) << std::endl
<< "lno_throw() noexcept? " << noexcept(block_throw()) << std::endl;
try {
may_throw();
} catch (...) {
std::cout << "exception captured from my_throw()" << std::endl;
}
try {
non_block_throw();
} catch (...) {
std::cout << "exception captured from non_block_throw()" << std::endl;
}
try {
block_throw();
} catch (...) {
std::cout << "exception captured from block_throw()" << std::endl;
}
}
| 494
|
892
|
{
"schema_version": "1.2.0",
"id": "GHSA-cjg2-2fjg-fph4",
"modified": "2022-01-14T19:58:51Z",
"published": "2022-01-14T21:03:36Z",
"aliases": [
"CVE-2022-21685"
],
"summary": "Integer underflow in Frontier",
"details": "### Impact\n\nA bug in Frontier's MODEXP precompile implementation can cause an integer underflow in certain conditions. This will cause a node crash for debug builds. For release builds (and production WebAssembly binaries), the impact is limited as it can only cause a normal EVM out-of-gas. It is recommended that you apply the patch as soon as possible.\n\nIf you do not use MODEXP precompile in your runtime, then you are not impacted.\n\n### Patches\n\nPatches are applied in PR #549.\n\n### Workarounds\n\nNone.\n\n### References\n\nPatch PR: #549\n\n### Credits\n\nThanks to SR-Labs for discovering the security vulnerability, and thanks to PureStake team for the patches.\n\n### For more information\n\nIf you have any questions or comments about this advisory:\n* Open an issue in the [Frontier repo](https://github.com/paritytech/frontier)\n",
"severity": [
],
"affected": [
{
"package": {
"ecosystem": "crates.io",
"name": "frontier"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "0"
}
]
}
],
"database_specific": {
"last_known_affected_version_range": "<= 0.1.0"
}
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/paritytech/frontier/security/advisories/GHSA-cjg2-2fjg-fph4"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-21685"
},
{
"type": "WEB",
"url": "https://github.com/paritytech/frontier/pull/549"
},
{
"type": "WEB",
"url": "https://github.com/paritytech/frontier/commit/8a93fdc6c9f4eb1d2f2a11b7ff1d12d70bf5a664"
},
{
"type": "PACKAGE",
"url": "https://github.com/paritytech/frontier"
}
],
"database_specific": {
"cwe_ids": [
"CWE-191"
],
"severity": "MODERATE",
"github_reviewed": true
}
}
| 986
|
6,304
|
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkPaint.h"
// https://crbug.com/772953
DEF_SIMPLE_GM(circle_sizes, canvas, 128, 128) {
SkPaint p;
p.setAntiAlias(true);
for (int i = 0; i < 16; ++i) {
canvas->drawCircle({14.0f + 32.0f * (i % 4),
14.0f + 32.0f * (i / 4)}, i + 1.0f, p);
}
}
| 242
|
373
|
/** @file
Aspire VN7-572G HSIO PTSS H File
Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef ASPIRE_VN7_572G_HSIO_PTSS_H_
#define ASPIRE_VN7_572G_HSIO_PTSS_H_
#include <PchHsioPtssTables.h>
#ifndef HSIO_PTSS_TABLE_SIZE
#define HSIO_PTSS_TABLE_SIZE(A) A##_Size = sizeof (A) / sizeof (HSIO_PTSS_TABLES)
#endif
//BoardId AspireVn7Dash572G
HSIO_PTSS_TABLES PchLpHsioPtss_AspireVn7Dash572G[] = {
/* PchSataHsioRxGen3EqBoostMag[1] = "1" */
{{14, V_PCH_PCR_FIA_LANE_OWN_SATA, 0x150, 0x01000000, (UINT32) ~0x3F000000}, PchSataTopoUnknown}
};
UINT16 PchLpHsioPtss_AspireVn7Dash572G_Size = sizeof(PchLpHsioPtss_AspireVn7Dash572G) / sizeof(HSIO_PTSS_TABLES);
#endif // ASPIRE_VN7_572G_HSIO_PTSS_H_
| 425
|
751
|
// Copyright 2016, 2018 by <NAME>, All Rights Reserved
#ifndef AGOO_TEXT_H
#define AGOO_TEXT_H
#include <stdbool.h>
#include "atomic.h"
#define AGOO_TEXT_MIN_SIZE 8
typedef struct _agooText {
struct _agooText *next;
long len; // length of valid text
long alen; // size of allocated text
atomic_int ref_cnt;
bool bin;
char text[AGOO_TEXT_MIN_SIZE];
} *agooText;
extern agooText agoo_text_create(const char *str, int len);
extern agooText agoo_text_dup(agooText t);
extern agooText agoo_text_allocate(int len);
extern void agoo_text_ref(agooText t);
extern void agoo_text_release(agooText t);
extern agooText agoo_text_append(agooText t, const char *s, int len);
extern agooText agoo_text_prepend(agooText t, const char *s, int len);
extern agooText agoo_text_append_json(agooText t, const char *s, int len);
extern agooText agoo_text_append_char(agooText t, const char c);
extern void agoo_text_reset(agooText t);
#endif // AGOO_TEXT_H
| 403
|
323
|
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import copy
import sys
sys.path.append('../../')
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.util.gui import GUI
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.Kinematics.LieAlgebra import RPY
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
# TESTING
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
import time
import os
import argparse
# ARGUMENTS
descr = "Spot Mini Mini Environment Tester (No Joystick)."
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("-hf",
"--HeightField",
help="Use HeightField",
action='store_true')
parser.add_argument("-r",
"--DebugRack",
help="Put Spot on an Elevated Rack",
action='store_true')
parser.add_argument("-p",
"--DebugPath",
help="Draw Spot's Foot Path",
action='store_true')
parser.add_argument("-ay",
"--AutoYaw",
help="Automatically Adjust Spot's Yaw",
action='store_true')
parser.add_argument("-ar",
"--AutoReset",
help="Automatically Reset Environment When Spot Falls",
action='store_true')
parser.add_argument("-dr",
"--DontRandomize",
help="Do NOT Randomize State and Environment.",
action='store_true')
ARGS = parser.parse_args()
def main():
""" The main() function. """
print("STARTING SPOT TEST ENV")
seed = 0
max_timesteps = 4e6
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
if ARGS.DebugRack:
on_rack = True
else:
on_rack = False
if ARGS.DebugPath:
draw_foot_path = True
else:
draw_foot_path = False
if ARGS.HeightField:
height_field = True
else:
height_field = False
if ARGS.DontRandomize:
env_randomizer = None
else:
env_randomizer = SpotEnvRandomizer()
env = spotBezierEnv(render=True,
on_rack=on_rack,
height_field=height_field,
draw_foot_path=draw_foot_path,
env_randomizer=env_randomizer)
# Set seeds
env.seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
state = env.reset()
g_u_i = GUI(env.spot.quadruped)
spot = SpotModel()
T_bf0 = spot.WorldToFoot
T_bf = copy.deepcopy(T_bf0)
bzg = BezierGait(dt=env._time_step)
bz_step = BezierStepper(dt=env._time_step, mode=0)
action = env.action_space.sample()
FL_phases = []
FR_phases = []
BL_phases = []
BR_phases = []
FL_Elbow = []
yaw = 0.0
print("STARTED SPOT TEST ENV")
t = 0
while t < (int(max_timesteps)):
bz_step.ramp_up()
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth = bz_step.StateMachine(
)
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth, SwingPeriod = g_u_i.UserInput(
)
# Update Swing Period
bzg.Tswing = SwingPeriod
yaw = env.return_yaw()
P_yaw = 5.0
if ARGS.AutoYaw:
YawRate += -yaw * P_yaw
# print("YAW RATE: {}".format(YawRate))
# TEMP
bz_step.StepLength = StepLength
bz_step.LateralFraction = LateralFraction
bz_step.YawRate = YawRate
bz_step.StepVelocity = StepVelocity
contacts = state[-4:]
FL_phases.append(env.spot.LegPhases[0])
FR_phases.append(env.spot.LegPhases[1])
BL_phases.append(env.spot.LegPhases[2])
BR_phases.append(env.spot.LegPhases[3])
# Get Desired Foot Poses
T_bf = bzg.GenerateTrajectory(StepLength, LateralFraction, YawRate,
StepVelocity, T_bf0, T_bf,
ClearanceHeight, PenetrationDepth,
contacts)
joint_angles = spot.IK(orn, pos, T_bf)
FL_Elbow.append(np.degrees(joint_angles[0][-1]))
# for i, (key, Tbf_in) in enumerate(T_bf.items()):
# print("{}: \t Angle: {}".format(key, np.degrees(joint_angles[i])))
# print("-------------------------")
env.pass_joint_angles(joint_angles.reshape(-1))
# Get External Observations
env.spot.GetExternalObservations(bzg, bz_step)
# Step
state, reward, done, _ = env.step(action)
# print("IMU Roll: {}".format(state[0]))
# print("IMU Pitch: {}".format(state[1]))
# print("IMU GX: {}".format(state[2]))
# print("IMU GY: {}".format(state[3]))
# print("IMU GZ: {}".format(state[4]))
# print("IMU AX: {}".format(state[5]))
# print("IMU AY: {}".format(state[6]))
# print("IMU AZ: {}".format(state[7]))
# print("-------------------------")
if done:
print("DONE")
if ARGS.AutoReset:
env.reset()
# plt.plot()
# # plt.plot(FL_phases, label="FL")
# # plt.plot(FR_phases, label="FR")
# # plt.plot(BL_phases, label="BL")
# # plt.plot(BR_phases, label="BR")
# plt.plot(FL_Elbow, label="FL ELbow (Deg)")
# plt.xlabel("dt")
# plt.ylabel("value")
# plt.title("Leg Phases")
# plt.legend()
# plt.show()
# time.sleep(1.0)
t += 1
env.close()
print(joint_angles)
if __name__ == '__main__':
main()
| 3,210
|
317
|
<reponame>heralex/OTB
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 otbStreamingResampleImageFilter_hxx
#define otbStreamingResampleImageFilter_hxx
#include "otbStreamingResampleImageFilter.h"
#include "itkProgressAccumulator.h"
#include "otbImage.h"
namespace otb
{
template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType>
StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecisionType>::StreamingResampleImageFilter()
{
// internal filters instantiation
m_DisplacementFilter = DisplacementFieldGeneratorType::New();
m_WarpFilter = WarpImageFilterType::New();
m_SignedOutputSpacing = m_DisplacementFilter->GetOutputSpacing();
// Initialize the displacement field spacing to zero : inconsistent
// value
this->SetDisplacementFieldSpacing(itk::NumericTraits<SpacingType>::ZeroValue());
// Wire minipipeline
m_WarpFilter->SetDisplacementField(m_DisplacementFilter->GetOutput());
}
template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType>
void StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecisionType>::GenerateData()
{
// Set up progress reporting
typename itk::ProgressAccumulator::Pointer progress = itk::ProgressAccumulator::New();
progress->SetMiniPipelineFilter(this);
progress->RegisterInternalFilter(m_WarpFilter, 1.f);
m_WarpFilter->GraftOutput(this->GetOutput());
m_WarpFilter->UpdateOutputData(m_WarpFilter->GetOutput());
this->GraftOutput(m_WarpFilter->GetOutput());
}
/**
*
*/
template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType>
void StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecisionType>::GenerateOutputInformation()
{
// check the output spacing of the displacement field
if (this->GetDisplacementFieldSpacing() == itk::NumericTraits<SpacingType>::ZeroValue())
{
this->SetDisplacementFieldSpacing(2. * this->GetOutputSpacing());
}
// Retrieve output largest region
SizeType largestSize = this->GetOutputSize();
// Set up displacement field filter
SizeType displacementFieldLargestSize;
for (unsigned int dim = 0; dim < InputImageType::ImageDimension; ++dim)
{
// std::ceil to avoid numerical problems due to division of
// spacings
// + 1 : We need to enlarge the displacement field size cause
// itk::WarpImageFilter::EvaluateDisplacementAtPhysicalPoint needs
// 4 neighbors and in the edges we can need 1 neighbor pixel
// outside the field
displacementFieldLargestSize[dim] =
static_cast<unsigned int>(std::ceil(largestSize[dim] * std::abs(this->GetOutputSpacing()[dim] / this->GetDisplacementFieldSpacing()[dim]))) + 1;
}
m_DisplacementFilter->SetOutputSize(displacementFieldLargestSize);
m_DisplacementFilter->SetOutputIndex(this->GetOutputStartIndex());
m_WarpFilter->SetInput(this->GetInput());
m_WarpFilter->GraftOutput(this->GetOutput());
m_WarpFilter->UpdateOutputInformation();
this->GraftOutput(m_WarpFilter->GetOutput());
}
template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType>
void StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecisionType>::PropagateRequestedRegion(itk::DataObject* output)
{
if (this->m_Updating)
return;
m_WarpFilter->GetOutput()->SetRequestedRegion(output);
m_WarpFilter->GetOutput()->PropagateRequestedRegion();
}
/**
* Method used to copy the parameters of the input image
*
*/
template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType>
void StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecisionType>::SetOutputParametersFromImage(const ImageBaseType* image)
{
this->SetOutputOrigin(image->GetOrigin());
this->SetOutputSpacing(internal::GetSignedSpacing(image));
this->SetOutputStartIndex(image->GetLargestPossibleRegion().GetIndex());
this->SetOutputSize(image->GetLargestPossibleRegion().GetSize());
}
template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType>
void StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecisionType>::SetDisplacementFieldSpacing(SpacingType outputSpacing)
{
m_SignedOutputSpacing = outputSpacing;
typename TInputImage::DirectionType direction = this->m_DisplacementFilter->GetOutputDirection();
for (unsigned int i = 0; i < TInputImage::ImageDimension; ++i)
{
if (outputSpacing[i] < 0)
{
if (direction[i][i] > 0)
{
for (unsigned int j = 0; j < TInputImage::ImageDimension; ++j)
{
direction[j][i] = -direction[j][i];
}
}
outputSpacing[i] = -outputSpacing[i];
}
}
this->m_DisplacementFilter->SetOutputSpacing(outputSpacing);
this->m_DisplacementFilter->SetOutputDirection(direction);
this->Modified();
}
template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType>
void StreamingResampleImageFilter<TInputImage, TOutputImage, TInterpolatorPrecisionType>::PrintSelf(std::ostream& os, itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "OutputOrigin: " << this->GetOutputOrigin() << std::endl;
os << indent << "OutputSpacing: " << this->GetOutputSpacing() << std::endl;
os << indent << "OutputStartIndex: " << this->GetOutputStartIndex() << std::endl;
os << indent << "OutputSize: " << this->GetOutputSize() << std::endl;
}
}
#endif
| 1,980
|
904
|
#include "backend.h"
#include "bitmap.h"
#include "image.h"
#include "source.h"
#include "source_private.h"
#include <stdlib.h>
#include <string.h>
#include <tiffio.h>
struct private {
TIFF *tiff;
void *data;
size_t pos, len;
int width;
int height;
};
static tsize_t mem_read(thandle_t data, tdata_t buffer, tsize_t len)
{
struct private *private = (struct private*)data;
memcpy(buffer, (char*)private->data + private->pos, len);
private->pos += len;
return len;
}
static tsize_t mem_write(thandle_t data, tdata_t buffer, tsize_t len)
{
struct private *private = (struct private*)data;
memcpy((char*)private->data + private->pos, buffer, len);
private->pos += len;
return len;
}
static int mem_close(thandle_t data)
{
(void)data;
return 0;
}
static toff_t mem_seek(thandle_t data, toff_t pos, int whence)
{
struct private *private = (struct private*)data;
if (whence == SEEK_SET) {
private->pos = pos;
} else if (whence == SEEK_CUR) {
private->pos += pos;
} else if (whence == SEEK_END) {
private->pos = private->len + pos;
} else {
return -1;
}
return private->pos;
}
static toff_t mem_size(thandle_t data)
{
struct private *private = (struct private*)data;
return private->len;
}
static void free_private(void *raw_private)
{
if (!raw_private) {
return;
}
struct private *private = raw_private;
TIFFClose(private->tiff);
private->tiff = NULL;
free(private);
}
static void load_image(void *raw_private, struct imv_image **image, int *frametime)
{
*image = NULL;
*frametime = 0;
struct private *private = raw_private;
/* libtiff suggests using their own allocation routines to support systems
* with segmented memory. I have no desire to support that, so I'm just
* going to use vanilla malloc/free. Systems where that isn't acceptable
* don't have upstream support from imv.
*/
void *bitmap = malloc(private->height * private->width * 4);
int rcode = TIFFReadRGBAImageOriented(private->tiff, private->width, private->height,
bitmap, ORIENTATION_TOPLEFT, 0);
/* 1 = success, unlike the rest of *nix */
if (rcode != 1) {
return;
}
struct imv_bitmap *bmp = malloc(sizeof *bmp);
bmp->width = private->width;
bmp->height = private->height;
bmp->format = IMV_ABGR;
bmp->data = bitmap;
*image = imv_image_create_from_bitmap(bmp);
}
static const struct imv_source_vtable vtable = {
.load_first_frame = load_image,
.free = free_private
};
static enum backend_result open_path(const char *path, struct imv_source **src)
{
struct private private;
TIFFSetErrorHandler(NULL);
private.tiff = TIFFOpen(path, "r");
if (!private.tiff) {
/* Header is read, so no BAD_PATH check here */
return BACKEND_UNSUPPORTED;
}
TIFFGetField(private.tiff, TIFFTAG_IMAGEWIDTH, &private.width);
TIFFGetField(private.tiff, TIFFTAG_IMAGELENGTH, &private.height);
struct private *new_private = malloc(sizeof private);
memcpy(new_private, &private, sizeof private);
*src = imv_source_create(&vtable, new_private);
return BACKEND_SUCCESS;
}
static enum backend_result open_memory(void *data, size_t len, struct imv_source **src)
{
TIFFSetErrorHandler(NULL);
struct private *private = malloc(sizeof *private);
private->data = data;
private->len = len;
private->pos = 0;
private->tiff = TIFFClientOpen("-", "rm", (thandle_t)private,
&mem_read, &mem_write, &mem_seek, &mem_close, &mem_size,
NULL, NULL);
if (!private->tiff) {
/* Header is read, so no BAD_PATH check here */
free(private);
return BACKEND_UNSUPPORTED;
}
TIFFGetField(private->tiff, TIFFTAG_IMAGEWIDTH, &private->width);
TIFFGetField(private->tiff, TIFFTAG_IMAGELENGTH, &private->height);
*src = imv_source_create(&vtable, private);
return BACKEND_SUCCESS;
}
const struct imv_backend imv_backend_libtiff = {
.name = "libtiff",
.description = "The de-facto tiff library",
.website = "http://www.libtiff.org/",
.license = "MIT",
.open_path = &open_path,
.open_memory = &open_memory,
};
| 1,518
|
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.performance.j2se.actions;
import org.netbeans.performance.j2se.setup.J2SESetup;
import org.netbeans.jellytools.nodes.Node;
import org.netbeans.jellytools.actions.OpenAction;
import org.netbeans.jellytools.nodes.SourcePackagesNode;
import org.netbeans.junit.NbTestSuite;
import org.netbeans.junit.NbModuleSuite;
/**
* Test of opening files if Editor is already opened.
* OpenFiles is used as a base for tests of opening files
* when editor is already opened.
*
* @author <EMAIL>
*/
public class OpenFilesWithOpenedEditorTest extends OpenFilesTest {
/** Name of file to pre-open */
public static String fileName_preopen;
/**
* Creates a new instance of OpenFilesWithOpenedEditor
* @param testName the name of the test
*/
public OpenFilesWithOpenedEditorTest(String testName) {
super(testName);
}
/**
* Creates a new instance of OpenFilesWithOpenedEditor
* @param testName the name of the test
* @param performanceDataName measured values will be saved under this name
*/
public OpenFilesWithOpenedEditorTest(String testName, String performanceDataName) {
super(testName, performanceDataName);
}
public static NbTestSuite suite() {
NbTestSuite suite = new NbTestSuite();
suite.addTest(NbModuleSuite.create(NbModuleSuite.createConfiguration(J2SESetup.class)
.addTest(OpenFilesWithOpenedEditorTest.class)
.enableModules(".*").clusters(".*")));
return suite;
}
@Override
public void testOpening20kBJavaFile(){
WAIT_AFTER_OPEN = 2000;
fileProject = "PerformanceTestData";
filePackage = "org.netbeans.test.performance";
fileName = "Main20kB.java";
fileName_preopen = "Main.java";
doMeasurement();
}
@Override
public void testOpening20kBTxtFile(){
WAIT_AFTER_OPEN = 2000;
fileProject = "PerformanceTestData";
filePackage = "org.netbeans.test.performance";
fileName = "textfile20kB.txt";
fileName_preopen = "textfile.txt";
doMeasurement();
}
@Override
public void testOpening20kBXmlFile(){
WAIT_AFTER_OPEN = 2000;
fileProject = "PerformanceTestData";
filePackage = "org.netbeans.test.performance";
fileName = "xmlfile20kB.xml";
fileName_preopen = "xmlfile.xml";
doMeasurement();
}
/**
* Initialize test - open Main.java file in the Source Editor.
*/
@Override
public void initialize(){
super.initialize();
new OpenAction().performAPI(new Node(new SourcePackagesNode("PerformanceTestData"), "org.netbeans.test.performance|" + fileName_preopen));
}
}
| 1,279
|
357
|
/**
*
* Copyright 2013 VMware, Inc. All rights reserved.
*/
package com.vmware.vmevent.interop;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
import com.vmware.vmevent.VmEventClientNativeException;
public class VmEventClientAdapter extends NativeAdapter
{
static String _endPoint = "2020";
public interface VmEventClientLibrary extends Library
{
VmEventClientLibrary INSTANCE =
(VmEventClientLibrary) Native.loadLibrary(
"vmeventclient",
VmEventClientLibrary.class);
int
EventLogAdd(
String pszServerName,
String pszServerEndPoint,
int eventID,
int eventType,
String eventText
);
}
public static int addEvent(String hostname, int eventType, int eventCategory, String eventText)
{
PointerByReference ppszDomain = new PointerByReference();
try
{
int errCode = VmEventClientLibrary.INSTANCE.EventLogAdd(
hostname,
_endPoint,
eventType,
eventCategory,
eventText);
if (errCode != 0)
{
throw new VmEventClientNativeException(errCode);
}
return errCode;
}
finally
{
}
}
}
| 1,027
|
1,767
|
package com.annimon.stream.iterator;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class LazyIteratorTest {
@Test
public void testHasNext() {
assertFalse(newIteratorEmpty().hasNext());
assertTrue(newIterator().hasNext());
}
@Test(expected = NoSuchElementException.class)
public void testNext() {
final LazyIterator<String> iterator = newIterator();
assertEquals(iterator.next(), "1");
assertEquals(iterator.next(), "2");
newIteratorEmpty().next();
}
@Test
public void testRemove() {
final List<String> list = new LinkedList<String>();
list.addAll(Arrays.asList("1", "2"));
final LazyIterator<String> iterator = new LazyIterator<String>(list);
assertEquals(iterator.next(), "1");
iterator.remove();
assertTrue(iterator.hasNext());
assertEquals(iterator.next(), "2");
iterator.remove();
assertFalse(iterator.hasNext());
assertTrue(list.isEmpty());
}
@Test(expected = NoSuchElementException.class)
public void testIterator() {
final LazyIterator<String> iterator = newIterator();
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertEquals(iterator.next(), "1");
assertEquals(iterator.next(), "2");
assertFalse(iterator.hasNext());
assertFalse(iterator.hasNext());
iterator.next();
}
private static LazyIterator<String> newIteratorEmpty() {
return new LazyIterator<String>(Collections.<String>emptyList());
}
private static LazyIterator<String> newIterator() {
return new LazyIterator<String>(Arrays.asList("1", "2"));
}
}
| 747
|
1,127
|
<reponame>artkuli/openvino<gh_stars>1000+
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""ngraph module namespace, exposing factory functions for all ops and other classes."""
# noqa: F401
try:
from ngraph.impl import util
__version__ = util.get_ngraph_version_string()
except ImportError:
__version__ = "0.0.0.dev0"
from ngraph.impl import Dimension
from ngraph.impl import Function
from ngraph.impl import Node
from ngraph.impl import PartialShape
from ngraph.helpers import function_from_cnn
from ngraph.helpers import function_to_cnn
from ngraph.opset9 import absolute
from ngraph.opset9 import absolute as abs
from ngraph.opset9 import acos
from ngraph.opset9 import acosh
from ngraph.opset9 import adaptive_avg_pool
from ngraph.opset9 import adaptive_max_pool
from ngraph.opset9 import add
from ngraph.opset9 import asin
from ngraph.opset9 import asinh
from ngraph.opset9 import assign
from ngraph.opset9 import atan
from ngraph.opset9 import atanh
from ngraph.opset9 import avg_pool
from ngraph.opset9 import batch_norm_inference
from ngraph.opset9 import batch_to_space
from ngraph.opset9 import binary_convolution
from ngraph.opset9 import broadcast
from ngraph.opset9 import bucketize
from ngraph.opset9 import ceiling
from ngraph.opset9 import ceiling as ceil
from ngraph.opset9 import clamp
from ngraph.opset9 import concat
from ngraph.opset9 import constant
from ngraph.opset9 import convert
from ngraph.opset9 import convert_like
from ngraph.opset9 import convolution
from ngraph.opset9 import convolution_backprop_data
from ngraph.opset9 import cos
from ngraph.opset9 import cosh
from ngraph.opset9 import ctc_greedy_decoder
from ngraph.opset9 import ctc_greedy_decoder_seq_len
from ngraph.opset9 import ctc_loss
from ngraph.opset9 import cum_sum
from ngraph.opset9 import cum_sum as cumsum
from ngraph.opset9 import deformable_convolution
from ngraph.opset9 import deformable_psroi_pooling
from ngraph.opset9 import depth_to_space
from ngraph.opset9 import detection_output
from ngraph.opset9 import dft
from ngraph.opset9 import divide
from ngraph.opset9 import einsum
from ngraph.opset9 import elu
from ngraph.opset9 import embedding_bag_offsets_sum
from ngraph.opset9 import embedding_bag_packed_sum
from ngraph.opset9 import embedding_segments_sum
from ngraph.opset9 import extract_image_patches
from ngraph.opset9 import equal
from ngraph.opset9 import erf
from ngraph.opset9 import exp
from ngraph.opset9 import eye
from ngraph.opset9 import fake_quantize
from ngraph.opset9 import floor
from ngraph.opset9 import floor_mod
from ngraph.opset9 import gather
from ngraph.opset9 import gather_elements
from ngraph.opset9 import gather_nd
from ngraph.opset9 import gather_tree
from ngraph.opset9 import gelu
from ngraph.opset9 import generate_proposals
from ngraph.opset9 import greater
from ngraph.opset9 import greater_equal
from ngraph.opset9 import grid_sample
from ngraph.opset9 import grn
from ngraph.opset9 import group_convolution
from ngraph.opset9 import group_convolution_backprop_data
from ngraph.opset9 import gru_cell
from ngraph.opset9 import gru_sequence
from ngraph.opset9 import hard_sigmoid
from ngraph.opset9 import hsigmoid
from ngraph.opset9 import hswish
from ngraph.opset9 import idft
from ngraph.opset9 import if_op
from ngraph.opset9 import interpolate
from ngraph.opset9 import irdft
from ngraph.opset9 import i420_to_bgr
from ngraph.opset9 import i420_to_rgb
from ngraph.opset9 import less
from ngraph.opset9 import less_equal
from ngraph.opset9 import log
from ngraph.opset9 import logical_and
from ngraph.opset9 import logical_not
from ngraph.opset9 import logical_or
from ngraph.opset9 import logical_xor
from ngraph.opset9 import log_softmax
from ngraph.opset9 import loop
from ngraph.opset9 import lrn
from ngraph.opset9 import lstm_cell
from ngraph.opset9 import lstm_sequence
from ngraph.opset9 import matmul
from ngraph.opset9 import matrix_nms
from ngraph.opset9 import max_pool
from ngraph.opset9 import maximum
from ngraph.opset9 import minimum
from ngraph.opset9 import mish
from ngraph.opset9 import mod
from ngraph.opset9 import multiclass_nms
from ngraph.opset9 import multiply
from ngraph.opset9 import mvn
from ngraph.opset9 import negative
from ngraph.opset9 import non_max_suppression
from ngraph.opset9 import non_zero
from ngraph.opset9 import normalize_l2
from ngraph.opset9 import not_equal
from ngraph.opset9 import nv12_to_bgr
from ngraph.opset9 import nv12_to_rgb
from ngraph.opset9 import one_hot
from ngraph.opset9 import pad
from ngraph.opset9 import parameter
from ngraph.opset9 import power
from ngraph.opset9 import prelu
from ngraph.opset9 import prior_box
from ngraph.opset9 import prior_box_clustered
from ngraph.opset9 import psroi_pooling
from ngraph.opset9 import proposal
from ngraph.opset9 import random_uniform
from ngraph.opset9 import range
from ngraph.opset9 import rdft
from ngraph.opset9 import read_value
from ngraph.opset9 import reduce_l1
from ngraph.opset9 import reduce_l2
from ngraph.opset9 import reduce_logical_and
from ngraph.opset9 import reduce_logical_or
from ngraph.opset9 import reduce_max
from ngraph.opset9 import reduce_mean
from ngraph.opset9 import reduce_min
from ngraph.opset9 import reduce_prod
from ngraph.opset9 import reduce_sum
from ngraph.opset9 import region_yolo
from ngraph.opset9 import reorg_yolo
from ngraph.opset9 import relu
from ngraph.opset9 import reshape
from ngraph.opset9 import result
from ngraph.opset9 import reverse_sequence
from ngraph.opset9 import rnn_cell
from ngraph.opset9 import rnn_sequence
from ngraph.opset9 import roi_align
from ngraph.opset9 import roi_pooling
from ngraph.opset9 import roll
from ngraph.opset9 import round
from ngraph.opset9 import scatter_elements_update
from ngraph.opset9 import scatter_update
from ngraph.opset9 import select
from ngraph.opset9 import selu
from ngraph.opset9 import shape_of
from ngraph.opset9 import shuffle_channels
from ngraph.opset9 import sigmoid
from ngraph.opset9 import sign
from ngraph.opset9 import sin
from ngraph.opset9 import sinh
from ngraph.opset9 import slice
from ngraph.opset9 import softmax
from ngraph.opset9 import softplus
from ngraph.opset9 import softsign
from ngraph.opset9 import space_to_batch
from ngraph.opset9 import space_to_depth
from ngraph.opset9 import split
from ngraph.opset9 import sqrt
from ngraph.opset9 import squared_difference
from ngraph.opset9 import squeeze
from ngraph.opset9 import strided_slice
from ngraph.opset9 import subtract
from ngraph.opset9 import swish
from ngraph.opset9 import tan
from ngraph.opset9 import tanh
from ngraph.opset9 import tensor_iterator
from ngraph.opset9 import tile
from ngraph.opset9 import topk
from ngraph.opset9 import transpose
from ngraph.opset9 import unsqueeze
from ngraph.opset9 import variadic_split
# Extend Node class to support binary operators
Node.__add__ = add
Node.__sub__ = subtract
Node.__mul__ = multiply
Node.__div__ = divide
Node.__truediv__ = divide
Node.__radd__ = lambda left, right: add(right, left)
Node.__rsub__ = lambda left, right: subtract(right, left)
Node.__rmul__ = lambda left, right: multiply(right, left)
Node.__rdiv__ = lambda left, right: divide(right, left)
Node.__rtruediv__ = lambda left, right: divide(right, left)
Node.__eq__ = equal
Node.__ne__ = not_equal
Node.__lt__ = less
Node.__le__ = less_equal
Node.__gt__ = greater
Node.__ge__ = greater_equal
| 2,469
|
314
|
<gh_stars>100-1000
// Copyright (c) <NAME>. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#ifndef CAN_CONTROLLER_H
#define CAN_CONTROLLER_H
#include <Arduino.h>
class CANControllerClass : public Stream {
public:
virtual int begin(long baudRate);
virtual void end();
int beginPacket(int id, int dlc = -1, bool rtr = false);
int beginExtendedPacket(long id, int dlc = -1, bool rtr = false);
virtual int endPacket();
virtual int parsePacket();
long packetId();
bool packetExtended();
bool packetRtr();
int packetDlc();
// from Print
virtual size_t write(uint8_t byte);
virtual size_t write(const uint8_t *buffer, size_t size);
// from Stream
virtual int available();
virtual int read();
virtual int peek();
virtual void flush();
virtual void onReceive(void(*callback)(int));
virtual int filter(int id) { return filter(id, 0x7ff); }
virtual int filter(int id, int mask);
virtual int filterExtended(long id) { return filterExtended(id, 0x1fffffff); }
virtual int filterExtended(long id, long mask);
virtual int observe();
virtual int loopback();
virtual int sleep();
virtual int wakeup();
protected:
CANControllerClass();
virtual ~CANControllerClass();
protected:
void (*_onReceive)(int);
bool _packetBegun;
long _txId;
bool _txExtended;
bool _txRtr;
int _txDlc;
int _txLength;
uint8_t _txData[8];
long _rxId;
bool _rxExtended;
bool _rxRtr;
int _rxDlc;
int _rxLength;
int _rxIndex;
uint8_t _rxData[8];
};
#endif
| 539
|
3,494
|
<filename>samples/_opengl/ObjLoader/androidstudio/ObjLoader/app/src/main/java/org/libcinder/samples/objloader/ObjLoaderActivity.java<gh_stars>1000+
package org.libcinder.samples.objloader;
import org.libcinder.app.CinderNativeActivity;
public class ObjLoaderActivity extends CinderNativeActivity {
static final String TAG = "ObjLoaderActivity";
}
| 112
|
306
|
<reponame>thesilvanator/SnowflakeOS
#include <math.h>
double fmax(double a, double b) {
return a > b ? a : b;
}
float fmaxf(float a, float b) {
return a > b ? a : b;
}
double fmin(double a, double b) {
return a < b ? a : b;
}
float fminf(float a, float b) {
return a < b ? a : b;
}
int min(int a, int b) {
return a < b ? a : b;
}
int max(int a, int b) {
return a > b ? a : b;
}
double fabs(double x) {
if (x < 0) {
return -x;
}
return x;
}
double exp(double x) {
double x0 = fabs(x);
if (x == 0) {
return 1;
}
const double ln2 = 0.6931471805599453;
int k = ceil((x0 / ln2) - 0.5);
double p = 1 << k;
double r = x0 - (k * ln2);
double tn = 1;
for (int i = 14; i > 0; i--) {
tn = tn * (r / i) + 1;
}
p *= tn;
if (x < 0) {
return 1 / p;
}
return p;
}
double log(double y) {
int yi = y;
int log2 = 0;
double x, r;
while (yi >>= 1) {
log2++;
}
x = (double) (1 << log2);
x = y / x;
r = -1.7417939 + (2.8212026 + (-1.4699568 + (0.44717955 - 0.056570851 * x) * x) * x) * x;
r += 0.69314718 * log2;
return r;
}
double ceil(double x) {
int n = (int) x;
if (n >= x) {
return n;
}
return n + 1;
}
double pow(double x, double y) {
return exp(x*log(y));
}
int powi(int x, int y) {
unsigned int n = 1;
while (y--) {
n *= x;
}
return n;
}
/* Note: not in the official <math.h>
*/
float clamp(float val, float min, float max) {
return fminf(fmaxf(val, min), max);
}
| 824
|
1,428
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sliderapp;
/**
*
* @author badhr
*/
public class SliderControl {
private SliderObserver[] observer = new SliderObserver[10];
private int pos,value;
public void addSlider(SliderObserver observer){
this.observer[pos++] = observer;
}
public void Notify(int value){
if(this.value != value){
this.value = value;
this.setValue(value);
}
}
public void setValue(int value){
for(int i = 0; i<pos; i++){
observer[i].update(value);
}
}
}
| 287
|
318
|
<reponame>Sunlitspace542/SNESticle<gh_stars>100-1000
#ifndef _NETSYS_H
#define _NETSYS_H
typedef int NetSysSemaT;
typedef int NetSysThreadT;
#define NETSYS_THREAD_INVALID (-1)
NetSysSemaT NetSysSemaNew(int initcount);
void NetSysSemaDelete(NetSysSemaT sema);
int NetSysSemaWait(NetSysSemaT sema);
int NetSysSemaSignal(NetSysSemaT sema);
int NetSysThreadStart(void *pThreadFunc, int priority, void *arg);
int NetSysGetSystemTime(void);
#endif
| 209
|
724
|
<filename>vega/modules/operators/functions/pytorch_to_tf.py
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MIT License for more details.
"""Convert pytorch weight to tf checkpoint."""
import logging
import re
import numpy
from collections import OrderedDict
def get_assignment_map(checkpoint_path, pop_global_step=True):
"""Get assignment from checkpoint path."""
import tensorflow.compat.v1 as tf
assignment_map = OrderedDict()
for name, var in tf.train.list_variables(checkpoint_path):
if pop_global_step and tf.GraphKeys.GLOBAL_STEP == name:
continue
if not name.endswith('/') and name.split('/'):
name = name[:name.index(name.split('/')[-1])]
assignment_map[name] = name
return assignment_map
def assign_pytorch_weights(pretrained_model_file, pretrained_prefix=None):
"""Assign pytorch weights to tf model."""
import torch
checkpoint = torch.load(pretrained_model_file)
return assign_weights(checkpoint, pretrained_prefix)
def load_weight(pt_state_dict, vars):
"""Load weigths."""
vars_values = []
for idx, var in enumerate(vars):
var_name = var.name
op_name, transpose = convert_name(var_name)
pt_name = list(pt_state_dict.keys())[idx]
logging.info('{} ==> {}'.format(var_name, pt_name))
values = pt_state_dict[pt_name].cpu().numpy()
if transpose:
values = numpy.transpose(values)
if list(var.shape) != list(values.shape):
raise ValueError("{}={} shape not equals {}={} shape".format(var.name, var.shape, pt_name, values.shape))
vars_values.append((var, values))
return vars_values
def assign_weights(pt_state_dict, pretrained_prefix=None):
"""Load pytorch state_dict and assign to tensorflow model."""
import tensorflow as tf
vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
vars.pop(0)
pt_state_dict = {k: v for k, v in pt_state_dict.items() if 'num_batches_tracked' not in k}
def _filter_vars_by_keys(var):
for key in pretrained_prefix.keys():
if var.name.startswith(key):
return True
def _filter_state_by_keys(state):
for key in pretrained_prefix.values():
if state.startswith(key):
return True
if pretrained_prefix:
vars = list(filter(_filter_vars_by_keys, vars))
pt_state_dict = {k: v for k, v in pt_state_dict.items() if _filter_state_by_keys(k)}
if not pt_state_dict or not vars:
raise ValueError("pertrained weight is None, please check the pretrained_prefix: {}".format(pretrained_prefix))
vars_values = load_weight(pt_state_dict, vars)
return [_var.assign(_value) for _var, _value in vars_values]
def convert_name(tf_name, start_prefix_to_remove=""):
"""Convert a TF variable name in a pytorch model weight name."""
tf_name = tf_name.replace(":0", "")
tf_name = re.sub(r"/[^/]*___([^/]*)/", r"/\1/", tf_name)
tf_name = tf_name.replace("_._", "/")
tf_name = re.sub(r"//+", "/", tf_name)
tf_name = tf_name.split("/")
tf_name = tf_name[1:]
transpose = bool(tf_name[-1] == "kernel" or "emb_projs" in tf_name or "out_projs" in tf_name)
if tf_name[-1] == "kernel" or tf_name[-1] == "embeddings" or tf_name[-1] == "gamma":
tf_name[-1] = "weight"
if tf_name[-1] == "beta":
tf_name[-1] = "bias"
if tf_name[-1] == "moving_mean":
tf_name[-1] = "running_mean"
if tf_name[-1] == "moving_variance":
tf_name[-1] = "running_var"
# Remove prefix if needed
tf_name = ".".join(tf_name)
if start_prefix_to_remove:
tf_name = tf_name.replace(start_prefix_to_remove, "", 1)
return tf_name, transpose
| 1,694
|
1,847
|
// Copyright (c) 2021 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file will NOT be compiled as part of Orbit 's build system. It' s meant to generate the
// testdata. Check out `testdata/Makefile` on how to compile it.
#include <cstdio>
void PrintHelloWorld() { std::puts("Hello World!\n"); }
int main() {
PrintHelloWorld();
return 0;
}
| 135
|
1,602
|
#!/usr/bin/env python3
# encoding: utf-8
"""
This script is used for manual validation.
"""
from __future__ import print_function
import numpy as np
from scipy import sparse
import os
import time
def read_csr_matrix_file(f):
data = []
row_ind = []
col_ind = []
with open(f, 'r') as handle:
m = int(handle.readline())
n = int(handle.readline())
for line in handle.readlines():
try:
elements = line.split()
value = np.float64(elements[0])
row_ind.append(int(elements[1])-1)
col_ind.append(int(elements[2])-1)
data.append(value)
except:
print('Error in parsing line:')
print(line)
raise()
A = sparse.csr_matrix((data, (row_ind, col_ind)), shape=(m, n), dtype=np.float64)
return A
def write_csr_matrix_file(f, A):
m,n = A.shape
with open(f, 'w') as handle:
print(m, file=handle)
print(n, file=handle)
rows, cols = A.nonzero()
for i,j in zip(rows, cols):
print('{} {} {}'.format(A[i,j], i+1, j+1), file=handle)
if not os.path.isfile('A.txt') or not os.path.isfile('AA.txt'):
print('This program requires A.txt and AA.txt to be generated from Chapel')
exit()
A = read_csr_matrix_file('A.txt')
write_csr_matrix_file('Apy.txt', A) # sanity check
start = time.time()
AA = A.dot(A)
end = time.time()
print('python time (s): ', end - start)
#print(AA.indptr)
#print(AA.indices)
#print(AA.has_sorted_indices)
#print(AA.sort_indices())
#print(AA.indptr)
#print(AA.indices)
# Validate results
AAref = read_csr_matrix_file('AA.txt')
AA.sort_indices()
if (AAref!=AA).nnz != 0:
print('Python A*A does not match AA.txt')
write_csr_matrix_file('AApy.txt', AA)
#print(np.allclose(AAref.A, A2.A))
| 888
|
542
|
package com.intsmaze.flink.validate;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* github地址: https://github.com/intsmaze
* 博客地址:https://www.cnblogs.com/intsmaze/
* 出版书籍《深入理解Flink核心设计与实践原理》
*
* @auther: intsmaze(刘洋)
* @date: 2020/10/15 18:33
*/
public class ValidatorUtil {
private static Validator validator = Validation.buildDefaultValidatorFactory()
.getValidator();
/**
* github地址: https://github.com/intsmaze
* 博客地址:https://www.cnblogs.com/intsmaze/
* 出版书籍《深入理解Flink核心设计与实践原理》
*
* @auther: intsmaze(刘洋)
* @date: 2020/10/15 18:33
*/
public static <T> Map<String,StringBuffer> validate(T obj){
Set<ConstraintViolation<T>> validatorSet = validator.validate(obj, Default.class);
Map<String,StringBuffer> errorMap = null;
if(validatorSet != null && validatorSet.size() >0 ){
errorMap = new HashMap<String,StringBuffer>(10);
String property = null;
for(ConstraintViolation<T> cv : validatorSet){
property = cv.getPropertyPath().toString();
if(errorMap.get(property) != null){
errorMap.get(property).append("," + cv.getMessage());
}else{
StringBuffer sb = new StringBuffer();
sb.append(cv.getMessage());
errorMap.put(property, sb);
}
}
}
return errorMap;
}
}
| 861
|
940
|
<gh_stars>100-1000
def foo():
ur"""unicode-raw"""
def bar():
u"""unicode"""
def baz():
r'raw'
def zap():
"""docstring"""
| 66
|
1,433
|
<reponame>gerald-yang/ubuntu-iotivity-demo
/* *****************************************************************
*
* Copyright 2015 Samsung Electronics All Rights Reserved.
*
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************/
/**
* @file
* This file contains the declaration of JniActionSet class
* and its members related to JniActionSet.
*/
#ifndef JNI_ACTIONSET_H_
#define JNI_ACTIONSET_H_
#include <vector>
#include <string>
#include "GroupManager.h"
#include "ActionSet.h"
#include "jni_object.h"
#include "jni_action.h"
using namespace OC;
using namespace OIC;
/**
* This class provides a set of functions to get and
* set ActionSet Class member variables.
*/
class JniActionSet : public JObject
{
public:
/**
* constructor
*/
JniActionSet(JNIEnv *env, jobject obj);
/**
* constructor
*/
JniActionSet(JNIEnv *env);
/**
* destructor
*/
~JniActionSet();
/**
* Retrieves target value from JniActionSet class object.
*
* @param name - ActionSet Name
*
* @return Boolean, true on success, otherwise false
*/
bool getJniActionSetName(std::string &name);
/**
* Sets target value of JniActionSet class object
*
* @param name - ActionSet Name
*
* @return Boolean, true on success, otherwise false
*/
bool setJniActionSetName(const std::string name);
/**
* Retrieves capability values from JniActionSet class object.
*
* @param actionList - List of Actions
*
* @return Boolean, true on success, otherwise false
*/
bool getJniListOfActions(std::vector<OIC::Action *> &actionList);
/**
* Converts actionSet class from java to CPP.
*
* @param env - Default JNI Environment Pointer
* @param jnewActionSet - action set
*
* @return OIC CPP ActionSet
*/
ActionSet *getActionSet(JNIEnv *env, jobject jnewActionSet);
/**
* Converts Time class from java to CPP.
*
* @param env - Default JNI Environment Pointer
* @param jnewActionSet - Java action set
* @param pActionSet - CPP action set
*
* @return Boolean, true on success, otherwise false
*/
bool setTimeInfo(JNIEnv *env, jobject jnewActionSet, OIC::ActionSet *pActionSet);
};
#endif //JNI_ACTIONSET_H_
| 1,248
|
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.nette.tester.preferences;
import java.io.File;
import java.util.prefs.Preferences;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.annotations.common.NullAllowed;
import org.netbeans.modules.php.api.phpmodule.PhpModule;
import org.netbeans.modules.php.api.util.StringUtils;
import org.netbeans.modules.php.nette.tester.TesterTestingProvider;
import org.netbeans.spi.project.support.ant.PropertyUtils;
import org.openide.filesystems.FileUtil;
/**
* Nette Tester preferences specific for each PHP module.
*/
public final class TesterPreferences {
private static final String PHP_INI_ENABLED = "php.ini.enabled"; // NOI18N
private static final String PHP_INI_PATH = "php.ini.path"; // NOI18N
private static final String TESTER_ENABLED = "tester.enabled"; // NOI18N
private static final String TESTER_PATH = "tester.path"; // NOI18N
private static final String BINARY_ENABLED = "binary.enabled"; // NOI18N
private static final String BINARY_EXECUTABLE = "binary.executable"; // NOI18N
private static final String COVERAGE_SOURCE_PATH_ENABLED = "coverage.source.path.enabled"; // NOI18N
private static final String COVERAGE_SOURCE_PATH = "coverage.source.path"; // NOI18N
private TesterPreferences() {
}
public static boolean isPhpIniEnabled(PhpModule phpModule) {
return getPreferences(phpModule).getBoolean(PHP_INI_ENABLED, false);
}
public static void setPhpIniEnabled(PhpModule phpModule, boolean phpIniEnabled) {
getPreferences(phpModule).putBoolean(PHP_INI_ENABLED, phpIniEnabled);
}
@CheckForNull
public static String getPhpIniPath(PhpModule phpModule) {
return resolvePath(phpModule, getPreferences(phpModule).get(PHP_INI_PATH, null));
}
public static void setPhpIniPath(PhpModule phpModule, String phpIniPath) {
getPreferences(phpModule).put(PHP_INI_PATH, relativizePath(phpModule, phpIniPath));
}
public static boolean isTesterEnabled(PhpModule phpModule) {
return getPreferences(phpModule).getBoolean(TESTER_ENABLED, false);
}
public static void setTesterEnabled(PhpModule phpModule, boolean testerEnabled) {
getPreferences(phpModule).putBoolean(TESTER_ENABLED, testerEnabled);
}
@CheckForNull
public static String getTesterPath(PhpModule phpModule) {
return resolvePath(phpModule, getPreferences(phpModule).get(TESTER_PATH, null));
}
public static void setTesterPath(PhpModule phpModule, String testerPath) {
getPreferences(phpModule).put(TESTER_PATH, relativizePath(phpModule, testerPath));
}
public static boolean isBinaryEnabled(PhpModule phpModule) {
return getPreferences(phpModule).getBoolean(BINARY_ENABLED, false);
}
public static void setBinaryEnabled(PhpModule phpModule, boolean binaryEnabled) {
getPreferences(phpModule).putBoolean(BINARY_ENABLED, binaryEnabled);
}
@CheckForNull
public static String getBinaryExecutable(PhpModule phpModule) {
return getPreferences(phpModule).get(BINARY_EXECUTABLE, null);
}
public static void setBinaryExecutable(PhpModule phpModule, @NullAllowed String binaryExecutable) {
if (binaryExecutable == null) {
getPreferences(phpModule).remove(BINARY_EXECUTABLE);
} else {
getPreferences(phpModule).put(BINARY_EXECUTABLE, binaryExecutable);
}
}
public static boolean isCoverageSourcePathEnabled(PhpModule phpModule) {
return getPreferences(phpModule).getBoolean(COVERAGE_SOURCE_PATH_ENABLED, false);
}
public static void setCoverageSourcePathEnabled(PhpModule phpModule, boolean pathEnabled) {
getPreferences(phpModule).putBoolean(COVERAGE_SOURCE_PATH_ENABLED, pathEnabled);
}
@CheckForNull
public static String getCoverageSourcePath(PhpModule phpModule) {
return resolvePath(phpModule, getPreferences(phpModule).get(COVERAGE_SOURCE_PATH, null));
}
public static void setCoverageSourcePath(PhpModule phpModule, String sourcePath) {
getPreferences(phpModule).put(COVERAGE_SOURCE_PATH, relativizePath(phpModule, sourcePath));
}
private static Preferences getPreferences(PhpModule module) {
return module.getPreferences(TesterTestingProvider.class, true);
}
private static String relativizePath(PhpModule phpModule, String filePath) {
if (!StringUtils.hasText(filePath)) {
return ""; // NOI18N
}
File file = new File(filePath);
String path = PropertyUtils.relativizeFile(FileUtil.toFile(phpModule.getProjectDirectory()), file);
if (path == null) {
// sorry, cannot be relativized
path = file.getAbsolutePath();
}
return path;
}
private static String resolvePath(PhpModule phpModule, String filePath) {
if (!StringUtils.hasText(filePath)) {
return null;
}
return PropertyUtils.resolveFile(FileUtil.toFile(phpModule.getProjectDirectory()), filePath).getAbsolutePath();
}
}
| 2,077
|
362
|
/*
* Copyright (c) 2005, The JUNG Authors
*
* All rights reserved.
*
* This software is open-source under the BSD license; see either
* "license.txt" or
* https://github.com/jrtom/jung/blob/master/LICENSE for a description.
* Created on Mar 8, 2005
*
*/
package edu.uci.ics.jung.visualization.control;
import edu.uci.ics.jung.visualization.MultiLayerTransformer.Layer;
import edu.uci.ics.jung.visualization.VisualizationServer;
import edu.uci.ics.jung.visualization.transform.MutableTransformer;
import java.awt.geom.Point2D;
/**
* ViewScalingGraphMouse applies a scaling transform to the View of the graph. This causes all
* elements of the graph to grow larger or smaller. ViewScalingGraphMouse, by default, is activated
* by the MouseWheel when the control key is pressed. The control key modifier can be overridden in
* the contstructor.
*
* @author <NAME>
*/
public class ViewScalingControl implements ScalingControl {
/** zoom the display in or out, depending on the direction of the mouse wheel motion. */
public void scale(VisualizationServer<?, ?> vv, float amount, Point2D from) {
MutableTransformer viewTransformer =
vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW);
viewTransformer.scale(amount, amount, from);
vv.repaint();
}
}
| 400
|
308
|
package com.hexagonaldemo.ticketapi.common.event.consumer;
import com.hexagonaldemo.ticketapi.common.model.Event;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentLinkedDeque;
@Slf4j
@Service
public abstract class AbstractEventKafkaStreamTestConsumer<T extends Event> {
private Deque<T> eventsQueue;
public abstract void consume(@Payload T event);
protected void consumerInternal(T event) {
log.info("Event received:: {}", event);
initializeEventQueue();
keepEvent(event);
log.info("Event added to the kafka event list as {}th entry, event: {}", queueSize(), event);
}
@Synchronized
public void wait(int maxWaitInSec, int expectedEventSize) {
initializeEventQueue();
try {
LocalDateTime startTime = LocalDateTime.now();
int checkCount = 0;
while (true) {
if (!(checkCount++ < maxWaitInSec)) break;
if (eventsQueue.size() >= expectedEventSize) break;
sleepOneSecond();
}
LocalDateTime endTime = LocalDateTime.now();
log.info("Tried {} seconds. Expected event count is {} and actual event size is {}", Duration.between(startTime, endTime).toSeconds(), expectedEventSize, eventsQueue.size());
} catch (Exception e) {
log.info("Expected event count is {} and actual event size is {}" + e, expectedEventSize, Objects.isNull(eventsQueue) ? 0 : eventsQueue.size());
}
}
protected void initializeEventQueue() {
if (Objects.isNull(eventsQueue)) {
this.eventsQueue = new ConcurrentLinkedDeque<>();
}
}
protected void keepEvent(T event) {
eventsQueue.add(event);
}
protected int queueSize() {
return eventsQueue.size();
}
private void sleepOneSecond() {
try {
Thread.sleep(1000); //NOSONAR
} catch (InterruptedException e) {
log.error("Sleep interrupted", e);
}
}
public void reset() {
eventsQueue = null;
}
public T pop() {
T event = eventsQueue.pollFirst();
log.info("Last event from the consumed list is popped for validation. Event: {}", event);
return event;
}
@Synchronized
public List<T> popAll() {
if (Objects.isNull(this.eventsQueue)) return List.of();
List<T> eventsAsList = new ArrayList<>(this.eventsQueue);
log.info("All {} events from the consumed list is popped for validation.", eventsQueue.size());
eventsQueue.clear();
return eventsAsList;
}
}
| 1,147
|
2,446
|
{
"data" : {
"content" : "“没啥大问题了,医疗费20。”见到浓妆女醒过来,毕云涛伸出手掌来。\n众人齐翻白眼,林雪眼中全是震惊之色,忙上前抓住浓妆女,只是探查她的病情。\n“你……你怎么做到的?”林雪忙问道。\n毕云涛双手一摊,说道:“就是这样啊!你不全都看见了吗?”\n年轻的警察有些疑惑的问道方静若:“张叔,这人还抓吗?”\n张叔低头沉吟,现在的情况他也搞不清楚了,这两名女子是林氏医馆的人,林氏医馆跟江南市的很多权贵都有结交,很明显,不是好惹的,至于小郎中跟浓妆女,也没发生什么事儿。\n“算了,收队吧!”张叔说道。\n“张叔,我不服!他……他还打了我屁股的!”方静若气呼呼的指着毕云涛,那眼神仿佛要将毕云涛给吃了一般。\n毕云涛浓眉一竖,道:“咋地?你还要赖上我不成?我跟你说,你屁股不够大,生不出儿子来的,我不要!”\n方静若眼睛瞪着溜大,看着毕云涛的眼神都快喷出了火花,两名警官都被吓傻了,方静若虽然人很漂亮,但是在警队里可是出了名的火爆,这男的肯定是凶多吉少了。\n但接下来的一幕却让众人傻眼,只见方静若走上前,嫣然一笑,对毕云涛说道:“不错!我就是要你负责,你难道不觉得我很漂亮吗?”\n林雪跟静儿两人一脸迷糊,不知道这是个什么情况。\n“那个……,没啥事儿的话,我们就先走了啊!还有很多病人等着我们去救治呢!”静儿给林雪递了个眼色,林雪当即会意。\n张叔点了点头,示意她们两人可以离去,然后只见静儿跟林雪两人噔噔瞪几声响就下了楼。\n毕云涛认真的打量起方静若来,然后再点了点头:“你很漂亮,但是生不出儿子。”\n方静若强忍着怒意,直接说道:“今天你这么羞辱我,这件事肯定不可能就这样完了的,有本事就给我留个电话!”\n毕云涛不得已之下,只好给方静若留了一个电话。\n得到毕云涛电话号码之后的方静若立马就带着两名警官走了,当然,临走之前他们还驱走了那名浓妆女。\n毕云涛看了看乱糟糟的房间,一时头大,这都什么事儿啊!\n第二天一大早,毕云涛就起床了,兴冲冲的走到老板娘哪里问长生医馆的地址。\n但是老板娘的回答让毕云涛差点打人。\n只见老板娘随意说道:“这个城市那么大,我咋知道长生医馆搬去哪里了?”\n毕云涛摸了摸脑袋,这话他好像听昨夜那个司机说过啊!\n没有办法,毕云涛只好再次踏上了寻找长生医馆的路途。\n就在毕云涛刚出旅馆的时候,突然之间,从街角钻出一个极其漂亮的女子。\n这女子大约二十来岁的样子,这女人腰细臀翘,眼睛更是水汪汪的,小嘴娇嫩微启,细眉没有经过任何的修饰,但却带着一丝妩媚,拥有东方女性独特的气质之美,简直美得冒泡!\n女子穿着简单的浅蓝色牛仔裤,上身也只是一件长袖红色格子衬衫,长袖挽起,露出洁白的玉臂,一个字:漂亮!\n毕云涛简直看呆了,这人好似画中走出来的仙子一般,并且,并且她还带着微笑向自己走来呢!\n咳咳!毕云涛连忙打起精神,将腰杆挺直了,就算是擦肩而过,也要留个潇洒帅气的形象不是?\n“嘿!一起去吃个饭吧!”漂亮女子脸上带着笑容开口道。\n只是不知道为什么,毕云涛老是觉得这女人自己仿佛在哪里见过,并且她的笑容,很不自然,似乎是憋出来的。\n毕云涛一愣,连忙左右望了望,没人啊!难道……难道美女要请吃饭!\n“那个……你跟我说话吗?”毕云涛羞涩的问道。\n“走吧!我请你吃饭!”漂亮女子直接拉起毕云涛的衣袖往前面拽,毕云涛吓了一大跳,连忙说道:“那啥啊!我们都不认识,你干吗请我吃饭,你别以为我乡下来的就好骗啊!昨天那啥还有两个骗子给我打发走了……”\n漂亮女子一头黑线,转过头来冷冷道:“不记得我了吗?昨天晚上你还打了我呢!”\n啥?毕云涛马上回忆起来,眼前的女子的样貌慢慢跟自己记忆中的那个人融合。\n毕云涛立即惊呼道:“噢!你!你就是昨天晚上被我打屁股的那个女警啊!”\n这声音一喊出来,顿时吸引了不少人的目光,引得路人纷纷回头偷看。\n方静若恨不得找个地缝钻进去,连忙道:“你小点声,这事我们还没完呢!还有我叫方静若,你今后若是敢提半个“被打屁股的女警”的话,我马上翻脸!”说着,方静若还扬了扬小粉拳。\n毕云涛立即点头,说道:“好!念在你要请我吃饭的份上,昨天晚上的事情我就当做没发生了,走吧!”\n方静若气得直咬银牙,但马上脸上又将脸上的怒容强行压了下去,若不是自己有求于他,见到毕云涛的那刻就要跟他拼命,更加别说请吃饭了。\n方静若带着毕云涛走到了一家装扮典雅的餐厅外,很有些小资情调的样子。\n毕云涛看了看眼前这个装扮典雅的餐厅,摇头说道:“方警官,那啥,昨天晚上的事儿我真的不追究了,这个餐厅恐怕有些贵,咱们将就下找个小饭馆就得了。”\n听见毕云涛这么说,方静若对毕云涛的印象稍微好转了一些,这小子还知道给自己节省钱,看样子也不是那么的坏嘛!\n咬了咬牙,方静若长袖一挥,说道:“别啰嗦,进去吃饭就是。”\n进了餐厅之后,马上就有服务员将两人带到一个桌子旁,然后恭敬的拿出菜单递给方静若。\n方静若把菜单拿给毕云涛,示意让毕云涛来点。\n毕云涛看了看,好家伙!图片上的美食真是诱人,但是价格都不菲呢!翻遍全部菜单,毕云涛都没有找到一份低于50的菜品。\n“你……,你点吧!我随便就行。”毕云涛说道。\n虽然毕云涛很想宰这女警一次,但是他现在还没搞清楚方静若的真正目的呢!一切还是看情况再说。",
"prev_id" : 1004,
"id" : 1005,
"next_id" : 1006,
"price" : 0,
"title" : "第六章 美女请吃饭",
"index" : 5,
"novel_id" : 1945
}
}
| 4,734
|
1,467
|
<reponame>ascheja/aws-sdk-java-v2
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics;
import java.time.Instant;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* An immutable collection of metrics.
*/
@SdkPublicApi
public interface MetricCollection extends Iterable<MetricRecord<?>> {
/**
* @return The name of this metric collection.
*/
String name();
/**
* Return a stream of records in this collection.
*/
default Stream<MetricRecord<?>> stream() {
return StreamSupport.stream(spliterator(), false);
}
/**
* Return all the values of the given metric.
*
* @param metric The metric.
* @param <T> The type of the value.
* @return All of the values of this metric.
*/
<T> List<T> metricValues(SdkMetric<T> metric);
/**
* @return The child metric collections.
*/
List<MetricCollection> children();
/**
* Return all of the {@link #children()} with a specific name.
*
* @param name The name by which we will filter {@link #children()}.
* @return The child metric collections that have the provided name.
*/
default Stream<MetricCollection> childrenWithName(String name) {
return children().stream().filter(c -> c.name().equals(name));
}
/**
* @return The time at which this collection was created.
*/
Instant creationTime();
}
| 676
|
509
|
package com.dyman.easyshow3d.thread;
/**
* Created by dyman on 18/5/17.
*/
public interface IAnalysisFinishCallback {
void verticeProgressUpdate(int threadID, int nums);
void faceProgressUpdate(int threadID, int nums);
void alvFinish();
void alvFaceFinish();
}
| 97
|
1,144
|
<filename>qemu-4.2.0/roms/u-boot/cmd/fs.c<gh_stars>1000+
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2012, NVIDIA CORPORATION. All rights reserved.
*
* Inspired by cmd_ext_common.c, cmd_fat.c.
*/
#include <common.h>
#include <command.h>
#include <fs.h>
#include <efi_loader.h>
static int do_size_wrapper(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return do_size(cmdtp, flag, argc, argv, FS_TYPE_ANY);
}
U_BOOT_CMD(
size, 4, 0, do_size_wrapper,
"determine a file's size",
"<interface> <dev[:part]> <filename>\n"
" - Find file 'filename' from 'dev' on 'interface'\n"
" and determine its size."
);
static int do_load_wrapper(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[])
{
efi_set_bootdev(argv[1], (argc > 2) ? argv[2] : "",
(argc > 4) ? argv[4] : "");
return do_load(cmdtp, flag, argc, argv, FS_TYPE_ANY);
}
U_BOOT_CMD(
load, 7, 0, do_load_wrapper,
"load binary file from a filesystem",
"<interface> [<dev[:part]> [<addr> [<filename> [bytes [pos]]]]]\n"
" - Load binary file 'filename' from partition 'part' on device\n"
" type 'interface' instance 'dev' to address 'addr' in memory.\n"
" 'bytes' gives the size to load in bytes.\n"
" If 'bytes' is 0 or omitted, the file is read until the end.\n"
" 'pos' gives the file byte position to start reading from.\n"
" If 'pos' is 0 or omitted, the file is read from the start."
)
static int do_save_wrapper(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[])
{
return do_save(cmdtp, flag, argc, argv, FS_TYPE_ANY);
}
U_BOOT_CMD(
save, 7, 0, do_save_wrapper,
"save file to a filesystem",
"<interface> <dev[:part]> <addr> <filename> bytes [pos]\n"
" - Save binary file 'filename' to partition 'part' on device\n"
" type 'interface' instance 'dev' from addr 'addr' in memory.\n"
" 'bytes' gives the size to save in bytes and is mandatory.\n"
" 'pos' gives the file byte position to start writing to.\n"
" If 'pos' is 0 or omitted, the file is written from the start."
)
static int do_ls_wrapper(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[])
{
return do_ls(cmdtp, flag, argc, argv, FS_TYPE_ANY);
}
U_BOOT_CMD(
ls, 4, 1, do_ls_wrapper,
"list files in a directory (default /)",
"<interface> [<dev[:part]> [directory]]\n"
" - List files in directory 'directory' of partition 'part' on\n"
" device type 'interface' instance 'dev'."
)
static int do_fstype_wrapper(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[])
{
return do_fs_type(cmdtp, flag, argc, argv);
}
U_BOOT_CMD(
fstype, 4, 1, do_fstype_wrapper,
"Look up a filesystem type",
"<interface> <dev>:<part>\n"
"- print filesystem type\n"
"fstype <interface> <dev>:<part> <varname>\n"
"- set environment variable to filesystem type\n"
);
| 1,206
|
1,188
|
<reponame>nagineni/chromium-crosswalk
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.android_webview;
import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
import java.io.InputStream;
/**
* The response information that is to be returned for a particular resource fetch.
*/
@JNINamespace("android_webview")
public class InterceptedRequestData {
private String mMimeType;
private String mCharset;
private InputStream mData;
public InterceptedRequestData(String mimeType, String encoding, InputStream data) {
mMimeType = mimeType;
mCharset = encoding;
mData = data;
}
@CalledByNative
public String getMimeType() {
return mMimeType;
}
@CalledByNative
public String getCharset() {
return mCharset;
}
@CalledByNative
public InputStream getData() {
return mData;
}
}
| 375
|
977
|
<reponame>pedropbazzo/graphql-spqr
package io.leangen.graphql.module.common.gson;
import io.leangen.graphql.generator.mapping.OutputConverter;
import io.leangen.graphql.generator.mapping.TypeMapper;
import io.leangen.graphql.module.SimpleModule;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class GsonModule implements SimpleModule {
private static final GsonArrayAdapter arrayAdapter = new GsonArrayAdapter();
@Override
public List<TypeMapper> getTypeMappers() {
return Arrays.asList(new GsonScalarTypeMapper(), arrayAdapter);
}
@Override
public List<OutputConverter<?, ?>> getOutputConverters() {
return Collections.singletonList(arrayAdapter);
}
@Override
public void setUp(SetupContext context) {
if (!getTypeMappers().isEmpty()) {
context.getSchemaGenerator().withTypeMappersPrepended(getTypeMappers().toArray(new TypeMapper[0]));
}
if (!getOutputConverters().isEmpty()) {
context.getSchemaGenerator().withOutputConvertersPrepended(getOutputConverters().toArray(new OutputConverter[0]));
}
}
}
| 434
|
1,705
|
{
"pagination": {
"ListComponents": {
"input_token": "nextToken",
"output_token": "nextToken",
"limit_key": "maxResults",
"result_key": "entities"
},
"ListThemes": {
"input_token": "nextToken",
"output_token": "nextToken",
"limit_key": "maxResults",
"result_key": "entities"
}
}
}
| 165
|
1,444
|
<filename>Mage.Sets/src/mage/cards/w/WeatheredWayfarer.java<gh_stars>1000+
package mage.cards.w;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.ActivateIfConditionActivatedAbility;
import mage.abilities.condition.common.OpponentControlsMoreCondition;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.search.SearchLibraryPutInHandEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.filter.StaticFilters;
import mage.filter.common.FilterLandCard;
import mage.target.common.TargetCardInLibrary;
/**
*
* @author LevelX2
*/
public final class WeatheredWayfarer extends CardImpl {
public WeatheredWayfarer(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.NOMAD);
this.subtype.add(SubType.CLERIC);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
// {W}, {tap}: Search your library for a land card, reveal it, and put it into your hand. Then shuffle your library. Activate this ability only if an opponent controls more lands than you.
Ability ability = new ActivateIfConditionActivatedAbility(
Zone.BATTLEFIELD,
new SearchLibraryPutInHandEffect(new TargetCardInLibrary(new FilterLandCard()), true, true),
new ManaCostsImpl("{W}"),
new OpponentControlsMoreCondition(StaticFilters.FILTER_LANDS));
ability.addCost(new TapSourceCost());
this.addAbility(ability);
}
private WeatheredWayfarer(final WeatheredWayfarer card) {
super(card);
}
@Override
public WeatheredWayfarer copy() {
return new WeatheredWayfarer(this);
}
}
| 731
|
2,406
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <algorithm>
#include <vector>
#include "openvino/core/core_visibility.hpp"
#include "openvino/core/rtti.hpp"
#include "openvino/core/shape.hpp"
namespace ov {
/// \brief Coordinates for a tensor element
class Coordinate : public std::vector<size_t> {
public:
OPENVINO_API Coordinate();
OPENVINO_API Coordinate(const std::initializer_list<size_t>& axes);
OPENVINO_API Coordinate(const Shape& shape);
OPENVINO_API Coordinate(const std::vector<size_t>& axes);
OPENVINO_API Coordinate(const Coordinate& axes);
OPENVINO_API Coordinate(size_t n, size_t initial_value = 0);
OPENVINO_API ~Coordinate();
template <class InputIterator>
Coordinate(InputIterator first, InputIterator last) : std::vector<size_t>(first, last) {}
OPENVINO_API Coordinate& operator=(const Coordinate& v);
OPENVINO_API Coordinate& operator=(Coordinate&& v) noexcept;
};
OPENVINO_API
std::ostream& operator<<(std::ostream& s, const Coordinate& coordinate);
template <>
class OPENVINO_API AttributeAdapter<Coordinate> : public IndirectVectorValueAccessor<Coordinate, std::vector<int64_t>> {
public:
AttributeAdapter(Coordinate& value) : IndirectVectorValueAccessor<Coordinate, std::vector<int64_t>>(value) {}
OPENVINO_RTTI("AttributeAdapter<Coordinate>");
BWDCMP_RTTI_DECLARATION;
};
} // namespace ov
| 509
|
14,668
|
// 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 "third_party/blink/renderer/core/frame/window_controls_overlay.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/navigator.h"
#include "third_party/blink/renderer/core/frame/window_controls_overlay_geometry_change_event.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
// static
const char WindowControlsOverlay::kSupplementName[] = "WindowControlsOverlay";
// static
WindowControlsOverlay& WindowControlsOverlay::From(Navigator& navigator) {
WindowControlsOverlay* supplement = FromIfExists(navigator);
if (!supplement) {
supplement = MakeGarbageCollected<WindowControlsOverlay>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
}
// static
WindowControlsOverlay* WindowControlsOverlay::FromIfExists(
Navigator& navigator) {
return Supplement<Navigator>::From<WindowControlsOverlay>(navigator);
}
// static
WindowControlsOverlay* WindowControlsOverlay::windowControlsOverlay(
Navigator& navigator) {
return &From(navigator);
}
WindowControlsOverlay::WindowControlsOverlay(Navigator& navigator)
: Supplement<Navigator>(navigator) {}
WindowControlsOverlay::~WindowControlsOverlay() = default;
ExecutionContext* WindowControlsOverlay::GetExecutionContext() const {
return GetSupplementable()->DomWindow();
}
const AtomicString& WindowControlsOverlay::InterfaceName() const {
return event_target_names::kWindowControlsOverlay;
}
bool WindowControlsOverlay::visible() const {
if (!GetSupplementable()->DomWindow())
return false;
return GetSupplementable()
->DomWindow()
->GetFrame()
->IsWindowControlsOverlayVisible();
}
DOMRect* WindowControlsOverlay::getTitlebarAreaRect() const {
if (!GetSupplementable()->DomWindow())
return DOMRect::Create(0, 0, 0, 0);
const auto& rect = GetSupplementable()
->DomWindow()
->GetFrame()
->GetWindowControlsOverlayRect();
return DOMRect::Create(rect.x(), rect.y(), rect.width(), rect.height());
}
void WindowControlsOverlay::WindowControlsOverlayChanged(
const gfx::Rect& rect) {
DispatchEvent(
*(MakeGarbageCollected<WindowControlsOverlayGeometryChangeEvent>(
event_type_names::kGeometrychange,
DOMRect::Create(rect.x(), rect.y(), rect.width(), rect.height()),
!rect.IsEmpty())));
}
void WindowControlsOverlay::Trace(blink::Visitor* visitor) const {
EventTargetWithInlineData::Trace(visitor);
Supplement<Navigator>::Trace(visitor);
}
} // namespace blink
| 995
|
45,293
|
public final class C /* p.C*/ extends p.A {
public C();// .ctor()
public int af();// af$light_idea_test_case()
public int getAp();// getAp$light_idea_test_case()
}
| 68
|
348
|
<filename>docs/data/leg-t2/061/06101365.json
{"nom":"Saint-Aubin-d'Appenai","circ":"1ère circonscription","dpt":"Orne","inscrits":335,"abs":165,"votants":170,"blancs":10,"nuls":4,"exp":156,"res":[{"nuance":"DVD","nom":"<NAME>","voix":85},{"nuance":"SOC","nom":"M. <NAME>","voix":71}]}
| 119
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.