repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
coman3/zitadel | internal/repository/org/domain.go | <reponame>coman3/zitadel
package org
import (
"context"
"encoding/json"
"github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/crypto"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/repository"
)
const (
UniqueOrgDomain = "org_domain"
domainEventPrefix = orgEventTypePrefix + "domain."
OrgDomainAddedEventType = domainEventPrefix + "added"
OrgDomainVerificationAddedEventType = domainEventPrefix + "verification.added"
OrgDomainVerificationFailedEventType = domainEventPrefix + "verification.failed"
OrgDomainVerifiedEventType = domainEventPrefix + "verified"
OrgDomainPrimarySetEventType = domainEventPrefix + "primary.set"
OrgDomainRemovedEventType = domainEventPrefix + "removed"
)
func NewAddOrgDomainUniqueConstraint(orgDomain string) *eventstore.EventUniqueConstraint {
return eventstore.NewAddEventUniqueConstraint(
UniqueOrgDomain,
orgDomain,
"Errors.Org.Domain.AlreadyExists")
}
func NewRemoveOrgDomainUniqueConstraint(orgDomain string) *eventstore.EventUniqueConstraint {
return eventstore.NewRemoveEventUniqueConstraint(
UniqueOrgDomain,
orgDomain)
}
type DomainAddedEvent struct {
eventstore.BaseEvent `json:"-"`
Domain string `json:"domain,omitempty"`
}
func (e *DomainAddedEvent) Data() interface{} {
return e
}
func (e *DomainAddedEvent) UniqueConstraints() []*eventstore.EventUniqueConstraint {
return nil
}
func NewDomainAddedEvent(ctx context.Context, aggregate *eventstore.Aggregate, domain string) *DomainAddedEvent {
return &DomainAddedEvent{
BaseEvent: *eventstore.NewBaseEventForPush(
ctx,
aggregate,
OrgDomainAddedEventType,
),
Domain: domain,
}
}
func DomainAddedEventMapper(event *repository.Event) (eventstore.EventReader, error) {
orgDomainAdded := &DomainAddedEvent{
BaseEvent: *eventstore.BaseEventFromRepo(event),
}
err := json.Unmarshal(event.Data, orgDomainAdded)
if err != nil {
return nil, errors.ThrowInternal(err, "ORG-GBr52", "unable to unmarshal org domain added")
}
return orgDomainAdded, nil
}
type DomainVerificationAddedEvent struct {
eventstore.BaseEvent `json:"-"`
Domain string `json:"domain,omitempty"`
ValidationType domain.OrgDomainValidationType `json:"validationType,omitempty"`
ValidationCode *crypto.CryptoValue `json:"validationCode,omitempty"`
}
func (e *DomainVerificationAddedEvent) Data() interface{} {
return e
}
func (e *DomainVerificationAddedEvent) UniqueConstraints() []*eventstore.EventUniqueConstraint {
return nil
}
func NewDomainVerificationAddedEvent(
ctx context.Context,
aggregate *eventstore.Aggregate,
domain string,
validationType domain.OrgDomainValidationType,
validationCode *crypto.CryptoValue) *DomainVerificationAddedEvent {
return &DomainVerificationAddedEvent{
BaseEvent: *eventstore.NewBaseEventForPush(
ctx,
aggregate,
OrgDomainVerificationAddedEventType,
),
Domain: domain,
ValidationType: validationType,
ValidationCode: validationCode,
}
}
func DomainVerificationAddedEventMapper(event *repository.Event) (eventstore.EventReader, error) {
orgDomainVerificationAdded := &DomainVerificationAddedEvent{
BaseEvent: *eventstore.BaseEventFromRepo(event),
}
err := json.Unmarshal(event.Data, orgDomainVerificationAdded)
if err != nil {
return nil, errors.ThrowInternal(err, "ORG-NRN32", "unable to unmarshal org domain verification added")
}
return orgDomainVerificationAdded, nil
}
type DomainVerificationFailedEvent struct {
eventstore.BaseEvent `json:"-"`
Domain string `json:"domain,omitempty"`
}
func (e *DomainVerificationFailedEvent) Data() interface{} {
return e
}
func (e *DomainVerificationFailedEvent) UniqueConstraints() []*eventstore.EventUniqueConstraint {
return nil
}
func NewDomainVerificationFailedEvent(ctx context.Context, aggregate *eventstore.Aggregate, domain string) *DomainVerificationFailedEvent {
return &DomainVerificationFailedEvent{
BaseEvent: *eventstore.NewBaseEventForPush(
ctx,
aggregate,
OrgDomainVerificationFailedEventType,
),
Domain: domain,
}
}
func DomainVerificationFailedEventMapper(event *repository.Event) (eventstore.EventReader, error) {
orgDomainVerificationFailed := &DomainVerificationFailedEvent{
BaseEvent: *eventstore.BaseEventFromRepo(event),
}
err := json.Unmarshal(event.Data, orgDomainVerificationFailed)
if err != nil {
return nil, errors.ThrowInternal(err, "ORG-Bhm37", "unable to unmarshal org domain verification failed")
}
return orgDomainVerificationFailed, nil
}
type DomainVerifiedEvent struct {
eventstore.BaseEvent `json:"-"`
Domain string `json:"domain,omitempty"`
}
func (e *DomainVerifiedEvent) Data() interface{} {
return e
}
func (e *DomainVerifiedEvent) UniqueConstraints() []*eventstore.EventUniqueConstraint {
return []*eventstore.EventUniqueConstraint{NewAddOrgDomainUniqueConstraint(e.Domain)}
}
func NewDomainVerifiedEvent(ctx context.Context, aggregate *eventstore.Aggregate, domain string) *DomainVerifiedEvent {
return &DomainVerifiedEvent{
BaseEvent: *eventstore.NewBaseEventForPush(
ctx,
aggregate,
OrgDomainVerifiedEventType,
),
Domain: domain,
}
}
func DomainVerifiedEventMapper(event *repository.Event) (eventstore.EventReader, error) {
orgDomainVerified := &DomainVerifiedEvent{
BaseEvent: *eventstore.BaseEventFromRepo(event),
}
err := json.Unmarshal(event.Data, orgDomainVerified)
if err != nil {
return nil, errors.ThrowInternal(err, "ORG-BFSwt", "unable to unmarshal org domain verified")
}
return orgDomainVerified, nil
}
type DomainPrimarySetEvent struct {
eventstore.BaseEvent `json:"-"`
Domain string `json:"domain,omitempty"`
}
func (e *DomainPrimarySetEvent) Data() interface{} {
return e
}
func (e *DomainPrimarySetEvent) UniqueConstraints() []*eventstore.EventUniqueConstraint {
return nil
}
func NewDomainPrimarySetEvent(ctx context.Context, aggregate *eventstore.Aggregate, domain string) *DomainPrimarySetEvent {
return &DomainPrimarySetEvent{
BaseEvent: *eventstore.NewBaseEventForPush(
ctx,
aggregate,
OrgDomainPrimarySetEventType,
),
Domain: domain,
}
}
func DomainPrimarySetEventMapper(event *repository.Event) (eventstore.EventReader, error) {
orgDomainPrimarySet := &DomainPrimarySetEvent{
BaseEvent: *eventstore.BaseEventFromRepo(event),
}
err := json.Unmarshal(event.Data, orgDomainPrimarySet)
if err != nil {
return nil, errors.ThrowInternal(err, "ORG-N5787", "unable to unmarshal org domain primary set")
}
return orgDomainPrimarySet, nil
}
type DomainRemovedEvent struct {
eventstore.BaseEvent `json:"-"`
Domain string `json:"domain,omitempty"`
isVerified bool
}
func (e *DomainRemovedEvent) Data() interface{} {
return e
}
func (e *DomainRemovedEvent) UniqueConstraints() []*eventstore.EventUniqueConstraint {
if !e.isVerified {
return nil
}
return []*eventstore.EventUniqueConstraint{NewRemoveOrgDomainUniqueConstraint(e.Domain)}
}
func NewDomainRemovedEvent(ctx context.Context, aggregate *eventstore.Aggregate, domain string, verified bool) *DomainRemovedEvent {
return &DomainRemovedEvent{
BaseEvent: *eventstore.NewBaseEventForPush(
ctx,
aggregate,
OrgDomainRemovedEventType,
),
Domain: domain,
isVerified: verified,
}
}
func DomainRemovedEventMapper(event *repository.Event) (eventstore.EventReader, error) {
orgDomainRemoved := &DomainRemovedEvent{
BaseEvent: *eventstore.BaseEventFromRepo(event),
}
err := json.Unmarshal(event.Data, orgDomainRemoved)
if err != nil {
return nil, errors.ThrowInternal(err, "ORG-BngB2", "unable to unmarshal org domain removed")
}
return orgDomainRemoved, nil
}
|
simpsonw/atmosphere | api/tests/base/test_version.py | """
Tests for base views (i.e. views shared between api versions)
"""
from rest_framework.test import APIRequestFactory
from rest_framework.test import APITestCase, force_authenticate
from api.base.views import VersionViewSet, DeployVersionViewSet
from api.tests.factories import UserFactory
class VersionTests(APITestCase):
view_set = VersionViewSet
def test_get_version(self):
"""
Test a sucessful response and shape
"""
user_a = UserFactory.create()
view = self.view_set.as_view({'get': 'list'})
request = APIRequestFactory().get("")
force_authenticate(request, user=user_a)
response = view(request)
self.assertEquals(response.status_code, 200)
data = response.data
keys = ['git_sha', 'git_sha_abbrev', 'commit_date', 'git_branch']
for key in keys:
self.assertIn(key, data)
self.assertIsNotNone(data[key])
class DeployVersionTests(VersionTests):
view_set = DeployVersionViewSet
|
snoopdave/incubator-usergrid | stack/corepersistence/queue/src/main/java/org/apache/usergrid/persistence/qakka/distributed/actors/QueueSender.java | <filename>stack/corepersistence/queue/src/main/java/org/apache/usergrid/persistence/qakka/distributed/actors/QueueSender.java
/*
* 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.usergrid.persistence.qakka.distributed.actors;
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
import akka.cluster.client.ClusterClient;
import akka.pattern.Patterns;
import akka.util.Timeout;
import com.codahale.metrics.Timer;
import com.google.inject.Inject;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.usergrid.persistence.actorsystem.ActorSystemFig;
import org.apache.usergrid.persistence.actorsystem.ActorSystemManager;
import org.apache.usergrid.persistence.qakka.MetricsService;
import org.apache.usergrid.persistence.qakka.QakkaFig;
import org.apache.usergrid.persistence.qakka.distributed.DistributedQueueService;
import org.apache.usergrid.persistence.qakka.distributed.messages.*;
import org.apache.usergrid.persistence.qakka.exceptions.QakkaException;
import org.apache.usergrid.persistence.qakka.exceptions.QakkaRuntimeException;
import org.apache.usergrid.persistence.qakka.serialization.auditlog.AuditLog;
import org.apache.usergrid.persistence.qakka.serialization.auditlog.AuditLogSerialization;
import org.apache.usergrid.persistence.qakka.serialization.transferlog.TransferLogSerialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Await;
import scala.concurrent.Future;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class QueueSender extends UntypedActor {
private static final Logger logger = LoggerFactory.getLogger( QueueSender.class );
private final String name = RandomStringUtils.randomAlphanumeric( 4 );
private final ActorSystemManager actorSystemManager;
private final TransferLogSerialization transferLogSerialization;
private final AuditLogSerialization auditLogSerialization;
private final ActorSystemFig actorSystemFig;
private final QakkaFig qakkaFig;
private final MetricsService metricsService;
@Inject
public QueueSender(
ActorSystemManager actorSystemManager,
TransferLogSerialization transferLogSerialization,
AuditLogSerialization auditLogSerialization,
ActorSystemFig actorSystemFig,
QakkaFig qakkaFig,
MetricsService metricsService
) {
this.actorSystemManager = actorSystemManager;
this.transferLogSerialization = transferLogSerialization;
this.auditLogSerialization = auditLogSerialization;
this.actorSystemFig = actorSystemFig;
this.qakkaFig = qakkaFig;
this.metricsService = metricsService;
}
@Override
public void onReceive(Object message) {
if ( message instanceof QueueSendRequest) {
QueueSendRequest qa = (QueueSendRequest) message;
// as far as caller is concerned, we are done.
getSender().tell( new QueueSendResponse(
DistributedQueueService.Status.SUCCESS, qa.getQueueName() ), getSender() );
final QueueWriter.WriteStatus writeStatus = sendMessageToRegion(
qa.getQueueName(),
qa.getSourceRegion(),
qa.getDestRegion(),
qa.getMessageId(),
qa.getDeliveryTime(),
qa.getExpirationTime() );
logResponse( writeStatus, qa.getQueueName(), qa.getDestRegion(), qa.getMessageId() );
} else {
unhandled( message );
}
}
QueueWriter.WriteStatus sendMessageToRegion(
String queueName,
String sourceRegion,
String destRegion,
UUID messageId,
Long deliveryTime,
Long expirationTime ) {
Timer.Context timer = metricsService.getMetricRegistry().timer( MetricsService.SEND_TIME_SEND ).time();
try {
int maxRetries = qakkaFig.getMaxSendRetries();
int retries = 0;
QueueWriteRequest request = new QueueWriteRequest(
queueName, sourceRegion, destRegion, messageId, deliveryTime, expirationTime );
while (retries++ < maxRetries) {
try {
Timeout t = new Timeout( qakkaFig.getSendTimeoutSeconds(), TimeUnit.SECONDS );
Future<Object> fut;
if (actorSystemManager.getCurrentRegion().equals( destRegion )) {
logger.trace("{}: Sending queue {} message to local region {}", name, queueName, destRegion );
// send to current region via local clientActor
ActorRef clientActor = actorSystemManager.getClientActor();
fut = Patterns.ask( clientActor, request, t );
} else {
logger.trace("{} Sending queue {} message to remote region {}", name, queueName, destRegion );
// send to remote region via cluster client for that region
ActorRef clusterClient = actorSystemManager.getClusterClient( destRegion );
fut = Patterns.ask(
clusterClient, new ClusterClient.Send( "/user/clientActor", request ), t );
}
// wait for response...
final Object response = Await.result( fut, t.duration() );
if (response != null && response instanceof QueueWriteResponse) {
QueueWriteResponse qarm = (QueueWriteResponse) response;
if (!QueueWriter.WriteStatus.ERROR.equals( qarm.getSendStatus() )) {
if (retries > 1) {
logger.debug( "queueAdd TOTAL_SUCCESS after {} retries", retries );
}
return qarm.getSendStatus();
} else {
logger.debug( "ERROR STATUS adding to queue, retrying {}", retries );
}
} else if (response != null) {
logger.debug( "NULL RESPONSE adding to queue, retrying {}", retries );
} else {
logger.debug( "TIMEOUT adding to queue, retrying {}", retries );
}
} catch (Exception e) {
logger.debug( "ERROR adding to queue, retrying " + retries, e );
}
}
throw new QakkaRuntimeException( "Error adding to queue after " + retries + " retries" );
} finally {
timer.stop();
}
}
void logResponse( QueueWriter.WriteStatus writeStatus, String queueName, String region, UUID messageId ) {
if ( writeStatus != null
&& writeStatus.equals( QueueWriter.WriteStatus.ERROR ) ) {
logger.debug( "ERROR status sending message: {}, {}, {}, {}",
new Object[]{queueName, actorSystemFig.getRegionLocal(), region, messageId} );
auditLogSerialization.recordAuditLog(
AuditLog.Action.SEND,
AuditLog.Status.ERROR,
queueName,
region,
messageId,
null);
} else if ( writeStatus != null
&& writeStatus.equals( QueueWriter.WriteStatus.SUCCESS_XFERLOG_NOTDELETED ) ) {
// queue actor failed to clean up transfer log
try {
transferLogSerialization.removeTransferLog(
queueName, actorSystemFig.getRegionLocal(), region, messageId );
} catch (QakkaException se) {
logger.error( "Unable to delete remove transfer log for {}, {}, {}, {}",
new Object[]{queueName, actorSystemFig.getRegionLocal(), region, messageId} );
logger.debug( "Unable to delete remove transfer log exception is:", se );
}
} else if ( writeStatus != null
&& writeStatus.equals( QueueWriter.WriteStatus.SUCCESS_XFERLOG_DELETED ) ) {
//logger.debug( "Delivery Success: {}, {}, {}, {}",
// new Object[]{queueName, actorSystemFig.getRegionLocal(), region, messageId} );
}
}
}
|
caroldf07/orange-talents-02-template-proposta | criacao-proposta/src/main/java/br/com/orangetalents/proposta/criarproposta/view/EnderecoRequest.java | <filename>criacao-proposta/src/main/java/br/com/orangetalents/proposta/criarproposta/view/EnderecoRequest.java
package br.com.orangetalents.proposta.criarproposta.view;
import br.com.orangetalents.proposta.criarproposta.model.Endereco;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
public class EnderecoRequest {
@Length(max = 2)
@NotBlank
private String UF;
@NotBlank
private String cidade;
@NotBlank
private String logradouro;
@NotBlank
private String complemento;
public EnderecoRequest(@Length(max = 2) @NotBlank String UF,
@NotBlank String cidade,
@NotBlank String logradouro,
@NotBlank String complemento) {
this.UF = UF;
this.cidade = cidade;
this.logradouro = logradouro;
this.complemento = complemento;
}
public Endereco toModel() {
return new Endereco(this.UF, this.cidade, this.logradouro, this.complemento);
}
}
|
bijugs/hbase-1.1.2.2.6.3.22-1 | hbase-native-client/src/hbase/client/scan.cc | <gh_stars>10-100
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "hbase/client/scan.h"
#include <algorithm>
#include <iterator>
#include <limits>
#include <stdexcept>
namespace hbase {
Scan::Scan() {}
Scan::~Scan() {}
Scan::Scan(const std::string &start_row) : start_row_(start_row) { CheckRow(start_row_); }
Scan::Scan(const std::string &start_row, const std::string &stop_row)
: start_row_(start_row), stop_row_(stop_row) {
CheckRow(start_row_);
CheckRow(stop_row_);
}
Scan::Scan(const Scan &scan) : Query(scan) {
start_row_ = scan.start_row_;
stop_row_ = scan.stop_row_;
max_versions_ = scan.max_versions_;
caching_ = scan.caching_;
max_result_size_ = scan.max_result_size_;
cache_blocks_ = scan.cache_blocks_;
load_column_families_on_demand_ = scan.load_column_families_on_demand_;
reversed_ = scan.reversed_;
allow_partial_results_ = scan.allow_partial_results_;
consistency_ = scan.consistency_;
tr_.reset(new TimeRange(scan.tr_->MinTimeStamp(), scan.tr_->MaxTimeStamp()));
family_map_.insert(scan.family_map_.begin(), scan.family_map_.end());
}
Scan &Scan::operator=(const Scan &scan) {
Query::operator=(scan);
start_row_ = scan.start_row_;
stop_row_ = scan.stop_row_;
max_versions_ = scan.max_versions_;
caching_ = scan.caching_;
max_result_size_ = scan.max_result_size_;
cache_blocks_ = scan.cache_blocks_;
load_column_families_on_demand_ = scan.load_column_families_on_demand_;
reversed_ = scan.reversed_;
allow_partial_results_ = scan.allow_partial_results_;
consistency_ = scan.consistency_;
tr_.reset(new TimeRange(scan.tr_->MinTimeStamp(), scan.tr_->MaxTimeStamp()));
family_map_.insert(scan.family_map_.begin(), scan.family_map_.end());
return *this;
}
Scan::Scan(const Get &get) {
cache_blocks_ = get.CacheBlocks();
max_versions_ = get.MaxVersions();
tr_.reset(new TimeRange(get.Timerange().MinTimeStamp(), get.Timerange().MaxTimeStamp()));
family_map_.insert(get.FamilyMap().begin(), get.FamilyMap().end());
}
Scan &Scan::AddFamily(const std::string &family) {
const auto &it = family_map_.find(family);
/**
* Check if any qualifiers are already present or not.
* Remove all existing qualifiers if the given family is already present in
* the map
*/
if (family_map_.end() != it) {
it->second.clear();
} else {
family_map_[family];
}
return *this;
}
Scan &Scan::AddColumn(const std::string &family, const std::string &qualifier) {
const auto &it = std::find(family_map_[family].begin(), family_map_[family].end(), qualifier);
/**
* Check if any qualifiers are already present or not.
* Add only if qualifiers for a given family are not present
*/
if (it == family_map_[family].end()) {
family_map_[family].push_back(qualifier);
}
return *this;
}
void Scan::SetReversed(bool reversed) { reversed_ = reversed; }
bool Scan::IsReversed() const { return reversed_; }
void Scan::SetStartRow(const std::string &start_row) { start_row_ = start_row; }
const std::string &Scan::StartRow() const { return start_row_; }
void Scan::SetStopRow(const std::string &stop_row) { stop_row_ = stop_row; }
const std::string &Scan::StopRow() const { return stop_row_; }
void Scan::SetCaching(int caching) { caching_ = caching; }
int Scan::Caching() const { return caching_; }
Scan &Scan::SetConsistency(const hbase::pb::Consistency consistency) {
consistency_ = consistency;
return *this;
}
hbase::pb::Consistency Scan::Consistency() const { return consistency_; }
void Scan::SetCacheBlocks(bool cache_blocks) { cache_blocks_ = cache_blocks; }
bool Scan::CacheBlocks() const { return cache_blocks_; }
void Scan::SetAllowPartialResults(bool allow_partial_results) {
allow_partial_results_ = allow_partial_results;
}
bool Scan::AllowPartialResults() const { return allow_partial_results_; }
void Scan::SetLoadColumnFamiliesOnDemand(bool load_column_families_on_demand) {
load_column_families_on_demand_ = load_column_families_on_demand;
}
bool Scan::LoadColumnFamiliesOnDemand() const { return load_column_families_on_demand_; }
Scan &Scan::SetMaxVersions(uint32_t max_versions) {
max_versions_ = max_versions;
return *this;
}
int Scan::MaxVersions() const { return max_versions_; }
void Scan::SetMaxResultSize(int64_t max_result_size) { max_result_size_ = max_result_size; }
int64_t Scan::MaxResultSize() const { return max_result_size_; }
Scan &Scan::SetTimeRange(int64_t min_stamp, int64_t max_stamp) {
tr_.reset(new TimeRange(min_stamp, max_stamp));
return *this;
}
Scan &Scan::SetTimeStamp(int64_t timestamp) {
tr_.reset(new TimeRange(timestamp, timestamp + 1));
return *this;
}
const TimeRange &Scan::Timerange() const { return *tr_; }
void Scan::CheckRow(const std::string &row) {
const int32_t kMaxRowLength = std::numeric_limits<int16_t>::max();
int row_length = row.size();
if (0 == row_length) {
throw std::runtime_error("Row length can't be 0");
}
if (row_length > kMaxRowLength) {
throw std::runtime_error("Length of " + row + " is greater than max row size: " +
std::to_string(kMaxRowLength));
}
}
bool Scan::HasFamilies() const { return !family_map_.empty(); }
const std::map<std::string, std::vector<std::string>> &Scan::FamilyMap() const {
return family_map_;
}
} // namespace hbase
|
alisle/ZeroTrust-Server | oauth/src/main/java/com/zerotrust/oauth/repository/ConfigRepository.java | <gh_stars>1-10
package com.zerotrust.oauth.repository;
import com.zerotrust.oauth.model.Config;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
import java.util.UUID;
@SuppressWarnings("unused")
@RepositoryRestResource(exported = false)
public interface ConfigRepository extends JpaRepository<Config, UUID> {
List<Config> findAll();
}
|
rockandsalt/conan-center-index | recipes/zbar/all/test_package/test_package.c | #include <stdio.h>
#include <stdlib.h>
#include <zbar.h>
zbar_image_scanner_t *scanner = NULL;
int main (int argc, char **argv)
{
/* create a reader */
scanner = zbar_image_scanner_create();
/* configure the reader */
zbar_image_scanner_set_config(scanner, 0, ZBAR_CFG_ENABLE, 1);
/* clean up */
zbar_image_scanner_destroy(scanner);
#ifdef ZBAR_VERSION_PARAM3
unsigned VersionMajor;
unsigned VersionMinor;
unsigned VersionPatch;
zbar_version(&VersionMajor, &VersionMinor, &VersionPatch);
printf("Compiled ZBar version %d.%d.%d \n", VersionMajor, VersionMinor, VersionPatch);
#else
unsigned VersionMajor;
unsigned VersionMinor;
zbar_version(&VersionMajor, &VersionMinor);
printf("Compiled ZBar version %d.%d \n", VersionMajor, VersionMinor);
#endif
printf("Zbar Test Completed \n");
return(0);
}
|
EndlessCoff33/shipment_tracker | spec/models/events/jira_event_spec.rb | <filename>spec/models/events/jira_event_spec.rb
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Events::JiraEvent do
describe '#approval?' do
context 'when the status changes from unapproved to approved' do
it 'returns true' do
expect(build(:jira_event, :approved).approval?).to be true
end
end
context 'when the status changes from approved to approved' do
it 'returns false' do
expect(build(:jira_event, :deployed).approval?).to be false
end
end
context 'when the status changes from unapproved to unapproved' do
it 'returns false' do
expect(build(:jira_event, :development_completed).approval?).to be false
end
end
context 'when the status changes from approved to unapproved' do
it 'returns false' do
expect(build(:jira_event, :unapproved).approval?).to be false
end
end
end
describe '#unapproval?' do
context 'when the status changes from unapproved to approved' do
it 'returns false' do
expect(build(:jira_event, :approved).unapproval?).to be false
end
end
context 'when the status changes from approved to approved' do
it 'returns false' do
expect(build(:jira_event, :deployed).unapproval?).to be false
end
end
context 'when the status changes from unapproved to unapproved' do
it 'returns false' do
expect(build(:jira_event, :development_completed).unapproval?).to be false
end
end
context 'when the status changes from approved to unapproved' do
it 'returns true' do
expect(build(:jira_event, :unapproved).unapproval?).to be true
end
end
end
describe '#transfer?' do
it 'returns true' do
expect(build(:jira_event, :moved).transfer?).to be true
end
end
describe '#development?' do
it 'returns true' do
expect(build(:jira_event, :started).development?).to be true
end
it 'returns false' do
expect(build(:jira_event, :approved).development?).to be false
end
end
describe 'changelog_old_key' do
it 'returns old key of a moved ticket' do
expect(build(:jira_event, :moved).changelog_old_key).to eq 'ONEJIRA-1'
end
it 'return of ticket that is not moved' do
expect(build(:jira_event, :started).changelog_old_key).to be nil
end
end
describe 'changelog_new_key' do
it 'returns old key of a moved ticket' do
expect(build(:jira_event, :moved).changelog_new_key).to eq '<KEY>'
end
it 'return of ticket that is not moved' do
expect(build(:jira_event, :started).changelog_new_key).to be nil
end
end
describe '#user_email' do
it 'returns the email of the user' do
expect(build(:jira_event, :created).user_email).to eq '<EMAIL>'
end
end
describe '#assignee_email' do
it 'returns the email of the assignee' do
expect(build(:jira_event, :development_completed).assignee_email).to eq '<EMAIL>'
end
end
end
|
keshbach/Arcade | Source/UtilsNet/UiCtrlsNet/FileTypeItem.cpp | <reponame>keshbach/Arcade<gh_stars>1-10
/////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2013-2014 <NAME>
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "FileTypeItem.h"
Common::Forms::FileTypeItem::FileTypeItem(
System::String^ sName,
System::String^ sFilters) :
m_sName(sName),
m_sFilters(sFilters)
{
}
Common::Forms::FileTypeItem::FileTypeItem()
{
}
Common::Forms::FileTypeItem::~FileTypeItem()
{
m_sName = nullptr;
m_sFilters = nullptr;
}
/////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2013-2014 <NAME>
/////////////////////////////////////////////////////////////////////////////
|
ScaryBoxStudios/TheRoom | src/Asset/Properties/PropertiesLoader.cpp | <filename>src/Asset/Properties/PropertiesLoader.cpp
#include "PropertiesLoader.hpp"
#include <assert.h>
#include <cstring>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include "Properties.hpp"
// Parsing helper functions declarations
Properties::Id ParseId(const rapidjson::Value& v); // Id
Properties::Color ParseColor(const rapidjson::Value& v); // Color
Properties::Transform ParseTransform(rapidjson::Value& t); // Transform
Properties::SceneNode ParseSceneNode(rapidjson::Value& sn); // SceneNode
template <>
Properties::MaterialFile PropertiesLoader::Load<Properties::MaterialFile>(rapidjson::Document& doc)
{
// Less verbose usage
using namespace rapidjson;
// Create the output material file struct
Properties::MaterialFile matFile;
// Parse textures
if (doc.HasMember("textures"))
{
Value& textures = doc["textures"];
assert(textures.IsArray());
for (SizeType i = 0; i < textures.Size(); ++i)
{
// Parse texture
Value& t = textures[i];
Properties::Texture tex = {};
// Id
tex.id = ParseId(t["id"]);
// Url
tex.url = t["url"].GetString();
// Add texture to list
matFile.textures.push_back(tex);
}
}
// Parse materials
if (doc.HasMember("materials"))
{
Value& materials = doc["materials"];
assert(materials.IsArray());
for (SizeType i = 0; i < materials.Size(); ++i)
{
// Parse maetrial
Value& m = materials[i];
Properties::Material mt = {};
// Id
mt.id = ParseId(m["id"]);
// Name
if(m.HasMember("name"))
mt.name = m["name"].GetString();
// Colors
if(m.HasMember("color"))
mt.color = ParseColor(m["color"]);
if (m.HasMember("emissive"))
mt.emissive = ParseColor(m["emissive"]);
// Aspects
if (m.HasMember("roughness"))
mt.roughness = static_cast<float>(m["roughness"].GetDouble());
if (m.HasMember("reflectivity"))
mt.reflectivity = static_cast<float>(m["reflectivity"].GetDouble());
if (m.HasMember("metallic"))
mt.metallic = static_cast<float>(m["metallic"].GetDouble());
// Opacity
if (m.HasMember("transparency"))
mt.transparency = static_cast<float>(m["transparency"].GetDouble());
// Wireframe
if (m.HasMember("wireframe"))
mt.wireframe = m["wireframe"].GetBool();
// Map
mt.dmap.valid = false;
if (m.HasMember("dmap"))
mt.dmap = ParseId(m["dmap"]);
// SpecMap
mt.smap.valid = false;
if (m.HasMember("smap"))
mt.smap = ParseId(m["smap"]);
// Nmap
mt.nmap.valid = false;
if(m.HasMember("nmap"))
mt.nmap = ParseId(m["nmap"]);
// Add parsed material to the list
matFile.materials.push_back(mt);
}
}
return matFile;
}
template<>
Properties::ModelFile PropertiesLoader::Load<Properties::ModelFile>(rapidjson::Document& doc)
{
// Less verbose usage
using namespace rapidjson;
// Create the output model file struct
Properties::ModelFile modelFile = {};
// Parse geometries
if (doc.HasMember("geometries"))
{
Value& geometries = doc["geometries"];
assert(geometries.IsArray());
for (SizeType i = 0; i < geometries.Size(); ++i)
{
// Parse geometry
Value& g = geometries[i];
Properties::Geometry gd = {};
// Id
gd.id = ParseId(g["id"]);
// Name
gd.name = g["name"].GetString();
// Url
gd.url = g["url"].GetString();
// Add parsed geometry to the list
modelFile.geometries.push_back(gd);
}
}
// Parse models
if (doc.HasMember("models"))
{
Value& models = doc["models"];
assert(models.IsArray());
for (SizeType i = 0; i < models.Size(); ++i)
{
// Parse model
Value& m = models[i];
Properties::Model model = {};
// Id
model.id.valid = false;
model.id = ParseId(m["id"]);
// Geometry Id
model.geometry.valid = false;
model.geometry = ParseId(m["geometry"]);
// Name
model.name = m["name"].GetString();
// Material
if (m.HasMember("materials"))
{
Value& mats = m["materials"];
assert(mats.IsArray());
model.materials.resize(mats.Size());
for (SizeType j = 0; j < mats.Size(); ++j)
{
Value& mat = mats[j];
model.materials[j] = ParseId(mat);
}
}
// Add to list
modelFile.models.push_back(model);
}
}
return modelFile;
}
void GetNestedDocument(rapidjson::Document& doc, rapidjson::Document& result, const char* key)
{
rapidjson::StringBuffer buffer;
assert(doc[key].IsObject());
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
doc[key].Accept(writer);
rapidjson::StringStream s(buffer.GetString());
result.ParseStream(s);
}
template<>
Properties::SceneFile PropertiesLoader::Load<Properties::SceneFile>(rapidjson::Document& doc)
{
// Less verbose usage
using namespace rapidjson;
// Create the output model file struct
Properties::SceneFile sceneFile = {};
// Parse extra Materials
if (doc.HasMember("extraMaterials"))
{
Document subDoc;
GetNestedDocument(doc, subDoc, "extraMaterials");
sceneFile.extraMaterials = Load<Properties::MaterialFile>(subDoc);
}
// Parse extra models
if (doc.HasMember("extraModels"))
{
Document subDoc;
GetNestedDocument(doc, subDoc, "extraModels");
sceneFile.extraModels = Load<Properties::ModelFile>(subDoc);
}
// Parse scene
if (doc.HasMember("scene"))
{
Value& sceneVal = doc["scene"];
assert(sceneVal.IsObject());
// Parse scene nodes
Value& nodes = sceneVal["nodes"];
assert(nodes.IsArray());
for (SizeType i = 0; i < nodes.Size(); ++i)
sceneFile.scene.nodes.push_back(ParseSceneNode(nodes[i]));
}
return sceneFile;
}
// --------------------------------------------------
// Parsing helper functions implementations
// --------------------------------------------------
// Id Parse helper
Properties::Id ParseId(const rapidjson::Value& v) { return Properties::Id { v.GetString(), true }; }
// Color Parse helper
Properties::Color ParseColor(const rapidjson::Value& v)
{
Properties::Color col = {};
assert(v.IsArray());
col.r = static_cast<std::uint8_t>(v[0].GetInt());
col.g = static_cast<std::uint8_t>(v[1].GetInt());
col.b = static_cast<std::uint8_t>(v[2].GetInt());
col.a = static_cast<std::uint8_t>(v[3].GetInt());
return col;
};
// Transform Parse helper
Properties::Transform ParseTransform(rapidjson::Value& t)
{
using namespace rapidjson;
Properties::Transform transform = {};
transform.scale = glm::vec3(1.0f);
// Position
if (t.HasMember("position"))
{
Value& pos = t["position"];
assert(pos.IsArray());
transform.position.x = static_cast<float>(pos[0].GetDouble());
transform.position.y = static_cast<float>(pos[1].GetDouble());
transform.position.z = static_cast<float>(pos[2].GetDouble());
}
// Scale
if (t.HasMember("scale"))
{
Value& sc = t["scale"];
assert(sc.IsArray());
transform.scale.x = static_cast<float>(sc[0].GetDouble());
transform.scale.y = static_cast<float>(sc[1].GetDouble());
transform.scale.z = static_cast<float>(sc[2].GetDouble());
}
// Rotation
if (t.HasMember("rotation"))
{
Value& rot = t["rotation"];
transform.rotation.x = static_cast<float>(rot[0].GetDouble());
transform.rotation.y = static_cast<float>(rot[1].GetDouble());
transform.rotation.z = static_cast<float>(rot[2].GetDouble());
}
return transform;
};
// Scene Node Parse helper
Properties::SceneNode ParseSceneNode(rapidjson::Value& sn)
{
using namespace rapidjson;
Properties::SceneNode sceneNode = {};
assert(sn.IsObject());
// Id
sceneNode.id = ParseId(sn["id"]);
// Model Id
sceneNode.model = ParseId(sn["model"]);
// Type
std::string type = sn["type"].GetString();
if (type == "Model")
sceneNode.type = Properties::SceneNode::Type::Model;
else if (type == "PointLight")
sceneNode.type = Properties::SceneNode::Type::PointLight;
else
assert(false);
// Transform
sceneNode.transform = ParseTransform(sn["transform"]);
// Children
if (sn.HasMember("children"))
{
Value& children = sn["children"];
assert(children.IsArray());
for (SizeType i = 0; i < children.Size(); ++i)
sceneNode.children.push_back(ParseSceneNode(children[i]));
}
return sceneNode;
};
void ParseJson(const PropertiesLoader::Buffer& data, rapidjson::Document& doc)
{
// Less verbose usage
using namespace rapidjson;
// Convert it to std::string containter
std::string json(std::begin(data), std::end(data));
// The scene file object to be filled
Properties::SceneFile sc = {};
// Parse the json file
doc.Parse(json.c_str());
// Root
assert(doc.IsObject());
}
|
Robbbert/messui | src/mame/drivers/bmjr.cpp | <gh_stars>10-100
// license:BSD-3-Clause
// copyright-holders:<NAME>
/***************************************************************************
Basic Master Jr (MB-6885) (c) 1982? Hitachi
preliminary driver by <NAME>
To enter the monitor: MON
To quit: E
TODO:
- Break key is unemulated (tied with the NMI)
****************************************************************************/
#include "emu.h"
#include "cpu/m6800/m6800.h"
#include "imagedev/cassette.h"
#include "machine/timer.h"
#include "sound/beep.h"
#include "emupal.h"
#include "screen.h"
#include "speaker.h"
class bmjr_state : public driver_device
{
public:
bmjr_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_maincpu(*this, "maincpu")
, m_cass(*this, "cassette")
, m_beep(*this, "beeper")
, m_p_wram(*this, "wram")
, m_p_chargen(*this, "chargen")
, m_io_keyboard(*this, "KEY%d", 0U)
{ }
void bmjr(machine_config &config);
private:
u8 key_r();
void key_w(u8 data);
u8 ff_r();
u8 unk_r();
u8 tape_r();
void tape_w(u8 data);
u8 tape_stop_r();
u8 tape_start_r();
void xor_display_w(u8 data);
u32 screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
void mem_map(address_map &map);
bool m_tape_switch;
u8 m_xor_display;
u8 m_key_mux;
u16 m_casscnt;
bool m_cassold, m_cassbit;
TIMER_DEVICE_CALLBACK_MEMBER(kansas_r);
virtual void machine_start() override;
virtual void machine_reset() override;
required_device<cpu_device> m_maincpu;
required_device<cassette_image_device> m_cass;
required_device<beep_device> m_beep;
required_shared_ptr<u8> m_p_wram;
required_region_ptr<u8> m_p_chargen;
required_ioport_array<16> m_io_keyboard;
};
u32 bmjr_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
u8 fg=4;
u16 sy=0,ma=0x100;
u8 const inv = (m_xor_display) ? 0xff : 0;
for(u8 y = 0; y < 24; y++ )
{
for (u8 ra = 0; ra < 8; ra++)
{
u16 *p = &bitmap.pix(sy++);
for (u16 x = ma; x < ma + 32; x++)
{
u8 const chr = m_p_wram[x];
u8 const gfx = m_p_chargen[(chr<<3) | ra] ^ inv;
/* Display a scanline of a character */
*p++ = BIT(gfx, 7) ? fg : 0;
*p++ = BIT(gfx, 6) ? fg : 0;
*p++ = BIT(gfx, 5) ? fg : 0;
*p++ = BIT(gfx, 4) ? fg : 0;
*p++ = BIT(gfx, 3) ? fg : 0;
*p++ = BIT(gfx, 2) ? fg : 0;
*p++ = BIT(gfx, 1) ? fg : 0;
*p++ = BIT(gfx, 0) ? fg : 0;
}
}
ma+=32;
}
return 0;
}
u8 bmjr_state::key_r()
{
return m_io_keyboard[m_key_mux]->read() | ioport("KEYMOD")->read();
}
void bmjr_state::key_w(u8 data)
{
m_key_mux = data & 0xf;
// if(data & 0xf0)
// printf("%02x",data & 0xf0);
}
u8 bmjr_state::ff_r()
{
return 0xff;
}
u8 bmjr_state::unk_r()
{
return 0x30;
}
TIMER_DEVICE_CALLBACK_MEMBER( bmjr_state::kansas_r )
{
/* cassette - turn pulses into a bit */
bool cass_ws = (m_cass->input() > +0.04) ? 1 : 0;
m_casscnt++;
if (cass_ws != m_cassold)
{
m_cassold = cass_ws;
m_cassbit = (m_casscnt < 12) ? 1 : 0;
m_casscnt = 0;
}
else
if (m_casscnt > 32)
{
m_casscnt = 32;
m_cassbit = 0;
}
}
u8 bmjr_state::tape_r()
{
//m_cass->change_state(CASSETTE_PLAY,CASSETTE_MASK_UISTATE);
return m_cassbit ? 0xff : 0x00;
}
void bmjr_state::tape_w(u8 data)
{
if(!m_tape_switch)
{
m_beep->set_state(!BIT(data, 7));
}
else
{
//m_cass->change_state(CASSETTE_RECORD,CASSETTE_MASK_UISTATE);
m_cass->output(BIT(data, 0) ? -1.0 : +1.0);
}
}
u8 bmjr_state::tape_stop_r()
{
m_tape_switch = 0;
//m_cass->change_state(CASSETTE_STOPPED,CASSETTE_MASK_UISTATE);
m_cass->change_state(CASSETTE_MOTOR_DISABLED,CASSETTE_MASK_MOTOR);
return 0x01;
}
u8 bmjr_state::tape_start_r()
{
m_tape_switch = 1;
m_cass->change_state(CASSETTE_MOTOR_ENABLED,CASSETTE_MASK_MOTOR);
return 0x01;
}
void bmjr_state::xor_display_w(u8 data)
{
m_xor_display = data;
}
void bmjr_state::mem_map(address_map &map)
{
map.unmap_value_high();
//0x0100, 0x03ff basic vram
//0x0900, 0x20ff vram, modes 0x40 / 0xc0
//0x2100, 0x38ff vram, modes 0x44 / 0xcc
map(0x0000, 0xafff).ram().share("wram");
map(0xb000, 0xdfff).rom();
map(0xe000, 0xe7ff).rom();
// map(0xe890, 0xe890) W MP-1710 tile color
// map(0xe891, 0xe891) W MP-1710 background color
// map(0xe892, 0xe892) W MP-1710 monochrome / color setting
map(0xee00, 0xee00).r(FUNC(bmjr_state::tape_stop_r)); //R stop tape
map(0xee20, 0xee20).r(FUNC(bmjr_state::tape_start_r)); //R start tape
map(0xee40, 0xee40).w(FUNC(bmjr_state::xor_display_w)); //W Picture reverse
map(0xee80, 0xee80).rw(FUNC(bmjr_state::tape_r), FUNC(bmjr_state::tape_w));//RW tape input / output
map(0xeec0, 0xeec0).rw(FUNC(bmjr_state::key_r), FUNC(bmjr_state::key_w));//RW keyboard
map(0xef00, 0xef00).r(FUNC(bmjr_state::ff_r)); //R timer
map(0xef40, 0xef40).r(FUNC(bmjr_state::ff_r)); //R unknown
map(0xef80, 0xef80).r(FUNC(bmjr_state::unk_r)); //R unknown
// map(0xefe0, 0xefe0) W screen mode
map(0xf000, 0xffff).rom();
}
/* Input ports */
static INPUT_PORTS_START( bmjr )
PORT_START("KEY0")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("Z") PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("A") PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("Q") PORT_CODE(KEYCODE_Q) PORT_CHAR('Q')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("1 !") PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!')
PORT_START("KEY1")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("X") PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("S") PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("W") PORT_CODE(KEYCODE_W) PORT_CHAR('W')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("2 \"") PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('\"')
PORT_START("KEY2")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("C") PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("D") PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("E") PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("3 #") PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#')
PORT_START("KEY3")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("V") PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("F") PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("R") PORT_CODE(KEYCODE_R) PORT_CHAR('R')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("4 $") PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$')
PORT_START("KEY4")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("B") PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("G") PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("T") PORT_CODE(KEYCODE_T) PORT_CHAR('T')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("5 %") PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%')
PORT_START("KEY5")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("N") PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("H") PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("Y") PORT_CODE(KEYCODE_Y) PORT_CHAR('Y')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("6 &") PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('&')
PORT_START("KEY6")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("M") PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("J") PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("U") PORT_CODE(KEYCODE_U) PORT_CHAR('U')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("7 \'") PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('\'')
PORT_START("KEY7")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME(", <") PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("K") PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("I") PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("8 (") PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('(')
PORT_START("KEY8")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME(". >") PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR('>')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("L") PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("O") PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("9 )") PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR(')')
PORT_START("KEY9")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("/ ?") PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("; +") PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR('+')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("P") PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("0") PORT_CODE(KEYCODE_0) PORT_CHAR('0')
PORT_START("KEY10")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_UNUSED )
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME(": *") PORT_CODE(KEYCODE_QUOTE) PORT_CHAR(':') PORT_CHAR('*')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("@ Up") PORT_CODE(KEYCODE_8_PAD) PORT_CHAR('@')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("- =") PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-') PORT_CHAR('=')
PORT_START("KEY11")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("Space") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ')
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("]") PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR(']')
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("[ Down") PORT_CODE(KEYCODE_OPENBRACE) PORT_CODE(KEYCODE_2_PAD) PORT_CHAR('[')
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("^ Right") PORT_CODE(KEYCODE_6_PAD) PORT_CHAR('^')
PORT_START("KEY12")
PORT_BIT(0x01,IP_ACTIVE_LOW,IPT_UNUSED)
PORT_BIT(0x02,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("Enter") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
PORT_BIT(0x04,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("Backspace") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
PORT_BIT(0x08,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("\xC2\xA5 / Left") PORT_CODE(KEYCODE_4_PAD)
PORT_START("KEY13")
PORT_DIPNAME( 0x01, 0x01, "D" )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_START("KEY14")
PORT_BIT( 0x0f, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("KEY15")
PORT_BIT( 0x0f, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("KEYMOD") /* Note: you should press Normal to return from a Kana state and vice-versa */
PORT_BIT(0x10,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME(DEF_STR( Normal )) PORT_CODE(KEYCODE_LCONTROL)
PORT_BIT(0x20,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("Shift") PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1)
PORT_BIT(0x40,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("Kana Shift") PORT_CODE(KEYCODE_LALT)
PORT_BIT(0x80,IP_ACTIVE_LOW,IPT_KEYBOARD) PORT_NAME("Kana") PORT_CODE(KEYCODE_RCONTROL)
INPUT_PORTS_END
static const gfx_layout bmjr_charlayout =
{
8, 8,
RGN_FRAC(1,1),
1,
{ 0 },
{ 0, 1, 2, 3, 4, 5, 6, 7 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
8*8
};
static GFXDECODE_START( gfx_bmjr )
GFXDECODE_ENTRY( "chargen", 0x0000, bmjr_charlayout, 0, 4 )
GFXDECODE_END
void bmjr_state::machine_start()
{
save_item(NAME(m_tape_switch));
save_item(NAME(m_xor_display));
save_item(NAME(m_key_mux));
save_item(NAME(m_casscnt));
save_item(NAME(m_cassold));
save_item(NAME(m_cassbit));
}
void bmjr_state::machine_reset()
{
m_beep->set_state(0);
m_tape_switch = 0;
m_xor_display = 0;
m_key_mux = 0;
m_cass->change_state(CASSETTE_MOTOR_DISABLED,CASSETTE_MASK_MOTOR);
}
void bmjr_state::bmjr(machine_config &config)
{
/* basic machine hardware */
// 750khz gets the cassette sound close to a normal kansas city 300 baud
M6800(config, m_maincpu, 750'000); //XTAL(4'000'000)/4); //unknown clock / divider
m_maincpu->set_addrmap(AS_PROGRAM, &bmjr_state::mem_map);
m_maincpu->set_vblank_int("screen", FUNC(bmjr_state::irq0_line_hold));
/* video hardware */
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER));
screen.set_refresh_hz(50);
screen.set_vblank_time(ATTOSECONDS_IN_USEC(2500)); /* not accurate */
screen.set_size(256, 192);
screen.set_visarea_full();
screen.set_screen_update(FUNC(bmjr_state::screen_update));
screen.set_palette("palette");
PALETTE(config, "palette", palette_device::BRG_3BIT);
GFXDECODE(config, "gfxdecode", "palette", gfx_bmjr);
/* Audio */
SPEAKER(config, "mono").front_center();
BEEP(config, "beeper", 1200).add_route(ALL_OUTPUTS, "mono", 0.50); // guesswork
/* Devices */
CASSETTE(config, m_cass);
m_cass->add_route(ALL_OUTPUTS, "mono", 0.05);
TIMER(config, "kansas_r").configure_periodic(FUNC(bmjr_state::kansas_r), attotime::from_hz(40000));
}
/* ROM definition */
ROM_START( bmjr )
ROM_REGION( 0x10000, "maincpu", ROMREGION_ERASEFF )
ROM_LOAD( "bas.rom", 0xb000, 0x3000, BAD_DUMP CRC(2318e04e) SHA1(cdb3535663090f5bcaba20b1dbf1f34724ef6a5f)) //12k ROMs doesn't exist ...
ROM_LOAD( "mon.rom", 0xf000, 0x1000, CRC(776cfa3a) SHA1(be747bc40fdca66b040e0f792b05fcd43a1565ce))
ROM_LOAD( "prt.rom", 0xe000, 0x0800, CRC(b9aea867) SHA1(b8dd5348790d76961b6bdef41cfea371fdbcd93d))
ROM_REGION( 0x800, "chargen", 0 )
ROM_LOAD( "font.rom", 0x0000, 0x0800, BAD_DUMP CRC(258c6fd7) SHA1(d7c7dd57d6fc3b3d44f14c32182717a48e24587f)) //taken from a JP emulator
ROM_END
/* Driver */
/* YEAR NAME PARENT COMPAT MACHINE INPUT CLASS INIT COMPANY FULLNAME FLAGS */
COMP( 1982, bmjr, 0, 0, bmjr, bmjr, bmjr_state, empty_init, "Hitachi", "Basic Master Jr", MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE )
|
lucasmrdt/50k-app | app/src/containers/index.js | import Level from './ConnectedLevel';
import TaskList from './ConnectedTaskList';
export * from './ConnectedFilter';
export {
Level,
TaskList,
};
|
huizhongyu/tempProject | app/src/main/java/cn/closeli/rtc/controller/PreviewActivity.java | <reponame>huizhongyu/tempProject
package cn.closeli.rtc.controller;
import android.app.admin.DevicePolicyManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.neovisionaries.ws.client.WebSocketState;
import com.vhd.base.util.LogUtil;
import com.vhd.camera.CameraEncoderv2;
import org.webrtc.MediaStream;
import org.webrtc.SurfaceViewRenderer;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import butterknife.BindInt;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.closeli.rtc.BaseActivity;
import cn.closeli.rtc.LoginActivity;
import cn.closeli.rtc.R;
import cn.closeli.rtc.constract.BundleKey;
import cn.closeli.rtc.constract.Constract;
import cn.closeli.rtc.constract.GlobalValue;
import cn.closeli.rtc.model.info.ParticipantInfoModel;
import cn.closeli.rtc.room.RoomClient;
import cn.closeli.rtc.sdk.IViewCallback;
import cn.closeli.rtc.sdk.ProxyVideoSink;
import cn.closeli.rtc.sdk.WebRTCManager;
import cn.closeli.rtc.utils.ActivityUtils;
import cn.closeli.rtc.utils.CallUtil;
import cn.closeli.rtc.utils.DeviceSettingManager;
import cn.closeli.rtc.utils.L;
import cn.closeli.rtc.utils.StringUtils;
import cn.closeli.rtc.utils.UIUtils;
import cn.closeli.rtc.utils.ViewUtils;
import cn.closeli.rtc.utils.ext.WorkThreadFactory;
import cn.closeli.rtc.widget.FocusLayout;
import cn.closeli.rtc.widget.UCToast;
import cn.closeli.rtc.widget.popwindow.MeetSettingPopupWindow;
import me.jessyan.autosize.internal.CustomAdapt;
import static cn.closeli.rtc.constract.GlobalValue.KEY_PANTILT_CONTROL;
import static cn.closeli.rtc.constract.GlobalValue.KEY_PARAMETER;
import static cn.closeli.rtc.constract.GlobalValue.KEY_ROLE_CONTROL;
import static cn.closeli.rtc.constract.GlobalValue.PANTILT_DOWN;
import static cn.closeli.rtc.constract.GlobalValue.PANTILT_LEFT;
import static cn.closeli.rtc.constract.GlobalValue.PANTILT_RIGHT;
import static cn.closeli.rtc.constract.GlobalValue.PANTILT_STOP;
import static cn.closeli.rtc.constract.GlobalValue.PANTILT_UP;
import static cn.closeli.rtc.constract.GlobalValue.ROLE_DIRECT;
import static cn.closeli.rtc.constract.GlobalValue.ROLE_INDIRECT;
import static cn.closeli.rtc.constract.GlobalValue.ZOOM_STOP;
import static cn.closeli.rtc.constract.GlobalValue.ZOOM_TELE;
import static cn.closeli.rtc.constract.GlobalValue.ZOOM_WIDE;
// 预览页面
public class PreviewActivity extends BaseActivity implements View.OnClickListener {
private static int CAMERA_ID = Camera.CameraInfo.CAMERA_FACING_FRONT;
@BindView(R.id.fl_preview)
FrameLayout fl_preview;
@BindView(R.id.sfv_preview)
SurfaceViewRenderer sfv_preview;
@BindView(R.id.iv_top)
ImageView iv_top;
@BindView(R.id.iv_left)
ImageView iv_left;
@BindView(R.id.iv_right)
ImageView iv_right;
@BindView(R.id.iv_bottom)
ImageView iv_bottom;
@BindView(R.id.constaint)
ConstraintLayout constaint;
@BindView(R.id.iv_guide)
ImageView iv_guide;
@BindView(R.id.tv_title_pre)
TextView tv_title_pre;
@BindView(R.id.constaint_show)
ConstraintLayout constaint_show;
@BindView(R.id.tv_key_0)
TextView tv_key_0;
@BindView(R.id.tv_key_1)
TextView tv_key_1;
@BindView(R.id.tv_key_2)
TextView tv_key_2;
@BindView(R.id.tv_key_3)
TextView tv_key_3;
@BindView(R.id.tv_key_4)
TextView tv_key_4;
@BindView(R.id.tv_key_5)
TextView tv_key_5;
@BindView(R.id.tv_key_6)
TextView tv_key_6;
@BindView(R.id.tv_key_7)
TextView tv_key_7;
@BindView(R.id.tv_key_8)
TextView tv_key_8;
@BindView(R.id.tv_key_9)
TextView tv_key_9;
private MediaStream mediaStream;
ProxyVideoSink localSink;
private boolean isPreviewLocal; //来源是否是本地预览
private boolean isControlState = true; //是否是相机控制状态
private FocusLayout mFocusLayout;
private String strOfKeySet; //当前已经设置的预置位
private boolean isPreviewSetModel = true; //是否是预置位设置模式
private MyHandler h = new MyHandler(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview);
ActivityUtils.getInstance().addActivity(this);
// StatusBarUtil.setColor(PreviewActivity.this, getResources().getColor(R.color.color_translate));
// showStatusBar();
ButterKnife.bind(this);
isPreviewLocal = getIntent().getBooleanExtra(BundleKey.IS_PREVIEW_LOCAL, true);
if (isPreviewLocal) {
DeviceSettingManager.getInstance().setCameraControlSynchro(KEY_PARAMETER, "default");
}
strOfKeySet = DeviceSettingManager.getInstance().getFromSp().getCurrentPreset();
}
private void initViewCallBack() {
WebRTCManager.get().addViewCallback(PreviewActivity.class, new IViewCallback() {
@Override
public void onSetLocalStream(MediaStream stream) {
if (RoomClient.get().getCurrentActivity() instanceof PreviewActivity) {
mediaStream = stream;
localSink = new ProxyVideoSink();
localSink.setTarget(sfv_preview);
mediaStream.videoTracks.get(0).addSink(localSink);
}
}
@Override
public void onSetLocalScreenStream(MediaStream stream) {
}
@Override
public void onSetLocalHDMIStream(MediaStream stream) {
}
@Override
public void onAddRemoteStream(MediaStream stream, ParticipantInfoModel participant) {
}
@Override
public void onCloseRemoteStream(MediaStream stream, ParticipantInfoModel participant) {
}
@Override
public void onMixStream(ParticipantInfoModel participant, boolean isHasShare) {
}
@Override
public void publishParticipantInfo(ParticipantInfoModel participant) {
}
});
}
private void initsetSurface() {
sfv_preview = WebRTCManager.get().setSurface(sfv_preview);
// surfaceLocal.setZOrderMediaOverlay(true);
sfv_preview.setMirror(false);
// if (isPreviewLocal) {
// sfv_preview.setMirror(true);
// }
}
private void initLocalPreview() {
ParticipantInfoModel participant = new ParticipantInfoModel();
participant.setLocalStreamType(0);
WebRTCManager.get().startPreView(participant);
}
private void inithdmiPreview() {
int[] idArray = new int[2];
if (!CameraEncoderv2.hasValidCamera(idArray)) {
Toast.makeText(PreviewActivity.this, "no vhd camera", Toast.LENGTH_LONG).show();
LogUtil.LOG_WARN("shareScreenHDMI", this.getClass().toString(),
"not find vhd camera");
return;
} else {
LogUtil.LOG_WARN("shareScreenHDMI", this.getClass().toString(),
"find vhd camera vid:pid(" +
String.format("%04x", idArray[0]) + ":" +
String.format("%04x", idArray[1]) + ")");
}
ParticipantInfoModel participant = new ParticipantInfoModel();
participant.setLocalStreamType(2);
WebRTCManager.get().shareHdmi(sfv_preview);
WebRTCManager.get().startPreView(participant);
}
//状态栏全屏
private void showStatusBar() {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setAttributes(attrs);
}
MeetSettingPopupWindow w;
/**
* test code
**/
// Fragment 操作 Popup
public void methodEvent(int type, List<ParticipantInfoModel> list) {
if (w != null) {
w.showNextPopup(list);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
L.d("do this ----onKeyDown>>> " + keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
if (constaint.getVisibility() == View.VISIBLE && event.getRepeatCount() == 0 && isControlState && isPreviewSetModel) {
iv_top.setPressed(true);
DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_UP);
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (constaint.getVisibility() == View.VISIBLE && event.getRepeatCount() == 0 && isControlState && isPreviewSetModel) {
iv_left.setPressed(true);
DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_LEFT);
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (constaint.getVisibility() == View.VISIBLE && event.getRepeatCount() == 0 && isControlState && isPreviewSetModel) {
iv_right.setPressed(true);
DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_RIGHT);
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (constaint.getVisibility() == View.VISIBLE && event.getRepeatCount() == 0 && isControlState && isPreviewSetModel) {
iv_bottom.setPressed(true);
DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_DOWN);
return true;
}
break;
case KeyEvent.KEYCODE_ZOOM_IN:
if (constaint.getVisibility() == View.VISIBLE) {
DeviceSettingManager.getInstance().setCameraControl(GlobalValue.KEY_ZOOM_CONTROL, ZOOM_TELE);
}
break;
case KeyEvent.KEYCODE_ZOOM_OUT:
if (constaint.getVisibility() == View.VISIBLE) {
DeviceSettingManager.getInstance().setCameraControl(GlobalValue.KEY_ZOOM_CONTROL, ZOOM_WIDE);
}
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
//处理遥控器 按键事件
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
L.d("do this ---->>>" + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {
DeviceSettingManager.DeviceModel d = DeviceSettingManager.getInstance().getFromSp();
d.setCurrentPreset(strOfKeySet);
DeviceSettingManager.getInstance().setModel(d);
DeviceSettingManager.getInstance().saveSp();
L.d("do this ---KEYCODE_BACK>>> " + strOfKeySet);
if (isControlState) {
isControlState = false;
DeviceSettingManager.getInstance().setCameraControlSynchro(KEY_ROLE_CONTROL, ROLE_INDIRECT);
} else {
DeviceSettingManager.getInstance().setCameraControlSynchro(GlobalValue.KEY_MEMU, "false");
DeviceSettingManager.getInstance().setCameraControlSynchro(KEY_ROLE_CONTROL, ROLE_INDIRECT);
finish();
}
}
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
if (constaint.getVisibility() == View.VISIBLE && event.getRepeatCount() == 0 && isControlState && isPreviewSetModel) {
iv_top.setPressed(false);
DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_STOP);
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (constaint.getVisibility() == View.VISIBLE && event.getRepeatCount() == 0 && isControlState && isPreviewSetModel) {
iv_bottom.setPressed(false);
DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_STOP);
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (constaint.getVisibility() == View.VISIBLE && event.getRepeatCount() == 0 && isControlState && isPreviewSetModel) {
iv_left.setPressed(false);
DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_STOP);
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (constaint.getVisibility() == View.VISIBLE && event.getRepeatCount() == 0 && isControlState && isPreviewSetModel) {
iv_right.setPressed(false);
DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_STOP);
return true;
}
break;
case KeyEvent.KEYCODE_ZOOM_IN:
if (constaint.getVisibility() == View.VISIBLE) {
DeviceSettingManager.getInstance().setCameraControl(GlobalValue.KEY_ZOOM_CONTROL, ZOOM_STOP);
}
break;
case KeyEvent.KEYCODE_ZOOM_OUT:
if (constaint.getVisibility() == View.VISIBLE) {
DeviceSettingManager.getInstance().setCameraControl(GlobalValue.KEY_ZOOM_CONTROL, ZOOM_STOP);
}
break;
case KeyEvent.KEYCODE_MENU:
if (!isPreviewSetModel) {
break;
}
if (!isControlState) {
isControlState = true;
constaint.setVisibility(View.VISIBLE);
} else {
// DeviceSettingManager.getInstance().setCameraControl(KEY_ROLE_CONTROL, ROLE_INDIRECT);
DeviceSettingManager.getInstance().setCameraControlSynchro(GlobalValue.KEY_MEMU, "true");
DeviceSettingManager.getInstance().setCameraControlSynchro(KEY_ROLE_CONTROL, ROLE_DIRECT);
isControlState = false;
// constaint.setVisibility(View.GONE);
// btn_image_config.setVisibility(View.GONE);
// tv_tip_menu.setVisibility(View.VISIBLE);
}
break;
case KeyEvent.KEYCODE_0:
setMemoryConfig(0);
break;
case KeyEvent.KEYCODE_1:
setMemoryConfig(1);
break;
case KeyEvent.KEYCODE_2:
setMemoryConfig(2);
break;
case KeyEvent.KEYCODE_3:
setMemoryConfig(3);
break;
case KeyEvent.KEYCODE_4:
setMemoryConfig(4);
break;
case KeyEvent.KEYCODE_5:
setMemoryConfig(5);
break;
case KeyEvent.KEYCODE_6:
setMemoryConfig(6);
break;
case KeyEvent.KEYCODE_7:
setMemoryConfig(7);
break;
case KeyEvent.KEYCODE_8:
setMemoryConfig(8);
break;
case KeyEvent.KEYCODE_9:
setMemoryConfig(9);
break;
case KeyEvent.KEYCODE_POUND:
isPreviewSetModel = !isPreviewSetModel;
tv_title_pre.setVisibility(isPreviewSetModel ? View.GONE : View.VISIBLE);
constaint_show.setVisibility(isPreviewSetModel ? View.GONE : View.VISIBLE);
if (!isPreviewSetModel) {
showSetPre();
}
iv_guide.setImageResource(isPreviewSetModel ? R.drawable.bg_guide_first : R.drawable.bg_guide_second);
break;
default:
break;
}
return super.onKeyUp(keyCode, event);
}
//展示已经设置好的预置位
private void showSetPre() {
tv_key_0.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 0) ? View.VISIBLE : View.INVISIBLE);
tv_key_1.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 1) ? View.VISIBLE : View.INVISIBLE);
tv_key_2.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 2) ? View.VISIBLE : View.INVISIBLE);
tv_key_3.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 3) ? View.VISIBLE : View.INVISIBLE);
tv_key_4.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 4) ? View.VISIBLE : View.INVISIBLE);
tv_key_5.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 5) ? View.VISIBLE : View.INVISIBLE);
tv_key_6.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 6) ? View.VISIBLE : View.INVISIBLE);
tv_key_7.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 7) ? View.VISIBLE : View.INVISIBLE);
tv_key_8.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 8) ? View.VISIBLE : View.INVISIBLE);
tv_key_9.setVisibility(StringUtils.isIndexEqual1(strOfKeySet, 9) ? View.VISIBLE : View.INVISIBLE);
}
@Override
protected void onResume() {
super.onResume();
RoomClient.get().setCurrentActivity(this);
initViewCallBack();
initsetSurface();
if (isPreviewLocal) {
initLocalPreview();
} else {
inithdmiPreview();
}
DeviceSettingManager.getInstance().setCameraControlSynchro(KEY_ROLE_CONTROL, ROLE_INDIRECT);
mFocusLayout = new FocusLayout(this);
bindListener();//绑定焦点变化事件
addContentView(mFocusLayout,
new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));//添加焦点层
}
private void bindListener() {
//获取根元素
View mContainerView = this.getWindow().getDecorView();//.findViewById(android.R.id.content);
//得到整个view树的viewTreeObserver
ViewTreeObserver viewTreeObserver = mContainerView.getViewTreeObserver();
//给观察者设置焦点变化监听
viewTreeObserver.addOnGlobalFocusChangeListener(mFocusLayout);
}
@Override
protected void onPause() {
super.onPause();
WebRTCManager.get().stopLocalPreview();
WebRTCManager.get().stopHDMIPreview();
sfv_preview.release();
DeviceSettingManager.getInstance().setCameraControlSynchro(KEY_ROLE_CONTROL, ROLE_INDIRECT);
}
@Override
protected void onDestroy() {
super.onDestroy();
h.removeMessages(100);
h = null;
}
@Override
public void onStateChange(WebSocketState socketState) {
}
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
@Override
public void onClick(View v) {
// if (v.getId() == R.id.btn_image_config) {
// btn_image_config.setOnClickListener(null);
// DeviceSettingManager.getInstance().setCameraControl(GlobalValue.KEY_MEMU, "true");
// DeviceSettingManager.getInstance().setCameraControl(KEY_ROLE_CONTROL, ROLE_DIRECT);
// CallUtil.asyncCall(500, () -> {
// constaint.setVisibility(View.GONE);
// btn_image_config.setVisibility(View.GONE);
// });
// }
}
//对对应按键 设置/读取预置位
private void setMemoryConfig(int key) {
if (isPreviewSetModel) {
if (StringUtils.isIndexEqual1(strOfKeySet, key)) {
// DeviceSettingManager.getInstance().setCameraControl(GlobalValue.MEMORY_RESET, String.valueOf(key));
DeviceSettingManager.getInstance().setCameraControl(GlobalValue.MEMORY_SET, String.valueOf(key));
} else {
DeviceSettingManager.getInstance().setCameraControl(GlobalValue.MEMORY_SET, String.valueOf(key));
//如果没有,在已有预置位标志上添加此按键键值
strOfKeySet = String.valueOf(Integer.valueOf(strOfKeySet) + DeviceSettingManager.getInstance().getSaveKeyData(key));
}
// showKeyMemoryToast(key);
Message msg = Message.obtain();
msg.what = 100;
msg.arg1 = key;
h.sendMessage(msg);
} else {
if (StringUtils.isIndexEqual1(strOfKeySet, key)) {
DeviceSettingManager.getInstance().setCameraControl(GlobalValue.MEMORY_RECALL, String.valueOf(key));
}
}
}
//预置位toast
private void showKeyMemoryToast(int key) {
UCToast.show(this, "预置位" + key + "设置成功");
}
public class MyHandler extends Handler {
private WeakReference<PreviewActivity> weakReference;
public MyHandler(PreviewActivity activity) {
weakReference = new WeakReference<>(activity);
}
/**
* Subclasses must implement this to receive messages.
*
* @param msg
*/
@Override
public void handleMessage(Message msg) {
L.d("do this --->>>" + msg.what);
if (msg.what == 100) {
int key = msg.arg1;
showKeyMemoryToast(key);
}
}
}
}
|
CapnSpellcheck/aka-ios-beacon | AKABeacon/AKABeacon/Classes/AKANullability.h | //
// AKANullability.h
// AKACommons
//
// Created by <NAME> on 20.09.15.
// Copyright © 2015 <NAME> & AKA Sarl. All rights reserved.
//
@import Foundation;
@import UIKit;
#ifndef AKANullability_h
#define AKANullability_h
/* Rationale:
We decided to (progressively) use nullability annotations in all interfaces, for the sake of Swift and also for the greater good.
That however rendered the source completely unreadable (Objective-C is already noisy, but with type declarations like `NSError* _Nullable __autoreleasing*_Nullable` it's just going too far.
So we decided to create type aliases using prefixes like 'opt_' (-ional), 'req_' (-uired), 'out_' (optional output parameter), 'reqout_' (required output parameter) and 'inout_' (optional input/output parameter). Out- and inout types are pointers to the respective type.
We initially used typedefs, but since these are visible in Swift (where it just creates confusion but doesn't help readability) we decided to use macros instead.
The #ifdef's should not be necessary if you create typedefs for prefixed type names such as opt_AKAProperty. We use them here, because it seems possible that something like out_NSError might be defined by another party. In this case we expect that it will be easier to detect such a conflict if we use their definition and get errors on our side of the table, since we are obviously not following naming conventions with this approach (the other party might be Apple).
We hate this approach, we just hate unreadable source code a bit more. If your point of view differs, we apologize (sincerely).
*/
#ifndef req_instancetype
// "nonnull instancetype" is not supported by AppCode (yet)
#define req_instancetype instancetype _Nonnull
#endif
#ifndef opt_instancetype
// "nullable instancetype" is not supported by AppCode (yet)
#define opt_instancetype instancetype _Nullable
#endif
#ifndef opt_id
#define opt_id id _Nullable
#endif
#ifndef req_id
#define req_id id _Nonnull
#endif
#ifndef out_id
#define out_id id _Nullable __autoreleasing * _Nullable
#endif
#ifndef inout_id
#define inout_id out_id
#endif
#ifndef opt_id_NSCopying
#define opt_id_NSCopying id<NSCopying> _Nullable
#endif
#ifndef req_id_NSCopying
#define req_id_NSCopying id<NSCopying> _Nonnull
#endif
#ifndef opt_NSObject
#define opt_NSObject NSObject* _Nullable
#endif
#ifndef req_NSObject
#define req_NSObject NSObject* _Nonnull
#endif
#ifndef opt_Class
#define opt_Class Class _Nullable
#endif
#ifndef req_Class
#define req_Class Class _Nonnull
#endif
#ifndef out_Class
#define out_Class Class _Nullable* _Nullable
#endif
#ifndef outreq_BOOL
#define outreq_BOOL BOOL* _Nonnull
#endif
#ifndef opt_NSError
#define opt_NSError NSError* _Nullable
#endif
#ifndef out_NSError
#define out_NSError NSError* _Nullable __autoreleasing*_Nullable
#endif
#ifndef req_NSError
#define req_NSError NSError* _Nonnull
#endif
#ifndef inout_NSError
#define inout_NSError out_NSError
#endif
#ifndef opt_NSString
#define opt_NSString NSString* _Nullable
#endif
#ifndef req_NSString
#define req_NSString NSString* _Nonnull
#endif
#ifndef out_NSString
#define out_NSString NSString* _Nullable __autoreleasing*_Nullable
#endif
#ifndef out_unichar
#define out_unichar unichar* _Nullable
#endif
#ifndef opt_NSNumber
#define opt_NSNumber NSNumber* _Nullable
#endif
#ifndef req_NSNumber
#define req_NSNumber NSNumber* _Nonnull
#endif
#ifndef out_NSNumber
#define out_NSNumber NSNumber* _Nullable __autoreleasing*_Nullable
#endif
#ifndef opt_NSDate
#define opt_NSDate NSDate* _Nullable
#endif
#ifndef req_NSDate
#define req_NSDate NSDate* _Nonnull
#endif
#ifndef opt_NSArray
#define opt_NSArray NSArray* _Nullable
#endif
#ifndef req_NSArray
#define req_NSArray NSArray* _Nonnull
#endif
#ifndef opt_NSSet
#define opt_NSSet NSSet* _Nullable
#endif
#ifndef req_NSSet
#define req_NSSet NSSet* _Nonnull
#endif
#ifndef opt_NSDictionary
#define opt_NSDictionary NSDictionary* _Nullable
#endif
#ifndef req_NSDictionary
#define req_NSDictionary NSDictionary* _Nonnull
#endif
#ifndef out_NSDictionary
#define out_NSDictionary NSDictionary* _Nullable __autoreleasing* _Nullable
#endif
#ifndef opt_NSMutableDictionary
#define opt_NSMutableDictionary NSMutableDictionary* _Nullable
#endif
#ifndef req_NSMutableDictionary
#define req_NSMutableDictionary NSMutableDictionary* _Nonnull
#endif
#ifndef opt_NSFormatter
#define opt_NSFormatter NSFormatter* _Nullable
#endif
#ifndef req_NSFormatter
#define req_NSFormatter NSFormatter* _Nonnull
#endif
#ifndef opt_NSDateFormatter
#define opt_NSDateFormatter NSDateFormatter* _Nullable
#endif
#ifndef req_NSDateFormatter
#define req_NSDateFormatter NSDateFormatter* _Nonnull
#endif
#ifndef opt_NSNumberFormatter
#define opt_NSNumberFormatter NSNumberFormatter* _Nullable
#endif
#ifndef req_NSNumberFormatter
#define req_NSNumberFormatter NSNumberFormatter* _Nonnull
#endif
#ifndef opt_NSLocale
#define opt_NSLocale NSLocale* _Nullable
#endif
#ifndef req_NSLocale
#define req_NSLocale NSLocale* _Nonnull
#endif
#ifndef opt_NSCalendar
#define opt_NSCalendar NSCalendar* _Nullable
#endif
#ifndef req_NSCalendar
#define req_NSCalendar NSCalendar* _Nonnull
#endif
#ifndef opt_NSTimeZone
#define opt_NSTimeZone NSTimeZone* _Nullable
#endif
#ifndef req_NSTimeZone
#define req_NSTimeZone NSTimeZone* _Nonnull
#endif
#ifndef opt_NSIndexPath
#define opt_NSIndexPath NSIndexPath* _Nullable
#endif
#ifndef req_NSIndexPath
#define req_NSIndexPath NSIndexPath* _Nonnull
#endif
#ifndef opt_SEL
#define opt_SEL SEL _Nullable
#endif
#ifndef req_SEL
#define req_SEL SEL _Nonnull
#endif
#ifndef opt_UIResponder
#define opt_UIResponder UIResponder* _Nullable
#endif
#ifndef req_UIResponder
#define req_UIResponder UIResponder* _Nonnull
#endif
#ifndef opt_UIViewController
#define opt_UIViewController UIViewController* _Nullable
#endif
#ifndef req_UIViewController
#define req_UIViewController UIViewController* _Nonnull
#endif
#ifndef opt_UIView
#define opt_UIView UIView* _Nullable
#endif
#ifndef req_UIView
#define req_UIView UIView* _Nonnull
#endif
#ifndef opt_UILabel
#define opt_UILabel UILabel* _Nullable
#endif
#ifndef req_UILabel
#define req_UILabel UILabel* _Nonnull
#endif
#ifndef opt_UITextField
#define opt_UITextField UITextField* _Nullable
#endif
#ifndef req_UITextField
#define req_UITextField UITextField* _Nonnull
#endif
#ifndef opt_UITextView
#define opt_UITextView UITextView* _Nullable
#endif
#ifndef req_UITextView
#define req_UITextView UITextView* _Nonnull
#endif
#ifndef opt_UISwitch
#define opt_UISwitch UISwitch* _Nullable
#endif
#ifndef req_UISwitch
#define req_UISwitch UISwitch* _Nonnull
#endif
#ifndef opt_UITableView
#define opt_UITableView UITableView* _Nullable
#endif
#ifndef req_UITableView
#define req_UITableView UITableView* _Nonnull
#endif
#ifndef opt_UITableViewCell
#define opt_UITableViewCell UITableViewCell* _Nullable
#endif
#ifndef req_UITableViewCell
#define req_UITableViewCell UITableViewCell* _Nonnull
#endif
#ifndef opt_UITableViewDataSource
#define opt_UITableViewDataSource id<UITableViewDataSource>_Nullable
#endif
#ifndef req_UITableViewDataSource
#define req_UITableViewDataSource id<UITableViewDataSource>_Nonnull
#endif
#ifndef opt_UITableViewDelegate
#define opt_UITableViewDelegate id<UITableViewDelegate>_Nullable
#endif
#ifndef req_UITableViewDelegate
#define req_UITableViewDelegate id<UITableViewDelegate>_Nonnull
#endif
#endif /* AKANullability_h */
|
Kaiofprates/orange-talents-02-template-casa-do-codigo | src/test/java/br/com/zup/desafio1/Category/CategoryFormTest.java | package br.com.zup.desafio1.Category;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@SpringBootTest
@AutoConfigureMockMvc
public class CategoryFormTest {
@Autowired
private MockMvc mockMvc;
@DisplayName("Deveria lidar com nome vazio")
@Test
public void nameEmptyTest() throws Exception{
CategoryRequestTest data = new CategoryRequestTest("");
mockMvc.perform(MockMvcRequestBuilders.post("/category")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(data))
).andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(jsonPath("$[0].error").isString())
.andExpect(jsonPath("$[0].error").value("The name field cannot be empty"))
.andExpect(jsonPath("$[0].field").value("name"))
.andDo(MockMvcResultHandlers.print());
}
}
|
VHAINNOVATIONS/Telepathology | Source/Java/CacheAPI/main/src/java/gov/va/med/imaging/storage/cache/impl/GroupPath.java | /**
*
*/
package gov.va.med.imaging.storage.cache.impl;
import java.util.List;
import gov.va.med.imaging.storage.cache.Group;
import gov.va.med.imaging.storage.cache.Region;
import gov.va.med.imaging.storage.cache.exceptions.CacheException;
/**
* @author VHAISWBECKEC
* A simple value object that contains references to a Group
* and all of its ancestors.
* The path field DOES NOT include the Group to which the GroupPath applies.
* The last entry in the path is the immediate ancestor (the parent) of the target Group.
*/
public class GroupPath
{
private Region region;
private List<Group> path;
private Group group;
public GroupPath(Region region, List<Group> path, Group group)
{
super();
this.region = region;
this.path = path;
this.group = group;
}
/**
* @return the group
*/
public Group getGroup()
{
return this.group;
}
/**
* @return the path
*/
public List<Group> getPath()
{
return this.path;
}
/**
* Return the names of the Group instances in the path as a String array, which
* is the way that the Cache usually deals with paths.
* @return
*/
public String[] getPathName()
{
String[] pathName = new String[path.size()];
int index=0;
for(Group group : path)
pathName[index++] = group.getName();
return pathName;
}
/**
* @return the region
*/
public Region getRegion()
{
return this.region;
}
/**
* Determines if the path from Region, through the path to the Group is valid.
* this method uses the Group.getName() to determine existence of the Group instances.
*
* @return
*/
public boolean validate()
{
try
{
Group parent = getRegion().getGroup(getPathName());
parent.getChildGroup(group.getName());
}
catch (CacheException x)
{
return false;
}
return true;
}
}
|
BernardoB95/Extrator_SPEDFiscal | Regs/Block_0/R0500.py | <filename>Regs/Block_0/R0500.py
from ..IReg import IReg
class R0500(IReg):
def __init__(self):
self._header = ['REG',
'DT_ALT',
'COD_NAT_CC',
'IND_CTA',
'NIVEL',
'COD_CTA',
'NOME_CTA']
self._hierarchy = "2"
|
MatIvan/LaborCoast-GWT | src/ru/mativ/shared/exception/LoginFialException.java | <gh_stars>0
package ru.mativ.shared.exception;
import java.io.Serializable;
public class LoginFialException extends Exception implements Serializable {
private static final long serialVersionUID = 1699524107930422612L;
public LoginFialException() {
super();
}
public LoginFialException(String message) {
super(message);
}
}
|
eugeneilyin/mdi-norm | src/RoundRedeem.js | <filename>src/RoundRedeem.js
import React from 'react'
import { Icon } from './Icon'
import { k, x, ek, bas } from './fragments'
export const RoundRedeem = /*#__PURE__*/ props => <Icon {...props}>
<path d={ek + "m10 15H5" + k + "v-1h16v1" + x + "zm1-5" + bas}/>
</Icon>
|
KWStudios/Techguns-Deathmatch | src/main/java/org/kwstudios/play/ragemode/updater/Updater.java | <gh_stars>0
package org.kwstudios.play.ragemode.updater;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.kwstudios.play.ragemode.loader.PluginLoader;
import org.kwstudios.play.ragemode.toolbox.ConstantHolder;
import com.google.common.io.Files;
import com.google.gson.Gson;
public class Updater {
private URL url;
private JavaPlugin plugin;
private String pluginurl;
private String version = "";
private String downloadURL = "";
private String[] changeLOG;
private boolean out = true;
/**
* Create a new SpigotPluginUpdate to check and update your plugin
*
* @param plugin
* - your plugin
* @param pluginurl
* - the url to your plugin.html on your webserver
*/
public Updater(JavaPlugin plugin, String pluginurl) {
try {
url = new URL(pluginurl);
} catch (MalformedURLException e) {
Bukkit.getConsoleSender().sendMessage(ConstantHolder.RAGEMODE_PREFIX + "Error in checking update for: '"
+ pluginurl + "' (invalid URL?)");
e.printStackTrace();
}
this.plugin = plugin;
this.pluginurl = pluginurl;
Thread thread = new Thread(new UpdateRunnable());
thread.start();
}
/**
* Enable a console output if new Version is availible
*/
public void enableOut() {
out = true;
}
/**
* Disable a console output if new Version is availible
*/
public void disableOut() {
out = false;
}
/**
* Check for a new Update
*
* @return if new update is availible
*/
private boolean needsUpdate() {
try {
URLConnection con = url.openConnection();
InputStream _in = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(_in, "UTF8"));
/*
* Document doc =
* DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
* _in);
*
* Node nod = doc.getElementsByTagName("item").item(0); NodeList
* children = nod.getChildNodes();
*
* version = children.item(1).getTextContent(); downloadURL =
* children.item(3).getTextContent(); changeLOG =
* children.item(5).getTextContent();
*/
Gson gson = new Gson();
UpdaterJson updaterJson = gson.fromJson(reader, UpdaterJson.class);
version = updaterJson.VERSION;
downloadURL = updaterJson.LINK;
changeLOG = updaterJson.RELEASE_NOTES;
if (newVersion(plugin.getDescription().getVersion(), version.replaceAll("[a-zA-z ]", ""))) {
if (out) {
Bukkit.getConsoleSender().sendMessage(ConstantHolder.RAGEMODE_PREFIX + "New Version found: "
+ version.replaceAll("[a-zA-z ]", "").replaceAll("-", ""));
Bukkit.getConsoleSender().sendMessage(
ConstantHolder.RAGEMODE_PREFIX + "Download it here: " + downloadURL.toString());
Bukkit.getConsoleSender().sendMessage(ConstantHolder.RAGEMODE_PREFIX + "Changelog: ");
for (String change : changeLOG) {
Bukkit.getConsoleSender().sendMessage(change);
}
}
return true;
}
} catch (IOException e) {
Bukkit.getConsoleSender().sendMessage(ConstantHolder.RAGEMODE_PREFIX + "Error in checking update for: '"
+ pluginurl + "' (invalid URL?) !");
e.printStackTrace();
}
return false;
}
/**
* Checks if the newversion is really newer then the other one
*
* @param oldv
* @param newv
* @return if it is newer
*/
private boolean newVersion(String oldv, String newv) {
// System.out.println("Check " + oldv + " - " + newv);
if (oldv != null && newv != null) {
oldv = oldv.replaceAll("[a-zA-z ]", "");
oldv = oldv.replaceAll(" ", "");
oldv = oldv.replaceAll("-", "");
newv = newv.replaceAll("[a-zA-z ]", "");
newv = newv.replaceAll(" ", "");
newv = newv.replaceAll("-", "");
oldv = oldv.replace('.', '_');
newv = newv.replace('.', '_');
// System.out.println("length: " + oldv.split("_").length +" || " +
// newv.split("_").length);
if (oldv.split("_").length != 0 && oldv.split("_").length != 1 && newv.split("_").length != 0
&& newv.split("_").length != 1) {
int vnum = Integer.valueOf(oldv.split("_")[0]);
int vsec = Integer.valueOf(oldv.split("_")[1]);
int vbuild = (oldv.split("_").length >= 3) ? Integer.valueOf(oldv.split("_")[2]) : 0;
int newvnum = Integer.valueOf(newv.split("_")[0]);
int newvsec = Integer.valueOf(newv.split("_")[1]);
int newvbuild = (newv.split("_").length >= 3) ? Integer.valueOf(newv.split("_")[2]) : 0;
// System.out.println("Check2: " + vnum + " ? " + newvnum + " ||
// " + vsec + " ? " + newvsec);
if (newvnum > vnum)
return true;
if (newvnum == vnum) {
if (newvsec > vsec) {
return true;
}
if (newvsec == vsec) {
if (newvbuild > vbuild) {
return true;
}
}
}
}
}
return false;
}
/**
* Executes the Update and tries to install it.
*
*/
private void externalUpdate() {
try {
URL download = new URL(downloadURL);
BufferedInputStream in = null;
FileOutputStream fout = null;
File newFile = null;
try {
if (out) {
plugin.getLogger().info("Trying to download from: " + downloadURL);
}
in = new BufferedInputStream(download.openStream());
String newFileName = PluginLoader.getInstance().getName().toLowerCase() + "-" + version.toLowerCase()
+ ".jar";
newFile = new File(PluginLoader.getInstance().getDataFolder(), newFileName);
fout = new FileOutputStream(newFile);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
if (newFile.exists()) {
URL oldFileURL = Bukkit.getPluginManager().getPlugin(PluginLoader.getInstance().getName()).getClass()
.getProtectionDomain().getCodeSource().getLocation();
String[] splittedPath = oldFileURL.getPath().split("/");
String oldFileName = splittedPath[splittedPath.length - 1];
File oldFile = new File(PluginLoader.getInstance().getDataFolder().getParentFile(), oldFileName);
// if (oldFile.exists()) {
// oldFile.delete();
// }
// File newPluginFile = new
// File(PluginLoader.getInstance().getDataFolder().getParentFile(),
// newFile.getName());
File newPluginFile = new File(PluginLoader.getInstance().getServer().getUpdateFolderFile(),
oldFile.getName());
if (!newPluginFile.getParentFile().exists()) {
newPluginFile.getParentFile().mkdirs();
}
Files.copy(newFile, newPluginFile);
newFile.delete();
}
if (out) {
plugin.getLogger().info("Succesfully downloaded file: " + downloadURL);
plugin.getLogger().info("To have the Features, you should restart your Server!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class UpdaterJson {
public String VERSION;
public String LINK;
public String[] RELEASE_NOTES;
}
private class UpdateRunnable implements Runnable {
@Override
public void run() {
Updater.this.enableOut();
if (Updater.this.needsUpdate()) {
Updater.this.externalUpdate();
}
}
}
} |
mankeyl/elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/NumericDoubleValues.java | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.fielddata;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.search.DoubleValues;
import java.io.IOException;
/**
* A per-document numeric value.
*/
public abstract class NumericDoubleValues extends DoubleValues {
/** Sole constructor. (For invocation by subclass
* constructors, typically implicit.) */
protected NumericDoubleValues() {}
// TODO: this interaction with sort comparators is really ugly...
/** Returns numeric docvalues view of raw double bits */
public NumericDocValues getRawDoubleValues() {
return new AbstractNumericDocValues() {
private int docID = -1;
@Override
public boolean advanceExact(int target) throws IOException {
docID = target;
return NumericDoubleValues.this.advanceExact(target);
}
@Override
public long longValue() throws IOException {
return Double.doubleToRawLongBits(NumericDoubleValues.this.doubleValue());
}
@Override
public int docID() {
return docID;
}
};
}
// yes... this is doing what the previous code was doing...
/** Returns numeric docvalues view of raw float bits */
public NumericDocValues getRawFloatValues() {
return new AbstractNumericDocValues() {
private int docID = -1;
@Override
public boolean advanceExact(int target) throws IOException {
docID = target;
return NumericDoubleValues.this.advanceExact(target);
}
@Override
public long longValue() throws IOException {
return Float.floatToRawIntBits((float) NumericDoubleValues.this.doubleValue());
}
@Override
public int docID() {
return docID;
}
};
}
}
|
mgpavlov/SoftUni | Java/Java Web/01.Java Web Development Basics - January 2019/11.Exam Preparation/ExamPrepII/examPrep2/src/main/java/exam/web/beans/HomeBean.java | package exam.web.beans;
import exam.domain.models.view.UserHomeViewModel;
import org.modelmapper.ModelMapper;
import exam.domain.models.service.UserServiceModel;
import exam.service.UserService;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
@Named
@RequestScoped
public class HomeBean extends BaseBean{
private List<UserHomeViewModel> notFriends;
private UserServiceModel loggedInUser;
private UserService userService;
private ModelMapper modelMapper;
public HomeBean() {
}
@Inject
public HomeBean(UserService userService, ModelMapper modelMapper) {
this.userService = userService;
this.modelMapper = modelMapper;
}
@PostConstruct
private void init() {
String currentUsername = (String) ((HttpSession) FacesContext
.getCurrentInstance()
.getExternalContext()
.getSession(true)).getAttribute("username");
String currentUserId = (String) ((HttpSession) FacesContext
.getCurrentInstance()
.getExternalContext()
.getSession(true)).getAttribute("userId");
this.loggedInUser = userService
.findUserById(currentUserId);
this.notFriends = this.userService.findAllUsers().stream()
.filter(u->!u.getId().equals(currentUserId))
.filter(u-> !loggedInUser.getFriends().stream().map(UserServiceModel::getUsername).collect(Collectors.toList()).contains(u.getUsername()))
.map(u->modelMapper.map(u, UserHomeViewModel.class))
.collect(Collectors.toList());
}
public List<UserHomeViewModel> getNotFriends() {
return this.notFriends;
}
public void setNotFriends(List<UserHomeViewModel> notFriends) {
this.notFriends = notFriends;
}
public UserServiceModel getLoggedInUser() {
return this.loggedInUser;
}
public void setLoggedInUser(UserServiceModel loggedInUser) {
this.loggedInUser = loggedInUser;
}
public void addFriend(String id){
UserServiceModel newFriend = this.userService.findUserById(id);
this.loggedInUser.getFriends().add(newFriend);
newFriend.getFriends().add(this.loggedInUser);
if (!this.userService.userUpdate(this.loggedInUser) || !this.userService.userUpdate(newFriend)){
throw new IllegalArgumentException("Cannot add friend!");
}
this.redirect("home");
}
public void removeUser(String id){
UserServiceModel userServiceModel = this.userService.findUserById(id);
if (!this.userService.userDelete(userServiceModel)){
throw new IllegalArgumentException("Cannot delete friend!");
}
this.redirect("home");
}
}
|
yoshson/workbench | workbench/contacts/forms.py | <reponame>yoshson/workbench<filename>workbench/contacts/forms.py
from collections import OrderedDict
from django import forms
from django.conf import settings
from django.contrib import messages
from django.forms.models import inlineformset_factory
from django.template.defaultfilters import linebreaksbr
from django.utils.html import format_html, format_html_join
from django.utils.translation import gettext_lazy as _, ngettext
from workbench.contacts.models import (
EmailAddress,
Group,
Organization,
Person,
PhoneNumber,
PostalAddress,
)
from workbench.tools.forms import Autocomplete, Form, ModelForm, Textarea, add_prefix
from workbench.tools.models import ProtectedError, SlowCollector
from workbench.tools.substitute_with import substitute_with
from workbench.tools.vcard import person_to_vcard, render_vcard_response
from workbench.tools.xlsx import WorkbenchXLSXDocument
class OrganizationSearchForm(Form):
q = forms.CharField(
required=False,
widget=forms.TextInput(
attrs={"class": "form-control", "placeholder": _("Search")}
),
label="",
)
g = forms.ModelChoiceField(
queryset=Group.objects.all(),
required=False,
empty_label=_("All groups"),
widget=forms.Select(attrs={"class": "custom-select"}),
label="",
)
def filter(self, queryset):
data = self.cleaned_data
queryset = queryset.search(data.get("q")).active()
return self.apply_renamed(queryset, "g", "groups")
class PersonSearchForm(Form):
q = forms.CharField(
required=False,
widget=forms.TextInput(
attrs={"class": "form-control", "placeholder": _("Search")}
),
label="",
)
g = forms.ModelChoiceField(
queryset=Group.objects.all(),
required=False,
empty_label=_("All groups"),
widget=forms.Select(attrs={"class": "custom-select"}),
label="",
)
def filter(self, queryset):
data = self.cleaned_data
queryset = queryset.search(data.get("q")).active()
return self.apply_renamed(queryset, "g", "groups").select_related(
"organization"
)
def response(self, request, queryset):
if request.GET.get("export") == "xlsx":
xlsx = WorkbenchXLSXDocument()
xlsx.people(queryset)
return xlsx.to_response("people.xlsx")
elif request.GET.get("export") == "vcard":
return render_vcard_response(
request,
"\n".join(
person_to_vcard(person).serialize()
for person in queryset.prefetch_related(
"phonenumbers", "emailaddresses", "postaladdresses"
)[: settings.BATCH_MAX_ITEMS]
),
)
class OrganizationForm(ModelForm):
user_fields = default_to_current_user = ("primary_contact",)
class Meta:
model = Organization
fields = (
"name",
"is_private_person",
"notes",
"primary_contact",
"default_billing_address",
"groups",
"is_archived",
)
widgets = {
"name": Textarea(),
"notes": Textarea(),
"default_billing_address": Textarea(),
"groups": forms.CheckboxSelectMultiple(),
}
class OrganizationDeleteForm(ModelForm):
class Meta:
model = Organization
fields = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
collector = SlowCollector(using=self.instance._state.db)
try:
collector.collect([self.instance])
except ProtectedError:
self.fields["substitute_with"] = forms.ModelChoiceField(
Organization.objects.exclude(pk=self.instance.pk),
widget=Autocomplete(model=Organization),
label=_("substitute with"),
)
if self.request.method == "GET":
messages.info(
self.request,
_(
"This organization has related objects. It is"
" therefore not possible to delete it, but you"
" may reassign the related objects to a different"
" organization."
" Alternatively, you can also archive the organization."
),
)
def delete(self):
if "substitute_with" in self.fields:
substitute_with(
to_delete=self.instance, keep=self.cleaned_data["substitute_with"]
)
else:
self.instance.delete()
class PersonForm(ModelForm):
user_fields = default_to_current_user = ["primary_contact"]
class Meta:
model = Person
fields = (
"address",
"given_name",
"family_name",
"address_on_first_name_terms",
"salutation",
"date_of_birth",
"notes",
"organization",
"primary_contact",
"groups",
"is_archived",
)
widgets = {
"notes": Textarea(),
"organization": Autocomplete(model=Organization),
"groups": forms.CheckboxSelectMultiple(),
}
def __init__(self, *args, **kwargs):
request = kwargs["request"]
initial = kwargs.setdefault("initial", {})
if organization := request.GET.get("organization"):
initial["organization"] = organization
super().__init__(*args, **kwargs)
kwargs.pop("request")
self.formsets = (
OrderedDict(
(
("phonenumbers", PhoneNumberFormset(*args, **kwargs)),
("emailaddresses", EmailAddressFormset(*args, **kwargs)),
("postaladdresses", PostalAddressFormset(*args, **kwargs)),
)
)
if self.instance.pk
else OrderedDict()
)
def clean(self):
data = super().clean()
if data.get("salutation") and len(data.get("salutation").split()) < 2:
self.add_warning(
_("This does not look right. Please add a full salutation."),
code="short-salutation",
)
if self.instance.pk and "organization" in self.changed_data:
from workbench.invoices.models import Invoice
from workbench.projects.models import Project
related = []
invoices = Invoice.objects.filter(contact=self.instance).count()
projects = Project.objects.filter(contact=self.instance).count()
for model, count in [
(Invoice, invoices),
(Project, projects),
]:
if count:
related.append(
"%s %s"
% (
count,
ngettext(
model._meta.verbose_name,
model._meta.verbose_name_plural,
count,
),
)
)
if related:
self.add_warning(
_(
"This person is the contact of the following related objects:"
" %s. Modifying this record may be more confusing than"
" archiving this one and creating a new record instead."
)
% ", ".join(related),
code="organization-update",
)
return data
def is_valid(self):
return all(
[super().is_valid()]
+ [formset.is_valid() for formset in self.formsets.values()]
)
def save(self, commit=True):
instance = super().save()
for formset in self.formsets.values():
formset.save()
return instance
PhoneNumberFormset = inlineformset_factory(
Person,
PhoneNumber,
fields=("type", "phone_number"),
extra=0,
widgets={
"type": forms.TextInput(
attrs={"class": "form-control short", "placeholder": _("type")}
),
"phone_number": forms.TextInput(attrs={"class": "form-control"}),
},
)
EmailAddressFormset = inlineformset_factory(
Person,
EmailAddress,
fields=("type", "email"),
extra=0,
widgets={
"type": forms.TextInput(
attrs={"class": "form-control short", "placeholder": _("type")}
),
"email": forms.TextInput(attrs={"class": "form-control"}),
},
)
class PostalAddressForm(forms.ModelForm):
class Meta:
model = PostalAddress
fields = (
"type",
"street",
"house_number",
"address_suffix",
"postal_code",
"city",
"country",
"postal_address_override",
)
widgets = {
"type": forms.TextInput(
attrs={"class": "form-control short", "placeholder": _("type")}
),
"postal_address_override": Textarea(
attrs={"class": "form-control", "rows": 3}
),
}
PostalAddressFormset = inlineformset_factory(
Person, PostalAddress, form=PostalAddressForm, extra=0
)
class PostalAddressSelectionForm(ModelForm):
def add_postal_address_selection_if_empty(
self, *, organization=None, person=None, for_billing=False
):
postal_addresses = []
if person:
if (
for_billing
and person.organization
and person.organization.default_billing_address
):
postal_addresses.append(
(
_("default billing address"),
person.organization.default_billing_address,
)
)
postal_addresses.extend(
(pa.type, pa.postal_address)
for pa in PostalAddress.objects.filter(person=person).select_related(
"person__organization"
)
)
if organization and (not person or not postal_addresses):
if for_billing and organization.default_billing_address:
postal_addresses.append(
(_("default billing address"), organization.default_billing_address)
)
postal_addresses.extend(
(pa.type, pa.postal_address)
for pa in PostalAddress.objects.filter(
person__organization=organization
)
.exclude(person=person)
.select_related("person__organization")
)
if postal_addresses:
self.fields["postal_address"].help_text = format_html(
'<strong>{}</strong><br><div class="'
' list-group list-group-horizontal flex-wrap">{}</div>',
_("Select one of the following addresses:"),
format_html_join(
"",
'<span class="list-group-item list-group-item-action w-auto"'
' data-field-value="{}"><strong>{}</strong><br>{}</span>',
[(pa, type, linebreaksbr(pa)) for type, pa in postal_addresses],
),
)
# repr(postal_addresses)
def clean(self):
data = super().clean()
postal_address = data.get("postal_address", "")
if len(postal_address.strip().splitlines()) < 3:
self.add_warning(
_(
"The postal address should probably be at least three"
" lines long."
),
code="short-postal-address",
)
return data
@add_prefix("modal")
class PersonAutocompleteForm(forms.Form):
person = forms.ModelChoiceField(
queryset=Person.objects.all(), widget=Autocomplete(model=Person), label=""
)
|
KevinLuo41/LeetCodeInPython | binary_tree_level_order_traversal_ii.py | <reponame>KevinLuo41/LeetCodeInPython
#!/usr/bin/env python
# encoding: utf-8
"""
binary_tree_level_order_traversal_ii.py
Created by Shengwei on 2014-07-29.
"""
# https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/
# tags: medium, tree, traversal, reversed, bfs
"""
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
"""
# https://oj.leetcode.com/discuss/5353/there-better-regular-level-order-traversal-reverse-result
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrderBottom(self, root):
if root is None:
return []
# the first None as a sentinel so the root
# level will be added to the result
stack = [None, root]
index = 0
while index < len(stack):
node = stack[index]
if node is None:
if index == len(stack) - 1:
break
stack.append(None)
else:
# add children in reversed order
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
# remember to increase index even when
# the node is None
index += 1
result, level = [], []
stack.pop() # remove the last None marker
while stack:
if stack[-1] is None:
# processed one level
result.append(level)
level = []
stack.pop() # pop out None marker
continue
level.append(stack.pop().val)
return result
############## alternative ##############
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrderBottom(self, root):
if root is None:
return []
stack, index = [root, None], 0
while index < len(stack):
node = stack[index]
if node is None:
if index == len(stack) - 1:
break
stack.append(None)
else:
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
# remember to increase index even when
# the node is None
index += 1
result = []
start = end = -1 # end always points at None
while end > -len(stack):
while start > -len(stack) and stack[start - 1]:
# stack[start - 1], if exists, is not None
start -= 1
# start == -len(stack) or stack[start - 1] is None
level = [node.val for node in stack[start:end]]
result.append(level)
# more exactly, start can be start - 2 now
start = end = start - 1
return result
|
jiandequn/code | log_chart_manager/src/main/java/com/ppfuns/report/mapper/AppDetailPageAlbumContentTypeCountDayMapper.java | package com.ppfuns.report.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ppfuns.report.entity.AppDetailPageAlbumContentTypeCountDay;
/**
* 按日统计专辑详情页专辑类型访问(AppDetailPageAlbumContentTypeCountDay)表数据库访问层
*
* @author jdq
* @since 2021-07-28 16:22:17
*/
public interface AppDetailPageAlbumContentTypeCountDayMapper extends BaseMapper<AppDetailPageAlbumContentTypeCountDay> {
}
|
redhat-openstack/manila | manila/tests/api/views/test_scheduler_stats.py | # Copyright (c) 2015 <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
from manila.api.views import scheduler_stats
from manila import test
POOL1 = {
'name': 'host1@backend1#pool1',
'host': 'host1',
'backend': 'backend1',
'pool': 'pool1',
'other': 'junk',
'capabilities': {
'pool_name': 'pool1',
'driver_handles_share_servers': False,
'QoS_support': 'False',
'timestamp': '2015-03-15T19:15:42.611690',
'allocated_capacity_gb': 5,
'total_capacity_gb': 10,
},
}
POOL2 = {
'name': 'host1@backend1#pool2',
'host': 'host1',
'backend': 'backend1',
'pool': 'pool2',
'capabilities': {
'pool_name': 'pool2',
'driver_handles_share_servers': False,
'QoS_support': 'False',
'timestamp': '2015-03-15T19:15:42.611690',
'allocated_capacity_gb': 15,
'total_capacity_gb': 20,
},
}
POOLS = [POOL1, POOL2]
POOLS_DETAIL_VIEW = {
'pools': [
{
'name': 'host1@backend1#pool1',
'host': 'host1',
'backend': 'backend1',
'pool': 'pool1',
'capabilities': {
'pool_name': 'pool1',
'driver_handles_share_servers': False,
'QoS_support': 'False',
'timestamp': '2015-03-15T19:15:42.611690',
'allocated_capacity_gb': 5,
'total_capacity_gb': 10,
},
}, {
'name': 'host1@backend1#pool2',
'host': 'host1',
'backend': 'backend1',
'pool': 'pool2',
'capabilities': {
'pool_name': 'pool2',
'driver_handles_share_servers': False,
'QoS_support': 'False',
'timestamp': '2015-03-15T19:15:42.611690',
'allocated_capacity_gb': 15,
'total_capacity_gb': 20,
}
}
]
}
class ViewBuilderTestCase(test.TestCase):
def setUp(self):
super(ViewBuilderTestCase, self).setUp()
self.builder = scheduler_stats.ViewBuilder()
def test_pools(self):
result = self.builder.pools(POOLS)
# Remove capabilities for summary view
expected = copy.deepcopy(POOLS_DETAIL_VIEW)
for pool in expected['pools']:
del pool['capabilities']
self.assertDictEqual(expected, result)
def test_pools_with_details(self):
result = self.builder.pools(POOLS, detail=True)
expected = POOLS_DETAIL_VIEW
self.assertDictEqual(expected, result)
|
sebastienbarbier/723e_react | src/app/reducers/report.reducer.js | <reponame>sebastienbarbier/723e_react
import { USER_LOGOUT, REPORT_SET_DATES, RESET } from "../constants";
import moment from "moment";
const initialState = {
dateBegin: moment.utc().startOf("year"),
dateEnd: moment.utc().endOf("year"),
title: null
};
function report(state = initialState, action) {
switch (action.type) {
case REPORT_SET_DATES:
return Object.assign(
{},
{
dateBegin: action.dateBegin.toDate(),
dateEnd: action.dateEnd.toDate(),
title: action.title
}
);
case USER_LOGOUT:
return Object.assign({}, initialState);
case RESET:
return Object.assign({}, initialState);
default:
return state;
}
}
export default report;
|
Szeba25/hades | src/main/java/hu/szeba/hades/wizard/view/panels/TaskEditorPanel.java | <reponame>Szeba25/hades
package hu.szeba.hades.wizard.view.panels;
import hu.szeba.hades.main.meta.Languages;
import hu.szeba.hades.main.util.FileUtilities;
import hu.szeba.hades.main.util.GridBagSetter;
import hu.szeba.hades.main.view.components.DialogFactory;
import hu.szeba.hades.main.view.elements.MappedElement;
import hu.szeba.hades.wizard.form.CodeEditorForm;
import hu.szeba.hades.wizard.form.HTMLDescriptionsEditorForm;
import hu.szeba.hades.wizard.form.InputResultEditorForm;
import hu.szeba.hades.wizard.model.WizardTask;
import hu.szeba.hades.wizard.view.components.ModifiableListPanel;
import hu.szeba.hades.wizard.view.elements.DescriptiveElement;
import org.apache.commons.io.FileUtils;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class TaskEditorPanel extends JPanel {
private DescriptiveElement currentElementRef;
private WizardTask currentTask;
private JPanel leftPanel;
private JTextField titleField;
private JComboBox<String> difficultyBox;
private JComboBox<String> lengthBox;
private JTextArea tags;
private JPanel rightPanel;
private ModifiableListPanel inputResultPanel;
private JButton editSources;
private JButton editSolutions;
private JButton editDescriptions;
private JPanel regexPanel;
private JTextArea regexInclude;
private JTextArea regexExclude;
private InputResultEditorForm inputResultEditorForm;
private CodeEditorForm sourceEditorForm;
private CodeEditorForm solutionEditorForm;
private HTMLDescriptionsEditorForm htmlDescriptionsEditorForm;
public TaskEditorPanel() {
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createEtchedBorder());
currentElementRef = null;
currentTask = null;
initializeComponents();
setupEvents();
this.add(leftPanel, BorderLayout.WEST);
this.add(rightPanel, BorderLayout.CENTER);
setVisible(false);
}
private void initializeComponents() {
initializeLeftPanel();
initializeRightPanel();
inputResultEditorForm = new InputResultEditorForm();
sourceEditorForm = new CodeEditorForm();
solutionEditorForm = new CodeEditorForm();
htmlDescriptionsEditorForm = new HTMLDescriptionsEditorForm();
}
private void initializeLeftPanel() {
leftPanel = new JPanel();
leftPanel.setLayout(new GridBagLayout());
leftPanel.setPreferredSize(new Dimension(250, 0));
titleField = new JTextField();
JLabel titleLabel = new JLabel(Languages.translate("Title:"));
titleLabel.setLabelFor(titleField);
// TODO: Translate these too!
difficultyBox = new JComboBox<>();
difficultyBox.addItem("Novice");
difficultyBox.addItem("Easy");
difficultyBox.addItem("Normal");
difficultyBox.addItem("Hard");
difficultyBox.addItem("Master");
// TODO: Translate these too!
JLabel difficultyLabel = new JLabel(Languages.translate("Difficulty:"));
difficultyLabel.setLabelFor(difficultyBox);
// TODO: Translate these too!
lengthBox = new JComboBox<>();
lengthBox.addItem("Short");
lengthBox.addItem("Medium");
lengthBox.addItem("Long");
// TODO: Translate these too!
JLabel lengthLabel = new JLabel(Languages.translate("Length:"));
lengthLabel.setLabelFor(lengthBox);
tags = new JTextArea();
JScrollPane tagsScroll = new JScrollPane(tags);
tagsScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
GridBagSetter gs = new GridBagSetter();
gs.setComponent(leftPanel);
gs.add(titleLabel,
0,
0,
GridBagConstraints.BOTH,
1,
1,
0,
0,
new Insets(5, 5, 5, 5));
gs.add(titleField,
1,
0,
GridBagConstraints.HORIZONTAL,
1,
1,
1,
0,
new Insets(5, 5, 5, 0));
gs.add(difficultyLabel,
0,
1,
GridBagConstraints.BOTH,
1,
1,
0,
0,
new Insets(0, 5, 5, 5));
gs.add(difficultyBox,
1,
1,
GridBagConstraints.HORIZONTAL,
1,
1,
1,
0,
new Insets(0, 5, 5, 0));
gs.add(lengthLabel,
0,
2,
GridBagConstraints.BOTH,
1,
1,
0,
0,
new Insets(0, 5, 5, 5));
gs.add(lengthBox,
1,
2,
GridBagConstraints.HORIZONTAL,
1,
1,
1,
0,
new Insets(0, 5, 5, 0));
gs.add(new JLabel(Languages.translate("Tags:")),
0,
3,
GridBagConstraints.BOTH,
2,
1,
0,
0,
new Insets(5, 5, 5, 5));
gs.add(tagsScroll,
0,
4,
GridBagConstraints.BOTH,
2,
1,
1,
1,
new Insets(5, 5, 5, 5));
}
private void initializeRightPanel() {
rightPanel = new JPanel();
rightPanel.setLayout(new GridBagLayout());
inputResultPanel = new ModifiableListPanel(Languages.translate("Input result pairs:"), 200);
inputResultPanel.setBorder(BorderFactory.createEtchedBorder());
regexPanel = new JPanel();
regexPanel.setLayout(new GridBagLayout());
regexPanel.setBorder(BorderFactory.createEtchedBorder());
regexInclude = new JTextArea();
JScrollPane regexIncludeScroll = new JScrollPane(regexInclude);
regexIncludeScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
regexInclude.setEnabled(false);
regexInclude.setBackground(new Color(220, 220, 220));
regexExclude = new JTextArea();
JScrollPane regexExcludeScroll = new JScrollPane(regexExclude);
regexExcludeScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
regexExclude.setEnabled(false);
regexExclude.setBackground(new Color(220, 220, 220));
GridBagSetter gs = new GridBagSetter();
gs.setComponent(regexPanel);
gs.add(new JLabel(Languages.translate("RegEx include:")),
0,
0,
GridBagConstraints.BOTH,
1,
1,
0,
0,
new Insets(5, 5, 5, 5));
gs.add(regexIncludeScroll,
0,
1,
GridBagConstraints.BOTH,
1,
1,
1,
1,
new Insets(0, 5, 5, 5));
gs.add(new JLabel(Languages.translate("RegEx exclude:")),
0,
2,
GridBagConstraints.BOTH,
1,
1,
0,
0,
new Insets(5, 5, 5, 5));
gs.add(regexExcludeScroll,
0,
3,
GridBagConstraints.BOTH,
1,
1,
1,
1,
new Insets(0, 5, 5, 5));
editSources = new JButton(Languages.translate("Edit sources"));
editSources.setFocusPainted(false);
editSolutions = new JButton(Languages.translate("Edit solutions"));
editSolutions.setFocusPainted(false);
editDescriptions = new JButton(Languages.translate("Edit descriptions"));
editDescriptions.setFocusPainted(false);
gs.setComponent(rightPanel);
gs.add(inputResultPanel,
0,
0,
GridBagConstraints.BOTH,
3,
1,
1,
0.3,
new Insets(5, 5, 5, 5));
gs.add(regexPanel,
0,
1,
GridBagConstraints.BOTH,
3,
1,
1,
0.7,
new Insets(0, 5, 5, 5));
gs.add(editSources,
0,
2,
GridBagConstraints.HORIZONTAL,
1,
1,
0.5,
0,
new Insets(5, 5,5, 5));
gs.add(editSolutions,
1,
2,
GridBagConstraints.HORIZONTAL,
1,
1,
0.5,
0,
new Insets(5,5, 5, 5));
gs.add(editDescriptions,
2,
2,
GridBagConstraints.HORIZONTAL,
1,
1,
0.5,
0,
new Insets(5,5, 5, 5));
}
private void setupEvents() {
inputResultPanel.getModifier().getAdd().addActionListener((event) -> {
String name = DialogFactory.showCustomInputDialog(
"",
Languages.translate("New input/result pair name:"),
Languages.translate("Add new input/result pair"),
Languages.translate("Ok"),
Languages.translate("Cancel"));
if (name != null) {
if (name.length() > 0 && FileUtilities.validFileName(name) && !currentTask.isInputResultFileExists(name)) {
try {
// Add a new i/r pair
currentTask.addInputResultFile(name);
DefaultListModel<MappedElement> model = (DefaultListModel<MappedElement>) inputResultPanel.getList().getModel();
MappedElement newElement = new MappedElement(name, name);
model.addElement(newElement);
inputResultPanel.getList().setSelectedValue(newElement, true);
// Open the editor
inputResultEditorForm.setContents(name, "", "");
inputResultEditorForm.setLocationRelativeTo(null);
inputResultEditorForm.setVisible(true);
// Save back content
currentTask.setInputFileData(name, inputResultEditorForm.getInputFileData());
currentTask.setResultFileData(name, inputResultEditorForm.getResultFileData());
// Rename if possible!
String newName = inputResultEditorForm.getNewName();
if (!name.equals(newName)) {
// Only rename if changed!
if (newName.length() > 0 && FileUtilities.validFileName(newName) && !currentTask.isInputResultFileExists(newName)) {
currentTask.renameInputResultFile(name, newName);
newElement.setId(newName);
newElement.setTitle(newName);
inputResultPanel.getList().repaint();
} else {
DialogFactory.showCustomError(
Languages.translate("This input/result pair name is invalid"),
Languages.translate("Invalid pair name"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
DialogFactory.showCustomError(
Languages.translate("This input/result pair name is invalid"),
Languages.translate("Invalid pair name"));
}
} else {
DialogFactory.showCustomError(
Languages.translate("This input/result pair name is invalid"),
Languages.translate("Invalid pair name"));
}
});
inputResultPanel.getModifier().getEdit().addActionListener((event) -> {
MappedElement selected = inputResultPanel.getList().getSelectedValue();
if (selected != null) {
try {
// Set contents, and open the editor
inputResultEditorForm.setContents(selected.getId(), currentTask.getInputFileData(selected.getId()), currentTask.getResultFileData(selected.getId()));
inputResultEditorForm.setLocationRelativeTo(null);
inputResultEditorForm.setVisible(true);
// Save back contents
currentTask.setInputFileData(selected.getId(), inputResultEditorForm.getInputFileData());
currentTask.setResultFileData(selected.getId(), inputResultEditorForm.getResultFileData());
// Rename if possible!
String newName = inputResultEditorForm.getNewName();
if (!selected.getId().equals(newName)) {
// Only rename if changed!
if (newName.length() > 0 && FileUtilities.validFileName(newName) && !currentTask.isInputResultFileExists(newName)) {
currentTask.renameInputResultFile(selected.getId(), newName);
selected.setId(newName);
selected.setTitle(newName);
inputResultPanel.getList().repaint();
} else {
DialogFactory.showCustomError(
Languages.translate("This input/result pair name is invalid"),
Languages.translate("Invalid pair name"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
inputResultPanel.getModifier().getDelete().addActionListener((event) -> {
MappedElement selected = inputResultPanel.getList().getSelectedValue();
if (selected != null) {
int result = DialogFactory.showCustomChoiceDialog(
Languages.translate("Delete this input/result pair?"),
Languages.translate("Delete input/result pair"),
Languages.translate("Delete"),
Languages.translate("Cancel"));
if (result == JOptionPane.YES_OPTION) {
currentTask.removeInputResultFile(selected.getId());
DefaultListModel<MappedElement> model = (DefaultListModel<MappedElement>) inputResultPanel.getList().getModel();
model.removeElement(selected);
}
}
});
editSources.addActionListener((event) -> {
sourceEditorForm.setFiles(currentTask.getSourceFiles(),
new File(currentTask.getTaskPath(), "sources"), currentTask.getReadonlySourcesData());
sourceEditorForm.setLocationRelativeTo(null);
sourceEditorForm.setVisible(true);
currentTask.setReadonlySourcesData(sourceEditorForm.getReadonlySourcesData());
});
editSolutions.addActionListener((event) -> {
solutionEditorForm.setFiles(currentTask.getSolutionFiles(),
new File(currentTask.getTaskPath(), "solutions"), null);
solutionEditorForm.setLocationRelativeTo(null);
solutionEditorForm.setVisible(true);
});
editDescriptions.addActionListener((event) -> {
htmlDescriptionsEditorForm.setup(
currentTask.getShortStory(),
currentTask.getStory(),
currentTask.getShortInstructions(),
currentTask.getInstructions());
htmlDescriptionsEditorForm.setLocationRelativeTo(null);
htmlDescriptionsEditorForm.setVisible(true);
currentTask.setShortStory(htmlDescriptionsEditorForm.getShortStory());
currentTask.setStory(htmlDescriptionsEditorForm.getStory());
currentTask.setShortInstructions(htmlDescriptionsEditorForm.getShortInstructions());
currentTask.setInstructions(htmlDescriptionsEditorForm.getInstructions());
});
}
public void hideAndDisable() {
currentTask = null;
currentElementRef = null;
setVisible(false);
}
public void setCurrentTask(WizardTask newTask, DescriptiveElement currentElementRef,
Map<String, String> taskIdToTitle,
TaskCollectionEditorPanel taskCollectionEditor) {
// Save old task
if (this.currentTask != null) {
// Set new names in the current list
this.currentElementRef.setTitle(titleField.getText());
this.currentTask.setTitle(titleField.getText());
this.currentTask.setDifficulty((String)difficultyBox.getSelectedItem());
this.currentTask.setLength((String) lengthBox.getSelectedItem());
this.currentTask.setTags(tags.getText());
this.currentTask.setRegExIncludeData(regexInclude.getText());
this.currentTask.setRegExExcludeData(regexExclude.getText());
// We work directly on input/result data, no need to set it back!
// We work directly on sources and solutions data, no need to set it back!
// Update references in task collection editor
taskIdToTitle.put(currentElementRef.getId(), currentElementRef.getTitle());
taskCollectionEditor.updateGraphTitles(taskIdToTitle);
} else {
setVisible(true);
}
// Load new task
titleField.setText(newTask.getTitle());
difficultyBox.setSelectedItem(newTask.getDifficulty());
lengthBox.setSelectedItem(newTask.getLength());
tags.setText(newTask.getTags());
regexInclude.setText(newTask.getRegExIncludeData());
regexExclude.setText(newTask.getRegExExcludeData());
// Only update the outer list for input result pairs
DefaultListModel<MappedElement> model = (DefaultListModel<MappedElement>) inputResultPanel.getList().getModel();
model.removeAllElements();
for (String name : newTask.getInputResultFileNames()) {
model.addElement(new MappedElement(name, name));
}
// We get the sources and solutions directly!
// Update current task
this.currentTask = newTask;
this.currentElementRef = currentElementRef;
}
}
|
onhout/fishbowl | lib/fishbowl/connection.rb | require 'nokogiri'
module Fishbowl
class Connection
include Singleton
def self.connect()
raise Fishbowl::Errors::MissingHost if Fishbowl.configuration.host.nil?
@host = Fishbowl.configuration.host
@port = Fishbowl.configuration.port.nil? ? 28192 : Fishbowl.configuration.port
@connection = TCPSocket.new @host, @port
self.instance
end
def self.login()
raise Fishbowl::Errors::ConnectionNotEstablished if @connection.nil?
raise Fishbowl::Errors::MissingUsername if Fishbowl.configuration.host.nil?
raise Fishbowl::Errors::MissingPassword if Fishbowl.configuration.host.nil?
@username = Fishbowl.configuration.username
@password = <PASSWORD>
code, _ = Fishbowl::Objects::BaseObject.new.send_request(login_request)
# Fishbowl::Errors.confirm_success_or_raise(code)
raise "Login failed" unless code.eql? "1000"
self.instance
end
def self.host
@host
end
def self.port
@port
end
def self.username
@username
end
def self.password
<PASSWORD>
end
def self.send(request, expected_response = 'FbiMsgsRs')
puts 'opening connection...' if Fishbowl.configuration.debug.eql? true
puts request if Fishbowl.configuration.debug.eql? true
puts 'waiting for response...' if Fishbowl.configuration.debug.eql? true
write(request)
get_response(expected_response)
end
def self.close
@connection.close
@connection = nil
end
private
def self.login_request
Nokogiri::XML::Builder.new do |xml|
xml.request {
xml.LoginRq {
xml.IAID Fishbowl.configuration.app_id
xml.IAName Fishbowl.configuration.app_name
xml.IADescription Fishbowl.configuration.app_description
xml.UserName Fishbowl.configuration.username
xml.UserPassword <PASSWORD>_password
}
}
end
end
def self.encoded_password
<PASSWORD>.<PASSWORD>(@password)
end
def self.write(request)
body = request.to_xml
size = [body.size].pack("L>")
@connection.write(size)
@connection.write(body)
end
def self.get_response(expectation)
puts "reading response" if Fishbowl.configuration.debug.eql? true
length = @connection.read(4).unpack('L>').join('').to_i
response = Nokogiri::XML.parse(@connection.read(length))
puts response if Fishbowl.configuration.debug.eql? true
status_code = response.xpath("/FbiXml/FbiMsgsRs").attr("statusCode").value
[status_code, response]
end
end
end |
ujjwalgulecha/Coding | Project Euler/euler46.cpp | <reponame>ujjwalgulecha/Coding
<<<<<<< HEAD
#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
int isprime(int x);
void gen(int *a);
int main()
{
int a[100000];
gen(a);
int i,j,x,flag=0;
float n;
for(x=1;;x+=2)
{
for(i=0;a[i]<x;i++)
{
n=sqrt((x-a[i])/2);
if(n==(int)n)
{
flag=0;
break;
}
else flag=1;
}
if (flag==1)
{
if(!isprime(x))
{cout<<x<<endl;exit(0);}
}
}
return 0;
}
void gen(int *a)
{
int i,j,k=2,flag;
a[0]=2;
a[1]=3;
for(i=4;i<100000;i++)
{
for(j=2;j<=sqrt(i);j++)
{
if(i%j==0)
{flag=1;break;}
else {flag=0;continue;}
}
if (flag==0){a[k]=i;k++;}
}
}
int isprime(int x)
{
int i,j,flag,count=0;
for(i=2;i<=x/2;i++){
if(x%i==0){
count++;
break;
}
}
if(count==0 && x!= 1)
return 1;
else return 0;
}
=======
#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
int isprime(int x);
void gen(int *a);
int main()
{
int a[100000];
gen(a);
int i,j,x,flag=0;
float n;
for(x=1;;x+=2)
{
for(i=0;a[i]<x;i++)
{
n=sqrt((x-a[i])/2);
if(n==(int)n)
{
flag=0;
break;
}
else flag=1;
}
if (flag==1)
{
if(!isprime(x))
{cout<<x<<endl;exit(0);}
}
}
return 0;
}
void gen(int *a)
{
int i,j,k=2,flag;
a[0]=2;
a[1]=3;
for(i=4;i<100000;i++)
{
for(j=2;j<=sqrt(i);j++)
{
if(i%j==0)
{flag=1;break;}
else {flag=0;continue;}
}
if (flag==0){a[k]=i;k++;}
}
}
int isprime(int x)
{
int i,j,flag,count=0;
for(i=2;i<=x/2;i++){
if(x%i==0){
count++;
break;
}
}
if(count==0 && x!= 1)
return 1;
else return 0;
}
>>>>>>> efd4245fe427ffeefe49c72470b81a015d8dcf82
|
huamichaelchen/deeplearning4j | deeplearning4j-core/src/main/java/org/deeplearning4j/nn/conf/layers/SubsamplingLayer.java | package org.deeplearning4j.nn.conf.layers;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.deeplearning4j.nn.conf.distribution.Distribution;
import org.deeplearning4j.nn.weights.WeightInit;
/**
* @author <NAME>
*/
@Data @NoArgsConstructor
public class SubsamplingLayer extends Layer {
private static final long serialVersionUID = -7095644470333017030L;
protected poolingType poolingType;
protected int[] filterSize; // Same as filter size from the last conv layer
protected int[] stride; // Default is 2. Down-sample by a factor of 2
public enum poolingType {
MAX, AVG, SUM, NONE
}
private SubsamplingLayer(Builder builder) {
super(builder);
this.poolingType = builder.poolingType;
this.stride = builder.stride;
// this.kernelSize = builder.kernelSize;
}
@AllArgsConstructor
public static class Builder extends Layer.Builder {
private poolingType poolingType;
private int[] stride; // Default is 2. Down-sample by a factor of 2
// private int[] kernelSize; // Same as filter size from the last conv layer
@Override
public Builder activation(String activationFunction) {
throw new UnsupportedOperationException("SubsamplingLayer does not accept activation");
}
@Override
public Builder weightInit(WeightInit weightInit) {
throw new UnsupportedOperationException("SubsamplingLayer does not accept weight init");
}
@Override
public Builder dist(Distribution dist){
throw new UnsupportedOperationException("SubsamplingLayer does not accept weight init");
}
@Override
public Builder dropOut(double dropOut) {
throw new UnsupportedOperationException("SubsamplingLayer does not accept dropout");
}
@Override
@SuppressWarnings("unchecked")
public SubsamplingLayer build() {
return new SubsamplingLayer(this);
}
}
}
|
beetle2k/Metin2Client | source/EterLib/GrpColor.h | <gh_stars>10-100
#pragma once
class CGraphicColor
{
public:
CGraphicColor(const CGraphicColor& c_rSrcColor);
CGraphicColor(float r, float g, float b, float a);
CGraphicColor(DWORD color);
CGraphicColor();
~CGraphicColor();
void Clear();
void Set(float r, float g, float b, float a);
void Set(const CGraphicColor& c_rSrcColor);
void Set(DWORD color);
void Blend(float p, const CGraphicColor& c_rSrcColor, const CGraphicColor& c_rDstColor);
DWORD GetPackValue() const;
protected:
float m_r;
float m_g;
float m_b;
float m_a;
};
|
ishandutta2007/fingerprint.ninja | app/components/SubmitButton/index.js | <filename>app/components/SubmitButton/index.js
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import loadingSpinner from 'static/loading.svg';
const Button = styled.button`
font-family: 'Montserrat', sans-serif;
background-color: rgba(0, 0, 0, 0);
width: 150px;
height: 50px;
border: 2px solid var(--col-font);
border-radius: 5px;
cursor: ${props => (props.disabled ? 'not-allowed' : 'pointer')};
outline: none;
${props =>
!props.disabled &&
`
&:hover {
color: var(--col-bg);
border-color: var(--col-font);
background-color: #666;
}
`};
`;
const Spinner = styled.img`
margin-top: 5px;
`;
const SubmitButton = ({
onSubmit, text, loading, disabledProp,
}) => (
<Button onClick={onSubmit} disabled={disabledProp}>
{loading ? <Spinner alt="" src={loadingSpinner} /> : text}
</Button>
);
SubmitButton.propTypes = {
onSubmit: PropTypes.func.isRequired,
text: PropTypes.string.isRequired,
loading: PropTypes.bool,
disabledProp: PropTypes.bool,
};
SubmitButton.defaultProps = {
loading: false,
disabledProp: false,
};
export default SubmitButton;
|
dejbug/cathy | lib/Edit.h | #pragma once
#include "Common.h"
#include "Child.h"
#include "Defines.h"
BEGIN_NAMESPACE (lib)
BEGIN_NAMESPACE (gui)
class Edit : public Child
{
public:
bool Attach (HWND parent, UINT cid);
public:
bool AppendText (LPCSTR text);
};
END_NAMESPACE (gui)
END_NAMESPACE (lib)
|
UECIT/ecds-schema | src/main/java/uk/nhs/nhsia/datastandards/ecds/impl/ClinicalDiagnosisGroupREADTypeImpl.java | <reponame>UECIT/ecds-schema<gh_stars>0
/*
* XML Type: ClinicalDiagnosisGroupREAD_Type
* Namespace: http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns
* Java type: uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType
*
* Automatically generated - do not modify.
*/
package uk.nhs.nhsia.datastandards.ecds.impl;
/**
* An XML ClinicalDiagnosisGroupREAD_Type(@http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns).
*
* This is a complex type.
*/
public class ClinicalDiagnosisGroupREADTypeImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType
{
private static final long serialVersionUID = 1L;
public ClinicalDiagnosisGroupREADTypeImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName DIAGNOSISSCHEMEINUSE$0 =
new javax.xml.namespace.QName("http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns", "DiagnosisSchemeInUse");
private static final javax.xml.namespace.QName PRIMARYDIAGNOSISGROUPREAD$2 =
new javax.xml.namespace.QName("http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns", "PrimaryDiagnosisGroupREAD");
private static final javax.xml.namespace.QName SECONDARYDIAGNOSISGROUPREAD$4 =
new javax.xml.namespace.QName("http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns", "SecondaryDiagnosisGroupREAD");
/**
* Gets the "DiagnosisSchemeInUse" element
*/
public uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType.Enum getDiagnosisSchemeInUse()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(DIAGNOSISSCHEMEINUSE$0, 0);
if (target == null)
{
return null;
}
return (uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType.Enum)target.getEnumValue();
}
}
/**
* Gets (as xml) the "DiagnosisSchemeInUse" element
*/
public uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType xgetDiagnosisSchemeInUse()
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType target = null;
target = (uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType)get_store().find_element_user(DIAGNOSISSCHEMEINUSE$0, 0);
return target;
}
}
/**
* Sets the "DiagnosisSchemeInUse" element
*/
public void setDiagnosisSchemeInUse(uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType.Enum diagnosisSchemeInUse)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(DIAGNOSISSCHEMEINUSE$0, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(DIAGNOSISSCHEMEINUSE$0);
}
target.setEnumValue(diagnosisSchemeInUse);
}
}
/**
* Sets (as xml) the "DiagnosisSchemeInUse" element
*/
public void xsetDiagnosisSchemeInUse(uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType diagnosisSchemeInUse)
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType target = null;
target = (uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType)get_store().find_element_user(DIAGNOSISSCHEMEINUSE$0, 0);
if (target == null)
{
target = (uk.nhs.nhsia.datastandards.ecds.DiagnosisSchemeInUseType)get_store().add_element_user(DIAGNOSISSCHEMEINUSE$0);
}
target.set(diagnosisSchemeInUse);
}
}
/**
* Gets the "PrimaryDiagnosisGroupREAD" element
*/
public uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.PrimaryDiagnosisGroupREAD getPrimaryDiagnosisGroupREAD()
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.PrimaryDiagnosisGroupREAD target = null;
target = (uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.PrimaryDiagnosisGroupREAD)get_store().find_element_user(PRIMARYDIAGNOSISGROUPREAD$2, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "PrimaryDiagnosisGroupREAD" element
*/
public void setPrimaryDiagnosisGroupREAD(uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.PrimaryDiagnosisGroupREAD primaryDiagnosisGroupREAD)
{
generatedSetterHelperImpl(primaryDiagnosisGroupREAD, PRIMARYDIAGNOSISGROUPREAD$2, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "PrimaryDiagnosisGroupREAD" element
*/
public uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.PrimaryDiagnosisGroupREAD addNewPrimaryDiagnosisGroupREAD()
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.PrimaryDiagnosisGroupREAD target = null;
target = (uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.PrimaryDiagnosisGroupREAD)get_store().add_element_user(PRIMARYDIAGNOSISGROUPREAD$2);
return target;
}
}
/**
* Gets array of all "SecondaryDiagnosisGroupREAD" elements
*/
public uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD[] getSecondaryDiagnosisGroupREADArray()
{
synchronized (monitor())
{
check_orphaned();
java.util.List targetList = new java.util.ArrayList();
get_store().find_all_element_users(SECONDARYDIAGNOSISGROUPREAD$4, targetList);
uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD[] result = new uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD[targetList.size()];
targetList.toArray(result);
return result;
}
}
/**
* Gets ith "SecondaryDiagnosisGroupREAD" element
*/
public uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD getSecondaryDiagnosisGroupREADArray(int i)
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD target = null;
target = (uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD)get_store().find_element_user(SECONDARYDIAGNOSISGROUPREAD$4, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
return target;
}
}
/**
* Returns number of "SecondaryDiagnosisGroupREAD" element
*/
public int sizeOfSecondaryDiagnosisGroupREADArray()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(SECONDARYDIAGNOSISGROUPREAD$4);
}
}
/**
* Sets array of all "SecondaryDiagnosisGroupREAD" element WARNING: This method is not atomicaly synchronized.
*/
public void setSecondaryDiagnosisGroupREADArray(uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD[] secondaryDiagnosisGroupREADArray)
{
check_orphaned();
arraySetterHelper(secondaryDiagnosisGroupREADArray, SECONDARYDIAGNOSISGROUPREAD$4);
}
/**
* Sets ith "SecondaryDiagnosisGroupREAD" element
*/
public void setSecondaryDiagnosisGroupREADArray(int i, uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD secondaryDiagnosisGroupREAD)
{
generatedSetterHelperImpl(secondaryDiagnosisGroupREAD, SECONDARYDIAGNOSISGROUPREAD$4, i, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);
}
/**
* Inserts and returns a new empty value (as xml) as the ith "SecondaryDiagnosisGroupREAD" element
*/
public uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD insertNewSecondaryDiagnosisGroupREAD(int i)
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD target = null;
target = (uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD)get_store().insert_element_user(SECONDARYDIAGNOSISGROUPREAD$4, i);
return target;
}
}
/**
* Appends and returns a new empty value (as xml) as the last "SecondaryDiagnosisGroupREAD" element
*/
public uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD addNewSecondaryDiagnosisGroupREAD()
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD target = null;
target = (uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD)get_store().add_element_user(SECONDARYDIAGNOSISGROUPREAD$4);
return target;
}
}
/**
* Removes the ith "SecondaryDiagnosisGroupREAD" element
*/
public void removeSecondaryDiagnosisGroupREAD(int i)
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(SECONDARYDIAGNOSISGROUPREAD$4, i);
}
}
/**
* An XML PrimaryDiagnosisGroupREAD(@http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns).
*
* This is a complex type.
*/
public static class PrimaryDiagnosisGroupREADImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.PrimaryDiagnosisGroupREAD
{
private static final long serialVersionUID = 1L;
public PrimaryDiagnosisGroupREADImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName PRIMARYDIAGNOSISREAD$0 =
new javax.xml.namespace.QName("http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns", "PrimaryDiagnosis_READ");
/**
* Gets the "PrimaryDiagnosis_READ" element
*/
public java.lang.String getPrimaryDiagnosisREAD()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(PRIMARYDIAGNOSISREAD$0, 0);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "PrimaryDiagnosis_READ" element
*/
public uk.nhs.nhsia.datastandards.ecds.PrimaryDiagnosisREADType xgetPrimaryDiagnosisREAD()
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.PrimaryDiagnosisREADType target = null;
target = (uk.nhs.nhsia.datastandards.ecds.PrimaryDiagnosisREADType)get_store().find_element_user(PRIMARYDIAGNOSISREAD$0, 0);
return target;
}
}
/**
* Sets the "PrimaryDiagnosis_READ" element
*/
public void setPrimaryDiagnosisREAD(java.lang.String primaryDiagnosisREAD)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(PRIMARYDIAGNOSISREAD$0, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(PRIMARYDIAGNOSISREAD$0);
}
target.setStringValue(primaryDiagnosisREAD);
}
}
/**
* Sets (as xml) the "PrimaryDiagnosis_READ" element
*/
public void xsetPrimaryDiagnosisREAD(uk.nhs.nhsia.datastandards.ecds.PrimaryDiagnosisREADType primaryDiagnosisREAD)
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.PrimaryDiagnosisREADType target = null;
target = (uk.nhs.nhsia.datastandards.ecds.PrimaryDiagnosisREADType)get_store().find_element_user(PRIMARYDIAGNOSISREAD$0, 0);
if (target == null)
{
target = (uk.nhs.nhsia.datastandards.ecds.PrimaryDiagnosisREADType)get_store().add_element_user(PRIMARYDIAGNOSISREAD$0);
}
target.set(primaryDiagnosisREAD);
}
}
}
/**
* An XML SecondaryDiagnosisGroupREAD(@http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns).
*
* This is a complex type.
*/
public static class SecondaryDiagnosisGroupREADImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements uk.nhs.nhsia.datastandards.ecds.ClinicalDiagnosisGroupREADType.SecondaryDiagnosisGroupREAD
{
private static final long serialVersionUID = 1L;
public SecondaryDiagnosisGroupREADImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName SECONDARYDIAGNOSISREAD$0 =
new javax.xml.namespace.QName("http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns", "SecondaryDiagnosis_READ");
/**
* Gets the "SecondaryDiagnosis_READ" element
*/
public java.lang.String getSecondaryDiagnosisREAD()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(SECONDARYDIAGNOSISREAD$0, 0);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "SecondaryDiagnosis_READ" element
*/
public uk.nhs.nhsia.datastandards.ecds.SecondaryDiagnosisREADType xgetSecondaryDiagnosisREAD()
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.SecondaryDiagnosisREADType target = null;
target = (uk.nhs.nhsia.datastandards.ecds.SecondaryDiagnosisREADType)get_store().find_element_user(SECONDARYDIAGNOSISREAD$0, 0);
return target;
}
}
/**
* Sets the "SecondaryDiagnosis_READ" element
*/
public void setSecondaryDiagnosisREAD(java.lang.String secondaryDiagnosisREAD)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(SECONDARYDIAGNOSISREAD$0, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(SECONDARYDIAGNOSISREAD$0);
}
target.setStringValue(secondaryDiagnosisREAD);
}
}
/**
* Sets (as xml) the "SecondaryDiagnosis_READ" element
*/
public void xsetSecondaryDiagnosisREAD(uk.nhs.nhsia.datastandards.ecds.SecondaryDiagnosisREADType secondaryDiagnosisREAD)
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.nhsia.datastandards.ecds.SecondaryDiagnosisREADType target = null;
target = (uk.nhs.nhsia.datastandards.ecds.SecondaryDiagnosisREADType)get_store().find_element_user(SECONDARYDIAGNOSISREAD$0, 0);
if (target == null)
{
target = (uk.nhs.nhsia.datastandards.ecds.SecondaryDiagnosisREADType)get_store().add_element_user(SECONDARYDIAGNOSISREAD$0);
}
target.set(secondaryDiagnosisREAD);
}
}
}
}
|
lmayZhou/lms-cloud | lms-cloud-starters/lms-cloud-starter-canal/src/main/java/com/lmaye/cloud/starter/canal/patterns/FloatType.java | package com.lmaye.cloud.starter.canal.patterns;
import org.springframework.stereotype.Component;
/**
* -- Float Type
*
* @author <NAME>
* @date 2021/4/2 10:14
* @email <EMAIL>
*/
@Component
public class FloatType implements IType {
/**
* 获取类型名称
*
* @return String
*/
@Override
public String getTypeName() {
return Float.class.getTypeName();
}
/**
* 类型转换
*
* @param value 值
* @return Float
*/
@Override
public Float convertType(String value) {
return Float.parseFloat(value);
}
}
|
eerimoq/async | tst/test_core_tcp_server.c | #include "nala.h"
#include "async.h"
#include "runtime_test.h"
TEST(call_all_functions)
{
struct async_t async;
struct async_tcp_server_t server;
struct async_tcp_server_client_t client;
async_init(&async);
runtime_test_set_async_mock();
async_set_runtime(&async, runtime_test_create());
runtime_test_tcp_server_init_mock_once("127.0.0.1", 4444);
async_tcp_server_init(&server, "127.0.0.1", 4444, NULL, NULL, NULL, &async);
runtime_test_tcp_server_add_client_mock_once();
async_tcp_server_add_client(&server, &client);
runtime_test_tcp_server_start_mock_once(1);
ASSERT_EQ(async_tcp_server_start(&server), 1);
runtime_test_tcp_server_client_write_mock_once(5);
async_tcp_server_client_write(&client, NULL, 5);
runtime_test_tcp_server_client_read_mock_once(5, 6);
ASSERT_EQ(async_tcp_server_client_read(&client, NULL, 5), 6u);
runtime_test_tcp_server_client_disconnect_mock_once();
async_tcp_server_client_disconnect(&client);
runtime_test_tcp_server_stop_mock_once();
async_tcp_server_stop(&server);
}
TEST(call_default_callbacks)
{
struct async_t async;
struct async_tcp_server_t server;
struct async_tcp_server_client_t client;
int handle;
struct nala_runtime_test_tcp_server_init_params_t *params_p;
async_init(&async);
runtime_test_set_async_mock();
async_set_runtime(&async, runtime_test_create());
handle = runtime_test_tcp_server_init_mock_once("127.0.0.2", 4445);
async_tcp_server_init(&server, "127.0.0.2", 4445, NULL, NULL, NULL, &async);
runtime_test_tcp_server_add_client_mock_once();
async_tcp_server_add_client(&server, &client);
runtime_test_tcp_server_start_mock_once(0);
ASSERT_EQ(async_tcp_server_start(&server), 0);
params_p = runtime_test_tcp_server_init_mock_get_params_in(handle);
/* Call the callbacks. */
params_p->on_connected(&client);
runtime_test_tcp_server_client_read_mock_once(32, 30);
runtime_test_tcp_server_client_read_mock_once(32, 0);
params_p->on_input(&client);
params_p->on_disconnected(&client);
}
|
ParisMaroulakosSeferiadis/meteorological-stations-network | greedy algorithms & graph problems/A2.py | <reponame>ParisMaroulakosSeferiadis/meteorological-stations-network<filename>greedy algorithms & graph problems/A2.py
import networkx as nx
from matplotlib import pyplot as plt
import hellas_cities
G1= hellas_cities.get_cities_distances_80_graph()
nx.draw(G1, with_labels=True)
plt.show()
C1 = nx.connected_components(G1)
print(len(list(C1)))
|
AnzerWall/inHere | java/inHere-java/src/main/java/com/inHere/entity/User.java | package com.inHere.entity;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* 用户实体
*/
public class User {
private String userId;
private String passwd;
private String saltKey;
private String userName;
private String headImg;
private String contactWay;
private Integer sex;
private String area;
private Integer schoolId;
private Integer roleId;
private Date createTime;
private Date updateTime;
private Integer is_admin;
private Integer available;
// school对象
private School school;
// 角色集合
private List<Roles> roles;
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId == null ? null : userId.trim();
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd == null ? null : passwd.trim();
}
public String getSaltKey() {
return saltKey;
}
public void setSaltKey(String saltKey) {
this.saltKey = saltKey == null ? null : saltKey.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getHeadImg() throws IOException {
return headImg == null ? null : new String(headImg.getBytes("ISO-8859-1"), "UTF-8");
}
public void setHeadImg(String headImg) {
this.headImg = headImg == null ? null : headImg.trim();
}
public String getContactWay() throws IOException {
return contactWay == null ? null : new String(contactWay.getBytes("ISO-8859-1"), "UTF-8");
}
public void setContactWay(String contactWay) {
this.contactWay = contactWay == null ? null : contactWay.trim();
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area == null ? null : area.trim();
}
public Integer getSchoolId() {
return schoolId;
}
public void setSchoolId(Integer schoolId) {
this.schoolId = schoolId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public List<Roles> getRoles() {
return roles;
}
public void setRoles(List<Roles> roles) {
this.roles = roles;
}
public Integer getIs_admin() {
return is_admin;
}
public void setIs_admin(Integer is_admin) {
this.is_admin = is_admin;
}
public Integer getAvailable() {
return available;
}
public void setAvailable(Integer available) {
this.available = available;
}
@Override
public String toString() {
return "User{" +
"userId='" + userId + '\'' +
", passwd='" + <PASSWORD> + '\'' +
", saltKey='" + saltKey + '\'' +
", userName='" + userName + '\'' +
", headImg='" + headImg + '\'' +
", contactWay='" + contactWay + '\'' +
", sex=" + sex +
", area='" + area + '\'' +
", schoolId=" + schoolId +
", roleId=" + roleId +
", createTime=" + createTime +
", updateTime=" + updateTime +
", school=" + school +
", roles=" + roles +
'}';
}
}
|
d-tree-org/opensrp-client-chw | opensrp-chw/src/test/java/org/smartregister/chw/fragment/FamilyProfileDueFragmentTest.java | package org.smartregister.chw.fragment;
import android.view.View;
import androidx.fragment.app.FragmentActivity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.reflect.Whitebox;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.smartregister.chw.application.ChwApplication;
import org.smartregister.family.adapter.FamilyRecyclerViewCustomAdapter;
@RunWith(RobolectricTestRunner.class)
@Config(application = ChwApplication.class, sdk = 22)
public class FamilyProfileDueFragmentTest {
@Mock
private FamilyRecyclerViewCustomAdapter clientAdapter;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testonEmptyRegisterCountIsCalled() {
FamilyProfileDueFragment spyFragment = Mockito.spy(FamilyProfileDueFragment.class);
FragmentActivity activity = Mockito.spy(FragmentActivity.class);
Mockito.when(spyFragment.getActivity()).thenReturn(activity);
View emptyView = Mockito.mock(View.class);
Whitebox.setInternalState(spyFragment, "emptyView", emptyView);
Whitebox.setInternalState(spyFragment, "clientAdapter", clientAdapter);
spyFragment.countExecute();
Mockito.verify(emptyView).setVisibility(Mockito.anyInt());
}
@Test
public void testonEmptyRegisterCountHidesViewHideView() {
FamilyProfileDueFragment spyFragment = Mockito.spy(FamilyProfileDueFragment.class);
FragmentActivity activity = Mockito.spy(FragmentActivity.class);
Mockito.when(spyFragment.getActivity()).thenReturn(activity);
View emptyView = Mockito.mock(View.class);
Whitebox.setInternalState(spyFragment, "emptyView", emptyView);
spyFragment.onEmptyRegisterCount(false);
Mockito.verify(emptyView).setVisibility(View.GONE);
}
@Test
public void testonEmptyRegisterCountHidesViewShowsView() {
FamilyProfileDueFragment spyFragment = Mockito.spy(FamilyProfileDueFragment.class);
FragmentActivity activity = Mockito.spy(FragmentActivity.class);
Mockito.when(spyFragment.getActivity()).thenReturn(activity);
View emptyView = Mockito.mock(View.class);
Whitebox.setInternalState(spyFragment, "emptyView", emptyView);
spyFragment.onEmptyRegisterCount(true);
Mockito.verify(emptyView).setVisibility(View.VISIBLE);
}
}
|
shengjian-tech/opennft | blockchainplatform-nft/blockchainplatform-nft-service/src/main/java/net/shengjian/makerone/service/INFTComputeOrderService.java | <reponame>shengjian-tech/opennft
package net.shengjian.makerone.service;
import net.shengjian.makerone.dto.ComputeOrderDTO;
import net.shengjian.rpc.annotation.RpcServiceAnnotation;
import java.math.BigDecimal;
/**
* @descriptions: nft订单价格计算接口
* @author: YSK
* @date: 2021/12/24 16:11
* @version: 1.0
*/
@RpcServiceAnnotation
public interface INFTComputeOrderService {
/**
* 计算订单金额
* @param price 商品单价
* @param num 购买数量
* @param royalties 合集版税
* @return 计算后的金额
* @throws Exception 计算错误抛出的异常
*/
ComputeOrderDTO computeOrder(BigDecimal price, Integer num, BigDecimal royalties,BigDecimal gasUsed) throws Exception;
}
|
mbanasiewicz/mobile-sdk-ios | sdk/sourcefiles/Categories/NSPointerArray+ANCategory.h | <filename>sdk/sourcefiles/Categories/NSPointerArray+ANCategory.h
/* Copyright 2021 Xandr INC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSPointerArray (ANCategory)
/**
* Adds pointer to the given object to the array.
*
* @param object Object whose pointer needs to be added to the array.
* If a pointer to this object already exists in the array, you get a duplicate.
* Call containsObject first if you don't want that to happen.
*/
- (void)addObject:(id)object;
/**
* Checks if pointer to the given object is present in the array.
*
* @param object Object whose pointer's presence needs to be checked.
*
* @return YES if pointer to the given object is already present in the array; NO otherwise.
*/
- (BOOL)containsObject:(id)object;
/**
* Removes a pointer that matches the pointer to the passed in object.
*
* @param object An object that's currently in the array. No ill effects if the object is not in the array.
*/
- (void)removeObject:(id)object;
- (id)objectAtIndex:(NSUInteger)index;
@end
NS_ASSUME_NONNULL_END
|
agenihorganization/opensplice | src/abstraction/os/posix/include/os_os_cond.h | /*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to TO_YEAR PrismTech
* Limited, its affiliated companies and licensors. 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 OS_POSIX_COND_H
#define OS_POSIX_COND_H
#if defined (__cplusplus)
extern "C" {
#endif
#include <unistd.h>
#include <pthread.h>
#ifdef OSPL_STRICT_MEM
typedef struct os_os_cond {
uint64_t signature; /* Used to identify initialized cond when memory is
freed - keep this first in the structure so its
so its address is the same as the os_cond */
pthread_cond_t cond;
#if defined(_POSIX_CLOCK_SELECTION)
clockid_t clockId;
#endif
} os_os_cond;
#else
typedef pthread_cond_t os_os_cond;
#endif
#if defined (__cplusplus)
}
#endif
#endif /* OS_POSIX_COND_H */
|
dante7qx/microservice-tornado | tornado-sysmgr-api/src/main/java/com/tornado/sysmgr/api/dto/resp/IpRuleRespDTO.java | <filename>tornado-sysmgr-api/src/main/java/com/tornado/sysmgr/api/dto/resp/IpRuleRespDTO.java
package com.tornado.sysmgr.api.dto.resp;
import lombok.Data;
/**
* IP规则返回参数
*
* @author dante
*
*/
@Data
public class IpRuleRespDTO {
private Long id;
private String ip;
private String remark;
private Boolean active;
private String updateUserName;
private String updateDate;
}
|
imranpopz/android_bootable_recovery-1 | libblkid/src/superblocks/silicon_raid.c | <filename>libblkid/src/superblocks/silicon_raid.c
/*
* Copyright (C) 2008 <NAME> <<EMAIL>>
* Copyright (C) 2005 <NAME> <<EMAIL>>
*
* Inspired by libvolume_id by
* <NAME> <<EMAIL>>
*
* This file may be redistributed under the terms of the
* GNU Lesser General Public License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <stdint.h>
#include <stddef.h>
#include "superblocks.h"
struct silicon_metadata {
uint8_t unknown0[0x2E];
uint8_t ascii_version[0x36 - 0x2E];
int8_t diskname[0x56 - 0x36];
int8_t unknown1[0x60 - 0x56];
uint32_t magic;
int8_t unknown1a[0x6C - 0x64];
uint32_t array_sectors_low;
uint32_t array_sectors_high;
int8_t unknown2[0x78 - 0x74];
uint32_t thisdisk_sectors;
int8_t unknown3[0x100 - 0x7C];
int8_t unknown4[0x104 - 0x100];
uint16_t product_id;
uint16_t vendor_id;
uint16_t minor_ver;
uint16_t major_ver;
uint8_t seconds;
uint8_t minutes;
uint8_t hour;
uint8_t day;
uint8_t month;
uint8_t year;
uint16_t raid0_stride;
int8_t unknown6[0x116 - 0x114];
uint8_t disk_number;
uint8_t type; /* SILICON_TYPE_* */
int8_t drives_per_striped_set;
int8_t striped_set_number;
int8_t drives_per_mirrored_set;
int8_t mirrored_set_number;
uint32_t rebuild_ptr_low;
uint32_t rebuild_ptr_high;
uint32_t incarnation_no;
uint8_t member_status;
uint8_t mirrored_set_state; /* SILICON_MIRROR_* */
uint8_t reported_device_location;
uint8_t idechannel;
uint8_t auto_rebuild;
uint8_t unknown8;
uint8_t text_type[0x13E - 0x12E];
uint16_t checksum1;
int8_t assumed_zeros[0x1FE - 0x140];
uint16_t checksum2;
} __attribute__((packed));
#define SILICON_MAGIC 0x2F000000
static uint16_t silraid_checksum(struct silicon_metadata *sil)
{
int sum = 0;
unsigned short count = offsetof(struct silicon_metadata, checksum1) / 2;
uint16_t *p = (uint16_t *) sil;
while (count--) {
uint16_t x = *p++;
sum += le16_to_cpu(x);
}
return (-sum & 0xFFFF);
}
static int probe_silraid(blkid_probe pr,
const struct blkid_idmag *mag __attribute__((__unused__)))
{
uint64_t off;
struct silicon_metadata *sil;
if (pr->size < 0x10000)
return 1;
if (!S_ISREG(pr->mode) && !blkid_probe_is_wholedisk(pr))
return 1;
off = ((pr->size / 0x200) - 1) * 0x200;
sil = (struct silicon_metadata *)
blkid_probe_get_buffer(pr, off,
sizeof(struct silicon_metadata));
if (!sil)
return errno ? -errno : 1;
if (le32_to_cpu(sil->magic) != SILICON_MAGIC)
return 1;
if (sil->disk_number >= 8)
return 1;
if (!blkid_probe_verify_csum(pr, silraid_checksum(sil), le16_to_cpu(sil->checksum1)))
return 1;
if (blkid_probe_sprintf_version(pr, "%u.%u",
le16_to_cpu(sil->major_ver),
le16_to_cpu(sil->minor_ver)) != 0)
return 1;
if (blkid_probe_set_magic(pr,
off + offsetof(struct silicon_metadata, magic),
sizeof(sil->magic),
(unsigned char *) &sil->magic))
return 1;
return 0;
}
const struct blkid_idinfo silraid_idinfo = {
.name = "silicon_medley_raid_member",
.usage = BLKID_USAGE_RAID,
.probefunc = probe_silraid,
.magics = BLKID_NONE_MAGIC
};
|
yiliangz/mass | framework/core/src/main/java/org/mass/framework/core/page/Page.java | <filename>framework/core/src/main/java/org/mass/framework/core/page/Page.java
package org.mass.framework.core.page;
import java.util.List;
/**
* Created by Allen on 2015/4/27.
*/
public interface Page<T> {
public Page nextPage();
public Page prevPage();
public List<T> getContent();
public boolean isFirst();
public boolean hasNext();
public long getPage();
public long getSize();
public long getTotal();
public long getTotalPage();
public void calculatePage(long total);
}
|
kvaps/deckhouse | modules/040-control-plane-manager/hooks/audit_policy_basic_targets_generated.go | <reponame>kvaps/deckhouse<filename>modules/040-control-plane-manager/hooks/audit_policy_basic_targets_generated.go
// Code generated by "tools/audit_policy.go" DO NOT EDIT.
package hooks
var auditPolicyBasicNamespaces = []string{
"d8-ceph-csi",
"d8-cert-manager",
"d8-chrony",
"d8-cloud-instance-manager",
"d8-cloud-provider-aws",
"d8-cloud-provider-azure",
"d8-cloud-provider-gcp",
"d8-cloud-provider-openstack",
"d8-cloud-provider-vsphere",
"d8-cloud-provider-yandex",
"d8-cni-cilium",
"d8-cni-flannel",
"d8-cni-simple-bridge",
"d8-descheduler",
"d8-flant-integration",
"d8-ingress-nginx",
"d8-istio",
"d8-keepalived",
"d8-linstor",
"d8-local-path-provisioner",
"d8-log-shipper",
"d8-metallb",
"d8-monitoring",
"d8-network-gateway",
"d8-okmeter",
"d8-openvpn",
"d8-operator-prometheus",
"d8-pod-reloader",
"d8-snapshot-controller",
"d8-system",
"d8-upmeter",
"d8-user-authn",
"d8-user-authz",
"kube-system",
}
var auditPolicyBasicServiceAccounts = []string{
"agent",
"alliance-ingressgateway",
"alliance-metadata-exporter",
"annotations-converter",
"cainjector",
"cert-exporter",
"cert-manager",
"cloud-controller-manager",
"cluster-autoscaler",
"cni-flannel",
"cni-simple-bridge",
"control-plane-proxy",
"controller",
"d8-control-plane-manager",
"d8-kube-dns",
"d8-kube-proxy",
"d8-vertical-pod-autoscaler-admission-controller",
"d8-vertical-pod-autoscaler-recommender",
"d8-vertical-pod-autoscaler-updater",
"dashboard",
"deckhouse",
"descheduler",
"dex",
"ebpf-exporter",
"events-exporter",
"extended-monitoring-exporter",
"grafana",
"image-availability-exporter",
"ingress-nginx",
"kiali",
"kube-state-metrics",
"legacy-cert-manager",
"legacy-webhook",
"linstor-controller",
"linstor-ha-controller",
"linstor-node",
"linstor-pools-importer",
"linstor-scheduler",
"local-path-provisioner",
"log-shipper",
"machine-controller-manager",
"monitoring-ping",
"multicluster-api-proxy",
"network-policy-engine",
"node-exporter",
"node-local-dns",
"node-termination-handler",
"okmeter",
"openvpn",
"operator",
"operator-prometheus",
"piraeus-operator",
"pod-reloader",
"pricing",
"prometheus",
"relay",
"smoke-mini",
"snapshot-controller",
"speaker",
"terraform-auto-converger",
"terraform-state-exporter",
"trickster",
"ui",
"upmeter",
"upmeter-agent",
"webhook",
"webhook-handler",
}
|
mliceaga/letmework4U-frontend2 | src/app/main/documentation/material-ui-components/components/hidden/BreakpointDown.js | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Hidden from '@material-ui/core/Hidden';
import withWidth from '@material-ui/core/withWidth';
import Typography from '@material-ui/core/Typography';
import compose from 'app/main/documentation/material-ui-components/compose';
const styles = theme => ({
root: {
flexGrow: 1,
},
container: {
display: 'flex',
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
flex: '1 0 auto',
margin: theme.spacing(1),
},
});
function BreakpointDown(props) {
const { classes } = props;
return (
<div className={classes.root}>
<Typography variant="subtitle1">Current width: {props.width}</Typography>
<div className={classes.container}>
<Hidden xsDown>
<Paper className={classes.paper}>xsDown</Paper>
</Hidden>
<Hidden smDown>
<Paper className={classes.paper}>smDown</Paper>
</Hidden>
<Hidden mdDown>
<Paper className={classes.paper}>mdDown</Paper>
</Hidden>
<Hidden lgDown>
<Paper className={classes.paper}>lgDown</Paper>
</Hidden>
<Hidden xlDown>
<Paper className={classes.paper}>xlDown</Paper>
</Hidden>
</div>
</div>
);
}
BreakpointDown.propTypes = {
classes: PropTypes.object.isRequired,
width: PropTypes.string.isRequired,
};
export default compose(
withStyles(styles),
withWidth(),
)(BreakpointDown);
|
ankurshukla1993/IOT-test | coeey/com/google/android/gms/internal/zzaun.java | package com.google.android.gms.internal;
import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Looper;
import android.support.annotation.Nullable;
import com.google.android.gms.auth.api.Auth.AuthCredentialsOptions;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.internal.zzab;
import com.google.android.gms.common.internal.zzr;
public final class zzaun extends zzab<zzaus> {
@Nullable
private final AuthCredentialsOptions zzedi;
public zzaun(Context context, Looper looper, zzr com_google_android_gms_common_internal_zzr, AuthCredentialsOptions authCredentialsOptions, ConnectionCallbacks connectionCallbacks, OnConnectionFailedListener onConnectionFailedListener) {
super(context, looper, 68, com_google_android_gms_common_internal_zzr, connectionCallbacks, onConnectionFailedListener);
this.zzedi = authCredentialsOptions;
}
protected final Bundle zzaae() {
return this.zzedi == null ? new Bundle() : this.zzedi.toBundle();
}
final AuthCredentialsOptions zzaal() {
return this.zzedi;
}
protected final /* synthetic */ IInterface zzd(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface queryLocalInterface = iBinder.queryLocalInterface("com.google.android.gms.auth.api.credentials.internal.ICredentialsService");
return queryLocalInterface instanceof zzaus ? (zzaus) queryLocalInterface : new zzaut(iBinder);
}
protected final String zzhf() {
return "com.google.android.gms.auth.api.credentials.service.START";
}
protected final String zzhg() {
return "com.google.android.gms.auth.api.credentials.internal.ICredentialsService";
}
}
|
Toromino/chromiumos-platform2 | power_manager/powerd/policy/charge_controller.cc | // Copyright 2019 The Chromium OS 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 "power_manager/powerd/policy/charge_controller.h"
#include <algorithm>
#include <cmath>
#include <base/check.h>
#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
#include <base/strings/string_util.h>
#include <base/strings/stringprintf.h>
#include "power_manager/common/battery_percentage_converter.h"
#include "power_manager/powerd/system/charge_controller_helper_interface.h"
namespace power_manager {
namespace policy {
namespace {
std::string GetWeekDayDebugString(
PowerManagementPolicy::WeekDay proto_week_day) {
switch (proto_week_day) {
case PowerManagementPolicy::MONDAY:
return "monday";
case PowerManagementPolicy::TUESDAY:
return "tuesday";
case PowerManagementPolicy::WEDNESDAY:
return "wednesday";
case PowerManagementPolicy::THURSDAY:
return "thursday";
case PowerManagementPolicy::FRIDAY:
return "friday";
case PowerManagementPolicy::SATURDAY:
return "saturday";
case PowerManagementPolicy::SUNDAY:
return "sunday";
}
return base::StringPrintf("invalid (%d)", proto_week_day);
}
std::string GetBatteryChargeModeDebugString(
PowerManagementPolicy::BatteryChargeMode::Mode battery_charge_mode) {
switch (battery_charge_mode) {
case PowerManagementPolicy::BatteryChargeMode::STANDARD:
return "standard";
case PowerManagementPolicy::BatteryChargeMode::EXPRESS_CHARGE:
return "express_charge";
case PowerManagementPolicy::BatteryChargeMode::PRIMARILY_AC_USE:
return "primarily_ac_use";
case PowerManagementPolicy::BatteryChargeMode::ADAPTIVE:
return "adaptive";
case PowerManagementPolicy::BatteryChargeMode::CUSTOM:
return "custom";
}
return base::StringPrintf("invalid (%d)", battery_charge_mode);
}
std::string GetPeakShiftDayConfigDebugString(
const PowerManagementPolicy::PeakShiftDayConfig& day_config) {
return base::StringPrintf(
"{day=%s time=%02d:%02d %02d:%02d %02d:%02d}",
GetWeekDayDebugString(day_config.day()).c_str(),
day_config.start_time().hour(), day_config.start_time().minute(),
day_config.end_time().hour(), day_config.end_time().minute(),
day_config.charge_start_time().hour(),
day_config.charge_start_time().minute());
}
std::string GetAdvancedBatteryChargeModeDayConfigDebugString(
const PowerManagementPolicy::AdvancedBatteryChargeModeDayConfig&
day_config) {
return base::StringPrintf("{day=%s time=%02d:%02d %02d:%02d}",
GetWeekDayDebugString(day_config.day()).c_str(),
day_config.charge_start_time().hour(),
day_config.charge_start_time().minute(),
day_config.charge_end_time().hour(),
day_config.charge_end_time().minute());
}
std::string GetPowerPolicyDebugString(const PowerManagementPolicy& policy) {
std::string str;
if (policy.has_peak_shift_battery_percent_threshold()) {
str += "peak_shift_battery_percent_threshold=" +
base::NumberToString(policy.peak_shift_battery_percent_threshold()) +
" ";
}
if (policy.peak_shift_day_configs_size()) {
str += "peak_shift_day_configs=[";
str += GetPeakShiftDayConfigDebugString(policy.peak_shift_day_configs(0));
for (int i = 1; i < policy.peak_shift_day_configs_size(); i++) {
str += ", " +
GetPeakShiftDayConfigDebugString(policy.peak_shift_day_configs(i));
}
str += "] ";
}
if (policy.has_boot_on_ac()) {
str += "boot_on_ac=";
str += policy.boot_on_ac() ? "true " : "false ";
}
if (policy.has_usb_power_share()) {
str += "usb_power_share=";
str += policy.usb_power_share() ? "true " : "false ";
}
if (policy.advanced_battery_charge_mode_day_configs_size()) {
str += "advanced_battery_charge_mode_day_configs=[";
str += GetAdvancedBatteryChargeModeDayConfigDebugString(
policy.advanced_battery_charge_mode_day_configs(0));
for (int i = 1; i < policy.advanced_battery_charge_mode_day_configs_size();
i++) {
str += ", " + GetAdvancedBatteryChargeModeDayConfigDebugString(
policy.advanced_battery_charge_mode_day_configs(i));
}
str += "] ";
}
if (policy.has_battery_charge_mode()) {
if (policy.battery_charge_mode().has_mode()) {
str +=
"battery_charge_mode=" +
GetBatteryChargeModeDebugString(policy.battery_charge_mode().mode()) +
" ";
}
if (policy.battery_charge_mode().has_custom_charge_start()) {
str += base::StringPrintf(
"custom_charge_start=%d ",
policy.battery_charge_mode().custom_charge_start());
}
if (policy.battery_charge_mode().has_custom_charge_stop()) {
str +=
base::StringPrintf("custom_charge_stop=%d ",
policy.battery_charge_mode().custom_charge_stop());
}
}
base::TrimString(str, " ", &str);
return str;
}
} // namespace
constexpr int ChargeController::kCustomChargeModeStartMin = 50;
constexpr int ChargeController::kCustomChargeModeStartMax = 95;
constexpr int ChargeController::kCustomChargeModeEndMin = 55;
constexpr int ChargeController::kCustomChargeModeEndMax = 100;
constexpr int ChargeController::kCustomChargeModeThresholdsMinDiff = 5;
constexpr int ChargeController::kPeakShiftBatteryThresholdMin = 15;
constexpr int ChargeController::kPeakShiftBatteryThresholdMax = 100;
// static
void ChargeController::ClampCustomBatteryChargeThresholds(int* start,
int* end) {
DCHECK(start);
DCHECK(end);
*end = std::clamp(*end, kCustomChargeModeEndMin, kCustomChargeModeEndMax);
*start =
std::clamp(std::min(*start, *end - kCustomChargeModeThresholdsMinDiff),
kCustomChargeModeStartMin, kCustomChargeModeStartMax);
}
// static
int ChargeController::ClampPeakShiftBatteryThreshold(int threshold) {
return std::clamp(threshold, kPeakShiftBatteryThresholdMin,
kPeakShiftBatteryThresholdMax);
}
ChargeController::ChargeController() = default;
ChargeController::~ChargeController() = default;
void ChargeController::Init(
system::ChargeControllerHelperInterface* helper,
BatteryPercentageConverter* battery_percentage_converter) {
DCHECK(helper);
DCHECK(battery_percentage_converter);
helper_ = helper;
battery_percentage_converter_ = battery_percentage_converter;
}
void ChargeController::HandlePolicyChange(const PowerManagementPolicy& policy) {
if (IsPolicyEqualToCache(policy)) {
return;
}
LOG(INFO) << "Received updated power policies: "
<< GetPowerPolicyDebugString(policy);
if (ApplyPolicyChange(policy)) {
cached_policy_ = policy;
} else {
cached_policy_.reset();
}
}
bool ChargeController::ApplyPolicyChange(const PowerManagementPolicy& policy) {
DCHECK(helper_);
// Try to apply as many changes as possible.
bool success = ApplyPeakShiftChange(policy);
success &= ApplyBootOnAcChange(policy);
success &= ApplyUsbPowerShareChange(policy);
success &= ApplyAdvancedBatteryChargeModeChange(policy);
success &= ApplyBatteryChargeModeChange(policy);
return success;
}
bool ChargeController::ApplyPeakShiftChange(
const PowerManagementPolicy& policy) {
if (!policy.has_peak_shift_battery_percent_threshold() ||
policy.peak_shift_day_configs_size() == 0) {
return helper_->SetPeakShiftEnabled(false);
}
if (!helper_->SetPeakShiftEnabled(true)) {
return false;
}
int actual_battery_percent_threshold =
std::round(battery_percentage_converter_->ConvertDisplayToActual(
policy.peak_shift_battery_percent_threshold()));
actual_battery_percent_threshold =
ClampPeakShiftBatteryThreshold(actual_battery_percent_threshold);
if (!helper_->SetPeakShiftBatteryPercentThreshold(
actual_battery_percent_threshold)) {
return false;
}
for (const auto& day_config : policy.peak_shift_day_configs()) {
if (!SetPeakShiftDayConfig(day_config)) {
return false;
}
}
return true;
}
bool ChargeController::ApplyBootOnAcChange(
const PowerManagementPolicy& policy) {
// Disable if |boot_on_ac| is unset.
return helper_->SetBootOnAcEnabled(policy.boot_on_ac());
}
bool ChargeController::ApplyUsbPowerShareChange(
const PowerManagementPolicy& policy) {
// Disable if |usb_power_share| is unset.
return helper_->SetUsbPowerShareEnabled(policy.usb_power_share());
}
bool ChargeController::ApplyAdvancedBatteryChargeModeChange(
const PowerManagementPolicy& policy) {
if (policy.advanced_battery_charge_mode_day_configs_size() == 0) {
return helper_->SetAdvancedBatteryChargeModeEnabled(false);
}
if (!helper_->SetAdvancedBatteryChargeModeEnabled(true)) {
return false;
}
for (const auto& day_config :
policy.advanced_battery_charge_mode_day_configs()) {
if (!SetAdvancedBatteryChargeModeDayConfig(day_config)) {
return false;
}
}
return true;
}
bool ChargeController::ApplyBatteryChargeModeChange(
const PowerManagementPolicy& policy) {
// If AdvancedBatteryChargeMode is specified, it overrides BatteryChargeMode.
if (policy.advanced_battery_charge_mode_day_configs_size() != 0) {
return true;
}
// STANDARD charge mode if either |battery_charge_mode| or
// |battery_charge_mode().mode| is unset.
if (!helper_->SetBatteryChargeMode(policy.battery_charge_mode().mode())) {
return false;
}
if (policy.battery_charge_mode().mode() !=
PowerManagementPolicy::BatteryChargeMode::CUSTOM) {
return true;
}
if (!policy.battery_charge_mode().has_custom_charge_start() ||
!policy.battery_charge_mode().has_custom_charge_stop()) {
LOG(ERROR) << "Start charge or stop charge is unset for custom battery"
<< " charge mode";
return false;
}
int custom_charge_start =
std::round(battery_percentage_converter_->ConvertDisplayToActual(
policy.battery_charge_mode().custom_charge_start()));
int custom_charge_end =
std::round(battery_percentage_converter_->ConvertDisplayToActual(
policy.battery_charge_mode().custom_charge_stop()));
ClampCustomBatteryChargeThresholds(&custom_charge_start, &custom_charge_end);
return helper_->SetBatteryChargeCustomThresholds(custom_charge_start,
custom_charge_end);
}
bool ChargeController::SetPeakShiftDayConfig(
const PowerManagementPolicy::PeakShiftDayConfig& day_config) {
if (!day_config.has_day() || !day_config.has_start_time() ||
!day_config.start_time().has_hour() ||
!day_config.start_time().has_minute() || !day_config.has_end_time() ||
!day_config.end_time().has_hour() ||
!day_config.end_time().has_minute() ||
!day_config.has_charge_start_time() ||
!day_config.charge_start_time().has_hour() ||
!day_config.charge_start_time().has_minute()) {
LOG(WARNING) << "Invalid peak shift day config proto";
return false;
}
std::string day_config_str = base::StringPrintf(
"%02d:%02d %02d:%02d %02d:%02d", day_config.start_time().hour(),
day_config.start_time().minute(), day_config.end_time().hour(),
day_config.end_time().minute(), day_config.charge_start_time().hour(),
day_config.charge_start_time().minute());
return helper_->SetPeakShiftDayConfig(day_config.day(), day_config_str);
}
bool ChargeController::SetAdvancedBatteryChargeModeDayConfig(
const PowerManagementPolicy::AdvancedBatteryChargeModeDayConfig&
day_config) {
if (!day_config.has_day() || !day_config.has_charge_start_time() ||
!day_config.charge_start_time().has_hour() ||
!day_config.charge_start_time().has_minute() ||
!day_config.has_charge_end_time() ||
!day_config.charge_end_time().has_hour() ||
!day_config.charge_end_time().has_minute()) {
LOG(WARNING) << "Invalid advanced battery charge mode day config proto";
return false;
}
int start_time_minutes = day_config.charge_start_time().hour() * 60 +
day_config.charge_start_time().minute();
int end_time_minutes = day_config.charge_end_time().hour() * 60 +
day_config.charge_end_time().minute();
if (start_time_minutes > end_time_minutes) {
LOG(WARNING) << "Invalid advanced battery charge mode day config proto:"
<< " start time must be less or equal than end time";
return false;
}
// Policy uses charge end time, but EC driver uses charge duration.
int duration_minutes = end_time_minutes - start_time_minutes;
std::string day_config_str = base::StringPrintf(
"%02d:%02d %02d:%02d", day_config.charge_start_time().hour(),
day_config.charge_start_time().minute(), duration_minutes / 60,
duration_minutes % 60);
return helper_->SetAdvancedBatteryChargeModeDayConfig(day_config.day(),
day_config_str);
}
bool ChargeController::IsPolicyEqualToCache(
const PowerManagementPolicy& policy) const {
if (!cached_policy_.has_value()) {
return false;
}
if (policy.has_peak_shift_battery_percent_threshold() !=
cached_policy_->has_peak_shift_battery_percent_threshold() ||
policy.peak_shift_battery_percent_threshold() !=
cached_policy_->peak_shift_battery_percent_threshold()) {
return false;
}
if (policy.peak_shift_day_configs_size() !=
cached_policy_->peak_shift_day_configs_size()) {
return false;
}
for (int i = 0; i < policy.peak_shift_day_configs_size(); i++) {
if (policy.peak_shift_day_configs(i).SerializeAsString() !=
cached_policy_->peak_shift_day_configs(i).SerializeAsString()) {
return false;
}
}
if (policy.has_boot_on_ac() != cached_policy_->has_boot_on_ac() ||
policy.boot_on_ac() != cached_policy_->boot_on_ac()) {
return false;
}
if (policy.has_usb_power_share() != cached_policy_->has_usb_power_share() ||
policy.usb_power_share() != cached_policy_->usb_power_share()) {
return false;
}
if (policy.advanced_battery_charge_mode_day_configs_size() !=
cached_policy_->advanced_battery_charge_mode_day_configs_size()) {
return false;
}
for (int i = 0; i < policy.advanced_battery_charge_mode_day_configs_size();
i++) {
if (policy.advanced_battery_charge_mode_day_configs(i)
.SerializeAsString() !=
cached_policy_->advanced_battery_charge_mode_day_configs(i)
.SerializeAsString()) {
return false;
}
}
if (policy.battery_charge_mode().SerializeAsString() !=
cached_policy_->battery_charge_mode().SerializeAsString()) {
return false;
}
return true;
}
} // namespace policy
} // namespace power_manager
|
wqk317/mi8_kernel_source | mi8/drivers/staging/qcacld-3.0/core/dp/htt/htt_fw_stats.c | /*
* Copyright (c) 2012-2018 The Linux Foundation. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/**
* @file htt_fw_stats.c
* @brief Provide functions to process FW status retrieved from FW.
*/
#include <htc_api.h> /* HTC_PACKET */
#include <htt.h> /* HTT_T2H_MSG_TYPE, etc. */
#include <qdf_nbuf.h> /* qdf_nbuf_t */
#include <qdf_mem.h> /* qdf_mem_set */
#include <ol_fw_tx_dbg.h> /* ol_fw_tx_dbg_ppdu_base */
#include <ol_htt_rx_api.h>
#include <ol_txrx_htt_api.h> /* htt_tx_status */
#include <htt_internal.h>
#include <wlan_defs.h>
#define ROUND_UP_TO_4(val) (((val) + 3) & ~0x3)
#ifdef WLAN_DEBUG
static char *bw_str_arr[] = {"20MHz", "40MHz", "80MHz", "160MHz"};
#endif
/*
* Defined the macro tx_rate_stats_print_cmn()
* so that this could be used in both
* htt_t2h_stats_tx_rate_stats_print() &
* htt_t2h_stats_tx_rate_stats_print_v2().
* Each of these functions take a different structure as argument,
* but with common fields in the structures--so using a macro
* to bypass the strong type-checking of a function seems a simple
* trick to use to avoid the code duplication.
*/
#define tx_rate_stats_print_cmn(_tx_rate_info, _concise) \
do { \
qdf_nofl_info("TX Rate Info:"); \
\
/* MCS */ \
qdf_nofl_info("%s: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d",\
"MCS counts (0..9)", \
_tx_rate_info->mcs[0], \
_tx_rate_info->mcs[1], \
_tx_rate_info->mcs[2], \
_tx_rate_info->mcs[3], \
_tx_rate_info->mcs[4], \
_tx_rate_info->mcs[5], \
_tx_rate_info->mcs[6], \
_tx_rate_info->mcs[7], \
_tx_rate_info->mcs[8], \
_tx_rate_info->mcs[9]); \
\
/* SGI */ \
qdf_nofl_info("%s: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d",\
"SGI counts (0..9)", \
_tx_rate_info->sgi[0], \
_tx_rate_info->sgi[1], \
_tx_rate_info->sgi[2], \
_tx_rate_info->sgi[3], \
_tx_rate_info->sgi[4], \
_tx_rate_info->sgi[5], \
_tx_rate_info->sgi[6], \
_tx_rate_info->sgi[7], \
_tx_rate_info->sgi[8], \
_tx_rate_info->sgi[9]); \
\
/* NSS */ \
qdf_nofl_info("NSS counts: 1x1 %d, 2x2 %d, 3x3 %d", \
_tx_rate_info->nss[0], \
_tx_rate_info->nss[1], _tx_rate_info->nss[2]);\
\
/* BW */ \
if (ARRAY_SIZE(_tx_rate_info->bw) == 3) \
qdf_nofl_info("BW counts: %s %d, %s %d, %s %d", \
bw_str_arr[0], _tx_rate_info->bw[0], \
bw_str_arr[1], _tx_rate_info->bw[1], \
bw_str_arr[2], _tx_rate_info->bw[2]); \
else if (ARRAY_SIZE(_tx_rate_info->bw) == 4) \
qdf_nofl_info("BW counts: %s %d, %s %d, %s %d, %s %d", \
bw_str_arr[0], _tx_rate_info->bw[0], \
bw_str_arr[1], _tx_rate_info->bw[1], \
bw_str_arr[2], _tx_rate_info->bw[2], \
bw_str_arr[3], _tx_rate_info->bw[3]); \
\
\
/* Preamble */ \
qdf_nofl_info("Preamble (O C H V) counts: %d, %d, %d, %d",\
_tx_rate_info->pream[0], \
_tx_rate_info->pream[1], \
_tx_rate_info->pream[2], \
_tx_rate_info->pream[3]); \
\
/* STBC rate counts */ \
qdf_nofl_info("%s: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d",\
"STBC rate counts (0..9)", \
_tx_rate_info->stbc[0], \
_tx_rate_info->stbc[1], \
_tx_rate_info->stbc[2], \
_tx_rate_info->stbc[3], \
_tx_rate_info->stbc[4], \
_tx_rate_info->stbc[5], \
_tx_rate_info->stbc[6], \
_tx_rate_info->stbc[7], \
_tx_rate_info->stbc[8], \
_tx_rate_info->stbc[9]); \
\
/* LDPC and TxBF counts */ \
qdf_nofl_info("LDPC Counts: %d", _tx_rate_info->ldpc);\
qdf_nofl_info("RTS Counts: %d", _tx_rate_info->rts_cnt);\
/* RSSI Values for last ack frames */ \
qdf_nofl_info("Ack RSSI: %d", _tx_rate_info->ack_rssi);\
} while (0)
static void htt_t2h_stats_tx_rate_stats_print(wlan_dbg_tx_rate_info_t *
tx_rate_info, int concise)
{
tx_rate_stats_print_cmn(tx_rate_info, concise);
}
static void htt_t2h_stats_tx_rate_stats_print_v2(wlan_dbg_tx_rate_info_v2_t *
tx_rate_info, int concise)
{
tx_rate_stats_print_cmn(tx_rate_info, concise);
}
/*
* Defined the macro rx_rate_stats_print_cmn()
* so that this could be used in both
* htt_t2h_stats_rx_rate_stats_print() &
* htt_t2h_stats_rx_rate_stats_print_v2().
* Each of these functions take a different structure as argument,
* but with common fields in the structures -- so using a macro
* to bypass the strong type-checking of a function seems a simple
* trick to use to avoid the code duplication.
*/
#define rx_rate_stats_print_cmn(_rx_phy_info, _concise) \
do { \
qdf_nofl_info("RX Rate Info:"); \
\
/* MCS */ \
qdf_nofl_info("%s: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d",\
"MCS counts (0..9)", \
_rx_phy_info->mcs[0], \
_rx_phy_info->mcs[1], \
_rx_phy_info->mcs[2], \
_rx_phy_info->mcs[3], \
_rx_phy_info->mcs[4], \
_rx_phy_info->mcs[5], \
_rx_phy_info->mcs[6], \
_rx_phy_info->mcs[7], \
_rx_phy_info->mcs[8], \
_rx_phy_info->mcs[9]); \
\
/* SGI */ \
qdf_nofl_info("%s: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d",\
"SGI counts (0..9)", \
_rx_phy_info->sgi[0], \
_rx_phy_info->sgi[1], \
_rx_phy_info->sgi[2], \
_rx_phy_info->sgi[3], \
_rx_phy_info->sgi[4], \
_rx_phy_info->sgi[5], \
_rx_phy_info->sgi[6], \
_rx_phy_info->sgi[7], \
_rx_phy_info->sgi[8], \
_rx_phy_info->sgi[9]); \
\
/*
* NSS \
* nss[0] just holds the count of non-stbc frames that were \
* sent at 1x1 rates and nsts holds the count of frames sent \
* with stbc. \
* It was decided to not include PPDUs sent w/ STBC in nss[0] \
* since it would be easier to change the value that needs to \
* be printed (from stbc+non-stbc count to only non-stbc count)\
* if needed in the future. Hence the addition in the host code\
* at this line.
*/ \
qdf_nofl_info("NSS counts: 1x1 %d, 2x2 %d, 3x3 %d, 4x4 %d",\
_rx_phy_info->nss[0] + _rx_phy_info->nsts,\
_rx_phy_info->nss[1], \
_rx_phy_info->nss[2], \
_rx_phy_info->nss[3]); \
\
/* NSTS */ \
qdf_nofl_info("NSTS count: %d", _rx_phy_info->nsts); \
\
/* BW */ \
if (ARRAY_SIZE(_rx_phy_info->bw) == 3) \
qdf_nofl_info("BW counts: %s %d, %s %d, %s %d", \
bw_str_arr[0], _rx_phy_info->bw[0], \
bw_str_arr[1], _rx_phy_info->bw[1], \
bw_str_arr[2], _rx_phy_info->bw[2]); \
else if (ARRAY_SIZE(_rx_phy_info->bw) == 4) \
qdf_nofl_info("BW counts: %s %d, %s %d, %s %d, %s %d", \
bw_str_arr[0], _rx_phy_info->bw[0], \
bw_str_arr[1], _rx_phy_info->bw[1], \
bw_str_arr[2], _rx_phy_info->bw[2], \
bw_str_arr[3], _rx_phy_info->bw[3]); \
\
/* Preamble */ \
qdf_nofl_info("Preamble counts: %d, %d, %d, %d, %d, %d",\
_rx_phy_info->pream[0], \
_rx_phy_info->pream[1], \
_rx_phy_info->pream[2], \
_rx_phy_info->pream[3], \
_rx_phy_info->pream[4], \
_rx_phy_info->pream[5]); \
\
/* STBC rate counts */ \
qdf_nofl_info("%s: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d",\
"STBC rate counts (0..9)", \
_rx_phy_info->stbc[0], \
_rx_phy_info->stbc[1], \
_rx_phy_info->stbc[2], \
_rx_phy_info->stbc[3], \
_rx_phy_info->stbc[4], \
_rx_phy_info->stbc[5], \
_rx_phy_info->stbc[6], \
_rx_phy_info->stbc[7], \
_rx_phy_info->stbc[8], \
_rx_phy_info->stbc[9]); \
\
/* LDPC and TxBF counts */ \
qdf_nofl_info("LDPC TXBF Counts: %d, %d", \
_rx_phy_info->ldpc, _rx_phy_info->txbf);\
/* RSSI Values for last received frames */ \
qdf_nofl_info("RSSI (data, mgmt): %d, %d",\
_rx_phy_info->data_rssi,\
_rx_phy_info->mgmt_rssi); \
\
qdf_nofl_info("RSSI Chain 0 (0x%02x 0x%02x 0x%02x 0x%02x)",\
((_rx_phy_info->rssi_chain0 >> 24) & 0xff),\
((_rx_phy_info->rssi_chain0 >> 16) & 0xff),\
((_rx_phy_info->rssi_chain0 >> 8) & 0xff),\
((_rx_phy_info->rssi_chain0 >> 0) & 0xff));\
\
qdf_nofl_info("RSSI Chain 1 (0x%02x 0x%02x 0x%02x 0x%02x)",\
((_rx_phy_info->rssi_chain1 >> 24) & 0xff),\
((_rx_phy_info->rssi_chain1 >> 16) & 0xff),\
((_rx_phy_info->rssi_chain1 >> 8) & 0xff),\
((_rx_phy_info->rssi_chain1 >> 0) & 0xff));\
\
qdf_nofl_info("RSSI Chain 2 (0x%02x 0x%02x 0x%02x 0x%02x)",\
((_rx_phy_info->rssi_chain2 >> 24) & 0xff),\
((_rx_phy_info->rssi_chain2 >> 16) & 0xff),\
((_rx_phy_info->rssi_chain2 >> 8) & 0xff),\
((_rx_phy_info->rssi_chain2 >> 0) & 0xff));\
} while (0)
static void htt_t2h_stats_rx_rate_stats_print(wlan_dbg_rx_rate_info_t *
rx_phy_info, int concise)
{
rx_rate_stats_print_cmn(rx_phy_info, concise);
}
static void htt_t2h_stats_rx_rate_stats_print_v2(wlan_dbg_rx_rate_info_v2_t *
rx_phy_info, int concise)
{
rx_rate_stats_print_cmn(rx_phy_info, concise);
}
static void
htt_t2h_stats_pdev_stats_print(struct wlan_dbg_stats *wlan_pdev_stats,
int concise)
{
#ifdef WLAN_DEBUG
struct wlan_dbg_tx_stats *tx = &wlan_pdev_stats->tx;
struct wlan_dbg_rx_stats *rx = &wlan_pdev_stats->rx;
#endif
qdf_nofl_info("WAL Pdev stats:");
qdf_nofl_info("\n### Tx ###");
/* Num HTT cookies queued to dispatch list */
qdf_nofl_info("comp_queued :\t%d", tx->comp_queued);
/* Num HTT cookies dispatched */
qdf_nofl_info("comp_delivered :\t%d", tx->comp_delivered);
/* Num MSDU queued to WAL */
qdf_nofl_info("msdu_enqued :\t%d", tx->msdu_enqued);
/* Num MPDU queued to WAL */
qdf_nofl_info("mpdu_enqued :\t%d", tx->mpdu_enqued);
/* Num MSDUs dropped by WMM limit */
qdf_nofl_info("wmm_drop :\t%d", tx->wmm_drop);
/* Num Local frames queued */
qdf_nofl_info("local_enqued :\t%d", tx->local_enqued);
/* Num Local frames done */
qdf_nofl_info("local_freed :\t%d", tx->local_freed);
/* Num queued to HW */
qdf_nofl_info("hw_queued :\t%d", tx->hw_queued);
/* Num PPDU reaped from HW */
qdf_nofl_info("hw_reaped :\t%d", tx->hw_reaped);
/* Num underruns */
qdf_nofl_info("mac underrun :\t%d", tx->underrun);
/* Num underruns */
qdf_nofl_info("phy underrun :\t%d", tx->phy_underrun);
/* Num PPDUs cleaned up in TX abort */
qdf_nofl_info("tx_abort :\t%d", tx->tx_abort);
/* Num MPDUs requed by SW */
qdf_nofl_info("mpdus_requed :\t%d", tx->mpdus_requed);
/* Excessive retries */
qdf_nofl_info("excess retries :\t%d", tx->tx_ko);
/* last data rate */
qdf_nofl_info("last rc :\t%d", tx->data_rc);
/* scheduler self triggers */
qdf_nofl_info("sched self trig :\t%d", tx->self_triggers);
/* SW retry failures */
qdf_nofl_info("ampdu retry failed:\t%d", tx->sw_retry_failure);
/* ilegal phy rate errirs */
qdf_nofl_info("illegal rate errs :\t%d", tx->illgl_rate_phy_err);
/* pdev continuous excessive retries */
qdf_nofl_info("pdev cont xretry :\t%d", tx->pdev_cont_xretry);
/* pdev continuous excessive retries */
qdf_nofl_info("pdev tx timeout :\t%d", tx->pdev_tx_timeout);
/* pdev resets */
qdf_nofl_info("pdev resets :\t%d", tx->pdev_resets);
/* PPDU > txop duration */
qdf_nofl_info("ppdu txop ovf :\t%d", tx->txop_ovf);
qdf_nofl_info("\n### Rx ###\n");
/* Cnts any change in ring routing mid-ppdu */
qdf_nofl_info("ppdu_route_change :\t%d", rx->mid_ppdu_route_change);
/* Total number of statuses processed */
qdf_nofl_info("status_rcvd :\t%d", rx->status_rcvd);
/* Extra frags on rings 0-3 */
qdf_nofl_info("r0_frags :\t%d", rx->r0_frags);
qdf_nofl_info("r1_frags :\t%d", rx->r1_frags);
qdf_nofl_info("r2_frags :\t%d", rx->r2_frags);
qdf_nofl_info("r3_frags :\t%d", rx->r3_frags);
/* MSDUs / MPDUs delivered to HTT */
qdf_nofl_info("htt_msdus :\t%d", rx->htt_msdus);
qdf_nofl_info("htt_mpdus :\t%d", rx->htt_mpdus);
/* MSDUs / MPDUs delivered to local stack */
qdf_nofl_info("loc_msdus :\t%d", rx->loc_msdus);
qdf_nofl_info("loc_mpdus :\t%d", rx->loc_mpdus);
/* AMSDUs that have more MSDUs than the status ring size */
qdf_nofl_info("oversize_amsdu :\t%d", rx->oversize_amsdu);
/* Number of PHY errors */
qdf_nofl_info("phy_errs :\t%d", rx->phy_errs);
/* Number of PHY errors dropped */
qdf_nofl_info("phy_errs dropped :\t%d", rx->phy_err_drop);
/* Number of mpdu errors - FCS, MIC, ENC etc. */
qdf_nofl_info("mpdu_errs :\t%d", rx->mpdu_errs);
}
static void
htt_t2h_stats_rx_reorder_stats_print(struct rx_reorder_stats *stats_ptr,
int concise)
{
qdf_nofl_info("Rx reorder statistics:");
qdf_nofl_info(" %u non-QoS frames received",
stats_ptr->deliver_non_qos);
qdf_nofl_info(" %u frames received in-order",
stats_ptr->deliver_in_order);
qdf_nofl_info(" %u frames flushed due to timeout",
stats_ptr->deliver_flush_timeout);
qdf_nofl_info(" %u frames flushed due to moving out of window",
stats_ptr->deliver_flush_oow);
qdf_nofl_info(" %u frames flushed due to receiving DELBA",
stats_ptr->deliver_flush_delba);
qdf_nofl_info(" %u frames discarded due to FCS error",
stats_ptr->fcs_error);
qdf_nofl_info(" %u frames discarded due to invalid peer",
stats_ptr->invalid_peer);
qdf_nofl_info
(" %u frames discarded due to duplication (non aggregation)",
stats_ptr->dup_non_aggr);
qdf_nofl_info(" %u frames discarded due to duplication in reorder queue",
stats_ptr->dup_in_reorder);
qdf_nofl_info(" %u frames discarded due to processed before",
stats_ptr->dup_past);
qdf_nofl_info(" %u times reorder timeout happened",
stats_ptr->reorder_timeout);
qdf_nofl_info(" %u times incorrect bar received",
stats_ptr->invalid_bar_ssn);
qdf_nofl_info(" %u times bar ssn reset happened",
stats_ptr->ssn_reset);
qdf_nofl_info(" %u times flushed due to peer delete",
stats_ptr->deliver_flush_delpeer);
qdf_nofl_info(" %u times flushed due to offload",
stats_ptr->deliver_flush_offload);
qdf_nofl_info(" %u times flushed due to ouf of buffer",
stats_ptr->deliver_flush_oob);
qdf_nofl_info(" %u MPDU's dropped due to PN check fail",
stats_ptr->pn_fail);
qdf_nofl_info(" %u MPDU's dropped due to lack of memory",
stats_ptr->store_fail);
qdf_nofl_info(" %u times tid pool alloc succeeded",
stats_ptr->tid_pool_alloc_succ);
qdf_nofl_info(" %u times MPDU pool alloc succeeded",
stats_ptr->mpdu_pool_alloc_succ);
qdf_nofl_info(" %u times MSDU pool alloc succeeded",
stats_ptr->msdu_pool_alloc_succ);
qdf_nofl_info(" %u times tid pool alloc failed",
stats_ptr->tid_pool_alloc_fail);
qdf_nofl_info(" %u times MPDU pool alloc failed",
stats_ptr->mpdu_pool_alloc_fail);
qdf_nofl_info(" %u times MSDU pool alloc failed",
stats_ptr->msdu_pool_alloc_fail);
qdf_nofl_info(" %u times tid pool freed",
stats_ptr->tid_pool_free);
qdf_nofl_info(" %u times MPDU pool freed",
stats_ptr->mpdu_pool_free);
qdf_nofl_info(" %u times MSDU pool freed",
stats_ptr->msdu_pool_free);
qdf_nofl_info(" %u MSDUs undelivered to HTT, queued to Rx MSDU free list",
stats_ptr->msdu_queued);
qdf_nofl_info(" %u MSDUs released from Rx MSDU list to MAC ring",
stats_ptr->msdu_recycled);
qdf_nofl_info(" %u MPDUs with invalid peer but A2 found in AST",
stats_ptr->invalid_peer_a2_in_ast);
qdf_nofl_info(" %u MPDUs with invalid peer but A3 found in AST",
stats_ptr->invalid_peer_a3_in_ast);
qdf_nofl_info(" %u MPDUs with invalid peer, Broadcast or Mulitcast frame",
stats_ptr->invalid_peer_bmc_mpdus);
qdf_nofl_info(" %u MSDUs with err attention word",
stats_ptr->rxdesc_err_att);
qdf_nofl_info(" %u MSDUs with flag of peer_idx_invalid",
stats_ptr->rxdesc_err_peer_idx_inv);
qdf_nofl_info(" %u MSDUs with flag of peer_idx_timeout",
stats_ptr->rxdesc_err_peer_idx_to);
qdf_nofl_info(" %u MSDUs with flag of overflow",
stats_ptr->rxdesc_err_ov);
qdf_nofl_info(" %u MSDUs with flag of msdu_length_err",
stats_ptr->rxdesc_err_msdu_len);
qdf_nofl_info(" %u MSDUs with flag of mpdu_length_err",
stats_ptr->rxdesc_err_mpdu_len);
qdf_nofl_info(" %u MSDUs with flag of tkip_mic_err",
stats_ptr->rxdesc_err_tkip_mic);
qdf_nofl_info(" %u MSDUs with flag of decrypt_err",
stats_ptr->rxdesc_err_decrypt);
qdf_nofl_info(" %u MSDUs with flag of fcs_err",
stats_ptr->rxdesc_err_fcs);
qdf_nofl_info(" %u Unicast frames with invalid peer handler",
stats_ptr->rxdesc_uc_msdus_inv_peer);
qdf_nofl_info(" %u unicast frame to DUT with invalid peer handler",
stats_ptr->rxdesc_direct_msdus_inv_peer);
qdf_nofl_info(" %u Broadcast/Multicast frames with invalid peer handler",
stats_ptr->rxdesc_bmc_msdus_inv_peer);
qdf_nofl_info(" %u MSDUs dropped due to no first MSDU flag",
stats_ptr->rxdesc_no_1st_msdu);
qdf_nofl_info(" %u MSDUs dropped due to ring overflow",
stats_ptr->msdu_drop_ring_ov);
qdf_nofl_info(" %u MSDUs dropped due to FC mismatch",
stats_ptr->msdu_drop_fc_mismatch);
qdf_nofl_info(" %u MSDUs dropped due to mgt frame in Remote ring",
stats_ptr->msdu_drop_mgmt_remote_ring);
qdf_nofl_info(" %u MSDUs dropped due to misc non error",
stats_ptr->msdu_drop_misc);
qdf_nofl_info(" %u MSDUs go to offload before reorder",
stats_ptr->offload_msdu_wal);
qdf_nofl_info(" %u data frame dropped by offload after reorder",
stats_ptr->offload_msdu_reorder);
qdf_nofl_info(" %u MPDUs with SN in the past & within BA window",
stats_ptr->dup_past_within_window);
qdf_nofl_info(" %u MPDUs with SN in the past & outside BA window",
stats_ptr->dup_past_outside_window);
}
static void
htt_t2h_stats_rx_rem_buf_stats_print(
struct rx_remote_buffer_mgmt_stats *stats_ptr, int concise)
{
qdf_nofl_info("Rx Remote Buffer Statistics:");
qdf_nofl_info(" %u MSDU's reaped for Rx processing",
stats_ptr->remote_reaped);
qdf_nofl_info(" %u MSDU's recycled within firmware",
stats_ptr->remote_recycled);
qdf_nofl_info(" %u MSDU's stored by Data Rx",
stats_ptr->data_rx_msdus_stored);
qdf_nofl_info(" %u HTT indications from WAL Rx MSDU",
stats_ptr->wal_rx_ind);
qdf_nofl_info(" %u HTT indications unconsumed from WAL Rx MSDU",
stats_ptr->wal_rx_ind_unconsumed);
qdf_nofl_info(" %u HTT indications from Data Rx MSDU",
stats_ptr->data_rx_ind);
qdf_nofl_info(" %u HTT indications unconsumed from Data Rx MSDU",
stats_ptr->data_rx_ind_unconsumed);
qdf_nofl_info(" %u HTT indications from ATHBUF",
stats_ptr->athbuf_rx_ind);
qdf_nofl_info(" %u Remote buffers requested for refill",
stats_ptr->refill_buf_req);
qdf_nofl_info(" %u Remote buffers filled by host",
stats_ptr->refill_buf_rsp);
qdf_nofl_info(" %u times MAC has no buffers",
stats_ptr->mac_no_bufs);
qdf_nofl_info(" %u times f/w write & read indices on MAC ring are equal",
stats_ptr->fw_indices_equal);
qdf_nofl_info(" %u times f/w has no remote buffers to post to MAC",
stats_ptr->host_no_bufs);
}
static void
htt_t2h_stats_txbf_info_buf_stats_print(
struct wlan_dbg_txbf_data_stats *stats_ptr)
{
qdf_nofl_info("TXBF data Statistics:");
qdf_nofl_info("tx_txbf_vht (0..9): %u, %u, %u, %u, %u, %u, %u, %u, %u, %d",
stats_ptr->tx_txbf_vht[0],
stats_ptr->tx_txbf_vht[1],
stats_ptr->tx_txbf_vht[2],
stats_ptr->tx_txbf_vht[3],
stats_ptr->tx_txbf_vht[4],
stats_ptr->tx_txbf_vht[5],
stats_ptr->tx_txbf_vht[6],
stats_ptr->tx_txbf_vht[7],
stats_ptr->tx_txbf_vht[8],
stats_ptr->tx_txbf_vht[9]);
qdf_nofl_info("rx_txbf_vht (0..9): %u, %u, %u, %u, %u, %u, %u, %u, %u, %u",
stats_ptr->rx_txbf_vht[0],
stats_ptr->rx_txbf_vht[1],
stats_ptr->rx_txbf_vht[2],
stats_ptr->rx_txbf_vht[3],
stats_ptr->rx_txbf_vht[4],
stats_ptr->rx_txbf_vht[5],
stats_ptr->rx_txbf_vht[6],
stats_ptr->rx_txbf_vht[7],
stats_ptr->rx_txbf_vht[8],
stats_ptr->rx_txbf_vht[9]);
qdf_nofl_info("tx_txbf_ht (0..7): %u, %u, %u, %u, %u, %u, %u, %u",
stats_ptr->tx_txbf_ht[0],
stats_ptr->tx_txbf_ht[1],
stats_ptr->tx_txbf_ht[2],
stats_ptr->tx_txbf_ht[3],
stats_ptr->tx_txbf_ht[4],
stats_ptr->tx_txbf_ht[5],
stats_ptr->tx_txbf_ht[6],
stats_ptr->tx_txbf_ht[7]);
qdf_nofl_info("tx_txbf_ofdm (0..7): %u, %u, %u, %u, %u, %u, %u, %u",
stats_ptr->tx_txbf_ofdm[0],
stats_ptr->tx_txbf_ofdm[1],
stats_ptr->tx_txbf_ofdm[2],
stats_ptr->tx_txbf_ofdm[3],
stats_ptr->tx_txbf_ofdm[4],
stats_ptr->tx_txbf_ofdm[5],
stats_ptr->tx_txbf_ofdm[6],
stats_ptr->tx_txbf_ofdm[7]);
qdf_nofl_info("tx_txbf_cck (0..6): %u, %u, %u, %u, %u, %u, %u",
stats_ptr->tx_txbf_cck[0],
stats_ptr->tx_txbf_cck[1],
stats_ptr->tx_txbf_cck[2],
stats_ptr->tx_txbf_cck[3],
stats_ptr->tx_txbf_cck[4],
stats_ptr->tx_txbf_cck[5],
stats_ptr->tx_txbf_cck[6]);
}
static void
htt_t2h_stats_txbf_snd_buf_stats_print(
struct wlan_dbg_txbf_snd_stats *stats_ptr)
{
qdf_nofl_info("TXBF snd Buffer Statistics:");
qdf_nofl_info("cbf_20: %u, %u, %u, %u",
stats_ptr->cbf_20[0],
stats_ptr->cbf_20[1],
stats_ptr->cbf_20[2],
stats_ptr->cbf_20[3]);
qdf_nofl_info("cbf_40: %u, %u, %u, %u",
stats_ptr->cbf_40[0],
stats_ptr->cbf_40[1],
stats_ptr->cbf_40[2],
stats_ptr->cbf_40[3]);
qdf_nofl_info("cbf_80: %u, %u, %u, %u",
stats_ptr->cbf_80[0],
stats_ptr->cbf_80[1],
stats_ptr->cbf_80[2],
stats_ptr->cbf_80[3]);
qdf_nofl_info("sounding: %u, %u, %u, %u, %u, %u, %u, %u, %u",
stats_ptr->sounding[0],
stats_ptr->sounding[1],
stats_ptr->sounding[2],
stats_ptr->sounding[3],
stats_ptr->sounding[4],
stats_ptr->sounding[5],
stats_ptr->sounding[6],
stats_ptr->sounding[7],
stats_ptr->sounding[8]);
}
static void
htt_t2h_stats_tx_selfgen_buf_stats_print(
struct wlan_dbg_tx_selfgen_stats *stats_ptr)
{
qdf_nofl_info("Tx selfgen Buffer Statistics:");
qdf_nofl_info(" %u su_ndpa",
stats_ptr->su_ndpa);
qdf_nofl_info(" %u mu_ndp",
stats_ptr->mu_ndp);
qdf_nofl_info(" %u mu_ndpa",
stats_ptr->mu_ndpa);
qdf_nofl_info(" %u mu_ndp",
stats_ptr->mu_ndp);
qdf_nofl_info(" %u mu_brpoll_1",
stats_ptr->mu_brpoll_1);
qdf_nofl_info(" %u mu_brpoll_2",
stats_ptr->mu_brpoll_2);
qdf_nofl_info(" %u mu_bar_1",
stats_ptr->mu_bar_1);
qdf_nofl_info(" %u mu_bar_2",
stats_ptr->mu_bar_2);
qdf_nofl_info(" %u cts_burst",
stats_ptr->cts_burst);
qdf_nofl_info(" %u su_ndp_err",
stats_ptr->su_ndp_err);
qdf_nofl_info(" %u su_ndpa_err",
stats_ptr->su_ndpa_err);
qdf_nofl_info(" %u mu_ndp_err",
stats_ptr->mu_ndp_err);
qdf_nofl_info(" %u mu_brp1_err",
stats_ptr->mu_brp1_err);
qdf_nofl_info(" %u mu_brp2_err",
stats_ptr->mu_brp2_err);
}
static void
htt_t2h_stats_wifi2_error_stats_print(
struct wlan_dbg_wifi2_error_stats *stats_ptr)
{
int i;
qdf_nofl_info("Scheduler error Statistics:");
qdf_nofl_info("urrn_stats: ");
qdf_nofl_info("urrn_stats: %d, %d, %d",
stats_ptr->urrn_stats[0],
stats_ptr->urrn_stats[1],
stats_ptr->urrn_stats[2]);
qdf_nofl_info("flush_errs (0..%d): ",
WHAL_DBG_FLUSH_REASON_MAXCNT);
for (i = 0; i < WHAL_DBG_FLUSH_REASON_MAXCNT; i++)
qdf_nofl_info(" %u", stats_ptr->flush_errs[i]);
qdf_nofl_info("\n");
qdf_nofl_info("schd_stall_errs (0..3): ");
qdf_nofl_info("%d, %d, %d, %d",
stats_ptr->schd_stall_errs[0],
stats_ptr->schd_stall_errs[1],
stats_ptr->schd_stall_errs[2],
stats_ptr->schd_stall_errs[3]);
qdf_nofl_info("schd_cmd_result (0..%d): ",
WHAL_DBG_CMD_RESULT_MAXCNT);
for (i = 0; i < WHAL_DBG_CMD_RESULT_MAXCNT; i++)
qdf_nofl_info(" %u", stats_ptr->schd_cmd_result[i]);
qdf_nofl_info("\n");
qdf_nofl_info("sifs_status (0..%d): ",
WHAL_DBG_SIFS_STATUS_MAXCNT);
for (i = 0; i < WHAL_DBG_SIFS_STATUS_MAXCNT; i++)
qdf_nofl_info(" %u", stats_ptr->sifs_status[i]);
qdf_nofl_info("\n");
qdf_nofl_info("phy_errs (0..%d): ",
WHAL_DBG_PHY_ERR_MAXCNT);
for (i = 0; i < WHAL_DBG_PHY_ERR_MAXCNT; i++)
qdf_nofl_info(" %u", stats_ptr->phy_errs[i]);
qdf_nofl_info("\n");
qdf_nofl_info(" %u rx_rate_inval",
stats_ptr->rx_rate_inval);
}
static void
htt_t2h_rx_musu_ndpa_pkts_stats_print(
struct rx_txbf_musu_ndpa_pkts_stats *stats_ptr)
{
qdf_nofl_info("Rx TXBF MU/SU Packets and NDPA Statistics:");
qdf_nofl_info(" %u Number of TXBF MU packets received",
stats_ptr->number_mu_pkts);
qdf_nofl_info(" %u Number of TXBF SU packets received",
stats_ptr->number_su_pkts);
qdf_nofl_info(" %u Number of TXBF directed NDPA",
stats_ptr->txbf_directed_ndpa_count);
qdf_nofl_info(" %u Number of TXBF retried NDPA",
stats_ptr->txbf_ndpa_retry_count);
qdf_nofl_info(" %u Total number of TXBF NDPA",
stats_ptr->txbf_total_ndpa_count);
}
#define HTT_TICK_TO_USEC(ticks, microsec_per_tick) (ticks * microsec_per_tick)
static inline int htt_rate_flags_to_mhz(uint8_t rate_flags)
{
if (rate_flags & 0x20)
return 40; /* WHAL_RC_FLAG_40MHZ */
if (rate_flags & 0x40)
return 80; /* WHAL_RC_FLAG_80MHZ */
if (rate_flags & 0x80)
return 160; /* WHAL_RC_FLAG_160MHZ */
return 20;
}
#define HTT_FW_STATS_MAX_BLOCK_ACK_WINDOW 64
static void
htt_t2h_tx_ppdu_bitmaps_pr(uint32_t *queued_ptr, uint32_t *acked_ptr)
{
char queued_str[HTT_FW_STATS_MAX_BLOCK_ACK_WINDOW + 1];
char acked_str[HTT_FW_STATS_MAX_BLOCK_ACK_WINDOW + 1];
int i, j, word;
qdf_mem_set(queued_str, HTT_FW_STATS_MAX_BLOCK_ACK_WINDOW, '0');
qdf_mem_set(acked_str, HTT_FW_STATS_MAX_BLOCK_ACK_WINDOW, '-');
i = 0;
for (word = 0; word < 2; word++) {
uint32_t queued = *(queued_ptr + word);
uint32_t acked = *(acked_ptr + word);
for (j = 0; j < 32; j++, i++) {
if (queued & (1 << j)) {
queued_str[i] = '1';
acked_str[i] = (acked & (1 << j)) ? 'y' : 'N';
}
}
}
queued_str[HTT_FW_STATS_MAX_BLOCK_ACK_WINDOW] = '\0';
acked_str[HTT_FW_STATS_MAX_BLOCK_ACK_WINDOW] = '\0';
qdf_nofl_info("%s\n", queued_str);
qdf_nofl_info("%s\n", acked_str);
}
static inline uint16_t htt_msg_read16(uint16_t *p16)
{
#ifdef BIG_ENDIAN_HOST
/*
* During upload, the bytes within each uint32_t word were
* swapped by the HIF HW. This results in the lower and upper bytes
* of each uint16_t to be in the correct big-endian order with
* respect to each other, but for each even-index uint16_t to
* have its position switched with its successor neighbor uint16_t.
* Undo this uint16_t position swapping.
*/
return (((size_t) p16) & 0x2) ? *(p16 - 1) : *(p16 + 1);
#else
return *p16;
#endif
}
static inline uint8_t htt_msg_read8(uint8_t *p8)
{
#ifdef BIG_ENDIAN_HOST
/*
* During upload, the bytes within each uint32_t word were
* swapped by the HIF HW.
* Undo this byte swapping.
*/
switch (((size_t) p8) & 0x3) {
case 0:
return *(p8 + 3);
case 1:
return *(p8 + 1);
case 2:
return *(p8 - 1);
default /* 3 */:
return *(p8 - 3);
}
#else
return *p8;
#endif
}
static void htt_make_u8_list_str(uint32_t *aligned_data,
char *buffer, int space, int max_elems)
{
uint8_t *p8 = (uint8_t *) aligned_data;
char *buf_p = buffer;
while (max_elems-- > 0) {
int bytes;
uint8_t val;
val = htt_msg_read8(p8);
if (val == 0)
/* not enough data to fill the reserved msg buffer*/
break;
bytes = qdf_snprint(buf_p, space, "%d,", val);
space -= bytes;
if (space > 0)
buf_p += bytes;
else /* not enough print buffer space for all the data */
break;
p8++;
}
if (buf_p == buffer)
*buf_p = '\0'; /* nothing was written */
else
*(buf_p - 1) = '\0'; /* erase the final comma */
}
static void htt_make_u16_list_str(uint32_t *aligned_data,
char *buffer, int space, int max_elems)
{
uint16_t *p16 = (uint16_t *) aligned_data;
char *buf_p = buffer;
while (max_elems-- > 0) {
int bytes;
uint16_t val;
val = htt_msg_read16(p16);
if (val == 0)
/* not enough data to fill the reserved msg buffer */
break;
bytes = qdf_snprint(buf_p, space, "%d,", val);
space -= bytes;
if (space > 0)
buf_p += bytes;
else /* not enough print buffer space for all the data */
break;
p16++;
}
if (buf_p == buffer)
*buf_p = '\0'; /* nothing was written */
else
*(buf_p - 1) = '\0'; /* erase the final comma */
}
static void
htt_t2h_tx_ppdu_log_print(struct ol_fw_tx_dbg_ppdu_msg_hdr *hdr,
struct ol_fw_tx_dbg_ppdu_base *record,
int length, int concise)
{
int i;
int record_size;
int calculated_record_size;
int num_records;
record_size = sizeof(*record);
calculated_record_size = record_size +
hdr->mpdu_bytes_array_len * sizeof(uint16_t);
if (calculated_record_size < record_size) {
qdf_err("Overflow due to record and hdr->mpdu_bytes_array_len %u",
hdr->mpdu_bytes_array_len);
return;
}
record_size = calculated_record_size;
calculated_record_size += hdr->mpdu_msdus_array_len * sizeof(uint8_t);
if (calculated_record_size < record_size) {
qdf_err("Overflow due to hdr->mpdu_msdus_array_len %u",
hdr->mpdu_msdus_array_len);
return;
}
record_size = calculated_record_size;
calculated_record_size += hdr->msdu_bytes_array_len * sizeof(uint16_t);
if (calculated_record_size < record_size) {
qdf_err("Overflow due to hdr->msdu_bytes_array_len %u",
hdr->msdu_bytes_array_len);
return;
}
record_size = calculated_record_size;
num_records = (length - sizeof(*hdr)) / record_size;
if (num_records < 0) {
qdf_err("Underflow due to length %d", length);
return;
}
qdf_nofl_info("Tx PPDU log elements: num_records %d", num_records);
for (i = 0; i < num_records; i++) {
uint16_t start_seq_num;
uint16_t start_pn_lsbs;
uint8_t num_mpdus;
uint16_t peer_id;
uint8_t ext_tid;
uint8_t rate_code;
uint8_t rate_flags;
uint8_t tries;
uint8_t complete;
uint32_t time_enqueue_us;
uint32_t time_completion_us;
uint32_t *msg_word = (uint32_t *) record;
/* fields used for both concise and complete printouts */
start_seq_num =
((*(msg_word + OL_FW_TX_DBG_PPDU_START_SEQ_NUM_WORD)) &
OL_FW_TX_DBG_PPDU_START_SEQ_NUM_M) >>
OL_FW_TX_DBG_PPDU_START_SEQ_NUM_S;
complete =
((*(msg_word + OL_FW_TX_DBG_PPDU_COMPLETE_WORD)) &
OL_FW_TX_DBG_PPDU_COMPLETE_M) >>
OL_FW_TX_DBG_PPDU_COMPLETE_S;
/* fields used only for complete printouts */
if (!concise) {
#define BUF_SIZE 80
char buf[BUF_SIZE];
uint8_t *p8;
uint8_t *calculated_p8;
time_enqueue_us =
HTT_TICK_TO_USEC(record->timestamp_enqueue,
hdr->microsec_per_tick);
time_completion_us =
HTT_TICK_TO_USEC(record->timestamp_completion,
hdr->microsec_per_tick);
start_pn_lsbs =
((*(msg_word +
OL_FW_TX_DBG_PPDU_START_PN_LSBS_WORD)) &
OL_FW_TX_DBG_PPDU_START_PN_LSBS_M) >>
OL_FW_TX_DBG_PPDU_START_PN_LSBS_S;
num_mpdus =
((*(msg_word +
OL_FW_TX_DBG_PPDU_NUM_MPDUS_WORD))&
OL_FW_TX_DBG_PPDU_NUM_MPDUS_M) >>
OL_FW_TX_DBG_PPDU_NUM_MPDUS_S;
peer_id =
((*(msg_word +
OL_FW_TX_DBG_PPDU_PEER_ID_WORD)) &
OL_FW_TX_DBG_PPDU_PEER_ID_M) >>
OL_FW_TX_DBG_PPDU_PEER_ID_S;
ext_tid =
((*(msg_word +
OL_FW_TX_DBG_PPDU_EXT_TID_WORD)) &
OL_FW_TX_DBG_PPDU_EXT_TID_M) >>
OL_FW_TX_DBG_PPDU_EXT_TID_S;
rate_code =
((*(msg_word +
OL_FW_TX_DBG_PPDU_RATE_CODE_WORD))&
OL_FW_TX_DBG_PPDU_RATE_CODE_M) >>
OL_FW_TX_DBG_PPDU_RATE_CODE_S;
rate_flags =
((*(msg_word +
OL_FW_TX_DBG_PPDU_RATE_FLAGS_WORD))&
OL_FW_TX_DBG_PPDU_RATE_FLAGS_M) >>
OL_FW_TX_DBG_PPDU_RATE_FLAGS_S;
tries =
((*(msg_word +
OL_FW_TX_DBG_PPDU_TRIES_WORD)) &
OL_FW_TX_DBG_PPDU_TRIES_M) >>
OL_FW_TX_DBG_PPDU_TRIES_S;
qdf_nofl_info(" - PPDU tx to peer %d, TID %d", peer_id,
ext_tid);
qdf_nofl_info(" start seq num= %u, start PN LSBs= %#04x",
start_seq_num, start_pn_lsbs);
qdf_nofl_info(" PPDU: %d MPDUs, (?) MSDUs, %d bytes",
num_mpdus,
/* num_msdus - not yet computed in target */
record->num_bytes);
if (complete) {
qdf_nofl_info(" enqueued: %u, completed: %u usec)",
time_enqueue_us, time_completion_us);
qdf_nofl_info(" %d tries, last tx used rate %d ",
tries, rate_code);
qdf_nofl_info("on %d MHz chan (flags = %#x)",
htt_rate_flags_to_mhz
(rate_flags), rate_flags);
qdf_nofl_info(" enqueued and acked MPDU bitmaps:");
htt_t2h_tx_ppdu_bitmaps_pr(msg_word +
OL_FW_TX_DBG_PPDU_ENQUEUED_LSBS_WORD,
msg_word +
OL_FW_TX_DBG_PPDU_BLOCK_ACK_LSBS_WORD);
} else {
qdf_nofl_info(" enqueued: %d us, not yet completed",
time_enqueue_us);
}
/* skip the regular msg fields to reach the tail area */
p8 = (uint8_t *) record;
calculated_p8 = p8 + sizeof(struct ol_fw_tx_dbg_ppdu_base);
if (calculated_p8 < p8) {
qdf_err("Overflow due to record %pK", p8);
continue;
}
p8 = calculated_p8;
if (hdr->mpdu_bytes_array_len) {
htt_make_u16_list_str((uint32_t *) p8, buf,
BUF_SIZE,
hdr->
mpdu_bytes_array_len);
qdf_nofl_info(" MPDU bytes: %s", buf);
}
calculated_p8 += hdr->mpdu_bytes_array_len * sizeof(uint16_t);
if (calculated_p8 < p8) {
qdf_err("Overflow due to hdr->mpdu_bytes_array_len %u",
hdr->mpdu_bytes_array_len);
continue;
}
p8 = calculated_p8;
if (hdr->mpdu_msdus_array_len) {
htt_make_u8_list_str((uint32_t *) p8, buf,
BUF_SIZE,
hdr->mpdu_msdus_array_len);
qdf_nofl_info(" MPDU MSDUs: %s", buf);
}
calculated_p8 += hdr->mpdu_msdus_array_len * sizeof(uint8_t);
if (calculated_p8 < p8) {
qdf_err("Overflow due to hdr->mpdu_msdus_array_len %u",
hdr->mpdu_msdus_array_len);
continue;
}
p8 = calculated_p8;
if (hdr->msdu_bytes_array_len) {
htt_make_u16_list_str((uint32_t *) p8, buf,
BUF_SIZE,
hdr->
msdu_bytes_array_len);
qdf_nofl_info(" MSDU bytes: %s", buf);
}
} else {
/* concise */
qdf_nofl_info("start seq num = %u ", start_seq_num);
qdf_nofl_info("enqueued and acked MPDU bitmaps:");
if (complete) {
htt_t2h_tx_ppdu_bitmaps_pr(msg_word +
OL_FW_TX_DBG_PPDU_ENQUEUED_LSBS_WORD,
msg_word +
OL_FW_TX_DBG_PPDU_BLOCK_ACK_LSBS_WORD);
} else {
qdf_nofl_info("(not completed)");
}
}
record = (struct ol_fw_tx_dbg_ppdu_base *)
(((uint8_t *) record) + record_size);
}
}
static void htt_t2h_stats_tidq_stats_print(
struct wlan_dbg_tidq_stats *tidq_stats, int concise)
{
qdf_nofl_info("TID QUEUE STATS:");
qdf_nofl_info("tid_txq_stats: %u", tidq_stats->wlan_dbg_tid_txq_status);
qdf_nofl_info("num_pkts_queued(0..9):");
qdf_nofl_info("%u, %u, %u, %u, %u, %u, %u, %u, %u, %u",
tidq_stats->txq_st.num_pkts_queued[0],
tidq_stats->txq_st.num_pkts_queued[1],
tidq_stats->txq_st.num_pkts_queued[2],
tidq_stats->txq_st.num_pkts_queued[3],
tidq_stats->txq_st.num_pkts_queued[4],
tidq_stats->txq_st.num_pkts_queued[5],
tidq_stats->txq_st.num_pkts_queued[6],
tidq_stats->txq_st.num_pkts_queued[7],
tidq_stats->txq_st.num_pkts_queued[8],
tidq_stats->txq_st.num_pkts_queued[9]);
qdf_nofl_info("tid_hw_qdepth(0..19):");
qdf_nofl_info("%u, %u, %u, %u, %u, %u, %u, %u, %u, %u",
tidq_stats->txq_st.tid_hw_qdepth[0],
tidq_stats->txq_st.tid_hw_qdepth[1],
tidq_stats->txq_st.tid_hw_qdepth[2],
tidq_stats->txq_st.tid_hw_qdepth[3],
tidq_stats->txq_st.tid_hw_qdepth[4],
tidq_stats->txq_st.tid_hw_qdepth[5],
tidq_stats->txq_st.tid_hw_qdepth[6],
tidq_stats->txq_st.tid_hw_qdepth[7],
tidq_stats->txq_st.tid_hw_qdepth[8],
tidq_stats->txq_st.tid_hw_qdepth[9]);
qdf_nofl_info("%u, %u, %u, %u, %u, %u, %u, %u, %u, %u",
tidq_stats->txq_st.tid_hw_qdepth[10],
tidq_stats->txq_st.tid_hw_qdepth[11],
tidq_stats->txq_st.tid_hw_qdepth[12],
tidq_stats->txq_st.tid_hw_qdepth[13],
tidq_stats->txq_st.tid_hw_qdepth[14],
tidq_stats->txq_st.tid_hw_qdepth[15],
tidq_stats->txq_st.tid_hw_qdepth[16],
tidq_stats->txq_st.tid_hw_qdepth[17],
tidq_stats->txq_st.tid_hw_qdepth[18],
tidq_stats->txq_st.tid_hw_qdepth[19]);
qdf_nofl_info("tid_sw_qdepth(0..19):");
qdf_nofl_info("%u, %u, %u, %u, %u, %u, %u, %u, %u, %u",
tidq_stats->txq_st.tid_sw_qdepth[0],
tidq_stats->txq_st.tid_sw_qdepth[1],
tidq_stats->txq_st.tid_sw_qdepth[2],
tidq_stats->txq_st.tid_sw_qdepth[3],
tidq_stats->txq_st.tid_sw_qdepth[4],
tidq_stats->txq_st.tid_sw_qdepth[5],
tidq_stats->txq_st.tid_sw_qdepth[6],
tidq_stats->txq_st.tid_sw_qdepth[7],
tidq_stats->txq_st.tid_sw_qdepth[8],
tidq_stats->txq_st.tid_sw_qdepth[9]);
qdf_nofl_info("%u, %u, %u, %u, %u, %u, %u, %u, %u, %u",
tidq_stats->txq_st.tid_sw_qdepth[10],
tidq_stats->txq_st.tid_sw_qdepth[11],
tidq_stats->txq_st.tid_sw_qdepth[12],
tidq_stats->txq_st.tid_sw_qdepth[13],
tidq_stats->txq_st.tid_sw_qdepth[14],
tidq_stats->txq_st.tid_sw_qdepth[15],
tidq_stats->txq_st.tid_sw_qdepth[16],
tidq_stats->txq_st.tid_sw_qdepth[17],
tidq_stats->txq_st.tid_sw_qdepth[18],
tidq_stats->txq_st.tid_sw_qdepth[19]);
}
static void htt_t2h_stats_tx_mu_stats_print(
struct wlan_dbg_tx_mu_stats *tx_mu_stats, int concise)
{
qdf_nofl_info("TX MU STATS:");
qdf_nofl_info("mu_sch_nusers_2: %u", tx_mu_stats->mu_sch_nusers_2);
qdf_nofl_info("mu_sch_nusers_3: %u", tx_mu_stats->mu_sch_nusers_3);
qdf_nofl_info("mu_mpdus_queued_usr: %u, %u, %u, %u",
tx_mu_stats->mu_mpdus_queued_usr[0],
tx_mu_stats->mu_mpdus_queued_usr[1],
tx_mu_stats->mu_mpdus_queued_usr[2],
tx_mu_stats->mu_mpdus_queued_usr[3]);
qdf_nofl_info("mu_mpdus_tried_usr: %u, %u, %u, %u",
tx_mu_stats->mu_mpdus_tried_usr[0],
tx_mu_stats->mu_mpdus_tried_usr[1],
tx_mu_stats->mu_mpdus_tried_usr[2],
tx_mu_stats->mu_mpdus_tried_usr[3]);
qdf_nofl_info("mu_mpdus_failed_usr: %u, %u, %u, %u",
tx_mu_stats->mu_mpdus_failed_usr[0],
tx_mu_stats->mu_mpdus_failed_usr[1],
tx_mu_stats->mu_mpdus_failed_usr[2],
tx_mu_stats->mu_mpdus_failed_usr[3]);
qdf_nofl_info("mu_mpdus_requeued_usr: %u, %u, %u, %u",
tx_mu_stats->mu_mpdus_requeued_usr[0],
tx_mu_stats->mu_mpdus_requeued_usr[1],
tx_mu_stats->mu_mpdus_requeued_usr[2],
tx_mu_stats->mu_mpdus_requeued_usr[3]);
qdf_nofl_info("mu_err_no_ba_usr: %u, %u, %u, %u",
tx_mu_stats->mu_err_no_ba_usr[0],
tx_mu_stats->mu_err_no_ba_usr[1],
tx_mu_stats->mu_err_no_ba_usr[2],
tx_mu_stats->mu_err_no_ba_usr[3]);
qdf_nofl_info("mu_mpdu_underrun_usr: %u, %u, %u, %u",
tx_mu_stats->mu_mpdu_underrun_usr[0],
tx_mu_stats->mu_mpdu_underrun_usr[1],
tx_mu_stats->mu_mpdu_underrun_usr[2],
tx_mu_stats->mu_mpdu_underrun_usr[3]);
qdf_nofl_info("mu_ampdu_underrun_usr: %u, %u, %u, %u",
tx_mu_stats->mu_ampdu_underrun_usr[0],
tx_mu_stats->mu_ampdu_underrun_usr[1],
tx_mu_stats->mu_ampdu_underrun_usr[2],
tx_mu_stats->mu_ampdu_underrun_usr[3]);
}
static void htt_t2h_stats_sifs_resp_stats_print(
struct wlan_dbg_sifs_resp_stats *sifs_stats, int concise)
{
qdf_nofl_info("SIFS RESP STATS:");
qdf_nofl_info("num of ps-poll trigger frames: %u",
sifs_stats->ps_poll_trigger);
qdf_nofl_info("num of uapsd trigger frames: %u",
sifs_stats->uapsd_trigger);
qdf_nofl_info("num of data trigger frames: %u, %u",
sifs_stats->qb_data_trigger[0],
sifs_stats->qb_data_trigger[1]);
qdf_nofl_info("num of bar trigger frames: %u, %u",
sifs_stats->qb_bar_trigger[0],
sifs_stats->qb_bar_trigger[1]);
qdf_nofl_info("num of ppdu transmitted at SIFS interval: %u",
sifs_stats->sifs_resp_data);
qdf_nofl_info("num of ppdu failed to meet SIFS resp timing: %u",
sifs_stats->sifs_resp_err);
}
void htt_t2h_stats_print(uint8_t *stats_data, int concise)
{
uint32_t *msg_word = (uint32_t *) stats_data;
enum htt_dbg_stats_type type;
enum htt_dbg_stats_status status;
int length;
type = HTT_T2H_STATS_CONF_TLV_TYPE_GET(*msg_word);
status = HTT_T2H_STATS_CONF_TLV_STATUS_GET(*msg_word);
length = HTT_T2H_STATS_CONF_TLV_LENGTH_GET(*msg_word);
/* check that we've been given a valid stats type */
if (status == HTT_DBG_STATS_STATUS_SERIES_DONE) {
return;
} else if (status == HTT_DBG_STATS_STATUS_INVALID) {
qdf_nofl_info("Target doesn't support stats type %d", type);
return;
} else if (status == HTT_DBG_STATS_STATUS_ERROR) {
qdf_nofl_info("Target couldn't upload stats type %d (no mem?)",
type);
return;
}
/* got valid (though perhaps partial) stats - process them */
switch (type) {
case HTT_DBG_STATS_WAL_PDEV_TXRX:
{
struct wlan_dbg_stats *wlan_dbg_stats_ptr;
wlan_dbg_stats_ptr =
(struct wlan_dbg_stats *)(msg_word + 1);
htt_t2h_stats_pdev_stats_print(wlan_dbg_stats_ptr,
concise);
break;
}
case HTT_DBG_STATS_RX_REORDER:
{
struct rx_reorder_stats *rx_reorder_stats_ptr;
rx_reorder_stats_ptr =
(struct rx_reorder_stats *)(msg_word + 1);
htt_t2h_stats_rx_reorder_stats_print
(rx_reorder_stats_ptr, concise);
break;
}
case HTT_DBG_STATS_RX_RATE_INFO:
{
wlan_dbg_rx_rate_info_t *rx_phy_info;
rx_phy_info = (wlan_dbg_rx_rate_info_t *) (msg_word + 1);
htt_t2h_stats_rx_rate_stats_print(rx_phy_info, concise);
break;
}
case HTT_DBG_STATS_RX_RATE_INFO_V2:
{
wlan_dbg_rx_rate_info_v2_t *rx_phy_info;
rx_phy_info = (wlan_dbg_rx_rate_info_v2_t *) (msg_word + 1);
htt_t2h_stats_rx_rate_stats_print_v2(rx_phy_info, concise);
break;
}
case HTT_DBG_STATS_TX_PPDU_LOG:
{
struct ol_fw_tx_dbg_ppdu_msg_hdr *hdr;
struct ol_fw_tx_dbg_ppdu_base *record;
if (status == HTT_DBG_STATS_STATUS_PARTIAL
&& length == 0) {
qdf_nofl_info("HTT_DBG_STATS_TX_PPDU_LOG -- length = 0!");
break;
}
hdr = (struct ol_fw_tx_dbg_ppdu_msg_hdr *)(msg_word + 1);
record = (struct ol_fw_tx_dbg_ppdu_base *)(hdr + 1);
htt_t2h_tx_ppdu_log_print(hdr, record, length, concise);
}
break;
case HTT_DBG_STATS_TX_RATE_INFO:
{
wlan_dbg_tx_rate_info_t *tx_rate_info;
tx_rate_info = (wlan_dbg_tx_rate_info_t *) (msg_word + 1);
htt_t2h_stats_tx_rate_stats_print(tx_rate_info, concise);
break;
}
case HTT_DBG_STATS_TX_RATE_INFO_V2:
{
wlan_dbg_tx_rate_info_v2_t *tx_rate_info;
tx_rate_info = (wlan_dbg_tx_rate_info_v2_t *) (msg_word + 1);
htt_t2h_stats_tx_rate_stats_print_v2(tx_rate_info, concise);
break;
}
case HTT_DBG_STATS_RX_REMOTE_RING_BUFFER_INFO:
{
struct rx_remote_buffer_mgmt_stats *rx_rem_buf;
rx_rem_buf =
(struct rx_remote_buffer_mgmt_stats *)(msg_word + 1);
htt_t2h_stats_rx_rem_buf_stats_print(rx_rem_buf, concise);
break;
}
case HTT_DBG_STATS_TXBF_INFO:
{
struct wlan_dbg_txbf_data_stats *txbf_info_buf;
txbf_info_buf =
(struct wlan_dbg_txbf_data_stats *)(msg_word + 1);
htt_t2h_stats_txbf_info_buf_stats_print(txbf_info_buf);
break;
}
case HTT_DBG_STATS_SND_INFO:
{
struct wlan_dbg_txbf_snd_stats *txbf_snd_buf;
txbf_snd_buf = (struct wlan_dbg_txbf_snd_stats *)(msg_word + 1);
htt_t2h_stats_txbf_snd_buf_stats_print(txbf_snd_buf);
break;
}
case HTT_DBG_STATS_TX_SELFGEN_INFO:
{
struct wlan_dbg_tx_selfgen_stats *tx_selfgen_buf;
tx_selfgen_buf =
(struct wlan_dbg_tx_selfgen_stats *)(msg_word + 1);
htt_t2h_stats_tx_selfgen_buf_stats_print(tx_selfgen_buf);
break;
}
case HTT_DBG_STATS_ERROR_INFO:
{
struct wlan_dbg_wifi2_error_stats *wifi2_error_buf;
wifi2_error_buf =
(struct wlan_dbg_wifi2_error_stats *)(msg_word + 1);
htt_t2h_stats_wifi2_error_stats_print(wifi2_error_buf);
break;
}
case HTT_DBG_STATS_TXBF_MUSU_NDPA_PKT:
{
struct rx_txbf_musu_ndpa_pkts_stats *rx_musu_ndpa_stats;
rx_musu_ndpa_stats = (struct rx_txbf_musu_ndpa_pkts_stats *)
(msg_word + 1);
htt_t2h_rx_musu_ndpa_pkts_stats_print(rx_musu_ndpa_stats);
break;
}
case HTT_DBG_STATS_TIDQ:
{
struct wlan_dbg_tidq_stats *tidq_stats;
tidq_stats = (struct wlan_dbg_tidq_stats *)(msg_word + 1);
htt_t2h_stats_tidq_stats_print(tidq_stats, concise);
break;
}
case HTT_DBG_STATS_TX_MU_INFO:
{
struct wlan_dbg_tx_mu_stats *tx_mu_stats;
tx_mu_stats = (struct wlan_dbg_tx_mu_stats *)(msg_word + 1);
htt_t2h_stats_tx_mu_stats_print(tx_mu_stats, concise);
break;
}
case HTT_DBG_STATS_SIFS_RESP_INFO:
{
struct wlan_dbg_sifs_resp_stats *sifs_stats;
sifs_stats = (struct wlan_dbg_sifs_resp_stats *)(msg_word + 1);
htt_t2h_stats_sifs_resp_stats_print(sifs_stats, concise);
break;
}
default:
break;
}
}
|
liwen-deepmotion/map_based_lidar_camera_calibration_tool | calibration_tool/trajectory/camera_config.py | # Author: <NAME> (<EMAIL>)
import json
import numpy as np
class CameraConfig(object):
def __init__(self):
self.fx = float()
self.fy = float()
self.cx = float()
self.cy = float()
self.w = int()
self.h = int()
def from_json_file(self, json_file_path: str):
with open(json_file_path, 'r') as f:
sensor_calibrations = json.load(f)
for sensor_config in sensor_calibrations['dm_device']['sensors']:
if sensor_config['type'] == 'camera':
self.w = sensor_config['width']
self.h = sensor_config['height']
self.fx, self.fy, self.cx, self.cy = \
sensor_config['intrinsics']
break
def intrinsic_matrix(self):
return np.array([
[self.fx, 0, self.cx],
[0, self.fy, self.cy],
[0, 0, 1]
])
def get_projection_matrix(self) -> np.ndarray(shape=(4, 4)):
w, h = self.w, self.h
fu, fv = self.fx, self.fy
u0, v0 = self.cx, self.cy
zNear, zFar = 0.54, 3000
# http://www.songho.ca/opengl/gl_projectionmatrix.html
# The following lines are copied from panolin's implementation
# opengl_render_state.cpp, line 404: ProjectionMatrixRUB_BottomLeft
L = +(u0) * zNear / -fu
T = +(v0) * zNear / fv
R = -(w - u0) * zNear / -fu
B = -(h - v0) * zNear / fv
P = np.zeros((4, 4), dtype=np.float32)
P[0, 0] = 2 * zNear / (R - L)
P[1, 1] = 2 * zNear / (T - B)
P[2, 2] = -(zFar + zNear) / (zFar - zNear)
P[2, 0] = (R + L) / (R - L)
P[2, 1] = (T + B) / (T - B)
P[2, 3] = -1.0
P[3, 2] = -(2 * zFar * zNear) / (zFar - zNear)
return P
|
realvitya/fmcapi | fmcapi/api_objects/update_packages/__init__.py | <reponame>realvitya/fmcapi<filename>fmcapi/api_objects/update_packages/__init__.py
import logging
from .listapplicabledevices import ListApplicableDevices
from .listapplicabledevices import ApplicableDevices
from .upgradepackages import UpgradePackages
from .upgradepackages import UpgradePackage
from .upgradepackage import Upgrades
logging.debug("In the update_packages __init__.py file.")
__all__ = [
"ListApplicableDevices",
"ApplicableDevices",
"UpgradePackages",
"UpgradePackage",
"Upgrades",
]
|
clilystudio/NetBook | allsrc/com/ushaqi/zhuishushenqi/model/YLPayOrder.java | <gh_stars>1-10
package com.ushaqi.zhuishushenqi.model;
public class YLPayOrder
{
private boolean ok;
private YLPayOrder.PayOrder payOrder;
public YLPayOrder.PayOrder getPayOrder()
{
return this.payOrder;
}
public boolean isOk()
{
return this.ok;
}
public void setOk(boolean paramBoolean)
{
this.ok = paramBoolean;
}
public void setPayOrder(YLPayOrder.PayOrder paramPayOrder)
{
this.payOrder = paramPayOrder;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.model.YLPayOrder
* JD-Core Version: 0.6.0
*/ |
MerHub/symfony | SprintMobiles/lib/impl/stubs/org/bouncycastle/crypto/params/DHKeyGenerationParameters.java | /**
*
* Classes for parameter objects for ciphers and generators.
*/
package org.bouncycastle.crypto.params;
public class DHKeyGenerationParameters extends org.bouncycastle.crypto.KeyGenerationParameters {
public DHKeyGenerationParameters(javabc.SecureRandom random, DHParameters params) {
}
public DHParameters getParameters() {
}
}
|
JiehangXie/PaddleSpeech | utils/remove_longshortdata.py | <gh_stars>1000+
#!/usr/bin/env python3
"""remove longshort data from manifest"""
import argparse
import logging
import jsonlines
from paddlespeech.s2t.utils.cli_utils import get_commandline_args
# manifest after format
# josnline like this
# {
# "input": [{"name": "input1", "shape": (100, 83), "feat": "xxx.ark:123"}],
# "output": [{"name":"target1", "shape": (40, 5002), "text": "a b c de"}],
# "utt2spk": "111-2222",
# "utt": "111-2222-333"
# }
def get_parser():
parser = argparse.ArgumentParser(
description="remove longshort data from format manifest",
formatter_class=argparse.ArgumentDefaultsHelpFormatter, )
parser.add_argument(
"--verbose", "-V", default=0, type=int, help="Verbose option")
parser.add_argument(
"--iaxis",
default=0,
type=int,
help="multi inputs index, 0 is the first")
parser.add_argument(
"--oaxis",
default=0,
type=int,
help="multi outputs index, 0 is the first")
parser.add_argument("--maxframes", default=2000, type=int, help="maxframes")
parser.add_argument("--minframes", default=10, type=int, help="minframes")
parser.add_argument("--maxchars", default=200, type=int, help="max tokens")
parser.add_argument("--minchars", default=0, type=int, help="min tokens")
parser.add_argument(
"--stride_ms", default=10, type=int, help="stride in ms unit.")
parser.add_argument(
"rspecifier",
type=str,
help="jsonl format manifest. e.g. manifest.jsonl")
parser.add_argument(
"wspecifier_or_wxfilename",
type=str,
help="Write specifier. e.g. manifest.jsonl")
return parser
def filter_input(args, line):
tmp = line['input'][args.iaxis]
if args.sound:
# second to frame
nframe = tmp['shape'][0] * 1000 / args.stride_ms
else:
nframe = tmp['shape'][0]
if nframe < args.minframes or nframe > args.maxframes:
return True
else:
return False
def filter_output(args, line):
nchars = len(line['output'][args.iaxis]['text'])
if nchars < args.minchars or nchars > args.maxchars:
return True
else:
return False
def main():
args = get_parser().parse_args()
logfmt = "%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s"
if args.verbose > 0:
logging.basicConfig(level=logging.INFO, format=logfmt)
else:
logging.basicConfig(level=logging.WARN, format=logfmt)
logging.info(get_commandline_args())
with jsonlines.open(args.rspecifier, 'r') as reader:
lines = list(reader)
logging.info(f"Example: {len(lines)}")
feat = lines[0]['input'][args.iaxis]['feat']
args.soud = False
if feat.split('.')[-1] not in 'ark, scp':
args.sound = True
count = 0
filter = 0
with jsonlines.open(args.wspecifier_or_wxfilename, 'w') as writer:
for line in lines:
if filter_input(args, line) or filter_output(args, line):
filter += 1
continue
writer.write(line)
count += 1
logging.info(f"Example after filter: {count}\{filter}")
if __name__ == '__main__':
main()
|
hoehnp/SpaceDesignTool | sta-src/Services/serviceDistanceRateUnit.cpp | <reponame>hoehnp/SpaceDesignTool
/*
This program is free software; you can redistribute it and/or modify it under
the terms of the European Union Public Licence - EUPL v.1.1 as published by
the European Commission.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1
for more details.
You should have received a copy of the European Union Public Licence - EUPL v.1.1
along with this program.
Further information about the European Union Public Licence - EUPL v.1.1 can
also be found on the world wide web at http://ec.europa.eu/idabc/eupl
*/
/*
------ Copyright (C) 2011 STA Steering Board (space.trajectory.analysis AT gmail.com) ----
*/
/*
------------------ Author: <NAME> ----------------------------------------
May 2011
*/
#include "serviceDistanceRateUnit.h"
#include <Eigen/Core>
using namespace Eigen;
#include "QDebug"
DialogServiceDistanceRateUnitFrame::DialogServiceDistanceRateUnitFrame( QWidget * parent, Qt::WindowFlags f) : QFrame(parent,f)
{
setupUi(this);
distanceRateUnitWidget = DialogServiceDistanceRateUnitFrame::comboBoxDistanceRateUnitsChoice;
myPastUnits = 0;
comboBoxDistanceRateUnitsChoice->setCurrentIndex(myPastUnits);
}
DialogServiceDistanceRateUnitFrame::~DialogServiceDistanceRateUnitFrame()
{
}
// Index meaning is as follows:
// index = 0 is Kilometers/s
// index = 1 is meters/s
// index = 2 is centi-meters/s
// index = 3 is mili-meters/s
// index = 4 is Astronomical Units/s
// Matrix coefficients as follows
// Km->Km, Km->m, Km->cm, Km->mm, Km->AU,
// m->Km, m->m, m->cm, m->mm, m->AU,
// cm->Km, cm->m, cm->cm, cm->mm, cm-> AU,
// mm->Km, mm->m, mm->cm, mm->mm, mm->AU,
// AU->Km, AU->m, AU->cm, AU->mm, AU->AU
// The matrice has to be transposed !!
static double distanceRateConversionMatrixCoeffs[25] =
{1.0, 0.001, 0.00001, 0.000001, 1.495978707e+08,
1000.0, 1.0, 0.01, 0.001, 1.495978707e+11,
100000.0, 100.0, 1.0, 0.1, 1.495978707e+13,
1000000.0, 1000.0, 10.0, 1.0, 1.495978707e+14,
0.6684587e-19, 0.6684587e-12, 0.6684587e-13, 0.6684587e-16, 1.0};
static const Matrix<double, 5, 5> distanceRateConversionMatrix(distanceRateConversionMatrixCoeffs);
double DialogServiceDistanceRateUnitFrame::convertDistanceRate(int fromDistanceRateUnit, int toDistanceRateUnit, double distance)
{
double finalDistanceRate = distance * distanceRateConversionMatrix(fromDistanceRateUnit, toDistanceRateUnit);
return finalDistanceRate;
}
//// Sets the input distance, the output distance and the current index inside the method
void DialogServiceDistanceRateUnitFrame::setInputDistanceRate(double niceInputDistanceRate)
{
myPastDistanceRate = niceInputDistanceRate;
}
// Index meaning is as follows:
// index = 0 is Kilometers/s
// index = 1 is meters/s
// index = 2 is centi-meters/s
// index = 3 is mili-meters/s
// index = 4 is Astronomical Units/s
void DialogServiceDistanceRateUnitFrame::on_comboBoxDistanceRateUnitsChoice_currentIndexChanged(int myIndex)
{
myFutureUnits = myIndex;
myFutureDistanceRate = convertDistanceRate(myPastUnits, myFutureUnits, myPastDistanceRate);
myPastDistanceRate = myFutureDistanceRate;
myPastUnits = myFutureUnits;
myRealDistanceRateForXMLSchema = convertDistanceRate (myPastUnits, 0, myFutureDistanceRate);
}
|
pyr-sh/keybase-notarybot | bot/vendor/github.com/pzduniak/unipdf/model/page.go | /*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.md', which is part of this source code package.
*/
//
// Allow higher level manipulation of PDF files and pages.
// This can be continuously expanded to support more and more features.
// Generic handling can be done by defining elements as PdfObject which
// can later be replaced and fully defined.
//
package model
import (
"bytes"
"errors"
"fmt"
"strings"
"github.com/pzduniak/unipdf/common"
"github.com/pzduniak/unipdf/core"
)
// PdfPage represents a page in a PDF document. (7.7.3.3 - Table 30).
type PdfPage struct {
Parent core.PdfObject
LastModified *PdfDate
Resources *PdfPageResources
CropBox *PdfRectangle
MediaBox *PdfRectangle
BleedBox *PdfRectangle
TrimBox *PdfRectangle
ArtBox *PdfRectangle
BoxColorInfo core.PdfObject
Contents core.PdfObject
Rotate *int64
Group core.PdfObject
Thumb core.PdfObject
B core.PdfObject
Dur core.PdfObject
Trans core.PdfObject
AA core.PdfObject
Metadata core.PdfObject
PieceInfo core.PdfObject
StructParents core.PdfObject
ID core.PdfObject
PZ core.PdfObject
SeparationInfo core.PdfObject
Tabs core.PdfObject
TemplateInstantiated core.PdfObject
PresSteps core.PdfObject
UserUnit core.PdfObject
VP core.PdfObject
Annots core.PdfObject
annotations []*PdfAnnotation
// Primitive container.
pageDict *core.PdfObjectDictionary
primitive *core.PdfIndirectObject
reader *PdfReader
}
// NewPdfPage returns a new PDF page.
func NewPdfPage() *PdfPage {
page := PdfPage{}
page.pageDict = core.MakeDict()
page.Resources = NewPdfPageResources()
container := core.PdfIndirectObject{}
container.PdfObject = page.pageDict
page.primitive = &container
return &page
}
func (p *PdfPage) setContainer(container *core.PdfIndirectObject) {
container.PdfObject = p.pageDict
p.primitive = container
}
// Duplicate creates a duplicate page based on the current one and returns it.
func (p *PdfPage) Duplicate() *PdfPage {
var dup PdfPage
dup = *p
dup.pageDict = core.MakeDict()
dup.primitive = core.MakeIndirectObject(dup.pageDict)
return &dup
}
// Build a PdfPage based on the underlying dictionary.
// Used in loading existing PDF files.
// Note that a new container is created (indirect object).
func (r *PdfReader) newPdfPageFromDict(p *core.PdfObjectDictionary) (*PdfPage, error) {
page := NewPdfPage()
page.pageDict = p
d := *p
pType, ok := d.Get("Type").(*core.PdfObjectName)
if !ok {
return nil, errors.New("missing/invalid Page dictionary Type")
}
if *pType != "Page" {
return nil, errors.New("page dictionary Type != Page")
}
if obj := d.Get("Parent"); obj != nil {
page.Parent = obj
}
if obj := d.Get("LastModified"); obj != nil {
strObj, ok := core.GetString(obj)
if !ok {
return nil, errors.New("page dictionary LastModified != string")
}
lastmod, err := NewPdfDate(strObj.Str())
if err != nil {
return nil, err
}
page.LastModified = &lastmod
}
if obj := d.Get("Resources"); obj != nil && !core.IsNullObject(obj) {
dict, ok := core.GetDict(obj)
if !ok {
return nil, fmt.Errorf("invalid resource dictionary (%T)", obj)
}
var err error
page.Resources, err = NewPdfPageResourcesFromDict(dict)
if err != nil {
return nil, err
}
} else {
// If Resources not explicitly defined, look up the tree (Parent objects) using
// the getParentResources() function. Resources should always be accessible.
resources, err := page.getParentResources()
if err != nil {
return nil, err
}
if resources == nil {
resources = NewPdfPageResources()
}
page.Resources = resources
}
if obj := d.Get("MediaBox"); obj != nil {
boxArr, ok := core.GetArray(obj)
if !ok {
return nil, errors.New("page MediaBox not an array")
}
var err error
page.MediaBox, err = NewPdfRectangle(*boxArr)
if err != nil {
return nil, err
}
}
if obj := d.Get("CropBox"); obj != nil {
boxArr, ok := core.GetArray(obj)
if !ok {
return nil, errors.New("page CropBox not an array")
}
var err error
page.CropBox, err = NewPdfRectangle(*boxArr)
if err != nil {
return nil, err
}
}
if obj := d.Get("BleedBox"); obj != nil {
boxArr, ok := core.GetArray(obj)
if !ok {
return nil, errors.New("page BleedBox not an array")
}
var err error
page.BleedBox, err = NewPdfRectangle(*boxArr)
if err != nil {
return nil, err
}
}
if obj := d.Get("TrimBox"); obj != nil {
boxArr, ok := core.GetArray(obj)
if !ok {
return nil, errors.New("page TrimBox not an array")
}
var err error
page.TrimBox, err = NewPdfRectangle(*boxArr)
if err != nil {
return nil, err
}
}
if obj := d.Get("ArtBox"); obj != nil {
boxArr, ok := core.GetArray(obj)
if !ok {
return nil, errors.New("page ArtBox not an array")
}
var err error
page.ArtBox, err = NewPdfRectangle(*boxArr)
if err != nil {
return nil, err
}
}
if obj := d.Get("BoxColorInfo"); obj != nil {
page.BoxColorInfo = obj
}
if obj := d.Get("Contents"); obj != nil {
page.Contents = obj
}
if obj := d.Get("Rotate"); obj != nil {
iObj, ok := core.GetInt(obj)
if !ok {
return nil, errors.New("invalid Page Rotate object")
}
iVal := int64(*iObj)
page.Rotate = &iVal
}
if obj := d.Get("Group"); obj != nil {
page.Group = obj
}
if obj := d.Get("Thumb"); obj != nil {
page.Thumb = obj
}
if obj := d.Get("B"); obj != nil {
page.B = obj
}
if obj := d.Get("Dur"); obj != nil {
page.Dur = obj
}
if obj := d.Get("Trans"); obj != nil {
page.Trans = obj
}
if obj := d.Get("AA"); obj != nil {
page.AA = obj
}
if obj := d.Get("Metadata"); obj != nil {
page.Metadata = obj
}
if obj := d.Get("PieceInfo"); obj != nil {
page.PieceInfo = obj
}
if obj := d.Get("StructParents"); obj != nil {
page.StructParents = obj
}
if obj := d.Get("ID"); obj != nil {
page.ID = obj
}
if obj := d.Get("PZ"); obj != nil {
page.PZ = obj
}
if obj := d.Get("SeparationInfo"); obj != nil {
page.SeparationInfo = obj
}
if obj := d.Get("Tabs"); obj != nil {
page.Tabs = obj
}
if obj := d.Get("TemplateInstantiated"); obj != nil {
page.TemplateInstantiated = obj
}
if obj := d.Get("PresSteps"); obj != nil {
page.PresSteps = obj
}
if obj := d.Get("UserUnit"); obj != nil {
page.UserUnit = obj
}
if obj := d.Get("VP"); obj != nil {
page.VP = obj
}
if obj := d.Get("Annots"); obj != nil {
page.Annots = obj
}
page.reader = r
return page, nil
}
// GetAnnotations returns the list of page annotations for `page`. If not loaded attempts to load the
// annotations, otherwise returns the loaded list.
func (page *PdfPage) GetAnnotations() ([]*PdfAnnotation, error) {
if page.annotations != nil {
return page.annotations, nil
}
if page.Annots == nil {
page.annotations = []*PdfAnnotation{}
return nil, nil
}
if page.reader == nil {
page.annotations = []*PdfAnnotation{}
return nil, nil
}
annots, err := page.reader.loadAnnotations(page.Annots)
if err != nil {
return nil, err
}
if annots == nil {
page.annotations = []*PdfAnnotation{}
}
page.annotations = annots
return page.annotations, nil
}
// AddAnnotation appends `annot` to the list of page annotations.
func (page *PdfPage) AddAnnotation(annot *PdfAnnotation) {
if page.annotations == nil {
page.GetAnnotations() // Ensure has been loaded.
}
page.annotations = append(page.annotations, annot)
}
// SetAnnotations sets the annotations list.
func (page *PdfPage) SetAnnotations(annotations []*PdfAnnotation) {
page.annotations = annotations
}
// loadAnnotations loads and returns the PDF annotations from the input annotations object (array).
func (r *PdfReader) loadAnnotations(annotsObj core.PdfObject) ([]*PdfAnnotation, error) {
annotsArr, ok := core.GetArray(annotsObj)
if !ok {
return nil, fmt.Errorf("Annots not an array")
}
var annotations []*PdfAnnotation
for _, obj := range annotsArr.Elements() {
obj = core.ResolveReference(obj)
// Technically all annotation dictionaries should be inside indirect objects.
// In reality, sometimes the annotation dictionary is inline within the Annots array.
if _, isNull := obj.(*core.PdfObjectNull); isNull {
// Can safely ignore.
continue
}
annotDict, isDict := obj.(*core.PdfObjectDictionary)
indirectObj, isIndirect := obj.(*core.PdfIndirectObject)
if isDict {
// Create a container; indirect object; around the dictionary.
indirectObj = &core.PdfIndirectObject{}
indirectObj.PdfObject = annotDict
} else {
if !isIndirect {
return nil, fmt.Errorf("annotation not in an indirect object")
}
}
annot, err := r.newPdfAnnotationFromIndirectObject(indirectObj)
if err != nil {
return nil, err
}
switch t := annot.GetContext().(type) {
case *PdfAnnotationWidget:
// Link widget annotation with form field (parent).
for _, field := range r.AcroForm.AllFields() {
if field.container == t.Parent {
t.parent = field
break
}
}
}
if annot != nil {
annotations = append(annotations, annot)
}
}
return annotations, nil
}
// GetMediaBox gets the inheritable media box value, either from the page
// or a higher up page/pages struct.
func (p *PdfPage) GetMediaBox() (*PdfRectangle, error) {
if p.MediaBox != nil {
return p.MediaBox, nil
}
node := p.Parent
for node != nil {
dict, ok := core.GetDict(node)
if !ok {
return nil, errors.New("invalid parent objects dictionary")
}
if obj := dict.Get("MediaBox"); obj != nil {
arr, ok := core.GetArray(obj)
if !ok {
return nil, errors.New("invalid media box")
}
rect, err := NewPdfRectangle(*arr)
if err != nil {
return nil, err
}
return rect, nil
}
node = dict.Get("Parent")
}
return nil, errors.New("media box not defined")
}
// getParentResources searches for page resources in the parent nodes of the page.
func (p *PdfPage) getParentResources() (*PdfPageResources, error) {
node := p.Parent
for node != nil {
dict, ok := core.GetDict(node)
if !ok {
common.Log.Debug("ERROR: invalid parent node")
return nil, errors.New("invalid parent object")
}
if obj := dict.Get("Resources"); obj != nil {
prDict, ok := core.GetDict(obj)
if !ok {
return nil, errors.New("invalid resource dict")
}
resources, err := NewPdfPageResourcesFromDict(prDict)
if err != nil {
return nil, err
}
return resources, nil
}
// Keep moving up the tree...
node = dict.Get("Parent")
}
// No resources defined...
return nil, nil
}
// GetPageDict converts the Page to a PDF object dictionary.
func (p *PdfPage) GetPageDict() *core.PdfObjectDictionary {
d := p.pageDict
d.Clear()
d.Set("Type", core.MakeName("Page"))
d.Set("Parent", p.Parent)
if p.LastModified != nil {
d.Set("LastModified", p.LastModified.ToPdfObject())
}
if p.Resources != nil {
d.Set("Resources", p.Resources.ToPdfObject())
}
if p.CropBox != nil {
d.Set("CropBox", p.CropBox.ToPdfObject())
}
if p.MediaBox != nil {
d.Set("MediaBox", p.MediaBox.ToPdfObject())
}
if p.BleedBox != nil {
d.Set("BleedBox", p.BleedBox.ToPdfObject())
}
if p.TrimBox != nil {
d.Set("TrimBox", p.TrimBox.ToPdfObject())
}
if p.ArtBox != nil {
d.Set("ArtBox", p.ArtBox.ToPdfObject())
}
d.SetIfNotNil("BoxColorInfo", p.BoxColorInfo)
d.SetIfNotNil("Contents", p.Contents)
if p.Rotate != nil {
d.Set("Rotate", core.MakeInteger(*p.Rotate))
}
d.SetIfNotNil("Group", p.Group)
d.SetIfNotNil("Thumb", p.Thumb)
d.SetIfNotNil("B", p.B)
d.SetIfNotNil("Dur", p.Dur)
d.SetIfNotNil("Trans", p.Trans)
d.SetIfNotNil("AA", p.AA)
d.SetIfNotNil("Metadata", p.Metadata)
d.SetIfNotNil("PieceInfo", p.PieceInfo)
d.SetIfNotNil("StructParents", p.StructParents)
d.SetIfNotNil("ID", p.ID)
d.SetIfNotNil("PZ", p.PZ)
d.SetIfNotNil("SeparationInfo", p.SeparationInfo)
d.SetIfNotNil("Tabs", p.Tabs)
d.SetIfNotNil("TemplateInstantiated", p.TemplateInstantiated)
d.SetIfNotNil("PresSteps", p.PresSteps)
d.SetIfNotNil("UserUnit", p.UserUnit)
d.SetIfNotNil("VP", p.VP)
if p.annotations != nil {
arr := core.MakeArray()
for _, annot := range p.annotations {
if subannot := annot.GetContext(); subannot != nil {
arr.Append(subannot.ToPdfObject())
} else {
// Generic annotation dict (without subtype).
arr.Append(annot.ToPdfObject())
}
}
if arr.Len() > 0 {
d.Set("Annots", arr)
}
} else if p.Annots != nil {
d.SetIfNotNil("Annots", p.Annots)
}
return d
}
// GetPageAsIndirectObject returns the page as a dictionary within an PdfIndirectObject.
func (p *PdfPage) GetPageAsIndirectObject() *core.PdfIndirectObject {
return p.primitive
}
// GetContainingPdfObject returns the page as a dictionary within an PdfIndirectObject.
func (p *PdfPage) GetContainingPdfObject() core.PdfObject {
return p.primitive
}
// ToPdfObject converts the PdfPage to a dictionary within an indirect object container.
func (p *PdfPage) ToPdfObject() core.PdfObject {
container := p.primitive
p.GetPageDict() // update.
return container
}
// AddImageResource adds an image to the XObject resources.
func (p *PdfPage) AddImageResource(name core.PdfObjectName, ximg *XObjectImage) error {
var xresDict *core.PdfObjectDictionary
if p.Resources.XObject == nil {
xresDict = core.MakeDict()
p.Resources.XObject = xresDict
} else {
var ok bool
xresDict, ok = (p.Resources.XObject).(*core.PdfObjectDictionary)
if !ok {
return errors.New("invalid xres dict type")
}
}
// Make a stream object container.
xresDict.Set(name, ximg.ToPdfObject())
return nil
}
// HasXObjectByName checks if has XObject resource by name.
func (p *PdfPage) HasXObjectByName(name core.PdfObjectName) bool {
xresDict, has := p.Resources.XObject.(*core.PdfObjectDictionary)
if !has {
return false
}
if obj := xresDict.Get(name); obj != nil {
return true
}
return false
}
// GetXObjectByName gets XObject by name.
func (p *PdfPage) GetXObjectByName(name core.PdfObjectName) (core.PdfObject, bool) {
xresDict, has := p.Resources.XObject.(*core.PdfObjectDictionary)
if !has {
return nil, false
}
if obj := xresDict.Get(name); obj != nil {
return obj, true
}
return nil, false
}
// HasFontByName checks if has font resource by name.
func (p *PdfPage) HasFontByName(name core.PdfObjectName) bool {
fontDict, has := p.Resources.Font.(*core.PdfObjectDictionary)
if !has {
return false
}
if obj := fontDict.Get(name); obj != nil {
return true
}
return false
}
// HasExtGState checks if ExtGState name is available.
func (p *PdfPage) HasExtGState(name core.PdfObjectName) bool {
if p.Resources == nil {
return false
}
if p.Resources.ExtGState == nil {
return false
}
egsDict, ok := core.TraceToDirectObject(p.Resources.ExtGState).(*core.PdfObjectDictionary)
if !ok {
common.Log.Debug("Expected ExtGState dictionary is not a dictionary: %v", core.TraceToDirectObject(p.Resources.ExtGState))
return false
}
// Update the dictionary.
obj := egsDict.Get(name)
has := obj != nil
return has
}
// AddExtGState adds a graphics state to the XObject resources.
func (p *PdfPage) AddExtGState(name core.PdfObjectName, egs *core.PdfObjectDictionary) error {
if p.Resources == nil {
//p.Resources = &PdfPageResources{}
p.Resources = NewPdfPageResources()
}
if p.Resources.ExtGState == nil {
p.Resources.ExtGState = core.MakeDict()
}
egsDict, ok := core.TraceToDirectObject(p.Resources.ExtGState).(*core.PdfObjectDictionary)
if !ok {
common.Log.Debug("Expected ExtGState dictionary is not a dictionary: %v", core.TraceToDirectObject(p.Resources.ExtGState))
return errors.New("type check error")
}
egsDict.Set(name, egs)
return nil
}
// AddFont adds a font dictionary to the Font resources.
func (p *PdfPage) AddFont(name core.PdfObjectName, font core.PdfObject) error {
if p.Resources == nil {
p.Resources = NewPdfPageResources()
}
if p.Resources.Font == nil {
p.Resources.Font = core.MakeDict()
}
fontDict, ok := core.TraceToDirectObject(p.Resources.Font).(*core.PdfObjectDictionary)
if !ok {
common.Log.Debug("Expected font dictionary is not a dictionary: %v", core.TraceToDirectObject(p.Resources.Font))
return errors.New("type check error")
}
// Update the dictionary.
fontDict.Set(name, font)
return nil
}
// WatermarkImageOptions contains options for configuring the watermark process.
type WatermarkImageOptions struct {
Alpha float64
FitToWidth bool
PreserveAspectRatio bool
}
// AddWatermarkImage adds a watermark to the page.
func (p *PdfPage) AddWatermarkImage(ximg *XObjectImage, opt WatermarkImageOptions) error {
// Page dimensions.
bbox, err := p.GetMediaBox()
if err != nil {
return err
}
pWidth := bbox.Urx - bbox.Llx
pHeight := bbox.Ury - bbox.Lly
wWidth := float64(*ximg.Width)
xOffset := (float64(pWidth) - float64(wWidth)) / 2
if opt.FitToWidth {
wWidth = pWidth
xOffset = 0
}
wHeight := pHeight
yOffset := float64(0)
if opt.PreserveAspectRatio {
wHeight = wWidth * float64(*ximg.Height) / float64(*ximg.Width)
yOffset = (pHeight - wHeight) / 2
}
if p.Resources == nil {
p.Resources = NewPdfPageResources()
}
// Find available image name for this page.
i := 0
imgName := core.PdfObjectName(fmt.Sprintf("Imw%d", i))
for p.Resources.HasXObjectByName(imgName) {
i++
imgName = core.PdfObjectName(fmt.Sprintf("Imw%d", i))
}
err = p.AddImageResource(imgName, ximg)
if err != nil {
return err
}
i = 0
gsName := core.PdfObjectName(fmt.Sprintf("GS%d", i))
for p.HasExtGState(gsName) {
i++
gsName = core.PdfObjectName(fmt.Sprintf("GS%d", i))
}
gs0 := core.MakeDict()
gs0.Set("BM", core.MakeName("Normal"))
gs0.Set("CA", core.MakeFloat(opt.Alpha))
gs0.Set("ca", core.MakeFloat(opt.Alpha))
err = p.AddExtGState(gsName, gs0)
if err != nil {
return err
}
contentStr := fmt.Sprintf("q\n"+
"/%s gs\n"+
"%.0f 0 0 %.0f %.4f %.4f cm\n"+
"/%s Do\n"+
"Q", gsName, wWidth, wHeight, xOffset, yOffset, imgName)
p.AddContentStreamByString(contentStr)
return nil
}
// AddContentStreamByString adds content stream by string. Puts the content
// string into a stream object and points the content stream towards it.
func (p *PdfPage) AddContentStreamByString(contentStr string) error {
stream, err := core.MakeStream([]byte(contentStr), core.NewFlateEncoder())
if err != nil {
return err
}
if p.Contents == nil {
// If not set, place it directly.
p.Contents = stream
} else if contArray, isArray := core.GetArray(p.Contents); isArray {
// If an array of content streams, append it.
contArray.Append(stream)
} else {
// Only 1 element in place. Wrap inside a new array and add the new one.
contArray := core.MakeArray(p.Contents, stream)
p.Contents = contArray
}
return nil
}
// AppendContentStream adds content stream by string. Appends to the last
// contentstream instance if many.
func (p *PdfPage) AppendContentStream(contentStr string) error {
cstreams, err := p.GetContentStreams()
if err != nil {
return err
}
if len(cstreams) == 0 {
cstreams = []string{contentStr}
return p.SetContentStreams(cstreams, core.NewFlateEncoder())
}
var buf bytes.Buffer
buf.WriteString(cstreams[len(cstreams)-1])
buf.WriteString("\n")
buf.WriteString(contentStr)
cstreams[len(cstreams)-1] = buf.String()
return p.SetContentStreams(cstreams, core.NewFlateEncoder())
}
// SetContentStreams sets the content streams based on a string array. Will make
// 1 object stream for each string and reference from the page Contents.
// Each stream will be encoded using the encoding specified by the StreamEncoder,
// if empty, will use identity encoding (raw data).
func (p *PdfPage) SetContentStreams(cStreams []string, encoder core.StreamEncoder) error {
if len(cStreams) == 0 {
p.Contents = nil
return nil
}
// If encoding is not set, use default raw encoder.
if encoder == nil {
encoder = core.NewRawEncoder()
}
var streamObjs []*core.PdfObjectStream
for _, cStream := range cStreams {
stream := &core.PdfObjectStream{}
// Make a new stream dict based on the encoding parameters.
sDict := encoder.MakeStreamDict()
encoded, err := encoder.EncodeBytes([]byte(cStream))
if err != nil {
return err
}
sDict.Set("Length", core.MakeInteger(int64(len(encoded))))
stream.PdfObjectDictionary = sDict
stream.Stream = []byte(encoded)
streamObjs = append(streamObjs, stream)
}
// Set the page contents.
// Point directly to the object stream if only one, or embed in an array.
if len(streamObjs) == 1 {
p.Contents = streamObjs[0]
} else {
contArray := core.MakeArray()
for _, streamObj := range streamObjs {
contArray.Append(streamObj)
}
p.Contents = contArray
}
return nil
}
func getContentStreamAsString(cstreamObj core.PdfObject) (string, error) {
cstreamObj = core.TraceToDirectObject(cstreamObj)
switch v := cstreamObj.(type) {
case *core.PdfObjectString:
return v.Str(), nil
case *core.PdfObjectStream:
buf, err := core.DecodeStream(v)
if err != nil {
return "", err
}
return string(buf), nil
}
return "", fmt.Errorf("invalid content stream object holder (%T)", cstreamObj)
}
// GetContentStreams returns the content stream as an array of strings.
func (p *PdfPage) GetContentStreams() ([]string, error) {
if p.Contents == nil {
return nil, nil
}
contents := core.TraceToDirectObject(p.Contents)
var cStreamObjs []core.PdfObject
if contArray, ok := contents.(*core.PdfObjectArray); ok {
cStreamObjs = contArray.Elements()
} else {
cStreamObjs = []core.PdfObject{contents}
}
var cStreams []string
for _, cStreamObj := range cStreamObjs {
cStreamStr, err := getContentStreamAsString(cStreamObj)
if err != nil {
return nil, err
}
cStreams = append(cStreams, cStreamStr)
}
return cStreams, nil
}
// GetAllContentStreams gets all the content streams for a page as one string.
func (p *PdfPage) GetAllContentStreams() (string, error) {
cstreams, err := p.GetContentStreams()
if err != nil {
return "", err
}
return strings.Join(cstreams, " "), nil
}
// PdfPageResourcesColorspaces contains the colorspace in the PdfPageResources.
// Needs to have matching name and colorspace map entry. The Names define the order.
type PdfPageResourcesColorspaces struct {
Names []string
Colorspaces map[string]PdfColorspace
container *core.PdfIndirectObject
}
// NewPdfPageResourcesColorspaces returns a new PdfPageResourcesColorspaces object.
func NewPdfPageResourcesColorspaces() *PdfPageResourcesColorspaces {
colorspaces := &PdfPageResourcesColorspaces{}
colorspaces.Names = []string{}
colorspaces.Colorspaces = map[string]PdfColorspace{}
colorspaces.container = &core.PdfIndirectObject{}
return colorspaces
}
// Set sets the colorspace corresponding to key. Add to Names if not set.
func (rcs *PdfPageResourcesColorspaces) Set(key core.PdfObjectName, val PdfColorspace) {
if _, has := rcs.Colorspaces[string(key)]; !has {
rcs.Names = append(rcs.Names, string(key))
}
rcs.Colorspaces[string(key)] = val
}
func newPdfPageResourcesColorspacesFromPdfObject(obj core.PdfObject) (*PdfPageResourcesColorspaces, error) {
colorspaces := &PdfPageResourcesColorspaces{}
if indObj, isIndirect := obj.(*core.PdfIndirectObject); isIndirect {
colorspaces.container = indObj
obj = indObj.PdfObject
}
dict, ok := core.GetDict(obj)
if !ok {
return nil, errors.New("CS attribute type error")
}
colorspaces.Names = []string{}
colorspaces.Colorspaces = map[string]PdfColorspace{}
for _, csName := range dict.Keys() {
csObj := dict.Get(csName)
colorspaces.Names = append(colorspaces.Names, string(csName))
cs, err := NewPdfColorspaceFromPdfObject(csObj)
if err != nil {
return nil, err
}
colorspaces.Colorspaces[string(csName)] = cs
}
return colorspaces, nil
}
// ToPdfObject returns the PDF representation of the colorspace.
func (rcs *PdfPageResourcesColorspaces) ToPdfObject() core.PdfObject {
dict := core.MakeDict()
for _, csName := range rcs.Names {
dict.Set(core.PdfObjectName(csName), rcs.Colorspaces[csName].ToPdfObject())
}
if rcs.container != nil {
rcs.container.PdfObject = dict
return rcs.container
}
return dict
}
|
willlunniss/andlytics | src/com/github/andlyticsproject/db/AppInfoTable.java | <filename>src/com/github/andlyticsproject/db/AppInfoTable.java<gh_stars>100-1000
package com.github.andlyticsproject.db;
import java.util.HashMap;
import android.net.Uri;
public class AppInfoTable {
public static final String DATABASE_TABLE_NAME = "appinfo";
public static final String UNIQUE_PACKAGE_NAMES = "appinfo/unique-packages";
public static final Uri CONTENT_URI = Uri.parse("content://"
+ AndlyticsContentProvider.AUTHORITY + "/" + DATABASE_TABLE_NAME);
public static final Uri UNIQUE_PACAKGES_CONTENT_URI = Uri.parse("content://"
+ AndlyticsContentProvider.AUTHORITY + "/" + UNIQUE_PACKAGE_NAMES);
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.andlytics."
+ DATABASE_TABLE_NAME;
public static final String KEY_ROWID = "_id";
public static final String KEY_APP_PACKAGENAME = "packagename";
public static final String KEY_APP_ACCOUNT = "account";
public static final String KEY_APP_LASTUPDATE = "lastupdate";
public static final String KEY_APP_NAME = "name";
public static final String KEY_APP_CATEGORY = "category";
public static final String KEY_APP_PUBLISHSTATE = "publishstate";
public static final String KEY_APP_ICONURL = "iconurl";
public static final String KEY_APP_GHOST = "ghost";
public static final String KEY_APP_RATINGS_EXPANDED = "ratingsexpanded";
public static final String KEY_APP_SKIP_NOTIFICATION = "skipnotification";
public static final String KEY_APP_VERSION_NAME = "versionname";
public static final String KEY_APP_ADMOB_ACCOUNT = "admobaccount";
public static final String KEY_APP_ADMOB_SITE_ID = "admobsiteid";
public static final String KEY_APP_ADMOB_AD_UNIT_ID = "admobadunitid";
public static final String KEY_APP_LAST_COMMENTS_UPDATE = "lastcommentsupdate";
public static final String KEY_APP_DEVELOPER_ID = "developerid";
public static final String KEY_APP_DEVELOPER_NAME = "developername";
public static final String TABLE_CREATE_APPINFO = "create table " + DATABASE_TABLE_NAME
+ " (_id integer primary key autoincrement, " + KEY_APP_PACKAGENAME + " text not null,"
+ KEY_APP_ACCOUNT + " text not null," + KEY_APP_LASTUPDATE + " date," + KEY_APP_NAME
+ " text," + KEY_APP_ICONURL + " text," + KEY_APP_CATEGORY + " text,"
+ KEY_APP_PUBLISHSTATE + " integer," + KEY_APP_GHOST + " integer,"
+ KEY_APP_RATINGS_EXPANDED + " integer," + KEY_APP_SKIP_NOTIFICATION + " integer,"
+ KEY_APP_VERSION_NAME + " text, " + KEY_APP_ADMOB_ACCOUNT + " text, "
+ KEY_APP_ADMOB_SITE_ID + " text, " + KEY_APP_ADMOB_AD_UNIT_ID + " text, "
+ KEY_APP_LAST_COMMENTS_UPDATE + " date, " + KEY_APP_DEVELOPER_ID + " text, "
+ KEY_APP_DEVELOPER_NAME + " text)";
public static HashMap<String, String> PROJECTION_MAP;
public static HashMap<String, String> PACKAGE_NAMES_MAP;
static {
PROJECTION_MAP = new HashMap<String, String>();
PROJECTION_MAP.put(AppInfoTable.KEY_ROWID, AppInfoTable.KEY_ROWID);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_PACKAGENAME, AppInfoTable.KEY_APP_PACKAGENAME);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_ACCOUNT, AppInfoTable.KEY_APP_ACCOUNT);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_LASTUPDATE, AppInfoTable.KEY_APP_LASTUPDATE);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_NAME, AppInfoTable.KEY_APP_NAME);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_CATEGORY, AppInfoTable.KEY_APP_CATEGORY);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_PUBLISHSTATE, AppInfoTable.KEY_APP_PUBLISHSTATE);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_ICONURL, AppInfoTable.KEY_APP_ICONURL);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_GHOST, AppInfoTable.KEY_APP_GHOST);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_RATINGS_EXPANDED,
AppInfoTable.KEY_APP_RATINGS_EXPANDED);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_SKIP_NOTIFICATION,
AppInfoTable.KEY_APP_SKIP_NOTIFICATION);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_VERSION_NAME, AppInfoTable.KEY_APP_VERSION_NAME);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_ADMOB_ACCOUNT, AppInfoTable.KEY_APP_ADMOB_ACCOUNT);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_ADMOB_SITE_ID, AppInfoTable.KEY_APP_ADMOB_SITE_ID);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_ADMOB_AD_UNIT_ID,
AppInfoTable.KEY_APP_ADMOB_AD_UNIT_ID);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_LAST_COMMENTS_UPDATE,
AppInfoTable.KEY_APP_LAST_COMMENTS_UPDATE);
PROJECTION_MAP.put(AppInfoTable.KEY_APP_DEVELOPER_ID, AppInfoTable.KEY_APP_DEVELOPER_ID);
PROJECTION_MAP
.put(AppInfoTable.KEY_APP_DEVELOPER_NAME, AppInfoTable.KEY_APP_DEVELOPER_NAME);
PACKAGE_NAMES_MAP = new HashMap<String, String>();
PACKAGE_NAMES_MAP.put(AppInfoTable.KEY_APP_PACKAGENAME, AppInfoTable.KEY_APP_PACKAGENAME);
}
}
|
GirZ0n/SPBU-Homework-1 | Homework_4/Task_2/Task_2.c | <reponame>GirZ0n/SPBU-Homework-1
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include "phonebook.h"
extern const int maxStringSize;
void getName(char* name, char* firstName, char* secondName)
{
scanf("%s %s", firstName, secondName);
name[0] = '\0';
strcat(name, firstName);
strcat(name, " ");
strcat(name, secondName);
}
char* createString(int size)
{
char* newString = malloc(sizeof(char) * size);
for (int i = 0; i < size; i++)
{
newString[i] = '\0';
}
return newString;
}
int main()
{
int phoneBookCapacity = 2;
int phoneBookSize = 0;
FILE* input = fopen("Phone_book.txt", "r");
struct Entry* phoneBook = phoneBookInit(&phoneBookSize, &phoneBookCapacity, input);
int numberOfEntries = phoneBookSize;
if (input != NULL)
{
fclose(input);
}
printf("Select an action from the suggestions below.\n");
printf("0 - Exit;\n");
printf("1 - Add telephone directory entry;\n");
printf("2 - Find phone number by name;\n");
printf("3 - Find name by phone number;\n");
printf("4 - Save current data to a file.\n\n");
printf("Attention! The phone number must be entered in the international format: +12345678...\n");
char* name = createString(maxStringSize);
char* firstName = createString(maxStringSize);
char* secondName = createString(maxStringSize);
char* phoneNumber = createString(maxStringSize);
int action = 0;
while (true)
{
printf("\n");
printf("Your action: ");
scanf("%d", &action);
switch (action)
{
case 0:
{
printf("Have a nice day! Bye :)");
return 0;
}
case 1:
{
printf("Enter first and last name: ");
getName(name, firstName, secondName);
printf("Enter phone number: ");
scanf("%s", phoneNumber);
phoneBook = addEntry(phoneBook, &phoneBookSize, &phoneBookCapacity, name, phoneNumber);
break;
}
case 2:
{
printf("Enter first and last name: ");
getName(name, firstName, secondName);
if (getPhoneByName(phoneBook, phoneBookSize, name, phoneNumber))
{
printf("Result: %s - %s\n", name, phoneNumber);
}
else
{
printf("The name is not in the phone book.\n");
}
break;
}
case 3:
{
printf("Enter the phone number: ");
scanf("%s", phoneNumber);
if (getNameByPhone(phoneBook, phoneBookSize, name, phoneNumber))
{
printf("Result: %s - %s\n", name, phoneNumber);
}
else
{
printf("The phone number is not in the phone book.\n");
}
break;
}
case 4:
{
FILE* output = fopen("Phone_book.txt", "a");
saveData(phoneBook, phoneBookSize, &numberOfEntries, output);
fclose(output);
break;
}
default:
{
printf("Enter the correct action.\n");
break;
}
}
}
}
|
chenpota/python | type-hints/example/12_decorator.py | <reponame>chenpota/python
import functools
from typing import TypeVar, cast
import decorator
#######################################
T = TypeVar('T')
def my_decorator(f: T) -> T:
@functools.wraps(f) # type: ignore
def wrapper(*args, **kwargs):
return f(*args, **kwargs) # type: ignore
return cast(T, wrapper)
@my_decorator
def func(v: int) -> None:
pass
func(3)
func('3') # error
|
atul-vyshnav/2021_IBM_Code_Challenge_StockIT | src/StockIT-v2-release_source_from_JADX/sources/com/google/android/gms/internal/firebase_messaging/zza.java | package com.google.android.gms.internal.firebase_messaging;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
public class zza extends Handler {
private static volatile zzb zza;
public zza() {
}
public zza(Looper looper) {
super(looper);
}
public zza(Looper looper, Handler.Callback callback) {
super(looper, callback);
}
public final void dispatchMessage(Message message) {
super.dispatchMessage(message);
}
}
|
Kwak-JunYoung/154Algoritm-5weeks | before/0214/7576.py | <reponame>Kwak-JunYoung/154Algoritm-5weeks<filename>before/0214/7576.py
from collections import deque
n, m = list(map(int, input().split()))
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def bfs(graph):
queue = deque([])
for x in range(m):
for y in range(n):
if graph[x][y] == 1:
queue.extend([x, y])
while queue:
current_x = queue.popleft()
current_y = queue.popleft()
for i in range(4):
new_x = current_x + dx[i]
new_y = current_y + dy[i]
if new_x not in range(m) or new_y not in range(n):
continue
if graph[new_x][new_y] == 0:
graph[new_x][new_y] = graph[current_x][current_y] + 1
queue.extend([new_x, new_y])
for g in graph:
if 0 in g:
return -1
return max(list(map(max, graph))) - 1
tomatoes = [[] for _ in range(m)]
for i in range(m):
tomatoes[i] = list(map(int, input().split()))
print(bfs(tomatoes)) |
Limingming2/yoloo_topondemo | topon571_fix/Pods/Headers/Public/DoraemonKit/DoraemonCPUViewController.h | //
// DoraemonCPUViewController.h
// DoraemonKit-DoraemonKit
//
// Created by yixiang on 2018/1/12.
//
#import "DoraemonBaseViewController.h"
@interface DoraemonCPUViewController : DoraemonBaseViewController
@end
|
TirthrajRao/spurtV2 | models/customerwishlist.model.js | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var customerwishlist = new Schema({
customer_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'customer'
},
product_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'product'
},
is_active: {
type:Number
},
created_date: {
type: Date,
Default:new Date()
},
modified_date: {
type: Date,
Default:new Date()
},
created_by: {
type: String,
Default: null
},
modified_by: {
type: String,
Default: null
}
});
module.exports = mongoose.model('customerwishlist', customerwishlist, 'customer_wishlist'); |
smart-cow/scow | cow-server/src/main/java/org/wiredwidgets/cow/server/transform/graph/bpmn20/Bpmn20ProcessBuilder.java | <filename>cow-server/src/main/java/org/wiredwidgets/cow/server/transform/graph/bpmn20/Bpmn20ProcessBuilder.java
/**
* Approved for Public Release: 10-4800. Distribution Unlimited.
* Copyright 2014 The MITRE 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.wiredwidgets.cow.server.transform.graph.bpmn20;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.omg.spec.bpmn._20100524.model.Definitions;
import org.omg.spec.bpmn._20100524.model.IoSpecification;
import org.omg.spec.bpmn._20100524.model.TActivity;
import org.omg.spec.bpmn._20100524.model.TFlowNode;
import org.omg.spec.bpmn._20100524.model.TFormalExpression;
import org.omg.spec.bpmn._20100524.model.TProcess;
import org.omg.spec.bpmn._20100524.model.TSequenceFlow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wiredwidgets.cow.server.api.model.v2.Activity;
import org.wiredwidgets.cow.server.api.model.v2.Process;
import org.wiredwidgets.cow.server.api.model.v2.Variable;
import org.wiredwidgets.cow.server.transform.AbstractProcessBuilder;
import org.wiredwidgets.cow.server.transform.graph.ActivityEdge;
import org.wiredwidgets.cow.server.transform.graph.ActivityGraph;
import org.wiredwidgets.cow.server.transform.graph.builder.GraphBuilder;
/**
*
* @author JKRANES
*/
@Component
public class Bpmn20ProcessBuilder extends AbstractProcessBuilder<Definitions> {
public static final String VARIABLES_PROPERTY = "variables";
public static final String PROCESS_INSTANCE_NAME_PROPERTY = "processInstanceName";
public static final String PROCESS_EXIT_PROPERTY = "processExitState";
private static final String BPMN20_MODEL_NAMESPACE = "http://www.omg.org/spec/BPMN/20100524/MODEL";
private static final String STRING_CLASS_NAME = String.class.getSimpleName();
@Autowired
GraphBuilder graphBuilder;
@Autowired
NodeBuilderService nodeBuilderService;
@Override
public Definitions build(Process source) {
Bpmn20ProcessContext context = new Bpmn20ProcessContext(source, new TProcess());
if (source.getMaxId() > 0) {
context.setRevised(true);
}
context.setStartId("_", source.getMaxId());
// Every process has a Map for ad-hoc content
context.addProcessVariable(VARIABLES_PROPERTY, Map.class.getCanonicalName());
// Name for the process instance
context.addProcessVariable(PROCESS_INSTANCE_NAME_PROPERTY, STRING_CLASS_NAME);
// Used with Exit actions to specify which action was taken
context.addProcessVariable(PROCESS_EXIT_PROPERTY, STRING_CLASS_NAME);
// Add any additional variables defined in the workflow
if (source.getVariables() != null) {
for (Variable var : source.getVariables().getVariables()) {
context.addProcessVariable(var.getName(), STRING_CLASS_NAME);
}
}
// build the activity graph
ActivityGraph graph = graphBuilder.buildGraph(source);
// put vertices in a list. We need them in a defined order.
List<Activity> activityVertices = new ArrayList<Activity>();
activityVertices.addAll(graph.vertexSet());
// create a new graph to hold created nodes
NodeGraph nodeGraph = new NodeGraph();
// initialize a corresponding list of Nodes
List<Bpmn20Node> nodeVertices = new ArrayList<Bpmn20Node>();
// build the nodes in the order defined by the list and add them to the nodeGraph
// in the same order
for (Activity activity : activityVertices) {
Bpmn20Node node = nodeBuilderService.buildNode(activity, context);
nodeVertices.add(node);
nodeGraph.addVertex(node);
}
// add edges to connect the nodes, using the list index positions
// to connect the new nodes in the same structure as the activity graph
for (ActivityEdge edge : graph.edgeSet()) {
// identify the corresponding node vertices
int sourceIndex = activityVertices.indexOf(graph.getEdgeSource(edge));
int targetIndex = activityVertices.indexOf(graph.getEdgeTarget(edge));
// create an edge for corresponding nodes
Bpmn20Edge nodeEdge = nodeGraph.addEdge(nodeVertices.get(sourceIndex), nodeVertices.get(targetIndex));
// create reference back to the ActivityEdge
// this is currently used for Decisions to construct the edge expression
nodeEdge.setActivityEdge(edge);
}
// Add the nodes to the BPMN20 object set
for (Bpmn20Node node : nodeGraph.vertexSet()) {
context.addNode(node);
}
// Add the edes to the BPMN20 object set
for (Bpmn20Edge edge : nodeGraph.edgeSet()) {
addEdge(context, nodeGraph, edge);
}
source.setMaxId(context.getId("_"));
return context.getDefinitions();
}
/**
* Add a transition (sequenceFlow) with a FormalExpression
* @param target
* @param transitionName
* @param expression
*/
private void addEdge(Bpmn20ProcessContext context, NodeGraph graph, Bpmn20Edge edge) {
TSequenceFlow sequenceFlow = new TSequenceFlow();
TFlowNode sourceNode = graph.getEdgeSource(edge).getNode().getValue();
TFlowNode targetNode = graph.getEdgeTarget(edge).getNode().getValue();
// follow convention of concatenating source and targetIds to form the sequence ID
String sequenceId = sourceNode.getId() + targetNode.getId();
sequenceFlow.setId(sequenceId);
sequenceFlow.setSourceRef(sourceNode);
sequenceFlow.setTargetRef(targetNode);
if (edge.getActivityEdge().getExpression() != null) {
// this edge represents a decision path
// set the name (for display purposes)
sequenceFlow.setName(edge.getActivityEdge().getExpression());
// create the expression that will be evaluated when selecting a path
// the name of the decision variable is based on the ID of the node
// which at this point has also been copied to the Key of the corresponding Activity
String varName = DecisionTaskNodeBuilder.getDecisionVarName(edge.getActivityEdge().getVarSource().getKey());
String expression = "return " + varName + " == \"" + edge.getActivityEdge().getExpression() + "\";";
TFormalExpression expr = new TFormalExpression();
expr.getContent().add(expression);
sequenceFlow.setConditionExpression(expr);
}
context.addEdge(sequenceFlow);
// incomings and outgoings are required by igrafx
sourceNode.getOutgoings().add(new QName(BPMN20_MODEL_NAMESPACE, sequenceFlow.getId()));
targetNode.getIncomings().add(new QName(BPMN20_MODEL_NAMESPACE, sequenceFlow.getId()));
}
}
|
mosermw/nifi | nifi/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-cluster-web/src/main/java/org/apache/nifi/cluster/context/ClusterContext.java | <gh_stars>0
/*
* 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.nifi.cluster.context;
import java.io.Serializable;
import java.util.List;
import org.apache.nifi.action.Action;
import org.apache.nifi.web.Revision;
/**
* Contains contextual information about clustering that may be serialized
* between manager and node when communicating over HTTP.
*/
public interface ClusterContext extends Serializable {
/**
* Returns a list of auditable actions. The list is modifiable
* and will never be null.
* @return a collection of actions
*/
List<Action> getActions();
Revision getRevision();
void setRevision(Revision revision);
/**
* @return true if the request was sent by the cluster manager; false otherwise
*/
boolean isRequestSentByClusterManager();
/**
* Sets the flag to indicate if a request was sent by the cluster manager.
* @param flag true if the request was sent by the cluster manager; false otherwise
*/
void setRequestSentByClusterManager(boolean flag);
/**
* Gets an id generation seed. This is used to ensure that nodes are able to generate the
* same id across the cluster. This is usually handled by the cluster manager creating the
* id, however for some actions (snippets, templates, etc) this is not possible.
* @return
*/
String getIdGenerationSeed();
}
|
JayMonari/java-personal | java-spring-blog/src/main/java/xyz/blog/thejaysics/service/AuthService.java | <gh_stars>0
package xyz.blog.thejaysics.service;
import java.util.Optional;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;
import xyz.blog.thejaysics.dto.AuthenticationResponse;
import xyz.blog.thejaysics.dto.LoginRequest;
import xyz.blog.thejaysics.dto.RegisterRequest;
import xyz.blog.thejaysics.model.User;
import xyz.blog.thejaysics.repository.UserRepository;
import xyz.blog.thejaysics.security.JwtProvider;
@Service
@AllArgsConstructor
public class AuthService {
private UserRepository userRepository;
private PasswordEncoder passwordEncoder;
private AuthenticationManager authenticationManager;
private JwtProvider jwtProvider;
public void signup(RegisterRequest registerRequest) {
User user = User.builder()
.username(registerRequest.getUsername())
.email(registerRequest.getEmail())
.password(passwordEncoder.encode(registerRequest.getPassword()))
.build();
userRepository.save(user);
}
public AuthenticationResponse login(LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String authenticationToken = jwtProvider.generateToken(authentication);
return new AuthenticationResponse(authenticationToken, loginRequest.getUsername());
}
public Optional<org.springframework.security.core.userdetails.User> getCurrentUser() {
org.springframework.security.core.userdetails.User principal =
(org.springframework.security.core.userdetails.User)
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return Optional.of(principal);
}
}
|
wolfman199311/laravel_react.js | admin/src/pages/apps/Ecommerce/Checkout/Shipping.js | // flow
import React from 'react';
import { Row, Col, Button } from 'reactstrap';
import { AvForm, AvField } from 'availity-reactstrap-validation';
import { Link } from 'react-router-dom';
import Select from 'react-select';
import MaskedInput from 'react-text-mask';
import { countries } from './Data';
// Shipping
const Shipping = props => {
const updateShippingCost = props.updateShipping || {};
return (
<React.Fragment>
<Row>
<Col>
<h4 className="mt-2">Saved Address</h4>
<p className="text-muted mb-3">Fill the form below in order to send you the order's invoice.</p>
<Row>
<Col md={6}>
<div className="border p-3 rounded">
<address className="mb-0 font-14 address-lg">
<div className="custom-control custom-radio">
<input
type="radio"
id="customRadio1"
name="customRadio"
className="custom-control-input"
defaultChecked
/>
<label
className="custom-control-label font-16 font-weight-bold"
htmlFor="customRadio1">
Home
</label>
</div>
<br />
<span className="font-weight-semibold"><NAME></span> <br />
795 Folsom Ave, Suite 600
<br />
San Francisco, CA 94107
<br />
<abbr title="Phone">P:</abbr> (123) 456-7890 <br />
</address>
</div>
</Col>
<Col md={6}>
<div className="border p-3 rounded">
<address className="mb-0 font-14 address-lg">
<div className="custom-control custom-radio">
<input
type="radio"
id="customRadio2"
name="customRadio"
className="custom-control-input"
/>
<label
className="custom-control-label font-16 font-weight-bold"
htmlFor="customRadio2">
office
</label>
</div>
<br />
<span className="font-weight-semibold"><NAME></span> <br />
795 Folsom Ave, Suite 600
<br />
San Francisco, CA 94107
<br />
<abbr title="Phone">P:</abbr> (123) 456-7890 <br />
</address>
</div>
</Col>
</Row>
<h4 className="mt-4">Add New Address</h4>
<p className="text-muted mb-4">Fill the form below so we can send you the order's invoice.</p>
<AvForm>
<Row>
<Col md={6}>
<AvField
name="firstname"
label="First Name"
type="text"
placeholder="Enter your first name"
required
/>
</Col>
<Col md={6}>
<AvField
name="lastname"
label="Last Name"
type="text"
placeholder="Enter your last name"
required
/>
</Col>
</Row>
<Row>
<Col md={6}>
<AvField
name="email"
label="Email Address"
type="email"
placeholder="Enter your email"
required
/>
</Col>
<Col md={6}>
<div className="form-group">
<label>Phone</label>
<MaskedInput
mask={[
'(',
/[1-9]/,
/\d/,
/\d/,
')',
' ',
/\d/,
/\d/,
/\d/,
'-',
/\d/,
/\d/,
/\d/,
/\d/,
]}
placeholder="(xxx) xxxx-xxxx"
className="form-control"
/>
</div>
</Col>
</Row>
<Row>
<Col md={12}>
<AvField name="address" label="Address" type="text" placeholder="Enter full address" />
</Col>
</Row>
<Row>
<Col md={4}>
<AvField
name="city"
label="Town / City"
type="text"
placeholder="Enter your town / city"
/>
</Col>
<Col md={4}>
<AvField name="state" label="State" type="text" placeholder="Enter your state" />
</Col>
<Col md={4}>
<AvField
name="zip"
label="Zip / Postal Code"
type="text"
placeholder="Enter your zip"
/>
</Col>
</Row>
<Row>
<Col md={12}>
<div className="form-group">
<label>Country</label>
<Select
className="react-select"
classNamePrefix="react-select"
options={countries}></Select>
</div>
</Col>
</Row>
<h4 className="mt-4">Shipping Method</h4>
<p className="text-muted mb-3">Fill the form below in order to send you the order's invoice.</p>
<Row>
<Col md={6}>
<div className="border p-3 rounded">
<div className="custom-control custom-radio">
<input
type="radio"
id="shippingMethodRadio1"
name="shippingOptions"
className="custom-control-input"
defaultChecked
onChange={e => {
updateShippingCost(0);
}}
/>
<label
className="custom-control-label font-16 font-weight-bold"
htmlFor="shippingMethodRadio1">
Standard Delivery - FREE
</label>
</div>
<p className="mb-0 pl-3 pt-1">
Estimated 5-7 days shipping (Duties and tax may be due upon delivery)
</p>
</div>
</Col>
<Col md={6}>
<div className="border p-3 rounded">
<div className="custom-control custom-radio">
<input
type="radio"
id="shippingMethodRadio2"
name="shippingOptions"
className="custom-control-input"
onChange={e => {
updateShippingCost(25);
}}
/>
<label
className="custom-control-label font-16 font-weight-bold"
htmlFor="shippingMethodRadio2">
Fast Delivery - $25
</label>
</div>
<p className="mb-0 pl-3 pt-1">
Estimated 1-2 days shipping (Duties and tax may be due upon delivery)
</p>
</div>
</Col>
</Row>
<Row className="mt-4">
<Col sm={6}>
<Link
to="/"
className="btn text-muted d-none d-sm-inline-block btn-link font-weight-semibold">
<i className="mdi mdi-arrow-left"></i> Back to Shopping Cart{' '}
</Link>
</Col>
<Col sm={6} className="text-sm-right">
<Button color="primary" type="submit">
<i className="mdi mdi-cash-multiple mr-1"></i> Continue to Payment
</Button>
</Col>
</Row>
</AvForm>
</Col>
</Row>
</React.Fragment>
);
};
export default Shipping;
|
VGTsome/smartStorage | server/api/v1/smartStorageOrder.go | package v1
import (
"fmt"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
resp "gin-vue-admin/model/response"
"gin-vue-admin/service"
"strconv"
"github.com/gin-gonic/gin"
)
// @Tags SmartStorageOrder
// @Summary 创建SmartStorageOrder
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SmartStorageOrder true "创建SmartStorageOrder"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /smartStorageOrder/createSmartStorageOrder [post]
func CreateSmartStorageOrder(c *gin.Context) {
var SSOLRQ request.SmartStorageOrderListReq
_ = c.ShouldBindJSON(&SSOLRQ)
userId, err1 := strconv.Atoi(c.Request.Header.Get("x-user-id"))
if err1 != nil {
userId = 0
}
err := service.CreateSmartStorageOrder(SSOLRQ, userId)
if err != nil {
response.FailWithMessage(fmt.Sprintf("创建失败,%v", err), c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// @Tags SmartStorageOrder
// @Summary 删除SmartStorageOrder
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SmartStorageOrder true "删除SmartStorageOrder"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /smartStorageOrder/deleteSmartStorageOrder [delete]
func DeleteSmartStorageOrder(c *gin.Context) {
var smartStorageOrder model.SmartStorageOrder
_ = c.ShouldBindJSON(&smartStorageOrder)
if service.GetSystemStatus() != 101 {
response.FailWithMessage("删除失败,系统状态不正确", c)
return
}
err := service.DeleteSmartStorageOrder(smartStorageOrder)
if err != nil {
response.FailWithMessage(fmt.Sprintf("删除失败,%v", err), c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags SmartStorageOrder
// @Summary 批量删除SmartStorageOrder
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除SmartStorageOrder"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /smartStorageOrder/deleteSmartStorageOrderByIds [delete]
func DeleteSmartStorageOrderByIds(c *gin.Context) {
var IDS request.IdsReq
_ = c.ShouldBindJSON(&IDS)
err := service.DeleteSmartStorageOrderByIds(IDS)
if err != nil {
response.FailWithMessage(fmt.Sprintf("删除失败,%v", err), c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags SmartStorageOrder
// @Summary 更新SmartStorageOrder
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SmartStorageOrder true "更新SmartStorageOrder"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /smartStorageOrder/updateSmartStorageOrder [put]
func UpdateSmartStorageOrder(c *gin.Context) {
var smartStorageOrder model.SmartStorageOrder
_ = c.ShouldBindJSON(&smartStorageOrder)
err := service.UpdateSmartStorageOrder(&smartStorageOrder)
if err != nil {
response.FailWithMessage(fmt.Sprintf("更新失败,%v", err), c)
} else {
response.OkWithMessage("更新成功", c)
}
}
func UpdateSmartStorageOrderStatus(c *gin.Context) {
var smartStorageOrder model.SmartStorageOrder
_ = c.ShouldBindJSON(&smartStorageOrder)
if smartStorageOrder.OrderStatus == 999 {
_, ssos := service.GetSmartStoragesOrderByOrderID(smartStorageOrder.OrderId)
for _, sso := range ssos {
sso.OrderStatus = 0
service.UpdateSmartStorageOrderStatus(&sso)
}
response.OkWithMessage("更新成功", c)
return
}
if smartStorageOrder.OrderStatus == 3 {
if smartStorageOrder.OrderNumber < 1 {
response.FailWithMessage("数量不能为负数和0", c)
return
}
service.UpdateSmartStorageOrderNumber(&smartStorageOrder)
response.OkWithMessage("更新成功", c)
return
}
err := service.UpdateSmartStorageOrderStatus(&smartStorageOrder)
if err != nil {
response.FailWithMessage(fmt.Sprintf("更新失败,%v", err), c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// @Tags SmartStorageOrder
// @Summary 用id查询SmartStorageOrder
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SmartStorageOrder true "用id查询SmartStorageOrder"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /smartStorageOrder/findSmartStorageOrder [get]
func FindSmartStorageOrder(c *gin.Context) {
var smartStorageOrder model.SmartStorageOrder
_ = c.ShouldBindQuery(&smartStorageOrder)
err, resmartStorageOrder := service.GetSmartStorageOrder(smartStorageOrder.ID)
if err != nil {
response.FailWithMessage(fmt.Sprintf("查询失败,%v", err), c)
} else {
response.OkWithData(gin.H{"resmartStorageOrder": resmartStorageOrder}, c)
}
}
// @Tags SmartStorageOrder
// @Summary 分页获取SmartStorageOrder列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.SmartStorageOrderSearch true "分页获取SmartStorageOrder列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /smartStorageOrder/getSmartStorageOrderList [get]
func GetSmartStorageOrderInfoById(c *gin.Context) {
var pageInfo request.SmartStorageOrderSearch
_ = c.ShouldBindQuery(&pageInfo)
userId, _ := strconv.Atoi(c.Request.Header.Get("x-user-id"))
err, list, total := service.GetSmartStorageOrderInfoById(pageInfo, userId)
if err != nil {
response.FailWithMessage(fmt.Sprintf("获取数据失败,%v", err), c)
} else {
response.OkWithData(resp.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, c)
}
}
func GetAllOrderList(c *gin.Context) {
var pageInfo request.SmartStorageOrderSearch
_ = c.ShouldBindQuery(&pageInfo)
err, list, total := service.GetAllOrderList(pageInfo)
if err != nil {
response.FailWithMessage(fmt.Sprintf("获取数据失败,%v", err), c)
} else {
response.OkWithData(resp.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, c)
}
}
func GetMyOrderList(c *gin.Context) {
var pageInfo request.SmartStorageOrderSearch
userId, _ := strconv.Atoi(c.Request.Header.Get("x-user-id"))
_ = c.ShouldBindQuery(&pageInfo)
err, list, total := service.GetMyOrderList(pageInfo, userId)
if err != nil {
response.FailWithMessage(fmt.Sprintf("获取数据失败,%v", err), c)
} else {
response.OkWithData(resp.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, c)
}
}
|
mail-suny-qq-com/Pncs-Server | pncs-smartbi/src/main/java/com/pactera/smartbi/sync/service/ISmartbiRoleService.java | <gh_stars>1-10
package com.pactera.smartbi.sync.service;
import com.pactera.core.base.service.IBaseService;
import com.pactera.core.message.Message;
import com.pactera.smartbi.sync.model.SmartbiRole;
/**
* 指标分类服务接口
*
* @author Suny
* @date 2020-04-01
*/
public interface ISmartbiRoleService extends IBaseService<SmartbiRole> {
Message sync(String roleId);
} |
jstastny-cz/appformer | uberfire-experimental/uberfire-experimental-client/src/test/java/org/uberfire/experimental/client/test/TestExperimentalFeatureDefRegistry.java | <reponame>jstastny-cz/appformer<filename>uberfire-experimental/uberfire-experimental-client/src/test/java/org/uberfire/experimental/client/test/TestExperimentalFeatureDefRegistry.java
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.experimental.client.test;
import org.uberfire.experimental.service.definition.ExperimentalFeatureDefinition;
import org.uberfire.experimental.service.definition.impl.ExperimentalFeatureDefRegistryImpl;
public class TestExperimentalFeatureDefRegistry extends ExperimentalFeatureDefRegistryImpl {
public static final String FEATURE_1 = "feature_1";
public static final String FEATURE_2 = "feature_2";
public static final String FEATURE_3 = "feature_3";
public static final String GLOBAL_FEATURE_1 = "globalFeature_1";
public static final String GLOBAL_FEATURE_2 = "globalFeature_2";
public static final String GLOBAL_FEATURE_3 = "globalFeature_3";
public static final String GROUP = "group";
public TestExperimentalFeatureDefRegistry() {
register(new ExperimentalFeatureDefinition(FEATURE_1, false, "", FEATURE_1, FEATURE_1));
register(new ExperimentalFeatureDefinition(FEATURE_2, false, GROUP, FEATURE_2, FEATURE_2));
register(new ExperimentalFeatureDefinition(FEATURE_3, false, "", FEATURE_3, FEATURE_3));
register(new ExperimentalFeatureDefinition(GLOBAL_FEATURE_1, true, "", GLOBAL_FEATURE_1, GLOBAL_FEATURE_1));
register(new ExperimentalFeatureDefinition(GLOBAL_FEATURE_2, true, "", GLOBAL_FEATURE_2, GLOBAL_FEATURE_2));
register(new ExperimentalFeatureDefinition(GLOBAL_FEATURE_3, true, "", GLOBAL_FEATURE_3, GLOBAL_FEATURE_3));
}
}
|
smartdong/YXDExtension | YXDExtensionDemo/YXDExtensionDemo/YXDExtension/YXDFunctionExtension/YXDCache/YXDCache.h | <gh_stars>1-10
//
// YXDCache.h
// YXDExtensionDemo
//
// Copyright © 2015年 YangXudong. All rights reserved.
//
#import "YYCache.h"
@interface YXDCache : YYCache
@end
|
mukul1987/incubator-ratis | ratis-common/src/main/java/org/apache/ratis/datastream/DataStreamType.java | /*
* 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.ratis.datastream;
import org.apache.ratis.conf.Parameters;
import org.apache.ratis.util.JavaUtils;
import org.apache.ratis.util.ReflectionUtils;
/** The type of data stream implementations. */
public interface DataStreamType {
/**
* Parse the given string as a {@link SupportedDataStreamType}
* or a user-defined {@link DataStreamType}.
*
* @param dataStreamType The string representation of an {@link DataStreamType}.
* @return a {@link SupportedDataStreamType} or a user-defined {@link DataStreamType}.
*/
static DataStreamType valueOf(String dataStreamType) {
final Throwable fromSupportedRpcType;
try { // Try parsing it as a SupportedRpcType
return SupportedDataStreamType.valueOfIgnoreCase(dataStreamType);
} catch (Throwable t) {
fromSupportedRpcType = t;
}
try {
// Try using it as a class name
return ReflectionUtils.newInstance(ReflectionUtils.getClass(dataStreamType, DataStreamType.class));
} catch(Throwable t) {
final String classname = JavaUtils.getClassSimpleName(DataStreamType.class);
final IllegalArgumentException iae = new IllegalArgumentException(
"Invalid " + classname + ": \"" + dataStreamType + "\" "
+ " cannot be used as a user-defined " + classname
+ " and it is not a " + JavaUtils.getClassSimpleName(SupportedDataStreamType.class) + ".");
iae.addSuppressed(t);
iae.addSuppressed(fromSupportedRpcType);
throw iae;
}
}
/** @return the name of the rpc type. */
String name();
/** @return a new client factory created using the given parameters. */
DataStreamFactory newClientFactory(Parameters parameters);
/** @return a new server factory created using the given parameters. */
DataStreamFactory newServerFactory(Parameters parameters);
/** An interface to get {@link DataStreamType}. */
interface Get {
/** @return the {@link DataStreamType}. */
DataStreamType getDataStreamType();
}
} |
YanaPIIDXer/YanaPServer | docs/html/search/files_7.js | <reponame>YanaPIIDXer/YanaPServer
var searchData=
[
['packet_2eh',['Packet.h',['../_packet_8h.html',1,'']]],
['packetheader_2ecpp',['PacketHeader.cpp',['../_packet_header_8cpp.html',1,'']]],
['packetheader_2eh',['PacketHeader.h',['../_packet_header_8h.html',1,'']]],
['packetserializer_2ecpp',['PacketSerializer.cpp',['../_packet_serializer_8cpp.html',1,'']]],
['packetserializer_2eh',['PacketSerializer.h',['../_packet_serializer_8h.html',1,'']]],
['peerbase_2ecpp',['PeerBase.cpp',['../_peer_base_8cpp.html',1,'']]],
['peerbase_2eh',['PeerBase.h',['../_peer_base_8h.html',1,'']]]
];
|
FirstLoveLife/Rider-Faiz | test/unique_ptr/hash/1.cc | <reponame>FirstLoveLife/Rider-Faiz
// { dg-do run { target c++11 } }
// 2010-06-11 <NAME> <<EMAIL>>
// Copyright (C) 2010-2018 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include "../../testsuite_allocator.h"
#include "../../testsuite_hooks.h"
#include <memory>
// User-defined pointer type that throws if a null pointer is dereferenced.
template<typename T>
struct Pointer : __gnu_test::PointerBase<Pointer<T>, T>
{};
template<typename T>
struct PointerDeleter : std::default_delete<T>
{
typedef Pointer<T> pointer;
void operator()(pointer) const;
};
template<class T>
auto
f(int) -> decltype(std::hash<Rider::Faiz::unique_ptr<T, PointerDeleter<T>>>(),
std::true_type());
template<class T>
auto
f(...) -> decltype(std::false_type());
static_assert(!decltype(f<Pointer<int>>(0))::value, "");
void
test01()
{
struct T
{};
Rider::Faiz::unique_ptr<T> u0(new T);
std::hash<Rider::Faiz::unique_ptr<T>> hu0;
std::hash<typename Rider::Faiz::unique_ptr<T>::pointer> hp0;
CHECK(hu0(u0) == hp0(u0.get()));
Rider::Faiz::unique_ptr<T[]> u1(new T[10]);
std::hash<Rider::Faiz::unique_ptr<T[]>> hu1;
std::hash<typename Rider::Faiz::unique_ptr<T[]>::pointer> hp1;
CHECK(hu1(u1) == hp1(u1.get()));
}
int
main()
{
test01();
return 0;
}
|
UQ-RCC/qldarch-backend | src/net/qldarch/architect/WsArchitects.java | package net.qldarch.architect;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import net.qldarch.WsBase;
import net.qldarch.archobj.ArchObj;
import net.qldarch.db.Db;
import net.qldarch.db.Rsc;
import net.qldarch.db.Sql;
import net.qldarch.jaxrs.ContentType;
@Path("/architects")
public class WsArchitects extends WsBase<ArchObj> {
}
|
koders/cookster-backend | src/main/java/lv/cookster/rest/MeasurementService.java | package lv.cookster.rest;
import lv.cookster.entity.Measurement;
import javax.persistence.Query;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
/**
* Created by Rihards on 11.01.2015
*/
@Path("/measurements")
public class MeasurementService extends CookingService {
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public List<Measurement> initialize() {
Query q = em.createQuery("SELECT m FROM Measurement m");
List<Measurement> resultList = (List<Measurement>) q.getResultList();
return resultList;
}
}
|
stbly/gemp-swccg-public | gemp-swccg-logic/src/main/java/com/gempukku/swccgo/logic/modifiers/UsePoliticsForPowerModifier.java | package com.gempukku.swccgo.logic.modifiers;
import com.gempukku.swccgo.common.Filterable;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.logic.conditions.Condition;
/**
* A modifier that causes affected cards to use politics instead to determine power.
*/
public class UsePoliticsForPowerModifier extends AbstractModifier {
/**
* Creates a modifier that causes cards accepted by the filter to use politics instead to determine power.
* @param source the source of the modifier
* @param affectFilter the filter
*/
public UsePoliticsForPowerModifier(PhysicalCard source, Filterable affectFilter) {
this(source, affectFilter, null);
}
/**
* Creates a modifier that causes cards accepted by the filter to use politics instead to determine power.
* @param source the source of the modifier
* @param affectFilter the filter
* @param condition the condition that must be fulfilled for the modifier to be in effect
*/
public UsePoliticsForPowerModifier(PhysicalCard source, Filterable affectFilter, Condition condition) {
super(source, "Power is equal to politics", affectFilter, condition, ModifierType.USE_POLITICS_FOR_POWER, true);
}
}
|
AnilKumarBejjanki/drools | kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesMatchedEvent.java | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.dmn.feel.runtime.events;
import java.util.List;
import org.kie.dmn.api.feel.runtime.events.FEELEvent;
/**
* An event class to report all matches for a decision table
*/
public class DecisionTableRulesMatchedEvent
extends FEELEventBase
implements FEELEvent {
private final String nodeName;
private final String dtName;
private final List<Integer> matches;
public DecisionTableRulesMatchedEvent(Severity severity, String msg, String nodeName, String dtName, List<Integer> matches) {
super( severity, msg, null );
this.nodeName = nodeName;
this.dtName = dtName;
this.matches = matches;
}
public String getNodeName() {
return nodeName;
}
public String getDecisionTableName() {
return dtName;
}
public List<Integer> getMatches() {
return matches;
}
@Override
public String toString() {
return "DecisionTableRulesMatchedEvent{" +
"severity=" + getSeverity() +
", message='" + getMessage() + '\'' +
", nodeName='" + nodeName + '\'' +
", dtName='" + dtName + '\'' +
", matches='" + matches + '\'' +
'}';
}
}
|
uguraba/SI | si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/impl/SecurityRegistryImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 Sierra Wireless and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Sierra Wireless - initial API and implementation
*******************************************************************************/
package org.eclipse.leshan.server.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.leshan.server.security.NonUniqueSecurityInfoException;
import org.eclipse.leshan.server.security.SecurityInfo;
import org.eclipse.leshan.server.security.SecurityRegistry;
import org.eclipse.leshan.util.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An in-memory security store.
* <p>
* This implementation serializes the registry content into a file to be able to re-load the security infos when the
* server is restarted.
* </p>
*/
public class SecurityRegistryImpl implements SecurityRegistry {
private static final Logger LOG = LoggerFactory.getLogger(SecurityRegistryImpl.class);
// lock for the two maps
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
// by client end-point
private Map<String, SecurityInfo> securityByEp = new HashMap<>();
// by PSK identity
private Map<String, SecurityInfo> securityByIdentity = new HashMap<>();
// the name of the file used to persist the registry content
private final String filename;
private PublicKey serverPublicKey;
private PrivateKey serverPrivateKey;
private X509Certificate[] serverX509CertChain;
private Certificate[] trustedCertificates = null; // TODO retrieve certs from JRE trustStore ?
// default location for persistence
private static final String DEFAULT_FILE = "data/security.data";
public SecurityRegistryImpl() {
this(DEFAULT_FILE, null, null);
}
/**
* Constructor for RPK
*/
public SecurityRegistryImpl(PrivateKey serverPrivateKey, PublicKey serverPublicKey) {
this(DEFAULT_FILE, serverPrivateKey, serverPublicKey);
}
/**
* Constructor for X509 certificates
*/
public SecurityRegistryImpl(PrivateKey serverPrivateKey, X509Certificate[] serverX509CertChain,
Certificate[] trustedCertificates) {
this(DEFAULT_FILE, serverPrivateKey, serverX509CertChain, trustedCertificates);
}
/**
* @param file the file path to persist the registry
*/
public SecurityRegistryImpl(String file, PrivateKey serverPrivateKey, PublicKey serverPublicKey) {
Validate.notEmpty(file);
filename = file;
this.serverPrivateKey = serverPrivateKey;
this.serverPublicKey = serverPublicKey;
loadFromFile();
}
/**
* @param file the file path to persist the registry
*/
public SecurityRegistryImpl(String file, PrivateKey serverPrivateKey, X509Certificate[] serverX509CertChain,
Certificate[] trustedCertificates) {
Validate.notEmpty(file);
Validate.notEmpty(serverX509CertChain);
Validate.notEmpty(trustedCertificates);
filename = file;
this.serverPrivateKey = serverPrivateKey;
this.serverX509CertChain = serverX509CertChain;
// extract the raw public key from the first certificate in the chain
this.serverPublicKey = serverX509CertChain[0].getPublicKey();
this.trustedCertificates = trustedCertificates;
loadFromFile();
}
/**
* {@inheritDoc}
*/
@Override
public SecurityInfo getByEndpoint(String endpoint) {
readLock.lock();
try {
return securityByEp.get(endpoint);
} finally {
readLock.unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public SecurityInfo getByIdentity(String identity) {
readLock.lock();
try {
return securityByIdentity.get(identity);
} finally {
readLock.unlock();
}
}
@Override
public Collection<SecurityInfo> getAll() {
readLock.lock();
try {
return Collections.unmodifiableCollection(securityByEp.values());
} finally {
readLock.unlock();
}
}
private SecurityInfo addToRegistry(SecurityInfo info) throws NonUniqueSecurityInfoException {
writeLock.lock();
try {
String identity = info.getIdentity();
if (identity != null) {
SecurityInfo infoByIdentity = securityByIdentity.get(info.getIdentity());
if (infoByIdentity != null && !info.getEndpoint().equals(infoByIdentity.getEndpoint())) {
throw new NonUniqueSecurityInfoException("PSK Identity " + info.getIdentity() + " is already used");
}
securityByIdentity.put(info.getIdentity(), info);
}
SecurityInfo previous = securityByEp.put(info.getEndpoint(), info);
return previous;
} finally {
writeLock.unlock();
}
}
@Override
public SecurityInfo add(SecurityInfo info) throws NonUniqueSecurityInfoException {
writeLock.lock();
try {
SecurityInfo previous = addToRegistry(info);
saveToFile();
return previous;
} finally {
writeLock.unlock();
}
}
@Override
public SecurityInfo remove(String endpoint) {
writeLock.lock();
try {
SecurityInfo info = securityByEp.get(endpoint);
if (info != null) {
if (info.getIdentity() != null) {
securityByIdentity.remove(info.getIdentity());
}
securityByEp.remove(endpoint);
saveToFile();
}
return info;
} finally {
writeLock.unlock();
}
}
protected void loadFromFile() {
File file = new File(filename);
if (!file.exists()) {
return;
}
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));) {
SecurityInfo[] infos = (SecurityInfo[]) in.readObject();
if (infos != null) {
for (SecurityInfo info : infos) {
addToRegistry(info);
}
if (infos.length > 0) {
LOG.debug("{} security infos loaded", infos.length);
}
}
} catch (NonUniqueSecurityInfoException | IOException | ClassNotFoundException e) {
LOG.error("Could not load security infos from file", e);
}
}
protected void saveToFile() {
try {
File file = new File(filename);
if (!file.exists()) {
File parent = file.getParentFile();
if (parent != null) {
parent.mkdirs();
}
file.createNewFile();
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));) {
out.writeObject(this.getAll().toArray(new SecurityInfo[0]));
}
} catch (IOException e) {
LOG.error("Could not save security infos to file", e);
}
}
@Override
public PublicKey getServerPublicKey() {
return serverPublicKey;
}
@Override
public PrivateKey getServerPrivateKey() {
return serverPrivateKey;
}
@Override
public X509Certificate[] getServerX509CertChain() {
return serverX509CertChain;
}
@Override
public Certificate[] getTrustedCertificates() {
return trustedCertificates;
}
}
|
aspose-tasks/Aspose.Tasks-for-C | Examples/CPP/WorkingWithTaskLinks/GetPredecessorSuccessorTasks.cpp | <filename>Examples/CPP/WorkingWithTaskLinks/GetPredecessorSuccessorTasks.cpp
#include "GetPredecessorSuccessorTasks.h"
#include <Tsk.h>
#include <TaskLinkCollection.h>
#include <TaskLink.h>
#include <Task.h>
#include <system/type_info.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/reflection/method_base.h>
#include <system/object.h>
#include <system/console.h>
#include <system/collections/ienumerator.h>
#include <Project.h>
#include <Key.h>
#include <enums/TaskKey.h>
#include "RunExamples.h"
namespace Aspose {
namespace Tasks {
namespace Examples {
namespace CPP {
namespace WorkingWithTaskLinks {
RTTI_INFO_IMPL_HASH(3001112903u, ::Aspose::Tasks::Examples::CPP::WorkingWithTaskLinks::GetPredecessorSuccessorTasks, ThisTypeBaseTypesInfo);
void GetPredecessorSuccessorTasks::Run()
{
// ExStart:GetPredecessorSuccessorTasks
// Create project instance
System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
System::SharedPtr<Project> project1 = System::MakeObject<Project>(dataDir + u"GetPredecessorSuccessorTasks.mpp");
// Display names of predecessor and successor tasks
{
auto tsklnk_enumerator = (project1->get_TaskLinks())->GetEnumerator();
decltype(tsklnk_enumerator->get_Current()) tsklnk;
while (tsklnk_enumerator->MoveNext() && (tsklnk = tsklnk_enumerator->get_Current(), true))
{
System::Console::WriteLine(System::String(u"Predecessor ") + tsklnk->get_PredTask()->Get(Tsk::Name()));
System::Console::WriteLine(System::String(u"Predecessor ") + tsklnk->get_SuccTask()->Get(Tsk::Name()));
}
}
// ExEnd:GetPredecessorSuccessorTasks
}
} // namespace WorkingWithTaskLinks
} // namespace CPP
} // namespace Examples
} // namespace Tasks
} // namespace Aspose
|
justinbarry/augur-copy | src/modules/reports/reducers/has-loaded-reports.js | import { UPDATE_HAS_LOADED_REPORTS, UPDATE_HAS_LOADED_MARKETS_TO_REPORT_ON } from 'modules/reports/actions/update-has-loaded-reports'
import { RESET_STATE } from 'modules/app/actions/reset-state'
const DEFAULT_STATE = { reports: false, marketsToReportOn: false }
export default function (hasLoadedReports = DEFAULT_STATE, action) {
switch (action.type) {
case UPDATE_HAS_LOADED_REPORTS:
return {
...hasLoadedReports,
reports: action.hasLoadedReports,
}
case UPDATE_HAS_LOADED_MARKETS_TO_REPORT_ON:
return {
...hasLoadedReports,
marketsToReportOn: action.hasLoadedMarketsToReportOn,
}
case RESET_STATE:
return DEFAULT_STATE
default:
return hasLoadedReports
}
}
|
jameshfisher/rollup | test/chunking-form/samples/minify-internal-exports/_expected/es/generated-shared2.js | const shared1 = 'shared1';
const foo = 'foo1';
var shared2 = 'shared2';
const foo$1 = 'foo2';
export { shared2 as a, foo$1 as b, foo as f, shared1 as s };
|
avineshpvs/vldb2018-sherlock | ukpsummarizer-be/cplex/cpoptimizer/examples/src/java/Color.java | <reponame>avineshpvs/vldb2018-sherlock
// ---------------------------------------------------------------*- Java -*-
// File: ./examples/src/java/Color.java
// --------------------------------------------------------------------------
// Licensed Materials - Property of IBM
//
// 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5725-A06 5725-A29
// Copyright IBM Corporation 1990, 2017. All Rights Reserved.
//
// Note to U.S. Government Users Restricted Rights:
// Use, duplication or disclosure restricted by GSA ADP Schedule
// Contract with IBM Corp.
// --------------------------------------------------------------------------
/* ------------------------------------------------------------
Problem Description
-------------------
The problem involves choosing colors for the countries on a map in
such a way that at most four colors (blue, white, yellow, green) are
used and no neighboring countries are the same color. In this exercise,
you will find a solution for a map coloring problem with six countries:
Belgium, Denmark, France, Germany, Luxembourg, and the Netherlands.
------------------------------------------------------------ */
import ilog.cp.*;
import ilog.concert.*;
public class Color {
public static String[] Names = {"blue", "white", "yellow", "green"};
public static void main(String[] args) {
try {
IloCP cp = new IloCP();
IloIntVar Belgium = cp.intVar(0, 3);
IloIntVar Denmark = cp.intVar(0, 3);
IloIntVar France = cp.intVar(0, 3);
IloIntVar Germany = cp.intVar(0, 3);
IloIntVar Luxembourg = cp.intVar(0, 3);
IloIntVar Netherlands = cp.intVar(0, 3);
cp.add(cp.neq(Belgium , France));
cp.add(cp.neq(Belgium , Germany));
cp.add(cp.neq(Belgium , Netherlands));
cp.add(cp.neq(Belgium , Luxembourg));
cp.add(cp.neq(Denmark , Germany));
cp.add(cp.neq(France , Germany));
cp.add(cp.neq(France , Luxembourg));
cp.add(cp.neq(Germany , Luxembourg));
cp.add(cp.neq(Germany , Netherlands));
if (cp.solve())
{
System.out.println();
System.out.println( "Belgium: " + Names[(int)cp.getValue(Belgium)]);
System.out.println( "Denmark: " + Names[(int)cp.getValue(Denmark)]);
System.out.println( "France: " + Names[(int)cp.getValue(France)]);
System.out.println( "Germany: " + Names[(int)cp.getValue(Germany)]);
System.out.println( "Luxembourg: " + Names[(int)cp.getValue(Luxembourg)]);
System.out.println( "Netherlands: " + Names[(int)cp.getValue(Netherlands)]);
}
} catch (IloException e) {
System.err.println("Error " + e);
}
}
}
|
jchlanda/oneAPI-DirectProgramming | qtclustering-dpct/libdata.h | <filename>qtclustering-dpct/libdata.h
#ifndef _LIBDATA_H_
#define _LIBDATA_H_
#include <CL/sycl.hpp>
#include <dpct/dpct.hpp>
float *generate_synthetic_data(float **rslt_mtrx, int **indr_mtrx, int *max_degree, float threshold, int N, int type);
#endif
|
jeffalder/newrelic-java-agent | newrelic-agent/src/main/java/com/newrelic/agent/profile/v2/TransactionProfileSessionImpl.java | <gh_stars>100-1000
/*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.newrelic.agent.profile.v2;
import java.io.IOException;
import java.io.Writer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.json.simple.JSONObject;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.newrelic.agent.ThreadService;
import com.newrelic.agent.TransactionData;
import com.newrelic.agent.profile.ThreadType;
import com.newrelic.agent.service.ServiceFactory;
import com.newrelic.agent.threads.BasicThreadInfo;
import com.newrelic.agent.threads.ThreadNameNormalizer;
import com.newrelic.agent.tracers.DefaultTracer;
import com.newrelic.agent.tracers.IgnoreChildSocketCalls;
import com.newrelic.agent.tracers.Tracer;
public class TransactionProfileSessionImpl implements TransactionProfileSession {
static final TransactionProfileService NO_OP_TRANSACTION_PROFILE_SERVICE = new TransactionProfileService() {
@Override
public boolean isTransactionProfileSessionActive() {
return false;
}
@Override
public TransactionProfileSession getTransactionProfileSession() {
return NO_OP_TRANSACTION_PROFILE_SESSION;
}
};
static final TransactionProfileSession NO_OP_TRANSACTION_PROFILE_SESSION = new TransactionProfileSession() {
@Override
public void writeJSONString(Writer out) throws IOException {
JSONObject.writeJSONString(ImmutableMap.of(), out);
}
@Override
public void transactionFinished(TransactionData transactionData) { }
@Override
public boolean isActive() {
return false;
}
@Override
public void noticeTracerStart(int signatureId, int tracerFlags, Tracer tracer) {
}
};
private static final int STACK_CAPTURE_LIMIT_PER_METRIC_PER_PERIOD = 5;
private final ThreadService threadService;
/**
* Transaction name to a transaction profile.
*/
private final LoadingCache<String, TransactionProfile> transactionProfileTrees;
private final DiscoveryProfile discoveryProfile;
public TransactionProfileSessionImpl(final Profile profile, final ThreadNameNormalizer threadNameNormalizer) {
this(profile, threadNameNormalizer, ServiceFactory.getThreadService());
}
private final LoadingCache<String, AtomicInteger> stackTraceLimits;
private final Profile profile;
protected TransactionProfileSessionImpl(final Profile profile, final ThreadNameNormalizer threadNameNormalizer, ThreadService threadService) {
this.threadService = threadService;
this.profile = profile;
this.transactionProfileTrees =
Caffeine.newBuilder().executor(Runnable::run).build(
transactionName -> new TransactionProfile(profile, threadNameNormalizer));
this.discoveryProfile = new DiscoveryProfile(profile, threadNameNormalizer);
this.stackTraceLimits =
Caffeine.newBuilder().expireAfterAccess(5, TimeUnit.SECONDS).executor(Runnable::run).build(
metricName -> new AtomicInteger(0));
}
@Override
public void transactionFinished(TransactionData transactionData) {
TransactionProfile txProfile = transactionProfileTrees.get(transactionData.getBlameMetricName());
txProfile.transactionFinished(transactionData);
}
@Override
public void writeJSONString(Writer out) throws IOException {
ImmutableMap<String, Object> map = ImmutableMap.of(
"transactions", transactionProfileTrees.asMap(),
"discovery", discoveryProfile);
JSONObject.writeJSONString(map, out);
}
@Override
public void noticeTracerStart(int signatureId, int tracerFlags, Tracer tracer) {
if (!threadService.isCurrentThreadAnAgentThread()) {
if (tracer == null) {
discoveryProfile.noticeStartTracer(signatureId);
Thread currentThread = Thread.currentThread();
profile.addStackTrace(new BasicThreadInfo(currentThread), currentThread.getStackTrace(), true, ThreadType.BasicThreadType.OTHER);
} else if (tracer.isLeaf() || tracer instanceof IgnoreChildSocketCalls) {
if (stackTraceLimits.get(tracer.getMetricName()).getAndIncrement() <
STACK_CAPTURE_LIMIT_PER_METRIC_PER_PERIOD) {
tracer.setAgentAttribute(DefaultTracer.BACKTRACE_PARAMETER_NAME, Thread.currentThread().getStackTrace());
}
}
}
}
@Override
public boolean isActive() {
return !ServiceFactory.getServiceManager().getCircuitBreakerService().isTripped();
}
}
|
itsMatoosh/UnderNet-Android | shared/src/main/java/me/matoosh/undernet/p2p/router/data/message/tunnel/MessageTunnelState.java | package me.matoosh.undernet.p2p.router.data.message.tunnel;
/**
* Represents the state of a message tunnel.
*/
public enum MessageTunnelState {
NOT_ESTABLISHED, //The message tunnel hasn't been established yet (just an empty tunnel object)
ESTABLISHING, //The message tunnel is currently being established.
ESTABLISHED, //The message tunnel has been established.
HOSTED //The message tunnel is being hosted. The self node is not the origin nor the destination of the tunnel.
}
|
vinooganesh/concourse | concourse-driver-java/src/main/java/com/cinchapi/concourse/util/Collections.java | <reponame>vinooganesh/concourse
/*
* Copyright (c) 2013-2021 Cinchapi Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cinchapi.concourse.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.google.common.collect.Lists;
/**
* Yet another utility class that deals with {@link Collection Collections}.
*
* @author <NAME>
*/
public final class Collections {
/**
* Convert the given {@code collection} to a {@link List}, if necessary.
*
* @param collection
* @return a List that contains all the elements in {@code collection}.
*/
public static <T> List<T> toList(Collection<T> collection) {
return collection instanceof List ? (List<T>) collection
: Lists.newArrayList(collection);
}
/**
* Convert the given {@code collection} to a {@link List} of {@link Long}
* values, if necessary. The client must attempt to do this for every
* collection of records because CaSH always passes user input in as a
* collection of {@link Integer integers}.
*
* @param collection
* @return a List that contains Long values
*/
public static <T> List<Long> toLongList(Collection<T> collection) {
List<Long> list = Lists.newArrayListWithCapacity(collection.size());
Iterator<T> it = collection.iterator();
while (it.hasNext()) {
T elt = it.next();
if(elt instanceof Number) {
list.add(((Number) elt).longValue());
}
else {
throw new ClassCastException("Cant convert object of type"
+ elt.getClass() + " to java.lang.Long");
}
}
return list;
}
private Collections() {/* noop */}
}
|
liuzyw/study-hello | study-util/src/main/java/com/study/util/sort/offer/FindSequence.java | package com.study.util.sort.offer;
/**
* Created on 2018-11-01
*
* @author liuzhaoyuan
*/
public class FindSequence {
public static void main(String[] args) {
find(15);
}
private static void find(int num) {
if ((num & 1) == 0) {
return;
}
int mid = num >>> 1;
int low = 0;
int fast = 0;
int sum = 0;
for (int i = 1; i <= mid + 1; i++) {
fast = i;
sum += fast;
while (sum > num) {
sum -= low;
low++;
}
if (sum == num) {
System.out.println(low + "-" + fast);
}
}
}
}
|
wangsenyuan/learn-go | src/codeforces/problems/set0/set004/d/solution.go | package main
import (
"bufio"
"bytes"
"fmt"
"os"
"sort"
)
func main() {
reader := bufio.NewReader(os.Stdin)
n, w, h := readThreeNums(reader)
envs := make([][]int, n)
for i := 0; i < n; i++ {
envs[i] = readNNums(reader, 2)
}
res := solve(n, w, h, envs)
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("%d\n", len(res)))
for i := 0; i < len(res); i++ {
buf.WriteString(fmt.Sprintf("%d ", res[i]))
}
fmt.Print(buf.String())
}
func readInt(bytes []byte, from int, val *int) int {
i := from
sign := 1
if bytes[i] == '-' {
sign = -1
i++
}
tmp := 0
for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
tmp = tmp*10 + int(bytes[i]-'0')
i++
}
*val = tmp * sign
return i
}
func readNum(reader *bufio.Reader) (a int) {
bs, _ := reader.ReadBytes('\n')
readInt(bs, 0, &a)
return
}
func readTwoNums(reader *bufio.Reader) (a int, b int) {
res := readNNums(reader, 2)
a, b = res[0], res[1]
return
}
func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
res := readNNums(reader, 3)
a, b, c = res[0], res[1], res[2]
return
}
func readNNums(reader *bufio.Reader, n int) []int {
res := make([]int, n)
x := 0
bs, _ := reader.ReadBytes('\n')
for i := 0; i < n; i++ {
for x < len(bs) && (bs[x] < '0' || bs[x] > '9') {
x++
}
x = readInt(bs, x, &res[i])
}
return res
}
func readUint64(bytes []byte, from int, val *uint64) int {
i := from
var tmp uint64
for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
tmp = tmp*10 + uint64(bytes[i]-'0')
i++
}
*val = tmp
return i
}
func solve(n, w, h int, envs [][]int) []int {
items := make([]Envelope, n)
var H int
for i := 0; i < n; i++ {
items[i] = Envelope{envs[i][0], envs[i][1], i}
H = max(H, envs[i][1])
}
sort.Sort(Envelopes(items))
H++
arr := make([]int, 2*H)
update := func(p int, v int) {
p += H
arr[p] = v
for p > 0 {
arr[p>>1] = max(arr[p], arr[p^1])
p >>= 1
}
}
get := func(l, r int) int {
var res int
l += H
r += H
for l < r {
if l&1 == 1 {
res = max(res, arr[l])
l++
}
if r&1 == 1 {
r--
res = max(res, arr[r])
}
l >>= 1
r >>= 1
}
return res
}
dp := make([]int, n+1)
var best int
for i := 0; i < n; i++ {
cur := items[i]
if cur.width <= w {
break
}
if cur.height <= h {
continue
}
cnt := get(cur.height+1, H)
dp[i] = cnt + 1
update(cur.height, cnt+1)
best = max(best, cnt+1)
}
if best == 0 {
return nil
}
cur := -1
for i := n - 1; i >= 0; i-- {
if dp[i] == best {
cur = i
break
}
}
res := make([]int, 0, best)
res = append(res, items[cur].index+1)
for i := cur - 1; i >= 0; i-- {
if dp[i]+1 == best && items[i].width > items[cur].width && items[i].height > items[cur].height {
best--
cur = i
res = append(res, items[cur].index+1)
}
}
//reverse(res)
return res
}
func max(a, b int) int {
if a >= b {
return a
}
return b
}
type Envelope struct {
width int
height int
index int
}
type Envelopes []Envelope
func (ps Envelopes) Len() int {
return len(ps)
}
func (ps Envelopes) Less(i, j int) bool {
return ps[i].width > ps[j].width || ps[i].width == ps[j].width && ps[i].height < ps[j].height
}
func (ps Envelopes) Swap(i, j int) {
ps[i], ps[j] = ps[j], ps[i]
}
|
ludwigfrank/site | src/theme/index.js | <reponame>ludwigfrank/site
import mapValues from 'lodash/mapValues'
import color from './color'
import React from 'react'
import typography from './typography'
import animation from './animation'
import spacing, { space, breakpoints } from './spacing'
import shadow from './shadow'
import { THEME_ACTIVE, THEME_DARK } from './constants'
import { ThemeProvider } from 'styled-components'
export const extractActiveThemeColor = (themeColorObject, activeTheme) => {
if (typeof themeColorObject !== 'object')
throw new Error('Theme should only consist of objects!')
const style = {}
mapValues(themeColorObject, (category, categoryName) => {
style[categoryName] = {}
mapValues(category, (color, colorName) => {
const c = themeColorObject[categoryName][colorName][activeTheme]
style[categoryName][colorName] = () => {
if (typeof c === 'string') return c
// Todo: Transform all colors to hsl
if (Array.isArray(c))
return c.map((val, index) =>
index !== 0
? index === 1
? val + '%,'
: val + '%'
: val + ','
)
}
})
})
return style
}
const col = extractActiveThemeColor(color, THEME_ACTIVE)
col.category = {
dark: extractActiveThemeColor(color, THEME_DARK),
}
const getTheme = (themeId = THEME_ACTIVE) => {
return {
color: extractActiveThemeColor(color, themeId),
typography,
shadow,
spacing,
space,
animation,
breakpoints,
}
}
export const themeActive = THEME_ACTIVE
const withTheme = (Component, themeId = THEME_ACTIVE) => props => (
<ThemeProvider theme={getTheme(themeId)}>
<Component {...props} />
</ThemeProvider>
)
export default withTheme
|
enthought/etsproxy | enthought/traits/ui/context_value.py | <filename>enthought/traits/ui/context_value.py
# proxy module
from traitsui.context_value import *
|
One-E2-Team/ISA | isabackend/src/main/java/rs/ac/uns/ftn/isa/onee2team/isabackend/repository/IWarehouseRepository.java | <filename>isabackend/src/main/java/rs/ac/uns/ftn/isa/onee2team/isabackend/repository/IWarehouseRepository.java
package rs.ac.uns.ftn.isa.onee2team.isabackend.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import rs.ac.uns.ftn.isa.onee2team.isabackend.model.pharmacy.Warehouse;
public interface IWarehouseRepository extends JpaRepository<Warehouse, Long> {
@Query(value = "select distinct w.medicine_id from warehouses w where w.pharmacy_id = :pharmacyId", nativeQuery = true)
List<Long> getAllMedicinesInPharmacy(@Param("pharmacyId") Long pharmacyId);
@Query("select w from Warehouse w where w.pharmacy.id = ?1 and w.medicine.id = ?2")
Warehouse getWarehouseByPharmacyAndMedicine(Long pharmacy_id, Long medicine_id);
@Query(value = "select * from warehouses w where w.pharmacy_id = ?2 and w.medicine_id = ?1", nativeQuery = true)
Warehouse getByMedicineAndPharmacy(Long medicineId, Long pharmacyId);
@Query(value = "select * from warehouses w where w.medicine_id = ?1", nativeQuery = true)
List<Warehouse> findAllByMedicineId(Long id);
@Query(value = "select pharmacy_id from warehouses w where w.medicine_id = ?1 and w.amount - w.reserved_amount >= ?2", nativeQuery = true)
List<Long> getAllPharmacyIdsWhereMedicineAmountIsAvailable(Long medicineId, Integer amount);
}
|
MyNameIsYesgo/fivem | code/components/gta-net-five/src/ObjectIdManager.cpp | #include <StdInc.h>
#include <Hooking.h>
#include <NetBuffer.h>
#include <NetLibrary.h>
#include <GameInit.h>
#include <ICoreGameInit.h>
#include <nutsnbolts.h>
#include <CloneManager.h>
#include <MinHook.h>
static std::list<int> g_objectIds;
static std::set<int> g_usedObjectIds;
static std::set<int> g_stolenObjectIds;
static uint32_t(*g_origAssignObjectId)(void*);
static uint32_t AssignObjectId(void* objectIds)
{
if (!Instance<ICoreGameInit>::Get()->OneSyncEnabled)
{
return g_origAssignObjectId(objectIds);
}
if (g_objectIds.empty())
{
trace("No free object ID!\n");
return 0;
}
auto it = g_objectIds.begin();
auto objectId = *it;
g_objectIds.erase(it);
g_usedObjectIds.insert(objectId);
TheClones->Log("%s: id %d\n", __func__, objectId);
return objectId;
}
static bool(*g_origReturnObjectId)(void*, uint16_t);
static bool ReturnObjectId(void* objectIds, uint16_t objectId)
{
if (!Instance<ICoreGameInit>::Get()->OneSyncEnabled)
{
return g_origReturnObjectId(objectIds, objectId);
}
if (g_usedObjectIds.find(objectId) != g_usedObjectIds.end())
{
TheClones->Log("%s: id %d\n", __func__, objectId);
g_usedObjectIds.erase(objectId);
// only return it to ourselves if it was ours to begin with
// (and only use this for network protocol version 0x201903031957 or above - otherwise server bookkeeping will go out of sync)
if (Instance<ICoreGameInit>::Get()->NetProtoVersion < 0x201903031957 || g_stolenObjectIds.find(objectId) == g_stolenObjectIds.end())
{
g_objectIds.push_back(objectId);
}
g_stolenObjectIds.erase(objectId);
return true;
}
return false;
}
void ObjectIds_ReturnObjectId(uint16_t objectId)
{
ReturnObjectId(nullptr, objectId);
}
static bool(*g_origHasSpaceForObjectId)(void*, int, bool);
static bool HasSpaceForObjectId(void* objectIds, int num, bool unkScript)
{
if (!Instance<ICoreGameInit>::Get()->OneSyncEnabled)
{
return g_origHasSpaceForObjectId(objectIds, num, unkScript);
}
return (g_objectIds.size() >= num);
}
void ObjectIds_AddObjectId(int objectId)
{
// track 'stolen' migration object IDs so we can return them to the server once they get deleted
bool wasOurs = false;
// this is ours now
g_usedObjectIds.insert(objectId);
// remove this object ID from our free list
for (auto it = g_objectIds.begin(); it != g_objectIds.end(); it++)
{
if (*it == objectId)
{
wasOurs = true;
g_objectIds.erase(it);
break;
}
}
if (!wasOurs)
{
g_stolenObjectIds.insert(objectId);
}
TheClones->Log("%s: id %d\n", __func__, objectId);
}
void ObjectIds_RemoveObjectId(int objectId)
{
// this is no longer ours
g_usedObjectIds.erase(objectId);
// we don't have to care if it got stolen anymore
g_stolenObjectIds.erase(objectId);
TheClones->Log("%s: id %d\n", __func__, objectId);
}
static NetLibrary* g_netLibrary;
static bool g_requestedIds;
void ObjectIds_BindNetLibrary(NetLibrary* netLibrary)
{
g_netLibrary = netLibrary;
netLibrary->AddReliableHandler("msgObjectIds", [](const char* data, size_t len)
{
net::Buffer buffer(reinterpret_cast<const uint8_t*>(data), len);
auto numIds = buffer.Read<uint16_t>();
int last = 0;
for (int i = 0; i < numIds; i++)
{
auto skip = buffer.Read<uint16_t>();
auto take = buffer.Read<uint16_t>();
last += skip + 1;
for (int j = 0; j <= take; j++)
{
int objectId = last++;
TheClones->Log("got object id %d\n", objectId);
g_objectIds.push_back(objectId);
g_stolenObjectIds.erase(objectId);
}
}
g_requestedIds = false;
});
}
static HookFunction hookFunction([]()
{
OnMainGameFrame.Connect([]()
{
if (g_netLibrary->GetConnectionState() != NetLibrary::CS_ACTIVE)
{
return;
}
if (!Instance<ICoreGameInit>::Get()->OneSyncEnabled)
{
return;
}
int reqCount = 16;
if (Instance<ICoreGameInit>::Get()->HasVariable("onesync_big"))
{
reqCount = 4;
}
if (g_objectIds.size() < reqCount)
{
if (!g_requestedIds)
{
net::Buffer outBuffer;
outBuffer.Write<uint16_t>(32);
g_netLibrary->SendReliableCommand("msgRequestObjectIds", (const char*)outBuffer.GetData().data(), outBuffer.GetCurOffset());
g_requestedIds = true;
}
}
});
OnKillNetworkDone.Connect([]()
{
g_objectIds.clear();
g_usedObjectIds.clear();
g_requestedIds = false;
});
MH_Initialize();
MH_CreateHook(hook::get_pattern("FF 89 C4 3E 00 00 33 D2", -12), AssignObjectId, (void**)&g_origAssignObjectId);
MH_CreateHook(hook::get_pattern("44 8B 91 C4 3E 00 00", -0x14), ReturnObjectId, (void**)&g_origReturnObjectId);
MH_CreateHook(hook::get_pattern("48 83 EC 20 8B B1 C4 3E 00 00", -0xB), HasSpaceForObjectId, (void**)&g_origHasSpaceForObjectId);
MH_EnableHook(MH_ALL_HOOKS);
});
|
stnguyen90/buffalo-cli | cli/internal/plugins/pop/test/tester.go | <gh_stars>0
package test
import (
"bytes"
"context"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/gobuffalo/buffalo-cli/v2/cli/cmds/test"
"github.com/gobuffalo/plugins"
"github.com/gobuffalo/pop/v5"
)
var _ plugins.Plugin = &Tester{}
var _ test.Argumenter = &Tester{}
var _ test.BeforeTester = &Tester{}
type Tester struct {
}
func (t *Tester) TestArgs(ctx context.Context, root string) ([]string, error) {
args := []string{"-p", "1"}
dy := filepath.Join(root, "database.yml")
if _, err := os.Stat(dy); err != nil {
return args, nil
}
b, err := ioutil.ReadFile(dy)
if err != nil {
return nil, err
}
if bytes.Contains(b, []byte("sqlite")) {
args = append(args, "-tags", "sqlite")
}
return args, nil
}
func (Tester) PluginName() string {
return "pop/tester"
}
func (t *Tester) BeforeTest(ctx context.Context, root string, args []string) error {
if err := pop.AddLookupPaths(root); err != nil {
return err
}
var err error
db, ok := ctx.Value("tx").(*pop.Connection)
if !ok {
if _, err := os.Stat(filepath.Join(root, "database.yml")); err != nil {
return err
}
db, err = pop.Connect("test")
if err != nil {
return err
}
}
// drop the test db:
db.Dialect.DropDB()
// create the test db:
if err := db.Dialect.CreateDB(); err != nil {
return err
}
for _, a := range args {
if a == "--force-migrations" {
return t.forceMigrations(root, db)
}
}
schema, err := t.findSchema(root)
if err != nil {
return err
}
if schema == nil {
return t.forceMigrations(root, db)
}
if err = db.Dialect.LoadSchema(schema); err != nil {
return err
}
return nil
}
func (t *Tester) forceMigrations(root string, db *pop.Connection) error {
ms := filepath.Join(root, "migrations")
fm, err := pop.NewFileMigrator(ms, db)
if err != nil {
return err
}
return fm.Up()
}
func (t *Tester) findSchema(root string) (io.Reader, error) {
ms := filepath.Join(root, "migrations", "schema.sql")
if f, err := os.Open(ms); err == nil {
return f, nil
}
if dev, err := pop.Connect("development"); err == nil {
schema := &bytes.Buffer{}
if err = dev.Dialect.DumpSchema(schema); err == nil {
return schema, nil
}
}
return nil, nil
}
|
TheCodeTherapy/mgzthree | examples/js/helpers/RectAreaLightHelper.js | <filename>examples/js/helpers/RectAreaLightHelper.js
/**
* Generated from 'examples/jsm/helpers/RectAreaLightHelper.js'
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three')) :
typeof define === 'function' && define.amd ? define(['exports', 'three'], factory) :
(global = global || self, factory(global.THREE = global.THREE || {}, global.THREE));
}(this, (function (exports, THREE) { 'use strict';
/**
* @author abelnation / http://github.com/abelnation
* @author Mugen87 / http://github.com/Mugen87
* @author WestLangley / http://github.com/WestLangley
*
* This helper must be added as a child of the light
*/
function RectAreaLightHelper( light, color ) {
this.type = 'RectAreaLightHelper';
this.light = light;
this.color = color; // optional hardwired color for the helper
var positions = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
var geometry = new THREE.BufferGeometry();
geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
geometry.computeBoundingSphere();
var material = new THREE.LineBasicMaterial( { fog: false } );
THREE.Line.call( this, geometry, material );
//
var positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
var geometry2 = new THREE.BufferGeometry();
geometry2.setAttribute( 'position', new THREE.Float32BufferAttribute( positions2, 3 ) );
geometry2.computeBoundingSphere();
this.add( new THREE.Mesh( geometry2, new THREE.MeshBasicMaterial( { side: THREE.BackSide, fog: false } ) ) );
this.update();
}
RectAreaLightHelper.prototype = Object.create( THREE.Line.prototype );
RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
RectAreaLightHelper.prototype.update = function () {
this.scale.set( 0.5 * this.light.width, 0.5 * this.light.height, 1 );
if ( this.color !== undefined ) {
this.material.color.set( this.color );
this.children[ 0 ].material.color.set( this.color );
} else {
this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
// prevent hue shift
var c = this.material.color;
var max = Math.max( c.r, c.g, c.b );
if ( max > 1 ) c.multiplyScalar( 1 / max );
this.children[ 0 ].material.color.copy( this.material.color );
}
};
RectAreaLightHelper.prototype.dispose = function () {
this.geometry.dispose();
this.material.dispose();
this.children[ 0 ].geometry.dispose();
this.children[ 0 ].material.dispose();
};
exports.RectAreaLightHelper = RectAreaLightHelper;
})));
|
gitter-badger/FlexNeuART | scripts/misc/sample_queries.py | <filename>scripts/misc/sample_queries.py
#!/usr/bin/env python
#
# Copyright 2014+ Carnegie Mellon University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
import os
import argparse
import random
from flexneuart.io.queries import read_queries, write_queries
from flexneuart.io.qrels import read_qrels, write_qrels
from flexneuart.config import QUESTION_FILE_JSON, QREL_FILE, DOCID_FIELD
parser = argparse.ArgumentParser(description='Sample queries and corresponding QREL entries.')
parser.add_argument('--data_dir',
metavar='data directory',
help='data directory',
type=str, required=True)
parser.add_argument('--input_subdir',
metavar='input data subirectory',
help='input data subdirectory',
type=str, required=True)
parser.add_argument('--seed',
metavar='random seed',
help='random seed',
type=int, default=0)
parser.add_argument('--out_subdir',
metavar='output data subirectory',
help='output data subdirectory',
type=str, required=True)
parser.add_argument('--qty',
metavar='1st part # of entries',
help='# of entries in the 1st part',
type=int, default=None)
args = parser.parse_args()
print(args)
data_dir = args.data_dir
query_id_list = []
query_list = read_queries(os.path.join(data_dir, args.input_subdir, QUESTION_FILE_JSON))
for data in query_list:
did = data[DOCID_FIELD]
query_id_list.append(did)
print('Read %d the queries' % (len(query_id_list)))
qrel_list = read_qrels(os.path.join(data_dir, args.input_subdir, QREL_FILE))
print('Read all the QRELs')
# print(qrel_list[0:10])
# print('Before shuffling:', query_id_list[0:10], '...')
random.seed(args.seed)
random.shuffle(query_id_list)
# print('After shuffling:', query_id_list[0:10], '...')
if len(query_id_list) == 0:
print('Nothing to sample, input is empty')
sys.exit(1)
sel_query_ids = set(query_id_list[0:args.qty])
print('We selected %d queries' % len(sel_query_ids))
out_dir = os.path.join(data_dir, args.out_subdir)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
queries_filtered = list(filter(lambda e: e[DOCID_FIELD] in sel_query_ids, query_list))
qrels_filtered = list(filter(lambda e: e.query_id in sel_query_ids, qrel_list))
write_qrels(qrels_filtered,os.path.join(out_dir, QREL_FILE))
write_queries(queries_filtered, os.path.join(out_dir, QUESTION_FILE_JSON))
|
victor-gil-sepulveda/pyProCT | pyproct/clustering/evaluation/metrics/test/TestDaviesBouldin.py | """
Created on 12/06/2013
@author: victor
"""
import unittest
from pyproct.clustering.clustering import Clustering
from pyRMSD.condensedMatrix import CondensedMatrix
from pyproct.clustering.cluster import Cluster
import numpy
from pyproct.clustering.evaluation.metrics.test.data import squared_CH_table1
from pyproct.clustering.evaluation.metrics.daviesBouldin import DaviesBouldinCalculator
from pyproct.clustering.evaluation.metrics.common import update_medoids
class TestDaviesBouldin(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.matrix = CondensedMatrix(squared_CH_table1)
cls.clusterings = [Clustering([Cluster(None, [0,1,2,3]), Cluster(None, [4,5])]),
Clustering([Cluster(None, [0,1]), Cluster(None, [2,3]), Cluster(None, [4,5])])]
update_medoids(cls.clusterings[0], cls.matrix)
update_medoids(cls.clusterings[0], cls.matrix)
def test_calculate_average_distances(self):
self.assertItemsEqual(DaviesBouldinCalculator.calc_average_distances(self.clusterings[0], self.matrix),
[7,6])
def test_max_db_term(self):
numpy.testing.assert_almost_equal( DaviesBouldinCalculator.db_terms_for_cluster(0, [5.0, 6.0, 6.0], self.clusterings[1].clusters, self.matrix),
[1.0, 0.7857142857142857], 5)
numpy.testing.assert_almost_equal( DaviesBouldinCalculator.db_terms_for_cluster(1, [5.0, 6.0, 6.0], self.clusterings[1].clusters, self.matrix),
[0.7058823529411765], 5)
numpy.testing.assert_almost_equal( DaviesBouldinCalculator.db_terms_for_cluster(2, [5.0, 6.0, 6.0], self.clusterings[1].clusters, self.matrix),
[], 5)
def test_db_eval(self):
self.assertAlmostEqual(DaviesBouldinCalculator().evaluate(self.clusterings[1], self.matrix), 0.5686274509803922, 5)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() |
digitalinteraction/openmovement | Firmware/WeighAX/Firmware/Common/Graphics/Display controller SSD1306.c | <reponame>digitalinteraction/openmovement
// Display driver for controller SSD1306 (similar to 1308)
// Written in a new format which will be used to control all page orientated displays in future
// <NAME> 08-12-11
#include "Compiler.h"
#include "GenericTypeDefs.h"
#include "TimeDelay.h"
#include "HardwareProfile.h"
// This has the constants in for this .c file in
#include "GraphicsConfig.h"
#ifndef EMULATOR
// Globals
// GD buffer
#pragma idata
unsigned char GDbuffer[(DISPLAY_WIDTH * DISPLAY_ROWS)] = {0};
unsigned char* GDbufferptr = GDbuffer;
#pragma udata
/*Microchip display drive functions*/
//#include "Graphics/Graphics.h"
//#include "Graphics/CustomDisplayDriver.h"
// Used by the Mchips pixel read/write
#define PIXEL_VAL_ON 0xffff
#define PIXEL_VAL_OFF 0x0000
// Color
WORD_VAL _color = {0}; // = (WORD_VAL)PIXEL_VAL_ON;
// Clipping region control
SHORT _clipRgn;
// Clipping region borders
SHORT _clipLeft;
SHORT _clipTop;
SHORT _clipRight;
SHORT _clipBottom;
// Controller specific functions
/*If used with the parralel port with a NAND flash device, be careful not to call these at the
same time since they share a HW module. If bit banged then both devices must be too. */
#ifdef DISPLAY_BITBANGED
#warning "Depreciated - This mode is slow - USES 8080 signaling"
#define DelaySetup() {Nop();Nop();Nop();Nop();Nop();Nop();Nop();Nop();Nop();Nop();}
void DisplayInterfaceOn(void) {}
// Write a raw value to the LCD
inline void DisplayWriteRaw(unsigned char value)
{
DISPLAY_DATA_TRIS = 0x00;
DISPLAY_DATA_WR = value;
DelaySetup();
DISPLAY_WR = 0;
DelaySetup();
DISPLAY_WR = 1;
}
static unsigned char DISPLAY_READ_VALUE;
inline unsigned char DisplayReadRaw(void)
{
unsigned char value;
DISPLAY_DATA_TRIS = 0xff;
value = DISPLAY_READ_VALUE;
DISPLAY_RE = 0;
DelaySetup();
DISPLAY_READ_VALUE = DISPLAY_DATA_RD;
DISPLAY_RE = 1;
return value;
}
#else
// Hardware port used
#ifndef DISPLAY8080
#error "No suport in HW for this mode, should be 8080 to be same as NAND flash devices"
#endif
#ifdef __C30__
#define DelaySetup() __builtin_nop()
// Initialise the PSP module to interface to the DISPLAY
void DisplayInterfaceOn(void)
{ // Tested 07/03/2011 K.Ladha
PMCON = 0b1010001100000000; /* :MSB: PMPEN=1 : NA = 0 : PSIDL = 1 : ADRMUX = 00 : PTBEEN = 0 : PTWREN = 1 : PTRDEN = 1 */
/* :LSB: CSF = 00 : ALP = 0 : CS2P = 0 : CS1P = 0 : BEP = 0 : WRSP = 0 : RDSP = 0 */
PMMODE = 0b0000001000000100; /* :MSB: BUSY = 0 : IRQM = 00 : INCM = 00 : MODE16 = 0 : MODE = 10 */
/* :LSB: WAITB = 00 : WAITM = 0001 : WAITE = 00 (2 Tcy byte write) Set to 1 tcy if at 4 MIPS*/
PMADDR = 0b0000000000000000; /* CS2 = 0 : CS1 = 0 : ADDR : 0b00000000000000 */
PMAEN = 0b0000000000000000; /* PTEN = 0000 0000 0000 00 : PTEN = 00 */
}
#elif defined (__C32__)
#define DelaySetup() asm("nop")
// KL 14-05-2012 Adding support for PIC32 devices
void DisplayInterfaceOn(void)
{
PMCONCLR = 0x8000; // Disable PMP module
PMCON = 0b00000000000000000010001100000000;
PMMODE = 0b00000000000000000000001000000000;
PMADDR = 0; // No address used
PMAEN = 0; // No address lines enabled
PMCONSET = 0x8000; // Enable PMP module
}
#endif
#if defined (__C30) || defined (__C32__)
// If we know the PSP is configured to complet in one clock cycle then we dont need to wait.
#define PSPWait(); {while (PMMODEbits.BUSY);} /*Waits for byte to be clocked out*/
#define DisplayWriteRaw(_value) {DISPLAY_DATA = _value;PSPWait();} /*Initiates HW to write byte*/
#define DisplayReadRaw() (DISPLAY_DATA){PSPWait();} /*You can't use NandReadRaw() as a dummy read, use x=NandReadRaw()*/
#endif
#endif
// Write a command to the DISPLAY
void DisplayWriteCommand(unsigned char command)
{
DISPLAY_CHIP_SELECT = 0;
DISPLAY_COMMAND_DATA = 0; // Command
DelaySetup();
DisplayWriteRaw(command);
DISPLAY_CHIP_SELECT = 1;
DelaySetup();
}
// Write data to the DISPLAY
void DisplayWriteData(unsigned char data)
{
DISPLAY_CHIP_SELECT = 0;
DISPLAY_COMMAND_DATA = 1; // Data
DelaySetup();
DisplayWriteRaw(data);
DISPLAY_CHIP_SELECT = 1;
DelaySetup();
}
// Initialize the graphical DISPLAY display
void DisplayInit(void)
{
DISPLAY_INIT_PINS(); // HW profile - inits to inactive
DisplayInterfaceOn();
DISPLAY_RESET = 0; // reset device
DelayMs(50);
DISPLAY_RESET = 1;
DelayMs(50);
DisplayWriteCommand(0xa8); // Set MUX ratio
DisplayWriteCommand(0x3f); // Set MUX ratio
DisplayWriteCommand(0xd3); // Set display offset
DisplayWriteCommand(0x00); // Set display offset
DisplayWriteCommand(0x40); // Set display start line to 0
//DisplayWriteCommand(0xa0); // Set segment remap
DisplayWriteCommand(0xa1); // Set segment remap reverse
//DisplayWriteCommand(0xc0); // Com direction normal
DisplayWriteCommand(0xc8); // Com direction inverse
DisplayWriteCommand(0xda); // Set COM pins configuration
DisplayWriteCommand(0x12); // configuration - set to default (disable com L/R remap, Alternate com config)
DisplayWriteCommand(0x81); // Set Contrast Control:
DisplayWriteCommand(0xff); // default: 0x7f
DisplayWriteCommand(0xa4); // Disable entire display on
DisplayWriteCommand(0xa6); // Set normal display mode
//DisplayWriteCommand(0xa7); // Set Inverse Display mode
DisplayWriteCommand(0xd5); // Set oscillator frequency
DisplayWriteCommand(0x80); // 0-f freq (8), 0-f prescale (1)
DisplayWriteCommand(0x8d); // Enable charge pump regulator
DisplayWriteCommand(0x14); // turn on
//DisplayWriteCommand(0x10); // turn off
DisplayWriteCommand(0x20); // Set Memory Addressing Mode:
//DisplayWriteCommand(0x00); // horizontal addressing mode
//DisplayWriteCommand(0x01); // vertical addressing mode
DisplayWriteCommand(0x02); // page addressing mode
DisplayWriteCommand(0x21); // set column address range
DisplayWriteCommand(0x00); // first column
DisplayWriteCommand(0x7f); // last column
DisplayWriteCommand(0x22); // set page address range
DisplayWriteCommand(0x00); // set low col address
DisplayWriteCommand(0x07); // set high col address
DisplayWriteCommand(0xb0); // start writing from page 0
//DisplayWriteCommand(0xa0); // segment address remap normal
DisplayWriteCommand(0xa1); // segment address remap reverse
//DisplayWriteCommand(0xd9); // Set precharge segment period?
//DisplayWriteCommand(0x22); // Left as default
//DisplayWriteCommand(0xdb); // Set vcomh deselect level?
//DisplayWriteCommand(0x20); // Left as default
DisplayWriteCommand(0xaf); // display on
//DisplayWriteCommand(0xae); // display off - sleep
// Wait for changes
Delay10us(100);
// Clear display
DisplayClear();
}
// Power saving modes
void DisplayOff(void) // <1uA - call DisplayInit / Restore to resume
{
DisplayWriteCommand(0xae); // display off - sleep
}
extern void DisplaySuspend(void)
{
DisplayWriteCommand(0xae); // display off - Only LCD's support partial power down
}
void DisplayRestore(void)
{
DisplayWriteCommand(0xaf); // display on
}
void DisplaySetContrast(unsigned char contrast)
{
DisplayWriteCommand(0x81); // Set Contrast Control:
DisplayWriteCommand(contrast); // default: 0x7f
}
// Clear the display
void DisplayClearDevice(void)
{
unsigned char column, page;
DISPLAY_CHIP_SELECT = 0;
DelaySetup();
for (page = 0; page < DISPLAY_ROWS; page++)
{
DISPLAY_COMMAND_DATA = 0; // command select
DelaySetup();
DisplayWriteRaw(0x10); // set higher column address = 0
DisplayWriteRaw(0x00); // set lower column address = 0
DisplayWriteRaw(0xb0 | page); // set page
for (column = 0; column < DISPLAY_WIDTH; column++)
{
DISPLAY_COMMAND_DATA = 1; // data select
DelaySetup();
#ifdef DISPLAY_DEBUG
DisplayWriteRaw(((column >> 2) & 1) ? 0xf0 : 0x0f); // debug pattern - should be 4x4 pixel checkerboard on full display
#else
DisplayWriteRaw(0x00); // clear
#endif
}
}
DISPLAY_COMMAND_DATA = 0; // command select
DelaySetup();
DisplayWriteRaw(0x10); // set higher column address = 0
DisplayWriteRaw(0x00); // set lower column address = 0
DisplayWriteRaw(0xb0); // page increment = 0
DISPLAY_CHIP_SELECT = 1;
DelaySetup();
}
// Clear from RAM
void DisplayClearRam(unsigned char *buffer, unsigned char span)
{
// GDbuffer is is same page orientated structure as the display
// i,e, the first 128 bytes is the top line 128x8 pixels
unsigned char i;
if (span == DISPLAY_WIDTH)
{
memset(buffer ,0, (DISPLAY_WIDTH * DISPLAY_ROWS));
}
for (i=0;i<8;i++) // all 8 lines
{
memset(buffer ,0, span);
buffer += (DISPLAY_WIDTH - span);
}
}
void DisplayClear(void)
{
DisplayClearRam(GDbuffer, DISPLAY_WIDTH);
DisplayClearDevice();
}
void DisplayRefresh(unsigned char *buffer, unsigned char span)
{
unsigned char row,col;
unsigned char *src = buffer;
DISPLAY_CHIP_SELECT = 0;
DelaySetup();
// Note: I'm not going to update the top two lines so
// I can show the time etc on them.
#ifndef DONT_REFRESH_TOP_DISP_LINES
for(row=0;row<DISPLAY_ROWS;row++)
{
#else
src += span;src += span;
for(row=2;row<DISPLAY_ROWS;row++)
{
#endif
// Load DISPLAY data address column and row
DISPLAY_COMMAND_DATA = 0; // command select
DelaySetup();
// Select the byte
DisplayWriteRaw(0x10); // set higher column address = 0
DisplayWriteRaw(0x00); // set lower column address = 0
DisplayWriteRaw(0xb0 | row); // set page
DISPLAY_COMMAND_DATA = 1; // data select
DelaySetup();
for(col=0;col<DISPLAY_WIDTH;col++)
{
DisplayWriteRaw(*src++);
}
// Skip any padding bytes between rows
src += span - DISPLAY_WIDTH;
}
DISPLAY_CHIP_SELECT = 1; // Deselect
DelaySetup();
}
// Microchips compatibility functions
/*********************************************************************
* Function: void ResetDevice()
*
* PreCondition: none
*
* Input: none
*
* Output: none
*
* Side Effects: none
*
* Overview: resets DISPLAY, initializes PMP
*
* Note: none
*
********************************************************************/
void ResetDevice(void)
{
//DisplayInit();
DisplayClear();
}
/*********************************************************************
* Function: void UpdateDisplayNow(void)
*
* Overview: Synchronizes the draw and frame buffers immediately.
*
* PreCondition: none
*
* Input: none
*
* Output: none
*
* Side Effects: none
*
********************************************************************/
void UpdateDisplayNow(void)
{
DisplayRefresh(GDbuffer, DISPLAY_WIDTH);
}
/*********************************************************************
* Function: void PutPixel(SHORT x, SHORT y)
*
* PreCondition: none
*
* Input: x,y - pixel coordinates
*
* Output: none
*
* Side Effects: none
*
* Overview: puts pixel
*
* Note: none
*
********************************************************************/
void PutPixel(SHORT x, SHORT y)
{
unsigned char column,temp,bit_mask;//page;
unsigned int page;
unsigned char* GDptr = GDbufferptr;
// Convert coordinates
column = x&DISPLAY_WIDTH_MASK; // 0-128
page = (y>>DISPLAY_ROW_BITS)&DISPLAY_ROW_MASK; // 0-8
temp = y&DISPLAY_ROW_MASK;
bit_mask = 1<<temp;
GDptr+= column+(DISPLAY_WIDTH*page);
// Set the bit
if (_color.Val) // Pixel on
{
*GDptr|=bit_mask;
}
else // Pixel off
{
*GDptr&=~bit_mask;
}
return;
}
/*********************************************************************
* Function: WORD GetPixel(SHORT x, SHORT y)
*
* PreCondition: none
*
* Input: x,y - pixel coordinates
*
* Output: pixel color
*
* Side Effects: none
*
* Overview: returns pixel color at x,y position
*
* Note: none
*
********************************************************************/
WORD GetPixel(SHORT x, SHORT y)
{
unsigned char column,temp,bit_mask;//page;
unsigned int page;
unsigned char* GDptr = GDbufferptr;
// Convert coordinates
column = x&DISPLAY_WIDTH_MASK; // 0-128
//page = (y>>DISPLAY_ROW_BITS)&DISPLAY_ROW_MASK; // 0-8
temp = y&DISPLAY_ROW_MASK;
bit_mask = 1<<temp;
//GDptr+= column+(DISPLAY_WIDTH*page);
// Optimise
page = (y<<(DISPLAY_WIDTH_BITS-DISPLAY_ROW_BITS)); // 0-8 * 128
GDptr+= column+page;
// Set the bit
if (*GDptr&bit_mask) // Pixel on
{
return PIXEL_VAL_ON;
}
else // Pixel off
{
return PIXEL_VAL_OFF;
}
}
/*********************************************************************
* Function: SetClip(control)
*
* Overview: Enables/disables clipping.
*
* PreCondition: none
*
* Input: control - Enables or disables the clipping.
* - CLIP_DISABLE: Disable clipping
* - CLIP_ENABLE: Enable clipping
*
* Output: none
*
* Side Effects: none
*
********************************************************************/
void SetClip(BYTE control)
{
//TODO: Figure out what this function is supposed to do?
return;
}
/*********************************************************************
* Function: IsDeviceBusy()
*
* Overview: Returns non-zero if LCD controller is busy
* (previous drawing operation is not completed).
*
* PreCondition: none
*
* Input: none
*
* Output: Busy status.
*
* Side Effects: none
*
********************************************************************/
WORD IsDeviceBusy()
{
// TODO: add function that checks whether current GD buffer is on screen
return 0;
}
// End Mchip compatibility code
#else
// Emulated DISPLAY update functions
void DisplayInit(void) { ; }
void DisplayOff(void) { ; }
void DisplayRefresh(unsigned char *buffer, unsigned char span)
{
EmuDisplayRefresh(buffer, span);
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.