max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
554 | <reponame>Amdrossa/Anime<filename>anime_downloader/extractors/kwik_extractor.py
import re
from util.Color import printer
from time import sleep
from extractors.kwik_token_extractor import kwik_token_extractor
from bs4 import BeautifulSoup
class KwikExtractor:
def __init__(self, session, gui=None):
self.session = session
self.gui = gui
self.token = None
def __get_cookie_and_response(self, episode):
printer("INFO", "Collecting request header values...", self.gui)
head = {
"referer": episode.page_url,
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 Edg/80.0.361.69"
}
response = self.session.get(episode.page_url, headers=head)
cookie = []
try:
cookie.append(response.headers["set-cookie"])
cookie.append(response)
except Exception as ex:
printer("ERROR", ex, self.gui)
return None
return cookie
def __set_token(self, response_text):
data = re.search("[\S]+\",[\d]+,\"[\S]+\",[\d]+,[\d]+,[\d]+", response_text).group(0)
parameters = data.split(",")
para1 = parameters[0].strip("\"")
para2 = int(parameters[1])
para3 = parameters[2].strip("\"")
para4 = int(parameters[3])
para5 = int(parameters[4])
para6 = int(parameters[5])
page_data = kwik_token_extractor.extract_data(para1, para2, para3, para4, para5, para6)
page_data = BeautifulSoup(page_data, "html.parser")
input_field = page_data.find("input", attrs={"name": "_token"})
# print(input_field)
if input_field is not None:
self.token = input_field["value"]
# print(self.token)
return True
return False
def set_direct_link(self, episode):
cookie = self.__get_cookie_and_response(episode)
if cookie is None:
printer("INFO", "Retrying header retrieval...", self.gui)
sleep(2)
cookie = self.__get_cookie_and_response(episode)
if cookie is None:
printer("ERROR", "Couldn't find headers needed ...", self.gui)
return False
# token = self.__get_token(cookie[1])
if self.token is None:
self.__set_token(cookie[1].text)
if self.token is None:
printer("ERROR", "No token found... skipping", self.gui)
return False
# print(cookie[0])
head = {
"origin": "https://kwik.cx",
"referer": episode.page_url,
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 Edg/80.0.361.69",
"cookie": cookie[0]
}
payload = {
"_token": self.token
}
post_url = "https://kwik.cx/d/" + episode.id
# print(head)
# print(payload)
# print(post_url)
resp_headers = self.session.post(post_url, data=payload, headers=head, allow_redirects=False)
# print(resp_headers)
try:
episode.download_url = resp_headers.headers["location"]
# print(resp_headers.headers["location"])
except Exception as ex:
# print(resp_headers)
# printer("ERROR", ex, self.gui)
self.token = None
printer("ERROR", "Failed to retrieve direct url for " + episode.title, self.gui)
return False
return True
| 1,678 |
1,104 | <reponame>mesch/roll20-character-sheets
{
"Name": "Nom",
"Race": "Race",
"Class": "Classe",
"Level": "Niveau",
"AbilityScores": "AbilityScores",
"STR": "FOR",
"Strength": "Force",
"CON": "CON",
"Constitution": "Constitution",
"DEX": "DEX",
"Dexterity": "Dextérité",
"INT": "INT",
"Intelligence": "Intelligence",
"WIS": "SAG",
"Wisdom": "Sagesse",
"CHA": "CAR",
"Charisma": "Charisme",
"Base": "Base",
"+Misc.": "+Misc.",
"+Item": "+Item",
"Mod": "Modérer",
"Total": "Totale ",
"Basic Melee Attack": "Basic Melee Attack",
"Basic Ranged Attack": "Basic Ranged Attack",
"Defenses": "Défenses",
"Attack": "Attaque",
"Damage": "Dégâts",
"Miss": "Raté",
"Ability": "Caractéristique",
"Misc.": "Divers",
"Weapon": "Arme",
"Item": "Objet",
"On Miss": "On Miss",
"AC": "CA",
"PD": "DP",
"MD": "DM",
"Basic melee": "Basic melee",
"Basic ranged": "Basic ranged",
"Situational Attack Modifier": "Situational Attack Modifier",
"Damage on hit": "Damage on hit",
"Damage on miss": "Damage on miss",
"Escalation die value": "Escalation die value",
"Attack result": "Résultat de l'attaque",
"Hit Points": "Points de Vie",
"HP": "PV",
"Recoveries": "Recoveries",
"Recovery": "Recovery",
"Recovery Value": "Recovery Value",
"Current": "Actuel",
"Max.": "Max.",
"Rec. Die": "Rec. Die",
"Temp.": "Temp.",
"Initiative": "Initiative",
"One Unique Thing": "Particularité",
"Describe your characters one unique thing ...": "Décrivez la particularité de votre personnage...",
"Class Features": "Capacités de classe",
"Talents": "Talents",
"Powers & Spells": "Pouvoirs & Sorts",
"Feats": "Dons",
"At-Will": "À volonté",
"Battle uses left": "Battle uses left",
"Daily uses left": "Daily uses left",
"Show Description": "Afficher description",
"Show Macro": "Afficher macro",
"Usage": "Utilisation",
"Type": "Type",
"Points": "Points",
"Icon Relationships": "Relations aux Icônes",
"Icon": "Icône :",
"positive": "positif",
"conflicted": "conflicted",
"negative": "négatif",
"Background": "Fond",
"Backgrounds": "Historiques",
"Roll": "Lancer",
"Attribute": "Attribut",
"Check": "Jet",
"Description": "Description ",
"Macro": "Macro",
"Magic Items": "Objets magiques",
"Equipment": "Équipement",
"Coins": "Pièces",
"Qty": "Qté",
"Incremental Advances": "Incremental Advances",
"4th / 7th / 10th Level": "4th / 7th / 10th Level <br>(+1 to 3 abilities)",
"abilities": "abilities",
"Extra Magic Item": "Extra Magic Item",
"Ability Score Bonus": "Ability Score Bonus",
"Skills": "Compétences",
"Power/Spell": "Pouvoir / Sort",
"Feat": "Don"
}
| 1,041 |
4,879 | <gh_stars>1000+
package com.mapswithme.maps.api;
/**
* Represents url_scheme::RoutePoint from core.
*/
public class RoutePoint
{
public final double mLat;
public final double mLon;
public final String mName;
public RoutePoint(double lat, double lon, String name)
{
mLat = lat;
mLon = lon;
mName = name;
}
}
| 122 |
764 | {"symbol": "CDX","address": "0x6fFF3806Bbac52A20e0d79BC538d527f6a22c96b","overview":{"en": ""},"email": "<EMAIL>","website": "https://cdxnet.com/","state": "NORMAL","links": {"blog": "https://cdxnet.com/blog/","twitter": "","telegram": "","github": ""}} | 104 |
1,056 | <reponame>Antholoj/netbeans<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.javafx2.editor.completion.impl;
import java.util.List;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.editor.mimelookup.MimeRegistration;
import org.netbeans.spi.editor.completion.CompletionItem;
import org.netbeans.spi.editor.mimelookup.MimeLocation;
/**
* Completer provides CompletionItems for a certain feature or a language
* construct. Its {@link Factory} is called when the user invokes the CC,
* and may create a Completer instance if it decides the context is interesting.
* The Completer may produce zero to many CompletionItems.
* <p/>
* The Completer may hold state, a new instance should be created for each Completion
* invocation by the {@code Factory.createCompleter} method.
* @author sdedic
*/
public interface Completer {
/**
* Processes the CompletionContext and provides the completion items.
* The method is called <b>OUTSIDE</b> the Document's read lock.
*
* @return null, or any number (incl. zero) CompletionItems
*/
@CheckForNull
public List<? extends CompletionItem> complete();
public boolean hasMoreItems();
/**
* Factory interface should be registered into MIME lookup using {@link MimeRegistration}
* annotation. The {@link #createCompleter} will be called with an initialized
* CompletionContext to decide whether the Factory can provide an appropriate Completer.
* This allows to decompose completion code into pieces and extend it over time.
*/
@MimeLocation(subfolderName="completion")
public interface Factory {
/**
* Called by the infrastructure when completion items are to be produced.
* The method should check the {@link CompletionContext}, whether its state
* is applicable to this Completer and if so, the {@link Completer} instance
* should be returned.
* <p/>
* New Completer instance should be allocated and initialized
* with CompletionContext by this method.
*
* @param ctx contextual information to create completion items
* @return
*/
@CheckForNull
public Completer createCompleter(@NonNull CompletionContext ctx);
}
}
| 987 |
2,519 | <filename>be/src/column/datum_tuple.h
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#pragma once
#include <vector>
#include "column/datum.h"
namespace starrocks::vectorized {
class Schema;
class DatumTuple {
public:
DatumTuple() = default;
explicit DatumTuple(std::vector<Datum> datums) : _datums(std::move(datums)) {}
size_t size() const { return _datums.size(); }
void reserve(size_t n) { _datums.reserve(n); }
void append(const Datum& datum) { _datums.emplace_back(datum); }
const Datum& operator[](size_t n) const { return _datums[n]; }
const Datum& get(size_t n) const { return _datums.at(n); }
Datum& operator[](size_t n) { return _datums[n]; }
Datum& get(size_t n) { return _datums.at(n); }
int compare(const Schema& schema, const DatumTuple& rhs) const;
const std::vector<Datum>& datums() const { return _datums; }
private:
std::vector<Datum> _datums;
};
} // namespace starrocks::vectorized
| 392 |
12,278 | /*
Copyright 2018 <NAME>
(<EMAIL>)
Distributed under the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt
or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_TT_IS_UNBOUNDED_ARRAY_HPP_INCLUDED
#define BOOST_TT_IS_UNBOUNDED_ARRAY_HPP_INCLUDED
#include <boost/type_traits/integral_constant.hpp>
namespace boost {
template<class T>
struct is_unbounded_array
: false_type { };
#if !defined(BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS)
template<class T>
struct is_unbounded_array<T[]>
: true_type { };
template<class T>
struct is_unbounded_array<const T[]>
: true_type { };
template<class T>
struct is_unbounded_array<volatile T[]>
: true_type { };
template<class T>
struct is_unbounded_array<const volatile T[]>
: true_type { };
#endif
} /* boost */
#endif
| 332 |
435 | <reponame>amaajemyfren/data<filename>pycon-pl-2013/videos/pycon-pl-2013-payments-processing-in-django.json
{
"description": "Tytu\u0142/Topic: Payments processing in django\nPrelegent/Speaker: <NAME>\n\nTalk will cover many advanced aspects of processing payments in django and will be mainly focused on integration with django-getpaid application. Django-getpaid is carefully designed multi-broker payment processor for Django framework. It was designed to provide following features: * multiple payment brokers support - allows using simultaneously many payments methods at the same time, * multiple payments currency support (getpaid will automatically filter available backends list accordingly to the payment currency), * integration flexibility - makes minimal assumption on 3rd party code - requires only an existence of any single django model representing an order, * proper architecture design - all backends which requires fetching payment confirmation are enforced to use asynchronous celery tasks. Django-getpaid is a production ready solution with support for all main payment processing services in Poland. It is also easily extendable via pluggable backend system to support any other services. Project site: https://github.com/cypreess/django-getpaid This talk will be an extended version of my 2013 DjangoCon talk: \"Apps for advanced plans, pricings, billings and payments\" concerning only payments topic. \n\nhttp://pl.pycon.org/2013/pl/agenda",
"duration": 2821,
"language": "eng",
"recorded": "2013-10-19",
"speakers": [
"<NAME>"
],
"thumbnail_url": "https://i.ytimg.com/vi/fiNAlpU3zkA/hqdefault.jpg",
"title": "Payments processing in django",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=fiNAlpU3zkA"
}
]
}
| 490 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.ai.formrecognizer.implementation.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
/** Authorization to copy a model to the specified target resource and modelId. */
@Fluent
public final class CopyAuthorization {
/*
* ID of the target Azure resource where the model should be copied to.
*/
@JsonProperty(value = "targetResourceId", required = true)
private String targetResourceId;
/*
* Location of the target Azure resource where the model should be copied
* to.
*/
@JsonProperty(value = "targetResourceRegion", required = true)
private String targetResourceRegion;
/*
* Identifier of the target model.
*/
@JsonProperty(value = "targetModelId", required = true)
private String targetModelId;
/*
* URL of the copied model in the target account.
*/
@JsonProperty(value = "targetModelLocation", required = true)
private String targetModelLocation;
/*
* Token used to authorize the request.
*/
@JsonProperty(value = "accessToken", required = true)
private String accessToken;
/*
* Date/time when the access token expires.
*/
@JsonProperty(value = "expirationDateTime", required = true)
private OffsetDateTime expirationDateTime;
/**
* Get the targetResourceId property: ID of the target Azure resource where the model should be copied to.
*
* @return the targetResourceId value.
*/
public String getTargetResourceId() {
return this.targetResourceId;
}
/**
* Set the targetResourceId property: ID of the target Azure resource where the model should be copied to.
*
* @param targetResourceId the targetResourceId value to set.
* @return the CopyAuthorization object itself.
*/
public CopyAuthorization setTargetResourceId(String targetResourceId) {
this.targetResourceId = targetResourceId;
return this;
}
/**
* Get the targetResourceRegion property: Location of the target Azure resource where the model should be copied to.
*
* @return the targetResourceRegion value.
*/
public String getTargetResourceRegion() {
return this.targetResourceRegion;
}
/**
* Set the targetResourceRegion property: Location of the target Azure resource where the model should be copied to.
*
* @param targetResourceRegion the targetResourceRegion value to set.
* @return the CopyAuthorization object itself.
*/
public CopyAuthorization setTargetResourceRegion(String targetResourceRegion) {
this.targetResourceRegion = targetResourceRegion;
return this;
}
/**
* Get the targetModelId property: Identifier of the target model.
*
* @return the targetModelId value.
*/
public String getTargetModelId() {
return this.targetModelId;
}
/**
* Set the targetModelId property: Identifier of the target model.
*
* @param targetModelId the targetModelId value to set.
* @return the CopyAuthorization object itself.
*/
public CopyAuthorization setTargetModelId(String targetModelId) {
this.targetModelId = targetModelId;
return this;
}
/**
* Get the targetModelLocation property: URL of the copied model in the target account.
*
* @return the targetModelLocation value.
*/
public String getTargetModelLocation() {
return this.targetModelLocation;
}
/**
* Set the targetModelLocation property: URL of the copied model in the target account.
*
* @param targetModelLocation the targetModelLocation value to set.
* @return the CopyAuthorization object itself.
*/
public CopyAuthorization setTargetModelLocation(String targetModelLocation) {
this.targetModelLocation = targetModelLocation;
return this;
}
/**
* Get the accessToken property: Token used to authorize the request.
*
* @return the accessToken value.
*/
public String getAccessToken() {
return this.accessToken;
}
/**
* Set the accessToken property: Token used to authorize the request.
*
* @param accessToken the accessToken value to set.
* @return the CopyAuthorization object itself.
*/
public CopyAuthorization setAccessToken(String accessToken) {
this.accessToken = accessToken;
return this;
}
/**
* Get the expirationDateTime property: Date/time when the access token expires.
*
* @return the expirationDateTime value.
*/
public OffsetDateTime getExpirationDateTime() {
return this.expirationDateTime;
}
/**
* Set the expirationDateTime property: Date/time when the access token expires.
*
* @param expirationDateTime the expirationDateTime value to set.
* @return the CopyAuthorization object itself.
*/
public CopyAuthorization setExpirationDateTime(OffsetDateTime expirationDateTime) {
this.expirationDateTime = expirationDateTime;
return this;
}
}
| 1,759 |
1,830 | <gh_stars>1000+
/*
* Copyright 2018-present Open Networking Foundation
* Copyright © 2020 camunda services GmbH (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.cluster.impl;
import io.atomix.cluster.BootstrapService;
import io.atomix.cluster.Node;
import io.atomix.cluster.discovery.ManagedNodeDiscoveryService;
import io.atomix.cluster.discovery.NodeDiscoveryEvent;
import io.atomix.cluster.discovery.NodeDiscoveryEventListener;
import io.atomix.cluster.discovery.NodeDiscoveryProvider;
import io.atomix.cluster.discovery.NodeDiscoveryService;
import io.atomix.utils.event.AbstractListenerManager;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
/** Default node discovery service. */
public class DefaultNodeDiscoveryService
extends AbstractListenerManager<NodeDiscoveryEvent, NodeDiscoveryEventListener>
implements ManagedNodeDiscoveryService {
private final BootstrapService bootstrapService;
private final Node localNode;
private final NodeDiscoveryProvider provider;
private final AtomicBoolean started = new AtomicBoolean();
private final NodeDiscoveryEventListener discoveryEventListener = this::post;
public DefaultNodeDiscoveryService(
final BootstrapService bootstrapService,
final Node localNode,
final NodeDiscoveryProvider provider) {
this.bootstrapService = bootstrapService;
this.localNode = localNode;
this.provider = provider;
}
@Override
public Set<Node> getNodes() {
return provider.getNodes();
}
@Override
public CompletableFuture<NodeDiscoveryService> start() {
if (started.compareAndSet(false, true)) {
provider.addListener(discoveryEventListener);
final Node node =
Node.builder().withId(localNode.id().id()).withAddress(localNode.address()).build();
return provider.join(bootstrapService, node).thenApply(v -> this);
}
return CompletableFuture.completedFuture(this);
}
@Override
public boolean isRunning() {
return started.get();
}
@Override
public CompletableFuture<Void> stop() {
if (started.compareAndSet(true, false)) {
return provider
.leave(localNode)
.thenRun(
() -> {
provider.removeListener(discoveryEventListener);
});
}
return CompletableFuture.completedFuture(null);
}
}
| 917 |
6,180 | /*
* Copyright 2008-2018 NVIDIA Corporation
*
* 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 type_traits.h
* \brief Temporarily define some type traits
* until nvcc can compile tr1::type_traits.
*/
namespace thrust
{
namespace detail
{
/// helper classes [4.3].
template<typename T>
struct add_const
{
typedef T const type;
}; // end add_const
template<typename T>
struct remove_const
{
typedef T type;
}; // end remove_const
template<typename T>
struct remove_const<const T>
{
typedef T type;
}; // end remove_const
template<typename T>
struct remove_volatile
{
typedef T type;
}; // end remove_volatile
template<typename T>
struct remove_volatile<volatile T>
{
typedef T type;
}; // end remove_volatile
template<typename T>
struct remove_cv
{
typedef typename remove_const<typename remove_volatile<T>::type>::type type;
}; // end remove_cv
} // end detail
} // end thrust
| 470 |
852 | /**
* \class L1TEventInfoClient
*
*
* Description: see header file.
*
*
* \author: <NAME> - HEPHY Vienna
*
*
*/
// this class header
#include "DQM/L1TMonitorClient/interface/L1TEventInfoClient.h"
// system include files
#include <cstdio>
#include <sstream>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <memory>
#include <vector>
#include <string>
// user include files
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include <TH2F.h>
#include "TROOT.h"
// constructor
L1TEventInfoClient::L1TEventInfoClient(const edm::ParameterSet& parSet)
: m_verbose(parSet.getUntrackedParameter<bool>("verbose", false)),
m_monitorDir(parSet.getUntrackedParameter<std::string>("monitorDir", "")),
m_runInEventLoop(parSet.getUntrackedParameter<bool>("runInEventLoop", false)),
m_runInEndLumi(parSet.getUntrackedParameter<bool>("runInEndLumi", false)),
m_runInEndRun(parSet.getUntrackedParameter<bool>("runInEndRun", false)),
m_runInEndJob(parSet.getUntrackedParameter<bool>("runInEndJob", false)),
m_l1Systems(parSet.getParameter<std::vector<edm::ParameterSet> >("L1Systems")),
m_l1Objects(parSet.getParameter<std::vector<edm::ParameterSet> >("L1Objects")),
m_disableL1Systems(parSet.getParameter<std::vector<std::string> >("DisableL1Systems")),
m_disableL1Objects(parSet.getParameter<std::vector<std::string> >("DisableL1Objects")),
m_nrL1Systems(0),
m_nrL1Objects(0),
m_totalNrQtSummaryEnabled(0) {
initialize();
}
// destructor
L1TEventInfoClient::~L1TEventInfoClient() {
//empty
}
void L1TEventInfoClient::initialize() {
if (m_verbose) {
std::cout << "\nMonitor directory = " << m_monitorDir << std::endl;
}
// L1 systems
m_nrL1Systems = m_l1Systems.size();
m_systemLabel.reserve(m_nrL1Systems);
m_systemLabelExt.reserve(m_nrL1Systems);
m_systemDisable.reserve(m_nrL1Systems);
// on average five quality test per system - just a best guess
m_systemQualityTestName.reserve(5 * m_nrL1Systems);
m_systemQualityTestHist.reserve(5 * m_nrL1Systems);
m_systemQtSummaryEnabled.reserve(5 * m_nrL1Systems);
int indexSys = 0;
int totalNrQualityTests = 0;
for (std::vector<edm::ParameterSet>::const_iterator itSystem = m_l1Systems.begin(); itSystem != m_l1Systems.end();
++itSystem) {
m_systemLabel.push_back(itSystem->getParameter<std::string>("SystemLabel"));
m_systemLabelExt.push_back(itSystem->getParameter<std::string>("HwValLabel"));
m_systemDisable.push_back(itSystem->getParameter<unsigned int>("SystemDisable"));
// check the additional disable flag from m_disableL1Systems
for (std::vector<std::string>::const_iterator itSys = m_disableL1Systems.begin(); itSys != m_disableL1Systems.end();
++itSys) {
if (*itSys == m_systemLabel[indexSys]) {
m_systemDisable[indexSys] = 1;
}
}
std::vector<edm::ParameterSet> qTests = itSystem->getParameter<std::vector<edm::ParameterSet> >("QualityTests");
size_t qtPerSystem = qTests.size();
std::vector<std::string> qtNames;
qtNames.reserve(qtPerSystem);
std::vector<std::string> qtFullPathHists;
qtFullPathHists.reserve(qtPerSystem);
std::vector<unsigned int> qtSumEnabled;
qtSumEnabled.reserve(qtPerSystem);
for (std::vector<edm::ParameterSet>::const_iterator itQT = qTests.begin(); itQT != qTests.end(); ++itQT) {
totalNrQualityTests++;
qtNames.push_back(itQT->getParameter<std::string>("QualityTestName"));
qtFullPathHists.push_back(itQT->getParameter<std::string>("QualityTestHist"));
unsigned int qtEnabled = itQT->getParameter<unsigned int>("QualityTestSummaryEnabled");
qtSumEnabled.push_back(qtEnabled);
if (qtEnabled) {
m_totalNrQtSummaryEnabled++;
}
}
m_systemQualityTestName.push_back(qtNames);
m_systemQualityTestHist.push_back(qtFullPathHists);
m_systemQtSummaryEnabled.push_back(qtSumEnabled);
indexSys++;
}
// L1 objects
//
m_nrL1Objects = m_l1Objects.size();
m_objectLabel.reserve(m_nrL1Objects);
m_objectDisable.reserve(m_nrL1Objects);
// on average five quality test per object - just a best guess
m_objectQualityTestName.reserve(5 * m_nrL1Objects);
m_objectQualityTestHist.reserve(5 * m_nrL1Objects);
m_objectQtSummaryEnabled.reserve(5 * m_nrL1Objects);
int indexObj = 0;
for (std::vector<edm::ParameterSet>::const_iterator itObject = m_l1Objects.begin(); itObject != m_l1Objects.end();
++itObject) {
m_objectLabel.push_back(itObject->getParameter<std::string>("ObjectLabel"));
m_objectDisable.push_back(itObject->getParameter<unsigned int>("ObjectDisable"));
// check the additional disable flag from m_disableL1Objects
for (std::vector<std::string>::const_iterator itObj = m_disableL1Objects.begin(); itObj != m_disableL1Objects.end();
++itObj) {
if (*itObj == m_objectLabel[indexObj]) {
m_objectDisable[indexObj] = 1;
}
}
std::vector<edm::ParameterSet> qTests = itObject->getParameter<std::vector<edm::ParameterSet> >("QualityTests");
size_t qtPerObject = qTests.size();
std::vector<std::string> qtNames;
qtNames.reserve(qtPerObject);
std::vector<std::string> qtFullPathHists;
qtFullPathHists.reserve(qtPerObject);
std::vector<unsigned int> qtSumEnabled;
qtSumEnabled.reserve(qtPerObject);
for (std::vector<edm::ParameterSet>::const_iterator itQT = qTests.begin(); itQT != qTests.end(); ++itQT) {
totalNrQualityTests++;
qtNames.push_back(itQT->getParameter<std::string>("QualityTestName"));
qtFullPathHists.push_back(itQT->getParameter<std::string>("QualityTestHist"));
unsigned int qtEnabled = itQT->getParameter<unsigned int>("QualityTestSummaryEnabled");
qtSumEnabled.push_back(qtEnabled);
if (qtEnabled) {
m_totalNrQtSummaryEnabled++;
}
}
m_objectQualityTestName.push_back(qtNames);
m_objectQualityTestHist.push_back(qtFullPathHists);
m_objectQtSummaryEnabled.push_back(qtSumEnabled);
indexObj++;
}
m_summaryContent.reserve(m_nrL1Systems + m_nrL1Objects);
m_meReportSummaryContent.reserve(totalNrQualityTests);
}
void L1TEventInfoClient::dqmEndLuminosityBlock(DQMStore::IBooker& ibooker,
DQMStore::IGetter& igetter,
const edm::LuminosityBlock& lumiSeg,
const edm::EventSetup& evSetup) {
if (m_runInEndLumi) {
book(ibooker, igetter);
readQtResults(ibooker, igetter);
if (m_verbose) {
std::cout << "\n L1TEventInfoClient::endLuminosityBlock\n" << std::endl;
dumpContentMonitorElements(ibooker, igetter);
}
}
}
void L1TEventInfoClient::dqmEndJob(DQMStore::IBooker& ibooker, DQMStore::IGetter& igetter) {
book(ibooker, igetter);
readQtResults(ibooker, igetter);
if (m_verbose) {
std::cout << "\n L1TEventInfoClient::endRun\n" << std::endl;
dumpContentMonitorElements(ibooker, igetter);
}
}
void L1TEventInfoClient::dumpContentMonitorElements(DQMStore::IBooker& ibooker, DQMStore::IGetter& igetter) {
std::cout << "\nSummary report " << std::endl;
// summary content
MonitorElement* me = igetter.get(m_meReportSummaryMap->getName());
std::cout << "\nSummary content per system and object as filled in histogram\n " << m_meReportSummaryMap->getName()
<< std::endl;
if (!me) {
std::cout << "\nNo histogram " << m_meReportSummaryMap->getName()
<< "\nNo summary content per system and object as filled in histogram.\n " << std::endl;
return;
}
TH2F* hist = me->getTH2F();
const int nBinsX = hist->GetNbinsX();
const int nBinsY = hist->GetNbinsY();
std::cout << nBinsX << " " << nBinsY;
std::vector<std::vector<int> > meReportSummaryMap(nBinsX, std::vector<int>(nBinsY));
// for (int iBinX = 0; iBinX < nBinsX; iBinX++) {
// for (int iBinY = 0; iBinY < nBinsY; iBinY++) {
// meReportSummaryMap[iBinX][iBinY]
// = static_cast<int>(me->GetBinContent(iBinX + 1, iBinY + 1));
// }
// }
std::cout << "\nL1 systems: " << m_nrL1Systems << " systems included\n"
<< "\n Summary content size: " << (m_summaryContent.size()) << std::endl;
for (unsigned int iSys = 0; iSys < m_nrL1Systems; ++iSys) {
std::cout << std::setw(10) << m_systemLabel[iSys] << std::setw(10) << m_systemLabelExt[iSys] << " \t"
<< m_systemDisable[iSys] << " \t" << std::setw(25) << " m_summaryContent[" << std::setw(2) << iSys
<< "] = " << meReportSummaryMap[0][iSys] << std::endl;
}
std::cout << "\n L1 trigger objects: " << m_nrL1Objects << " objects included\n" << std::endl;
for (unsigned int iMon = m_nrL1Systems; iMon < m_nrL1Systems + m_nrL1Objects; ++iMon) {
std::cout << std::setw(20) << m_objectLabel[iMon - m_nrL1Systems] << " \t" << m_objectDisable[iMon - m_nrL1Systems]
<< " \t" << std::setw(25) << " m_summaryContent[" << std::setw(2) << iMon << "] = \t"
<< m_summaryContent[iMon] << std::endl;
}
std::cout << std::endl;
// quality tests
std::cout << "\nQuality test results as filled in "
<< "\n " << m_monitorDir << "/EventInfo/reportSummaryContents\n"
<< "\n Total number of quality tests: " << (m_meReportSummaryContent.size()) << "\n"
<< std::endl;
for (std::vector<MonitorElement*>::const_iterator itME = m_meReportSummaryContent.begin();
itME != m_meReportSummaryContent.end();
++itME) {
std::cout << std::setw(50) << (*itME)->getName() << " \t" << std::setw(25) << (*itME)->getFloatValue() << std::endl;
}
std::cout << std::endl;
}
void L1TEventInfoClient::book(DQMStore::IBooker& ibooker, DQMStore::IGetter& igetter) {
std::string dirEventInfo = m_monitorDir + "/EventInfo";
ibooker.setCurrentFolder(dirEventInfo);
// ...and book it again
m_meReportSummary = ibooker.bookFloat("reportSummary");
// initialize reportSummary to 1
if (m_meReportSummary) {
m_meReportSummary->Fill(1);
}
// define float histograms for reportSummaryContents (one histogram per quality test),
// initialize them to zero
// initialize also m_summaryContent to dqm::qstatus::DISABLED
ibooker.setCurrentFolder(dirEventInfo + "/reportSummaryContents");
// general counters:
// iAllQTest: all quality tests for all systems and objects
// iAllMon: all monitored systems and objects
int iAllQTest = 0;
int iAllMon = 0;
for (unsigned int iMon = 0; iMon < m_nrL1Systems; ++iMon) {
m_summaryContent.push_back(dqm::qstatus::DISABLED);
const std::vector<std::string>& sysQtName = m_systemQualityTestName[iMon];
for (std::vector<std::string>::const_iterator itQtName = sysQtName.begin(); itQtName != sysQtName.end();
++itQtName) {
const std::string hStr = m_monitorDir + "_L1Sys_" + m_systemLabel[iMon] + "_" + (*itQtName);
m_meReportSummaryContent.push_back(ibooker.bookFloat(hStr));
m_meReportSummaryContent[iAllQTest]->Fill(0.);
iAllQTest++;
}
iAllMon++;
}
for (unsigned int iMon = 0; iMon < m_nrL1Objects; ++iMon) {
m_summaryContent.push_back(dqm::qstatus::DISABLED);
const std::vector<std::string>& objQtName = m_objectQualityTestName[iMon];
for (std::vector<std::string>::const_iterator itQtName = objQtName.begin(); itQtName != objQtName.end();
++itQtName) {
const std::string hStr = m_monitorDir + "_L1Obj_" + m_objectLabel[iMon] + "_" + (*itQtName);
m_meReportSummaryContent.push_back(ibooker.bookFloat(hStr));
m_meReportSummaryContent[iAllQTest]->Fill(0.);
iAllQTest++;
}
iAllMon++;
}
ibooker.setCurrentFolder(dirEventInfo);
// define a histogram with two bins on X and maximum of m_nrL1Systems, m_nrL1Objects on Y
int nBinsY = std::max(m_nrL1Systems, m_nrL1Objects);
m_meReportSummaryMap = ibooker.book2D("reportSummaryMap", "reportSummaryMap", 2, 1, 3, nBinsY, 1, nBinsY + 1);
if (m_monitorDir == "L1TEMU") {
m_meReportSummaryMap->setTitle("L1TEMU: L1 Emulator vs Data Report Summary Map");
} else if (m_monitorDir == "L1T") {
m_meReportSummaryMap->setTitle("L1T: L1 Trigger Data Report Summary Map");
} else {
// do nothing
}
m_meReportSummaryMap->setAxisTitle("", 1);
m_meReportSummaryMap->setAxisTitle("", 2);
m_meReportSummaryMap->setBinLabel(1, "L1 systems", 1);
m_meReportSummaryMap->setBinLabel(2, "L1 objects", 1);
for (int iBin = 0; iBin < nBinsY; ++iBin) {
m_meReportSummaryMap->setBinLabel(iBin + 1, " ", 2);
}
}
void L1TEventInfoClient::readQtResults(DQMStore::IBooker& ibooker, DQMStore::IGetter& igetter) {
// initialize summary content, summary sum and ReportSummaryContent float histograms
// for all L1 systems and L1 objects
for (std::vector<int>::iterator it = m_summaryContent.begin(); it != m_summaryContent.end(); ++it) {
(*it) = dqm::qstatus::DISABLED;
}
m_summarySum = 0.;
for (std::vector<MonitorElement*>::iterator itME = m_meReportSummaryContent.begin();
itME != m_meReportSummaryContent.end();
++itME) {
(*itME)->Fill(0.);
}
// general counters:
// iAllQTest: all quality tests for all systems and objects
// iAllMon: all monitored systems and objects
int iAllQTest = 0;
int iAllMon = 0;
// quality tests for all L1 systems
for (unsigned int iSys = 0; iSys < m_nrL1Systems; ++iSys) {
// get the reports for each quality test
const std::vector<std::string>& sysQtName = m_systemQualityTestName[iSys];
const std::vector<std::string>& sysQtHist = m_systemQualityTestHist[iSys];
const std::vector<unsigned int>& sysQtSummaryEnabled = m_systemQtSummaryEnabled[iSys];
// pro system counter for quality tests
int iSysQTest = 0;
for (std::vector<std::string>::const_iterator itQtName = sysQtName.begin(); itQtName != sysQtName.end();
++itQtName) {
// get results, status and message
MonitorElement* qHist = igetter.get(sysQtHist[iSysQTest]);
if (qHist) {
const std::vector<QReport*> qtVec = qHist->getQReports();
if (m_verbose) {
std::cout << "\nNumber of quality tests "
<< " for histogram " << sysQtHist[iSysQTest] << ": " << qtVec.size() << "\n"
<< std::endl;
}
const QReport* sysQReport = qHist->getQReport(*itQtName);
if (sysQReport) {
const float sysQtResult = sysQReport->getQTresult();
const int sysQtStatus = sysQReport->getStatus();
const std::string& sysQtMessage = sysQReport->getMessage();
if (m_verbose) {
std::cout << "\n"
<< (*itQtName) << " quality test:"
<< "\n result: " << sysQtResult << "\n status: " << sysQtStatus
<< "\n message: " << sysQtMessage << "\n"
<< "\nFilling m_meReportSummaryContent[" << iAllQTest << "] with value " << sysQtResult << "\n"
<< std::endl;
}
m_meReportSummaryContent[iAllQTest]->Fill(sysQtResult);
// for the summary map, keep the highest status value ("ERROR") of all tests
// which are considered for the summary plot
if (sysQtSummaryEnabled[iSysQTest]) {
if (sysQtStatus > m_summaryContent[iAllMon]) {
m_summaryContent[iAllMon] = sysQtStatus;
}
m_summarySum += sysQtResult;
}
} else {
// for the summary map, if the test was not found but it is assumed to be
// considered for the summary plot, set it to dqm::qstatus::INVALID
int sysQtStatus = dqm::qstatus::INVALID;
if (sysQtSummaryEnabled[iSysQTest]) {
if (sysQtStatus > m_summaryContent[iAllMon]) {
m_summaryContent[iAllMon] = sysQtStatus;
}
}
m_meReportSummaryContent[iAllQTest]->Fill(0.);
if (m_verbose) {
std::cout << "\n" << (*itQtName) << " quality test not found\n" << std::endl;
}
}
} else {
// for the summary map, if the histogram was not found but it is assumed
// to have a test be considered for the summary plot, set it to dqm::qstatus::INVALID
int sysQtStatus = dqm::qstatus::INVALID;
if (sysQtSummaryEnabled[iSysQTest]) {
if (sysQtStatus > m_summaryContent[iAllMon]) {
m_summaryContent[iAllMon] = sysQtStatus;
}
}
m_meReportSummaryContent[iAllQTest]->Fill(0.);
if (m_verbose) {
std::cout << "\nHistogram " << sysQtHist[iSysQTest] << " not found\n" << std::endl;
}
}
// increase counters for quality tests
iSysQTest++;
iAllQTest++;
}
iAllMon++;
}
// quality tests for all L1 objects
for (unsigned int iObj = 0; iObj < m_nrL1Objects; ++iObj) {
// get the reports for each quality test
const std::vector<std::string>& objQtName = m_objectQualityTestName[iObj];
const std::vector<std::string>& objQtHist = m_objectQualityTestHist[iObj];
const std::vector<unsigned int>& objQtSummaryEnabled = m_objectQtSummaryEnabled[iObj];
// pro object counter for quality tests
int iObjQTest = 0;
for (std::vector<std::string>::const_iterator itQtName = objQtName.begin(); itQtName != objQtName.end();
++itQtName) {
// get results, status and message
MonitorElement* qHist = igetter.get(objQtHist[iObjQTest]);
if (qHist) {
const std::vector<QReport*> qtVec = qHist->getQReports();
if (m_verbose) {
std::cout << "\nNumber of quality tests "
<< " for histogram " << objQtHist[iObjQTest] << ": " << qtVec.size() << "\n"
<< std::endl;
}
const QReport* objQReport = qHist->getQReport(*itQtName);
if (objQReport) {
const float objQtResult = objQReport->getQTresult();
const int objQtStatus = objQReport->getStatus();
const std::string& objQtMessage = objQReport->getMessage();
if (m_verbose) {
std::cout << "\n"
<< (*itQtName) << " quality test:"
<< "\n result: " << objQtResult << "\n status: " << objQtStatus
<< "\n message: " << objQtMessage << "\n"
<< "\nFilling m_meReportSummaryContent[" << iAllQTest << "] with value " << objQtResult << "\n"
<< std::endl;
}
m_meReportSummaryContent[iAllQTest]->Fill(objQtResult);
// for the summary map, keep the highest status value ("ERROR") of all tests
// which are considered for the summary plot
if (objQtSummaryEnabled[iObjQTest]) {
if (objQtStatus > m_summaryContent[iAllMon]) {
m_summaryContent[iAllMon] = objQtStatus;
}
m_summarySum += objQtResult;
}
} else {
// for the summary map, if the test was not found but it is assumed to be
// considered for the summary plot, set it to dqm::qstatus::INVALID
int objQtStatus = dqm::qstatus::INVALID;
if (objQtSummaryEnabled[iObjQTest]) {
if (objQtStatus > m_summaryContent[iAllMon]) {
m_summaryContent[iAllMon] = objQtStatus;
}
}
m_meReportSummaryContent[iAllQTest]->Fill(0.);
if (m_verbose) {
std::cout << "\n" << (*itQtName) << " quality test not found\n" << std::endl;
}
}
} else {
// for the summary map, if the histogram was not found but it is assumed
// to have a test be considered for the summary plot, set it to dqm::qstatus::INVALID
int objQtStatus = dqm::qstatus::INVALID;
if (objQtSummaryEnabled[iObjQTest]) {
if (objQtStatus > m_summaryContent[iAllMon]) {
m_summaryContent[iAllMon] = objQtStatus;
}
}
m_meReportSummaryContent[iAllQTest]->Fill(0.);
if (m_verbose) {
std::cout << "\nHistogram " << objQtHist[iObjQTest] << " not found\n" << std::endl;
}
}
// increase counters for quality tests
iObjQTest++;
iAllQTest++;
}
iAllMon++;
}
// reportSummary value
m_reportSummary = m_summarySum / float(m_totalNrQtSummaryEnabled);
if (m_meReportSummary) {
m_meReportSummary->Fill(m_reportSummary);
}
// fill the ReportSummaryMap for L1 systems (bin 1 on X)
for (unsigned int iSys = 0; iSys < m_nrL1Systems; ++iSys) {
double summCont = static_cast<double>(m_summaryContent[iSys]);
m_meReportSummaryMap->setBinContent(1, iSys + 1, summCont);
}
// fill the ReportSummaryMap for L1 objects (bin 2 on X)
for (unsigned int iMon = m_nrL1Systems; iMon < m_nrL1Systems + m_nrL1Objects; ++iMon) {
double summCont = static_cast<double>(m_summaryContent[iMon]);
m_meReportSummaryMap->setBinContent(2, iMon - m_nrL1Systems + 1, summCont);
}
}
| 9,180 |
303 | /* Copyright (C) 2005-2011 <NAME> */
package com.lightcrafts.ui.action;
import javax.swing.*;
import java.awt.event.ActionEvent;
public abstract class ToggleAction extends AbstractAction {
// Property keys
public final static String TOGGLE_STATE = "ToggleState";
public final static String PRESSED_ICON = "PressedIcon";
private String onName;
private Icon onIcon;
private String onDescription;
private String offName;
private Icon offIcon;
private String offDescription;
private boolean state;
public ToggleAction() {
putValue(TOGGLE_STATE, Boolean.FALSE);
}
public ToggleAction(String onName, String offName) {
super(offName);
this.onName = onName;
this.offName = offName;
putValue(TOGGLE_STATE, Boolean.FALSE);
}
public ToggleAction(
String onName, Icon onIcon, String offName, Icon offIcon
) {
super(offName, offIcon);
this.onName = onName;
this.onIcon = onIcon;
this.offName = offName;
this.offIcon = offIcon;
putValue(TOGGLE_STATE, Boolean.FALSE);
}
protected abstract void onActionPerformed(ActionEvent event);
protected abstract void offActionPerformed(ActionEvent event);
public void setState(boolean state) {
if (this.state != state) {
actionPerformed(null);
}
}
public boolean getState() {
return state;
}
public void setName(String name, boolean state) {
if (state) {
onName = name;
}
else {
offName = name;
}
actionPerformed(null);
}
public String getName(boolean state) {
return state ? onName : offName;
}
public void setIcon(Icon icon, boolean state) {
if (state) {
onIcon = icon;
}
else {
offIcon = icon;
}
actionPerformed(null);
}
public void setPressedIcon(Icon icon) {
putValue(PRESSED_ICON, icon);
}
public void setDescription(String description, boolean state) {
if (state) {
onDescription = description;
}
else {
offDescription = description;
}
actionPerformed(null);
}
public void actionPerformed(ActionEvent event) {
state = ! state;
String name = state ? onName : offName;
putValue(NAME, name);
Icon icon = state ? onIcon : offIcon;
putValue(SMALL_ICON, icon);
String description = state ? onDescription : offDescription;
putValue(SHORT_DESCRIPTION, description);
// If it's a real event (not a programmatic call to setState()),
// then invoke the ActionListeners:
if (event != null) {
if (state) {
onActionPerformed(event);
}
else {
offActionPerformed(event);
}
}
putValue(TOGGLE_STATE, Boolean.valueOf(state));
}
}
| 1,308 |
310 | {
"name": "Monosnap",
"description": "A screenshot and annotation tool.",
"url": "https://monosnap.com/welcome"
}
| 45 |
347 | package org.ovirt.engine.ui.webadmin.section.main.view.tab.quota;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.presenter.ActionPanelPresenterWidget;
import org.ovirt.engine.ui.common.presenter.QuotaBreadCrumbsPresenterWidget;
import org.ovirt.engine.ui.common.widget.tab.AbstractTabPanel;
import org.ovirt.engine.ui.common.widget.tab.DetailTabLayout;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.QuotaActionPanelPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.quota.QuotaSubTabPanelPresenter;
import org.ovirt.engine.ui.webadmin.section.main.view.AbstractSubTabPanelView;
import org.ovirt.engine.ui.webadmin.widget.tab.SimpleTabPanel;
import com.google.gwt.core.client.GWT;
import com.google.inject.Inject;
public class QuotaSubTabPanelView extends AbstractSubTabPanelView implements QuotaSubTabPanelPresenter.ViewDef {
interface ViewIdHandler extends ElementIdHandler<QuotaSubTabPanelView> {
ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
}
private final QuotaActionPanelPresenterWidget<Void> actionPanel;
private final SimpleTabPanel tabPanel;
@Inject
public QuotaSubTabPanelView(QuotaBreadCrumbsPresenterWidget breadCrumbs,
QuotaActionPanelPresenterWidget<Void> actionPanel, DetailTabLayout detailTabLayout) {
this.actionPanel = actionPanel;
this.tabPanel = new SimpleTabPanel(breadCrumbs, actionPanel, detailTabLayout);
initWidget(getTabPanel());
actionPanel.removeButton(actionPanel.getNewButtonDefinition());
}
@Override
protected void generateIds() {
ViewIdHandler.idHandler.generateAndSetIds(this);
}
@Override
protected Object getContentSlot() {
return QuotaSubTabPanelPresenter.TYPE_SetTabContent;
}
@Override
protected AbstractTabPanel getTabPanel() {
return tabPanel;
}
@Override
public ActionPanelPresenterWidget<?, ?, ?> getActionPanelPresenterWidget() {
return actionPanel;
}
}
| 724 |
839 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.rs.security.jose.jwe;
import java.util.logging.Logger;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.rs.security.jose.jwa.KeyAlgorithm;
public class DirectKeyEncryptionAlgorithm implements KeyEncryptionProvider {
private static final Logger LOG = LogUtils.getL7dLogger(DirectKeyEncryptionAlgorithm.class);
public byte[] getEncryptedContentEncryptionKey(JweHeaders headers, byte[] theCek) {
checkKeyEncryptionAlgorithm(headers);
return new byte[0];
}
protected void checkKeyEncryptionAlgorithm(JweHeaders headers) {
KeyAlgorithm keyAlgo = headers.getKeyEncryptionAlgorithm();
if (keyAlgo != null && !KeyAlgorithm.DIRECT.equals(keyAlgo)) {
LOG.warning("Key encryption algorithm header is set");
throw new JweException(JweException.Error.INVALID_KEY_ALGORITHM);
}
}
@Override
public KeyAlgorithm getAlgorithm() {
return KeyAlgorithm.DIRECT;
}
}
| 566 |
1,444 |
package mage.cards.k;
import java.util.UUID;
import mage.MageInt;
import mage.ObjectColor;
import mage.abilities.keyword.ExaltedAbility;
import mage.abilities.keyword.ProtectionAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
/**
*
* @author jeffwadsworth
*/
public final class KnightOfGlory extends CardImpl {
public KnightOfGlory(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.KNIGHT);
this.power = new MageInt(2);
this.toughness = new MageInt(1);
// Protection from black
this.addAbility(ProtectionAbility.from(ObjectColor.BLACK));
// Exalted
this.addAbility(new ExaltedAbility());
}
private KnightOfGlory(final KnightOfGlory card) {
super(card);
}
@Override
public KnightOfGlory copy() {
return new KnightOfGlory(this);
}
}
| 425 |
1,165 | package com.tmobile.pacbot.azure.inventory.collector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.Azure;
import com.microsoft.azure.management.storage.PublicEndpoints;
import com.microsoft.azure.management.storage.StorageAccount;
import com.tmobile.pacbot.azure.inventory.auth.AzureCredentialProvider;
import com.tmobile.pacbot.azure.inventory.vo.StorageAccountVH;
import com.tmobile.pacbot.azure.inventory.vo.SubscriptionVH;
@Component
public class StorageAccountInventoryCollector {
@Autowired
AzureCredentialProvider azureCredentialProvider;
private static Logger log = LoggerFactory.getLogger(StorageAccountInventoryCollector.class);
public List<StorageAccountVH> fetchStorageAccountDetails(SubscriptionVH subscription,
Map<String, Map<String, String>> tagMap) {
List<StorageAccountVH> storageAccountList = new ArrayList<StorageAccountVH>();
Azure azure = azureCredentialProvider.getClient(subscription.getTenant(),subscription.getSubscriptionId());
PagedList<StorageAccount> storageAccounts = azure.storageAccounts().list();
for (StorageAccount storageAccount : storageAccounts) {
StorageAccountVH storageAccountVH = new StorageAccountVH();
storageAccountVH.setResourceGroupName(storageAccount.resourceGroupName());
storageAccountVH.setKind(storageAccount.kind().toString());
storageAccountVH.setCanAccessFromAzureServices(storageAccount.canAccessFromAzureServices());
storageAccountVH.setIpAddressesWithAccess(storageAccount.ipAddressesWithAccess());
storageAccountVH.setId(storageAccount.id());
storageAccountVH.setIpAddressRangesWithAccess(storageAccount.ipAddressRangesWithAccess());
storageAccountVH.setAccessAllowedFromAllNetworks(storageAccount.isAccessAllowedFromAllNetworks());
storageAccountVH.setAzureFilesAadIntegrationEnabled(storageAccount.isAzureFilesAadIntegrationEnabled());
storageAccountVH.setHnsEnabled(storageAccount.isHnsEnabled());
storageAccountVH.setName(storageAccount.name());
storageAccountVH.setRegionName(storageAccount.regionName());
storageAccountVH.setNetworkSubnetsWithAccess(storageAccount.networkSubnetsWithAccess());
storageAccountVH.setSystemAssignedManagedServiceIdentityPrincipalId(
storageAccount.systemAssignedManagedServiceIdentityPrincipalId());
storageAccountVH.setSystemAssignedManagedServiceIdentityTenantId(
storageAccount.systemAssignedManagedServiceIdentityTenantId());
storageAccountVH.setTags(Util.tagsList(tagMap, storageAccount.resourceGroupName(), storageAccount.tags()));
storageAccountVH.setSubscription(subscription.getSubscriptionId());
storageAccountVH.setSubscriptionName(subscription.getSubscriptionName());
endPointDetails(storageAccount.endPoints(), storageAccountVH);
storageAccountList.add(storageAccountVH);
}
log.info("Target Type : {} Total: {} ","Storage Account",storageAccountList.size());
return storageAccountList;
}
private void endPointDetails(PublicEndpoints endpoints, StorageAccountVH storageAccountVH) {
Map<String, String> endpointsMap = new HashMap<String, String>();
endpointsMap.put("blobEndPoint", endpoints.primary().blob());
endpointsMap.put("fileEndPoint", endpoints.primary().file());
endpointsMap.put("queueEndPoint", endpoints.primary().queue());
endpointsMap.put("tableEndPoint", endpoints.primary().table());
endpointsMap.put("dfsEndPoint", endpoints.primary().dfs());
endpointsMap.put("webEndPoint", endpoints.primary().web());
storageAccountVH.setEndpointsMap(endpointsMap);
}
}
| 1,171 |
743 | import configparser
import os
import traceback
from pathlib import Path
from utils.utils import get_project_root
class Config(object):
def __init__(self, auto_load: bool = True, create_env: bool = True):
self.config = configparser.ConfigParser(allow_no_value=True, interpolation=configparser.ExtendedInterpolation())
self.default_config = os.path.join(get_project_root(), "config", "default.ini")
self.file = os.path.join(get_project_root(), "config", "config.ini")
if not os.path.isfile(self.file):
self.write_default()
if auto_load:
self.load_config()
if create_env:
self.rebase()
def load_config(self, filename=None):
if filename:
self.file = Path(filename).absolute()
try:
self.config.read(self.file)
except FileNotFoundError:
print("The file specified does not exists")
self.write_default()
except configparser.ParsingError:
print("Error encountered while parsing, check configuration file syntax")
except Exception as e:
print("Unhandled exception, contact support")
print(f"Exception : {e}")
def save_config(self):
with open(self.file, 'w') as configfile:
self.config.write(configfile)
def rebase(self):
no_rebase = ["", "csharp", "cpp", "powershell", "nodebug"]
for key, directory in self.config["DIRECTORIES"].items():
if directory and directory not in no_rebase:
p = Path(os.path.join(get_project_root(), directory))
p.mkdir(parents=True, exist_ok=True)
return self
def get_config(self):
return self.config
def get_section(self, s):
return self.config[s]
def get_boolean(self, section, key):
try:
debug = int(self.get(section, key))
return debug == 1
except KeyError:
return False
except ValueError:
return False
except TypeError:
return False
except Exception as e:
raise e
def get_int(self, section, key):
try:
return int(self.get(section, key))
except KeyError:
return False
except ValueError:
return False
except TypeError:
return False
except Exception as e:
raise e
def get_path(self, section, key):
try:
_path = Path(os.path.join(get_project_root(), self.get(section, key))).absolute()
return _path
except KeyError:
return None
except ValueError:
return None
except TypeError:
return None
except Exception as e:
raise e
def get_list(self, section, key):
try:
return [x.strip().encode() for x in self.get(section, key).split(",")]
except KeyError:
return None
except ValueError:
return None
except TypeError:
return None
except Exception as e:
raise e
def get(self, s, v):
try:
return self.config[s][v]
except KeyError:
return None
def set(self, s, v, new_value):
self.config[s][v] = new_value
def test(self):
print(self.get("PLACEHOLDERS", "SHELLCODE"))
def write_default(self):
content = open(self.default_config).read()
with open(self.file, "w") as default:
default.write(content)
if __name__ == "__main__":
c = Config()
c.test()
| 1,681 |
604 | <filename>scraper/src/test/java/com/serphacker/serposcope/scraper/http/ScrapClientSSLIT.java
/*
* Serposcope - SEO rank checker https://serposcope.serphacker.com/
*
* Copyright (c) 2016 SERP Hacker
* @author <NAME> <<EMAIL>>
* @license https://opensource.org/licenses/MIT MIT License
*/
package com.serphacker.serposcope.scraper.http;
import com.serphacker.serposcope.scraper.DeepIntegrationTest;
import com.serphacker.serposcope.scraper.http.proxy.HttpProxy;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author admin
*/
public class ScrapClientSSLIT extends DeepIntegrationTest {
public ScrapClientSSLIT() {
}
@Test
public void testSslWithInvalidHostnameFail() throws Exception {
ScrapClient client = new ScrapClient();
client.get("https://192.168.3.11");
assertTrue(client.getException() instanceof SSLPeerUnverifiedException);
}
@Test
public void testSslWithInvalidHostname() throws Exception {
ScrapClient client = new ScrapClient();
client.setInsecureSSL(true);
assertEquals(200, client.get("https://192.168.3.11"));
}
// @Test(expected = SSLHandshakeException.class)
// public void testSslWithSelfSignedFail() throws Exception {
// ScrapClient client = new ScrapClient(false);
// CloseableHttpResponse response = client.execute(new HttpGet("https://selfsigned.indahax.com"));
// }
// @Test
// public void testSslWithSelfSigned() throws Exception {
// ScrapClient client = new ScrapClient(true);
// CloseableHttpResponse response = client.execute(new HttpGet("https://selfsigned.indahax.com"));
// assertEquals(200, response.getStatusLine().getStatusCode());
// }
@Test
public void testMitmSslProxyWithSelfSignedCertificateFail() {
ScrapClient client = new ScrapClient();
client.setProxy(new HttpProxy("127.0.0.1", 8080));
client.get("https://httpbin.org");
assertTrue(client.getException() instanceof SSLHandshakeException);
}
@Test
public void testMitmSslProxyWithSelfSignedCertificateSuccess() {
ScrapClient client = new ScrapClient();
client.setInsecureSSL(true);
client.setProxy(new HttpProxy("127.0.0.1", 8080));
assertEquals(200, client.get("https://httpbin.org"));
}
@Test
public void testInsecureSwitching() throws Exception {
ScrapClient client = new ScrapClient();
client.setInsecureSSL(true);
client.setProxy(new HttpProxy("127.0.0.1", 8080));
assertEquals(200, client.get("https://httpbin.org"));
boolean occured=false;
client.setInsecureSSL(false);
assertEquals(-1, client.get("https://httpbin.org"));
}
}
| 1,176 |
852 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
l1tdeStage2CaloLayer2 = DQMEDAnalyzer('L1TdeStage2CaloLayer2',
calol2JetCollectionData = cms.InputTag("caloStage2Digis", "Jet"),
calol2JetCollectionEmul = cms.InputTag("valCaloStage2Layer2Digis"),
calol2EGammaCollectionData = cms.InputTag("caloStage2Digis", "EGamma"),
calol2EGammaCollectionEmul = cms.InputTag("valCaloStage2Layer2Digis"),
calol2TauCollectionData = cms.InputTag("caloStage2Digis", "Tau"),
calol2TauCollectionEmul = cms.InputTag("valCaloStage2Layer2Digis"),
calol2EtSumCollectionData = cms.InputTag("caloStage2Digis", "EtSum"),
calol2EtSumCollectionEmul = cms.InputTag("valCaloStage2Layer2Digis"),
monitorDir = cms.untracked.string("L1TEMU/L1TStage2CaloLayer2/L1TdeStage2CaloLayer2"),
enable2DComp = cms.untracked.bool(True) # When true eta-phi comparison plots are also produced
)
| 375 |
781 | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#import "Brush.h"
#import "IHaveProperties.h"
@interface Shape : UIView <IHaveProperties>
@property Brush* stroke;
@property double strokeThickness;
@property NSString* strokeStartLineCap;
@property NSString* strokeEndLineCap;
@property Brush* fill;
@property NSString* strokeLineJoin;
@property double strokeMiterLimit;
@property NSString* stretch;
@end
| 157 |
3,262 | <gh_stars>1000+
#include "mesh_importer.h"
#include "../../mesh/wavefront_reader.h"
using namespace Halley;
void MeshImporter::import(const ImportingAsset& asset, IAssetCollector& collector)
{
for (auto& f: asset.inputFiles) {
if (f.name.getExtension() == ".obj") {
auto reader = std::make_unique<WavefrontReader>();
std::unique_ptr<Mesh> result = reader->parse(f.data);
collector.output(asset.assetId, AssetType::Mesh, Serializer::toBytes(*result));
}
}
}
| 178 |
895 | <reponame>JKot-Coder/slang<gh_stars>100-1000
#include "slang-signal.h"
#include "slang-exception.h"
#include "stdio.h"
namespace Slang
{
static const char* _getSignalTypeAsText(SignalType type)
{
switch (type)
{
case SignalType::AssertFailure: return "assert failure";
case SignalType::Unimplemented: return "unimplemented";
case SignalType::Unreachable: return "hit unreachable code";
case SignalType::Unexpected: return "unexpected";
case SignalType::InvalidOperation: return "invalid operation";
case SignalType::AbortCompilation: return "abort compilation";
default: return "unhandled";
}
}
String _getMessage(SignalType type, char const* message)
{
StringBuilder buf;
const char* const typeText = _getSignalTypeAsText(type);
buf << typeText;
if (message)
{
buf << ": " << message;
}
return buf.ProduceString();
}
// One point of having as a single function is a choke point both for handling (allowing different
// handling scenarios) as well as a choke point to set a breakpoint to catch 'signal' types
SLANG_RETURN_NEVER void handleSignal(SignalType type, char const* message)
{
StringBuilder buf;
const char*const typeText = _getSignalTypeAsText(type);
buf << typeText << ": " << message;
// Can be useful to enable during debug when problem is on CI
if (false)
{
printf("%s\n", _getMessage(type, message).getBuffer());
}
#if SLANG_HAS_EXCEPTIONS
switch (type)
{
case SignalType::InvalidOperation: throw InvalidOperationException(_getMessage(type, message));
case SignalType::AbortCompilation: throw AbortCompilationException();
default: throw InternalError(_getMessage(type, message));
}
#else
// Attempt to drop out into the debugger. If a debugger isn't attached this will likely crash - which is probably the best
// we can do.
SLANG_BREAKPOINT(0);
// 'panic'. Exit with an error code as we can't throw or catch.
exit(-1);
#endif
}
}
| 794 |
507 | <reponame>mjuenema/python-terrascript<gh_stars>100-1000
# terrascript/xenorchestra/r.py
# Automatically generated by tools/makecode.py ()
import warnings
warnings.warn(
"using the 'legacy layout' is deprecated", DeprecationWarning, stacklevel=2
)
import terrascript
class xenorchestra_acl(terrascript.Resource):
pass
class xenorchestra_cloud_config(terrascript.Resource):
pass
class xenorchestra_resource_set(terrascript.Resource):
pass
class xenorchestra_vm(terrascript.Resource):
pass
| 180 |
5,169 | {
"name": "PANetWorking",
"version": "0.1.1",
"summary": "全世界网络框架封装",
"description": "TODO: Add long description of the pod here.",
"homepage": "https://gitee.com/sdgfhsggsdfgsfds/PANetWorking.git",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"liulujie": "<EMAIL>"
},
"source": {
"git": "https://gitee.com/sdgfhsggsdfgsfds/PANetWorking.git",
"tag": "0.1.1"
},
"platforms": {
"ios": "11.0"
},
"source_files": "PANetWorking/Classes/**/*",
"vendored_libraries": "PANetWorking/Classes/pod-pasecurity/*.{a}",
"dependencies": {
"AFNetworking": [
"~> 4.0.1"
]
}
}
| 328 |
429 | /* vim: tabstop=4 shiftwidth=4 noexpandtab
* This file is part of ToaruOS and is released under the terms
* of the NCSA / University of Illinois License - see LICENSE.md
* Copyright (C) 2018 <NAME>
*
* Configuration File Reader
*
* Reads an implementation of the INI "standard". Note that INI
* isn't actually a standard. We support the following:
* - ; comments
* - foo=bar keyword assignment
* - [sections]
*/
#pragma once
#include <_cheader.h>
#include <toaru/hashmap.h>
_Begin_C_Header
/**
* A configuration file is represented as a hashmap of sections,
* which are themselves hashmaps. You may modify these hashmaps
* to change key values, or add new sections.
*/
typedef struct {
hashmap_t * sections;
} confreader_t;
/**
* confreader_load
*
* Open a configuration file and read its contents.
* Returns NULL if the requested file failed to open.
*/
extern confreader_t * confreader_load(const char * file);
/**
* confreader_get
*
* Retrieve a string value from the config file.
* An empty string for `section` represents the default section.
* If the value is not found, NULL is returned.
*/
extern char * confreader_get(confreader_t * ctx, char * section, char * value);
/**
* confreader_getd
*
* Retrieve a string value from the config file, falling back
* to a default value if the requested key is not found.
*/
extern char * confreader_getd(confreader_t * ctx, char * section, char * value, char * def);
/**
* confreader_int
*
* Retrieve an integer value from the config file.
*
* This is a convenience wrapper that calls atoi().
* If the value is not found, 0 is returned.
*/
extern int confreader_int(confreader_t * ctx, char * section, char * value);
/**
* confreader_intd
*
* Retrieve an integer value from the config file, falling back
* to a default if the requested key is not found.
*/
extern int confreader_intd(confreader_t * ctx, char * section, char * value, int def);
/**
* confreader_free
*
* Free the memory associated with a config file.
*/
extern void confreader_free(confreader_t * conf);
/**
* confreader_write
*
* Write a config file back out to a file.
*/
extern int confreader_write(confreader_t * config, const char * file);
/**
* confreader_create_empty
*
* Create an empty configuration file to be modified directly
* through hashmap values.
*/
extern confreader_t * confreader_create_empty(void);
_End_C_Header
| 720 |
556 | <filename>ios/Classes/MACustomCalloutViewFactory.h
//////////////////////////////////////////////////////////
// GENERATED BY FLUTTIFY. DO NOT EDIT IT.
//////////////////////////////////////////////////////////
#import <Foundation/Foundation.h>
#import <Flutter/Flutter.h>
#import <MAMapKit/MAMapKit.h>
@interface MACustomCalloutViewFactory : NSObject <FlutterPlatformViewFactory>
- (instancetype)initWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar;
@property(nonatomic) NSObject<FlutterPluginRegistrar>* registrar;
@end
@interface MACustomCalloutViewPlatformView : NSObject <MATraceDelegate, MAMultiPointOverlayRendererDelegate, MAMapViewDelegate, FlutterPlatformView>
- (instancetype)initWithViewId:(int64_t)viewId frame:(CGRect)frame registrar:(NSObject <FlutterPluginRegistrar> *)registrar arguments:(id _Nullable)args;
@property(nonatomic) NSObject<FlutterPluginRegistrar>* registrar;
@end
| 286 |
348 | {"nom":"Moussac","circ":"3ème circonscription","dpt":"Vienne","inscrits":387,"abs":187,"votants":200,"blancs":15,"nuls":8,"exp":177,"res":[{"nuance":"REM","nom":"<NAME>","voix":123},{"nuance":"FN","nom":"<NAME>","voix":54}]} | 88 |
1,747 | <reponame>myott/helios<gh_stars>1000+
/*-
* -\-\-
* Helios Services
* --
* Copyright (C) 2016 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.helios.agent;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.spotify.helios.agent.Agent.EMPTY_EXECUTIONS;
import static com.spotify.helios.servicescommon.ServiceRegistrars.createServiceRegistrar;
import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.digest;
import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.heliosAclProvider;
import static java.lang.management.ManagementFactory.getOperatingSystemMXBean;
import static java.lang.management.ManagementFactory.getRuntimeMXBean;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Strings;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import com.google.common.util.concurrent.AbstractIdleService;
import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerCertificates;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.auth.gcr.ContainerRegistryAuthSupplier;
import com.spotify.docker.client.exceptions.DockerCertificateException;
import com.spotify.helios.common.HeliosRuntimeException;
import com.spotify.helios.common.SystemClock;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.descriptors.TaskStatusEvent;
import com.spotify.helios.master.metrics.HealthCheckGauge;
import com.spotify.helios.master.metrics.TotalHealthCheckGauge;
import com.spotify.helios.serviceregistration.ServiceRegistrar;
import com.spotify.helios.servicescommon.EventSender;
import com.spotify.helios.servicescommon.EventSenderFactory;
import com.spotify.helios.servicescommon.FastForwardConfig;
import com.spotify.helios.servicescommon.ManagedStatsdReporter;
import com.spotify.helios.servicescommon.PersistentAtomicReference;
import com.spotify.helios.servicescommon.ReactorFactory;
import com.spotify.helios.servicescommon.ServiceUtil;
import com.spotify.helios.servicescommon.ZooKeeperRegistrarService;
import com.spotify.helios.servicescommon.coordination.CuratorClientFactoryImpl;
import com.spotify.helios.servicescommon.coordination.DefaultZooKeeperClient;
import com.spotify.helios.servicescommon.coordination.ZooKeeperClient;
import com.spotify.helios.servicescommon.coordination.ZooKeeperClientProvider;
import com.spotify.helios.servicescommon.coordination.ZooKeeperHealthChecker;
import com.spotify.helios.servicescommon.coordination.ZooKeeperModelReporter;
import com.spotify.helios.servicescommon.coordination.ZooKeeperNodeUpdaterFactory;
import com.spotify.helios.servicescommon.statistics.DockerVersionSupplier;
import com.spotify.helios.servicescommon.statistics.FastForwardReporter;
import com.spotify.helios.servicescommon.statistics.Metrics;
import com.spotify.helios.servicescommon.statistics.MetricsImpl;
import com.spotify.helios.servicescommon.statistics.NoopMetrics;
import com.sun.management.OperatingSystemMXBean;
import io.dropwizard.configuration.ConfigurationException;
import io.dropwizard.lifecycle.Managed;
import io.dropwizard.setup.Environment;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.AuthInfo;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Helios agent.
*/
public class AgentService extends AbstractIdleService implements Managed {
private static final Logger log = LoggerFactory.getLogger(AgentService.class);
private static final String TASK_HISTORY_FILENAME = "task-history.json";
private static final TypeReference<Map<JobId, Execution>> JOBID_EXECUTIONS_MAP =
new TypeReference<Map<JobId, Execution>>() {
};
private final Agent agent;
private final Server server;
private final ZooKeeperClient zooKeeperClient;
private final HostInfoReporter hostInfoReporter;
private final AgentInfoReporter agentInfoReporter;
private final EnvironmentVariableReporter environmentVariableReporter;
private final LabelReporter labelReporter;
private final FileChannel stateLockFile;
private final FileLock stateLock;
private final ZooKeeperAgentModel model;
private final Metrics metrics;
private final ServiceRegistrar serviceRegistrar;
private ZooKeeperRegistrarService zkRegistrar;
/**
* Create a new agent instance.
*
* @param config The service configuration.
* @param environment The DropWizard environment.
*
* @throws ConfigurationException If an error occurs with the DropWizard configuration.
* @throws InterruptedException If the thread is interrupted.
* @throws IOException IOException
*/
public AgentService(final AgentConfig config, final Environment environment)
throws ConfigurationException, InterruptedException, IOException {
// Create state directory, if necessary
final Path stateDirectory = config.getStateDirectory().toAbsolutePath().normalize();
if (!Files.exists(stateDirectory)) {
try {
Files.createDirectories(stateDirectory);
} catch (IOException e) {
log.error("Failed to create state directory: {}", stateDirectory, e);
throw new RuntimeException(e);
}
}
// Take a file lock in the state directory to ensure this is the only agent using it
final Path lockPath = config.getStateDirectory().resolve("lock");
try {
stateLockFile = FileChannel.open(lockPath, CREATE, WRITE);
stateLock = stateLockFile.tryLock();
if (stateLock == null) {
throw new IllegalStateException("State lock file already locked: " + lockPath);
}
} catch (OverlappingFileLockException e) {
throw new IllegalStateException("State lock file already locked: " + lockPath);
} catch (IOException e) {
log.error("Failed to take state lock: {}", lockPath, e);
throw new RuntimeException(e);
}
final Path idPath = config.getStateDirectory().resolve("id");
final String id;
try {
if (Files.exists(idPath)) {
id = new String(Files.readAllBytes(idPath), UTF_8);
} else {
id = config.getId();
Files.write(idPath, id.getBytes(UTF_8));
}
} catch (IOException e) {
log.error("Failed to set up id file: {}", idPath, e);
throw new RuntimeException(e);
}
// Configure metrics
final MetricRegistry metricsRegistry = environment.metrics();
metricsRegistry.registerAll(new GarbageCollectorMetricSet());
metricsRegistry.registerAll(new MemoryUsageGaugeSet());
final DockerClient dockerClient = createDockerClient(config);
if (config.isInhibitMetrics()) {
log.info("Not starting metrics");
metrics = new NoopMetrics();
} else {
log.info("Starting metrics");
metrics = new MetricsImpl(metricsRegistry, MetricsImpl.Type.AGENT);
if (!Strings.isNullOrEmpty(config.getStatsdHostPort())) {
environment.lifecycle().manage(new ManagedStatsdReporter(config.getStatsdHostPort(),
metricsRegistry));
}
final FastForwardConfig ffwdConfig = config.getFfwdConfig();
if (ffwdConfig != null) {
// include the version docker as an additional attribute in FastForwardReporter
final DockerVersionSupplier versionSupplier = new DockerVersionSupplier(dockerClient);
final Supplier<Map<String, String>> attributesSupplier =
() -> ImmutableMap.of("docker_version", versionSupplier.get());
final FastForwardReporter reporter = FastForwardReporter.create(
metricsRegistry,
ffwdConfig.getAddress(),
ffwdConfig.getMetricKey(),
ffwdConfig.getReportingIntervalSeconds(),
attributesSupplier);
environment.lifecycle().manage(reporter);
}
}
// This CountDownLatch will signal EnvironmentVariableReporter and LabelReporter when to report
// data to ZK. They only report once and then stop, so we need to tell them when to start
// reporting otherwise they'll race with ZooKeeperRegistrarService and might have their data
// erased if they are too fast.
final CountDownLatch zkRegistrationSignal = new CountDownLatch(1);
this.zooKeeperClient = setupZookeeperClient(config, id, zkRegistrationSignal);
final DockerHealthChecker dockerHealthChecker = new DockerHealthChecker(
metrics.getSupervisorMetrics(), TimeUnit.SECONDS, 30);
environment.lifecycle().manage(dockerHealthChecker);
// Set up model
final ZooKeeperModelReporter modelReporter =
new ZooKeeperModelReporter(metrics.getZooKeeperMetrics());
final ZooKeeperClientProvider zkClientProvider = new ZooKeeperClientProvider(
zooKeeperClient, modelReporter);
final String taskStatusEventTopic = TaskStatusEvent.TASK_STATUS_EVENT_TOPIC;
final List<EventSender> eventSenders = EventSenderFactory
.build(environment, config, metricsRegistry, taskStatusEventTopic);
final TaskHistoryWriter historyWriter;
if (config.isJobHistoryDisabled()) {
historyWriter = null;
} else {
historyWriter = new TaskHistoryWriter(
config.getName(), zooKeeperClient, stateDirectory.resolve(TASK_HISTORY_FILENAME));
}
try {
this.model =
new ZooKeeperAgentModel(zkClientProvider, config.getName(), stateDirectory, historyWriter,
eventSenders, taskStatusEventTopic);
} catch (IOException e) {
throw new RuntimeException(e);
}
// Set up service registrar
this.serviceRegistrar = createServiceRegistrar(config.getServiceRegistrarPlugin(),
config.getServiceRegistryAddress(),
config.getDomain());
final ZooKeeperNodeUpdaterFactory nodeUpdaterFactory =
new ZooKeeperNodeUpdaterFactory(zooKeeperClient);
this.hostInfoReporter =
new HostInfoReporter((OperatingSystemMXBean) getOperatingSystemMXBean(), nodeUpdaterFactory,
config.getName(), dockerClient, config.getDockerHost(),
1, TimeUnit.MINUTES, zkRegistrationSignal);
this.agentInfoReporter =
new AgentInfoReporter(getRuntimeMXBean(), nodeUpdaterFactory, config.getName(),
1, TimeUnit.MINUTES, zkRegistrationSignal);
this.environmentVariableReporter = new EnvironmentVariableReporter(
config.getName(), config.getEnvVars(), nodeUpdaterFactory, zkRegistrationSignal);
this.labelReporter = new LabelReporter(
config.getName(), config.getLabels(), nodeUpdaterFactory, zkRegistrationSignal);
final String namespace = "helios-" + id;
final List<ContainerDecorator> decorators = Lists.newArrayList();
if (!isNullOrEmpty(config.getRedirectToSyslog())) {
decorators.add(new SyslogRedirectingContainerDecorator(config.getRedirectToSyslog()));
}
if (!config.getBinds().isEmpty()) {
decorators.add(new BindVolumeContainerDecorator(config.getBinds()));
}
if (!config.getExtraHosts().isEmpty()) {
decorators.add(new AddExtraHostContainerDecorator(config.getExtraHosts()));
}
final SupervisorFactory supervisorFactory = new SupervisorFactory(
model, dockerClient,
config.getEnvVars(), serviceRegistrar,
decorators,
config.getDockerHost(),
config.getName(),
metrics.getSupervisorMetrics(),
namespace,
config.getDomain(),
config.getDns());
final ReactorFactory reactorFactory = new ReactorFactory();
final PortAllocator portAllocator = new PortAllocator(config.getPortRangeStart(),
config.getPortRangeEnd());
final PersistentAtomicReference<Map<JobId, Execution>> executions;
try {
executions = PersistentAtomicReference.create(stateDirectory.resolve("executions.json"),
JOBID_EXECUTIONS_MAP,
Suppliers.ofInstance(EMPTY_EXECUTIONS));
} catch (IOException e) {
throw new RuntimeException(e);
}
final Reaper reaper = new Reaper(dockerClient, namespace);
this.agent = new Agent(model, supervisorFactory, reactorFactory, executions, portAllocator,
reaper);
final ZooKeeperHealthChecker zkHealthChecker = new ZooKeeperHealthChecker(zooKeeperClient);
final DockerDaemonHealthChecker dockerDaemonHealthChecker =
new DockerDaemonHealthChecker(dockerClient);
if (!config.getNoHttp()) {
environment.healthChecks().register("docker", dockerHealthChecker);
environment.healthChecks().register("zookeeper", zkHealthChecker);
environment.healthChecks().register("dockerd", dockerDaemonHealthChecker);
// Report each individual healthcheck as a gauge metric
environment.healthChecks().getNames().forEach(
name -> environment.metrics().register(
"helios." + name + ".ok", new HealthCheckGauge(environment.healthChecks(), name)));
// and add one gauge for the overall health, similar to what HealthCheckServlet does - if
// any healthcheck fails, then report overall health of false.
// this causes each healthcheck to be executed twice each time metrics are reported, but
// this feels ok since each check is cheap.
environment.metrics().register("helios.healthy",
new TotalHealthCheckGauge(environment.healthChecks()));
environment.jersey().register(new AgentModelTaskResource(model));
environment.jersey().register(new AgentModelTaskStatusResource(model));
environment.lifecycle().manage(this);
this.server = ServiceUtil.createServerFactory(config.getHttpEndpoint(),
config.getAdminEndpoint(),
config.getNoHttp())
.build(environment);
} else {
this.server = null;
}
environment.lifecycle().manage(this);
}
private DockerClient createDockerClient(final AgentConfig config) throws IOException {
final DefaultDockerClient.Builder builder = DefaultDockerClient.builder()
.uri(config.getDockerHost().uri());
if (config.getConnectionPoolSize() != -1) {
builder.connectionPoolSize(config.getConnectionPoolSize());
}
if (!isNullOrEmpty(config.getDockerHost().dockerCertPath())) {
final Path dockerCertPath = java.nio.file.Paths.get(config.getDockerHost().dockerCertPath());
final DockerCertificates dockerCertificates;
try {
dockerCertificates = new DockerCertificates(dockerCertPath);
} catch (DockerCertificateException e) {
throw new RuntimeException(e);
}
builder.dockerCertificates(dockerCertificates);
}
if (config.getGoogleCredentials() != null) {
builder.registryAuthSupplier(
ContainerRegistryAuthSupplier
.forCredentials(config.getGoogleCredentials())
.build()
);
}
return new PollingDockerClient(builder);
}
/**
* Create a Zookeeper client and create the control and state nodes if needed.
*
* @param config The service configuration.
*
* @return A zookeeper client.
*/
private ZooKeeperClient setupZookeeperClient(final AgentConfig config, final String id,
final CountDownLatch zkRegistrationSignal) {
ACLProvider aclProvider = null;
List<AuthInfo> authorization = null;
final String agentUser = config.getZookeeperAclAgentUser();
final String agentPassword = config.getZooKeeperAclAgentPassword();
final String masterUser = config.getZookeeperAclMasterUser();
final String masterDigest = config.getZooKeeperAclMasterDigest();
if (!isNullOrEmpty(agentPassword)) {
if (isNullOrEmpty(agentUser)) {
throw new HeliosRuntimeException(
"Agent username must be set if a password is set");
}
authorization = Lists.newArrayList(new AuthInfo(
"digest", String.format("%s:%s", agentUser, agentPassword).getBytes()));
}
if (config.isZooKeeperEnableAcls()) {
if (isNullOrEmpty(agentUser) || isNullOrEmpty(agentPassword)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but agent username and/or password not set");
}
if (isNullOrEmpty(masterUser) || isNullOrEmpty(masterDigest)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but master username and/or digest not set");
}
aclProvider = heliosAclProvider(
masterUser, masterDigest,
agentUser, digest(agentUser, agentPassword));
}
final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3);
final CuratorFramework curator = new CuratorClientFactoryImpl().newClient(
config.getZooKeeperConnectionString(),
config.getZooKeeperSessionTimeoutMillis(),
config.getZooKeeperConnectionTimeoutMillis(),
zooKeeperRetryPolicy,
aclProvider,
authorization);
final ZooKeeperClient client = new DefaultZooKeeperClient(curator,
config.getZooKeeperClusterId());
client.start();
// Register the agent
final AgentZooKeeperRegistrar agentZooKeeperRegistrar = new AgentZooKeeperRegistrar(
config.getName(), id, config.getZooKeeperRegistrationTtlMinutes(), new SystemClock());
zkRegistrar = ZooKeeperRegistrarService.newBuilder()
.setZooKeeperClient(client)
.setZooKeeperRegistrar(agentZooKeeperRegistrar)
.setZkRegistrationSignal(zkRegistrationSignal)
.build();
return client;
}
@Override
protected void startUp() throws Exception {
logBanner();
zkRegistrar.startAsync().awaitRunning();
model.startAsync().awaitRunning();
agent.startAsync().awaitRunning();
hostInfoReporter.startAsync();
agentInfoReporter.startAsync();
environmentVariableReporter.startAsync();
labelReporter.startAsync();
metrics.start();
if (server != null) {
try {
server.start();
} catch (Exception e) {
log.error("Unable to start server, shutting down", e);
server.stop();
}
}
}
private void logBanner() {
try {
final String banner = Resources.toString(Resources.getResource("agent-banner.txt"), UTF_8);
log.info("\n{}", banner);
} catch (IllegalArgumentException | IOException ignored) {
// ignore
}
}
@Override
protected void shutDown() throws Exception {
if (server != null) {
server.stop();
}
hostInfoReporter.stopAsync().awaitTerminated();
agentInfoReporter.stopAsync().awaitTerminated();
environmentVariableReporter.stopAsync().awaitTerminated();
labelReporter.stopAsync().awaitTerminated();
agent.stopAsync().awaitTerminated();
if (serviceRegistrar != null) {
serviceRegistrar.close();
}
zkRegistrar.stopAsync().awaitTerminated();
model.stopAsync().awaitTerminated();
metrics.stop();
zooKeeperClient.close();
try {
stateLock.release();
} catch (IOException e) {
log.error("Failed to release state lock", e);
}
try {
stateLockFile.close();
} catch (IOException e) {
log.error("Failed to close state lock file", e);
}
}
@Override
public void start() throws Exception {
}
@Override
public void stop() throws Exception {
shutDown();
}
}
| 7,133 |
593 | package org.ananas.runner.kernel.job;
import java.io.IOException;
import org.ananas.runner.kernel.build.Builder;
public interface JobManager {
String run(String jobId, Builder builder, String projectId, String token);
void cancelJob(String id) throws IOException;
}
| 79 |
6,036 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "gsl/gsl"
#include "core/providers/cuda/cuda_kernel.h"
#include "core/providers/cuda/cudnn_common.h"
namespace onnxruntime {
namespace cuda {
template <typename T, typename T1, typename T2>
class BatchNormalizationGrad final : public CudaKernel {
public:
BatchNormalizationGrad(const OpKernelInfo& info)
: CudaKernel{info},
cudnn_batch_norm_mode_(CUDNN_BATCHNORM_SPATIAL) {
float tmp_epsilon;
ORT_ENFORCE(info.GetAttr<float>("epsilon", &tmp_epsilon).IsOK());
epsilon_ = ClampCudnnBatchNormEpsilon(static_cast<double>(tmp_epsilon));
// spatial or not
int64_t tmp_spatial;
if (info.GetAttr<int64_t>("spatial", &tmp_spatial).IsOK()) {
spatial_ = tmp_spatial;
}
if (spatial_ == 0) {
cudnn_batch_norm_mode_ = CUDNN_BATCHNORM_PER_ACTIVATION;
}
}
Status ComputeInternal(OpKernelContext* context) const override;
private:
double epsilon_;
int64_t spatial_ = 1;
cudnnBatchNormMode_t cudnn_batch_norm_mode_;
};
} // namespace cuda
} // namespace onnxruntime
| 475 |
2,151 | <reponame>zipated/src
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_DISPLAY_OUTPUT_PROTECTION_CONTROLLER_MUS_H_
#define CHROME_BROWSER_CHROMEOS_DISPLAY_OUTPUT_PROTECTION_CONTROLLER_MUS_H_
#include "base/macros.h"
#include "base/threading/thread_checker.h"
#include "chrome/browser/chromeos/display/output_protection_delegate.h"
#include "services/ui/public/interfaces/display/output_protection.mojom.h"
namespace chromeos {
// Display content protection controller for running with Mus server.
class OutputProtectionControllerMus
: public OutputProtectionDelegate::Controller {
public:
OutputProtectionControllerMus();
~OutputProtectionControllerMus() override;
// OutputProtectionDelegate::Controller:
void QueryStatus(
int64_t display_id,
const OutputProtectionDelegate::QueryStatusCallback& callback) override;
void SetProtection(
int64_t display_id,
uint32_t desired_method_mask,
const OutputProtectionDelegate::SetProtectionCallback& callback) override;
private:
display::mojom::OutputProtectionPtr output_protection_;
base::ThreadChecker thread_checker_;
DISALLOW_COPY_AND_ASSIGN(OutputProtectionControllerMus);
};
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_DISPLAY_OUTPUT_PROTECTION_CONTROLLER_MUS_H_
| 478 |
1,355 | <gh_stars>1000+
// Copyright (c) 2018 <NAME>
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include "logging.h"
#include "pybind11_utils.h"
#include <jet/logging.h>
namespace py = pybind11;
using namespace jet;
void addLogging(pybind11::module& m) {
py::enum_<LoggingLevel>(m, "LoggingLevel")
.value("ALL", LoggingLevel::All)
.value("DEBUG", LoggingLevel::Debug)
.value("INFO", LoggingLevel::Info)
.value("WARN", LoggingLevel::Warn)
.value("ERROR", LoggingLevel::Error)
.value("OFF", LoggingLevel::Off)
.export_values();
py::class_<Logging>(m, "Logging")
.def_static("setLevel", &Logging::setLevel)
.def_static("mute", &Logging::mute)
.def_static("unmute", &Logging::unmute);
}
| 362 |
563 | <reponame>devilWwj/android-patternview
package com.eftimoff.patternview.cells;
import android.os.Parcel;
import android.os.Parcelable;
import com.eftimoff.patternview.utils.CellUtils;
/**
* Class representing an object in specific position.
*/
public class Cell implements Parcelable {
private int row;
private int column;
/**
* @param row The row of the cell.
* @param column The column of the cell.
*/
public Cell(int row, int column) {
CellUtils.checkRange(row, column);
this.row = row;
this.column = column;
}
/**
* Gets the row index.
*
* @return the row index.
*/
public int getRow() {
return row;
}
/**
* Gets the column index.
*
* @return the column index.
*/
public int getColumn() {
return column;
}
/**
* Gets the ID.It is counted from left to right, top to bottom of the
* matrix, starting by zero.
*
* @return the ID.
*/
public String getId() {
final String formatRow = String.format("%03d", row);
final String formatColumn = String.format("%03d", column);
return formatRow + "-" + formatColumn;
}
@Override
public String toString() {
return "(r=" + getRow() + ",c=" + getColumn() + ")";
}
@Override
public boolean equals(Object object) {
if (object instanceof Cell) {
return getColumn() == ((Cell) object).getColumn() && getRow() == ((Cell) object).getRow();
}
return super.equals(object);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(getColumn());
parcel.writeInt(getRow());
}
public void readFromParcel(Parcel in) {
column = in.readInt();
row = in.readInt();
}
public static final Parcelable.Creator<Cell> CREATOR = new Parcelable.Creator<Cell>() {
public Cell createFromParcel(Parcel in) {
return new Cell(in);
}
public Cell[] newArray(int size) {
return new Cell[size];
}
};
private Cell(Parcel in) {
readFromParcel(in);
}
}
| 953 |
478 | <reponame>hawesy/qlcplus<gh_stars>100-1000
/*
Q Light Controller Plus - Unit test
resource_paths.h
Copyright (c) <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
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 RESOURCE_PATHS_H
#define RESOURCE_PATHS_H
#define INTERNAL_FIXTUREDIR "../../../resources/fixtures/"
#define INTERNAL_PROFILEDIR "../../../resources/inputprofiles/"
#define INTERNAL_SCRIPTDIR "../../../resources/rgbscripts/"
#endif
| 282 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000
{"nom":"Mouleydier","circ":"2ème circonscription","dpt":"Dordogne","inscrits":842,"abs":415,"votants":427,"blancs":28,"nuls":15,"exp":384,"res":[{"nuance":"REM","nom":"<NAME>","voix":216},{"nuance":"FN","nom":"<NAME>","voix":168}]} | 120 |
4,772 | package example.service;
import example.repo.Customer279Repository;
import org.springframework.stereotype.Service;
@Service
public class Customer279Service {
public Customer279Service(Customer279Repository repo) {}
}
| 60 |
435 | <reponame>amaajemyfren/data
{
"copyright_text": "Creative Commons Attribution license (reuse allowed)",
"description": "The dateutil library provides a number of extensions to Python's standard datetime handling libraries. This talk will provide an overview of how to use (and not use!) dateutil to improve your datetime-handling experience, and also cover some of the recent changes to the library.",
"duration": 2062,
"language": "eng",
"recorded": "2016-07-17",
"related_urls": [
"https://2016.pygotham.org/talks/278/python-dateutil-a-delight/"
],
"speakers": [
"<NAME>"
],
"tags": [
"dateutil"
],
"thumbnail_url": "https://i.ytimg.com/vi/X_bCto95Imc/maxresdefault.jpg",
"title": "python-dateutil: A delightful romp in the never-confusing world of dates and times",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=X_bCto95Imc"
}
]
}
| 328 |
11,094 | arr = [2, 3, "apple", 52, 'c', True]
print(arr) | 22 |
782 | /*
* Copyright (c) 2021, <NAME>. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.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.
*/
package boofcv.abst.distort;
import boofcv.struct.distort.Point2Transform2_F32;
import georegression.struct.point.Point2D_F32;
import java.util.List;
/**
* <p>Defines a {@link Point2Transform2_F32 mapping} which deforms the image based on the location of key points inside the image.
* Image pixels will gravitate towards closer key points and their distorted location based on some distance metric.</p>
*
* <p>Concurrency: Do not use this class to render at the same time you're invoking any of its functions! The
* transformation will be in an unsafe state.</p>
*
* @author <NAME>
*/
public interface PointDeformKeyPoints extends Point2Transform2_F32 {
/**
* Must be called first. Specifies the shape of the image this transform will be applied to
* @param width image width
* @param height image height
*/
void setImageShape( int width , int height );
/**
* Specifies the location of all the key points. The initial distorted location of each keypoint will be set to
* the same location.
* @param locations Location of key points in undistorted image. Local copy of points is saved.
*/
void setSource(List<Point2D_F32> locations );
/**
* Specifies the distorted location of all the key points.
*
* @param locations location of key points in distorted image. Local copy of points is saved.
*/
void setDestination(List<Point2D_F32> locations );
/**
* Changes the source location of a single key point
*
* @param which Index of key point to change
* @param x distorted x-coordinate
* @param y distorted y-coordinate
*/
void setSource(int which , float x , float y );
/**
* Changes the destination location of a single key point
* @param which Index of key point to change
* @param x distorted x-coordinate
* @param y distorted y-coordinate
*/
void setDestination(int which , float x , float y );
}
| 710 |
2,372 | <reponame>ceti-dev/PhysX
//
// 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 NVIDIA CORPORATION 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 ''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.
//
// Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef DY_ARTICULATION_DEBUG_FNS_H
#define DY_ARTICULATION_DEBUG_FNS_H
#include "DyArticulationFnsScalar.h"
#include "DyArticulationFnsSimd.h"
namespace physx
{
namespace Dy
{
#if 0
void printMomentum(const char* id, PxTransform* pose, Cm::SpatialVector* velocity, FsInertia* inertia, PxU32 linkCount)
{
typedef ArticulationFnsScalar Fns;
Cm::SpatialVector m = Cm::SpatialVector::zero();
for(PxU32 i=0;i<linkCount;i++)
m += Fns::translateForce(pose[i].p - pose[0].p, Fns::multiply(inertia[i], velocity[i]));
printf("momentum (%20s): (%f, %f, %f), (%f, %f, %f)\n", id, m.linear.x, m.linear.y, m.linear.z, m.angular.x, m.angular.y, m.angular.z);
}
#endif
class ArticulationFnsDebug
{
typedef ArticulationFnsSimdBase SimdBase;
typedef ArticulationFnsSimd<ArticulationFnsDebug> Simd;
typedef ArticulationFnsScalar Scalar;
public:
static PX_FORCE_INLINE FsInertia addInertia(const FsInertia& in1, const FsInertia& in2)
{
return FsInertia(M33Add(in1.ll, in2.ll),
M33Add(in1.la, in2.la),
M33Add(in1.aa, in2.aa));
}
static PX_FORCE_INLINE FsInertia subtractInertia(const FsInertia& in1, const FsInertia& in2)
{
return FsInertia(M33Sub(in1.ll, in2.ll),
M33Sub(in1.la, in2.la),
M33Sub(in1.aa, in2.aa));
}
static Mat33V invertSym33(const Mat33V &m)
{
PxMat33 n_ = Scalar::invertSym33(unsimdify(m));
Mat33V n = SimdBase::invertSym33(m);
compare33(n_, unsimdify(n));
return n;
}
static Mat33V invSqrt(const Mat33V &m)
{
PxMat33 n_ = Scalar::invSqrt(unsimdify(m));
Mat33V n = SimdBase::invSqrt(m);
compare33(n_, unsimdify(n));
return n;
}
static FsInertia invertInertia(const FsInertia &I)
{
SpInertia J_ = Scalar::invertInertia(unsimdify(I));
FsInertia J = SimdBase::invertInertia(I);
compareInertias(J_,unsimdify(J));
return J;
}
static Mat33V computeSIS(const FsInertia &I, const Cm::SpatialVectorV S[3], Cm::SpatialVectorV*PX_RESTRICT IS)
{
Cm::SpatialVector IS_[3];
Scalar::multiply(IS_, unsimdify(I), unsimdify(&S[0]));
PxMat33 D_ = Scalar::multiplySym(IS_, unsimdify(&S[0]));
Mat33V D = SimdBase::computeSIS(I, S, IS);
compare33(unsimdify(D), D_);
return D;
}
static FsInertia multiplySubtract(const FsInertia &I, const Mat33V &D, const Cm::SpatialVectorV IS[3], Cm::SpatialVectorV*PX_RESTRICT DSI)
{
Cm::SpatialVector DSI_[3];
Scalar::multiply(DSI_, unsimdify(IS), unsimdify(D));
SpInertia J_ = Scalar::multiplySubtract(unsimdify(I), DSI_, unsimdify(IS));
FsInertia J = SimdBase::multiplySubtract(I, D, IS, DSI);
compareInertias(unsimdify(J), J_);
return J;
}
static FsInertia multiplySubtract(const FsInertia &I, const Cm::SpatialVectorV S[3])
{
SpInertia J_ = Scalar::multiplySubtract(unsimdify(I), unsimdify(S), unsimdify(S));
FsInertia J = SimdBase::multiplySubtract(I, S);
compareInertias(unsimdify(J), J_);
return J;
}
static FsInertia translateInertia(Vec3V offset, const FsInertia &I)
{
PxVec3 offset_;
V3StoreU(offset, offset_);
SpInertia J_ = Scalar::translate(offset_, unsimdify(I));
FsInertia J = SimdBase::translateInertia(offset, I);
compareInertias(J_, unsimdify(J));
return J;
}
static PX_FORCE_INLINE FsInertia propagate(const FsInertia &I,
const Cm::SpatialVectorV S[3],
const Mat33V &load,
const FloatV isf)
{
SpInertia J_ = Scalar::propagate(unsimdify(I), unsimdify(&S[0]), unsimdify(load), unsimdify(isf));
FsInertia J = Simd::propagate(I, S, load, isf);
compareInertias(J_, unsimdify(J));
return J;
}
static PX_FORCE_INLINE Mat33V computeDriveInertia(const FsInertia &I0,
const FsInertia &I1,
const Cm::SpatialVectorV S[3])
{
PxMat33 m_ = Scalar::computeDriveInertia(unsimdify(I0), unsimdify(I1), unsimdify(&S[0]));
Mat33V m = Simd::computeDriveInertia(I0, I1, S);
compare33(m_, unsimdify(m));
return m;
}
static const PxMat33 unsimdify(const Mat33V &m)
{
PX_ALIGN(16, PxMat33) m_;
PxMat33_From_Mat33V(m, m_);
return m_;
}
static PxReal unsimdify(const FloatV &m)
{
PxF32 f;
FStore(m, &f);
return f;
}
static SpInertia unsimdify(const FsInertia &I)
{
return SpInertia (unsimdify(I.ll),
unsimdify(I.la),
unsimdify(I.aa));
}
static const Cm::SpatialVector* unsimdify(const Cm::SpatialVectorV *S)
{
return reinterpret_cast<const Cm::SpatialVector*>(S);
}
private:
static PxReal absmax(const PxVec3& n)
{
return PxMax(PxAbs(n.x), PxMax(PxAbs(n.y),PxAbs(n.z)));
}
static PxReal norm(const PxMat33& n)
{
return PxMax(absmax(n.column0), PxMax(absmax(n.column1), absmax(n.column2)));
}
static void compare33(const PxMat33& ref, const PxMat33& n)
{
PxReal errNorm = norm(ref-n);
PX_UNUSED(errNorm);
PX_ASSERT(errNorm <= PxMax(norm(ref)*1e-3f, 1e-4f));
}
static void compareInertias(const SpInertia& a, const SpInertia& b)
{
compare33(a.mLL, b.mLL);
compare33(a.mLA, b.mLA);
compare33(a.mAA, b.mAA);
}
};
#if DY_ARTICULATION_DEBUG_VERIFY
static bool isPositiveDefinite(const Mat33V& m)
{
PX_ALIGN_PREFIX(16) PxMat33 m1 PX_ALIGN_SUFFIX(16);
PxMat33_From_Mat33V(m, m1);
return isPositiveDefinite(m1);
}
static bool isPositiveDefinite(const FsInertia& s)
{
return isPositiveDefinite(ArticulationFnsDebug::unsimdify(s));
}
static PxReal magnitude(const Cm::SpatialVectorV &v)
{
return PxSqrt(FStore(V3Dot(v.linear, v.linear)) + FStore(V3Dot(v.angular, v.angular)));
}
static bool almostEqual(const Cm::SpatialVectorV &ref, const Cm::SpatialVectorV& test, PxReal tolerance)
{
return magnitude(ref-test)<=tolerance*magnitude(ref);
}
#endif
}
}
#endif //DY_ARTICULATION_DEBUG_FNS_H
| 3,253 |
575 | /*
* Copyright (C) 2004, 2005, 2006, 2008 <NAME> <<EMAIL>>
* Copyright (C) 2004, 2005, 2006, 2007 <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_ELEMENT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_ELEMENT_H_
#include "third_party/blink/renderer/core/svg/svg_geometry_element.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
class SVGAnimatedPath;
class SVGPathByteStream;
class StylePath;
class SVGPathElement final : public SVGGeometryElement {
DEFINE_WRAPPERTYPEINFO();
public:
explicit SVGPathElement(Document&);
Path AsPath() const override;
Path AttributePath() const;
float getTotalLength(ExceptionState&) override;
SVGPointTearOff* getPointAtLength(float distance, ExceptionState&) override;
SVGAnimatedPath* GetPath() const { return path_.Get(); }
float ComputePathLength() const override;
const SVGPathByteStream& PathByteStream() const;
FloatRect GetBBox() override;
void Trace(Visitor*) const override;
private:
const StylePath* GetStylePath() const;
void SvgAttributeChanged(const SvgAttributeChangedParams&) override;
void CollectStyleForPresentationAttribute(
const QualifiedName&,
const AtomicString&,
MutableCSSPropertyValueSet*) override;
Node::InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void RemovedFrom(ContainerNode&) override;
void InvalidateMPathDependencies();
Member<SVGAnimatedPath> path_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_ELEMENT_H_
| 725 |
3,012 | <filename>NetworkPkg/Include/Guid/Ip4Config2Hii.h
/** @file
GUIDs used as HII FormSet and HII Package list GUID in Ip4Dxe driver.
Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef __IP4_CONFIG2_HII_GUID_H__
#define __IP4_CONFIG2_HII_GUID_H__
#define IP4_CONFIG2_NVDATA_GUID \
{ \
0x9b942747, 0x154e, 0x4d29, { 0xa4, 0x36, 0xbf, 0x71, 0x0, 0xc8, 0xb5, 0x3b } \
}
extern EFI_GUID gIp4Config2NvDataGuid;
#endif
| 263 |
621 | <filename>Chapter15/train_lm.py<gh_stars>100-1000
#!/usr/bin/env python3
import gym
import ptan
import pathlib
import argparse
import itertools
import numpy as np
from typing import List
from textworld.gym import register_games
from textworld import EnvInfos
from lib import preproc, model, common
import torch
import torch.optim as optim
from ignite.engine import Engine
GAMMA = 0.9
BATCH_SIZE = 16
LEARNING_RATE_LM = 1e-5
LEARNING_RATE = 1e-5
# have to be less or equal to env.action_space.max_length
LM_MAX_TOKENS = 4
LM_MAX_COMMANDS = 10
LM_STOP_AVG_REWARD = -1.0
EXTRA_GAME_INFO = {
"inventory": True,
"description": True,
"intermediate_reward": True,
"admissible_commands": True,
"policy_commands": True,
"last_command": True,
}
def unpack_batch(batch: List[ptan.experience.ExperienceFirstLast], prep: preproc.Preprocessor):
states = []
rewards = []
not_done_idx = []
next_states = []
for idx, exp in enumerate(batch):
states.append(exp.state['obs'])
rewards.append(exp.reward)
if exp.last_state is not None:
not_done_idx.append(idx)
next_states.append(exp.last_state['obs'])
return prep.encode_sequences(states)
def batch_generator(exp_source: ptan.experience.ExperienceSourceFirstLast,
batch_size: int):
batch = []
for exp in exp_source:
batch.append(exp)
if len(batch) == batch_size:
yield batch
batch.clear()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-g", "--game", default="simple",
help="Game prefix to be used during training, default=simple")
parser.add_argument("--params", choices=list(common.PARAMS.keys()), default='small',
help="Training params, could be one of %s" % (list(common.PARAMS.keys())))
parser.add_argument("-s", "--suffices", type=int, default=1,
help="Count of game indices to use during training, default=1")
parser.add_argument("-v", "--validation", default='-val',
help="Suffix for game used for validation, default=-val")
parser.add_argument("--cuda", default=False, action='store_true',
help="Use cuda for training")
parser.add_argument("-r", "--run", required=True, help="Run name")
parser.add_argument("--load-cmd", help="If specified, command generator will be loaded "
"from given prefix, otherwise it will be trained")
args = parser.parse_args()
device = torch.device("cuda" if args.cuda else "cpu")
params = common.PARAMS[args.params]
game_files = ["games/%s%s.ulx" % (args.game, s) for s in range(1, args.suffices+1)]
val_game_file = "games/%s%s.ulx" % (args.game, args.validation)
if not all(map(lambda p: pathlib.Path(p).exists(), game_files)):
raise RuntimeError(f"Some game files from {game_files} not found! Probably you need to run make_games.sh")
action_space, observation_space = common.get_games_spaces(game_files + [val_game_file])
env_id = register_games(game_files, request_infos=EnvInfos(**EXTRA_GAME_INFO), name=args.game,
action_space=action_space, observation_space=observation_space)
print("Registered env %s for game files %s" % (env_id, game_files))
val_env_id = register_games([val_game_file], request_infos=EnvInfos(**EXTRA_GAME_INFO), name=args.game,
action_space=action_space, observation_space=observation_space)
print("Game %s, with file %s will be used for validation" % (val_env_id, val_game_file))
env = gym.make(env_id)
env = preproc.TextWorldPreproc(env, use_admissible_commands=False,
keep_admissible_commands=True,
reward_wrong_last_command=-0.1)
prep = preproc.Preprocessor(
dict_size=env.observation_space.vocab_size,
emb_size=params.embeddings, num_sequences=env.num_fields,
enc_output_size=params.encoder_size).to(device)
cmd = model.CommandModel(prep.obs_enc_size, env.observation_space.vocab_size, prep.emb,
max_tokens=LM_MAX_TOKENS,
max_commands=LM_MAX_COMMANDS,
start_token=env.action_space.BOS_id,
sep_token=env.action_space.EOS_id).to(device)
if args.load_cmd is not None:
load_path = pathlib.Path(args.load_cmd)
prep.load_state_dict(torch.load(load_path/"prep.dat"))
cmd.load_state_dict(torch.load(load_path/"cmd.dat"))
print("Preprocessor and command generator are loaded from %s" % load_path)
else:
agent = model.CmdAgent(env, cmd, prep, device=device)
exp_source = ptan.experience.ExperienceSourceFirstLast(
env, agent, gamma=GAMMA, steps_count=1)
buffer = ptan.experience.ExperienceReplayBuffer(
exp_source, params.replay_size)
optimizer = optim.RMSprop(itertools.chain(prep.parameters(), cmd.parameters()),
lr=LEARNING_RATE_LM, eps=1e-5)
def process_batch(engine, batch):
optimizer.zero_grad()
obs_t = unpack_batch(batch, prep)
commands = []
for s in batch:
cmds = []
for c in s.state['admissible_commands']:
t = env.action_space.tokenize(c)
if len(t)-2 <= LM_MAX_TOKENS:
cmds.append(t)
commands.append(cmds)
loss_t = model.pretrain_loss(cmd, commands, obs_t)
loss_t.backward()
optimizer.step()
if engine.state.metrics.get('avg_reward', LM_STOP_AVG_REWARD) > LM_STOP_AVG_REWARD:
print("Mean reward reached %.2f, stop pretraining" % LM_STOP_AVG_REWARD)
engine.should_terminate = True
return {
"loss": loss_t.item(),
}
engine = Engine(process_batch)
run_name = f"lm-{args.params}_{args.run}"
save_path = pathlib.Path("saves") / run_name
save_path.mkdir(parents=True, exist_ok=True)
common.setup_ignite(engine, exp_source, run_name)
try:
engine.run(common.batch_generator(buffer, BATCH_SIZE, BATCH_SIZE))
except KeyboardInterrupt:
print("Interrupt got, saving the model...")
torch.save(prep.state_dict(), save_path/"prep.dat")
torch.save(cmd.state_dict(), save_path/"cmd.dat")
print("Using preprocessor and command generator")
prep.train(False)
cmd.train(False)
val_env = gym.make(val_env_id)
val_env = preproc.TextWorldPreproc(val_env, use_admissible_commands=False,
keep_admissible_commands=True,
reward_wrong_last_command=-0.1)
net = model.DQNModel(obs_size=prep.obs_enc_size,
cmd_size=prep.obs_enc_size).to(device)
tgt_net = ptan.agent.TargetNet(net)
cmd_encoder = preproc.Encoder(params.embeddings, prep.obs_enc_size).to(device)
tgt_cmd_encoder = ptan.agent.TargetNet(cmd_encoder)
agent = model.CmdDQNAgent(env, net, cmd, cmd_encoder, prep, epsilon=1, device=device)
exp_source = ptan.experience.ExperienceSourceFirstLast(
env, agent, gamma=GAMMA, steps_count=1)
buffer = ptan.experience.ExperienceReplayBuffer(
exp_source, params.replay_size)
optimizer = optim.RMSprop(itertools.chain(net.parameters(), cmd_encoder.parameters()),
lr=LEARNING_RATE, eps=1e-5)
def process_batch(engine, batch):
optimizer.zero_grad()
loss_t = model.calc_loss_dqncmd(
batch, prep, cmd,
cmd_encoder, tgt_cmd_encoder.target_model,
net, tgt_net.target_model, GAMMA, env, device)
loss_t.backward()
optimizer.step()
eps = 1 - engine.state.iteration / params.epsilon_steps
agent.epsilon = max(params.epsilon_final, eps)
if engine.state.iteration % params.sync_nets == 0:
tgt_net.sync()
tgt_cmd_encoder.sync()
return {
"loss": loss_t.item(),
"epsilon": agent.epsilon,
}
engine = Engine(process_batch)
run_name = f"dqn-{args.params}_{args.run}"
save_path = pathlib.Path("saves") / run_name
save_path.mkdir(parents=True, exist_ok=True)
common.setup_ignite(engine, exp_source, run_name,
extra_metrics=('val_reward', 'val_steps'))
@engine.on(ptan.ignite.PeriodEvents.ITERS_100_COMPLETED)
@torch.no_grad()
def validate(engine):
reward = 0.0
steps = 0
obs = val_env.reset()
while True:
obs_t = prep.encode_sequences([obs['obs']]).to(device)
cmds = cmd.commands(obs_t)[0]
cmd_embs_t = prep._apply_encoder(cmds, cmd_encoder)
q_vals = net.q_values_cmd(obs_t[0], cmd_embs_t)
act = np.argmax(q_vals)
best_cmd = cmds[act]
tokens = [
env.action_space.id2w[t]
for t in best_cmd
if t not in {cmd.sep_token, cmd.start_token}
]
action = " ".join(tokens)
obs, r, is_done, _ = val_env.step(action)
steps += 1
reward += r
if is_done:
break
engine.state.metrics['val_reward'] = reward
engine.state.metrics['val_steps'] = steps
print("Validation got %.3f reward in %d steps" % (reward, steps))
best_val_reward = getattr(engine.state, "best_val_reward", None)
if best_val_reward is None:
engine.state.best_val_reward = reward
elif best_val_reward < reward:
print("Best validation reward updated: %s -> %s" % (best_val_reward, reward))
save_net_name = save_path / ("best_val_%.3f.dat" % reward)
torch.save(net.state_dict(), save_net_name)
engine.state.best_val_reward = reward
@engine.on(ptan.ignite.EpisodeEvents.BEST_REWARD_REACHED)
def best_reward_updated(trainer: Engine):
reward = trainer.state.metrics['avg_reward']
if reward > 0:
save_net_name = save_path / ("best_train_%.3f_.dat" % reward)
torch.save(net.state_dict(), save_net_name)
print("%d: best avg training reward: %.3f, saved" % (
trainer.state.iteration, reward))
engine.run(common.batch_generator(buffer, 100 + 0*params.replay_initial, BATCH_SIZE))
| 5,079 |
395 | {
"name": "worldmodels",
"version": "0.0.1",
"dependencies": {
"markdown-it": "*",
"markdown-it-center-text": "^1.0.3",
"markdown-it-katex": "*"
},
"repository": {
"type": "git",
"url": "https://github.com/worldmodels/worldmodels.github.io"
},
"license": "MIT"
}
| 140 |
995 | <reponame>calebmarchent/fizz
/*
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <fizz/crypto/Utils.h>
#include <sodium.h>
#include <folly/ssl/Init.h>
namespace {
class InitFizz {
public:
InitFizz() {
if (sodium_init() == -1) {
throw std::runtime_error("Couldn't init libsodium");
}
folly::ssl::init();
}
};
} // namespace
namespace fizz {
bool CryptoUtils::equal(folly::ByteRange a, folly::ByteRange b) {
if (a.size() != b.size()) {
return false;
}
return sodium_memcmp(a.data(), b.data(), a.size()) == 0;
}
void CryptoUtils::clean(folly::MutableByteRange range) {
sodium_memzero(range.data(), range.size());
}
void CryptoUtils::init() {
static InitFizz initFizz;
}
} // namespace fizz
| 341 |
365 | <filename>extern/sdlew/include/SDL2/SDL_haptic.h<gh_stars>100-1000
#ifndef _SDL_haptic_h
#define _SDL_haptic_h
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_joystick.h"
#include "begin_code.h"
#ifdef __cplusplus
extern "C" {
#endif
struct _SDL_Haptic;
typedef struct _SDL_Haptic SDL_Haptic;
#define SDL_HAPTIC_CONSTANT (1<<0)
#define SDL_HAPTIC_SINE (1<<1)
#define SDL_HAPTIC_LEFTRIGHT (1<<2)
#define SDL_HAPTIC_TRIANGLE (1<<3)
#define SDL_HAPTIC_SAWTOOTHUP (1<<4)
#define SDL_HAPTIC_SAWTOOTHDOWN (1<<5)
#define SDL_HAPTIC_RAMP (1<<6)
#define SDL_HAPTIC_SPRING (1<<7)
#define SDL_HAPTIC_DAMPER (1<<8)
#define SDL_HAPTIC_INERTIA (1<<9)
#define SDL_HAPTIC_FRICTION (1<<10)
#define SDL_HAPTIC_CUSTOM (1<<11)
#define SDL_HAPTIC_GAIN (1<<12)
#define SDL_HAPTIC_AUTOCENTER (1<<13)
#define SDL_HAPTIC_STATUS (1<<14)
#define SDL_HAPTIC_PAUSE (1<<15)
#define SDL_HAPTIC_POLAR 0
#define SDL_HAPTIC_CARTESIAN 1
#define SDL_HAPTIC_SPHERICAL 2
#define SDL_HAPTIC_INFINITY 4294967295U
typedef struct SDL_HapticDirection
{
Uint8 type;
Sint32 dir[3];
} SDL_HapticDirection;
typedef struct SDL_HapticConstant
{
Uint16 type;
SDL_HapticDirection direction;
Uint32 length;
Uint16 delay;
Uint16 button;
Uint16 interval;
Sint16 level;
Uint16 attack_length;
Uint16 attack_level;
Uint16 fade_length;
Uint16 fade_level;
} SDL_HapticConstant;
typedef struct SDL_HapticPeriodic
{
Uint16 type;
SDL_HapticDirection direction;
Uint32 length;
Uint16 delay;
Uint16 button;
Uint16 interval;
Uint16 period;
Sint16 magnitude;
Sint16 offset;
Uint16 phase;
Uint16 attack_length;
Uint16 attack_level;
Uint16 fade_length;
Uint16 fade_level;
} SDL_HapticPeriodic;
typedef struct SDL_HapticCondition
{
Uint16 type;
SDL_HapticDirection direction;
Uint32 length;
Uint16 delay;
Uint16 button;
Uint16 interval;
Uint16 right_sat[3];
Uint16 left_sat[3];
Sint16 right_coeff[3];
Sint16 left_coeff[3];
Uint16 deadband[3];
Sint16 center[3];
} SDL_HapticCondition;
typedef struct SDL_HapticRamp
{
Uint16 type;
SDL_HapticDirection direction;
Uint32 length;
Uint16 delay;
Uint16 button;
Uint16 interval;
Sint16 start;
Sint16 end;
Uint16 attack_length;
Uint16 attack_level;
Uint16 fade_length;
Uint16 fade_level;
} SDL_HapticRamp;
typedef struct SDL_HapticLeftRight
{
Uint16 type;
Uint32 length;
Uint16 large_magnitude;
Uint16 small_magnitude;
} SDL_HapticLeftRight;
typedef struct SDL_HapticCustom
{
Uint16 type;
SDL_HapticDirection direction;
Uint32 length;
Uint16 delay;
Uint16 button;
Uint16 interval;
Uint8 channels;
Uint16 period;
Uint16 samples;
Uint16 *data;
Uint16 attack_length;
Uint16 attack_level;
Uint16 fade_length;
Uint16 fade_level;
} SDL_HapticCustom;
typedef union SDL_HapticEffect
{
Uint16 type;
SDL_HapticConstant constant;
SDL_HapticPeriodic periodic;
SDL_HapticCondition condition;
SDL_HapticRamp ramp;
SDL_HapticLeftRight leftright;
SDL_HapticCustom custom;
} SDL_HapticEffect;
typedef int SDLCALL tSDL_NumHaptics(void);
typedef const char * SDLCALL tSDL_HapticName(int device_index);
typedef SDL_Haptic * SDLCALL tSDL_HapticOpen(int device_index);
typedef int SDLCALL tSDL_HapticOpened(int device_index);
typedef int SDLCALL tSDL_HapticIndex(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_MouseIsHaptic(void);
typedef SDL_Haptic * SDLCALL tSDL_HapticOpenFromMouse(void);
typedef int SDLCALL tSDL_JoystickIsHaptic(SDL_Joystick * joystick);
typedef SDL_Haptic * SDLCALL tSDL_HapticOpenFromJoystick(SDL_Joystick *
joystick);
typedef void SDLCALL tSDL_HapticClose(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_HapticNumEffects(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_HapticNumEffectsPlaying(SDL_Haptic * haptic);
extern DECLSPEC unsigned int SDLCALL SDL_HapticQuery(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_HapticNumAxes(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_HapticEffectSupported(SDL_Haptic * haptic,
SDL_HapticEffect *
effect);
typedef int SDLCALL tSDL_HapticNewEffect(SDL_Haptic * haptic,
SDL_HapticEffect * effect);
typedef int SDLCALL tSDL_HapticUpdateEffect(SDL_Haptic * haptic,
int effect,
SDL_HapticEffect * data);
typedef int SDLCALL tSDL_HapticRunEffect(SDL_Haptic * haptic,
int effect,
Uint32 iterations);
typedef int SDLCALL tSDL_HapticStopEffect(SDL_Haptic * haptic,
int effect);
typedef void SDLCALL tSDL_HapticDestroyEffect(SDL_Haptic * haptic,
int effect);
typedef int SDLCALL tSDL_HapticGetEffectStatus(SDL_Haptic * haptic,
int effect);
typedef int SDLCALL tSDL_HapticSetGain(SDL_Haptic * haptic, int gain);
typedef int SDLCALL tSDL_HapticSetAutocenter(SDL_Haptic * haptic,
int autocenter);
typedef int SDLCALL tSDL_HapticPause(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_HapticUnpause(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_HapticStopAll(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_HapticRumbleSupported(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_HapticRumbleInit(SDL_Haptic * haptic);
typedef int SDLCALL tSDL_HapticRumblePlay(SDL_Haptic * haptic, float strength, Uint32 length );
typedef int SDLCALL tSDL_HapticRumbleStop(SDL_Haptic * haptic);
extern tSDL_NumHaptics *SDL_NumHaptics;
extern tSDL_HapticName *SDL_HapticName;
extern tSDL_HapticOpen *SDL_HapticOpen;
extern tSDL_HapticOpened *SDL_HapticOpened;
extern tSDL_HapticIndex *SDL_HapticIndex;
extern tSDL_MouseIsHaptic *SDL_MouseIsHaptic;
extern tSDL_HapticOpenFromMouse *SDL_HapticOpenFromMouse;
extern tSDL_JoystickIsHaptic *SDL_JoystickIsHaptic;
extern tSDL_HapticOpenFromJoystick *SDL_HapticOpenFromJoystick;
extern tSDL_HapticClose *SDL_HapticClose;
extern tSDL_HapticNumEffects *SDL_HapticNumEffects;
extern tSDL_HapticNumEffectsPlaying *SDL_HapticNumEffectsPlaying;
extern tSDL_HapticNumAxes *SDL_HapticNumAxes;
extern tSDL_HapticEffectSupported *SDL_HapticEffectSupported;
extern tSDL_HapticNewEffect *SDL_HapticNewEffect;
extern tSDL_HapticUpdateEffect *SDL_HapticUpdateEffect;
extern tSDL_HapticRunEffect *SDL_HapticRunEffect;
extern tSDL_HapticStopEffect *SDL_HapticStopEffect;
extern tSDL_HapticDestroyEffect *SDL_HapticDestroyEffect;
extern tSDL_HapticGetEffectStatus *SDL_HapticGetEffectStatus;
extern tSDL_HapticSetGain *SDL_HapticSetGain;
extern tSDL_HapticSetAutocenter *SDL_HapticSetAutocenter;
extern tSDL_HapticPause *SDL_HapticPause;
extern tSDL_HapticUnpause *SDL_HapticUnpause;
extern tSDL_HapticStopAll *SDL_HapticStopAll;
extern tSDL_HapticRumbleSupported *SDL_HapticRumbleSupported;
extern tSDL_HapticRumbleInit *SDL_HapticRumbleInit;
extern tSDL_HapticRumblePlay *SDL_HapticRumblePlay;
extern tSDL_HapticRumbleStop *SDL_HapticRumbleStop;
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif
| 3,654 |
513 | {
"family": "Athiti",
"variants": ["200", "300", "regular", "500", "600", "700"],
"subsets": ["latin", "latin-ext", "thai", "vietnamese"],
"version": "v5",
"lastModified": "2020-07-23",
"files": {
"200": "http://fonts.gstatic.com/s/athiti/v5/pe0sMISdLIZIv1wAxDNyAv2-C99ycg.ttf",
"300": "http://fonts.gstatic.com/s/athiti/v5/pe0sMISdLIZIv1wAoDByAv2-C99ycg.ttf",
"500": "http://fonts.gstatic.com/s/athiti/v5/pe0sMISdLIZIv1wA-DFyAv2-C99ycg.ttf",
"600": "http://fonts.gstatic.com/s/athiti/v5/pe0sMISdLIZIv1wA1DZyAv2-C99ycg.ttf",
"700": "http://fonts.gstatic.com/s/athiti/v5/pe0sMISdLIZIv1wAsDdyAv2-C99ycg.ttf",
"regular": "http://fonts.gstatic.com/s/athiti/v5/pe0vMISdLIZIv1w4DBhWCtaiAg.ttf"
},
"category": "sans-serif",
"kind": "webfonts#webfont"
}
| 426 |
6,451 | from great_expectations.core.usage_statistics.anonymizers.anonymizer import Anonymizer
from great_expectations.core.usage_statistics.anonymizers.store_backend_anonymizer import (
StoreBackendAnonymizer,
)
from great_expectations.data_context.store import (
CheckpointStore,
ConfigurationStore,
EvaluationParameterStore,
ExpectationsStore,
HtmlSiteStore,
MetricStore,
Store,
ValidationsStore,
)
class StoreAnonymizer(Anonymizer):
def __init__(self, salt=None):
super().__init__(salt=salt)
# ordered bottom up in terms of inheritance order
self._ge_classes = [
CheckpointStore,
ValidationsStore,
ExpectationsStore,
EvaluationParameterStore,
MetricStore,
ConfigurationStore,
Store,
HtmlSiteStore,
]
self._store_backend_anonymizer = StoreBackendAnonymizer(salt=salt)
def anonymize_store_info(self, store_name, store_obj):
anonymized_info_dict = {}
anonymized_info_dict["anonymized_name"] = self.anonymize(store_name)
store_backend_obj = store_obj.store_backend
self.anonymize_object_info(
object_=store_obj,
anonymized_info_dict=anonymized_info_dict,
ge_classes=self._ge_classes,
)
anonymized_info_dict[
"anonymized_store_backend"
] = self._store_backend_anonymizer.anonymize_store_backend_info(
store_backend_obj=store_backend_obj
)
return anonymized_info_dict
def is_parent_class_recognized(self, store_obj):
return self._is_parent_class_recognized(
classes_to_check=self._ge_classes, object_=store_obj
)
| 778 |
3,182 | <reponame>Tasemo/intellij-community
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class DefaultPrivateFieldTest {
private int a = 0;
private String b = "";
public static void main(String[] args) throws Exception {
Field field = DefaultPrivateFieldTest.class.getDeclaredField("a");
System.out.println(Modifier.isPrivate(field.getModifiers()));
}
}
| 124 |
348 | <filename>docs/data/leg-t2/061/06102342.json
{"nom":"Rai","circ":"2ème circonscription","dpt":"Orne","inscrits":1080,"abs":582,"votants":498,"blancs":45,"nuls":11,"exp":442,"res":[{"nuance":"LR","nom":"<NAME>","voix":229},{"nuance":"REM","nom":"<NAME>","voix":213}]} | 109 |
4,879 | #import "MWMTableViewCell.h"
@protocol MWMPlacePageOpeningHoursCellProtocol <NSObject>
- (BOOL)forcedButton;
- (BOOL)isPlaceholder;
- (BOOL)isEditor;
- (BOOL)openingHoursCellExpanded;
- (void)setOpeningHoursCellExpanded:(BOOL)openingHoursCellExpanded;
@end
@interface MWMPlacePageOpeningHoursCell : MWMTableViewCell
@property (nonatomic, readonly) BOOL isClosed;
- (void)configWithDelegate:(id<MWMPlacePageOpeningHoursCellProtocol>)delegate
info:(NSString *)info;
- (CGFloat)cellHeight;
@end
| 200 |
588 | <reponame>fmilano/CppMicroServices<filename>compendium/DeclarativeServices/test/TestServiceMetadataParserV1.cpp
/*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include "../src/metadata/MetadataParserFactory.hpp"
#include "../src/metadata/MetadataParserImpl.hpp"
#include "../src/metadata/ServiceMetadata.hpp"
#include "Mocks.hpp"
#include "gtest/gtest.h"
#include <cppmicroservices/FrameworkEvent.h>
#include <cppmicroservices/FrameworkFactory.h>
using cppmicroservices::AnyMap;
using cppmicroservices::scrimpl::FakeLogger;
using cppmicroservices::scrimpl::metadata::MetadataParserFactory;
using cppmicroservices::scrimpl::metadata::MetadataParserImplV1;
using cppmicroservices::scrimpl::metadata::ServiceMetadata;
namespace {
// Classes derive from this to provide input test cases
struct TestInputs
{
const AnyMap& operator[](std::size_t i) const { return metadatas[i]; }
std::vector<AnyMap> metadatas;
};
// An instance of this class represents a test case.
// For the inputs in ValidInputs corresponding to the index metadataIndex,
// the members of the parsed metadata are expected to be the ones provided
// in the constructor.
struct ServiceMetadataParserValidState
{
ServiceMetadataParserValidState(std::size_t _metadataIndex,
std::string _serviceScope,
std::vector<std::string> _interfaces)
: metadataIndex(_metadataIndex)
, serviceScope(_serviceScope)
, interfaces(_interfaces)
{}
std::size_t metadataIndex;
std::string serviceScope;
std::vector<std::string> interfaces;
friend std::ostream& operator<<(std::ostream& os,
const ServiceMetadataParserValidState& obj)
{
os << "Metadata Index: " << obj.metadataIndex
<< " service scope: " << obj.serviceScope << " interfaces: [ ";
std::for_each(
obj.interfaces.begin(),
obj.interfaces.end(),
[&os](const std::string& interface) { os << interface << " "; });
return os << "]\n";
}
};
class ValidServiceMetadataTest
: public ::testing::TestWithParam<ServiceMetadataParserValidState>
{
public:
std::shared_ptr<FakeLogger> GetLogger() { return logger; }
protected:
std::shared_ptr<FakeLogger> logger;
virtual void SetUp() { logger = std::make_shared<FakeLogger>(); }
};
// Valid service metadata inputs
struct ValidInputs : public TestInputs
{
ValidInputs()
{
// CheckWithInterfaceNoScope
std::vector<cppmicroservices::Any> interfaces{
cppmicroservices::Any(std::string("Interface1")),
cppmicroservices::Any(std::string("Interface2"))
};
metadatas.push_back(
AnyMap(std::unordered_map<std::string, cppmicroservices::Any>(
{ { "interfaces", cppmicroservices::Any(interfaces) } })));
// CheckWithInterfaceAndScope_SINGLETON
metadatas.push_back(
AnyMap(std::unordered_map<std::string, cppmicroservices::Any>(
{ { "interfaces", cppmicroservices::Any(interfaces) },
{ "scope", cppmicroservices::Any(std::string("singleton")) } })));
// CheckWithInterfaceAndScope_PROTOTYPE
metadatas.push_back(
AnyMap(std::unordered_map<std::string, cppmicroservices::Any>(
{ { "interfaces", cppmicroservices::Any(interfaces) },
{ "scope", cppmicroservices::Any(std::string("prototype")) } })));
// CheckWithInterfaceAndScope_BUNDLE
metadatas.push_back(
AnyMap(std::unordered_map<std::string, cppmicroservices::Any>(
{ { "interfaces", cppmicroservices::Any(interfaces) },
{ "scope", cppmicroservices::Any(std::string("bundle")) } })));
}
};
TEST_P(ValidServiceMetadataTest, TestServiceMetadataSuccessModes)
{
ServiceMetadataParserValidState smvs = GetParam();
auto inputs = ValidInputs();
std::size_t i = smvs.metadataIndex;
MetadataParserImplV1 metadataparser(GetLogger());
auto prop = metadataparser.CreateServiceMetadata(inputs[i]);
ASSERT_EQ(prop.scope, smvs.serviceScope);
ASSERT_THAT(prop.interfaces, ::testing::ContainerEq(smvs.interfaces));
}
INSTANTIATE_TEST_SUITE_P(
SuccessModes,
ValidServiceMetadataTest,
testing::Values(
ServiceMetadataParserValidState(0,
"singleton",
{ "Interface1", "Interface2" }),
ServiceMetadataParserValidState(1,
"singleton",
{ "Interface1", "Interface2" }),
ServiceMetadataParserValidState(2,
"prototype",
{ "Interface1", "Interface2" }),
ServiceMetadataParserValidState(3,
"bundle",
{ "Interface1", "Interface2" })));
// For the metadata in InvalidInputs corresponding to metadataIndex,
// we expect the exception message output by the Metadata Parser to be
// exactly errorOutput. Instead, if we expect the errorOutput to be
// contained in the generated error message, we set isPartial = true. (This
// mode is useful when we don't want to specify really long error messages)
struct ServiceMetadataParserInvalidState
{
ServiceMetadataParserInvalidState(std::size_t _metadataIndex,
std::string _errorOutput,
bool _isPartial = false)
: metadataIndex(_metadataIndex)
, errorOutput(_errorOutput)
, isPartial(_isPartial)
{}
std::size_t metadataIndex;
std::string errorOutput;
bool isPartial;
friend std::ostream& operator<<(std::ostream& os,
const ServiceMetadataParserInvalidState& obj)
{
return os << "";
return os << "Metadata Index: " << obj.metadataIndex
<< " error output: " << obj.errorOutput
<< " Perform partial match: " << (obj.isPartial ? "Yes" : "No")
<< "\n";
}
};
class InvalidServiceMetadataTest
: public ::testing::TestWithParam<ServiceMetadataParserInvalidState>
{
public:
std::shared_ptr<FakeLogger> GetLogger() { return logger; }
protected:
std::shared_ptr<FakeLogger> logger;
virtual void SetUp() { logger = std::make_shared<FakeLogger>(); }
};
struct InvalidInputs : public TestInputs
{
InvalidInputs()
{
// ConstructorWithNoInterface
metadatas.push_back(
AnyMap(std::unordered_map<std::string, cppmicroservices::Any>(
{ { std::string("scope"),
cppmicroservices::Any(std::string("prototype")) } })));
// ConstructorWithInterfaceAndInvalidScope
std::vector<cppmicroservices::Any> interfaces{
cppmicroservices::Any(std::string("Interface1")),
cppmicroservices::Any(std::string("Interface2"))
};
metadatas.push_back(
AnyMap(std::unordered_map<std::string, cppmicroservices::Any>(
{ { std::string("interfaces"), cppmicroservices::Any(interfaces) },
{ std::string("scope"),
cppmicroservices::Any(std::string("foobar")) } })));
// ConstructorWithInterfaceAndIllegalScope
metadatas.push_back(
AnyMap(std::unordered_map<std::string, cppmicroservices::Any>(
{ { std::string("interfaces"), cppmicroservices::Any(interfaces) },
{ std::string("scope"), cppmicroservices::Any(42) } })));
// ConstructorWithIllegalInterface
interfaces = { cppmicroservices::Any(true) };
metadatas.push_back(
AnyMap(std::unordered_map<std::string, cppmicroservices::Any>(
{ { std::string("interfaces"), cppmicroservices::Any(interfaces) } })));
}
};
TEST_P(InvalidServiceMetadataTest, TestServiceMetadataFailureModes)
{
ServiceMetadataParserInvalidState smis = GetParam();
auto inputs = InvalidInputs();
std::size_t i = smis.metadataIndex;
try {
MetadataParserImplV1 metadataparser(GetLogger());
auto sMetadata = metadataparser.CreateServiceMetadata(inputs[i]);
FAIL() << "This failure suggests that parsing has succeeded. "
"Shouldn't happen for failure mode tests";
} catch (const std::exception& err) {
std::string exceptionMsg{ err.what() };
if (!smis.isPartial) {
ASSERT_THAT(exceptionMsg, ::testing::StrEq(smis.errorOutput));
} else {
ASSERT_THAT(exceptionMsg, ::testing::HasSubstr(smis.errorOutput));
}
}
}
INSTANTIATE_TEST_SUITE_P(
FailureModes,
InvalidServiceMetadataTest,
testing::Values(ServiceMetadataParserInvalidState(
0,
"Missing key 'interfaces' in the manifest."),
ServiceMetadataParserInvalidState(
1,
"Invalid value 'foobar'. The valid choices are : [bundle, "
"prototype, singleton]."),
ServiceMetadataParserInvalidState(
2,
"Unexpected type for the name 'scope'. Exception: "
"cppmicroservices::BadAnyCastException",
/*isPartial=*/true),
ServiceMetadataParserInvalidState(
3,
"Exception: cppmicroservices::BadAnyCastException:",
/*isPartial=*/true)));
}
| 3,867 |
841 | package cgeo.geocaching.filters.core;
import cgeo.geocaching.R;
import cgeo.geocaching.enumerations.CacheAttribute;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.storage.SqlBuilder;
import cgeo.geocaching.utils.LocalizationUtils;
import cgeo.geocaching.utils.expressions.ExpressionConfig;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.BooleanUtils;
public class AttributesGeocacheFilter extends BaseGeocacheFilter {
private static final String CONFIG_KEY_INVERSE = "inverse";
private final Map<String, String> attributes = new HashMap<>();
private final Set<String> attributesRaw = new HashSet<>();
private boolean inverse = false;
public void setAttributes(final Map<CacheAttribute, Boolean> atts) {
this.attributes.clear();
this.attributesRaw.clear();
for (Map.Entry<CacheAttribute, Boolean> entry : atts.entrySet()) {
if (entry.getValue() != null) {
this.attributes.put(entry.getKey().getValue(entry.getValue()), entry.getValue() ? entry.getKey().rawName : null);
if (entry.getValue()) {
attributesRaw.add(entry.getKey().rawName);
}
}
}
}
public void setInverse(final boolean inverse) {
this.inverse = inverse;
}
public boolean isInverse() {
return inverse;
}
public Map<CacheAttribute, Boolean> getAttributes() {
final Map<CacheAttribute, Boolean> result = new HashMap<>();
for (String attString : attributes.keySet()) {
final CacheAttribute ca = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attString));
if (ca != null) {
result.put(ca, CacheAttribute.isEnabled(attString));
}
}
return result;
}
@Override
public Boolean filter(final Geocache cache) {
if (cache == null) {
return null;
}
if (attributes.isEmpty()) {
return true;
}
//check if cache attributes are not filled -> means that this filter is inconclusive
if (cache.getAttributes().isEmpty() && !cache.isDetailed()) {
return null;
}
int found = 0;
for (String cacheAtt : cache.getAttributes()) {
if (attributes.containsKey(cacheAtt) || attributesRaw.contains(cacheAtt)) {
found++;
}
}
return inverse != (found == attributes.size());
}
@Override
public boolean isFiltering() {
return !attributes.isEmpty();
}
@Override
public void addToSql(final SqlBuilder sqlBuilder) {
if (attributes.isEmpty()) {
sqlBuilder.addWhereTrue();
} else {
if (inverse) {
sqlBuilder.openWhere(SqlBuilder.WhereType.NOT);
}
sqlBuilder.openWhere(SqlBuilder.WhereType.AND);
for (Map.Entry<String, String> att : attributes.entrySet()) {
final String attTableId = sqlBuilder.getNewTableId();
final String whereStart = "EXISTS (SELECT geocode FROM cg_attributes " + attTableId + " WHERE " + attTableId + ".geocode = " + sqlBuilder.getMainTableId() + ".geocode AND attribute ";
if (att.getValue() == null) {
sqlBuilder.addWhere(whereStart + " = ?)", att.getKey());
} else {
sqlBuilder.addWhere(whereStart + " IN (?, ?))", att.getKey(), att.getValue());
}
}
sqlBuilder.closeWhere();
if (inverse) {
sqlBuilder.closeWhere();
}
}
}
@Override
public void setConfig(final ExpressionConfig config) {
this.inverse = config.getFirstValue(CONFIG_KEY_INVERSE, false, BooleanUtils::toBoolean);
attributes.clear();
attributesRaw.clear();
for (String value : config.getDefaultList()) {
final CacheAttribute ca = CacheAttribute.getByName(value);
if (ca != null) {
final boolean isYesValue = CacheAttribute.isEnabled(value);
attributes.put(value, isYesValue ? ca.rawName : null);
if (isYesValue) {
attributesRaw.add(ca.rawName);
}
}
}
}
@Override
public ExpressionConfig getConfig() {
final ExpressionConfig config = new ExpressionConfig();
config.putList(CONFIG_KEY_INVERSE, Boolean.toString(inverse));
config.putDefaultList(new ArrayList<>(attributes.keySet()));
return config;
}
@Override
protected String getUserDisplayableConfig() {
if (attributes.isEmpty()) {
return LocalizationUtils.getString(R.string.cache_filter_userdisplay_none);
}
if (attributes.size() > 1) {
return LocalizationUtils.getPlural(R.plurals.cache_filter_userdisplay_multi_item, attributes.size());
}
return attributes.keySet().iterator().next();
}
}
| 2,236 |
516 | #include "mdns.hpp"
#include "mdns_utils.hpp"
#include "txt_record_ref.hpp"
using namespace v8;
using namespace node;
namespace node_mdns {
NAN_METHOD(TXTRecordGetLength) {
if (argumentCountMismatch(info, 1)) {
return throwArgumentCountMismatchException(info, 1);
}
if ( ! info[0]->IsObject() || ! TxtRecordRef::HasInstance(ToObject(info[0]))) {
return throwTypeError("argument 1 must be a buffer (txtRecord)");
}
TxtRecordRef * ref = Nan::ObjectWrap::Unwrap<TxtRecordRef>(ToObject(info[0]));
uint16_t result = ::TXTRecordGetLength( & ref->GetTxtRecordRef());
info.GetReturnValue().Set(result);
}
} // end of namespace node_mdns
| 266 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.security.keyvault.keys.cryptography;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Map;
import java.util.Objects;
class SecretProperties {
private final ClientLogger logger = new ClientLogger(SecretProperties.class);
/*
* The secret id.
*/
String id;
/*
* The secret version.
*/
String version;
/*
* Determines whether the object is enabled.
*/
Boolean enabled;
/*
* Not before date in UTC.
*/
OffsetDateTime notBefore;
/*
* Expiry date in UTC.
*/
OffsetDateTime expiresOn;
/*
* Creation time in UTC.
*/
OffsetDateTime createdOn;
/*
* Last updated time in UTC.
*/
OffsetDateTime updatedOn;
/*
* The secret name.
*/
String name;
/*
* Reflects the deletion recovery level currently in effect for secrets in
* the current vault. If it contains 'Purgeable', the secret can be
* permanently deleted by a privileged user; otherwise, only the system can
* purge the secret, at the end of the retention interval. Possible values
* include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable',
* 'Recoverable+ProtectedSubscription'.
*/
String recoveryLevel;
/*
* The content type of the secret.
*/
@JsonProperty(value = "contentType")
String contentType;
/*
* Application specific metadata in the form of key-value pairs.
*/
@JsonProperty(value = "tags")
Map<String, String> tags;
/*
* If this is a secret backing a KV certificate, then this field specifies
* the corresponding key backing the KV certificate.
*/
@JsonProperty(value = "kid", access = JsonProperty.Access.WRITE_ONLY)
String keyId;
/*
* True if the secret's lifetime is managed by key vault. If this is a
* secret backing a certificate, then managed will be true.
*/
@JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY)
Boolean managed;
SecretProperties(String secretName) {
this.name = secretName;
}
/*
* Creates empty instance of SecretProperties.
*/
SecretProperties() { }
/*
* Get the secret name.
*
* @return the name of the secret.
*/
String getName() {
return this.name;
}
/*
* Get the recovery level of the secret.
* @return the recoveryLevel of the secret.
*/
String getRecoveryLevel() {
return recoveryLevel;
}
/*
* Get the enabled value.
*
* @return the enabled value
*/
Boolean isEnabled() {
return this.enabled;
}
/**
* The number of days a secret is retained before being deleted for a soft delete-enabled Key Vault.
*/
@JsonProperty(value = "recoverableDays", access = JsonProperty.Access.WRITE_ONLY)
private Integer recoverableDays;
/*
* Set the enabled value.
*
* @param enabled The enabled value to set
* @throws NullPointerException if {@code enabled} is null.
* @return the SecretProperties object itself.
*/
SecretProperties setEnabled(Boolean enabled) {
Objects.requireNonNull(enabled);
this.enabled = enabled;
return this;
}
/*
* Get the notBefore UTC time.
*
* @return the notBefore UTC time.
*/
OffsetDateTime getNotBefore() {
return notBefore;
}
/**
* Gets the number of days a secret is retained before being deleted for a soft delete-enabled Key Vault.
* @return the recoverable days.
*/
public Integer getRecoverableDays() {
return recoverableDays;
}
/*
* Set the {@link OffsetDateTime notBefore} UTC time.
*
* @param notBefore The notBefore UTC time to set
* @return the SecretProperties object itself.
*/
SecretProperties setNotBefore(OffsetDateTime notBefore) {
this.notBefore = notBefore;
return this;
}
/*
* Get the Secret Expiry time in UTC.
*
* @return the expires UTC time.
*/
OffsetDateTime getExpiresOn() {
if (this.expiresOn == null) {
return null;
}
return this.expiresOn;
}
/*
* Set the {@link OffsetDateTime expires} UTC time.
*
* @param expiresOn The expiry time to set for the secret.
* @return the SecretProperties object itself.
*/
SecretProperties setExpiresOn(OffsetDateTime expiresOn) {
this.expiresOn = expiresOn;
return this;
}
/*
* Get the the UTC time at which secret was created.
*
* @return the created UTC time.
*/
OffsetDateTime getCreatedOn() {
return createdOn;
}
/*
* Get the UTC time at which secret was last updated.
*
* @return the last updated UTC time.
*/
OffsetDateTime getUpdatedOn() {
return updatedOn;
}
/*
* Get the secret identifier.
*
* @return the secret identifier.
*/
String getId() {
return this.id;
}
/*
* Get the content type.
*
* @return the content type.
*/
String getContentType() {
return this.contentType;
}
/*
* Set the contentType.
*
* @param contentType The contentType to set
* @return the updated SecretProperties object itself.
*/
SecretProperties setContentType(String contentType) {
this.contentType = contentType;
return this;
}
/*
* Get the tags associated with the secret.
*
* @return the value of the tags.
*/
Map<String, String> getTags() {
return this.tags;
}
/*
* Set the tags to be associated with the secret.
*
* @param tags The tags to set
* @return the updated SecretProperties object itself.
*/
SecretProperties setTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
/*
* Get the keyId identifier.
*
* @return the keyId identifier.
*/
String getKeyId() {
return this.keyId;
}
/*
* Get the managed value.
*
* @return the managed value
*/
Boolean isManaged() {
return this.managed;
}
/*
* Get the version of the secret.
*
* @return the version of the secret.
*/
String getVersion() {
return this.version;
}
/*
* Unpacks the attributes json response and updates the variables in the Secret Attributes object.
* Uses Lazy Update to set values for variables id, tags, contentType, managed and keyId as these variables are
* part of main json body and not attributes json body when the secret response comes from list Secrets operations.
* @param attributes The key value mapping of the Secret attributes
*/
@JsonProperty("attributes")
@SuppressWarnings("unchecked")
void unpackAttributes(Map<String, Object> attributes) {
this.enabled = (Boolean) attributes.get("enabled");
this.notBefore = epochToOffsetDateTime(attributes.get("nbf"));
this.expiresOn = epochToOffsetDateTime(attributes.get("exp"));
this.createdOn = epochToOffsetDateTime(attributes.get("created"));
this.updatedOn = epochToOffsetDateTime(attributes.get("updated"));
this.recoveryLevel = (String) attributes.get("recoveryLevel");
this.contentType = (String) lazyValueSelection(attributes.get("contentType"), this.contentType);
this.keyId = (String) lazyValueSelection(attributes.get("keyId"), this.keyId);
this.tags = (Map<String, String>) lazyValueSelection(attributes.get("tags"), this.tags);
this.managed = (Boolean) lazyValueSelection(attributes.get("managed"), this.managed);
this.recoverableDays = (Integer) attributes.get("recoverableDays");
unpackId((String) attributes.get("id"));
}
@JsonProperty(value = "id")
void unpackId(String id) {
if (id != null && id.length() > 0) {
this.id = id;
try {
URL url = new URL(id);
String[] tokens = url.getPath().split("/");
this.name = (tokens.length >= 3 ? tokens[2] : null);
this.version = (tokens.length >= 4 ? tokens[3] : null);
} catch (MalformedURLException e) {
// Should never come here.
logger.error("Received Malformed Secret Id URL from KV Service");
}
}
}
private OffsetDateTime epochToOffsetDateTime(Object epochValue) {
if (epochValue != null) {
Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L);
return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
}
return null;
}
private Object lazyValueSelection(Object input1, Object input2) {
if (input1 == null) {
return input2;
}
return input1;
}
}
| 3,658 |
623 | /*---------------------------------------------------------------------------*/
// Author : hiyohiyo
// Mail : <EMAIL>
// Web : https://crystalmark.info/
// License : The MIT License
/*---------------------------------------------------------------------------*/
#pragma once
#include "CommonFx.h"
#include <atlimage.h>
#include <gdiplus.h>
#pragma comment(lib, "Gdiplus.lib")
using namespace Gdiplus;
class CSliderCtrlFx : public CSliderCtrl
{
DECLARE_DYNAMIC(CSliderCtrlFx)
public:
CSliderCtrlFx();
virtual ~CSliderCtrlFx();
BOOL InitControl(int x, int y, int width, int height, double zoomRatio, CDC* bkDC, int renderMode, BOOL bHighContrast, BOOL bDarkMode, int min, int max, int pos);
BOOL m_bHighContrast;
CBrush m_BkBrush;
protected:
// Image
void SetBkReload(void);
void LoadCtrlBk(CDC* drawDC);
int m_X;
int m_Y;
CSize m_CtrlSize;
CRect m_Margin;
int m_RenderMode;
BOOL m_bDarkMode;
// Image
CDC* m_BkDC;
CBitmap m_BkBitmap;
BOOL m_bBkBitmapInit;
BOOL m_bBkLoad;
CBitmap m_CtrlBitmap;
CImage m_CtrlImage;
};
| 427 |
614 | <reponame>fengjixuchui/AndroidQuick<gh_stars>100-1000
package com.androidwind.androidquick.demo.features.module.ioc.dagger2;
/**
* @author ddnosh
* @website http://blog.csdn.net/ddnosh
*/
import dagger.Component;
import com.androidwind.androidquick.demo.injector.FragmentScope;
@FragmentScope
@Component
public interface Test1Component {
// void inject(Dagger2Fragment dagger2Fragment);
}
| 141 |
835 | <reponame>CaptEmulation/modeldb
# THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class ModeldbHydratedProject(BaseType):
def __init__(self, project=None, collaborator_user_infos=None, owner_user_info=None, allowed_actions=None):
required = {
"project": False,
"collaborator_user_infos": False,
"owner_user_info": False,
"allowed_actions": False,
}
self.project = project
self.collaborator_user_infos = collaborator_user_infos
self.owner_user_info = owner_user_info
self.allowed_actions = allowed_actions
for k, v in required.items():
if self[k] is None and v:
raise ValueError('attribute {} is required'.format(k))
@staticmethod
def from_json(d):
from .ModeldbProject import ModeldbProject
from .ModeldbCollaboratorUserInfo import ModeldbCollaboratorUserInfo
from .UacUserInfo import UacUserInfo
from .UacAction import UacAction
tmp = d.get('project', None)
if tmp is not None:
d['project'] = ModeldbProject.from_json(tmp)
tmp = d.get('collaborator_user_infos', None)
if tmp is not None:
d['collaborator_user_infos'] = [ModeldbCollaboratorUserInfo.from_json(tmp) for tmp in tmp]
tmp = d.get('owner_user_info', None)
if tmp is not None:
d['owner_user_info'] = UacUserInfo.from_json(tmp)
tmp = d.get('allowed_actions', None)
if tmp is not None:
d['allowed_actions'] = [UacAction.from_json(tmp) for tmp in tmp]
return ModeldbHydratedProject(**d)
| 590 |
679 | <gh_stars>100-1000
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _FRAMEWORK_SCRIPT_STORAGEBRIDGE_HXX_
#define _FRAMEWORK_SCRIPT_STORAGEBRIDGE_HXX_
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <drafts/com/sun/star/script/framework/storage/XScriptInfoAccess.hpp>
#include "StorageBridgeFactory.hxx"
namespace scripting_runtimemgr
{
// for simplification
#define css ::com::sun::star
#define dcsssf ::drafts::com::sun::star::script::framework
class StorageBridge : public ::cppu::WeakImplHelper1< dcsssf::storage::XScriptInfoAccess >
{
friend class StorageBridgeFactory;
public:
//XScriptInfoAccess
//=========================================================================
/**
* Get the implementations for a given URI
*
* @param queryURI
* The URI to get the implementations for
*
* @return XScriptURI
* The URIs of the implementations
*/
virtual css::uno::Sequence< css::uno::Reference< dcsssf::storage::XScriptInfo > >
SAL_CALL getImplementations(
const ::rtl::OUString& queryURI )
throw ( css::lang::IllegalArgumentException,
css::uno::RuntimeException );
//=========================================================================
/**
* Get the all logical names stored in this storage
*
* @return sequence < ::rtl::OUString >
* The logical names
*/
virtual css::uno::Sequence< ::rtl::OUString >
SAL_CALL getScriptLogicalNames()
throw ( css::lang::IllegalArgumentException, css::uno::RuntimeException );
private:
StorageBridge( const css::uno::Reference< css::uno::XComponentContext >& xContext,
sal_Int32 sid );
void initStorage() throw ( css::uno::RuntimeException );
css::uno::Reference< css::uno::XComponentContext > m_xContext;
css::uno::Reference< dcsssf::storage::XScriptInfoAccess > m_xScriptInfoAccess;
sal_Int32 m_sid;
};
}
#endif //_COM_SUN_STAR_SCRIPTING_STORAGEBRIDGE_HXX_
| 953 |
626 | /*
* Copyright 2017, OpenCensus Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opencensus.benchmarks.trace;
import static com.google.common.base.Preconditions.checkState;
import io.opencensus.trace.AttributeValue;
import io.opencensus.trace.BlankSpan;
import io.opencensus.trace.Link;
import io.opencensus.trace.MessageEvent.Type;
import io.opencensus.trace.Span;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.samplers.Samplers;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
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;
/** Benchmarks for {@link Span} to record trace events. */
@State(Scope.Benchmark)
public class RecordTraceEventsBenchmark {
private static final String SPAN_NAME = "MySpanName";
private static final String ANNOTATION_DESCRIPTION = "MyAnnotation";
private static final String ATTRIBUTE_KEY = "MyAttributeKey";
private static final String ATTRIBUTE_VALUE = "MyAttributeValue";
@State(Scope.Benchmark)
public static class Data {
private Span linkedSpan = BlankSpan.INSTANCE;
private Span span = BlankSpan.INSTANCE;
@Param({"impl", "impl-lite"})
String implementation;
@Param({"true", "false"})
boolean sampled;
@Setup
public void setup() {
Tracer tracer = BenchmarksUtil.getTracer(implementation);
linkedSpan =
tracer
.spanBuilderWithExplicitParent(SPAN_NAME, null)
.setSampler(sampled ? Samplers.alwaysSample() : Samplers.neverSample())
.startSpan();
span =
tracer
.spanBuilderWithExplicitParent(SPAN_NAME, null)
.setSampler(sampled ? Samplers.alwaysSample() : Samplers.neverSample())
.startSpan();
}
@TearDown
public void doTearDown() {
checkState(linkedSpan != BlankSpan.INSTANCE, "Uninitialized linkedSpan");
checkState(span != BlankSpan.INSTANCE, "Uninitialized span");
linkedSpan.end();
span.end();
}
}
/** This benchmark attempts to measure performance of adding an attribute to the span. */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span putAttribute(Data data) {
data.span.putAttribute(ATTRIBUTE_KEY, AttributeValue.stringAttributeValue(ATTRIBUTE_VALUE));
return data.span;
}
/** This benchmark attempts to measure performance of adding an annotation to the span. */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span addAnnotation(Data data) {
data.span.addAnnotation(ANNOTATION_DESCRIPTION);
return data.span;
}
/** This benchmark attempts to measure performance of adding a network event to the span. */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span addMessageEvent(Data data) {
data.span.addMessageEvent(
io.opencensus.trace.MessageEvent.builder(Type.RECEIVED, 1)
.setUncompressedMessageSize(3)
.build());
return data.span;
}
/** This benchmark attempts to measure performance of adding a link to the span. */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span addLink(Data data) {
data.span.addLink(
Link.fromSpanContext(data.linkedSpan.getContext(), Link.Type.PARENT_LINKED_SPAN));
return data.span;
}
}
| 1,500 |
348 | from rest_framework.generics import ListAPIView
from rest_framework.permissions import AllowAny
from tags.api.serializers import TagSerializer
class TagListAPIView(ListAPIView):
serializer_class = TagSerializer
queryset = serializer_class.Meta.model.objects.all()
permission_classes = [AllowAny]
| 96 |
310 | <reponame>orekyuu/doma
package org.seasar.doma.internal.expr.node;
public class ExpressionLocation {
protected final String expression;
protected final int position;
public ExpressionLocation(String expression, int position) {
this.expression = expression;
this.position = position;
}
public String getExpression() {
return expression;
}
public int getPosition() {
return position;
}
@Override
public String toString() {
return expression + ":" + position;
}
}
| 151 |
588 | /*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include "cppmicroservices/ServiceObjects.h"
#include "cppmicroservices/BundleContext.h"
#include "cppmicroservices/Framework.h"
#include "cppmicroservices/FrameworkFactory.h"
#include "gtest/gtest.h"
using namespace cppmicroservices;
struct ITestServiceA
{
virtual ~ITestServiceA() {}
};
TEST(ServiceObjectsTest, TestServiceObjects)
{
struct TestServiceA : public ITestServiceA
{};
FrameworkFactory factory;
auto framework = factory.NewFramework();
framework.Start();
auto context = framework.GetBundleContext();
auto s1 = std::make_shared<TestServiceA>();
ServiceRegistration<ITestServiceA> reg1 =
context.RegisterService<ITestServiceA>(s1);
auto ref = context.GetServiceReference("ITestServiceA");
ServiceObjects<void> serviceObject = context.GetServiceObjects(ref);
ASSERT_TRUE(serviceObject.GetService() != nullptr);
auto invalid_ref = context.GetServiceReference("InvalidService");
ASSERT_THROW(context.GetServiceObjects(invalid_ref), std::invalid_argument);
auto ref_from_so = serviceObject.GetServiceReference();
ASSERT_TRUE(ref_from_so);
// Move ctor and assignment
ServiceObjects<void> serviceObjMove(std::move(serviceObject));
ASSERT_TRUE(serviceObjMove.GetServiceReference());
serviceObjMove = context.GetServiceObjects(ref_from_so);
ASSERT_TRUE(serviceObjMove.GetServiceReference());
// verify GetService returns null after service unregistration
reg1.Unregister();
ASSERT_TRUE(serviceObjMove.GetService() == nullptr);
}
| 664 |
681 | # global
import numpy as np
import tensorflow as tf
from typing import Union, Tuple, List
from tensorflow.python.types.core import Tensor
from tensorflow.python.framework.dtypes import DType
# local
import ivy
def can_cast(from_: Union[tf.DType, Tensor], to: tf.DType) -> bool:
if isinstance(from_, Tensor):
from_ = from_.dtype
from_str = str(from_)
to_str = str(to)
if ivy.dtype_bits(to) < ivy.dtype_bits(from_):
return False
if "'int" in from_str and "uint" in to_str:
return False
if "bool" in from_str and (("int" in to_str) or ("float" in to_str)):
return False
if "int" in from_str and (("float" in to_str) or ("bool" in to_str)):
return False
if "float" in from_str and "bool" in to_str:
return False
if "float" in from_str and "int" in to_str:
return False
if "uint" in from_str and "'int" in to_str:
if ivy.dtype_bits(to) <= ivy.dtype_bits(from_):
return False
return True
ivy_dtype_dict = {
tf.int8: "int8",
tf.int16: "int16",
tf.int32: "int32",
tf.int64: "int64",
tf.uint8: "uint8",
tf.uint16: "uint16",
tf.uint32: "uint32",
tf.uint64: "uint64",
tf.bfloat16: "bfloat16",
tf.float16: "float16",
tf.float32: "float32",
tf.float64: "float64",
tf.bool: "bool",
}
native_dtype_dict = {
"int8": tf.int8,
"int16": tf.int16,
"int32": tf.int32,
"int64": tf.int64,
"uint8": tf.uint8,
"uint16": tf.uint16,
"uint32": tf.uint32,
"uint64": tf.uint64,
"bfloat16": tf.bfloat16,
"float16": tf.float16,
"float32": tf.float32,
"float64": tf.float64,
"bool": tf.bool,
}
# noinspection PyShadowingBuiltins
def iinfo(type: Union[DType, str, Tensor]) -> np.iinfo:
return tf.experimental.numpy.iinfo(ivy.as_ivy_dtype(type))
class Finfo:
def __init__(self, tf_finfo):
self._tf_finfo = tf_finfo
@property
def bits(self):
return self._tf_finfo.bits
@property
def eps(self):
return float(self._tf_finfo.eps)
@property
def max(self):
return float(self._tf_finfo.max)
@property
def min(self):
return float(self._tf_finfo.min)
@property
def smallest_normal(self):
return float(self._tf_finfo.tiny)
# noinspection PyShadowingBuiltins
def finfo(type: Union[DType, str, Tensor]) -> Finfo:
return Finfo(tf.experimental.numpy.finfo(ivy.as_native_dtype(type)))
def result_type(*arrays_and_dtypes: Union[Tensor, tf.DType]) -> tf.DType:
if len(arrays_and_dtypes) <= 1:
return tf.experimental.numpy.result_type(arrays_and_dtypes)
result = tf.experimental.numpy.result_type(
arrays_and_dtypes[0], arrays_and_dtypes[1]
)
for i in range(2, len(arrays_and_dtypes)):
result = tf.experimental.numpy.result_type(result, arrays_and_dtypes[i])
return result
def broadcast_to(x: Tensor, shape: Tuple[int, ...]) -> Tensor:
return tf.broadcast_to(x, shape)
def broadcast_arrays(*arrays: Tensor) -> List[Tensor]:
if len(arrays) > 1:
desired_shape = tf.broadcast_dynamic_shape(arrays[0].shape, arrays[1].shape)
if len(arrays) > 2:
for i in range(2, len(arrays)):
desired_shape = tf.broadcast_dynamic_shape(
desired_shape, arrays[i].shape
)
else:
return [arrays[0]]
result = []
for tensor in arrays:
result.append(tf.broadcast_to(tensor, desired_shape))
return result
def astype(x: Tensor, dtype: tf.DType, copy: bool = True) -> Tensor:
dtype = ivy.as_native_dtype(dtype)
if copy:
if x.dtype == dtype:
new_tensor = tf.experimental.numpy.copy(x)
return new_tensor
else:
if x.dtype == dtype:
return x
else:
new_tensor = tf.experimental.numpy.copy(x)
new_tensor = tf.cast(new_tensor, dtype)
return new_tensor
return tf.cast(x, dtype)
def dtype_bits(dtype_in):
dtype_str = as_ivy_dtype(dtype_in)
if "bool" in dtype_str:
return 1
return int(
dtype_str.replace("tf.", "")
.replace("uint", "")
.replace("int", "")
.replace("bfloat", "")
.replace("float", "")
)
def dtype(x, as_native=False):
if as_native:
return ivy.to_native(x).dtype
return as_ivy_dtype(x.dtype)
def as_ivy_dtype(dtype_in):
if isinstance(dtype_in, str):
return ivy.Dtype(dtype_in)
return ivy.Dtype(ivy_dtype_dict[dtype_in])
def as_native_dtype(dtype_in):
if not isinstance(dtype_in, str):
return dtype_in
return native_dtype_dict[ivy.Dtype(dtype_in)]
| 2,232 |
5,411 | <filename>code/components/rage-formats-x/include/convert/phBound_five_rdr3.h<gh_stars>1000+
/*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#pragma once
#include <string>
#define RAGE_FORMATS_GAME rdr3
#define RAGE_FORMATS_GAME_RDR3
#include <phBound.h>
#undef RAGE_FORMATS_GAME_RDR3
#define RAGE_FORMATS_GAME five
#define RAGE_FORMATS_GAME_FIVE
#include <phBound.h>
#include <convert/base.h>
#include <map>
#include <vector>
inline float g_boundOffset[2];
namespace rage
{
static inline void fillBaseBound(rdr3::phBound* out, five::phBound* in)
{
auto& centroid = in->GetCentroid();
out->SetCentroid(rdr3::phVector3(centroid.x + g_boundOffset[0], centroid.y + g_boundOffset[1], centroid.z));
auto& cg = in->GetCG();
out->SetCG(rdr3::phVector3(cg.x + g_boundOffset[0], cg.y + g_boundOffset[1], cg.z));
auto& aabbMin = in->GetAABBMin();
out->SetAABBMin(rdr3::phVector3(aabbMin.x + g_boundOffset[0], aabbMin.y + g_boundOffset[1], aabbMin.z));
auto& aabbMax = in->GetAABBMax();
out->SetAABBMax(rdr3::phVector3(aabbMax.x + g_boundOffset[0], aabbMax.y + g_boundOffset[1], aabbMax.z));
out->SetRadius(in->GetRadius());
out->SetMargin(in->GetMargin());
}
static rdr3::phBound* convertBoundToFive(five::phBound* bound);
template<>
rdr3::phBoundComposite* convert(five::phBoundComposite* bound)
{
auto out = new (false) rdr3::phBoundComposite;
out->SetBlockMap();
fillBaseBound(out, bound);
out->SetUnkFloat(5.0f);
// convert child bounds
uint16_t childCount = bound->GetNumChildBounds();
std::vector<rdr3::phBound*> children(childCount);
for (uint16_t i = 0; i < childCount; i++)
{
children[i] = convertBoundToFive(bound->GetChildBound(i));
}
out->SetChildBounds(childCount, &children[0]);
#if 0
// convert aux data
std::vector<rdr3::phBoundAABB> childAABBs(childCount);
five::phBoundAABB* inAABBs = bound->GetChildAABBs();
for (uint16_t i = 0; i < childCount; i++)
{
childAABBs[i].min = rdr3::phVector3(inAABBs[i].min.x + g_boundOffset[0], inAABBs[i].min.y + g_boundOffset[1], inAABBs[i].min.z);
childAABBs[i].intUnk = 1;
childAABBs[i].max = rdr3::phVector3(inAABBs[i].max.x + g_boundOffset[0], inAABBs[i].max.y + g_boundOffset[1], inAABBs[i].max.z);
childAABBs[i].floatUnk = 0.005f;
}
out->SetChildAABBs(childCount, &childAABBs[0]);
#endif
// convert matrices
std::vector<rdr3::Matrix3x4> childMatrices(childCount);
five::Matrix3x4* inMatrices = bound->GetChildMatrices();
memcpy(&childMatrices[0], inMatrices, sizeof(rdr3::Matrix3x4) * childCount);
out->SetChildMatrices(childCount, &childMatrices[0]);
// add bound flags
std::vector<rdr3::phBoundFlagEntry> boundFlags(childCount);
for (uint16_t i = 0; i < childCount; i++)
{
boundFlags[i].m_0 = 0x3E;
boundFlags[i].pad = 0;
boundFlags[i].m_4 = 0x7F3BEC0;
boundFlags[i].pad2 = 0;
}
out->SetBoundFlags(childCount, &boundFlags[0]);
return out;
}
static inline void fillPolyhedronBound(rdr3::phBoundPolyhedron* out, five::phBoundPolyhedron* in)
{
auto& quantum = in->GetQuantum();
out->SetQuantum(rdr3::Vector4(quantum.x, quantum.y, quantum.z, /*quantum.w*/ 7.62962742e-008));
auto& offset = in->GetVertexOffset();
out->SetVertexOffset(rdr3::Vector4(offset.x + g_boundOffset[0], offset.y + g_boundOffset[1], offset.z, /*offset.w*/ 0.0025f));
// vertices
five::phBoundVertex* vertices = in->GetVertices();
std::vector<rdr3::phBoundVertex> outVertices(in->GetNumVertices());
memcpy(&outVertices[0], vertices, outVertices.size() * sizeof(*vertices));
out->SetVertices(outVertices.size(), &outVertices[0]);
// polys
five::phBoundPoly* polys = in->GetPolygons();
uint32_t numPolys = in->GetNumPolygons();
std::vector<rdr3::phBoundPoly> outPolys(numPolys);
std::vector<uint8_t> outPolyMaterials(numPolys);
//memcpy(outPolys.data(), in->GetPolygons(), sizeof(rdr3::phBoundPoly) * numPolys);
auto vertToVector = [&](const auto& vertex)
{
return rage::Vector3(
(vertex.x * quantum.x) + offset.x,
(vertex.y * quantum.y) + offset.y,
(vertex.z * quantum.z) + offset.z);
};
auto calculateArea = [&](const rdr3::phBoundPoly& poly)
{
rage::Vector3 v1 = vertToVector(vertices[poly.poly.v1]);
rage::Vector3 v2 = vertToVector(vertices[poly.poly.v2]);
rage::Vector3 v3 = vertToVector(vertices[poly.poly.v3]);
rage::Vector3 d1 = v1 - v2;
rage::Vector3 d2 = v3 - v2;
rage::Vector3 cross = rage::Vector3::CrossProduct(d1, d2);
return cross.Length() / 2.0f;
};
auto inPolys = in->GetPolygons();
for (int i = 0; i < numPolys; i++)
{
if (inPolys[i].type == 0)
{
outPolys[i].poly.v1 = inPolys[i].poly.v1;
outPolys[i].poly.v2 = inPolys[i].poly.v2;
outPolys[i].poly.v3 = inPolys[i].poly.v3;
outPolys[i].poly.e1 = inPolys[i].poly.e1;
outPolys[i].poly.e2 = inPolys[i].poly.e2;
outPolys[i].poly.e3 = inPolys[i].poly.e3;
outPolys[i].poly.triangleArea = calculateArea(outPolys[i]);
outPolys[i].type = 0;
}
else if (inPolys[i].type == 1)
{
outPolys[i].sphere.index = inPolys[i].sphere.index;
outPolys[i].sphere.radius = inPolys[i].sphere.radius;
outPolys[i].type = 1;
}
else if (inPolys[i].type == 2)
{
outPolys[i].capsule.index = inPolys[i].capsule.index;
outPolys[i].capsule.length = inPolys[i].capsule.length;
outPolys[i].capsule.indexB = inPolys[i].capsule.indexB;
outPolys[i].type = 2;
}
else if (inPolys[i].type == 3)
{
memcpy(&outPolys[i].box.indices, &inPolys[i].box.indices, sizeof(inPolys[i].box.indices));
outPolys[i].type = 3;
}
else if (inPolys[i].type == 4)
{
memcpy(&outPolys[i].box.indices, &inPolys[i].box.indices, sizeof(inPolys[i].box.indices));
outPolys[i].type = 4;
}
}
if (((five::phBoundGeometry*)in)->GetPolysToMaterials())
{
memcpy(outPolyMaterials.data(), ((five::phBoundGeometry*)in)->GetPolysToMaterials(), sizeof(uint8_t) * numPolys);
}
out->SetPolys(outPolys.size(), &outPolys[0]);
if (out->GetType() == rdr3::phBoundType::Geometry || out->GetType() == rdr3::phBoundType::BVH)
{
if (!outPolyMaterials.empty())
{
rdr3::phBoundGeometry* geom = static_cast<rdr3::phBoundGeometry*>(out);
geom->SetPolysToMaterials(&outPolyMaterials[0]);
}
}
}
static inline uint8_t ConvertMaterialIndexrdr3(uint8_t index)
{
return index;
}
static inline void fillGeometryBound(rdr3::phBoundGeometry* out, five::phBoundGeometry* in)
{
uint32_t materialColors[] = { 0x208DFFFF };
out->SetMaterialColors(1, materialColors);
std::vector<rdr3::phBoundMaterial> materials(in->GetNumMaterials());
five::phBoundMaterial* inMaterials = in->GetMaterials();
for (int i = 0; i < materials.size(); i++)
{
materials[i].mat1.materialIdx = ConvertMaterialIndexrdr3(inMaterials[i].mat1.materialIdx);
materials[i].mat1.roomId = inMaterials[i].mat1.roomId;
materials[i].mat2.materialColorIdx = 0x1;
}
out->SetMaterials(materials.size(), &materials[0]);
}
template<>
rdr3::phBoundGeometry* convert(five::phBoundGeometry* bound)
{
auto out = new (false) rdr3::phBoundGeometry;
fillBaseBound(out, bound);
fillPolyhedronBound(out, bound);
fillGeometryBound(out, bound);
return out;
}
template<>
rdr3::phBVH* convert(five::phBVH* in)
{
auto out = new (false) rdr3::phBVH;
out->SetAABB(
Vector3(in->m_aabbMin.x, in->m_aabbMin.y, in->m_aabbMin.z),
Vector3(in->m_aabbMax.x, in->m_aabbMax.y, in->m_aabbMax.z));
out->SetBVH(
in->m_nodes.GetCount(),
(rage::rdr3::phBVHNode*)&in->m_nodes.Get(0));
return out;
}
template<>
rdr3::phBoundBVH* convert(five::phBoundBVH* bound)
{
auto out = new (false) rdr3::phBoundBVH;
fillBaseBound(out, bound);
fillPolyhedronBound(out, bound);
fillGeometryBound(out, bound);
out->SetBVH(convert<rdr3::phBVH*>(bound->GetBVH()));
//rdr3::CalculateBVH(out);
return out;
}
template<>
rdr3::phBoundSphere* convert(five::phBoundSphere* bound)
{
auto out = new (false) rdr3::phBoundSphere;
fillBaseBound(out, bound);
return out;
}
template<>
rdr3::phBoundBox* convert(five::phBoundBox* bound)
{
auto out = new (false) rdr3::phBoundBox;
fillBaseBound(out, bound);
//rage::rdr3::phBoundMaterial material = { 0 };
//material.mat1.materialIdx = ConvertMaterialIndex(bound->GetMaterial().mat1.materialIdx);
//out->SetMaterial(material);
return out;
}
template<>
rdr3::phBoundCapsule* convert(five::phBoundCapsule* bound)
{
auto out = new (false) rdr3::phBoundCapsule;
fillBaseBound(out, bound);
return out;
}
static rdr3::phBound* convertBoundToFive(five::phBound* bound)
{
switch (bound->GetType())
{
case five::phBoundType::Sphere:
return convert<rdr3::phBoundSphere*>(static_cast<five::phBoundSphere*>(bound));
case five::phBoundType::Composite:
return convert<rdr3::phBoundComposite*>(static_cast<five::phBoundComposite*>(bound));
case five::phBoundType::Geometry:
return convert<rdr3::phBoundGeometry*>(static_cast<five::phBoundGeometry*>(bound));
case five::phBoundType::BVH:
return convert<rdr3::phBoundBVH*>(static_cast<five::phBoundBVH*>(bound));
case five::phBoundType::Box:
return convert<rdr3::phBoundBox*>(static_cast<five::phBoundBox*>(bound));
case five::phBoundType::Capsule:
return convert<rdr3::phBoundCapsule*>(static_cast<five::phBoundCapsule*>(bound));
}
return nullptr;
}
template<>
rdr3::phBoundComposite* convert(five::phBound* bound)
{
if (bound->GetType() == five::phBoundType::Composite)
{
return (rdr3::phBoundComposite*)convertBoundToFive(bound);
}
auto out = new (false) rdr3::phBoundComposite;
out->SetBlockMap();
auto originalBound = convertBoundToFive(bound);
fillBaseBound(out, bound);
out->SetUnkFloat(5.0f);
// convert child bounds
out->SetChildBounds(1, &originalBound);
#if 0
// convert aux data
rdr3::phBoundAABB aabb;
aabb.min = rdr3::phVector3(bound->GetAABBMin().x + g_boundOffset[0], bound->GetAABBMin().y + g_boundOffset[1], bound->GetAABBMin().z);
aabb.max = rdr3::phVector3(bound->GetAABBMax().x + g_boundOffset[0], bound->GetAABBMax().y + g_boundOffset[1], bound->GetAABBMax().z);
aabb.intUnk = 1;
aabb.floatUnk = 0.005f;
out->SetChildAABBs(1, &aabb);
#endif
// convert matrices
rdr3::Matrix3x4 childMatrix;
childMatrix._1 = { 1.f, 0.f, 0.f };
childMatrix._2 = { 0.f, 1.f, 0.f };
childMatrix._3 = { 0.f, 0.f, 1.f };
childMatrix._4 = { 0.f, 0.f, 0.f };
out->SetChildMatrices(1, &childMatrix);
// add bound flags
rdr3::phBoundFlagEntry boundFlag;
boundFlag.m_0 = 0x3E;
boundFlag.pad = 0;
boundFlag.m_4 = 0x7F3BEC0;
boundFlag.pad2 = 0;
out->SetBoundFlags(1, &boundFlag);
return out;
}
template<>
rdr3::phBoundComposite* convert(five::datOwner<five::phBound>* bound)
{
return convert<rdr3::phBoundComposite*>(bound->GetChild());
}
template<>
rdr3::phBound* convert(five::phBound* bound)
{
return convertBoundToFive(bound);
}
template<>
rdr3::pgDictionary<rdr3::phBound>* convert(five::pgDictionary<five::phBound>* phd)
{
rdr3::pgDictionary<rdr3::phBound>* out = new (false) rdr3::pgDictionary<rdr3::phBound>();
out->SetBlockMap();
rdr3::pgDictionary<rdr3::phBound> newDrawables;
if (phd->GetCount())
{
for (auto& bound : *phd)
{
newDrawables.Add(bound.first, convert<rdr3::phBound*>(bound.second));
}
}
out->SetFrom(&newDrawables);
return out;
}
}
| 4,743 |
355 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from ..builder import (ALGORITHMS, build_backbone, build_head, build_memory,
build_neck)
from .base import BaseModel
@ALGORITHMS.register_module()
class NPID(BaseModel):
"""NPID.
Implementation of `Unsupervised Feature Learning via Non-parametric
Instance Discrimination <https://arxiv.org/abs/1805.01978>`_.
Args:
backbone (dict): Config dict for module of backbone.
neck (dict): Config dict for module of deep features to compact feature
vectors. Defaults to None.
head (dict): Config dict for module of loss functions.
Defaults to None.
memory_bank (dict): Config dict for module of memory banks.
Defaults to None.
neg_num (int): Number of negative samples for each image.
Defaults to 65536.
ensure_neg (bool): If False, there is a small probability
that negative samples contain positive ones. Defaults to False.
"""
def __init__(self,
backbone,
neck=None,
head=None,
memory_bank=None,
neg_num=65536,
ensure_neg=False,
init_cfg=None):
super(NPID, self).__init__(init_cfg)
self.backbone = build_backbone(backbone)
if neck is not None:
self.neck = build_neck(neck)
assert head is not None
self.head = build_head(head)
assert memory_bank is not None
self.memory_bank = build_memory(memory_bank)
self.neg_num = neg_num
self.ensure_neg = ensure_neg
def extract_feat(self, img):
"""Function to extract features from backbone.
Args:
img (Tensor): Input images of shape (N, C, H, W).
Typically these should be mean centered and std scaled.
Returns:
tuple[Tensor]: backbone outputs.
"""
x = self.backbone(img)
return x
def forward_train(self, img, idx, **kwargs):
"""Forward computation during training.
Args:
img (Tensor): Input images of shape (N, C, H, W).
Typically these should be mean centered and std scaled.
idx (Tensor): Index corresponding to each image.
kwargs: Any keyword arguments to be used to forward.
Returns:
dict[str, Tensor]: A dictionary of loss components.
"""
feature = self.extract_feat(img)
idx = idx.cuda()
if self.with_neck:
feature = self.neck(feature)[0]
feature = nn.functional.normalize(feature) # BxC
bs, feat_dim = feature.shape[:2]
neg_idx = self.memory_bank.multinomial.draw(bs * self.neg_num)
if self.ensure_neg:
neg_idx = neg_idx.view(bs, -1)
while True:
wrong = (neg_idx == idx.view(-1, 1))
if wrong.sum().item() > 0:
neg_idx[wrong] = self.memory_bank.multinomial.draw(
wrong.sum().item())
else:
break
neg_idx = neg_idx.flatten()
pos_feat = torch.index_select(self.memory_bank.feature_bank, 0,
idx) # BXC
neg_feat = torch.index_select(self.memory_bank.feature_bank, 0,
neg_idx).view(bs, self.neg_num,
feat_dim) # BxKxC
pos_logits = torch.einsum('nc,nc->n',
[pos_feat, feature]).unsqueeze(-1)
neg_logits = torch.bmm(neg_feat, feature.unsqueeze(2)).squeeze(2)
losses = self.head(pos_logits, neg_logits)
# update memory bank
with torch.no_grad():
self.memory_bank.update(idx, feature.detach())
return losses
| 1,923 |
5,196 | /*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cartographer/mapping/2d/probability_grid_range_data_inserter_2d.h"
#include <cstdlib>
#include "Eigen/Core"
#include "Eigen/Geometry"
#include "cartographer/mapping/2d/xy_index.h"
#include "cartographer/mapping/internal/2d/ray_to_pixel_mask.h"
#include "cartographer/mapping/probability_values.h"
#include "glog/logging.h"
namespace cartographer {
namespace mapping {
namespace {
// Factor for subpixel accuracy of start and end point for ray casts.
constexpr int kSubpixelScale = 1000;
void GrowAsNeeded(const sensor::RangeData& range_data,
ProbabilityGrid* const probability_grid) {
Eigen::AlignedBox2f bounding_box(range_data.origin.head<2>());
// Padding around bounding box to avoid numerical issues at cell boundaries.
constexpr float kPadding = 1e-6f;
for (const sensor::RangefinderPoint& hit : range_data.returns) {
bounding_box.extend(hit.position.head<2>());
}
for (const sensor::RangefinderPoint& miss : range_data.misses) {
bounding_box.extend(miss.position.head<2>());
}
probability_grid->GrowLimits(bounding_box.min() -
kPadding * Eigen::Vector2f::Ones());
probability_grid->GrowLimits(bounding_box.max() +
kPadding * Eigen::Vector2f::Ones());
}
void CastRays(const sensor::RangeData& range_data,
const std::vector<uint16>& hit_table,
const std::vector<uint16>& miss_table,
const bool insert_free_space, ProbabilityGrid* probability_grid) {
GrowAsNeeded(range_data, probability_grid);
const MapLimits& limits = probability_grid->limits();
const double superscaled_resolution = limits.resolution() / kSubpixelScale;
const MapLimits superscaled_limits(
superscaled_resolution, limits.max(),
CellLimits(limits.cell_limits().num_x_cells * kSubpixelScale,
limits.cell_limits().num_y_cells * kSubpixelScale));
const Eigen::Array2i begin =
superscaled_limits.GetCellIndex(range_data.origin.head<2>());
// Compute and add the end points.
std::vector<Eigen::Array2i> ends;
ends.reserve(range_data.returns.size());
for (const sensor::RangefinderPoint& hit : range_data.returns) {
ends.push_back(superscaled_limits.GetCellIndex(hit.position.head<2>()));
probability_grid->ApplyLookupTable(ends.back() / kSubpixelScale, hit_table);
}
if (!insert_free_space) {
return;
}
// Now add the misses.
for (const Eigen::Array2i& end : ends) {
std::vector<Eigen::Array2i> ray =
RayToPixelMask(begin, end, kSubpixelScale);
for (const Eigen::Array2i& cell_index : ray) {
probability_grid->ApplyLookupTable(cell_index, miss_table);
}
}
// Finally, compute and add empty rays based on misses in the range data.
for (const sensor::RangefinderPoint& missing_echo : range_data.misses) {
std::vector<Eigen::Array2i> ray = RayToPixelMask(
begin, superscaled_limits.GetCellIndex(missing_echo.position.head<2>()),
kSubpixelScale);
for (const Eigen::Array2i& cell_index : ray) {
probability_grid->ApplyLookupTable(cell_index, miss_table);
}
}
}
} // namespace
proto::ProbabilityGridRangeDataInserterOptions2D
CreateProbabilityGridRangeDataInserterOptions2D(
common::LuaParameterDictionary* parameter_dictionary) {
proto::ProbabilityGridRangeDataInserterOptions2D options;
options.set_hit_probability(
parameter_dictionary->GetDouble("hit_probability"));
options.set_miss_probability(
parameter_dictionary->GetDouble("miss_probability"));
options.set_insert_free_space(
parameter_dictionary->HasKey("insert_free_space")
? parameter_dictionary->GetBool("insert_free_space")
: true);
CHECK_GT(options.hit_probability(), 0.5);
CHECK_LT(options.miss_probability(), 0.5);
return options;
}
ProbabilityGridRangeDataInserter2D::ProbabilityGridRangeDataInserter2D(
const proto::ProbabilityGridRangeDataInserterOptions2D& options)
: options_(options),
hit_table_(ComputeLookupTableToApplyCorrespondenceCostOdds(
Odds(options.hit_probability()))),
miss_table_(ComputeLookupTableToApplyCorrespondenceCostOdds(
Odds(options.miss_probability()))) {}
void ProbabilityGridRangeDataInserter2D::Insert(
const sensor::RangeData& range_data, GridInterface* const grid) const {
ProbabilityGrid* const probability_grid = static_cast<ProbabilityGrid*>(grid);
CHECK(probability_grid != nullptr);
// By not finishing the update after hits are inserted, we give hits priority
// (i.e. no hits will be ignored because of a miss in the same cell).
CastRays(range_data, hit_table_, miss_table_, options_.insert_free_space(),
probability_grid);
probability_grid->FinishUpdate();
}
} // namespace mapping
} // namespace cartographer
| 1,947 |
1,144 | <reponame>yodaos-project/yodaos
/* SPDX-License-Identifier: GPL-2.0+ */
/*
* (C) Copyright 2002
* <NAME>, Omicron Ceti AB, <EMAIL>.
*/
#ifndef _U_BOOT_I386_H_
#define _U_BOOT_I386_H_ 1
struct global_data;
extern char gdt_rom[];
/* cpu/.../cpu.c */
int arch_cpu_init(void);
int x86_cpu_init_f(void);
int cpu_init_f(void);
void setup_gdt(struct global_data *id, u64 *gdt_addr);
/*
* Setup FSP execution environment GDT to use the one we used in
* arch/x86/cpu/start16.S and reload the segment registers.
*/
void setup_fsp_gdt(void);
int init_cache(void);
int cleanup_before_linux(void);
/* cpu/.../timer.c */
void timer_isr(void *);
typedef void (timer_fnc_t) (void);
int register_timer_isr (timer_fnc_t *isr_func);
unsigned long get_tbclk_mhz(void);
void timer_set_base(uint64_t base);
int i8254_init(void);
/* cpu/.../interrupts.c */
int cpu_init_interrupts(void);
int cleanup_before_linux(void);
int x86_cleanup_before_linux(void);
void x86_enable_caches(void);
void x86_disable_caches(void);
int x86_init_cache(void);
void reset_cpu(ulong addr);
ulong board_get_usable_ram_top(ulong total_size);
int default_print_cpuinfo(void);
/* Set up a UART which can be used with printch(), printhex8(), etc. */
int setup_internal_uart(int enable);
void setup_pcat_compatibility(void);
void isa_unmap_rom(u32 addr);
u32 isa_map_rom(u32 bus_addr, int size);
/* arch/x86/lib/... */
int video_bios_init(void);
/* arch/x86/lib/fsp/... */
/**
* fsp_save_s3_stack() - save stack address to CMOS for next S3 boot
*
* At the end of pre-relocation phase, save the new stack address
* to CMOS and use it as the stack on next S3 boot for fsp_init()
* continuation function.
*
* @return: 0 if OK, -ve on error
*/
int fsp_save_s3_stack(void);
void board_init_f_r_trampoline(ulong) __attribute__ ((noreturn));
void board_init_f_r(void) __attribute__ ((noreturn));
int arch_misc_init(void);
/* Read the time stamp counter */
static inline __attribute__((no_instrument_function)) uint64_t rdtsc(void)
{
uint32_t high, low;
__asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high));
return (((uint64_t)high) << 32) | low;
}
/* board/... */
void timer_set_tsc_base(uint64_t new_base);
uint64_t timer_get_tsc(void);
void quick_ram_check(void);
#define PCI_VGA_RAM_IMAGE_START 0xc0000
#endif /* _U_BOOT_I386_H_ */
| 936 |
21,684 | // Copyright 2010-2014 RethinkDB, all rights reserved.
#include "extproc/js_job.hpp"
#include <v8.h>
#include <libplatform/libplatform.h>
#include <stdint.h>
#include <limits>
#include "containers/archive/boost_types.hpp"
#include "containers/archive/stl_types.hpp"
#include "extproc/extproc_job.hpp"
#include "math.hpp"
#include "rdb_protocol/pseudo_time.hpp"
#include "rdb_protocol/configured_limits.hpp"
#include "utils.hpp"
const js_id_t MIN_ID = 1;
const js_id_t MAX_ID = std::numeric_limits<js_id_t>::max();
// Picked from a hat.
#define TO_JSON_RECURSION_LIMIT 500
// Returns an empty counted_t on error.
ql::datum_t js_to_datum(const v8::Handle<v8::Value> &value,
const ql::configured_limits_t &limits,
std::string *err_out);
// Returns an empty handle on error and sets `err_out` accordingly.
v8::Handle<v8::Value> js_from_datum(const ql::datum_t &datum,
std::string *err_out);
#ifdef V8_NEEDS_BUFFER_ALLOCATOR
class array_buffer_allocator_t : public v8::ArrayBuffer::Allocator {
public:
void *Allocate(size_t length) {
void *data = rmalloc(length);
memset(data, 0, length);
return data;
}
void *AllocateUninitialized(size_t length) {
return rmalloc(length);
}
void Free(void *data, UNUSED size_t length) {
free(data);
}
};
#endif
// Each worker process should have a single instance of this class before using the v8 API
class js_instance_t {
public:
static void run_other_tasks();
static void maybe_initialize_v8();
static v8::Isolate *isolate();
private:
js_instance_t();
~js_instance_t();
static js_instance_t *instance;
v8::Isolate *isolate_;
scoped_ptr_t<v8::Platform> platform;
#ifdef V8_NEEDS_BUFFER_ALLOCATOR
array_buffer_allocator_t array_buffer_allocator;
#endif
};
js_instance_t *js_instance_t::instance = nullptr;
js_instance_t::js_instance_t() {
v8::V8::InitializeICU();
platform.init(v8::platform::CreateDefaultPlatform());
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
#ifdef V8_NEEDS_BUFFER_ALLOCATOR
v8::Isolate::CreateParams params;
params.array_buffer_allocator = &array_buffer_allocator;
isolate_ = v8::Isolate::New(params);
#else
isolate_ = v8::Isolate::New();
#endif
isolate_->Enter();
}
js_instance_t::~js_instance_t() {
isolate_->Exit();
isolate_->Dispose();
v8::V8::Dispose();
v8::V8::ShutdownPlatform();
}
void js_instance_t::run_other_tasks() {
v8::platform::PumpMessageLoop(instance->platform.get(), isolate());
}
v8::Isolate *js_instance_t::isolate() {
return instance->isolate_;
}
void js_instance_t::maybe_initialize_v8() {
if (instance == nullptr) {
instance = new js_instance_t;
}
}
// Wrapper around `v8::Persistent<v8::Value> >` that calls `Reset()` on destruction
class persistent_value_t {
public:
~persistent_value_t() {
value.Reset();
}
v8::Persistent<v8::Value> value;
};
// Worker-side JS evaluation environment.
class js_env_t {
public:
js_env_t();
js_result_t eval(const std::string &source, const ql::configured_limits_t &limits);
js_result_t call(js_id_t id, const std::vector<ql::datum_t> &args,
const ql::configured_limits_t &limits);
void release(js_id_t id);
void run_other_tasks(uint64_t task_counter);
private:
js_id_t remember_value(const v8::Handle<v8::Value> &value);
const std::shared_ptr<persistent_value_t> find_value(js_id_t id);
js_id_t next_id;
std::map<js_id_t, std::shared_ptr<persistent_value_t> > values;
};
// Cleans the worker process's environment when instantiated
class js_context_t {
public:
js_context_t() :
local_scope(js_instance_t::isolate()),
context(v8::Context::New(js_instance_t::isolate())),
scope(context) { }
v8::HandleScope local_scope;
v8::Local<v8::Context> context;
v8::Context::Scope scope;
};
enum js_task_t {
TASK_EVAL,
TASK_CALL,
TASK_RELEASE,
TASK_EXIT
};
// The job_t runs in the context of the main rethinkdb process
js_job_t::js_job_t(extproc_pool_t *pool, signal_t *interruptor,
const ql::configured_limits_t &_limits) :
extproc_job(pool, &worker_fn, interruptor), limits(_limits) { }
js_result_t js_job_t::eval(const std::string &source) {
js_task_t task = js_task_t::TASK_EVAL;
write_message_t wm;
wm.append(&task, sizeof(task));
serialize<cluster_version_t::LATEST_OVERALL>(&wm, source);
serialize<cluster_version_t::LATEST_OVERALL>(&wm, limits);
{
int res = send_write_message(extproc_job.write_stream(), &wm);
if (res != 0) {
throw extproc_worker_exc_t("failed to send data to the worker");
}
}
js_result_t result;
archive_result_t res
= deserialize<cluster_version_t::LATEST_OVERALL>(extproc_job.read_stream(),
&result);
if (bad(res)) {
throw extproc_worker_exc_t(strprintf("failed to deserialize eval result from worker "
"(%s)", archive_result_as_str(res)));
}
return result;
}
js_result_t js_job_t::call(js_id_t id, const std::vector<ql::datum_t> &args) {
js_task_t task = js_task_t::TASK_CALL;
write_message_t wm;
wm.append(&task, sizeof(task));
serialize<cluster_version_t::LATEST_OVERALL>(&wm, id);
serialize<cluster_version_t::LATEST_OVERALL>(&wm, args);
serialize<cluster_version_t::LATEST_OVERALL>(&wm, limits);
{
int res = send_write_message(extproc_job.write_stream(), &wm);
if (res != 0) {
throw extproc_worker_exc_t("failed to send data to the worker");
}
}
js_result_t result;
archive_result_t res
= deserialize<cluster_version_t::LATEST_OVERALL>(extproc_job.read_stream(),
&result);
if (bad(res)) {
throw extproc_worker_exc_t(strprintf("failed to deserialize call result from worker "
"(%s)", archive_result_as_str(res)));
}
return result;
}
void js_job_t::release(js_id_t id) {
js_task_t task = js_task_t::TASK_RELEASE;
write_message_t wm;
wm.append(&task, sizeof(task));
serialize<cluster_version_t::LATEST_OVERALL>(&wm, id);
{
int res = send_write_message(extproc_job.write_stream(), &wm);
if (res != 0) {
throw extproc_worker_exc_t("failed to send data to the worker");
}
}
// Wait for a response so we don't flood the job with requests
bool dummy_result;
archive_result_t res
= deserialize<cluster_version_t::LATEST_OVERALL>(extproc_job.read_stream(),
&dummy_result);
// dummy_result should always be true
if (bad(res) || !dummy_result) {
throw extproc_worker_exc_t(strprintf("failed to deserialize release result from worker "
"(%s)", archive_result_as_str(res)));
}
}
void js_job_t::exit() {
js_task_t task = js_task_t::TASK_EXIT;
write_message_t wm;
wm.append(&task, sizeof(task));
{
int res = send_write_message(extproc_job.write_stream(), &wm);
if (res != 0) {
throw extproc_worker_exc_t("failed to send data to the worker");
}
}
// Wait for a response so we don't flood the job with requests
bool dummy_result;
archive_result_t res
= deserialize<cluster_version_t::LATEST_OVERALL>(extproc_job.read_stream(),
&dummy_result);
// dummy_result should always be true
if (bad(res) || !dummy_result) {
throw extproc_worker_exc_t(strprintf("failed to deserialize exit result from worker "
"(%s)", archive_result_as_str(res)));
}
}
void js_job_t::worker_error() {
extproc_job.worker_error();
}
void js_env_t::run_other_tasks(uint64_t task_counter) {
js_instance_t::run_other_tasks();
if (task_counter % 128 == 0) {
// Force collection of all garbage
js_instance_t::isolate()->LowMemoryNotification();
}
}
bool send_js_result(write_stream_t *stream_out, const js_result_t &js_result) {
write_message_t wm;
serialize<cluster_version_t::LATEST_OVERALL>(&wm, js_result);
int res = send_write_message(stream_out, &wm);
return res == 0;
}
bool send_dummy_result(write_stream_t *stream_out) {
write_message_t wm;
serialize<cluster_version_t::LATEST_OVERALL>(&wm, true);
int res = send_write_message(stream_out, &wm);
return res == 0;
}
bool run_eval(read_stream_t *stream_in,
write_stream_t *stream_out,
js_env_t *js_env,
uint64_t task_counter) {
std::string source;
ql::configured_limits_t limits;
{
archive_result_t res
= deserialize<cluster_version_t::LATEST_OVERALL>(stream_in,
&source);
if (bad(res)) { return false; }
res = deserialize<cluster_version_t::LATEST_OVERALL>(stream_in,
&limits);
if (bad(res)) { return false; }
}
js_result_t js_result;
try {
js_result = js_env->eval(source, limits);
} catch (const std::exception &e) {
js_result = e.what();
} catch (...) {
js_result = std::string("encountered an unknown exception");
}
js_env->run_other_tasks(task_counter);
return send_js_result(stream_out, js_result);
}
bool run_call(read_stream_t *stream_in,
write_stream_t *stream_out,
js_env_t *js_env,
uint64_t task_counter) {
js_id_t id;
std::vector<ql::datum_t> args;
ql::configured_limits_t limits;
{
archive_result_t res
= deserialize<cluster_version_t::LATEST_OVERALL>(stream_in, &id);
if (bad(res)) { return false; }
res = deserialize<cluster_version_t::LATEST_OVERALL>(stream_in, &args);
if (bad(res)) { return false; }
res = deserialize<cluster_version_t::LATEST_OVERALL>(stream_in, &limits);
if (bad(res)) { return false; }
}
js_result_t js_result;
try {
js_result = js_env->call(id, args, limits);
} catch (const std::exception &e) {
js_result = e.what();
} catch (...) {
js_result = std::string("encountered an unknown exception");
}
js_env->run_other_tasks(task_counter);
return send_js_result(stream_out, js_result);
}
bool run_release(read_stream_t *stream_in,
write_stream_t *stream_out,
js_env_t *js_env,
uint64_t task_counter) {
js_id_t id;
archive_result_t res = deserialize<cluster_version_t::LATEST_OVERALL>(stream_in,
&id);
if (bad(res)) { return false; }
js_env->release(id);
js_env->run_other_tasks(task_counter);
return send_dummy_result(stream_out);
}
bool run_exit(write_stream_t *stream_out) {
return send_dummy_result(stream_out);
}
bool js_job_t::worker_fn(read_stream_t *stream_in, write_stream_t *stream_out) {
static uint64_t task_counter = 0;
bool running = true;
js_instance_t::maybe_initialize_v8();
js_env_t js_env;
while (running) {
task_counter += 1;
js_task_t task;
int64_t read_size = sizeof(task);
{
int64_t res = force_read(stream_in, &task, read_size);
if (res != read_size) { return false; }
}
switch (task) {
case TASK_EVAL:
if (!run_eval(stream_in, stream_out, &js_env, task_counter)) {
return false;
}
break;
case TASK_CALL:
if (!run_call(stream_in, stream_out, &js_env, task_counter)) {
return false;
}
break;
case TASK_RELEASE:
if (!run_release(stream_in, stream_out, &js_env, task_counter)) {
return false;
}
break;
case TASK_EXIT:
return run_exit(stream_out);
default:
return false;
}
}
unreachable();
}
static void append_caught_error(std::string *err_out, const v8::TryCatch &try_catch) {
if (!try_catch.HasCaught()) return;
v8::String::Utf8Value exception(try_catch.Exception());
const char *message = *exception;
guarantee(message != nullptr);
err_out->append(message, strlen(message));
}
// The env_t runs in the context of the worker process
js_env_t::js_env_t() :
next_id(MIN_ID) { }
js_result_t js_env_t::eval(const std::string &source,
const ql::configured_limits_t &limits) {
js_context_t clean_context;
js_result_t result("");
std::string *err_out = boost::get<std::string>(&result);
v8::Isolate *isolate = js_instance_t::isolate();
v8::HandleScope handle_scope(isolate);
// TODO: use an "external resource" to avoid copy?
v8::Handle<v8::String> src = v8::String::NewFromUtf8(isolate,
source.data(),
v8::String::NewStringType::kNormalString,
source.size());
// This constructor registers itself with v8 so that any errors generated
// within v8 will be available within this object.
v8::TryCatch try_catch;
// Firstly, compilation may fail (because of say a syntax error)
v8::Handle<v8::Script> script = v8::Script::Compile(src);
if (script.IsEmpty()) {
// Get the error out of the TryCatch object
append_caught_error(err_out, try_catch);
} else {
// Secondly, evaluation may fail because of an exception generated
// by the code
v8::Handle<v8::Value> result_val = script->Run();
if (result_val.IsEmpty()) {
// Get the error from the TryCatch object
append_caught_error(err_out, try_catch);
} else {
// Scripts that evaluate to functions become RQL Func terms that
// can be passed to map, filter, reduce, etc.
if (result_val->IsFunction()) {
v8::Handle<v8::Function> func
= v8::Handle<v8::Function>::Cast(result_val);
result = remember_value(func);
} else {
guarantee(!result_val.IsEmpty());
// JSONify result.
ql::datum_t datum = js_to_datum(result_val, limits, err_out);
if (datum.has()) {
result = datum;
}
}
}
}
return result;
}
js_id_t js_env_t::remember_value(const v8::Handle<v8::Value> &value) {
guarantee(next_id < MAX_ID);
js_id_t id = next_id++;
// Save this value in a persistent handle so it isn't deallocated when
// its scope is destructed.
std::shared_ptr<persistent_value_t> persistent_handle(new persistent_value_t());
persistent_handle->value.Reset(js_instance_t::isolate(), value);
values.insert(std::make_pair(id, persistent_handle));
return id;
}
const std::shared_ptr<persistent_value_t> js_env_t::find_value(js_id_t id) {
std::map<js_id_t, std::shared_ptr<persistent_value_t> >::iterator it = values.find(id);
guarantee(it != values.end());
return it->second;
}
v8::Local<v8::Value> run_js_func(v8::Handle<v8::Function> fn,
const std::vector<ql::datum_t> &args,
std::string *err_out) {
v8::Isolate *isolate = js_instance_t::isolate();
v8::TryCatch try_catch;
v8::EscapableHandleScope scope(isolate);
// Construct receiver object.
v8::Handle<v8::Object> obj = v8::Object::New(isolate);
guarantee(!obj.IsEmpty());
// Construct arguments.
scoped_array_t<v8::Handle<v8::Value> > handles(args.size());
for (size_t i = 0; i < args.size(); ++i) {
handles[i] = js_from_datum(args[i], err_out);
if (!err_out->empty()) {
return v8::Handle<v8::Value>();
}
}
// Call function with environment as its receiver.
v8::Local<v8::Value> result = fn->Call(obj, args.size(), handles.data());
if (result.IsEmpty()) {
append_caught_error(err_out, try_catch);
}
return scope.Escape(result);
}
js_result_t js_env_t::call(js_id_t id,
const std::vector<ql::datum_t> &args,
const ql::configured_limits_t &limits) {
js_context_t clean_context;
js_result_t result("");
std::string *err_out = boost::get<std::string>(&result);
const std::shared_ptr<persistent_value_t> found_value = find_value(id);
guarantee(!found_value->value.IsEmpty());
v8::Isolate *isolate = js_instance_t::isolate();
v8::HandleScope handle_scope(isolate);
// Construct local handle from persistent handle
v8::Local<v8::Value> local_handle =
v8::Local<v8::Value>::New(isolate, found_value->value);
v8::Local<v8::Function> fn = v8::Local<v8::Function>::Cast(local_handle);
v8::Handle<v8::Value> value = run_js_func(fn, args, err_out);
if (!value.IsEmpty()) {
if (value->IsFunction()) {
*err_out = "Returning functions from within `r.js` is unsupported.";
} else {
// JSONify result.
ql::datum_t datum = js_to_datum(value, limits, err_out);
if (datum.has()) {
result = datum;
}
}
}
return result;
}
void js_env_t::release(js_id_t id) {
guarantee(id < next_id);
size_t num_erased = values.erase(id);
guarantee(1 == num_erased);
}
// TODO: Is there a better way of detecting circular references than a recursion limit?
ql::datum_t js_make_datum(const v8::Handle<v8::Value> &value,
int recursion_limit,
const ql::configured_limits_t &limits,
std::string *err_out) {
ql::datum_t result;
if (0 == recursion_limit) {
err_out->assign("Recursion limit exceeded in js_to_json (circular reference?).");
return result;
}
--recursion_limit;
// TODO: should we handle BooleanObject, NumberObject, StringObject?
v8::HandleScope handle_scope(js_instance_t::isolate());
if (value->IsString()) {
v8::Handle<v8::String> string = value->ToString();
guarantee(!string.IsEmpty());
size_t length = string->Utf8Length();
scoped_array_t<char> temp_buffer(length);
string->WriteUtf8(temp_buffer.data(), length);
try {
result = ql::datum_t(datum_string_t(length, temp_buffer.data()));
} catch (const ql::base_exc_t &ex) {
err_out->assign(ex.what());
}
} else if (value->IsObject()) {
// This case is kinda weird. Objects can have stuff in them that isn't
// represented in their JSON (eg. their prototype, v8 hidden fields).
if (value->IsArray()) {
v8::Handle<v8::Array> arrayh = v8::Handle<v8::Array>::Cast(value);
std::vector<ql::datum_t> datum_array;
datum_array.reserve(arrayh->Length());
for (uint32_t i = 0; i < arrayh->Length(); ++i) {
v8::Handle<v8::Value> elth = arrayh->Get(i);
guarantee(!elth.IsEmpty());
ql::datum_t item = js_make_datum(elth, recursion_limit, limits, err_out);
if (!item.has()) {
// Result is still empty, the error message has been set
return result;
}
datum_array.push_back(std::move(item));
}
result = ql::datum_t(std::move(datum_array), limits);
} else if (value->IsFunction()) {
// We can't represent functions in JSON.
err_out->assign("Cannot convert function to ql::datum_t.");
} else if (value->IsRegExp()) {
// We can't represent regular expressions in datums
err_out->assign("Cannot convert RegExp to ql::datum_t.");
} else if (value->IsDate()) {
result = ql::pseudo::make_time(value->NumberValue() / 1000,
"+00:00");
} else {
// Treat it as a dictionary.
v8::Handle<v8::Object> objh = value->ToObject();
guarantee(!objh.IsEmpty());
v8::Handle<v8::Array> properties = objh->GetPropertyNames();
guarantee(!properties.IsEmpty());
ql::datum_object_builder_t builder;
uint32_t len = properties->Length();
for (uint32_t i = 0; i < len; ++i) {
v8::Handle<v8::String> keyh = properties->Get(i)->ToString();
guarantee(!keyh.IsEmpty());
v8::Handle<v8::Value> valueh = objh->Get(keyh);
guarantee(!valueh.IsEmpty());
ql::datum_t item = js_make_datum(valueh, recursion_limit, limits, err_out);
if (!item.has()) {
// Result is still empty, the error message has been set
return result;
}
size_t length = keyh->Utf8Length();
scoped_array_t<char> temp_buffer(length);
keyh->WriteUtf8(temp_buffer.data(), length);
datum_string_t key_string(length, temp_buffer.data());
builder.overwrite(key_string, item);
}
result = std::move(builder).to_datum();
}
} else if (value->IsNumber()) {
double num_val = value->NumberValue();
if (!risfinite(num_val)) {
err_out->assign("Number return value is not finite.");
} else {
result = ql::datum_t(num_val);
}
} else if (value->IsBoolean()) {
result = ql::datum_t::boolean(value->BooleanValue());
} else if (value->IsNull()) {
result = ql::datum_t::null();
} else {
err_out->assign(value->IsUndefined() ?
"Cannot convert javascript `undefined` to ql::datum_t." :
"Unrecognized value type when converting to ql::datum_t.");
}
return result;
}
ql::datum_t js_to_datum(const v8::Handle<v8::Value> &value,
const ql::configured_limits_t &limits,
std::string *err_out) {
guarantee(!value.IsEmpty());
guarantee(err_out != nullptr);
v8::HandleScope handle_scope(js_instance_t::isolate());
err_out->assign("Unknown error when converting to ql::datum_t.");
return js_make_datum(value, TO_JSON_RECURSION_LIMIT, limits, err_out);
}
v8::Handle<v8::Value> js_from_datum(const ql::datum_t &datum,
std::string *err_out) {
guarantee(datum.has());
v8::Isolate *isolate = js_instance_t::isolate();
switch (datum.get_type()) {
case ql::datum_t::type_t::MINVAL:
err_out->assign("`r.minval` cannot be passed to `r.js`.");
return v8::Handle<v8::Value>();
case ql::datum_t::type_t::MAXVAL:
err_out->assign("`r.maxval` cannot be passed to `r.js`.");
return v8::Handle<v8::Value>();
case ql::datum_t::type_t::R_BINARY:
// TODO: In order to support this, we need to link against a static version of
// V8, which provides an ArrayBuffer API.
err_out->assign("`r.binary` data cannot be used in `r.js`.");
return v8::Handle<v8::Value>();
case ql::datum_t::type_t::R_BOOL:
if (datum.as_bool()) {
return v8::True(isolate);
} else {
return v8::False(isolate);
}
case ql::datum_t::type_t::R_NULL:
return v8::Null(isolate);
case ql::datum_t::type_t::R_NUM:
return v8::Number::New(isolate, datum.as_num());
case ql::datum_t::type_t::R_STR:
return v8::String::NewFromUtf8(isolate, datum.as_str().to_std().c_str());
case ql::datum_t::type_t::R_ARRAY: {
v8::Handle<v8::Array> array = v8::Array::New(isolate);
for (size_t i = 0; i < datum.arr_size(); ++i) {
v8::HandleScope scope(isolate);
v8::Handle<v8::Value> val = js_from_datum(datum.get(i), err_out);
if (val.IsEmpty()) {
// The recursive call to `js_from_datum` should have set `err_out`
guarantee(!err_out->empty());
return v8::Handle<v8::Value>();
}
array->Set(i, val);
}
return array;
}
case ql::datum_t::type_t::R_OBJECT: {
if (datum.is_ptype(ql::pseudo::time_string)) {
double epoch_time = ql::pseudo::time_to_epoch_time(datum);
v8::Handle<v8::Value> date = v8::Date::New(isolate, epoch_time * 1000);
return date;
} else {
v8::Handle<v8::Object> obj = v8::Object::New(isolate);
for (size_t i = 0; i < datum.obj_size(); ++i) {
auto pair = datum.get_pair(i);
v8::HandleScope scope(isolate);
v8::Handle<v8::Value> key = v8::String::NewFromUtf8(isolate, pair.first.to_std().c_str());
v8::Handle<v8::Value> val = js_from_datum(pair.second, err_out);
if (val.IsEmpty()) {
// The recursive call to `js_from_datum` should have set `err_out`
guarantee(!err_out->empty());
return v8::Handle<v8::Value>();
}
guarantee(!key.IsEmpty() && !val.IsEmpty());
obj->Set(key, val);
}
return obj;
}
}
case ql::datum_t::type_t::UNINITIALIZED: // fallthru
default:
err_out->assign("bad datum value in js extproc");
return v8::Handle<v8::Value>();
}
}
| 12,556 |
1,014 | package com.github.neuralnetworks.input.image;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import com.github.neuralnetworks.input.InputConverter;
/**
* ImageInputProvider that retrieves all images from the original source image based on the sliding window technique
*/
public abstract class SlidingWindowImageInputProvider extends ImageInputProvider
{
private static final long serialVersionUID = 1L;
private List<BufferedImage> sourceImages;
private BufferedImage[] images;
private int width;
private int height;
private int strideX;
private int strideY;
private int currentImage;
private int currentX;
private int currentY;
private int inputSize;
public SlidingWindowImageInputProvider(InputConverter inputConverter, List<BufferedImage> sourceImages, int width, int height, int strideX, int strideY)
{
super(inputConverter);
this.sourceImages = sourceImages;
this.width = width;
this.height = height;
this.strideX = strideX;
this.strideY = strideY;
}
@Override
public int getInputSize()
{
if (inputSize == 0)
{
for (BufferedImage si : sourceImages)
{
inputSize += (si.getWidth() - width) / strideX + (si.getHeight() - height) / strideY;
}
}
return inputSize * super.getInputSize();
}
@Override
public List<BufferedImage> getNextRawImages()
{
if (images == null)
{
images = new BufferedImage[properties.getImagesBulkSize()];
}
IntStream stream = IntStream.range(0, properties.getImagesBulkSize());
stream.forEach(i -> {
if (sourceImages.get(currentImage).getWidth() - width > currentX)
{
currentX++;
} else if (sourceImages.get(currentImage).getHeight() - height > currentY)
{
currentY++;
currentX = 0;
} else
{
currentImage = (currentImage + 1) % sourceImages.size();
currentY = currentX = 0;
}
images[i] = sourceImages.get(currentImage).getSubimage(currentX, currentY, width, height);
});
return Arrays.asList(images);
}
@Override
public int getInputDimensions()
{
return width * height * 3;
}
@Override
public int getTargetDimensions()
{
return 0;
}
}
| 754 |
6,693 | <reponame>xihushui599/machinelearning
/*
Copyright (C) 2016 - 2019 <NAME>(<EMAIL>)
https://www.cnblogs.com/pinard
Permission given to modify the code as long as you keep this declaration at the top
用PMML实现机器学习模型的跨平台上线 https://www.cnblogs.com/pinard/p/9220199.html
*/
import org.dmg.pmml.FieldName;
import org.dmg.pmml.PMML;
import org.jpmml.evaluator.*;
import org.xml.sax.SAXException;
import javax.xml.bind.JAXBException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by 刘建平Pinard on 2018/6/24.
*/
public class PMMLDemo {
private Evaluator loadPmml(){
PMML pmml = new PMML();
InputStream inputStream = null;
try {
inputStream = new FileInputStream("D:/demo.pmml");
} catch (IOException e) {
e.printStackTrace();
}
if(inputStream == null){
return null;
}
InputStream is = inputStream;
try {
pmml = org.jpmml.model.PMMLUtil.unmarshal(is);
} catch (SAXException e1) {
e1.printStackTrace();
} catch (JAXBException e1) {
e1.printStackTrace();
}finally {
//关闭输入流
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ModelEvaluatorFactory modelEvaluatorFactory = ModelEvaluatorFactory.newInstance();
Evaluator evaluator = modelEvaluatorFactory.newModelEvaluator(pmml);
pmml = null;
return evaluator;
}
private int predict(Evaluator evaluator,int a, int b, int c, int d) {
Map<String, Integer> data = new HashMap<String, Integer>();
data.put("x1", a);
data.put("x2", b);
data.put("x3", c);
data.put("x4", d);
List<InputField> inputFields = evaluator.getInputFields();
//过模型的原始特征,从画像中获取数据,作为模型输入
Map<FieldName, FieldValue> arguments = new LinkedHashMap<FieldName, FieldValue>();
for (InputField inputField : inputFields) {
FieldName inputFieldName = inputField.getName();
Object rawValue = data.get(inputFieldName.getValue());
FieldValue inputFieldValue = inputField.prepare(rawValue);
arguments.put(inputFieldName, inputFieldValue);
}
Map<FieldName, ?> results = evaluator.evaluate(arguments);
List<TargetField> targetFields = evaluator.getTargetFields();
TargetField targetField = targetFields.get(0);
FieldName targetFieldName = targetField.getName();
Object targetFieldValue = results.get(targetFieldName);
System.out.println("target: " + targetFieldName.getValue() + " value: " + targetFieldValue);
int primitiveValue = -1;
if (targetFieldValue instanceof Computable) {
Computable computable = (Computable) targetFieldValue;
primitiveValue = (Integer)computable.getResult();
}
System.out.println(a + " " + b + " " + c + " " + d + ":" + primitiveValue);
return primitiveValue;
}
public static void main(String args[]){
PMMLDemo demo = new PMMLDemo();
Evaluator model = demo.loadPmml();
demo.predict(model,1,8,99,1);
demo.predict(model,111,89,9,11);
}
}
| 1,711 |
1,433 | <gh_stars>1000+
//-----------------------------------------------------------------------------
//
// BasicWindowCovering.cpp
//
// Implementation of the Z-Wave COMMAND_CLASS_BASIC_WINDOW_COVERING
//
// Copyright (c) 2010 <NAME> <<EMAIL>>
//
// SOFTWARE NOTICE AND LICENSE
//
// This file is part of OpenZWave.
//
// OpenZWave is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// OpenZWave is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with OpenZWave. If not, see <http://www.gnu.org/licenses/>.
//
//-----------------------------------------------------------------------------
#include "command_classes/CommandClasses.h"
#include "command_classes/BasicWindowCovering.h"
#include "Defs.h"
#include "Msg.h"
#include "Driver.h"
#include "Node.h"
#include "platform/Log.h"
#include "value_classes/ValueButton.h"
using namespace OpenZWave;
enum BasicWindowCoveringCmd
{
BasicWindowCoveringCmd_StartLevelChange = 0x01,
BasicWindowCoveringCmd_StopLevelChange = 0x02
};
enum
{
BasicWindowCoveringIndex_Open = 0,
BasicWindowCoveringIndex_Close
};
//-----------------------------------------------------------------------------
// <BasicWindowCovering::SetValue>
// Set a value on the Z-Wave device
//-----------------------------------------------------------------------------
bool BasicWindowCovering::SetValue
(
Value const& _value
)
{
if( ValueID::ValueType_Button == _value.GetID().GetType() )
{
ValueButton const* button = static_cast<ValueButton const*>(&_value);
uint8 action = 0x40;
if( button->GetID().GetIndex() ) // Open is index zero, so non-zero is close.
{
// Close
action = 0;
}
if( button && button->IsPressed() )
{
Log::Write( LogLevel_Info, GetNodeId(), "BasicWindowCovering - Start Level Change (%s)", action ? "Open" : "Close" );
Msg* msg = new Msg( "BasicWindowCoveringCmd_StartLevelChange", GetNodeId(), REQUEST, FUNC_ID_ZW_SEND_DATA, true );
msg->SetInstance( this, _value.GetID().GetInstance() );
msg->Append( GetNodeId() );
msg->Append( 3 );
msg->Append( GetCommandClassId() );
msg->Append( BasicWindowCoveringCmd_StartLevelChange );
msg->Append( action );
msg->Append( GetDriver()->GetTransmitOptions() );
GetDriver()->SendMsg( msg, Driver::MsgQueue_Send );
return true;
}
else
{
Log::Write( LogLevel_Info, GetNodeId(), "BasicWindowCovering - Stop Level Change" );
Msg* msg = new Msg( "BasicWindowCoveringCmd_StopLevelChange", GetNodeId(), REQUEST, FUNC_ID_ZW_SEND_DATA, true );
msg->SetInstance( this, _value.GetID().GetInstance() );
msg->Append( GetNodeId() );
msg->Append( 2 );
msg->Append( GetCommandClassId() );
msg->Append( BasicWindowCoveringCmd_StopLevelChange );
msg->Append( GetDriver()->GetTransmitOptions() );
GetDriver()->SendMsg( msg, Driver::MsgQueue_Send );
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// <BasicWindowCovering::CreateVars>
// Create the values managed by this command class
//-----------------------------------------------------------------------------
void BasicWindowCovering::CreateVars
(
uint8 const _instance
)
{
if( Node* node = GetNodeUnsafe() )
{
node->CreateValueButton( ValueID::ValueGenre_User, GetCommandClassId(), _instance, BasicWindowCoveringIndex_Open, "Open", 0 );
node->CreateValueButton( ValueID::ValueGenre_User, GetCommandClassId(), _instance, BasicWindowCoveringIndex_Close, "Close", 0 );
}
}
| 1,227 |
21,684 | <reponame>zadcha/rethinkdb
// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "arch/os_signal.hpp"
#include "arch/runtime/thread_pool.hpp"
#include "arch/types.hpp"
#include "do_on_thread.hpp"
os_signal_cond_t::os_signal_cond_t() :
#ifdef _WIN32
source_type(0)
#else
source_pid(-1),
source_uid(-1),
source_signo(0)
#endif
{
DEBUG_VAR thread_message_t *old = linux_thread_pool_t::get_thread_pool()->exchange_interrupt_message(this);
rassert(old == NULL);
}
os_signal_cond_t::~os_signal_cond_t() {
if (!is_pulsed()) {
DEBUG_VAR thread_message_t *old = thread_pool_t::get_thread_pool()->exchange_interrupt_message(NULL);
rassert(old == this);
}
}
void os_signal_cond_t::on_thread_switch() {
// TODO: There's probably an outside chance of a use-after-free bug here.
do_on_thread(home_thread(), std::bind(&os_signal_cond_t::pulse, this));
}
std::string os_signal_cond_t::format() {
#ifdef _WIN32
switch (source_type) {
case CTRL_C_EVENT:
return "Control-C";
case CTRL_BREAK_EVENT:
return "Control-Break";
case CTRL_CLOSE_EVENT:
return "Close (End Task) Event";
case CTRL_LOGOFF_EVENT:
return "Logoff Event";
case CTRL_SHUTDOWN_EVENT:
return "Shutdown Event";
default:
return strprintf("console signal %ud", source_type);
}
#else
switch (source_signo) {
case SIGINT:
return strprintf("SIGINT from pid %d, uid %d",
source_pid, source_uid);
case SIGTERM:
return strprintf("SIGTERM from pid %d, uid %d",
source_pid, source_uid);
default:
return strprintf("signal %d from pid %d, uid %d",
source_signo, source_pid, source_uid);
}
#endif
}
| 824 |
2,139 | package org.jruby.benchmark;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.jruby.Ruby;
import org.jruby.RubyFixnum;
import org.jruby.RubyInstanceConfig;
import org.jruby.runtime.builtin.IRubyObject;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
@Warmup(iterations = 3, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Fork(1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class JavaInterfaceBenchmark {
private static final int INVOCATIONS = 200_000_000;
private static final Ruby RUBY = initRuby();
private static final RubyFixnum LEFT = RUBY.newFixnum(ThreadLocalRandom.current().nextInt());
private static final RubyFixnum RIGHT = RUBY.newFixnum(ThreadLocalRandom.current().nextInt());
private static final JavaInterfaceBenchmark.Summation JAVA_SUMMER =
new JavaInterfaceBenchmark.Summation() {
@Override
public IRubyObject sum(final RubyFixnum left, final RubyFixnum right) {
return left.op_plus(RUBY.getCurrentContext(), right);
}
};
public interface Summation {
IRubyObject sum(RubyFixnum left, RubyFixnum right);
}
@Benchmark
@OperationsPerInvocation(INVOCATIONS)
public void benchHalfRubyVersion(final Blackhole blackhole) {
blackhole.consume(
RUBY.executeScript(
"org.jruby.benchmark.JavaInterfaceBenchmark.doRun(RubySummation.new)"
,"benchHalfRubyVersion")
);
}
@Benchmark
@OperationsPerInvocation(INVOCATIONS)
public void benchJavaVersion(final Blackhole blackhole) {
blackhole.consume(doRun(JAVA_SUMMER));
}
public static IRubyObject doRun(final JavaInterfaceBenchmark.Summation summer) {
IRubyObject sum = null;
for (int i = 0; i < INVOCATIONS; ++i) {
sum = summer.sum(LEFT, RIGHT);
}
return sum;
}
private static Ruby initRuby() {
final RubyInstanceConfig config = new RubyInstanceConfig();
config.setCompileMode(RubyInstanceConfig.CompileMode.FORCE);
final Ruby ruby = Ruby.newInstance(config);
ruby.executeScript(
new StringBuilder()
.append("class RubySummation\n")
.append("\tinclude org.jruby.benchmark.JavaInterfaceBenchmark::Summation\n")
.append('\n')
.append("\tdef sum(a, b)\n")
.append("\t\ta + b\n")
.append("\tend\n")
.append("end")
.toString(), "initRuby"
);
return ruby;
}
}
| 1,344 |
4,949 | <reponame>BBArikL/tenacity<filename>src/widgets/Plot.h
/**********************************************************************
Audacity: A Digital Audio Editor
Plot.h
<NAME>
This class is a generic plot.
**********************************************************************/
#ifndef __AUDACITY_PLOT__
#define __AUDACITY_PLOT__
#include "wxPanelWrapper.h" // to inherit
#include "MemoryX.h"
class Ruler;
struct PlotData
{
std::unique_ptr<wxPen> pen;
std::vector<float> xdata;
std::vector<float> ydata;
};
class Plot : public wxPanelWrapper
{
public:
Plot(wxWindow *parent, wxWindowID winid,
float x_min, float x_max, float y_min, float y_max,
const TranslatableString& xlabel, const TranslatableString& ylabel,
int xformat = 1, int yformat = 1, //Ruler::RealFormat
int count = 1, const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxTAB_TRAVERSAL | wxNO_BORDER);
inline PlotData* GetPlotData(int id)
{ return &m_plots[id]; }
private:
void OnPaint(wxPaintEvent & evt);
void OnSize(wxSizeEvent & evt);
float m_xmin, m_xmax;
float m_ymin, m_ymax;
std::vector<PlotData> m_plots;
std::unique_ptr<Ruler> m_xruler, m_yruler;
int XToScreen(float x, wxRect& rect);
int YToScreen(float y, wxRect& rect);
DECLARE_EVENT_TABLE()
};
#endif
| 584 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
#define HASH_SIZE_DEFAULT 20 // default to SHA1
namespace Common
{
class Thumbprint : public X509FindValue, public X509Identity
{
public:
typedef std::shared_ptr<Thumbprint> SPtr;
static ErrorCode Create(std::wstring const & str, _Out_ SPtr & result);
static ErrorCode Create(PCCertContext certContext, _Out_ SPtr & result);
Thumbprint();
Thumbprint(Thumbprint const & other);
Thumbprint(Thumbprint && other);
ErrorCode Initialize(std::wstring const & hashValue);
ErrorCode Initialize(PCCertContext certContext);
X509FindType::Enum Type() const override;
void const * Value() const override; // returns address of CRYPT_HASH_BLOB
BYTE const * Hash() const; // returns hash value
DWORD HashSizeInBytes() const;
bool CertChainShouldBeVerified() const;
bool PrimaryValueEqualsTo(Thumbprint const & other) const;
Thumbprint & operator = (Thumbprint const & other);
Thumbprint & operator = (Thumbprint && other);
bool operator == (Thumbprint const & rhs) const;
bool operator != (Thumbprint const & rhs) const;
bool operator < (Thumbprint const & rhs) const;
bool operator == (X509Identity const & rhs) const override; // override X509Identity
bool operator < (X509Identity const & rhs) const override; // override X509Identity
X509Identity::Type IdType() const override;
void WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const;
private:
void SetBlobValue();
void OnWriteTo(Common::TextWriter & w, Common::FormatOptions const &) const override;
bool EqualsTo(X509FindValue const & other) const override; // override X509FindValue
ByteBuffer buffer_;
CRYPT_HASH_BLOB value_;
bool certChainShouldBeVerified_;
};
}
| 760 |
428 | <reponame>cping/LGame
/**
* Copyright 2008 - 2020 The Loon Game Engine Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @project loon
* @author cping
* @email:<EMAIL>
* @version 0.5
*/
package loon.font;
import loon.BaseIO;
import loon.LRelease;
import loon.LSysException;
import loon.LSystem;
import loon.LTexture;
import loon.LTextureBatch;
import loon.LTextureBatch.Cache;
import loon.canvas.Canvas;
import loon.canvas.Image;
import loon.canvas.LColor;
import loon.events.Updateable;
import loon.geom.Affine2f;
import loon.geom.PointF;
import loon.geom.PointI;
import loon.geom.RectF;
import loon.opengl.BlendMethod;
import loon.opengl.BlendState;
import loon.opengl.GL20;
import loon.opengl.GLEx;
import loon.opengl.Painter;
import loon.utils.CharArray;
import loon.utils.CharIterator;
import loon.utils.GLUtils;
import loon.utils.IntMap;
import loon.utils.LIterator;
import loon.utils.MathUtils;
import loon.utils.OrderedSet;
import loon.utils.StrBuilder;
import loon.utils.StringUtils;
import loon.utils.TArray;
import loon.utils.parse.StrTokenizer;
/**
* Adobe的DBF格式字体文件支持(主要是给C#版monogame环境用的,本地字库默认没法调用,除非调用本地api,问题是不想自己写环境适配才用的monogame……)
*/
public class BDFont implements IFont, LRelease {
public static class BDFGlyph {
protected byte[][] glyph;
protected int x, y;
protected int advance;
protected int encoding;
public BDFGlyph() {
this.glyph = new byte[0][0];
x = 0;
y = 0;
advance = 0;
}
public BDFGlyph(byte[][] glyph) {
this.glyph = glyph;
x = 0;
y = glyph.length;
advance = (glyph.length < 1) ? 0 : (glyph[0].length);
}
public BDFGlyph(byte[][] glyph, int offset, int width, int ascent) {
this.glyph = glyph;
x = offset;
y = ascent;
advance = width;
}
public byte[][] getGlyph() {
return glyph;
}
public BDFGlyph setGlyph(byte[][] glyph) {
this.glyph = glyph;
return this;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public BDFGlyph set(int x, int y) {
this.x = x;
this.y = y;
return this;
}
public int getGlyphWidth() {
return (glyph.length < 1) ? 0 : (glyph[0].length);
}
public int getGlyphHeight() {
return glyph.length;
}
public int getGlyphOffset() {
return x;
}
public int getGlyphAscent() {
return y;
}
public int getGlyphDescent() {
return glyph.length - y;
}
public int getCharacterWidth() {
return advance;
}
public BDFGlyph setCharacterWidth(int v) {
advance = v;
return this;
}
public BDFGlyph setCharacterWidth(float v) {
advance = MathUtils.ceil(v);
return this;
}
public float paint(Canvas g, float x, float y, float scale) {
return paint(g, x, y, scale, LColor.DEF_COLOR);
}
public float paint(Canvas g, float x, float y, float scale, int color) {
int w = ((glyph.length < 1) ? 0 : (glyph[0].length));
int h = glyph.length;
Image img = Image.createImage(w, h);
int[] glyphPixels = new int[w * h];
for (int k = 0, j = 0; j < h; j++) {
for (int i = 0; i < w; k++, i++) {
glyphPixels[k] = LColor.combine(glyph[j][i], color);
}
}
img.setPixels(glyphPixels, w, h);
int dx = MathUtils.round(x + this.x * scale);
int dy = MathUtils.round(y - this.y * scale);
int dw = MathUtils.round(w * scale);
int dh = MathUtils.round(h * scale);
g.draw(img, dx, dy, dx + dw, dy + dh, 0, 0, w, h);
img.close();
img = null;
return advance * scale;
}
public byte getPixel(int x, int y) {
byte[][] data = getGlyph();
int ix = x - getX();
int iy = y + getY();
if (iy >= 0 && iy < data.length) {
if (ix >= 0 && ix < data[iy].length) {
return data[iy][ix];
}
}
return 0;
}
public void contract() {
byte[][] data = getGlyph();
if (data.length == 0) {
set(0, 0);
return;
}
int gx = getX();
int gy = getY();
int gw = data[0].length;
int gh = data.length;
int cx1 = gx;
int cy1 = -gy;
int cx2 = gx + gw;
int cy2 = -gy + gh;
while (cy2 > cy1 && rowEmpty(data, cy2 + gy - 1))
cy2--;
while (cy1 < cy2 && rowEmpty(data, cy1 + gy))
cy1++;
while (cx2 > cx1 && colEmpty(data, cx2 - gx - 1))
cx2--;
while (cx1 < cx2 && colEmpty(data, cx1 - gx))
cx1++;
if (cx2 == cx1 || cy2 == cy1) {
set(0, 0);
setGlyph(new byte[0][0]);
return;
}
if (cx1 != gx || cy1 != -gy || cx2 != gx + gw || cy2 != -gy + gh) {
int cw = cx2 - cx1;
int ch = cy2 - cy1;
byte[][] newData = new byte[ch][cw];
for (int dy = 0, sy = cy1 + gy; dy < ch; dy++, sy++) {
for (int dx = 0, sx = cx1 - gx; dx < cw; dx++, sx++) {
newData[dy][dx] = data[sy][sx];
}
}
set(cx1, -cy1);
setGlyph(newData);
}
}
private static boolean rowEmpty(byte[][] a, int row) {
for (byte b : a[row]) {
if (b != 0) {
return false;
}
}
return true;
}
private static boolean colEmpty(byte[][] a, int col) {
for (byte[] b : a) {
if (b[col] != 0) {
return false;
}
}
return true;
}
}
private class CharRect extends RectF {
public Character name;
public LColor color;
}
private static class IntObject {
public int width;
public int height;
public int storedX;
public int storedY;
}
private void putChildChars(Character ch, float x, float y, float w, float h, LColor c) {
if (_childChars == null) {
_childChars = new TArray<CharRect>();
}
CharRect obj = new CharRect();
obj.name = ch;
obj.x = x;
obj.y = y;
obj.width = w;
obj.height = h;
obj.color = c;
_childChars.add(obj);
}
private static class UpdateFont implements Updateable {
private BDFont strfont;
public UpdateFont(BDFont strf) {
this.strfont = strf;
}
@Override
public void action(Object a) {
if (strfont._isClose) {
return;
}
strfont.loadFont();
strfont.expandTexture();
if (strfont.textureWidth > strfont._maxTextureWidth || strfont.textureHeight > strfont._maxTextureHeight) {
strfont._outBounds = true;
}
Canvas canvas = LSystem.base().graphics().createCanvas(strfont.textureWidth, strfont.textureHeight);
int rowHeight = 0;
int positionX = 0;
int positionY = 0;
int customCharsLength = (strfont.additionalChars != null) ? strfont.additionalChars.length : 0;
StrBuilder sbr = new StrBuilder(customCharsLength);
final OrderedSet<Character> outchached = new OrderedSet<Character>();
for (int i = 0, size = customCharsLength; i < size; i++) {
boolean outchar = false;
char ch = strfont.additionalChars[i];
int charwidth = strfont.charWidth(ch);
if (charwidth <= 0) {
charwidth = 1;
}
int ocharwidth = charwidth;
if (charwidth <= 15 && !StringUtils.isAlphaOrDigit(ch)) {
if (charwidth < strfont.getPixelFontSize()) {
charwidth = (int) strfont.getPixelFontSize();
}
} else if (fullflags.indexOf(ch) != -1 || halfflags.indexOf(ch) != -1) {
charwidth = (int) (ocharwidth * strfont.scalePixelFont);
}
if (charwidth >= 22) {
charwidth -= 1;
} else if (charwidth >= 20 && StringUtils.isAlphaOrDigit(ch)) {
charwidth += 1;
}
int charheight = strfont.getHeight();
if (charheight <= 0) {
charheight = (int) strfont.getPixelFontSize();
}
IntObject newIntObject = new IntObject();
newIntObject.width = charwidth;
newIntObject.height = charheight;
if (positionY <= strfont.textureHeight - newIntObject.height
&& positionX <= strfont.textureWidth - newIntObject.width) {
strfont.drawAlphabet(canvas, ch, positionX, positionY);
} else {
outchached.add(ch);
strfont._outBounds = true;
outchar = true;
}
if (positionX + newIntObject.width >= strfont.textureWidth) {
positionX = 0;
positionY += rowHeight;
rowHeight = 0;
}
newIntObject.storedX = positionX;
newIntObject.storedY = positionY;
if (newIntObject.height < strfont.fontHeight) {
newIntObject.height = (int) strfont.fontHeight;
}
if (newIntObject.height - 1 <= strfont.getPixelFontSize()) {
newIntObject.height += 1;
}
if (newIntObject.height > rowHeight) {
rowHeight = newIntObject.height + 1;
}
positionX += newIntObject.width;
strfont.customChars.put(ch, newIntObject);
if (!outchar) {
strfont._chars.add(ch);
}
}
if (sbr.length() > 0) {
if (positionY <= strfont.textureHeight - strfont.getPixelFontSize()) {
strfont.draw(canvas, sbr.toString(), 0, positionY);
} else {
for (int i = 0; i < sbr.length(); i++) {
outchached.add(sbr.charAt(i));
}
strfont._outBounds = true;
}
sbr = null;
}
LTextureBatch tmpbatch = strfont.fontBatch;
strfont.fontBatch = new LTextureBatch(strfont.displayList = canvas.toTexture());
strfont.fontBatch.setBlendState(BlendState.AlphaBlend);
if (tmpbatch != null) {
tmpbatch.close();
}
// 若字符串超过当前纹理大小,则创建新纹理保存
if (strfont._outBounds) {
StrBuilder temp = new StrBuilder(outchached.size());
for (LIterator<Character> it = outchached.iterator(); it.hasNext();) {
temp.append(it.next());
}
strfont._childFont = new BDFont(strfont.path, strfont.fontIndex, strfont.pixelSize,
temp.toString().toCharArray(), strfont.isasyn, strfont.textureWidth, strfont.textureHeight,
strfont._maxTextureWidth, strfont._maxTextureHeight);
strfont._childFont.cpy(strfont);
}
if (positionX > strfont.textureWidth || positionY > strfont.textureHeight) {
strfont._outBounds = true;
}
strfont._initChars = true;
strfont.isDrawing = false;
}
}
protected static final int NAME_COPYRIGHT = 0;
protected static final int NAME_FAMILY = 1;
protected static final int NAME_STYLE = 2;
protected static final int NAME_UNIQUE_ID = 3;
protected static final int NAME_FAMILY_AND_STYLE = 4;
protected static final int NAME_VERSION = 5;
protected static final int NAME_POSTSCRIPT = 6;
protected static final int NAME_TRADEMARK = 7;
protected static final int NAME_MANUFACTURER = 8;
protected static final int NAME_DESIGNER = 9;
protected static final int NAME_DESCRIPTION = 10;
protected static final int NAME_VENDOR_URL = 11;
protected static final int NAME_DESIGNER_URL = 12;
protected static final int NAME_LICENSE_DESCRIPTION = 13;
protected static final int NAME_LICENSE_URL = 14;
protected static final int NAME_WINDOWS_FAMILY = 16;
protected static final int NAME_WINDOWS_STYLE = 17;
protected static final int NAME_MACOS_FAMILY_AND_STYLE = 18;
protected static final int NAME_SAMPLE_TEXT = 19;
protected static final int NAME_POSTSCRIPT_CID = 20;
protected static final int NAME_WWS_FAMILY = 21;
protected static final int NAME_WWS_STYLE = 22;
private Updateable _submitUpdate;
private final static String fullflags = ",。?;:“‘‘”【】{}《》()~!·¥";
private final static String halfflags = ",.:;\"'?[]{}\\|!`~@#$%^&*()-+=";
private final static int defaultPixelMinFontSize = 12;
private PointI offset;
private IntMap<String> names = new IntMap<String>();
private IntMap<BDFGlyph> characters = new IntMap<BDFGlyph>();
private String fontVersionName;
private String encoding;
private float pixelSize, pixelFontSize;
private float ascent, descent;
private float typoascent, typodescent;
private float xheight, fontHeight, linegap;
private int pixelColor = LColor.DEF_COLOR;
private String path;
private boolean isLoading, isLoaded;
private int fontIndex = 0;
private final char newLineFlag = LSystem.LF;
private final char newSpaceFlag = LSystem.SPACE;
private final char newTabSpaceFlag = LSystem.TAB;
private final char newRFlag = LSystem.CR;
private final CharArray _chars;
private final int _maxTextureWidth;
private final int _maxTextureHeight;
private boolean _isClose = false;
private boolean _outBounds = false;
private boolean _displayLazy = false;
private BDFont _childFont = null;
private int _initDraw = -1;
private int _drawLimit = 0;
private int textureWidth = 512;
private int textureHeight = 512;
private LTexture displayList;
private boolean useCache, isDrawing, isasyn;
private float fontScale = 1f, scalePixelFont = 1f, fontSize;
private float offsetX = 0, offsetY = 0;
private final IntMap<Cache> displays;
private int totalCharSet = 256;
private IntMap<IntObject> customChars = new IntMap<IntObject>();
private LColor[] colors = null;
private String text;
private IntObject intObject;
private Cache display;
private int charCurrent;
private int totalWidth = 0, totalHeight = 0;
private LTextureBatch fontBatch;
private boolean _initChars = false;
private char[] additionalChars = null;
private TArray<CharRect> _childChars;
public BDFont(String path) {
this(path, defaultPixelMinFontSize);
}
public BDFont(String path, float fontSize) {
this(path, 0, fontSize);
}
public BDFont(String path, int idx, float fontSize) {
this(path, idx, fontSize, (char[]) null);
}
public BDFont(String path, String message) {
this(path, 0, defaultPixelMinFontSize, message);
}
public BDFont(String path, float fontSize, String message) {
this(path, 0, fontSize, message);
}
public BDFont(String path, int idx, float fontSize, String message) {
this(path, idx, fontSize, message == null ? null : message.toCharArray(), true, 512, 512, 1024, 1024);
}
public BDFont(String path, int idx, float fontSize, char[] charMessage) {
this(path, idx, fontSize, charMessage, true, 512, 512, 1024, 1024);
}
public BDFont(String path, int idx, float fontSize, char[] charMessage, boolean asyn, int tw, int th, int maxWidth,
int maxHeight) {
CharSequence chs = StringUtils.unificationChars(charMessage);
this.set(0f, 0f, 0f, 0f, 0f, 0f, 1f);
this.path = path;
this.fontIndex = idx;
this.isLoading = isLoaded = false;
this.pixelSize = fontSize;
this._displayLazy = useCache = true;
this._chars = new CharArray(chs.length());
this._maxTextureWidth = maxWidth;
this._maxTextureHeight = maxHeight;
this.textureWidth = tw;
this.textureHeight = th;
this.totalCharSet = getMaxTextCount();
this.displays = new IntMap<Cache>(totalCharSet);
this.isasyn = asyn;
if (chs != null && chs.length() > 0) {
this.text = StringUtils.getString(chs);
this.expandTexture();
}
if (StringUtils.isEmpty(text)) {
_isClose = true;
}
this._drawLimit = 0;
}
public boolean containsTexture(String mes) {
if (StringUtils.isEmpty(text)) {
return false;
}
if (StringUtils.isEmpty(mes)) {
return true;
}
String find = StringUtils.unificationStrings(mes);
for (int i = 0; i < find.length(); i++) {
char ch = find.charAt(i);
if (!StringUtils.isSpace(ch) && text.indexOf(ch) == -1) {
boolean child = false;
if (_childFont != null) {
child = _childFont.containsTexture(mes);
}
return child;
}
}
return true;
}
public boolean containsTexture(char ch) {
if (StringUtils.isEmpty(text)) {
return false;
}
if (StringUtils.isSpace(ch)) {
return true;
}
boolean child = false;
if (_childFont != null) {
child = _childFont.containsTexture(ch);
}
return child || text.indexOf(ch) != -1;
}
public BDFont updateTexture(String message) {
return updateTexture(message, this.isasyn);
}
public BDFont updateTexture(String message, boolean asyn) {
return updateTexture(message != null ? message.toCharArray() : null, asyn);
}
public BDFont updateTexture(char[] charMessage) {
return updateTexture(charMessage, this.isasyn);
}
public BDFont updateTexture(char[] charMessage, boolean asyn) {
if (_isClose) {
return this;
}
cancelSubmit();
this._chars.clear();
for (Cache c : displays.values()) {
if (c != null) {
c.close();
}
}
displays.clear();
if (checkOutBounds()) {
_childFont.close();
_childFont = null;
}
if (fontBatch != null) {
fontBatch.close();
fontBatch = null;
}
if (displayList != null) {
displayList.close(true);
displayList = null;
}
if (customChars != null) {
customChars.clear();
}
if (_childChars != null) {
_childChars.clear();
}
CharSequence chs = StringUtils.unificationChars(charMessage);
this._initChars = _outBounds = isDrawing = false;
this._initDraw = -1;
this.isasyn = asyn;
if (chs != null && chs.length() > 0) {
this.text = StringUtils.getString(chs);
this.expandTexture();
}
if (StringUtils.isEmpty(text)) {
_isClose = true;
}
this._drawLimit = 0;
return this;
}
public void cpy(BDFont font) {
this.names = font.names;
this.characters = font.characters;
this.fontVersionName = font.fontVersionName;
this.encoding = font.encoding;
this.pixelSize = font.pixelSize;
this.pixelFontSize = font.pixelFontSize;
this.ascent = font.ascent;
this.descent = font.descent;
this.typoascent = font.typoascent;
this.typodescent = font.typodescent;
this.xheight = font.xheight;
this.fontHeight = font.fontHeight;
this.linegap = font.linegap;
this.scalePixelFont = font.scalePixelFont;
this.path = font.path;
this.isLoading = font.isLoading;
this.isLoaded = font.isLoaded;
}
private void make() {
make(isasyn);
}
private synchronized void make(boolean asyn) {
if (_isClose) {
return;
}
if (_initChars) {
return;
}
if (isDrawing) {
return;
}
cancelSubmit();
isDrawing = true;
_submitUpdate = new UpdateFont(this);
if (asyn) {
LSystem.unload(_submitUpdate);
} else {
_submitUpdate.action(null);
}
}
public boolean isSubmitting() {
return _submitUpdate == null ? false : LSystem.containsUnLoad(_submitUpdate);
}
public BDFont cancelSubmit() {
if (_submitUpdate != null) {
LSystem.removeUnLoad(_submitUpdate);
}
return this;
}
public boolean loadFont() {
if (!isLoading) {
isLoading = true;
if (!isLoaded && !StringUtils.isEmpty(path)) {
loadFont(path, fontIndex);
isLoaded = true;
}
}
return isLoaded && isLoading;
}
public boolean isLoaded() {
return this.isLoaded;
}
public BDFont reset() {
if (_isClose) {
return this;
}
this.updateTexture(this.text);
if (names != null) {
names.clear();
}
if (characters != null) {
characters.clear();
}
this._initDraw = 0;
this._initChars = false;
this.isDrawing = false;
this.isLoaded = false;
this.isLoading = false;
return this;
}
protected void loadFont(String path, int idx) {
StrTokenizer tokenizer = BaseIO.loadStrTokenizer(path, "\t\n\r\f");
int count = 0;
while (tokenizer.hasMoreTokens()) {
String[] kv = nextSplitChars(tokenizer);
if (kv != null && kv.length > 0) {
if (kv[0].equals("STARTFONT") && idx == count) {
readFont(tokenizer, this);
count++;
}
}
}
}
public BDFont set(float ascent, float descent, float typoascent, float typodescent, float xheight, float linegap,
float scale) {
if (offset == null) {
offset = new PointI();
}
this.ascent = ascent;
this.descent = descent;
this.typoascent = typoascent;
this.typodescent = typodescent;
this.xheight = xheight;
this.linegap = linegap;
this.scalePixelFont = scale;
return this;
}
private static String[] nextSplitChars(StrTokenizer tokenizer) {
String result = tokenizer.nextToken().trim();
return StringUtils.split(result, " ");
}
private static void readChar(StrTokenizer tokenizer, BDFont bm) {
BDFGlyph g = new BDFGlyph();
int encoding = -1;
while (tokenizer.hasMoreTokens()) {
String[] kv = nextSplitChars(tokenizer);
if (kv[0].equals("BITMAP")) {
if (readBitmap(tokenizer, g)) {
break;
}
} else if (kv[0].equals("ENDCHAR")) {
break;
} else if (kv.length < 2) {
continue;
} else if (kv[0].equals("ENCODING")) {
encoding = Integer.parseInt(StringUtils.dequote(kv[1]));
if (bm.encoding == "x") {
encoding += 0xF000;
}
g.encoding = encoding;
} else if (kv[0].equals("DWIDTH")) {
try {
int i = Integer.parseInt(StringUtils.dequote(kv[1]));
g.setCharacterWidth(i);
} catch (LSysException ex) {
}
} else if (kv[0].equals("BBX")) {
try {
int w = (kv.length > 1) ? Integer.parseInt(StringUtils.dequote(kv[1])) : 0;
int h = (kv.length > 2) ? Integer.parseInt(StringUtils.dequote(kv[2])) : 0;
int o = (kv.length > 3) ? Integer.parseInt(StringUtils.dequote(kv[3])) : 0;
int d = (kv.length > 4) ? Integer.parseInt(StringUtils.dequote(kv[4])) : 0;
g.setGlyph(new byte[h][w]);
g.set(o, h + d);
} catch (LSysException ex) {
}
}
}
if (encoding >= 0) {
bm.putCharacter(encoding, g);
}
}
private static boolean readBitmap(StrTokenizer tokenizer, BDFGlyph g) {
byte[][] glyph = g.getGlyph();
int row = 0;
while (tokenizer.hasMoreTokens() && row < glyph.length) {
String[] kv = nextSplitChars(tokenizer);
if (kv[0].equals("ENDCHAR")) {
return true;
} else {
unpack(kv[0], glyph[row++]);
}
}
return false;
}
private static BDFont readFont(StrTokenizer tokenizer, BDFont bm) {
while (tokenizer.hasMoreTokens()) {
String[] kv = nextSplitChars(tokenizer);
if (kv[0].equals("STARTCHAR")) {
readChar(tokenizer, bm);
} else if (kv[0].equals("ENDFONT")) {
break;
} else if (kv.length < 2) {
continue;
}
if (kv[0].equals("FAMILY_NAME")) {
bm.setName(NAME_FAMILY, StringUtils.dequote(kv[1]));
} else if (kv[0].equals("WEIGHT_NAME")) {
bm.setName(NAME_STYLE, StringUtils.dequote(kv[1]));
} else if (kv[0].equals("FONT_VERSION")) {
bm.setName(NAME_VERSION, StringUtils.dequote(kv[1]));
} else if (kv[0].equals("COPYRIGHT")) {
bm.setName(NAME_COPYRIGHT, StringUtils.dequote(kv[1]));
} else if (kv[0].equals("FOUNDRY")) {
bm.setName(NAME_MANUFACTURER, StringUtils.dequote(kv[1]));
} else if (kv[0].equals("FONT")) {
bm.fontVersionName = StringUtils.dequote(kv[1]);
} else if (kv[0].equals("SIZE") || kv[0].equals("PIXEL_SIZE")) {
try {
bm.pixelSize = Integer.parseInt(StringUtils.dequote(kv[1]));
} catch (Exception ex) {
}
} else if (kv[0].equals("FONT_ASCENT")) {
try {
int i = Integer.parseInt(StringUtils.dequote(kv[1]));
bm.setLineAscent(i);
bm.setAscent(i);
} catch (Exception ex) {
}
} else if (kv[0].equals("FONT_DESCENT")) {
try {
int i = Integer.parseInt(StringUtils.dequote(kv[1]));
bm.setLineDescent(i);
bm.setDescent(i);
} catch (Exception ex) {
}
} else if (kv[0].equals("X_HEIGHT")) {
try {
int i = Integer.parseInt(StringUtils.dequote(kv[1]));
bm.setXHeight(i);
} catch (Exception ex) {
}
} else if (kv[0].equals("CHARSET_REGISTRY")) {
bm.encoding = StringUtils.dequote(kv[1]);
}
}
return bm;
}
private static void unpack(String h, byte[] b) {
int i = 0;
CharIterator ci = new CharIterator(h);
for (char ch = ci.first(); ch != CharIterator.DONE; ch = ci.next()) {
int v;
if (ch >= '0' && ch <= '9') {
v = (ch - '0');
} else if (ch >= 'A' && ch <= 'F') {
v = (ch - 'A' + 10);
} else if (ch >= 'a' && ch <= 'f') {
v = (ch - 'a' + 10);
} else {
continue;
}
if (i < b.length) {
b[i++] = (byte) (((v & 0x08) == 0) ? 0 : -1);
}
if (i < b.length) {
b[i++] = (byte) (((v & 0x04) == 0) ? 0 : -1);
}
if (i < b.length) {
b[i++] = (byte) (((v & 0x02) == 0) ? 0 : -1);
}
if (i < b.length) {
b[i++] = (byte) (((v & 0x01) == 0) ? 0 : -1);
}
}
}
public int getTextureWidth() {
return this.textureWidth;
}
public int getTextureHeight() {
return this.textureHeight;
}
public LTexture getTexture() {
return displayList;
}
public boolean isEmpty() {
return characters.isEmpty();
}
public boolean containsCharacter(int ch) {
return characters.containsKey(ch);
}
public int charsCount() {
return characters.size;
}
public BDFGlyph getCharacter(int ch) {
return characters.get(ch);
}
public BDFGlyph putCharacter(int ch, BDFGlyph fc) {
characters.put(ch, fc);
return fc;
}
public BDFGlyph removeCharacter(int ch) {
return characters.remove(ch);
}
public int[] codePoints() {
int[] arr = new int[characters.size()];
int i = 0;
for (int cp : characters.keys()) {
arr[i++] = cp;
}
return arr;
}
public float getScale() {
return scalePixelFont;
}
public BDFont setScale(float scale) {
this.loadFont();
this.scalePixelFont = scale;
return this;
}
public BDFont setPixelFontSize(float size) {
this.loadFont();
if (size > 15) {
this.pixelFontSize = size + 1;
} else {
this.pixelFontSize = size;
}
this.scalePixelFont = (pixelFontSize / this.pixelSize);
return this;
}
public float getPixelFontSize() {
this.loadFont();
return pixelFontSize <= 0 ? this.pixelSize : pixelFontSize;
}
@Override
public float getAscent() {
this.loadFont();
return ascent * scalePixelFont;
}
public float getDescent() {
this.loadFont();
return descent * scalePixelFont;
}
public float getLineAscent() {
this.loadFont();
return typoascent * scalePixelFont;
}
public float getLineDescent() {
this.loadFont();
return typodescent * scalePixelFont;
}
public float getXHeight() {
this.loadFont();
return xheight * scalePixelFont;
}
public float getLineGap() {
this.loadFont();
return linegap * scalePixelFont;
}
public BDFont setAscent(float v) {
ascent = MathUtils.ceil(v);
return this;
}
public BDFont setDescent(float v) {
descent = MathUtils.ceil(v);
return this;
}
public BDFont setLineAscent(float v) {
typoascent = MathUtils.ceil(v);
return this;
}
public BDFont setLineDescent(float v) {
typodescent = MathUtils.ceil(v);
return this;
}
public BDFont setXHeight(float v) {
xheight = MathUtils.ceil(v);
return this;
}
public BDFont setLineGap(float v) {
linegap = MathUtils.ceil(v);
return this;
}
public BDFont setXHeight() {
if (characters.containsKey((int) 'x')) {
BDFGlyph g = characters.get((int) 'x');
xheight = g.getGlyphAscent();
}
return this;
}
private void expandTexture() {
this.additionalChars = text == null ? null : text.toCharArray();
totalCharSet = getMaxTextCount();
if (additionalChars != null && additionalChars.length > totalCharSet) {
textureWidth = MathUtils.min(textureWidth * 2, this._maxTextureWidth);
textureHeight = MathUtils.min(textureHeight * 2, this._maxTextureHeight);
}
}
public PointF draw(Canvas g, String s, PointF b) {
return draw(g, s, b.x, b.y, Integer.MAX_VALUE, typoascent + typodescent + linegap);
}
public PointF draw(Canvas g, String s, PointF b, float w) {
return draw(g, s, b.x, b.y, w, typoascent + typodescent + linegap);
}
public PointF draw(Canvas g, String s, PointF b, float w, float h) {
return draw(g, s, b.x, b.y, w, h);
}
public PointF draw(Canvas g, String s, float bx, float by) {
return draw(g, s, bx, by, Integer.MAX_VALUE, typoascent + typodescent + linegap);
}
public PointF draw(Canvas g, String s, float bx, float by, float w) {
return draw(g, s, bx, by, w, typoascent + typodescent + linegap);
}
public PointF draw(Canvas g, String s, float bx, float by, float w, float h) {
if (!loadFont()) {
return null;
}
if (characters.size == 0) {
return null;
}
float cx = bx, cy = by;
int i = 0;
while (i < s.length()) {
int ch = s.charAt(i);
if (ch < 0x10000) {
i++;
} else {
i += 2;
}
switch (ch) {
case LSystem.LF:
case LSystem.CR:
cx = bx;
cy += ((h + 1) * scalePixelFont);
break;
default:
if (characters.containsKey(ch)) {
BDFGlyph bm = characters.get(ch);
if (cx - bx + bm.getCharacterWidth() >= w) {
cx = bx;
cy += h;
}
float pos = offsetPos((char) ch, bm);
float hl = (bm.getCharacterWidth() * scalePixelFont);
if (halfflags.indexOf(ch) != -1 || StringUtils.isAlphaOrDigit(ch)) {
hl *= 2;
}
cx += bm.paint(g, cx + pos, cy + hl, scalePixelFont, pixelColor);
} else if (characters.containsKey(-1)) {
BDFGlyph bm = characters.get(-1);
if (cx - bx + bm.getCharacterWidth() >= w) {
cx = bx;
cy += h;
}
float pos = offsetPos((char) ch, bm);
float hl = (bm.getCharacterWidth() * scalePixelFont);
if (halfflags.indexOf(ch) != -1 || StringUtils.isAlphaOrDigit(ch)) {
hl *= 2;
}
cx += bm.paint(g, cx + pos, cy + hl, scalePixelFont, pixelColor);
}
break;
}
}
return new PointF(cx, cy);
}
public PointF drawAlphabet(Canvas g, char ch, PointF b) {
return drawAlphabet(g, ch, b.x, b.y, Integer.MAX_VALUE, typoascent + typodescent + linegap);
}
public PointF drawAlphabet(Canvas g, char ch, PointF b, float w) {
return drawAlphabet(g, ch, b.x, b.y, w, typoascent + typodescent + linegap);
}
public PointF drawAlphabet(Canvas g, char ch, PointF b, float w, float h) {
return drawAlphabet(g, ch, b.x, b.y, w, h);
}
public PointF drawAlphabet(Canvas g, char ch, float bx, float by) {
return drawAlphabet(g, ch, bx, by, Integer.MAX_VALUE, typoascent + typodescent + linegap);
}
public PointF drawAlphabet(Canvas g, char ch, float bx, float by, float w) {
return drawAlphabet(g, ch, bx, by, w, typoascent + typodescent + linegap);
}
public PointF drawAlphabet(Canvas g, char ch, float bx, float by, float w, float h) {
if (!loadFont()) {
return null;
}
if (characters.size == 0) {
return null;
}
float cx = bx, cy = by;
if (characters.containsKey(ch)) {
BDFGlyph bm = characters.get(ch);
if (cx - bx + bm.getCharacterWidth() >= w) {
cx = bx;
cy += h;
}
float pos = offsetPos((char) ch, bm);
float hl = (bm.getCharacterWidth() * scalePixelFont);
if (halfflags.indexOf(ch) != -1 || StringUtils.isAlphaOrDigit(ch)) {
hl *= 2;
}
cx += bm.paint(g, cx + pos, cy + hl, scalePixelFont, pixelColor);
}
return new PointF(cx, cy);
}
private final static float offsetPos(char ch, BDFGlyph bm) {
if (halfflags.indexOf(ch) != -1) {
return bm.getCharacterWidth();
}
return fullflags.indexOf(ch) != -1 ? bm.getCharacterWidth() * 1.4f : 0;
}
public BDFont contractGlyphs() {
for (BDFGlyph glyph : characters.values()) {
glyph.contract();
}
return this;
}
public boolean containsName(int nametype) {
return names.containsKey(nametype);
}
public String getName(int nametype) {
return names.get(nametype);
}
public void setName(int nametype, String name) {
names.put(nametype, name);
}
public void removeName(int nametype) {
names.remove(nametype);
}
public int[] nameTypes() {
int[] nt = names.keys();
int[] nt2 = new int[nt.length];
for (int i = 0; i < nt.length; i++) {
nt2[i] = nt[i];
}
return nt2;
}
public boolean isBoldStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("BOLD") || s.contains("BLACK") || s.contains("HEAVY");
} else {
return false;
}
}
public boolean isItalicStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("ITALIC") || s.contains("OBLIQUE") || s.contains("SLANT");
} else {
return false;
}
}
public boolean isUnderlineStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("UNDERLINE") || s.contains("UNDERSCORE");
} else {
return false;
}
}
public boolean isOutlineStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("OUTLINE");
} else {
return false;
}
}
public boolean isShadowStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("SHADOW");
} else {
return false;
}
}
public boolean isCondensedStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("CONDENSE") || s.contains("NARROW");
} else {
return false;
}
}
public boolean isExtendedStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("EXTEND") || s.contains("EXPAND") || s.contains("WIDE");
} else {
return false;
}
}
public boolean isNegativeStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("NEGATIVE") || s.contains("REVERSE") || s.contains("INVERSE") || s.contains("INVERT");
} else {
return false;
}
}
public boolean isStrikeoutStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("STRIKEOUT") || s.contains("STRIKETHR");
} else {
return false;
}
}
public boolean isRegularStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).trim();
return s.equalsIgnoreCase("") || s.equalsIgnoreCase("PLAIN") || s.equalsIgnoreCase("REGULAR")
|| s.equalsIgnoreCase("NORMAL") || s.equalsIgnoreCase("MEDIUM");
} else {
return false;
}
}
public boolean isObliqueStyle() {
if (names.containsKey(NAME_STYLE)) {
String s = names.get(NAME_STYLE).toUpperCase();
return s.contains("OBLIQUE") || s.contains("SLANT");
} else {
return false;
}
}
public int getMacStyle() {
int s = 0;
if (isBoldStyle())
s |= 0x01;
if (isItalicStyle())
s |= 0x02;
if (isUnderlineStyle())
s |= 0x04;
if (isOutlineStyle())
s |= 0x08;
if (isShadowStyle())
s |= 0x10;
if (isCondensedStyle())
s |= 0x20;
if (isExtendedStyle())
s |= 0x40;
return s;
}
public int getFsSelection() {
int s = 0;
if (isItalicStyle())
s |= 0x0001;
if (isUnderlineStyle())
s |= 0x0002;
if (isNegativeStyle())
s |= 0x0004;
if (isOutlineStyle())
s |= 0x0008;
if (isStrikeoutStyle())
s |= 0x0010;
if (isBoldStyle())
s |= 0x0020;
if (isRegularStyle())
s |= 0x0040;
if (isObliqueStyle())
s |= 0x0200;
return s;
}
@Override
public void drawString(GLEx g, String chars, float x, float y, float sx, float sy, float ax, float ay,
float rotation, LColor c) {
drawString(chars, x, y, sx, sy, ax, ay, rotation, c);
}
public void drawString(String chars, float x, float y) {
drawString(x, y, 1f, 1f, 0, 0, 0, chars, LColor.white, 0, chars.length());
}
public void drawString(String chars, float x, float y, LColor color) {
drawString(x, y, 1f, 1f, 0, 0, 0, chars, color, 0, chars.length());
}
public void drawString(String chars, float x, float y, float rotation, LColor color) {
drawString(x, y, 1f, 1f, 0, 0, rotation, chars, color, 0, chars.length());
}
public void drawString(String chars, float x, float y, float rotation) {
drawString(x, y, 1f, 1f, 0, 0, rotation, chars, LColor.white, 0, chars.length());
}
public void drawString(String chars, float x, float y, float sx, float sy, float rotation, LColor c) {
drawString(x, y, sx, sy, 0, 0, rotation, chars, c, 0, chars.length());
}
public void drawString(String chars, float x, float y, float sx, float sy, float ax, float ay, float rotation,
LColor c) {
drawString(x, y, sx, sy, ax, ay, rotation, chars, c, 0, chars.length());
}
private final boolean cehckRunning(String chars) {
if (_isClose) {
return false;
}
if (StringUtils.isEmpty(chars)) {
return false;
}
if (!isLoaded) {
return loadFont();
}
make();
if (processing()) {
return false;
}
if (_displayLazy) {
if (_initDraw < _drawLimit) {
_initDraw++;
return false;
}
}
if (displayList.isClosed()) {
return false;
}
return true;
}
private void drawString(float mx, float my, float sx, float sy, float ax, float ay, float rotation, String chars,
LColor c, int startIndex, int endIndex) {
if (!cehckRunning(chars)) {
return;
}
if (displays.size > LSystem.DEFAULT_MAX_CACHE_SIZE) {
synchronized (displays) {
for (Cache cache : displays.values()) {
if (cache != null) {
cache.close();
cache = null;
}
}
}
displays.clear();
}
final float nsx = sx * fontScale;
final float nsy = sy * fontScale;
final float x = mx + offset.x;
final float y = my + offset.y;
this.intObject = null;
this.charCurrent = 0;
this.totalWidth = 0;
this.totalHeight = 0;
if (rotation != 0 && (ax == 0 && ay == 0)) {
ax = stringWidth(chars) / 2;
ay = getHeight();
}
if (useCache) {
display = displays.get(chars);
if (display == null) {
clearChildString();
fontBatch.begin();
float old = fontBatch.getFloatColor();
fontBatch.setColor(c);
for (int i = startIndex; i < endIndex; i++) {
char ch = chars.charAt(i);
charCurrent = ch;
if (charCurrent == newRFlag) {
continue;
}
if (charCurrent == newLineFlag) {
totalHeight += getPixelFontSize();
totalWidth = 0;
continue;
}
if (charCurrent == newSpaceFlag) {
totalWidth += getAscent();
continue;
}
if (charCurrent == newTabSpaceFlag) {
totalWidth += (getAscent() * 3);
continue;
}
intObject = customChars.get(charCurrent);
if (intObject != null) {
if (!checkOutBounds() || containsChar(ch)) {
fontBatch.drawQuad(totalWidth, totalHeight, (totalWidth + intObject.width) - offsetX,
(totalHeight + intObject.height) - offsetY, intObject.storedX, intObject.storedY,
intObject.storedX + intObject.width - offsetX,
intObject.storedY + intObject.height - offsetY);
} else if (checkOutBounds()) {
putChildChars(ch, totalWidth, totalHeight, (totalWidth + intObject.width) - offsetX,
(totalHeight + intObject.height) - offsetY, null);
}
totalWidth += intObject.width;
}
}
fontBatch.setBlendState(BlendState.AlphaBlend);
fontBatch.commit(x, y, nsx, nsy, ax, ay, rotation);
fontBatch.setColor(old);
displays.put(chars, display = fontBatch.newCache());
} else if (display != null && fontBatch != null && fontBatch.toTexture() != null) {
fontBatch.postCache(display, c, x, y, nsx, nsy, ax, ay, rotation);
}
} else {
clearChildString();
fontBatch.begin();
float old = fontBatch.getFloatColor();
fontBatch.setColor(c);
for (int i = startIndex; i < endIndex; i++) {
char ch = chars.charAt(i);
charCurrent = ch;
if (charCurrent == newRFlag) {
continue;
}
if (charCurrent == newLineFlag) {
totalHeight += getPixelFontSize();
totalWidth = 0;
continue;
}
if (charCurrent == newSpaceFlag) {
totalWidth += getAscent();
continue;
}
if (charCurrent == newTabSpaceFlag) {
totalWidth += (getAscent() * 3);
continue;
}
intObject = customChars.get(charCurrent);
if (intObject != null) {
if (!checkOutBounds() || containsChar(ch)) {
fontBatch.drawQuad(totalWidth, totalHeight, (totalWidth + intObject.width) - offsetX,
(totalHeight + intObject.height) - offsetY, intObject.storedX, intObject.storedY,
intObject.storedX + intObject.width - offsetX,
intObject.storedY + intObject.height - offsetY);
} else if (checkOutBounds()) {
putChildChars(ch, totalWidth, totalHeight, (totalWidth + intObject.width) - offsetX,
(totalHeight + intObject.height) - offsetY, null);
}
totalWidth += intObject.width;
}
}
fontBatch.setColor(old);
fontBatch.setBlendState(BlendState.AlphaBlend);
fontBatch.commit(x, y, nsx, nsy, ax, ay, rotation);
}
if (checkOutBounds() && _childChars != null) {
_childFont._drawChildString(_childChars, mx, my, sx, sy, ax, ay, rotation, chars, c, startIndex, endIndex);
}
}
private void _drawChildString(TArray<CharRect> child, float mx, float my, float sx, float sy, float ax, float ay,
float rotation, String chars, LColor c, int startIndex, int endIndex) {
if (child == null) {
return;
}
if (!cehckRunning(chars)) {
return;
}
if (displays.size > LSystem.DEFAULT_MAX_CACHE_SIZE) {
synchronized (displays) {
for (Cache cache : displays.values()) {
if (cache != null) {
cache.close();
cache = null;
}
}
}
displays.clear();
}
final float nsx = sx * fontScale;
final float nsy = sy * fontScale;
final float x = mx + offset.x;
final float y = my + offset.y;
this.intObject = null;
this.charCurrent = 0;
this.totalWidth = 0;
this.totalHeight = 0;
if (rotation != 0 && (ax == 0 && ay == 0)) {
ax = stringWidth(chars) / 2;
ay = getHeight();
}
if (useCache) {
display = displays.get(chars);
if (display == null) {
fontBatch.begin();
float old = fontBatch.getFloatColor();
fontBatch.setColor(c);
for (int i = 0; i < child.size; i++) {
CharRect rect = child.get(i);
if (rect != null) {
char ch = rect.name;
intObject = customChars.get(ch);
if (intObject != null && containsChar(ch)) {
fontBatch.drawQuad(rect.x, rect.y, rect.width, rect.height, intObject.storedX,
intObject.storedY, intObject.storedX + intObject.width - offsetX,
intObject.storedY + intObject.height - offsetY);
} else if (checkOutBounds()) {
putChildChars(ch, rect.x, rect.y, rect.width, rect.height, null);
}
}
}
fontBatch.setBlendState(BlendState.AlphaBlend);
fontBatch.commit(x, y, nsx, nsy, ax, ay, rotation);
fontBatch.setColor(old);
displays.put(chars, display = fontBatch.newCache());
} else if (display != null && fontBatch != null && fontBatch.toTexture() != null) {
fontBatch.postCache(display, c, x, y, nsx, nsy, ax, ay, rotation);
}
} else {
fontBatch.begin();
float old = fontBatch.getFloatColor();
fontBatch.setColor(c);
for (int i = 0; i < child.size; i++) {
CharRect rect = child.get(i);
if (rect != null) {
char ch = rect.name;
intObject = customChars.get(ch);
if (intObject != null && containsChar(ch)) {
fontBatch.drawQuad(rect.x, rect.y, rect.width, rect.height, intObject.storedX,
intObject.storedY, intObject.storedX + intObject.width - offsetX,
intObject.storedY + intObject.height - offsetY);
} else if (checkOutBounds()) {
putChildChars(ch, rect.x, rect.y, rect.width, rect.height, null);
}
}
}
fontBatch.setColor(old);
fontBatch.setBlendState(BlendState.AlphaBlend);
fontBatch.commit(x, y, nsx, nsy, ax, ay, rotation);
}
if (checkOutBounds() && _childChars != null) {
_childFont._drawChildString(_childChars, mx, my, sx, sy, ax, ay, rotation, chars, c, startIndex, endIndex);
}
}
@Override
public void drawString(GLEx gl, String chars, float x, float y) {
drawString(gl, x, y, 1f, 1f, 0, chars, LColor.white);
}
@Override
public void drawString(GLEx gl, String chars, float x, float y, LColor color) {
drawString(gl, x, y, 1f, 1f, 0, chars, color);
}
@Override
public void drawString(GLEx gl, String chars, float x, float y, float rotation, LColor color) {
drawString(gl, x, y, 1f, 1f, rotation, chars, color);
}
public void drawString(GLEx gl, String chars, float x, float y, float rotation) {
drawString(gl, x, y, 1f, 1f, rotation, chars, LColor.white);
}
public void drawString(GLEx gl, String chars, float x, float y, float sx, float sy, float rotation, LColor c) {
drawString(gl, x, y, sx, sy, rotation, chars, c);
}
public void drawString(GLEx gl, float x, float y, float sx, float sy, float rotation, String chars, LColor c) {
drawString(gl, x, y, sx, sy, 0, 0, rotation, chars, c, 0, chars.length());
}
public void drawString(GLEx gl, float x, float y, float sx, float sy, float ax, float ay, float rotation,
String chars, LColor c) {
drawString(gl, x, y, sx, sy, ax, ay, rotation, chars, c, 0, chars.length());
}
private void drawString(GLEx gl, float mx, float my, float sx, float sy, float ax, float ay, float rotation,
String chars, LColor c, int startIndex, int endIndex) {
if (!cehckRunning(chars)) {
return;
}
final float nsx = sx * fontScale;
final float nsy = sy * fontScale;
final float x = mx + offset.x;
final float y = my + offset.y;
this.intObject = null;
this.charCurrent = 0;
this.totalWidth = 0;
this.totalHeight = 0;
int old = gl.color();
boolean childDraw = false;
final boolean anchor = ax != 0 || ay != 0;
final boolean angle = rotation != 0;
final boolean update = angle || anchor;
final int blend = gl.getBlendMode();
try {
gl.setBlendMode(BlendMethod.MODE_NORMAL);
gl.setTint(c);
if (update) {
gl.saveTx();
Affine2f xf = gl.tx();
if (angle) {
float centerX = x + this.getWidth(chars) / 2;
float centerY = y + this.getHeight(chars) / 2;
xf.translate(centerX, centerY);
xf.preRotate(rotation);
xf.translate(-centerX, -centerY);
}
if (anchor) {
xf.translate(ax, ay);
}
}
for (int i = startIndex; i < endIndex; i++) {
char ch = chars.charAt(i);
charCurrent = ch;
intObject = customChars.get(charCurrent);
if (charCurrent == newRFlag) {
continue;
}
if (charCurrent == newLineFlag) {
totalHeight += getPixelFontSize();
totalWidth = 0;
continue;
}
if (charCurrent == newSpaceFlag) {
totalWidth += ascent;
continue;
}
if (charCurrent == newTabSpaceFlag) {
totalWidth += (ascent * 3);
continue;
}
if (intObject != null) {
if (!checkOutBounds() || containsChar(ch)) {
gl.draw(displayList, x + (totalWidth * nsx), y + (totalHeight * nsy), intObject.width * nsx,
intObject.height * nsy, intObject.storedX, intObject.storedY, intObject.width,
intObject.height, c);
} else if (checkOutBounds()) {
putChildChars(ch, x + (totalWidth * nsx), y + (totalHeight * nsy), intObject.width * nsx,
intObject.height * sy, null);
childDraw = true;
}
totalWidth += intObject.width;
}
}
} finally {
gl.setBlendMode(blend);
gl.setTint(old);
if (update) {
gl.restoreTx();
}
}
if (childDraw && _childChars != null) {
_childFont._drawChildString(_childChars, gl, mx, my, sx, sy, ax, ay, rotation, chars, c, startIndex,
endIndex);
_childChars.clear();
}
}
private void _drawChildString(TArray<CharRect> child, GLEx gl, float mx, float my, float sx, float sy, float ax,
float ay, float rotation, String chars, LColor c, int startIndex, int endIndex) {
if (!cehckRunning(chars)) {
return;
}
final float x = mx + offset.x;
final float y = my + offset.y;
this.intObject = null;
this.charCurrent = 0;
this.totalWidth = 0;
this.totalHeight = 0;
int old = gl.color();
boolean childDraw = false;
final boolean anchor = ax != 0 || ay != 0;
final boolean angle = rotation != 0;
final boolean update = angle || anchor;
final int blend = gl.getBlendMode();
try {
gl.setBlendMode(BlendMethod.MODE_NORMAL);
gl.setTint(c);
if (update) {
gl.saveTx();
Affine2f xf = gl.tx();
if (angle) {
float centerX = x + this.getWidth(chars) / 2;
float centerY = y + this.getHeight(chars) / 2;
xf.translate(centerX, centerY);
xf.preRotate(rotation);
xf.translate(-centerX, -centerY);
}
if (anchor) {
xf.translate(ax, ay);
}
}
for (int i = 0; i < child.size; i++) {
CharRect rect = child.get(i);
if (rect != null) {
char ch = rect.name;
intObject = customChars.get(ch);
if (intObject != null && containsChar(ch)) {
gl.draw(displayList, rect.x, rect.y, rect.width, rect.height, intObject.storedX, intObject.storedY,
intObject.width, intObject.height, c);
} else if (checkOutBounds()) {
putChildChars(ch, rect.x, rect.y, rect.width, rect.height, null);
childDraw = true;
}
}
}
} finally {
gl.setBlendMode(blend);
gl.setTint(old);
if (update) {
gl.restoreTx();
}
}
if (childDraw && _childChars != null) {
_childFont._drawChildString(_childChars, gl, mx, my, sx, sy, ax, ay, rotation, chars, c, startIndex,
endIndex);
_childChars.clear();
}
}
public int getMaxTextCount() {
float size = MathUtils.max(defaultPixelMinFontSize, pixelSize) + 1;
return MathUtils.max(0, (int) ((textureWidth / size) * (textureHeight / size)));
}
public int getTextCount() {
return _chars != null ? _chars.size() : 0;
}
public String getChars() {
return _chars.getString();
}
private boolean checkCharRunning() {
if (_isClose) {
return false;
}
make();
if (processing()) {
return false;
}
if (_displayLazy) {
if (_initDraw < _drawLimit) {
_initDraw++;
return false;
}
}
if (displayList.isClosed()) {
return false;
}
return true;
}
public void addChar(char c, float x, float y, LColor color) {
if (!checkCharRunning()) {
return;
}
if (c == newLineFlag || c == newRFlag || c == newSpaceFlag || c == newTabSpaceFlag) {
return;
}
if (!checkOutBounds() || containsChar(c)) {
this.charCurrent = c;
intObject = customChars.get(charCurrent);
if (intObject != null) {
if (color != null) {
setImageColor(color);
}
fontBatch.setBlendState(BlendState.AlphaBlend);
if (c == newLineFlag) {
fontBatch.draw(colors, x, y + getPixelFontSize(), intObject.width * fontScale - offsetX,
intObject.height * fontScale - offsetY, intObject.storedX, intObject.storedY,
intObject.storedX + intObject.width - offsetX,
intObject.storedY + intObject.height - offsetY);
} else {
fontBatch.draw(colors, x, y, intObject.width * fontScale - offsetX,
intObject.height * fontScale - offsetY, intObject.storedX, intObject.storedY,
intObject.storedX + intObject.width - offsetX,
intObject.storedY + intObject.height - offsetY);
}
if (colors != null) {
colors = null;
}
}
} else if (checkOutBounds()) {
putChildChars(c, x, y, intObject.width, intObject.height, color);
}
}
private void clearChildString() {
if (checkOutBounds() && _childChars != null) {
_childChars.clear();
}
}
public void startChar() {
if (!checkCharRunning()) {
return;
}
clearChildString();
fontBatch.begin();
}
public void stopChar() {
if (!checkCharRunning()) {
return;
}
GL20 g = LSystem.base().graphics().gl;
if (g != null) {
int old = GLUtils.getBlendMode();
GLUtils.setBlendMode(g, BlendMethod.MODE_NORMAL);
fontBatch.end();
GLUtils.setBlendMode(g, old);
}
postChildString();
}
private void postChildString() {
if (checkOutBounds() && _childChars != null) {
int len = _childChars.size;
if (len > 0) {
_childFont.startChar();
for (int i = 0; i < len; i++) {
CharRect rect = _childChars.get(i);
_childFont.addChar(rect.name, rect.x, rect.y, rect.color);
}
_childFont.stopChar();
}
}
}
private boolean checkOutBounds() {
return _outBounds && _childFont != null;
}
private boolean processing() {
return fontBatch == null || isDrawing;
}
public void postCharCache() {
if (!checkCharRunning()) {
return;
}
GL20 g = LSystem.base().graphics().gl;
if (g != null) {
int old = GLUtils.getBlendMode();
GLUtils.setBlendMode(g, BlendMethod.MODE_NORMAL);
fontBatch.postLastCache();
GLUtils.setBlendMode(g, old);
}
postChildString();
}
public Cache saveCharCache() {
if (!checkCharRunning()) {
return null;
}
fontBatch.disposeLastCache();
return fontBatch.newCache();
}
public LTextureBatch getFontBatch() {
return fontBatch;
}
private void setImageColor(float r, float g, float b, float a) {
setColor(Painter.TOP_LEFT, r, g, b, a);
setColor(Painter.TOP_RIGHT, r, g, b, a);
setColor(Painter.BOTTOM_LEFT, r, g, b, a);
setColor(Painter.BOTTOM_RIGHT, r, g, b, a);
}
private void setImageColor(LColor c) {
if (c == null) {
return;
}
setImageColor(c.r, c.g, c.b, c.a);
}
private void setColor(int corner, float r, float g, float b, float a) {
if (colors == null) {
colors = new LColor[] { new LColor(1, 1, 1, 1f), new LColor(1, 1, 1, 1f), new LColor(1, 1, 1, 1f),
new LColor(1, 1, 1, 1f) };
}
colors[corner].r = r;
colors[corner].g = g;
colors[corner].b = b;
colors[corner].a = a;
}
public boolean containsChar(char c) {
return _chars.contains(c);
}
public boolean containsChars(String str) {
if (StringUtils.isEmpty(str)) {
return true;
}
int count = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
if (_chars.contains(str.charAt(i))) {
count++;
}
}
return count == len;
}
public int getPixelColor() {
return this.pixelColor;
}
public void setPixelColor(int pixel) {
this.pixelColor = pixel;
}
public void setPixelColor(LColor color) {
this.pixelColor = (color == null ? LColor.DEF_COLOR : color.getARGB());
}
public int charHeight(char c) {
return charWidth(c);
}
@Override
public int charWidth(char c) {
loadFont();
if (characters.containsKey(c)) {
BDFGlyph g = characters.get(c);
if (fullflags.indexOf(c) != -1) {
return (int) (g.getCharacterWidth() * 1.4f * scalePixelFont);
} else {
return (int) (g.getCharacterWidth() * scalePixelFont);
}
}
return 0;
}
public int getLineWidth(String message) {
if (StringUtils.isNullOrEmpty(message)) {
return 0;
}
loadFont();
int count = 0;
for (int i = 0, size = message.length(); i < size; i++) {
char ch = message.charAt(i);
if (characters.containsKey(ch)) {
BDFGlyph g = characters.get(ch);
if (fullflags.indexOf(ch) != -1) {
count += (int) (g.getCharacterWidth() * 1.4f * scalePixelFont);
} else {
count += (int) (g.getCharacterWidth() * scalePixelFont);
}
}
}
return count;
}
@Override
public int stringWidth(String message) {
if (StringUtils.isNullOrEmpty(message)) {
return 0;
}
loadFont();
if (message.indexOf(LSystem.LF) == -1) {
return getLineWidth(message);
} else {
StrBuilder sbr = new StrBuilder();
int width = 0;
for (int i = 0, size = message.length(); i < size; i++) {
char ch = message.charAt(i);
if (ch == LSystem.LF) {
width = MathUtils.max(getLineWidth(sbr.toString()), width);
sbr.setLength(0);
} else {
sbr.append(ch);
}
}
return width;
}
}
@Override
public int stringHeight(String message) {
if (StringUtils.isNullOrEmpty(message)) {
return 0;
}
loadFont();
if (message.indexOf(LSystem.LF) == -1) {
return getHeight();
} else {
String[] list = StringUtils.split(message, LSystem.LF);
return list.length * getHeight();
}
}
@Override
public int getHeight() {
return (int) MathUtils.max(fontHeight, getPixelFontSize()) + 1;
}
@Override
public void setAssent(float assent) {
this.setAscent(assent);
}
@Override
public String getFontName() {
return names.get(NAME_FAMILY);
}
public void setFontSize(float size) {
setSize((int) size);
}
@Override
public void setSize(int size) {
this.fontSize = size;
this.fontScale = fontSize / getPixelFontSize();
}
public int getFontSize() {
return getSize();
}
@Override
public int getSize() {
return this.fontSize == 0 ? (int) getPixelFontSize() : (int) fontSize;
}
@Override
public PointI getOffset() {
return offset;
}
@Override
public void setOffset(PointI v) {
offset.set(v);
}
@Override
public void setOffsetX(int x) {
offset.x = x;
}
@Override
public void setOffsetY(int y) {
this.offset.y = y;
}
@Override
public String confineLength(String s, int width) {
int length = 0;
for (int i = 0; i < s.length(); i++) {
length += stringWidth(String.valueOf(s.charAt(i)));
if (length >= width) {
int pLength = stringWidth("...");
while (length + pLength >= width && i >= 0) {
length -= stringWidth(String.valueOf(s.charAt(i)));
i--;
}
s = s.substring(0, ++i) + "...";
break;
}
}
return s;
}
public int getWidth(String s) {
if (_isClose) {
return 0;
}
make();
if (processing()) {
return stringWidth(s);
}
if (displayList.isClosed()) {
return 0;
}
int totalWidth = 0;
IntObject intObject = null;
int currentChar = 0;
char[] charList = s.toCharArray();
int maxWidth = 0;
for (int i = 0; i < charList.length; i++) {
currentChar = charList[i];
intObject = customChars.get(currentChar);
if (intObject != null) {
if (currentChar == newLineFlag) {
maxWidth = MathUtils.max(maxWidth, totalWidth);
totalWidth = 0;
}
totalWidth += intObject.width;
}
}
return MathUtils.max(maxWidth, totalWidth);
}
public int getHeight(String s) {
if (_isClose) {
return 0;
}
make();
if (processing()) {
return stringHeight(s);
}
if (displayList.isClosed()) {
return 0;
}
int currentChar = 0;
char[] charList = s.toCharArray();
int lines = 0;
int height = 0;
int maxHeight = 0;
for (int i = 0; i < charList.length; i++) {
currentChar = charList[i];
intObject = customChars.get(currentChar);
if (intObject != null) {
maxHeight = MathUtils.max(maxHeight, intObject.height);
height = maxHeight;
}
if (currentChar == newLineFlag) {
lines++;
height = 0;
}
}
return (int) (lines * getLineAscent() + height);
}
public boolean isClosed() {
return _isClose;
}
@Override
public void close() {
if (_isClose) {
return;
}
cancelSubmit();
for (Cache c : displays.values()) {
if (c != null) {
c.close();
}
}
displays.clear();
if (fontBatch != null) {
fontBatch.close();
fontBatch = null;
}
if (displayList != null) {
displayList.close(true);
displayList = null;
}
if (customChars != null) {
customChars.clear();
customChars = null;
}
isDrawing = false;
_displayLazy = false;
_initChars = false;
_initDraw = -1;
_isClose = true;
if (checkOutBounds()) {
_childFont.close();
_childFont = null;
}
}
}
| 24,946 |
2,867 | <gh_stars>1000+
#include <mysqlx/xdevapi.h>
using namespace ::mysqlx;
function __NJS_NATIVE_CONNECT_MYSQL(_auth, _schema, _coll)
{
try
{
if(!_auth) _auth = "mysqlx://root@localhost";
else
{
if(_auth.type == __NJS_STRING) _auth = "mysqlx://" + _auth;
else if(_auth.type == __NJS_OBJECT)
{
var _strauth = "mysqlx://";
var _user = __NJS_Object_Get("user", _auth);
if(_user.type == __NJS_STRING) _strauth += _user;
else _strauth += "root";
var _pass = __NJS_Object_Get("pass", _auth);
if(_pass.type == __NJS_STRING) _strauth += ":" + _pass;
var _host = __NJS_Object_Get("host", _auth);
if(_host.type == __NJS_STRING) _strauth += "@" + _host;
else _strauth += "localhost";
_auth = _strauth;
}
}
if(!_schema) _schema = "nectarSchema";
if(!_coll) _coll = "nectar";
Session* sess = new Session(__NJS_Get_String(_auth));
Schema sch= sess->getSchema(__NJS_Get_String(_schema));
Collection coll= sch.createCollection(__NJS_Get_String(_coll), true);
var _mysqlObject = __NJS_Create_Object();
function _mysql_close()
{
delete sess;
};
function _mysql_add(_json)
{
"SCOPED_FUNCTION";
try
{
coll.add(__NJS_Get_String(_json)).execute();
var _result = __NJS_Create_Boolean(1);
return _result;
}
catch(const std::exception& e)
{
return __NJS_Create_Boolean(0);
}
};
function _mysql_modify(_obj)
{
"SCOPED_FUNCTION";
try
{
var _search = __NJS_Object_Get("search",_obj);
if(_search.type != __NJS_STRING) return __NJS_Create_Boolean(0);
auto _cm = coll.modify(__NJS_Get_String(_search));
var _set = __NJS_Object_Get("set", _obj);
if(_set && _set.type == __NJS_ARRAY)
{
for(int i = 0; i < _set.get().a->__NJS_VALUE.size(); i+=2)
{
if(i+1 <= _set.get().a->__NJS_VALUE.size())
{
var _left = __NJS_Object_Get(i, _set);
var _right = __NJS_Object_Get(i+1, _set);
if(_left.type == __NJS_STRING && _right.type == __NJS_STRING)
_cm.set(__NJS_Get_String(_left), __NJS_Get_String(_right));
}
}
}
_cm.execute();
var _result = __NJS_Create_Boolean(1);
return _result;
}
catch(const std::exception& e)
{
return __NJS_Create_Boolean(0);
}
}
function _mysql_find(_request)
{
"SCOPED_FUNCTION";
try
{
var _result = __NJS_Create_Array();
std::list<DbDoc> dbList;
if(_request) dbList = coll.find(__NJS_Get_String(_request)).execute().fetchAll();
else dbList = coll.find().execute().fetchAll();
int i = 0;
std::list<DbDoc>::iterator it;
stringstream s;
s << "{\"data\":[";
for (it = dbList.begin(); it != dbList.end(); it++)
{
if(i) s << ",";
it->print(s);
i++;
}
s << "], \"code\":0, \"length\":" << dbList.size() << "}";
std::string _str = std::string(s.str());
var _data = _str.c_str();
return _data;
}
catch(const std::exception& e)
{
return '{"code:"1, "msg":"Find error"}';
}
}
function _mysql_remove(_request)
{
"SCOPED_FUNCTION";
try
{
coll.remove(__NJS_Get_String(_request)).execute();
return __NJS_Create_Boolean(1);
}
catch(const std::exception& e)
{
return __NJS_Create_Boolean(0);
}
}
__NJS_Object_Set("version", "8", _mysqlObject);
__NJS_Object_Set("add", _mysql_add, _mysqlObject);
__NJS_Object_Set("modify", _mysql_modify, _mysqlObject);
__NJS_Object_Set("find", _mysql_find, _mysqlObject);
__NJS_Object_Set("remove", _mysql_remove, _mysqlObject);
__NJS_Object_Set("close", _mysql_close, _mysqlObject);
return _mysqlObject;
}
catch (const mysqlx::Error &err)
{
cout <<"ERROR: " <<err <<endl;
return var();
}
catch (std::exception &ex)
{
cout <<"STD EXCEPTION: " <<ex.what() <<endl;
return var();
}
catch (const char *ex)
{
cout <<"EXCEPTION: " <<ex <<endl;
return var();
}
};
| 3,473 |
351 | <filename>python/app/plugins/http/Jenkins/CVE_2018_1000110.py
#!/usr/bin/env python3
import re
from app.lib.utils.request import request
from app.lib.utils.common import get_capta, get_useragent
class CVE_2018_1000110_BaseVerify:
def __init__(self, url):
self.info = {
'name': 'CVE-2018-1000110漏洞',
'description': 'CVE-2018-1000110漏洞,可用来用户名枚举,受影响版本: Jenkins Git Plugin version 3.7.0 and earlier in GitStatus.java',
'date': '2018-03-13',
'exptype': 'check',
'type': 'Username Enum'
}
self.url = url
if not self.url.startswith("http") and not self.url.startswith("https"):
self.url = "http://" + self.url
self.headers = {
"User-Agent": get_useragent()
}
self.capta = get_capta()
def check(self):
"""
检测是否存在漏洞
:param:
:return bool True or False: 是否存在漏洞
"""
result = ""
url = self.url + "/securityRealm/user/admin/search/index?q="
try:
check_req = request.get(url + self.capta, headers = self.headers)
if "Search for '%s'" % (self.capta) in check_req.text:
return True
else:
print('不存在CVE-2018-1000110用户枚举漏洞')
return False
except Exception as e:
print(e)
print('不存在CVE-2018-1000110用户枚举漏洞')
return False
finally:
pass
if __name__ == '__main__':
CVE_2018_1000110 = CVE_2018_1000110_BaseVerify('http://10.4.69.55:8789')
CVE_2018_1000110.check() | 914 |
335 | <gh_stars>100-1000
{
"word": "Jet",
"definitions": [
"A rapid stream of liquid or gas forced out of a small opening.",
"A nozzle or narrow opening for sending out a jet of liquid or gas.",
"A jet engine.",
"An aircraft powered by one or more jet engines."
],
"parts-of-speech": "Noun"
} | 130 |
819 | /*
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef VR_SEURAT_TILER_SELECTION_SELECTION_SOLVER_H_
#define VR_SEURAT_TILER_SELECTION_SELECTION_SOLVER_H_
#include <vector>
#include "absl/types/span.h"
#include "seurat/tiler/selection/selection_problem.h"
namespace seurat {
namespace tiler {
namespace selection {
// An interface for solving SelectionProblems.
//
// Implementations are not thread safe unless specified otherwise.
class SelectionSolver {
public:
virtual ~SelectionSolver() = default;
// Sets the current problem to solve, possibly precomputing values required
// for the subsequent Solve().
//
// A single Init() may be followed by multiple Solve()'s to iteratively
// improve upon a solution.
virtual void Init(const SelectionProblem& problem) = 0;
// Solves the current problem, possibly making use of an existing
// |multipliers|.
//
// Returns the items which were selected as well as the |multipliers|
// corresponding to this solution.
//
// Returns false upon failure, e.g. due to numerical stability problems.
virtual bool Solve(absl::Span<double> multipliers,
std::vector<int>* selected) = 0;
};
// Evaluates the dual of a SelectionProblem.
//
// See selection_problem.h for details.
class DualSelectionSolver {
public:
virtual ~DualSelectionSolver() = default;
// Sets the current problem to solve, possibly precomputing values required
// for the subsequent Solve().
//
// A single Init() may be followed by multiple Solve()'s to iteratively
// improve upon a solution.
virtual void Init(const SelectionProblem& problem) = 0;
// Evaluates the dual of the current problem at the given |multipliers|.
//
// Returns false upon failure, e.g. due to numerical stability problems.
virtual bool Solve(absl::Span<const double> multipliers,
std::vector<int>* selected) = 0;
};
} // namespace selection
} // namespace tiler
} // namespace seurat
#endif // VR_SEURAT_TILER_SELECTION_SELECTION_SOLVER_H_
| 763 |
514 | ##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
"""Supplies custom logging levels BLATHER and TRACE.
$Revision: 1.1 $
"""
import logging
__all__ = ["BLATHER", "TRACE"]
# In the days of zLOG, there were 7 standard log levels, and ZODB/ZEO used
# all of them. Here's how they map to the logging package's 5 standard
# levels:
#
# zLOG logging
# ------------- ---------------
# PANIC (300) FATAL, CRITICAL (50)
# ERROR (200) ERROR (40)
# WARNING, PROBLEM (100) WARN (30)
# INFO (0) INFO (20)
# BLATHER (-100) none -- defined here as BLATHER (15)
# DEBUG (-200) DEBUG (10)
# TRACE (-300) none -- defined here as TRACE (5)
#
# TRACE is used by ZEO for extremely verbose trace output, enabled only
# when chasing bottom-level communications bugs. It really should be at
# a lower level than DEBUG.
#
# BLATHER is a harder call, and various instances could probably be folded
# into INFO or DEBUG without real harm.
BLATHER = 15
TRACE = 5
logging.addLevelName(BLATHER, "BLATHER")
logging.addLevelName(TRACE, "TRACE")
| 634 |
1,236 | <reponame>jasonfeihe/BitFunnel<filename>NativeJIT/inc/Temporary/StlAllocator.h
// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <cstddef> // For ptrdiff_t and size_t.
#include "IAllocator.h"
namespace Allocators
{
//*************************************************************************
//
// StlAllocator is a is a wrapper class for IAllocator. It is used to
// create an allocator that is compatible with the STL container classes
// like map and vector.
//
// This template declaration is a subset of the declaration in the C++98
// spec (ISO/IEC 14882:1998), section 20.4.1.
// See specification draft: http://www.open-std.org/jtc1/sc22/open/n2356/.
// Also see http://www.codeguru.com/Cpp/Cpp/cpp_mfc/stl/article.php/c4079/.
//
//*************************************************************************
template <typename T> class StlAllocator {
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <typename U> struct rebind
{
typedef StlAllocator<U> other;
};
StlAllocator(IAllocator& allocator);
// The following two methods are in the C++98 specification but were
// not implemented. Keeping the declarations here to document
// differences from the specification and to help with debugging.
//StlAllocator() throw();
//StlAllocator(const StlAllocator&) throw();
template <typename U> StlAllocator(const StlAllocator<U>&) throw();
// The following method is in the C++98 specification but was
// not implemented. Keeping the declarations here to document
// differences from the specification and to help with debugging.
//~StlAllocator() throw();
pointer address(reference x) const;
const_pointer address(const_reference x) const;
pointer allocate(size_type count, const void* hint = 0);
void deallocate(pointer p, size_type n);
size_type max_size() const throw();
void construct(pointer p, const_reference val);
void destroy(pointer p);
bool operator==(const StlAllocator&);
bool operator!=(const StlAllocator&);
private:
template <typename S>
friend class StlAllocator;
// StlAllocator does not implement an assignment operator because
// it stores a reference to its IAllocator.
StlAllocator& operator=(const StlAllocator&);
IAllocator& m_allocator;
};
template <typename T>
StlAllocator<T>::StlAllocator(IAllocator& allocator)
: m_allocator(allocator)
{
}
template <typename T>
template <typename U>
StlAllocator<T>::StlAllocator(const StlAllocator<U>& rhs) throw()
: m_allocator(rhs.m_allocator)
{
}
template <typename T>
typename StlAllocator<T>::pointer StlAllocator<T>::address(typename StlAllocator<T>::reference x) const
{
return &x;
}
template <typename T>
typename StlAllocator<T>::const_pointer StlAllocator<T>::address(typename StlAllocator<T>::const_reference x) const
{
return &x;
}
template <typename T>
typename StlAllocator<T>::pointer StlAllocator<T>::allocate(typename StlAllocator<T>::size_type count, const void* /*hint*/)
{
return static_cast<StlAllocator<T>::pointer>(m_allocator.Allocate(sizeof(T) * count));
}
template <typename T>
void StlAllocator<T>::deallocate(typename StlAllocator<T>::pointer p, typename StlAllocator<T>::size_type /*count*/)
{
m_allocator.Deallocate(p);
}
template <typename T>
typename StlAllocator<T>::size_type StlAllocator<T>::max_size() const throw()
{
return m_allocator.MaxSize();
}
template <typename T>
void StlAllocator<T>::construct(typename StlAllocator<T>::pointer ptr, typename StlAllocator<T>::const_reference val)
{
new (ptr) T(val);
}
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4100)
#endif
// Warning C4100 says that 'ptr' is unreferenced as a formal parameter.
// This happens when T is a simple type like int. In this case it seems that
// the compiler optimizes away the call to ptr->~T(), causing the ptr to
// seem unreferenced. This seems like a compiler bug.
template <typename T>
void StlAllocator<T>::destroy(typename StlAllocator<T>::pointer ptr)
{
ptr->~T();
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
template <typename T>
bool StlAllocator<T>::operator==(const StlAllocator&)
{
return true;
}
template <typename T>
bool StlAllocator<T>::operator!=(const StlAllocator&)
{
return false;
}
}
| 2,324 |
421 | """Utilities for multithreaded parallel execution of tasks."""
import threading
import multiprocessing
import multiprocessing.pool
from contextlib import contextmanager
from Queue import Queue
import logging
from .log import log_to_client
class TaskQueue(Queue, object):
"""Executable task queue used for multithreaded execution of multiple
function calls. Concurrency is limited by `pool_size`."""
def __init__(self, pool_size):
super(TaskQueue, self).__init__()
self.pool_size = pool_size
self.errors = []
def enqueue_task(self, fn, *args, **kwargs):
self.put((fn, args, kwargs))
def _task_executor(self, fn, args, kwargs):
try:
fn(*args, **kwargs)
except Exception as e:
self.errors.append(e)
def execute(self):
self.pool = multiprocessing.pool.ThreadPool(self.pool_size)
while not self.empty():
fn, args, kwargs = self.get()
self.pool.apply_async(self._task_executor, args=(fn, args, kwargs))
self.pool.close()
self.pool.join()
if self.errors:
for error in self.errors:
logging.exception(error)
error_msg = error.message or str(error)
log_to_client(error_msg)
raise RuntimeError("Exceptions encountered during parallel task execution")
@contextmanager
def parallel_task_queue(pool_size=multiprocessing.cpu_count()):
"""Context manager for setting up a TaskQueue. Upon leaving the
context manager, all tasks that were enqueued will be executed
in parallel subject to `pool_size` concurrency constraints."""
task_queue = TaskQueue(pool_size)
yield task_queue
task_queue.execute()
| 685 |
409 | <reponame>tapir-dream/berserkJS
#ifndef PAGEEXTENSION_H
#define PAGEEXTENSION_H
#include <QObject>
#include <QtScript>
#include "scriptbinding.h"
#include "mywebview.h"
#include "appinfo.h"
class PageExtension : public QObject
{
Q_OBJECT
private:
MyWebView* webview;
public:
explicit PageExtension(MyWebView* webview);
~PageExtension();
AppInfo* appInfo;
signals:
public slots:
void message(QString wparam = "",
QString lparam = "");
void sendSignal(QString signal = "",
QString value = "");
double cpu();
double memory();
};
#endif // PAGEEXTENSION_H
| 266 |
479 |
import sys
import antlr
import tinyc_l
import inherit_p
def main():
L = tinyc_l.Lexer()
P = inherit_p.Parser(L)
P.setFilename(L.getFilename())
### Parse the input expression
try:
P.program()
except antlr.ANTLRException, ex:
print "*** error(s) while parsing."
print ">>> exit(1)"
sys.exit(1)
ast = P.getAST()
if not ast:
print "stop - no AST generated."
return
###show tree
print "Tree: " + ast.toStringTree()
print "List: " + ast.toStringList()
print "Node: " + ast.toString()
print "visit>>"
visitor = Visitor()
visitor.visit(ast);
print "visit<<"
if __name__ == "__main__":
main()
| 308 |
575 | <gh_stars>100-1000
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_PAGE_IMAGE_ANNOTATION_CONTENT_RENDERER_CONTENT_PAGE_ANNOTATOR_DRIVER_H_
#define COMPONENTS_PAGE_IMAGE_ANNOTATION_CONTENT_RENDERER_CONTENT_PAGE_ANNOTATOR_DRIVER_H_
#include <map>
#include <utility>
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "components/page_image_annotation/core/page_annotator.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_observer_tracker.h"
#include "third_party/blink/public/web/web_element.h"
#include "ui/base/page_transition_types.h"
namespace page_image_annotation {
// This class holds a PageAnnotator for a given RenderFrame and feeds it
// information about images as they appear / disappear from the page.
//
// This class can also be used to access the Content-level interface (i.e.
// blink::WebElement) for DOM nodes with associated images.
class ContentPageAnnotatorDriver
: public content::RenderFrameObserver,
public content::RenderFrameObserverTracker<ContentPageAnnotatorDriver> {
public:
~ContentPageAnnotatorDriver() override;
static ContentPageAnnotatorDriver* GetOrCreate(
content::RenderFrame* render_frame);
// Given a page URL and a URI fragment (which could possibly be an absolute
// URL, relative URL or data URI), produces a source ID.
//
// The source ID of a URL is the absolute version of the URL. The source ID of
// a data URI is the base64 encoded SHA256 hash of the data string.
//
// If a source ID cannot be generated (e.g. the URI fragment is malformed),
// the empty string is returned.
static std::string GenerateSourceId(const GURL& page_url,
const std::string& uri_fragment);
PageAnnotator& GetPageAnnotator();
// Returns the element associated with the given node ID. If there is no such
// element, returns a null blink::WebElement.
blink::WebElement GetElement(uint64_t node_id);
private:
// We delete ourselves on frame destruction, so disallow construction on the
// stack.
ContentPageAnnotatorDriver(content::RenderFrame* render_frame);
// content::RenderFrameObserver:
void DidFinishDocumentLoad() override;
void OnDestruct() override;
// Traverse the DOM starting at the given node, and add all elements with
// associated images to the |tracked_elements_| map.
void FindImages(const GURL& page_url, blink::WebElement element);
// Traverse the DOM for elements with associated images, add these elements to
// |tracked_elements_|, and send element info to the PageAnnotator.
void FindAndTrackImages();
// Return the bitmap associated with the given node ID.
SkBitmap GetBitmapForId(uint64_t node_id);
// The next ID to assign to a DOM node.
uint64_t next_node_id_;
// The current set of tracked DOM nodes.
std::map<uint64_t, std::pair<PageAnnotator::ImageMetadata, blink::WebElement>>
tracked_elements_;
PageAnnotator page_annotator_;
base::WeakPtrFactory<ContentPageAnnotatorDriver> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ContentPageAnnotatorDriver);
};
} // namespace page_image_annotation
#endif // COMPONENTS_PAGE_IMAGE_ANNOTATION_CONTENT_RENDERER_CONTENT_PAGE_ANNOTATOR_DRIVER_H_
| 1,089 |
4,320 | <filename>runelite-jshell/src/main/java/net/runelite/jshell/RemappingThrowable.java
/*
* Copyright (c) 2021 Abex
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.jshell;
import com.google.common.base.Strings;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import jdk.jshell.EvalException;
class RemappingThrowable extends Throwable
{
private final String source;
private final Map<String, Integer> offsets;
private final Throwable wrapped;
private final Map<Throwable, Throwable> dejaVu;
public RemappingThrowable(String source, Map<String, Integer> offsets, Throwable other)
{
this(source, offsets, other, new HashMap<>());
}
private RemappingThrowable(String source, Map<String, Integer> offsets, Throwable other, Map<Throwable, Throwable> dejaVu)
{
super();
this.source = source;
this.offsets = offsets;
this.wrapped = other;
this.dejaVu = dejaVu;
dejaVu.put(wrapped, this);
setStackTrace(Stream.of(wrapped.getStackTrace())
.map(e ->
{
Integer boxOffset = offsets.get(e.getFileName());
if (boxOffset == null)
{
return e;
}
int offset = boxOffset;
int line = e.getLineNumber();
for (int i = 0; i <= offset && i < source.length(); i++)
{
if (source.charAt(i) == '\n')
{
line++;
}
}
return new StackTraceElement(
Strings.isNullOrEmpty(e.getClassName()) ? "Shell" : e.getClassName(),
Strings.isNullOrEmpty(e.getMethodName()) ? "global" : e.getMethodName(),
"",
line);
})
.toArray(StackTraceElement[]::new));
if (wrapped.getCause() != null)
{
initCause(remap(wrapped.getCause()));
}
for (Throwable suppressed : wrapped.getSuppressed())
{
addSuppressed(remap(suppressed));
}
}
private Throwable remap(Throwable other)
{
Throwable remap = dejaVu.get(other);
if (remap == null)
{
remap = new RemappingThrowable(source, offsets, other, dejaVu);
// ctor inserts into the map
}
return remap;
}
@Override
public String getMessage()
{
return wrapped.getMessage();
}
@Override
public String getLocalizedMessage()
{
return wrapped.getLocalizedMessage();
}
@Override
public synchronized Throwable fillInStackTrace()
{
return this;
}
@Override
public String toString()
{
String className;
if (wrapped instanceof EvalException)
{
className = ((EvalException) wrapped).getExceptionClassName();
}
else
{
className = wrapped.getClass().getName();
}
String message = wrapped.getLocalizedMessage();
if (message == null)
{
return className;
}
return className + ": " + message;
}
}
| 1,388 |
6,304 | <reponame>rhencke/engine
// Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "tools/fiddle/examples.h"
// HASH=5de2de0f00354e59074a9bb1a42d5a63
REG_FIDDLE(Miter_Limit, 384, 170, false, 0) {
void draw(SkCanvas* canvas) {
SkPoint pts[] = {{ 10, 50 }, { 110, 80 }, { 10, 110 }};
SkVector v[] = { pts[0] - pts[1], pts[2] - pts[1] };
SkScalar angle1 = SkScalarATan2(v[0].fY, v[0].fX);
SkScalar angle2 = SkScalarATan2(v[1].fY, v[1].fX);
const SkScalar strokeWidth = 20;
SkScalar miterLimit = 1 / SkScalarSin((angle2 - angle1) / 2);
SkScalar miterLength = strokeWidth * miterLimit;
SkPath path;
path.moveTo(pts[0]);
path.lineTo(pts[1]);
path.lineTo(pts[2]);
SkPaint paint; // set to default kMiter_Join
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeMiter(miterLimit);
paint.setStrokeWidth(strokeWidth);
canvas->drawPath(path, paint);
paint.setStrokeWidth(1);
canvas->drawLine(pts[1].fX - miterLength / 2, pts[1].fY + 50,
pts[1].fX + miterLength / 2, pts[1].fY + 50, paint);
canvas->translate(200, 0);
miterLimit *= 0.99f;
paint.setStrokeMiter(miterLimit);
paint.setStrokeWidth(strokeWidth);
canvas->drawPath(path, paint);
paint.setStrokeWidth(1);
canvas->drawLine(pts[1].fX - miterLength / 2, pts[1].fY + 50,
pts[1].fX + miterLength / 2, pts[1].fY + 50, paint);
}
} // END FIDDLE
| 712 |
14,668 | <filename>third_party/blink/renderer/platform/scheduler/common/throttling/budget_pool.cc
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/scheduler/common/throttling/budget_pool.h"
#include <cstdint>
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
namespace blink {
namespace scheduler {
using base::sequence_manager::TaskQueue;
BudgetPool::BudgetPool(const char* name) : name_(name), is_enabled_(true) {}
BudgetPool::~BudgetPool() {
for (auto* throttler : associated_throttlers_) {
throttler->RemoveBudgetPool(this);
}
}
const char* BudgetPool::Name() const {
return name_;
}
void BudgetPool::AddThrottler(base::TimeTicks now,
TaskQueueThrottler* throttler) {
throttler->AddBudgetPool(this);
associated_throttlers_.insert(throttler);
if (!is_enabled_)
return;
throttler->UpdateQueueState(now);
}
void BudgetPool::UnregisterThrottler(TaskQueueThrottler* throttler) {
associated_throttlers_.erase(throttler);
}
void BudgetPool::RemoveThrottler(base::TimeTicks now,
TaskQueueThrottler* throttler) {
throttler->RemoveBudgetPool(this);
associated_throttlers_.erase(throttler);
if (!is_enabled_)
return;
throttler->UpdateQueueState(now);
}
void BudgetPool::EnableThrottling(base::sequence_manager::LazyNow* lazy_now) {
if (is_enabled_)
return;
is_enabled_ = true;
TRACE_EVENT0("renderer.scheduler", "BudgetPool_EnableThrottling");
UpdateStateForAllThrottlers(lazy_now->Now());
}
void BudgetPool::DisableThrottling(base::sequence_manager::LazyNow* lazy_now) {
if (!is_enabled_)
return;
is_enabled_ = false;
TRACE_EVENT0("renderer.scheduler", "BudgetPool_DisableThrottling");
UpdateStateForAllThrottlers(lazy_now->Now());
// TODO(altimin): We need to disable TimeBudgetQueues here or they will
// regenerate extra time budget when they are disabled.
}
bool BudgetPool::IsThrottlingEnabled() const {
return is_enabled_;
}
void BudgetPool::Close() {
DCHECK_EQ(0u, associated_throttlers_.size());
}
void BudgetPool::UpdateStateForAllThrottlers(base::TimeTicks now) {
for (TaskQueueThrottler* throttler : associated_throttlers_)
throttler->UpdateQueueState(now);
}
} // namespace scheduler
} // namespace blink
| 919 |
928 | <reponame>0xAnarz/core<gh_stars>100-1000
/*
* Preprocessor Library by Parra Studios
* Copyright (C) 2016 - 2021 <NAME> <<EMAIL>>
*
* A generic header-only preprocessor metaprogramming library.
*
*/
#ifndef PREPROCESSOR_DETECTION_H
#define PREPROCESSOR_DETECTION_H 1
/* -- Headers -- */
#include <preprocessor/preprocessor_api.h>
#include <preprocessor/preprocessor_arguments.h>
#include <preprocessor/preprocessor_concatenation.h>
#ifdef __cplusplus
extern "C" {
#endif
/* -- Macros -- */
#define PREPROCESSOR_DETECT(...) \
PREPROCESSOR_ARGS_SECOND(__VA_ARGS__, 0, )
#define PREPROCESSOR_DETECT_TOKEN(token) token, 1
#define PREPROCESSOR_DETECT_PARENTHESIS_IMPL(...) \
PREPROCESSOR_DETECT_TOKEN(~)
#define PREPROCESSOR_DETECT_PARENTHESIS(expr) \
PREPROCESSOR_DETECT(PREPROCESSOR_DETECT_PARENTHESIS_IMPL expr)
#define PREPROCESSOR_DETECT_COMPARABLE(expr) \
PREPROCESSOR_DETECT_PARENTHESIS(PREPROCESSOR_CONCAT(PREPROCESSOR_COMPARE_, expr)(()))
#ifdef __cplusplus
}
#endif
#endif /* PREPROCESSOR_DETECTION_H */
| 484 |
335 | <gh_stars>100-1000
{
"word": "Fragrance",
"definitions": [
"A pleasant, sweet smell.",
"A perfume or aftershave."
],
"parts-of-speech": "Noun"
} | 83 |
369 | // Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include <cstddef>
class Sink
{
public:
virtual ~Sink() = default;
virtual void put(const char *data, size_t size) = 0;
};
| 145 |
646 | import unittest
from nboost.delegates import RequestDelegate, ResponseDelegate
class TestDelegates(unittest.TestCase):
def test_request_1(self):
request = RequestDelegate({
'body': {
"from": 0,
"size": 20,
"query": {
"term": {"user": "kimchy"}
},
"nboost": {
"cids": ['0', '2']
}
}
})
self.assertEqual("kimchy", request.query)
self.assertEqual(20, request.topk)
def test_request_2(self):
request = RequestDelegate({
'url': {
"query": {"q": "message:test query", "size": 20}
}
})
self.assertEqual("message:test query", request.query)
def test_request_3(self):
request = RequestDelegate({
'body': {
"query": {
"match": "hello there"
},
}
})
self.assertEqual("hello there", request.query)
def test_request_4(self):
request = RequestDelegate({
'body': {
"size": 11,
"query": {
"function_score": {
"query": {
"bool": {
"should": [
{
"match": {
"text": {
"query": "query one",
"operator": "and"
}
}
},
{
"match": {
"text": {
"query": "query two",
"operator": "or"
}
}
}
]
}
},
"script_score": {
"script": {
"source": "1 + ((5 - doc[\"priority\"].value) / 10.0) + ((doc[\"branch\"].value == \"All\") ? 0.5 : 0)"
}
}
}
}
}
},
query_path='body.query.function_score.query.bool.should.[*].match.text.query'
)
self.assertEqual('query one. query two', request.query)
def test_request_5(self):
request = RequestDelegate({
'body': {
"id": "searchTemplate",
"params": {
"query": "my query",
"from": 0,
"size": 9
}
}
},
query_path='body.params.query'
)
self.assertEqual('my query', request.query)
def test_response_1(self):
response = ResponseDelegate({
'body': {
"nboost": {'cvalues_path': '_source.message'},
"took": 5,
"timed_out": False,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.3862944,
"hits": [
{
"_index": "twitter",
"_type": "_doc",
"_id": "0",
"_score": 1.4,
"_source": {
"message": "trying out Elasticsearch",
}
}, {
"_index": "twitter",
"_type": "_doc",
"_id": "1",
"_score": 1.34245,
"_source": {
"message": "second result",
}
},
{
"_index": "twitter",
"_type": "_doc",
"_id": "2",
"_score": 1.121234,
"_source": {
"message": "third result",
}
}
]
}
}
}, RequestDelegate({}))
self.assertEqual(1.4, response.choices[0]['_score'])
self.assertEqual(["trying out Elasticsearch", "second result", "third result"], response.cvalues)
self.assertEqual(['0', '1', '2'], response.cids)
| 3,623 |
322 | [
{
"type": "org.apache.eagle.alert.engine.publisher.impl.AlertKafkaPublisher",
"name": "network-syslog-publish",
"policyIds": [
"syslog_severity_check"
],
"dedupIntervalMin": "PT0M",
"properties": {
"kafka_broker": "localhost:9092",
"topic": "syslog_alerts",
"value_deserializer": "org.apache.kafka.common.serialization.ByteArrayDeserializer",
"value_serializer": "org.apache.kafka.common.serialization.ByteArraySerializer"
},
"serializer": "org.apache.eagle.alert.engine.extension.SherlockAlertSerializer"
}
] | 243 |
1,122 | //Problem: https://www.hackerrank.com/challenges/organizing-containers-of-balls
//Java 8
/*
Initial Thoughts: We can sum each column to get the
number of each type of ball, then
we can sum horizontally to get the
size of all of the containers, and
if the two sets of numbers don't match
then it is impossible
Time Complexity: O(n^2) //We must look at every ball in a n*n matrix
Space Complexity: O(n^2) //We dynamically store them in sets
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for(int a0 = 0; a0 < q; a0++){
///////////BUILD THE INPUT MATRIX///////////
int n = in.nextInt();
int[][] M = new int[n][n];
for(int M_i=0; M_i < n; M_i++){
for(int M_j=0; M_j < n; M_j++){
M[M_i][M_j] = in.nextInt();
}
}
////////////////////////////////////////////
//Create a bag for the amount of each ball and the sizes of containers
LinkedList<Integer> containers = new LinkedList<>();
LinkedList<Integer> balls = new LinkedList<>();
for(int i = 0; i < n; i++){
int rowSum = 0;
int colSum = 0;
for(int j = 0; j < n; j++){
rowSum += M[i][j];
colSum += M[j][i];
}
balls.add(colSum);
containers.add(rowSum);
}
//Check if the two bags are equal
containers.removeAll(balls);
if(containers.isEmpty()) System.out.println("Possible");
else System.out.println("Impossible");
}
}
}
| 1,047 |
2,023 | import re
import sys
def copy_board(board, sets):
"""Return a copy of board setting new squares from 'sets' dictionary."""
return [[sets.get((r, c), board[r][c]) for c in range(9)] for r in range(9)]
def get_alternatives_for_square(board, nrow, ncolumn):
"""Return sequence of valid digits for square (nrow, ncolumn) in board."""
def _box(idx, size=3):
"""Return indexes to cover a box (3x3 sub-matrix of a board)."""
start = (idx // size) * size
return range(start, start + size)
nums_in_box = [board[r][c] for r in _box(nrow) for c in _box(ncolumn)]
nums_in_row = [board[nrow][c] for c in range(9)]
nums_in_column = [board[r][ncolumn] for r in range(9)]
nums = nums_in_box + nums_in_row + nums_in_column
return sorted(set(range(1, 9+1)) - set(nums))
def get_more_constrained_square(board):
"""Get the square in board with more constrains (less alternatives)."""
ranges = ((x, y) for x in range(9) for y in range(9))
constrains = [(len(get_alternatives_for_square(board, r, c)), (r, c))
for (r, c) in ranges if not board[r][c]]
if constrains:
return min(constrains)[1]
def solve(board):
"""Return a solved Sudoku board (None if no solution was found)."""
pos = get_more_constrained_square(board)
if not pos:
return board # all squares are filled, so this board is the solution
nrow, ncolumn = pos
for test_digit in get_alternatives_for_square(board, nrow, ncolumn):
test_board = copy_board(board, {(nrow, ncolumn): test_digit})
solved_board = solve(test_board)
if solved_board:
return solved_board
def lines2board(lines):
"""Parse a text board stripping spaces and setting 0's for empty squares."""
spaces = re.compile("\s+")
return [[(int(c) if c in "123456789" else 0) for c in spaces.sub("", line)]
for line in lines if line.strip()]
def main(args):
"""Solve a Sudoku board read from a text file."""
from pprint import pprint
path, = args
board = lines2board(open(path))
pprint(board)
pprint(solve(board))
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| 891 |
421 | {"archiveHeader":0,"currentFileHeader":null,"validateOnly":false,"fileWriteCount":0,"directoryWriteCount":0,"basePath":null,"archivePath":null,"isCompressed":false,"currentFileOffset":0,"archiveOffset":0,"timeSliceInSecs":-1,"working":false,"failures":[],"startTimestamp":1491848703} | 83 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.