max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
4,339 | <filename>modules/core/src/test/java/org/apache/ignite/cache/RebalanceAfterResettingLostPartitionTest.java<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.cache;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.TestRecordingCommunicationSpi;
import org.apache.ignite.internal.processors.cache.GridCacheGroupIdMessage;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionSupplyMessage;
import org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionState;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.lang.IgniteBiPredicate;
import org.apache.ignite.plugin.extensions.communication.Message;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
*
*/
public class RebalanceAfterResettingLostPartitionTest extends GridCommonAbstractTest {
/** Cache name. */
private static final String CACHE_NAME = "cache" + UUID.randomUUID().toString();
/** Cache size */
public static final int CACHE_SIZE = 10_000;
/** Stop all grids and cleanup persistence directory. */
@Before
public void before() throws Exception {
stopAllGrids();
cleanPersistenceDir();
}
/** Stop all grids and cleanup persistence directory. */
@After
public void after() throws Exception {
stopAllGrids();
cleanPersistenceDir();
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
cfg.setCommunicationSpi(new TestRecordingCommunicationSpi());
cfg.setRebalanceBatchSize(100);
cfg.setConsistentId(igniteInstanceName);
DataStorageConfiguration storageCfg = new DataStorageConfiguration().setWalSegmentSize(4 * 1024 * 1024);
storageCfg.getDefaultDataRegionConfiguration()
.setPersistenceEnabled(true)
.setMaxSize(500L * 1024 * 1024);
cfg.setDataStorageConfiguration(storageCfg);
cfg.setCacheConfiguration(new CacheConfiguration()
.setName(CACHE_NAME)
.setCacheMode(CacheMode.PARTITIONED)
.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)
.setAffinity(new RendezvousAffinityFunction(false, 32))
.setBackups(1));
return cfg;
}
/**
* Test to restore lost partitions and rebalance data on working grid with two nodes.
*
* @throws Exception if fail.
*/
@SuppressWarnings("unchecked")
@Test
public void testRebalanceAfterPartitionsWereLost() throws Exception {
startGrids(2);
grid(0).cluster().active(true);
for (int j = 0; j < CACHE_SIZE; j++)
grid(0).cache(CACHE_NAME).put(j, "Value" + j);
String g1Name = grid(1).name();
// Stopping the the second node.
stopGrid(1);
// Cleaning the persistence for second node.
cleanPersistenceDir(g1Name);
AtomicInteger msgCntr = new AtomicInteger();
TestRecordingCommunicationSpi.spi(ignite(0)).blockMessages(new IgniteBiPredicate<ClusterNode, Message>() {
@Override public boolean apply(ClusterNode clusterNode, Message msg) {
if (msg instanceof GridDhtPartitionSupplyMessage &&
((GridCacheGroupIdMessage)msg).groupId() == CU.cacheId(CACHE_NAME)) {
if (msgCntr.get() > 3)
return true;
else
msgCntr.incrementAndGet();
}
return false;
}
});
// Starting second node again(with the same consistent id).
startGrid(1);
// Waitting for rebalance.
TestRecordingCommunicationSpi.spi(ignite(0)).waitForBlocked();
// Killing the first node at the moment of rebalancing.
stopGrid(0);
// Returning first node to the cluster.
IgniteEx g0 = startGrid(0);
assertTrue(Objects.requireNonNull(
grid(0).cachex(CACHE_NAME)).context().topology().localPartitions().stream().allMatch(
p -> p.state() == GridDhtPartitionState.LOST));
// Verify that partition loss is detected.
assertTrue(Objects.requireNonNull(
grid(1).cachex(CACHE_NAME)).context().topology().localPartitions().stream().allMatch(
p -> p.state() == GridDhtPartitionState.LOST));
// Reset lost partitions and wait for PME.
grid(1).resetLostPartitions(Arrays.asList(CACHE_NAME, "ignite-sys-cache"));
awaitPartitionMapExchange();
assertTrue(Objects.requireNonNull(
grid(0).cachex(CACHE_NAME)).context().topology().localPartitions().stream().allMatch(
p -> p.state() == GridDhtPartitionState.OWNING));
// Verify that partitions are in owning state.
assertTrue(Objects.requireNonNull(
grid(1).cachex(CACHE_NAME)).context().topology().localPartitions().stream().allMatch(
p -> p.state() == GridDhtPartitionState.OWNING));
// Verify that data was successfully rebalanced.
for (int i = 0; i < CACHE_SIZE; i++)
assertEquals("Value" + i, grid(0).cache(CACHE_NAME).get(i));
for (int i = 0; i < CACHE_SIZE; i++)
assertEquals("Value" + i, grid(1).cache(CACHE_NAME).get(i));
}
}
| 2,562 |
1,323 | <gh_stars>1000+
//
// GJGCGroupShowItem.h
// ZYChat
//
// Created by ZYVincent QQ:1003081775 on 14-11-6.
// Copyright (c) 2014年 ZYV. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "GJGCCommonHeadView.h"
@interface GJGCInformationGroupShowItemModel : NSObject
@property (nonatomic,strong)NSAttributedString *name;
@property (nonatomic,strong)NSString *headUrl;
@property (nonatomic,assign)long long groupId;
@end
@interface GJGCInformationGroupShowItem : UIButton
@property (nonatomic,strong)GJGCCommonHeadView *headView;
@property (nonatomic,strong)GJCFCoreTextContentView *nameLabel;
@property (nonatomic,strong)UIImageView *seprateLine;
@property (nonatomic,assign)BOOL showBottomSeprateLine;
- (void)setGroupItem:(GJGCInformationGroupShowItemModel *)contentModel;
@end
| 288 |
6,497 | <reponame>JokerQueue/cachecloud
package com.sohu.cache.entity;
import lombok.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 客户端耗时统计
* @author leifu
*/
@Data
public class AppClientCostTimeStat {
private long id;
/**
* 应用id
*/
private long appId;
/**
* 格式yyyyMMddHHmm00
*/
private long collectTime;
/**
* 客户端ip
*/
private String clientIp;
/**
* 上报时间
*/
private Date reportTime;
/**
* 创建时间
*/
private Date createTime;
/**
* 命令
*/
private String command;
/**
* 调用次数
*/
private int count;
/**
* 实例ip
*/
private String instanceHost;
/**
* 实例port
*/
private int instancePort;
/**
* 实例id
*/
private long instanceId;
/**
* 中位值
*/
private int median;
/**
* 平均值
*/
private double mean;
/**
* 90%最大值
*/
private int ninetyPercentMax;
/**
* 99%最大值
*/
private int ninetyNinePercentMax;
/**
* 100%最大值
*/
private int hundredMax;
public Date getReportTime() {
return (Date) reportTime.clone();
}
public void setReportTime(Date reportTime) {
this.reportTime = (Date) reportTime.clone();
}
public Date getCreateTime() {
return (Date) createTime.clone();
}
public void setCreateTime(Date createTime) {
this.createTime = (Date) createTime.clone();
}
public Long getCollectTimeStamp() throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date;
try {
date = sdf.parse(String.valueOf(this.collectTime));
return date.getTime();
} catch (Exception e) {
return 0L;
}
}
public Long getTimeStamp() throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = sdf.parse(String.valueOf(this.collectTime));
return date.getTime();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((clientIp == null) ? 0 : clientIp.hashCode());
result = prime * result + (int) (instanceId ^ (instanceId >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AppClientCostTimeStat other = (AppClientCostTimeStat) obj;
if (clientIp == null) {
if (other.clientIp != null)
return false;
} else if (!clientIp.equals(other.clientIp))
return false;
if (instanceId != other.instanceId)
return false;
return true;
}
}
| 1,607 |
494 | <filename>astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/AbstractRowSliceQueryImpl.java
/*******************************************************************************
* Copyright 2011 Netflix
*
* 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.netflix.astyanax.thrift;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
import org.apache.cassandra.thrift.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import com.netflix.astyanax.Serializer;
import com.netflix.astyanax.model.ByteBufferRange;
import com.netflix.astyanax.model.ColumnSlice;
import com.netflix.astyanax.query.RowSliceQuery;
public abstract class AbstractRowSliceQueryImpl<K, C> implements RowSliceQuery<K, C> {
protected SlicePredicate predicate = new SlicePredicate().setSlice_range(ThriftUtils.createAllInclusiveSliceRange());
private Serializer<C> serializer;
public AbstractRowSliceQueryImpl(Serializer<C> serializer) {
this.serializer = serializer;
}
@Override
public RowSliceQuery<K, C> withColumnSlice(C... columns) {
if (columns != null) {
predicate.setColumn_names(serializer.toBytesList(Arrays.asList(columns))).setSlice_rangeIsSet(false);
}
return this;
}
@Override
public RowSliceQuery<K, C> withColumnSlice(Collection<C> columns) {
if (columns != null)
predicate.setColumn_names(serializer.toBytesList(columns)).setSlice_rangeIsSet(false);
return this;
}
@Override
public RowSliceQuery<K, C> withColumnRange(C startColumn, C endColumn, boolean reversed, int count) {
predicate.setSlice_range(ThriftUtils.createSliceRange(serializer, startColumn, endColumn, reversed, count));
return this;
}
@Override
public RowSliceQuery<K, C> withColumnRange(ByteBuffer startColumn, ByteBuffer endColumn, boolean reversed, int count) {
predicate.setSlice_range(new SliceRange(startColumn, endColumn, reversed, count));
return this;
}
@Override
public RowSliceQuery<K, C> withColumnSlice(ColumnSlice<C> slice) {
if (slice.getColumns() != null) {
predicate.setColumn_names(serializer.toBytesList(slice.getColumns())).setSlice_rangeIsSet(false);
}
else {
predicate.setSlice_range(ThriftUtils.createSliceRange(serializer, slice.getStartColumn(),
slice.getEndColumn(), slice.getReversed(), slice.getLimit()));
}
return this;
}
@Override
public RowSliceQuery<K, C> withColumnRange(ByteBufferRange range) {
predicate.setSlice_range(new SliceRange().setStart(range.getStart()).setFinish(range.getEnd())
.setCount(range.getLimit()).setReversed(range.isReversed()));
return this;
}
}
| 1,200 |
841 | <reponame>ProgrammingLanguageLeader/django-user-accounts<gh_stars>100-1000
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-13 08:55
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('account', '0002_fix_str'),
]
operations = [
migrations.CreateModel(
name='PasswordExpiry',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('expiry', models.PositiveIntegerField(default=0)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='password_expiry', to=settings.AUTH_USER_MODEL, verbose_name='user')),
],
),
migrations.CreateModel(
name='PasswordHistory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=255)),
('timestamp', models.DateTimeField(default=django.utils.timezone.now)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='password_history', to=settings.AUTH_USER_MODEL)),
],
),
]
| 666 |
324 | <gh_stars>100-1000
/**
* Copyright (C) 2012 10gen Inc.
* Copyright (C) 2013 Tokutek Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mongo/pch.h"
#include "mongo/db/client.h"
#include "mongo/db/commands/fsync.h"
#include "mongo/db/commands/server_status.h"
#include "mongo/db/crash.h"
#include "mongo/db/repl/bgsync.h"
#include "mongo/db/repl/rs_sync.h"
#include "mongo/base/counter.h"
#include "mongo/db/stats/timer_stats.h"
#include "mongo/client/remote_transaction.h"
#include "mongo/db/ops/delete.h"
#include "mongo/db/ops/insert.h"
namespace mongo {
#define ROLLBACK_ID "rollbackStatus"
void incRBID();
void applyMissingOpsInOplog(GTID minUnappliedGTID, const bool inRollback);
// this enum represents possible values stored in local.replInfo during
// rollback, under the "rollbackStatus" document. The existence of this
// document implies that a rollback is in progress. It's possible
// to resume a rollback that is in some of these states. We save this
// state because we don't want to depend on rollback succeeding in "one shot".
// A lot can go wrong, like a connection dying.
enum rollback_state {
RB_NOT_STARTED = 0, // this means that we have not started a rollback
RB_STARTING, // means we have started rolling back oplog entries. We cannot recover from this state
RB_DOCS_REMOVED, // documents have been removed, but a remove snapshot's version has not been applied
RB_SNAPSHOT_APPLIED // remote snapshot of documents has been applied, but we have yet to sync forward to a safe point
// After syncing forward, via replicateForwardToGTID, we are done with rollback
};
static BSONObj findOneFromConn(DBClientConnection* conn, const string &ns, const Query& query) {
return conn->findOne(ns, query, 0, QueryOption_SlaveOk);
}
// assumes transaction is created
void updateRollbackStatus(const BSONObj& status) {
BSONObj o = status.getOwned();
LOCK_REASON(lockReason, "repl rollback: updating rollback status to replInfo");
Client::ReadContext ctx(rsReplInfo, lockReason);
Collection* replInfoDetails = getCollection(rsReplInfo);
verify(replInfoDetails);
const uint64_t flags = Collection::NO_UNIQUE_CHECKS | Collection::NO_LOCKTREE;
replInfoDetails->insertObject(o, flags);
}
bool getRollbackStatus(BSONObj& o) {
LOCK_REASON(lockReason, "repl rollback: getting rollback status from replInfo");
Client::ReadContext ctx(rsReplInfo, lockReason);
Client::Transaction txn(DB_READ_UNCOMMITTED);
bool found = Collection::findOne(rsReplInfo, BSON("_id" << ROLLBACK_ID), o, true);
txn.commit();
return found;
}
void clearRollbackStatus(const BSONObj& status) {
LOCK_REASON(lockReason, "repl rollback: clearing rollback status");
Client::ReadContext ctx(rsReplInfo, lockReason);
Collection* cl= getCollection(rsReplInfo);
verify(cl);
cl->deleteObject(BSON("" << ROLLBACK_ID), status);
}
bool isRollbackRequired(OplogReader& r, uint64_t *lastTS) {
string hn = r.conn()->getServerAddress();
verify(r.more());
BSONObj rollbackStatus;
bool found = getRollbackStatus(rollbackStatus);
if (found) {
// we have a rollback in progress,
// must complete it
log() << "Rollback needed, found rollbackStatus: " << rollbackStatus << rsLog;
return true;
}
BSONObj o = r.nextSafe();
uint64_t ts = o["ts"]._numberLong();
uint64_t lastHash = o["h"].numberLong();
GTID gtid = getGTIDFromBSON("_id", o);
if (!theReplSet->gtidManager->rollbackNeeded(gtid, ts, lastHash)) {
log() << "Rollback NOT needed! " << gtid << endl;
return false;
}
log() << "Rollback needed! Our GTID: " <<
theReplSet->gtidManager->getLiveState().toString() <<
", remote GTID: " << gtid.toString() << ". Attempting rollback." << rsLog;
*lastTS = ts;
return true;
}
void findRollbackPoint(
OplogReader& r, uint64_t oplogTS,
GTID* idToRollbackTo,
uint64_t* rollbackPointTS,
uint64_t* rollbackPointHash
)
{
bool gtidFound = false;
try {
GTID ourLast = theReplSet->gtidManager->getLiveState();
shared_ptr<DBClientCursor> rollbackCursor = r.getRollbackCursor(ourLast);
uassert(17350, "rollback failed to get a cursor to start reading backwards from.", rollbackCursor.get());
while (rollbackCursor->more()) {
BSONObj remoteObj = rollbackCursor->next();
GTID remoteGTID = getGTIDFromBSON("_id", remoteObj);
uint64_t remoteTS = remoteObj["ts"]._numberLong();
uint64_t remoteLastHash = remoteObj["h"].numberLong();
if (remoteTS + 1800*1000 < oplogTS) {
log() << "Rollback takes us too far back, throwing exception. remoteTS: " << remoteTS << " oplogTS: " << oplogTS << rsLog;
throw RollbackOplogException("replSet rollback too long a time period for a rollback (at least 30 minutes).");
break;
}
//now try to find an entry in our oplog with that GTID
BSONObjBuilder localQuery;
BSONObj localObj;
addGTIDToBSON("_id", remoteGTID, localQuery);
bool foundLocally = false;
{
LOCK_REASON(lockReason, "repl: looking up oplog entry for rollback");
Client::ReadContext ctx(rsoplog, lockReason);
Client::Transaction transaction(DB_SERIALIZABLE);
foundLocally = Collection::findOne(rsoplog, localQuery.done(), localObj);
transaction.commit();
}
if (foundLocally) {
GTID localGTID = getGTIDFromBSON("_id", localObj);
uint64_t localTS = localObj["ts"]._numberLong();
uint64_t localLastHash = localObj["h"].numberLong();
if (localLastHash == remoteLastHash &&
localTS == remoteTS &&
GTID::cmp(localGTID, remoteGTID) == 0
)
{
*idToRollbackTo = localGTID;
*rollbackPointTS = localTS;
*rollbackPointHash = localLastHash;
gtidFound = true;
log() << "found id to rollback to " << idToRollbackTo->toString() << rsLog;
break;
}
}
}
// At this point, either we have found the point to try to rollback to,
// or we have determined that we cannot rollback
if (!gtidFound) {
// we cannot rollback
throw RollbackOplogException("could not find ID to rollback to");
}
}
catch (DBException& e) {
log() << "Caught DBException during rollback " << e.toString() << rsLog;
throw RollbackOplogException("DBException while trying to find ID to rollback to: " + e.toString());
}
catch (std::exception& e2) {
log() << "Caught std::exception during rollback " << e2.what() << rsLog;
throw RollbackOplogException(str::stream() << "Exception while trying to find ID to rollback to: " << e2.what());
}
}
bool canStartRollback(OplogReader& r, GTID idToRollbackTo) {
shared_ptr<DBClientConnection> conn(r.conn_shared());
// before we start rollback, let's make sure that the minUnapplied on the remote
// server is past the id that we are rolling back to. Otherwise, the snapshot
// we create will not be up to date, and the rollback algorithm will not work
BSONObjBuilder b;
b.append("_id", "minUnapplied");
// Note that another way to get this information is to
// request a heartbeat. That one will technically return
// a more up to date value for minUnapplied
BSONObj res = findOneFromConn(conn.get(), rsReplInfo, Query(b.done()));
GTID minUnapplied = getGTIDFromBSON("GTID", res);
if (GTID::cmp(minUnapplied, idToRollbackTo) < 0) {
log() << "Remote server has minUnapplied " << minUnapplied.toString() << \
" we want to rollback to " << idToRollbackTo.toString() << \
". Therefore, exiting and retrying." << rsLog;
return false;
}
return true;
}
// transitions us to rollback state,
// writes to replInfo fact that we have started rollback
void startRollback(
GTID idToRollbackTo,
uint64_t rollbackPointTS,
uint64_t rollbackPointHash
)
{
incRBID();
// now that we are settled, we have to take care of the GTIDManager
// and the repl info thread.
// We need to reset the state of the GTIDManager to the point
// we intend to rollback to, and we need to make sure that the repl info thread
// has captured this information.
theReplSet->gtidManager->resetAfterInitialSync(
idToRollbackTo,
rollbackPointTS,
rollbackPointHash
);
// now force an update of the repl info thread
theReplSet->forceUpdateReplInfo();
Client::Transaction txn(DB_SERIALIZABLE);
updateRollbackStatus(BSON("_id" << ROLLBACK_ID << "state" << RB_STARTING<< "info" << "starting rollback"));
txn.commit(DB_TXN_NOSYNC);
}
void rollbackToGTID(GTID idToRollbackTo, RollbackDocsMap* docsMap, RollbackSaveData* rsSave) {
// at this point, everything should be settled, the applier should
// have nothing left (and remain that way, because this is the only
// thread that can put work on the applier). Now we can rollback
// the data.
while (true) {
BSONObj o;
{
LOCK_REASON(lockReason, "repl: checking for oplog data");
Client::ReadContext ctx(rsoplog, lockReason);
Client::Transaction txn(DB_SERIALIZABLE);
// if there is nothing in the oplog, break
o = getLastEntryInOplog();
if (o.isEmpty()) {
throw RollbackOplogException("Oplog empty when rolling back to a GTID");
}
}
GTID lastGTID = getGTIDFromBSON("_id", o);
// if we have rolled back enough, break from while loop
if (GTID::cmp(lastGTID, idToRollbackTo) <= 0) {
dassert(GTID::cmp(lastGTID, idToRollbackTo) == 0);
break;
}
rollbackTransactionFromOplog(o, docsMap, rsSave);
}
log() << "Rolling back to " << idToRollbackTo.toString() << " produced " <<
docsMap->size() << " documents for which we need to retrieve a snapshot of." << rsLog;
}
void removeDataFromDocsMap() {
Client::Transaction txn(DB_SERIALIZABLE);
RollbackDocsMapIterator docsMap;
size_t numDocs = 0;
log() << "Removing documents from collections for rollback." << rsLog;
for (RollbackDocsMapIterator it; it.ok(); it.advance()){
numDocs++;
DocID curr = it.current();
LOCK_REASON(lockReason, "repl: deleting a doc during rollback");
Client::ReadContext ctx(curr.ns, lockReason);
Collection* cl = getCollection(curr.ns);
verify(cl);
BSONObj currDoc;
LOG(2) << "Finding by pk of " << curr.pk << rsLog;
bool found = cl->findByPK(curr.pk, currDoc);
if (found) {
deleteOneObject(cl, curr.pk, currDoc, Collection::NO_LOCKTREE);
}
}
log() << "Done removing " << numDocs << " documents from collections for rollback." << rsLog;
updateRollbackStatus(BSON("_id" << ROLLBACK_ID << "state" << RB_DOCS_REMOVED<< \
"info" << "removed docs from docs map"));
txn.commit(DB_TXN_NOSYNC);
}
// on input, conn is a connection for which the caller has created a multi-statement
// mvcc transaction over it. Reads the document from the remote server and
// applies it locally
void applySnapshotOfDocsMap(shared_ptr<DBClientConnection> conn) {
size_t numDocs = 0;
log() << "Applying documents to collections for rollback." << rsLog;
for (RollbackDocsMapIterator it; it.ok(); it.advance()){
numDocs++;
DocID curr = it.current();
LOCK_REASON(lockReason, "repl: appling snapshot of doc during rollback");
Client::ReadContext ctx(curr.ns, lockReason);
Collection* cl = getCollection(curr.ns);
if (cl->isPKHidden()) {
log() << "Collection " << curr.ns << " has a hidden PK, yet it has \
a document for which we want to apply a snapshot of: " << \
curr.pk << rsLog;
throw RollbackOplogException("Collection for which we are applying a document has a hidden PK");
}
BSONObj pkWithFields = cl->fillPKWithFields(curr.pk);
BSONObj remoteImage = findOneFromConn(conn.get(), curr.ns, Query(pkWithFields));
if (!remoteImage.isEmpty()) {
const uint64_t flags = Collection::NO_UNIQUE_CHECKS | Collection::NO_LOCKTREE;
insertOneObject(cl, remoteImage, flags);
}
}
log() << "Done applying remote images of " << numDocs << " documents to collections for rollback." << rsLog;
}
class RollbackGTIDSetBuilder {
GTID _minUnappliedGTID;
static void removeExistingGTIDSet() {
string errmsg;
Collection* cl = getCollection(rsRollbackGTIDSet);
if (cl != NULL) {
BSONObjBuilder result;
cl->drop(errmsg,result);
cl = NULL;
}
}
public:
RollbackGTIDSetBuilder(GTID minUnapplied) {
// write lock needed to (maybe) drop and recreate the
// collection
LOCK_REASON(lockReason, "repl: initializing set of committed GTIDs during rollback");
Client::WriteContext ctx(rsRollbackGTIDSet, lockReason);
removeExistingGTIDSet();
Collection* cl = getOrCreateCollection(rsRollbackGTIDSet, false);
BSONObjBuilder docBuilder;
docBuilder.append("_id", "minUnapplied");
docBuilder.append("gtid", minUnapplied);
const uint64_t flags = Collection::NO_UNIQUE_CHECKS | Collection::NO_LOCKTREE;
BSONObj doc = docBuilder.done();
insertOneObject(cl, doc, flags);
_minUnappliedGTID = minUnapplied;
}
void addGTID(GTID gtid) {
if (GTID::cmp(_minUnappliedGTID, gtid) <= 0) {
Collection* cl = getCollection(rsRollbackGTIDSet);
verify(cl);
BSONObjBuilder docBuilder;
docBuilder.append("_id", gtid);
const uint64_t flags = Collection::NO_UNIQUE_CHECKS | Collection::NO_LOCKTREE;
BSONObj doc = docBuilder.obj();
insertOneObject(cl, doc, flags);
}
}
static void dropGTIDSet() {
LOCK_REASON(lockReason, "repl: dropping set of committed GTIDs during rollback");
Client::WriteContext ctx(rsRollbackGTIDSet, lockReason);
removeExistingGTIDSet();
}
};
class RollbackGTIDSet {
GTID _minUnappliedGTID;
public:
RollbackGTIDSet() { }
GTID getMinUnapplied() {
return _minUnappliedGTID;
}
void initialize() {
LOCK_REASON(lockReason, "repl rollback: initializing RollbackGTIDSet");
Client::ReadContext ctx(rsRollbackGTIDSet, lockReason);
Client::Transaction transaction(DB_READ_UNCOMMITTED);
Collection* cl = getCollection(rsRollbackGTIDSet);
verify(cl);
BSONObj o;
bool foundMinUnapplied = Collection::findOne(
rsRollbackGTIDSet,
BSON ("_id" << "minUnapplied"),
o,
true
);
verify(foundMinUnapplied);
_minUnappliedGTID = getGTIDFromBSON("gtid", o);
transaction.commit();
}
bool GTIDExists(GTID gtid) {
if (GTID::cmp(gtid, _minUnappliedGTID) < 0) {
return true;
}
LOCK_REASON(lockReason, "repl rollback: checking to see if a GTID exists");
Client::ReadContext ctx(rsRollbackGTIDSet, lockReason);
Client::Transaction transaction(DB_READ_UNCOMMITTED);
BSONObj result;
Collection* cl = getCollection(rsRollbackGTIDSet);
verify(cl); // sanity check
bool found = Collection::findOne(
rsRollbackGTIDSet,
BSON ("_id" << gtid),
result,
true
);
transaction.commit();
return found;
}
};
void createAppliedGTIDSet(
GTID minUnapplied,
shared_ptr<DBClientConnection> conn,
RollbackGTIDSetBuilder* appliedGTIDs
)
{
LOCK_REASON(lockReason, "repl: adding list of committed GTIDs during rollback");
Client::ReadContext ctx(rsRollbackGTIDSet, lockReason);
log() << "creating GTIDSet with minUnapplied " << minUnapplied.toString() << rsLog;
uint64_t numGTIDs = 0;
// we have gotten the minUnapplied and lastGTID on the remote server,
// now let's look at the oplog from that point on to learn what the gaps are
BSONObj query = BSON("_id" << BSON("$gte" << minUnapplied));
const BSONObj fields = BSON("_id" << 1 << "a" << 1);
shared_ptr<DBClientCursor> cursor(
conn->query(
rsoplog,
Query(query).hint(BSON("_id" << 1)),
0,
0,
&fields,
QueryOption_SlaveOk
).release()
);
// now we have a cursor
// put each doc we get back into a map
uassert(17360, "Could not create a cursor to read remote oplog GTIDs during rollback", cursor.get());
while (cursor->more()) {
BSONObj curr = cursor->next();
GTID gtid = getGTIDFromBSON("_id", curr);
bool applied = curr["a"].Bool();
if (applied) {
appliedGTIDs->addGTID(gtid);
numGTIDs++;
}
}
log() << "done creating RollbackGTIDSet with " << numGTIDs << " GTIDs." << rsLog;
}
void applyInformationFromRemoteSnapshot(OplogReader& r) {
shared_ptr<DBClientConnection> conn(r.conn_shared());
RemoteTransaction rtxn(*conn, "mvcc");
BSONObj lastOp = findOneFromConn(conn.get(), rsoplog, Query().sort(reverseIDObj));
log() << "lastOp of snapshot " << lastOp << rsLog;
GTID lastGTID = getGTIDFromBSON("_id", lastOp);
uint64_t lastHash = lastOp["h"].numberLong();
// two things to do, first is to get the snapshot of the oplog and find out what
// gaps exist
BSONObjBuilder b;
b.append("_id", "minUnapplied");
BSONObj res = findOneFromConn(conn.get(), rsReplInfo , b.done());
GTID minUnapplied = getGTIDFromBSON("GTID", res);
Client::Transaction txn(DB_SERIALIZABLE);
RollbackGTIDSetBuilder appliedGTIDsBuilder(minUnapplied);
createAppliedGTIDSet(minUnapplied, conn, &appliedGTIDsBuilder);
// apply snapshot of each doc in docsMap
applySnapshotOfDocsMap(conn);
bool ok = rtxn.commit();
verify(ok); // absolutely no reason this should fail, it was read only
RemoteTransaction rSecondTxn(*conn, "readUncommitted");
BSONObj lastObjAfterSnapshotDone = r.getLastOp();
log() << "lastOp after snapshot " << lastObjAfterSnapshotDone << rsLog;
GTID lastGTIDAfterSnapshotDone = getGTIDFromBSON("_id", lastObjAfterSnapshotDone);
uint64_t lastTSAfterSnapshotDone = lastObjAfterSnapshotDone["ts"]._numberLong();
uint64_t lastHashAfterSnapshotDone = lastObjAfterSnapshotDone["h"].numberLong();
ok = rSecondTxn.commit();
verify(ok); // absolutely no reason this should fail, it was read only
BSONObjBuilder statusBuilder;
statusBuilder.append("_id", ROLLBACK_ID);
statusBuilder.append("state", RB_SNAPSHOT_APPLIED);
statusBuilder.append("info", "applied snapshot data, about to run forward");
statusBuilder.append("lastGTID", lastGTID);
statusBuilder.append("lastHash", (long long)lastHash);
statusBuilder.append("lastGTIDAfterSnapshotDone", lastGTIDAfterSnapshotDone);
statusBuilder.appendDate("lastTSAfterSnapshotDone", lastTSAfterSnapshotDone);
statusBuilder.append("lastHashAfterSnapshotDone", (long long)lastHashAfterSnapshotDone);
updateRollbackStatus(statusBuilder.done());
txn.commit(DB_TXN_NOSYNC);
}
void replicateForwardToGTID(
OplogReader& r,
bool preSnapshot
)
{
// now replicate everything until we get to lastGTID
// start from idToRollbackTo
BSONObj o;
bool found = getRollbackStatus(o);
verify(found);
log() << "Rollback status: " << o << rsLog;
verify(o["state"].Int() == RB_SNAPSHOT_APPLIED);
GTID lastGTID;
uint64_t lastHash;
if (preSnapshot) {
lastGTID = getGTIDFromBSON("lastGTID", o);
lastHash = o["lastHash"].numberLong();
}
else {
lastGTID = getGTIDFromBSON("lastGTIDAfterSnapshotDone", o);
lastHash = o["lastHashAfterSnapshotDone"].numberLong();
}
GTID startPoint;
{
Client::Transaction txn(DB_SERIALIZABLE);
BSONObj start = getLastEntryInOplog();
startPoint = getGTIDFromBSON("_id", start);
txn.commit();
}
log () << "replicating from " << startPoint.toString() << " to " << lastGTID.toString() << rsLog;
if (GTID::cmp(startPoint, lastGTID) >= 0) {
log() << "returning early because startPoint >= lastGTID" << rsLog;
return;
}
// let's first do a sanity check that the remote machine we are replicating from
// does have the GTID and hash we intend to replicate to. If not, we have to go
// fatal, as something went wrong.
BSONObj targetObj = r.findOpWithGTID(lastGTID);
if (targetObj.isEmpty() || ((uint64_t)targetObj["h"].numberLong()) != lastHash) {
if (targetObj.isEmpty()) {
log() << "target did not have the GTID we were looking for" << targetObj << rsLog;
}
else {
log() << "our hash " << lastHash << "their hash " << targetObj["h"].numberLong() << rsLog;
}
throw RollbackOplogException("Member we are syncing from does not have the target GTID we wish to replicate to.");
}
r.resetCursor();
r.tailingQueryGTE(rsoplog, startPoint);
uassert(17361, "Cursor died while running replicateForwardToGTID", r.haveCursor());
// appliedGTIDs only used if preSnapshot is true
RollbackGTIDSet appliedGTIDs;
appliedGTIDs.initialize();
BSONObj checkFirstObj = r.next().getOwned();
GTID currGTID = getGTIDFromBSON("_id", checkFirstObj);
if (GTID::cmp(startPoint, currGTID) != 0) {
throw RollbackOplogException("Could not find startPoint on remote server");
}
while (GTID::cmp(currGTID, lastGTID) < 0) {
while (r.more()) {
BSONObj curr = r.nextSafe().getOwned();
currGTID = getGTIDFromBSON("_id", curr);
if (GTID::cmp(currGTID, lastGTID) > 0) {
break; // we are done
}
{
bool bigTxn = false;
Client::Transaction transaction(DB_SERIALIZABLE);
replicateFullTransactionToOplog(curr, r, &bigTxn);
// we are operating as a secondary. We don't have to fsync
transaction.commit(DB_TXN_NOSYNC);
}
// apply the transaction if it existed in snapshot
bool applyTransaction = true;
if (preSnapshot) {
applyTransaction = appliedGTIDs.GTIDExists(currGTID);
}
if (applyTransaction) {
RollbackDocsMap docsMap;
applyTransactionFromOplog(curr, preSnapshot ? &docsMap : NULL, true);
}
if (GTID::cmp(currGTID, lastGTID) == 0) {
break; // we are done
}
}
r.tailCheck();
uassert(17362, "Cursor died while running replicateForwardToGTID", r.haveCursor());
}
log () << "Done replicating from " << startPoint.toString() << " to " << lastGTID.toString() << rsLog;
}
void finishRollback(bool finishedEarly) {
BSONObj o;
bool found = getRollbackStatus(o);
verify(found);
if (!finishedEarly) {
verify(o["state"].Int() == RB_SNAPSHOT_APPLIED);
GTID lastGTIDAfterSnapshotDone = getGTIDFromBSON("lastGTIDAfterSnapshotDone", o);
uint64_t lastTS = o["lastTSAfterSnapshotDone"]._numberLong();
uint64_t lastHash = o["lastHashAfterSnapshotDone"].numberLong();
theReplSet->gtidManager->resetAfterInitialSync(
lastGTIDAfterSnapshotDone,
lastTS,
lastHash
);
// now force an update of the repl info thread
theReplSet->forceUpdateReplInfo();
}
// now delete a bunch of stuff
Client::Transaction txn(DB_SERIALIZABLE);
// remove docsMap and RollbackGTIDSet
RollbackGTIDSetBuilder::dropGTIDSet();
RollbackDocsMap::dropDocsMap();
clearRollbackStatus(o);
txn.commit(DB_TXN_NOSYNC);
theReplSet->leaveRollbackState();
}
uint32_t runRollbackInternal(OplogReader& r, uint64_t oplogTS) {
enum rollback_state startState = RB_NOT_STARTED;
BSONObj o;
if (getRollbackStatus(o)) {
startState = static_cast<enum rollback_state>(o["state"].Int());
verify(startState > RB_NOT_STARTED && startState <= RB_SNAPSHOT_APPLIED);
}
if (startState == RB_STARTING) {
log() << "Rollback found in RB_STARTING phase, cannot recover" << rsLog;
throw RollbackOplogException("Rollback was left in state we cannot recover from");
}
if (startState == RB_NOT_STARTED) {
// starting from ourLast, we need to read the remote oplog
// backwards until we find an entry in the remote oplog
// that has the same GTID, timestamp, and hash as
// what we have in our oplog. If we don't find one that is within
// some reasonable timeframe, then we go fatal
GTID idToRollbackTo;
uint64_t rollbackPointTS = 0;
uint64_t rollbackPointHash = 0;
findRollbackPoint(
r,
oplogTS,
&idToRollbackTo,
&rollbackPointTS,
&rollbackPointHash
);
if (!canStartRollback(r, idToRollbackTo)) {
return 2;
}
startRollback(idToRollbackTo, rollbackPointTS, rollbackPointHash);
RollbackDocsMap docsMap; // stores the documents we need to get images of
docsMap.initialize();
RollbackSaveData rsSave;
rsSave.initialize();
rollbackToGTID(idToRollbackTo, &docsMap, &rsSave);
if (docsMap.size() == 0) {
log() << "Rollback produced no docs in docsMap, exiting early" << rsLog;
finishRollback(true);
theReplSet->leaveRollbackState();
return 0;
}
// at this point docsMap has the list of documents (identified by collection and pk)
// that we need to get a snapshot of
removeDataFromDocsMap();
}
if (startState < RB_SNAPSHOT_APPLIED) {
applyInformationFromRemoteSnapshot(r);
}
replicateForwardToGTID(r, true);
log() << "Applying missing ops for rollback" << rsLog;
RollbackGTIDSet appliedGTIDs;
appliedGTIDs.initialize();
applyMissingOpsInOplog(appliedGTIDs.getMinUnapplied(), true);
log() << "Done applying missing ops for rollback" << rsLog;
// while we were applying the remote images above, a collection may have been dropped
// That drop will be associated with a point in time after lastGTID. For that reason,
// we cannot transition to secondary just yet, because there may be data missing
// from the point in time associated with lastGTID. Therefore, to be safe,
// we play forward to lastGTIDAfterSnapshotDone, a point in time taken after
// we committed our MVCC transaction
replicateForwardToGTID(r, false);
finishRollback(false);
return 0;
}
void BackgroundSync::settleApplierForRollback() {
boost::unique_lock<boost::mutex> lock(_mutex);
while (_deque.size() > 0) {
log() << "waiting for applier to finish work before doing rollback " << rsLog;
_queueDone.wait(lock);
}
verifySettled();
}
uint32_t BackgroundSync::runRollback(OplogReader& r, uint64_t oplogTS) {
log() << "Starting to run rollback" << rsLog;
// first, let's get all the operations that are being applied out of the way,
// we don't want to rollback an item in the oplog while simultaneously,
// the applier thread is applying it to the oplog
settleApplierForRollback();
{
// so we know nothing is simultaneously occurring
RWLockRecursive::Exclusive e(operationLock);
LOCK_REASON(lockReason, "repl: killing all operations for rollback");
Lock::GlobalWrite lk(lockReason);
ClientCursor::invalidateAllCursors();
Client::abortLiveTransactions();
theReplSet->goToRollbackState();
// we leave rollback state upon successful
// execution of runRollbackInternal, which we call below
}
for (uint32_t attempts = 0; attempts < 10; attempts++) {
try {
if (attempts == 0) {
return runRollbackInternal(r, oplogTS);
}
else {
OplogReader newReader (false);
// find a target to sync from the last op time written
getOplogReader(&newReader);
// no server found
bool gotReader = true;
{
boost::unique_lock<boost::mutex> lock(_mutex);
if (_currentSyncTarget == NULL) {
gotReader = false;
}
}
if (gotReader) {
return runRollbackInternal(newReader, oplogTS);
}
}
}
catch (RollbackOplogException& e) {
throw;
}
catch (DBException& e) {
log() << "Caught DBException during rollback " << e.toString() << rsLog;
}
catch (std::exception& e2) {
log() << "Caught std::exception during rollback " << e2.what() << rsLog;
}
sleepsecs(1);
}
// after trying repeatedly, we eventually give up
throw RollbackOplogException("Attempt to rollback has failed.");
}
} // namespace mongo
| 15,294 |
1,171 | import pytest
import numpy as np
from anndata import AnnData
from scipy.sparse import csr_matrix
import scanpy as sc
# test "data" for 3 cells * 4 genes
X = [
[-1, 2, 0, 0],
[1, 2, 4, 0],
[0, 2, 2, 0],
] # with gene std 1,0,2,0 and center 0,2,2,0
X_scaled = [
[-1, 2, 0, 0],
[1, 2, 2, 0],
[0, 2, 1, 0],
] # with gene std 1,0,1,0 and center 0,2,1,0
X_centered = [
[-1, 0, -1, 0],
[1, 0, 1, 0],
[0, 0, 0, 0],
] # with gene std 1,0,1,0 and center 0,0,0,0
@pytest.mark.parametrize('typ', [np.array, csr_matrix], ids=lambda x: x.__name__)
@pytest.mark.parametrize('dtype', ['float32', 'int64'])
def test_scale(typ, dtype):
# test AnnData arguments
# test scaling with default zero_center == True
adata0 = AnnData(typ(X), dtype=dtype)
sc.pp.scale(adata0)
assert np.allclose(csr_matrix(adata0.X).toarray(), X_centered)
# test scaling with explicit zero_center == True
adata1 = AnnData(typ(X), dtype=dtype)
sc.pp.scale(adata1, zero_center=True)
assert np.allclose(csr_matrix(adata1.X).toarray(), X_centered)
# test scaling with explicit zero_center == False
adata2 = AnnData(typ(X), dtype=dtype)
sc.pp.scale(adata2, zero_center=False)
assert np.allclose(csr_matrix(adata2.X).toarray(), X_scaled)
# test bare count arguments, for simplicity only with explicit copy=True
# test scaling with default zero_center == True
data0 = typ(X, dtype=dtype)
cdata0 = sc.pp.scale(data0, copy=True)
assert np.allclose(csr_matrix(cdata0).toarray(), X_centered)
# test scaling with explicit zero_center == True
data1 = typ(X, dtype=dtype)
cdata1 = sc.pp.scale(data1, zero_center=True, copy=True)
assert np.allclose(csr_matrix(cdata1).toarray(), X_centered)
# test scaling with explicit zero_center == False
data2 = typ(X, dtype=dtype)
cdata2 = sc.pp.scale(data2, zero_center=False, copy=True)
assert np.allclose(csr_matrix(cdata2).toarray(), X_scaled)
| 847 |
427 | //===-- FileSpecTest.cpp ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "lldb/Host/FileSpec.h"
using namespace lldb_private;
TEST(FileSpecTest, FileAndDirectoryComponents) {
FileSpec fs_posix("/foo/bar", false, FileSpec::ePathSyntaxPosix);
EXPECT_STREQ("/foo/bar", fs_posix.GetCString());
EXPECT_STREQ("/foo", fs_posix.GetDirectory().GetCString());
EXPECT_STREQ("bar", fs_posix.GetFilename().GetCString());
FileSpec fs_windows("F:\\bar", false, FileSpec::ePathSyntaxWindows);
EXPECT_STREQ("F:\\bar", fs_windows.GetCString());
// EXPECT_STREQ("F:\\", fs_windows.GetDirectory().GetCString()); // It returns
// "F:/"
EXPECT_STREQ("bar", fs_windows.GetFilename().GetCString());
FileSpec fs_posix_root("/", false, FileSpec::ePathSyntaxPosix);
EXPECT_STREQ("/", fs_posix_root.GetCString());
EXPECT_EQ(nullptr, fs_posix_root.GetDirectory().GetCString());
EXPECT_STREQ("/", fs_posix_root.GetFilename().GetCString());
FileSpec fs_windows_drive("F:", false, FileSpec::ePathSyntaxWindows);
EXPECT_STREQ("F:", fs_windows_drive.GetCString());
EXPECT_EQ(nullptr, fs_windows_drive.GetDirectory().GetCString());
EXPECT_STREQ("F:", fs_windows_drive.GetFilename().GetCString());
FileSpec fs_windows_root("F:\\", false, FileSpec::ePathSyntaxWindows);
EXPECT_STREQ("F:\\", fs_windows_root.GetCString());
EXPECT_STREQ("F:", fs_windows_root.GetDirectory().GetCString());
// EXPECT_STREQ("\\", fs_windows_root.GetFilename().GetCString()); // It
// returns "/"
FileSpec fs_posix_long("/foo/bar/baz", false, FileSpec::ePathSyntaxPosix);
EXPECT_STREQ("/foo/bar/baz", fs_posix_long.GetCString());
EXPECT_STREQ("/foo/bar", fs_posix_long.GetDirectory().GetCString());
EXPECT_STREQ("baz", fs_posix_long.GetFilename().GetCString());
FileSpec fs_windows_long("F:\\bar\\baz", false, FileSpec::ePathSyntaxWindows);
EXPECT_STREQ("F:\\bar\\baz", fs_windows_long.GetCString());
// EXPECT_STREQ("F:\\bar", fs_windows_long.GetDirectory().GetCString()); // It
// returns "F:/bar"
EXPECT_STREQ("baz", fs_windows_long.GetFilename().GetCString());
FileSpec fs_posix_trailing_slash("/foo/bar/", false,
FileSpec::ePathSyntaxPosix);
EXPECT_STREQ("/foo/bar/.", fs_posix_trailing_slash.GetCString());
EXPECT_STREQ("/foo/bar", fs_posix_trailing_slash.GetDirectory().GetCString());
EXPECT_STREQ(".", fs_posix_trailing_slash.GetFilename().GetCString());
FileSpec fs_windows_trailing_slash("F:\\bar\\", false,
FileSpec::ePathSyntaxWindows);
EXPECT_STREQ("F:\\bar\\.", fs_windows_trailing_slash.GetCString());
// EXPECT_STREQ("F:\\bar",
// fs_windows_trailing_slash.GetDirectory().GetCString()); // It returns
// "F:/bar"
EXPECT_STREQ(".", fs_windows_trailing_slash.GetFilename().GetCString());
}
TEST(FileSpecTest, AppendPathComponent) {
FileSpec fs_posix("/foo", false, FileSpec::ePathSyntaxPosix);
fs_posix.AppendPathComponent("bar");
EXPECT_STREQ("/foo/bar", fs_posix.GetCString());
EXPECT_STREQ("/foo", fs_posix.GetDirectory().GetCString());
EXPECT_STREQ("bar", fs_posix.GetFilename().GetCString());
FileSpec fs_posix_2("/foo", false, FileSpec::ePathSyntaxPosix);
fs_posix_2.AppendPathComponent("//bar/baz");
EXPECT_STREQ("/foo/bar/baz", fs_posix_2.GetCString());
EXPECT_STREQ("/foo/bar", fs_posix_2.GetDirectory().GetCString());
EXPECT_STREQ("baz", fs_posix_2.GetFilename().GetCString());
FileSpec fs_windows("F:\\bar", false, FileSpec::ePathSyntaxWindows);
fs_windows.AppendPathComponent("baz");
EXPECT_STREQ("F:\\bar\\baz", fs_windows.GetCString());
// EXPECT_STREQ("F:\\bar", fs_windows.GetDirectory().GetCString()); // It
// returns "F:/bar"
EXPECT_STREQ("baz", fs_windows.GetFilename().GetCString());
FileSpec fs_posix_root("/", false, FileSpec::ePathSyntaxPosix);
fs_posix_root.AppendPathComponent("bar");
EXPECT_STREQ("/bar", fs_posix_root.GetCString());
EXPECT_STREQ("/", fs_posix_root.GetDirectory().GetCString());
EXPECT_STREQ("bar", fs_posix_root.GetFilename().GetCString());
FileSpec fs_windows_root("F:\\", false, FileSpec::ePathSyntaxWindows);
fs_windows_root.AppendPathComponent("bar");
EXPECT_STREQ("F:\\bar", fs_windows_root.GetCString());
// EXPECT_STREQ("F:\\", fs_windows_root.GetDirectory().GetCString()); // It
// returns "F:/"
EXPECT_STREQ("bar", fs_windows_root.GetFilename().GetCString());
}
TEST(FileSpecTest, CopyByAppendingPathComponent) {
FileSpec fs = FileSpec("/foo", false, FileSpec::ePathSyntaxPosix)
.CopyByAppendingPathComponent("bar");
EXPECT_STREQ("/foo/bar", fs.GetCString());
EXPECT_STREQ("/foo", fs.GetDirectory().GetCString());
EXPECT_STREQ("bar", fs.GetFilename().GetCString());
}
static void Compare(const FileSpec &one, const FileSpec &two, bool full_match,
bool remove_backup_dots, bool result) {
EXPECT_EQ(result, FileSpec::Equal(one, two, full_match, remove_backup_dots))
<< "File one: " << one.GetCString() << "\nFile two: " << two.GetCString()
<< "\nFull match: " << full_match
<< "\nRemove backup dots: " << remove_backup_dots;
}
TEST(FileSpecTest, EqualSeparator) {
FileSpec backward("C:\\foo\\bar", false, FileSpec::ePathSyntaxWindows);
FileSpec forward("C:/foo/bar", false, FileSpec::ePathSyntaxWindows);
EXPECT_EQ(forward, backward);
const bool full_match = true;
const bool remove_backup_dots = true;
const bool match = true;
Compare(forward, backward, full_match, remove_backup_dots, match);
Compare(forward, backward, full_match, !remove_backup_dots, match);
Compare(forward, backward, !full_match, remove_backup_dots, match);
Compare(forward, backward, !full_match, !remove_backup_dots, match);
}
TEST(FileSpecTest, EqualDotsWindows) {
const bool full_match = true;
const bool remove_backup_dots = true;
const bool match = true;
std::pair<const char *, const char *> tests[] = {
{R"(C:\foo\bar\baz)", R"(C:\foo\foo\..\bar\baz)"},
{R"(C:\bar\baz)", R"(C:\foo\..\bar\baz)"},
{R"(C:\bar\baz)", R"(C:/foo/../bar/baz)"},
{R"(C:/bar/baz)", R"(C:\foo\..\bar\baz)"},
{R"(C:\bar)", R"(C:\foo\..\bar)"},
{R"(C:\foo\bar)", R"(C:\foo\.\bar)"},
{R"(C:\foo\bar)", R"(C:\foo\bar\.)"},
};
for(const auto &test: tests) {
FileSpec one(test.first, false, FileSpec::ePathSyntaxWindows);
FileSpec two(test.second, false, FileSpec::ePathSyntaxWindows);
EXPECT_NE(one, two);
Compare(one, two, full_match, remove_backup_dots, match);
Compare(one, two, full_match, !remove_backup_dots, !match);
Compare(one, two, !full_match, remove_backup_dots, match);
Compare(one, two, !full_match, !remove_backup_dots, !match);
}
}
TEST(FileSpecTest, EqualDotsPosix) {
const bool full_match = true;
const bool remove_backup_dots = true;
const bool match = true;
std::pair<const char *, const char *> tests[] = {
{R"(/foo/bar/baz)", R"(/foo/foo/../bar/baz)"},
{R"(/bar/baz)", R"(/foo/../bar/baz)"},
{R"(/bar)", R"(/foo/../bar)"},
{R"(/foo/bar)", R"(/foo/./bar)"},
{R"(/foo/bar)", R"(/foo/bar/.)"},
};
for(const auto &test: tests) {
FileSpec one(test.first, false, FileSpec::ePathSyntaxPosix);
FileSpec two(test.second, false, FileSpec::ePathSyntaxPosix);
EXPECT_NE(one, two);
Compare(one, two, full_match, remove_backup_dots, match);
Compare(one, two, full_match, !remove_backup_dots, !match);
Compare(one, two, !full_match, remove_backup_dots, match);
Compare(one, two, !full_match, !remove_backup_dots, !match);
}
}
TEST(FileSpecTest, EqualDotsPosixRoot) {
const bool full_match = true;
const bool remove_backup_dots = true;
const bool match = true;
std::pair<const char *, const char *> tests[] = {
{R"(/)", R"(/..)"}, {R"(/)", R"(/.)"}, {R"(/)", R"(/foo/..)"},
};
for(const auto &test: tests) {
FileSpec one(test.first, false, FileSpec::ePathSyntaxPosix);
FileSpec two(test.second, false, FileSpec::ePathSyntaxPosix);
EXPECT_NE(one, two);
Compare(one, two, full_match, remove_backup_dots, match);
Compare(one, two, full_match, !remove_backup_dots, !match);
Compare(one, two, !full_match, remove_backup_dots, !match);
Compare(one, two, !full_match, !remove_backup_dots, !match);
}
}
TEST(FileSpecTest, GetNormalizedPath) {
std::pair<const char *, const char *> posix_tests[] = {
{"/foo/.././bar", "/bar"},
{"/foo/./../bar", "/bar"},
{"/foo/../bar", "/bar"},
{"/foo/./bar", "/foo/bar"},
{"/foo/..", "/"},
{"/foo/.", "/foo"},
{"/foo//bar", "/foo/bar"},
{"/foo//bar/baz", "/foo/bar/baz"},
{"/foo//bar/./baz", "/foo/bar/baz"},
{"/./foo", "/foo"},
{"/", "/"},
{"//", "//"},
{"//net", "//net"},
{"/..", "/"},
{"/.", "/"},
{"..", ".."},
{".", "."},
{"../..", "../.."},
{"foo/..", "."},
{"foo/../bar", "bar"},
{"../foo/..", ".."},
{"./foo", "foo"},
};
for (auto test : posix_tests) {
EXPECT_EQ(test.second,
FileSpec(test.first, false, FileSpec::ePathSyntaxPosix)
.GetNormalizedPath()
.GetPath());
}
std::pair<const char *, const char *> windows_tests[] = {
{R"(c:\bar\..\bar)", R"(c:\bar)"},
{R"(c:\bar\.\bar)", R"(c:\bar\bar)"},
{R"(c:\bar\..)", R"(c:\)"},
{R"(c:\bar\.)", R"(c:\bar)"},
{R"(c:\.\bar)", R"(c:\bar)"},
{R"(\)", R"(\)"},
// {R"(\\)", R"(\\)"},
// {R"(\\net)", R"(\\net)"},
{R"(c:\..)", R"(c:\)"},
{R"(c:\.)", R"(c:\)"},
{R"(\..)", R"(\)"},
// {R"(c:..)", R"(c:..)"},
{R"(..)", R"(..)"},
{R"(.)", R"(.)"},
{R"(c:..\..)", R"(c:..\..)"},
{R"(..\..)", R"(..\..)"},
{R"(foo\..)", R"(.)"},
{R"(foo\..\bar)", R"(bar)"},
{R"(..\foo\..)", R"(..)"},
{R"(.\foo)", R"(foo)"},
};
for (auto test : windows_tests) {
EXPECT_EQ(test.second,
FileSpec(test.first, false, FileSpec::ePathSyntaxWindows)
.GetNormalizedPath()
.GetPath())
<< "Original path: " << test.first;
}
}
TEST(FileSpecTest, FormatFileSpec) {
auto win = FileSpec::ePathSyntaxWindows;
FileSpec F;
EXPECT_EQ("(empty)", llvm::formatv("{0}", F).str());
EXPECT_EQ("(empty)", llvm::formatv("{0:D}", F).str());
EXPECT_EQ("(empty)", llvm::formatv("{0:F}", F).str());
F = FileSpec("C:\\foo\\bar.txt", false, win);
EXPECT_EQ("C:\\foo\\bar.txt", llvm::formatv("{0}", F).str());
EXPECT_EQ("C:\\foo\\", llvm::formatv("{0:D}", F).str());
EXPECT_EQ("bar.txt", llvm::formatv("{0:F}", F).str());
F = FileSpec("foo\\bar.txt", false, win);
EXPECT_EQ("foo\\bar.txt", llvm::formatv("{0}", F).str());
EXPECT_EQ("foo\\", llvm::formatv("{0:D}", F).str());
EXPECT_EQ("bar.txt", llvm::formatv("{0:F}", F).str());
F = FileSpec("foo", false, win);
EXPECT_EQ("foo", llvm::formatv("{0}", F).str());
EXPECT_EQ("foo", llvm::formatv("{0:F}", F).str());
EXPECT_EQ("(empty)", llvm::formatv("{0:D}", F).str());
} | 4,871 |
906 | // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "esp_jpg_decode.h"
#include "esp_system.h"
#if ESP_IDF_VERSION_MAJOR >= 4 // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/tjpgd.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "tjpgd.h"
#elif CONFIG_IDF_TARGET_ESP32S3
#include "esp32s3/rom/tjpgd.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/tjpgd.h"
#endif
#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG)
#include "esp32-hal-log.h"
#define TAG ""
#else
#include "esp_log.h"
static const char* TAG = "esp_jpg_decode";
#endif
typedef struct {
jpg_scale_t scale;
jpg_reader_cb reader;
jpg_writer_cb writer;
void * arg;
size_t len;
size_t index;
} esp_jpg_decoder_t;
static const char * jd_errors[] = {
"Succeeded",
"Interrupted by output function",
"Device error or wrong termination of input stream",
"Insufficient memory pool for the image",
"Insufficient stream input buffer",
"Parameter error",
"Data format error",
"Right format but not supported",
"Not supported JPEG standard"
};
static uint32_t _jpg_write(JDEC *decoder, void *bitmap, JRECT *rect)
{
uint16_t x = rect->left;
uint16_t y = rect->top;
uint16_t w = rect->right + 1 - x;
uint16_t h = rect->bottom + 1 - y;
uint8_t *data = (uint8_t *)bitmap;
esp_jpg_decoder_t * jpeg = (esp_jpg_decoder_t *)decoder->device;
if (jpeg->writer) {
return jpeg->writer(jpeg->arg, x, y, w, h, data);
}
return 0;
}
static uint32_t _jpg_read(JDEC *decoder, uint8_t *buf, uint32_t len)
{
esp_jpg_decoder_t * jpeg = (esp_jpg_decoder_t *)decoder->device;
if (jpeg->len && len > (jpeg->len - jpeg->index)) {
len = jpeg->len - jpeg->index;
}
if (len) {
len = jpeg->reader(jpeg->arg, jpeg->index, buf, len);
if (!len) {
ESP_LOGE(TAG, "Read Fail at %u/%u", jpeg->index, jpeg->len);
}
jpeg->index += len;
}
return len;
}
esp_err_t esp_jpg_decode(size_t len, jpg_scale_t scale, jpg_reader_cb reader, jpg_writer_cb writer, void * arg)
{
static uint8_t work[3100];
JDEC decoder;
esp_jpg_decoder_t jpeg;
jpeg.len = len;
jpeg.reader = reader;
jpeg.writer = writer;
jpeg.arg = arg;
jpeg.scale = scale;
jpeg.index = 0;
JRESULT jres = jd_prepare(&decoder, _jpg_read, work, 3100, &jpeg);
if(jres != JDR_OK){
ESP_LOGE(TAG, "JPG Header Parse Failed! %s", jd_errors[jres]);
return ESP_FAIL;
}
uint16_t output_width = decoder.width / (1 << (uint8_t)(jpeg.scale));
uint16_t output_height = decoder.height / (1 << (uint8_t)(jpeg.scale));
//output start
writer(arg, 0, 0, output_width, output_height, NULL);
//output write
jres = jd_decomp(&decoder, _jpg_write, (uint8_t)jpeg.scale);
//output end
writer(arg, output_width, output_height, output_width, output_height, NULL);
if (jres != JDR_OK) {
ESP_LOGE(TAG, "JPG Decompression Failed! %s", jd_errors[jres]);
return ESP_FAIL;
}
//check if all data has been consumed.
if (len && jpeg.index < len) {
_jpg_read(&decoder, NULL, len - jpeg.index);
}
return ESP_OK;
}
| 1,641 |
311 | package datadog.trace.instrumentation.playws21;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.propagate;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.startSpan;
import static datadog.trace.instrumentation.playws.HeadersInjectAdapter.SETTER;
import static datadog.trace.instrumentation.playws.PlayWSClientDecorator.DECORATE;
import static datadog.trace.instrumentation.playws.PlayWSClientDecorator.PLAY_WS_REQUEST;
import com.google.auto.service.AutoService;
import datadog.trace.agent.tooling.Instrumenter;
import datadog.trace.bootstrap.instrumentation.api.AgentSpan;
import datadog.trace.instrumentation.playws.BasePlayWSClientInstrumentation;
import net.bytebuddy.asm.Advice;
import play.shaded.ahc.org.asynchttpclient.AsyncHandler;
import play.shaded.ahc.org.asynchttpclient.Request;
import play.shaded.ahc.org.asynchttpclient.handler.StreamedAsyncHandler;
import play.shaded.ahc.org.asynchttpclient.ws.WebSocketUpgradeHandler;
@AutoService(Instrumenter.class)
public class PlayWSClientInstrumentation extends BasePlayWSClientInstrumentation {
public static class ClientAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static AgentSpan methodEnter(
@Advice.Argument(0) final Request request,
@Advice.Argument(value = 1, readOnly = false) AsyncHandler asyncHandler) {
final AgentSpan span = startSpan(PLAY_WS_REQUEST);
DECORATE.afterStart(span);
DECORATE.onRequest(span, request);
propagate().inject(span, request, SETTER);
if (asyncHandler instanceof StreamedAsyncHandler) {
asyncHandler = new StreamedAsyncHandlerWrapper((StreamedAsyncHandler) asyncHandler, span);
} else if (!(asyncHandler instanceof WebSocketUpgradeHandler)) {
// websocket upgrade handlers aren't supported
asyncHandler = new AsyncHandlerWrapper(asyncHandler, span);
}
return span;
}
@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void methodExit(
@Advice.Enter final AgentSpan clientSpan, @Advice.Thrown final Throwable throwable) {
if (throwable != null) {
DECORATE.onError(clientSpan, throwable);
DECORATE.beforeFinish(clientSpan);
clientSpan.finish();
}
}
}
}
| 815 |
3,428 | <reponame>ghalimi/stdlib
{"id":"00255","group":"easy-ham-1","checksum":{"type":"MD5","value":"11be25bd4a3d55702ed4a1f13e7d2a3d"},"text":"From <EMAIL> Fri Sep 6 11:40:54 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: z<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby spamassassin.taint.org (Postfix) with ESMTP id 7D5C516F19\n\tfor <zzzz@localhost>; Fri, 6 Sep 2002 11:39:13 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor zzzz@localhost (single-drop); Fri, 06 Sep 2002 11:39:13 +0100 (IST)\nReceived: from lugh.tuatha.org (<EMAIL> [192.168.3.11]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g86AQeC32186 for\n <<EMAIL>>; Fri, 6 Sep 2002 11:26:40 +0100\nReceived: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id LAA06471; Fri, 6 Sep 2002 11:24:33 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host root@localhost [127.0.0.1]\n claimed to be lugh\nReceived: from web12102.mail.yahoo.com (web12102.mail.yahoo.com\n [216.136.172.22]) by lugh.tuatha.org (8.9.3/8.9.3) with SMTP id LAA06436\n for <<EMAIL>>; Fri, 6 Sep 2002 11:24:22 +0100\nMessage-Id: <<EMAIL>>\nReceived: from [159.134.146.155] by web12102.mail.yahoo.com via HTTP;\n Fri, 06 Sep 2002 11:24:17 BST\nDate: Fri, 6 Sep 2002 11:24:17 +0100 (BST)\nFrom: =?iso-8859-1?q?Colin=20Nevin?= <<EMAIL>>\nTo: [email protected]\nMIME-Version: 1.0\nContent-Type: text/plain; charset=iso-8859-1\nContent-Transfer-Encoding: 8bit\nSubject: [ILUG] semaphores on linux RH7.3\nSender: [email protected]\nErrors-To: [email protected]\nX-Mailman-Version: 1.1\nPrecedence: bulk\nList-Id: Irish Linux Users' Group <ilug.linux.ie>\nX-Beenthere: [email protected]\n\nHi All,\n\nI have a question which is a bit tricky and was\nwondering of anyone has come across this problem\nbefore or could point me in the right direction.\n\nI am involved in porting a SCO unix application to\nLinux, and we have encountered a problem with the way\nsemaphores are being handled. The application uses\nmulitple processes to run application code with the\nmain process known as the bsh which controls all i/o\nbe it screen, or file i/o, syncronisation is handled\nvia semaphores.\n\nIn certain circumstances the main process and the\napplication child process seem to lock up both waiting\nfor the syncronisation semaphores to change state, I\nhave attached ddd to the processes and it seems that\nthe semaphore code is doing the correct things for\nsyncronisation but the processes stay stuck in the\nsemop() system call.\n\nI have also noticed that if I introduce a slight delay\nbetween changing semaphore states the problem goes\naway, but this causes our entire application to run\nreally sloooww !! lol\n\nIs there anything weird or different with the standard\nimplemenation of semaphores on modern linux that could\ncause a semop() to fail to pick up the change in state\n\nin a semaphore immediately?\n\nSetting sem_flg = IPC_NOWAIT and checking for errno ==\nEAGAIN and recalling semop() if the semop() call fails\n(-1) also fixes the problem but again system\nperformance goes down the toilet.\n\nboth the parent controlling process run as the same\nuid, and the parent creates the semaphores with\npermissions 0666.\n\nAny pointers would be appreciated!\n\nRgds,\n\n<NAME> \n\n__________________________________________________\nDo You Yahoo!?\nEverything you'll ever need on one web page\nfrom News and Sport to Email and Music Charts\nhttp://uk.my.yahoo.com\n\n-- \nIrish Linux Users' Group: <EMAIL>\nhttp://www.linux.ie/mailman/listinfo/ilug for (un)subscription information.\nList maintainer: <EMAIL>\n\n\n"} | 1,337 |
422 | """
COLOR·SKY
03/20/2020
"""
import cv2
import numpy as np
import pyautogui
from PIL import ImageGrab
from pywinauto.findwindows import find_window,WindowNotFoundError
from win32gui import SetForegroundWindow
winsize = list(pyautogui.size()) # The resolution of the monitor
def get_mouse_position():
# Get current mouse position
return list(pyautogui.position())
def record(direct, name):
# Make a screenshot
im = ImageGrab.grab()
im.save(f"{direct}/{name}.jpg")
def get_intersect(x1, y1, x2, y2, x3, y3, x4, y4):
"""
:param x1: x position of the first rect's upplerleft point
:param y1: y position of the first rect's upplerleft point
:param x2: x position of the first rect's lowerright point
:param y2: y position of the first rect's lowerright point
:param x3: x position of the second rect's upplerleft point
:param y3: y position of the second rect's upplerleft point
:param x4: x position of the second rect's lowerright point
:param y4: y position of the second rect's lowerright point
"""
intersect = True
if (x1 > x4 or x3 > x2) or (y1 > y4 or y2 < y3):
return False, 0, 0, 0, 0
upperleft = (max(x1, x3), max(y1, y3))
lowerright = (min(x2, x4), min(y2, y4))
if lowerright[0] - upperleft[0] < 10 or lowerright[1] - upperleft[1] < 10:
return False, 0, 0, 0, 0
return intersect, int(upperleft[0]), int(upperleft[1]), int(lowerright[0]), int(lowerright[1])
def constrain(val, min_val, max_val):
return int(min(max_val, max(min_val, val)))
def map_value(value, leftmin, leftmax, rightmin, rightmax):
leftspan = leftmax - leftmin
rightspan = rightmax - rightmin
valuescaled = float(value - leftmin) / float(leftspan)
return rightmin + (valuescaled * rightspan)
def increase_brightness(img, value=30):
"""
Change brightness of a cv2 image
Reference: https://stackoverflow.com/questions/32609098/how-to-fast-change-image-brightness-with-python-opencv
"""
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
return img
class ImageMask:
def __init__(self, filename=None, image=None, x=winsize[0] / 2, y=winsize[1] / 2, brightness = 0):
self.image = image
self.x, self.y = int(x), int(y)
if image is None:
self.image = cv2.imread(filename)
self.h, self.w, _ = self.image.shape
self.all_black = not np.any(self.image)
self.brightness = brightness
if self.brightness != 0:
self.image = increase_brightness(self.image, self.brightness)
def get_region(self, ulx, uly, lrx, lry):
"""
return part of the image enclosed by the rectangle
"""
image_ulx = int(ulx - (self.x - self.w / 2))
image_uly = int(uly - (self.y - self.h / 2))
image_lrx = int(lrx - (self.x - self.w / 2))
image_lry = int(lry - (self.y - self.h / 2))
image = self.image[image_uly:image_lry, image_ulx:image_lrx]
return image
def get_pixel(self, px, py):
h, w, c = self.image.shape
# point px, py is within the image
if self.x + w / 2 > px > self.x - w / 2 and self.y + h / 2 > py > self.y - h / 2:
# Convert monitor position to image position
dx = px - self.x
dy = py - self.y
imgx = int(w / 2) + dx
imgy = int(h / 2) + dy
return self.image[imgy][imgx]
else:
return [0, 0, 0]
class SketchWindow:
def __init__(self, name, x, y, w, h, bg=255):
self.name, self.x, self.y, self.w, self.h, self.bg = name, x, y, w, h, bg
self.z = 0
self.background = np.zeros((int(self.h), int(self.w), 3), np.uint8)
self.background.fill(self.bg)
self.window_scale = 1.0
self.offsetx = 0
self.offsety = 0
self.masked = False
self.imgidx = 0
self.imgs = []
self.imgx = int(winsize[0]/2)
self.imgy = int(winsize[1]/2)
def reset_bg(self):
self.background = np.zeros((int(self.h), int(self.w), 3), np.uint8)
self.background.fill(self.bg)
def set_img_seq(self, imgs, imgx=None, imgy=None):
self.imgs = imgs
if imgx and imgy:
self.imgx = imgx
self.imgy = imgy
def mask_img(self, img):
"""
Mask an image at location (imgx, imgy) relative to the monitor
:param img: ImageMask object
:param curx: x position
:param cury: y position
"""
# if img.all_black:
# return
self.masked = True
self.background = np.zeros((int(self.h), int(self.w), 3), np.uint8)
intersect, ulx, uly, lrx, lry = get_intersect(
self.x - self.w / 2,
self.y - self.h / 2,
self.x + self.w / 2,
self.y + self.h / 2,
img.x - img.w / 2,
img.y - img.h / 2,
img.x + img.w / 2,
img.y + img.h / 2,
)
if not intersect:
return
corpped_img = img.get_region(ulx, uly, lrx, lry)
bgulx = int(ulx - (self.x - self.w / 2))
bguly = int(uly - (self.y - self.h / 2))
imgh, imgw, _ = corpped_img.shape
self.background[bguly:bguly + imgh, bgulx:bgulx + imgw] = corpped_img
def set_position(self, x, y):
self.x, self.y = x, y
def set_size(self, w, h):
self.w, self.h = w, h
def set_windowscale(self, scale):
self.window_scale = scale
def to_front(self):
try:
hwnd = find_window(title=self.name)
SetForegroundWindow(hwnd)
except WindowNotFoundError:
pass
def destroy(self):
cv2.destroyWindow(self.name)
class AnimatedSketchWindow(SketchWindow):
def __init__(self, name, x, y, w, h, bg=255):
SketchWindow.__init__(self, name, x, y, w, h, bg)
self.min_w = 120
self.min_h = 80
self.max_w = int(w)
self.max_h = int(h)
self.scale = 1.0
self.scalex = 1.0
self.scaley = 1.0
self.vscale = 0
self.vscalex = 0
self.vscaley = 0
self.vx = 0
self.vy = 0
self.vz = 0
self.in_transition = False
self.frame_expired = 0
def update(self):
if self.imgs:
self.imgidx %= (len(self.imgs)-1)
self.mask_img(ImageMask(self.imgs[self.imgidx],x=self.imgx, y=self.imgy))
self.imgidx += 1
else:
self.masked = False
self.scale += self.vscale
self.scalex += self.vscalex
self.scaley += self.vscaley
if self.vscale != 0:
self.w = self.max_w * self.scale
self.h = self.max_h * self.scale
else:
self.w = self.max_w * self.scalex
self.h = self.max_h * self.scaley
self.w = constrain(self.w, self.min_w, self.max_w)
self.h = constrain(self.h, self.min_h, self.max_h)
self.x += self.vx
self.y += self.vy
self.z += self.vz
if self.w in [self.max_w, self.min_w] and self.h in [self.max_h, self.min_h]:
self.frame_expired += 1
self.in_transition = False
else:
self.frame_expired = 0
self.in_transition = True
if not self.masked:
self.background = np.zeros((int(self.h), int(self.w), 3), np.uint8)
self.background.fill(self.bg)
def to_screen(self):
if self.z != 0:
vecx = self.x - winsize[0] / 2
vecy = self.y - winsize[1] / 2
vect = np.array([vecx, vecy])
normv = vect/np.sqrt(np.sum(vect**2))
normx, normy = normv[0], normv[1]
return self.x + self.z * normx, self.y + self.z * normy
else:
return self.x, self.y
def draw(self, x=None, y=None, hide = False, destroy = False):
self.w = constrain(self.w, self.min_w, self.max_w)
self.h = constrain(self.h, self.min_h, self.max_h)
if x is None and y is None:
x, y = int(self.x), int(self.y)
if self.w == self.min_w and self.h == self.min_h:
if destroy:
cv2.destroyWindow(self.name)
return
if hide:
pass
else:
return
if self.z != 0:
vecx = self.x - winsize[0] / 2
vecy = self.y - winsize[1] / 2
vect = np.array([vecx, vecy])
normv = vect/np.sqrt(np.sum(vect**2))
normx, normy = normv[0], normv[1]
x += self.z * normx
y += self.z * normy
cv2.namedWindow(self.name, cv2.WINDOW_NORMAL)
cv2.moveWindow(self.name,
int((x - self.w / 2 * self.window_scale + self.offsetx)),
int((y - self.h / 2 * self.window_scale + self.offsety)),
)
cv2.resizeWindow(self.name, int(self.w * self.window_scale), int(self.h * self.window_scale))
if len(self.background) != 0:
cv2.imshow(self.name, self.background)
cv2.waitKey(1) | 4,738 |
319 | <filename>streams/storm/tools/NaiveBayesStorm/src/main/java/org/openimaj/storm/topology/orchestrator/TwitterNaiveBayesTopologyOrchestrator.java
package org.openimaj.storm.topology.orchestrator;
import java.util.List;
import org.openimaj.kestrel.KestrelServerSpec;
import backtype.storm.generated.StormTopology;
import backtype.storm.scheme.StringScheme;
import backtype.storm.spout.UnreliableKestrelThriftSpout;
/**
* @author <NAME> (<EMAIL>)
*
*/
public class TwitterNaiveBayesTopologyOrchestrator implements StormTopologyOrchestrator{
private List<KestrelServerSpec> serverList;
private String queue;
@Override
public StormTopology buildTopology() {
UnreliableKestrelThriftSpout spout = new UnreliableKestrelThriftSpout(serverList,new StringScheme(),queue);
// TwitterBolt bolt = new TwitterBolt();
return null;
}
}
| 287 |
575 | /* <NAME> `gentilkiwi`
http://blog.gentilkiwi.com
<EMAIL>
Licence : https://creativecommons.org/licenses/by/4.0/
*/
#pragma once
#include "globals.h"
#include "kull_m_process.h"
typedef enum _OBJECT_INFORMATION_CLASS
{
ObjectBasicInformation,
ObjectNameInformation,
ObjectTypeInformation,
ObjectAllInformation,
ObjectDataInformation
} OBJECT_INFORMATION_CLASS, *POBJECT_INFORMATION_CLASS;
typedef struct _OBJECT_TYPE_INFORMATION
{
UNICODE_STRING TypeName;
ULONG TotalNumberOfObjects;
ULONG TotalNumberOfHandles;
ULONG TotalPagedPoolUsage;
ULONG TotalNonPagedPoolUsage;
ULONG TotalNamePoolUsage;
ULONG TotalHandleTableUsage;
ULONG HighWaterNumberOfObjects;
ULONG HighWaterNumberOfHandles;
ULONG HighWaterPagedPoolUsage;
ULONG HighWaterNonPagedPoolUsage;
ULONG HighWaterNamePoolUsage;
ULONG HighWaterHandleTableUsage;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccessMask;
BOOLEAN SecurityRequired;
BOOLEAN MaintainHandleCount;
// ...
ULONG PoolType;
ULONG DefaultPagedPoolCharge;
ULONG DefaultNonPagedPoolCharge;
} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;
typedef struct __PUBLIC_OBJECT_TYPE_INFORMATION
{
UNICODE_STRING TypeName;
ULONG Reserved [22]; // reserved for internal use
} PUBLIC_OBJECT_TYPE_INFORMATION, *PPUBLIC_OBJECT_TYPE_INFORMATION;
typedef struct _OBJECT_BASIC_INFORMATION
{
ULONG Attributes;
ACCESS_MASK GrantedAccess;
ULONG HandleCount;
ULONG PointerCount;
ULONG PagedPoolCharge;
ULONG NonPagedPoolCharge;
ULONG Reserved[3];
ULONG NameInfoSize;
ULONG TypeInfoSize;
ULONG SecurityDescriptorSize;
LARGE_INTEGER CreationTime;
} OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION;
typedef struct _PUBLIC_OBJECT_BASIC_INFORMATION
{
ULONG Attributes;
ACCESS_MASK GrantedAccess;
ULONG HandleCount;
ULONG PointerCount;
ULONG Reserved[10]; // reserved for internal use
} PUBLIC_OBJECT_BASIC_INFORMATION, *PPUBLIC_OBJECT_BASIC_INFORMATION;
extern NTSTATUS WINAPI NtQueryObject(IN OPTIONAL HANDLE Handle, IN OBJECT_INFORMATION_CLASS ObjectInformationClass, OUT OPTIONAL PVOID ObjectInformation, IN ULONG ObjectInformationLength, OUT OPTIONAL PULONG ReturnLength);
typedef struct _SYSTEM_HANDLE
{
DWORD ProcessId;
BYTE ObjectTypeNumber;
BYTE Flags;
USHORT Handle;
PVOID Object;
ACCESS_MASK GrantedAccess;
} SYSTEM_HANDLE, *PSYSTEM_HANDLE;
typedef struct _SYSTEM_HANDLE_INFORMATION
{
DWORD HandleCount;
SYSTEM_HANDLE Handles[ANYSIZE_ARRAY];
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
typedef BOOL (CALLBACK * PKULL_M_SYSTEM_HANDLE_ENUM_CALLBACK) (PSYSTEM_HANDLE pSystemHandle, PVOID pvArg);
typedef BOOL (CALLBACK * PKULL_M_HANDLE_ENUM_CALLBACK) (HANDLE handle, PSYSTEM_HANDLE pSystemHandle, PVOID pvArg);
typedef struct _HANDLE_ENUM_DATA
{
PCUNICODE_STRING type;
DWORD dwDesiredAccess;
DWORD dwOptions;
PKULL_M_HANDLE_ENUM_CALLBACK callBack;
PVOID pvArg;
} HANDLE_ENUM_DATA, *PHANDLE_ENUM_DATA;
NTSTATUS kull_m_handle_getHandles(PKULL_M_SYSTEM_HANDLE_ENUM_CALLBACK callBack, PVOID pvArg);
NTSTATUS kull_m_handle_getHandlesOfType(PKULL_M_HANDLE_ENUM_CALLBACK callBack, LPCTSTR type, DWORD dwDesiredAccess, DWORD dwOptions, PVOID pvArg);
BOOL CALLBACK kull_m_handle_getHandlesOfType_callback(PSYSTEM_HANDLE pSystemHandle, PVOID pvArg);
BOOL kull_m_handle_GetUserObjectInformation(HANDLE hObj, int nIndex, PVOID *pvInfo, PDWORD nLength); | 1,299 |
1,717 | <filename>src/test/java/perf/ConcurrencyReadTest.java
package perf;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import com.fasterxml.jackson.core.*;
/**
* Manual performance test to try out various synchronization
* methods for symbol tables.
*/
public class ConcurrencyReadTest
{
private final static int THREADS = 50;
private void test() throws Exception
{
final JsonFactory jf = new JsonFactory();
final byte[] INPUT = "{\"a\":1}".getBytes("UTF-8");
final AtomicInteger count = new AtomicInteger();
for (int i = 0; i < THREADS; ++i) {
new Thread(new Runnable() {
@Override
public void run()
{
try {
while (true) {
parse(jf, INPUT);
count.addAndGet(1);
}
} catch (IOException e) {
System.err.println("PROBLEM: "+e);
}
}
}).start();
}
// wait slightly....
Thread.sleep(200L);
double totalTime = 0.0;
double totalCount = 0.0;
while (true) {
long start = System.currentTimeMillis();
int startCount = count.get();
Thread.sleep(1000L);
int done = count.get() - startCount;
long time = System.currentTimeMillis() - start;
totalTime += time;
totalCount += done;
double rate = (double) done / (double) time;
System.out.printf("Rate: %.1f (avg: %.1f)\n", rate, totalCount/totalTime);
}
}
protected void parse(JsonFactory jf, byte[] input) throws IOException
{
JsonParser jp = jf.createParser(input, 0, input.length);
while (jp.nextToken() != null) {
;
}
jp.close();
}
public static void main(String[] args) throws Exception
{
if (args.length != 0) {
System.err.println("Usage: java ...");
System.exit(1);
}
new ConcurrencyReadTest().test();
}
}
| 1,141 |
507 | <gh_stars>100-1000
# tests/test_provider_camptocamp_geoserver.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:16:50 UTC)
def test_provider_import():
import terrascript.provider.camptocamp.geoserver
def test_resource_import():
from terrascript.resource.camptocamp.geoserver import geoserver_datastore
from terrascript.resource.camptocamp.geoserver import geoserver_featuretype
from terrascript.resource.camptocamp.geoserver import geoserver_workspace
# TODO: Shortcut imports without namespace for official and supported providers.
# TODO: This has to be moved into a required_providers block.
# def test_version_source():
#
# import terrascript.provider.camptocamp.geoserver
#
# t = terrascript.provider.camptocamp.geoserver.geoserver()
# s = str(t)
#
# assert 'https://github.com/camptocamp/terraform-provider-geoserver' in s
# assert '0.0.3' in s
| 324 |
32,544 | <gh_stars>1000+
package com.baeldung.storm.bolt;
import org.apache.storm.topology.BasicOutputCollector;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseBasicBolt;
import org.apache.storm.tuple.Tuple;
public class PrintingBolt extends BaseBasicBolt {
@Override
public void execute(Tuple tuple, BasicOutputCollector basicOutputCollector) {
System.out.println(tuple);
}
@Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
}
}
| 186 |
9,228 | <reponame>twstewart42/ParlAI
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from typing import Optional, Tuple
from parlai.agents.transformer.modules import (
create_embeddings,
BasicAttention,
TransformerEncoder,
TransformerResponseWrapper,
)
from parlai.core.opt import Opt
from parlai.core.torch_agent import DictionaryAgent
class TransformerMemNetModel(nn.Module):
"""
Model which takes context, memories, candidates and encodes them.
"""
@classmethod
def build_context_encoder(
cls, opt, dictionary, embedding=None, padding_idx=None, reduction_type='mean'
):
return cls.build_encoder(
opt, dictionary, embedding, padding_idx, reduction_type
)
@classmethod
def build_candidate_encoder(
cls, opt, dictionary, embedding=None, padding_idx=None, reduction_type='mean'
):
return cls.build_encoder(
opt, dictionary, embedding, padding_idx, reduction_type
)
@classmethod
def build_encoder(
cls, opt, dictionary, embedding=None, padding_idx=None, reduction_type='mean'
):
return TransformerEncoder(
opt=opt,
embedding=embedding,
vocabulary_size=len(dictionary),
padding_idx=padding_idx,
reduction_type=reduction_type,
)
def __init__(self, opt: Opt, dictionary: DictionaryAgent):
super().__init__()
self.opt = opt
self.pad_idx = dictionary[dictionary.null_token]
# set up embeddings
self.embeddings = create_embeddings(
dictionary, opt['embedding_size'], self.pad_idx
)
self.share_word_embedding = opt.get('share_word_embeddings', True)
if not self.share_word_embedding:
self.cand_embeddings = create_embeddings(
dictionary, opt['embedding_size'], self.pad_idx
)
if not opt.get('learn_embeddings'):
self.embeddings.weight.requires_grad = False
if not self.share_word_embedding:
self.cand_embeddings.weight.requires_grad = False
self.reduction_type = opt.get('reduction_type', 'mean')
self.context_encoder = self.build_context_encoder(
opt,
dictionary,
self.embeddings,
self.pad_idx,
reduction_type=self.reduction_type,
)
if opt.get('share_encoders'):
self.cand_encoder = TransformerResponseWrapper(
self.context_encoder, self.context_encoder.out_dim
)
else:
if not self.share_word_embedding:
cand_embeddings = self.cand_embeddings
else:
cand_embeddings = self.embeddings
self.cand_encoder = self.build_candidate_encoder(
opt,
dictionary,
cand_embeddings,
self.pad_idx,
reduction_type=self.reduction_type,
)
# build memory encoder
if opt.get('wrap_memory_encoder', False):
self.memory_transformer = TransformerResponseWrapper(
self.context_encoder, self.context_encoder.out_dim
)
else:
self.memory_transformer = self.context_encoder
self.attender = BasicAttention(
dim=2, attn=opt['memory_attention'], residual=True
)
def encode_cand(self, words):
"""
Encode the candidates.
"""
if words is None:
return None
# flatten if there are many candidates
if words.dim() == 3:
oldshape = words.shape
words = words.reshape(oldshape[0] * oldshape[1], oldshape[2])
else:
oldshape = None
encoded = self.cand_encoder(words)
if oldshape is not None:
encoded = encoded.reshape(oldshape[0], oldshape[1], -1)
return encoded
def encode_context_memory(self, context_w, memories_w, context_segments=None):
"""
Encode the context and memories.
"""
# [batch, d]
if context_w is None:
# it's possible that only candidates were passed into the
# forward function, return None here for LHS representation
return None, None
context_h = self.context_encoder(context_w, segments=context_segments)
if memories_w is None:
return [], context_h
bsz = memories_w.size(0)
memories_w = memories_w.view(-1, memories_w.size(-1))
memories_h = self.memory_transformer(memories_w)
memories_h = memories_h.view(bsz, -1, memories_h.size(-1))
context_h = context_h.unsqueeze(1)
context_h, weights = self.attender(context_h, memories_h)
return weights, context_h
def forward(
self,
xs: torch.LongTensor,
mems: torch.LongTensor,
cands: torch.LongTensor,
context_segments: Optional[torch.LongTensor] = None,
) -> Tuple[torch.LongTensor, torch.LongTensor]:
"""
Forward pass.
:param LongTensor[batch,seqlen] xs: input tokens IDs
:param LongTensor[batch,num_mems,seqlen] mems: memory token IDs
:param LongTensor[batch,num_cands,seqlen] cands: candidate token IDs
:param LongTensor[batch,seqlen] context_segments: segment IDs for xs,
used if n_segments is > 0 for the context encoder
"""
# encode the context and memories together
weights, context_h = self.encode_context_memory(
xs, mems, context_segments=context_segments
)
# encode the candidates
cands_h = self.encode_cand(cands)
# possibly normalize the context and candidate representations
if self.opt['normalize_sent_emb']:
context_h = context_h / context_h.norm(2, dim=1, keepdim=True)
cands_h = cands_h / cands_h.norm(2, dim=1, keepdim=True)
return context_h, cands_h
| 2,823 |
333 | #include <caml/alloc.h>
#include <caml/memory.h>
#include <caml/mlvalues.h>
#include <unistd.h>
// Detect platform
#if defined(_WIN32)
#define OCAML_ALCOTEST_WINDOWS
#elif defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
#if defined(_POSIX_VERSION)
#define OCAML_ALCOTEST_POSIX
#endif
#endif
// Windows support
#if defined(OCAML_ALCOTEST_WINDOWS)
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <windows.h>
CAMLprim value ocaml_alcotest_get_terminal_dimensions(value unit)
{
CAMLparam1(unit);
CAMLlocal2(result, pair);
CONSOLE_SCREEN_BUFFER_INFO csbi;
int success = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
if (success)
{
result = caml_alloc(1, 0);
pair = caml_alloc(2, 0);
Store_field(result, 0, pair);
Store_field(pair, 0, Val_int((int)(csbi.dwSize.Y)));
Store_field(pair, 1, Val_int((int)(csbi.dwSize.X)));
}
else
{
result = Val_int(0);
}
CAMLreturn(result);
}
// POSIX support
#elif defined(OCAML_ALCOTEST_POSIX)
#include <sys/ioctl.h>
CAMLprim value ocaml_alcotest_get_terminal_dimensions(value unit)
{
CAMLparam1(unit);
CAMLlocal2(result, pair);
struct winsize ws;
int z = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
if (z == 0)
{
result = caml_alloc(1, 0);
pair = caml_alloc(2, 0);
Store_field(result, 0, pair);
Store_field(pair, 0, Val_int(ws.ws_row));
Store_field(pair, 1, Val_int(ws.ws_col));
}
else
{
result = Val_int(0);
}
CAMLreturn(result);
}
// Unsupported platform
#else
CAMLprim value ocaml_alcotest_get_terminal_dimensions(value unit)
{
CAMLparam1(unit);
CAMLlocal2(result, pair);
result = Val_int(0);
CAMLreturn(result);
}
#endif
/* duplicated from caml/sys.h and io.c */
CAMLextern value caml_channel_descriptor(value vchannel);
#define NO_ARG Val_int(0)
CAMLextern void caml_sys_error (value);
/* End of code duplication */
static int alcotest_saved_stdout;
static int alcotest_saved_stderr;
CAMLprim value alcotest_before_test (value voutput, value vstdout, value vstderr) {
int output_fd, stdout_fd, stderr_fd, fd, ret;
stdout_fd = Int_val(caml_channel_descriptor(vstdout));
stderr_fd = Int_val(caml_channel_descriptor(vstderr));
output_fd = Int_val(caml_channel_descriptor(voutput));
fd = dup(stdout_fd);
if(fd == -1) caml_sys_error(NO_ARG);
alcotest_saved_stdout = fd;
fd = dup(stderr_fd);
if(fd == -1) caml_sys_error(NO_ARG);
alcotest_saved_stderr = fd;
ret = dup2(output_fd, stdout_fd);
if(ret == -1) caml_sys_error(NO_ARG);
ret = dup2(output_fd, stderr_fd);
if(ret == -1) caml_sys_error(NO_ARG);
return Val_unit;
}
CAMLprim value alcotest_after_test (value vstdout, value vstderr) {
int stdout_fd, stderr_fd, ret;
stdout_fd = Int_val(caml_channel_descriptor(vstdout));
stderr_fd = Int_val(caml_channel_descriptor(vstderr));
ret = dup2(alcotest_saved_stdout, stdout_fd);
if(ret == -1) caml_sys_error(NO_ARG);
ret = dup2(alcotest_saved_stderr, stderr_fd);
if(ret == -1) caml_sys_error(NO_ARG);
ret = close(alcotest_saved_stdout);
if(ret == -1) caml_sys_error(NO_ARG);
ret = close(alcotest_saved_stderr);
if(ret == -1) caml_sys_error(NO_ARG);
return Val_unit;
}
| 1,421 |
337 | <gh_stars>100-1000
import java.util.*;
class A {
private Collection<String> collection;
A() {
collection = createCollection();
}
Collection<String> createCollection() {
return new ArrayList<>();
}
public void foo() {
collection.add("1")
}
public Collection<String> getCollection() {
return collection;
}
} | 147 |
23,439 | <reponame>joyeekk/nacos
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.cluster.transport;
import com.alibaba.nacos.common.utils.ByteUtils;
import com.alibaba.nacos.naming.consistency.Datum;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Instances;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JacksonSerializerTest {
private Serializer serializer;
private Instances instances;
@Before
public void setUp() throws Exception {
serializer = new JacksonSerializer();
instances = new Instances();
instances.getInstanceList().add(new Instance("1.1.1.1", 1234, "cluster"));
}
@Test
public void testSerialize() {
String actual = new String(serializer.serialize(instances));
assertTrue(actual.contains("\"instanceList\":["));
assertTrue(actual.contains("\"clusterName\":\"cluster\""));
assertTrue(actual.contains("\"ip\":\"1.1.1.1\""));
assertTrue(actual.contains("\"port\":1234"));
}
@Test
@SuppressWarnings("checkstyle:linelength")
public void testDeserialize() {
String example = "{\"instanceList\":[{\"ip\":\"1.1.1.1\",\"port\":1234,\"weight\":1.0,\"healthy\":true,\"enabled\":true,\"ephemeral\":true,\"clusterName\":\"cluster\",\"metadata\":{},\"lastBeat\":1590563397264,\"marked\":false,\"instanceIdGenerator\":\"simple\",\"instanceHeartBeatInterval\":5000,\"instanceHeartBeatTimeOut\":15000,\"ipDeleteTimeout\":30000}]}";
Instances actual = serializer.deserialize(ByteUtils.toBytes(example), Instances.class);
assertEquals(1, actual.getInstanceList().size());
Instance actualInstance = actual.getInstanceList().get(0);
assertEquals("1.1.1.1", actualInstance.getIp());
assertEquals("cluster", actualInstance.getClusterName());
assertEquals(1234, actualInstance.getPort());
}
@Test
@SuppressWarnings("checkstyle:linelength")
public void testDeserializeMap() {
String example = "{\"datum\":{\"key\":\"instances\",\"value\":{\"instanceList\":[{\"ip\":\"1.1.1.1\",\"port\":1234,\"weight\":1.0,\"healthy\":true,\"enabled\":true,\"ephemeral\":true,\"clusterName\":\"cluster\",\"metadata\":{},\"lastBeat\":1590563397533,\"marked\":false,\"instanceIdGenerator\":\"simple\",\"instanceHeartBeatInterval\":5000,\"instanceHeartBeatTimeOut\":15000,\"ipDeleteTimeout\":30000}]},\"timestamp\":100000}}";
Map<String, Datum<Instances>> actual = serializer.deserializeMap(ByteUtils.toBytes(example), Instances.class);
assertEquals(actual.size(), 1);
assertTrue(actual.containsKey("datum"));
Datum<Instances> actualDatum = actual.get("datum");
assertEquals("instances", actualDatum.key);
assertEquals(100000L, actualDatum.timestamp.get());
assertEquals(1, actualDatum.value.getInstanceList().size());
Instance actualInstance = actualDatum.value.getInstanceList().get(0);
assertEquals("1.1.1.1", actualInstance.getIp());
assertEquals("cluster", actualInstance.getClusterName());
assertEquals(1234, actualInstance.getPort());
}
}
| 1,413 |
5,169 | <filename>Specs/c/3/a/PointFree-Validated/0.2.0/PointFree-Validated.podspec.json
{
"name": "PointFree-Validated",
"module_name": "Validated",
"version": "0.2.0",
"summary": "A result type that accumulates multiple errors.",
"description": "Swift error handling short-circuits on the first failure. Because of this, it's not the greatest option for handling things like form data, where multiple inputs may result in multiple errors.\n\nValidated is a Result-like type that can accumulate multiple errors.",
"homepage": "https://github.com/pointfreeco/swift-validated",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>",
"<NAME>": "<EMAIL>"
},
"social_media_url": "https://twitter.com/pointfreeco",
"source": {
"git": "https://github.com/pointfreeco/swift-validated.git",
"tag": "0.2.0"
},
"platforms": {
"ios": "8.0",
"osx": "10.9",
"tvos": "9.0",
"watchos": "2.0"
},
"source_files": [
"Sources",
"Sources/**/*.swift"
],
"dependencies": {
"NonEmpty": [
"~> 0.2.0"
]
}
}
| 416 |
14,668 | <reponame>zealoussnow/chromium
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill_assistant/browser/actions/select_option_action.h"
#include "base/guid.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/data_model/autofill_profile.h"
#include "components/autofill/core/browser/field_types.h"
#include "components/autofill_assistant/browser/actions/action_test_utils.h"
#include "components/autofill_assistant/browser/actions/mock_action_delegate.h"
#include "components/autofill_assistant/browser/selector.h"
#include "components/autofill_assistant/browser/service.pb.h"
#include "components/autofill_assistant/browser/user_model.h"
#include "components/autofill_assistant/browser/web/mock_web_controller.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace autofill_assistant {
namespace {
using ::base::test::RunOnceCallback;
using ::testing::_;
using ::testing::InSequence;
using ::testing::Pointee;
using ::testing::Property;
using ::testing::Return;
class SelectOptionActionTest : public testing::Test {
public:
SelectOptionActionTest() {}
void SetUp() override {
ON_CALL(mock_action_delegate_, GetWebController)
.WillByDefault(Return(&mock_web_controller_));
proto_.set_option_comparison_attribute(SelectOptionProto::VALUE);
}
protected:
void Run() {
ON_CALL(mock_action_delegate_, GetUserData)
.WillByDefault(Return(&user_data_));
ActionProto action_proto;
*action_proto.mutable_select_option() = proto_;
SelectOptionAction action(&mock_action_delegate_, action_proto);
action.ProcessAction(callback_.Get());
}
MockActionDelegate mock_action_delegate_;
MockWebController mock_web_controller_;
base::MockCallback<Action::ProcessActionCallback> callback_;
SelectOptionProto proto_;
UserData user_data_;
UserModel user_model_;
};
TEST_F(SelectOptionActionTest, NoValueToSelectFails) {
Selector selector({"#select"});
*proto_.mutable_element() = selector.proto;
EXPECT_CALL(
callback_,
Run(Pointee(Property(&ProcessedActionProto::status, INVALID_ACTION))));
Run();
}
TEST_F(SelectOptionActionTest, EmptyTextFilterValueFails) {
Selector selector({"#select"});
*proto_.mutable_element() = selector.proto;
proto_.mutable_text_filter_value()->set_re2("");
EXPECT_CALL(
callback_,
Run(Pointee(Property(&ProcessedActionProto::status, INVALID_ACTION))));
Run();
}
TEST_F(SelectOptionActionTest, EmptyAutofillValueFails) {
Selector selector({"#select"});
*proto_.mutable_element() = selector.proto;
proto_.mutable_autofill_regexp_value();
EXPECT_CALL(
callback_,
Run(Pointee(Property(&ProcessedActionProto::status, INVALID_ACTION))));
Run();
}
TEST_F(SelectOptionActionTest, EmptySelectorFails) {
proto_.mutable_text_filter_value()->set_re2("option");
EXPECT_CALL(
callback_,
Run(Pointee(Property(&ProcessedActionProto::status, INVALID_SELECTOR))));
Run();
}
TEST_F(SelectOptionActionTest, MissingOptionComparisonAttributeFails) {
Selector selector({"select"});
*proto_.mutable_element() = selector.proto;
proto_.set_option_comparison_attribute(SelectOptionProto::NOT_SET);
EXPECT_CALL(
callback_,
Run(Pointee(Property(&ProcessedActionProto::status, INVALID_ACTION))));
Run();
}
TEST_F(SelectOptionActionTest, CheckExpectedCallChain) {
InSequence sequence;
Selector selector({"#select"});
*proto_.mutable_element() = selector.proto;
proto_.mutable_text_filter_value()->set_re2("option");
proto_.set_strict(true);
Selector expected_selector = selector;
EXPECT_CALL(mock_action_delegate_,
OnShortWaitForElement(expected_selector, _))
.WillOnce(RunOnceCallback<1>(OkClientStatus(), base::Seconds(0)));
auto expected_element =
test_util::MockFindElement(mock_action_delegate_, expected_selector);
EXPECT_CALL(mock_web_controller_,
SelectOption("option", false, SelectOptionProto::VALUE, true,
EqualsElement(expected_element), _))
.WillOnce(RunOnceCallback<5>(OkClientStatus()));
EXPECT_CALL(
callback_,
Run(Pointee(Property(&ProcessedActionProto::status, ACTION_APPLIED))));
Run();
}
TEST_F(SelectOptionActionTest, RequestDataFromUnknownProfile) {
Selector selector({"#select"});
*proto_.mutable_element() = selector.proto;
auto* value = proto_.mutable_autofill_regexp_value();
value->mutable_profile()->set_identifier("none");
value->mutable_value_expression_re2()
->mutable_value_expression()
->add_chunk()
->set_text("value");
EXPECT_CALL(callback_, Run(Pointee(Property(&ProcessedActionProto::status,
PRECONDITION_FAILED))));
Run();
}
TEST_F(SelectOptionActionTest, RequestUnknownDataFromProfile) {
autofill::AutofillProfile contact(base::GenerateGUID(),
autofill::test::kEmptyOrigin);
// Middle name is expected to be empty.
autofill::test::SetProfileInfo(&contact, "John", /* middle name */ "", "Doe",
"", "", "", "", "", "", "", "", "");
user_model_.SetSelectedAutofillProfile(
"contact", std::make_unique<autofill::AutofillProfile>(contact),
&user_data_);
Selector selector({"#select"});
*proto_.mutable_element() = selector.proto;
auto* value = proto_.mutable_autofill_regexp_value();
value->mutable_profile()->set_identifier("contact");
value->mutable_value_expression_re2()
->mutable_value_expression()
->add_chunk()
->set_key(static_cast<int>(autofill::ServerFieldType::NAME_MIDDLE));
EXPECT_CALL(callback_, Run(Pointee(Property(&ProcessedActionProto::status,
AUTOFILL_INFO_NOT_AVAILABLE))));
Run();
}
TEST_F(SelectOptionActionTest, SelectOptionFromProfileValue) {
autofill::AutofillProfile contact(base::GenerateGUID(),
autofill::test::kEmptyOrigin);
autofill::test::SetProfileInfo(&contact, "John", "", "Doe", "", "", "", "",
"", "", "", "", "");
user_model_.SetSelectedAutofillProfile(
"contact", std::make_unique<autofill::AutofillProfile>(contact),
&user_data_);
InSequence sequence;
Selector selector({"#select"});
*proto_.mutable_element() = selector.proto;
auto* value = proto_.mutable_autofill_regexp_value();
value->mutable_profile()->set_identifier("contact");
value->mutable_value_expression_re2()
->mutable_value_expression()
->add_chunk()
->set_key(static_cast<int>(autofill::ServerFieldType::NAME_FIRST));
Selector expected_selector = selector;
EXPECT_CALL(mock_action_delegate_,
OnShortWaitForElement(expected_selector, _))
.WillOnce(RunOnceCallback<1>(OkClientStatus(), base::Seconds(0)));
EXPECT_CALL(mock_web_controller_,
SelectOption("John", false, SelectOptionProto::VALUE, false,
EqualsElement(test_util::MockFindElement(
mock_action_delegate_, expected_selector)),
_))
.WillOnce(RunOnceCallback<5>(OkClientStatus()));
EXPECT_CALL(
callback_,
Run(Pointee(Property(&ProcessedActionProto::status, ACTION_APPLIED))));
Run();
}
TEST_F(SelectOptionActionTest, SelectRegularExpressionValue) {
InSequence sequence;
Selector selector({"#select"});
*proto_.mutable_element() = selector.proto;
proto_.mutable_text_filter_value()->set_re2("^option$");
proto_.mutable_text_filter_value()->set_case_sensitive(true);
Selector expected_selector = selector;
EXPECT_CALL(mock_action_delegate_,
OnShortWaitForElement(expected_selector, _))
.WillOnce(RunOnceCallback<1>(OkClientStatus(), base::Seconds(0)));
auto expected_element =
test_util::MockFindElement(mock_action_delegate_, expected_selector);
EXPECT_CALL(mock_web_controller_,
SelectOption("^option$", true, SelectOptionProto::VALUE, false,
EqualsElement(expected_element), _))
.WillOnce(RunOnceCallback<5>(OkClientStatus()));
EXPECT_CALL(
callback_,
Run(Pointee(Property(&ProcessedActionProto::status, ACTION_APPLIED))));
Run();
}
TEST_F(SelectOptionActionTest, EscapeRegularExpressionAutofillValue) {
autofill::AutofillProfile contact(base::GenerateGUID(),
autofill::test::kEmptyOrigin);
autofill::test::SetProfileInfo(&contact, "John", "", "Doe", "", "", "", "",
"", "", "", "", "+41791234567");
user_model_.SetSelectedAutofillProfile(
"contact", std::make_unique<autofill::AutofillProfile>(contact),
&user_data_);
InSequence sequence;
Selector selector({"#select"});
*proto_.mutable_element() = selector.proto;
auto* value = proto_.mutable_autofill_regexp_value();
value->mutable_profile()->set_identifier("contact");
*value->mutable_value_expression_re2()->mutable_value_expression() =
test_util::ValueExpressionBuilder()
.addChunk("^")
.addChunk(autofill::ServerFieldType::PHONE_HOME_WHOLE_NUMBER)
.addChunk("$")
.toProto();
value->mutable_value_expression_re2()->set_case_sensitive(true);
Selector expected_selector = selector;
EXPECT_CALL(mock_action_delegate_,
OnShortWaitForElement(expected_selector, _))
.WillOnce(RunOnceCallback<1>(OkClientStatus(), base::Seconds(0)));
EXPECT_CALL(
mock_web_controller_,
SelectOption("^\\+41791234567$", true, SelectOptionProto::VALUE, false,
EqualsElement(test_util::MockFindElement(
mock_action_delegate_, expected_selector)),
_))
.WillOnce(RunOnceCallback<5>(OkClientStatus()));
EXPECT_CALL(
callback_,
Run(Pointee(Property(&ProcessedActionProto::status, ACTION_APPLIED))));
Run();
}
} // namespace
} // namespace autofill_assistant
| 4,132 |
897 | /* This algorithm will print the next greater element for all the indices in an array using stacks.
The procedure is to store the index of the next greater element in an answer array. Incase, there is no next greater element,
-1 will be stored.*/
#include <bits/stdc++.h>
using namespace std;
//Function to print the next greater element
void next_greater(int arr[],int n)
{
int ans[n]; //declaring an answer array
for(int i=0;i<n;i++)
ans[i]=-1; //marking all the indices with -1 initially
stack<int> s;
s.push(0); //pushing the zeroth index of arr
//iterating through the rest of indices of arr
for(int i=1;i<n;i++)
{
/*If the stack is not empty and the value at cuurent index (arr[i]) is greater than value at s.top(),
then next greater element for arr[s.top()] will be arr[i]. Once the next greater element for a particular
index is found, then tha particular index can be popped out*/
while(s.empty()==false && arr[i]>arr[s.top()])
{
ans[s.top()]=i;
s.pop();
}
s.push(i); //pushing the current index so that it can be compared with the values to its right in further iterations
}
//printing the final answer
for(int i=0;i<n;i++)
{
if(ans[i]==-1) //if the value of ans[i] remains -1, it means there is no next greater element for it
cout<<"-1 ";
else
cout<<arr[ans[i]]<<" ";
}
return;
}
//Driver Code
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
next_greater(arr,n);
return 0;
}
/* Time Complexity : o(n)
Space Complexity: O(n)
Sample Input : 4
4 5 2 25
Sample Output : 5 25 25 -1 */
| 710 |
17,809 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "winget/Manifest.h"
#include "winget/Locale.h"
#include "winget/UserSettings.h"
namespace AppInstaller::Manifest
{
void Manifest::ApplyLocale(const std::string& locale)
{
CurrentLocalization = DefaultLocalization;
// Get target locale from Preferred Languages settings if applicable
std::vector<std::string> targetLocales;
if (locale.empty())
{
targetLocales = Locale::GetUserPreferredLanguages();
}
else
{
targetLocales.emplace_back(locale);
}
for (auto const& targetLocale : targetLocales)
{
const ManifestLocalization* bestLocalization = nullptr;
double bestScore = Locale::GetDistanceOfLanguage(targetLocale, DefaultLocalization.Locale);
for (auto const& localization : Localizations)
{
double score = Locale::GetDistanceOfLanguage(targetLocale, localization.Locale);
if (score > bestScore)
{
bestLocalization = &localization;
bestScore = score;
}
}
// If there's better locale than default And is compatible with target locale, merge and return;
if (bestScore >= Locale::MinimumDistanceScoreAsCompatibleMatch)
{
if (bestLocalization != nullptr)
{
CurrentLocalization.ReplaceOrMergeWith(*bestLocalization);
}
break;
}
}
}
std::vector<string_t> Manifest::GetAggregatedTags() const
{
std::vector<string_t> resultTags = DefaultLocalization.Get<Localization::Tags>();
for (const auto& locale : Localizations)
{
auto tags = locale.Get<Localization::Tags>();
for (const auto& tag : tags)
{
if (std::find(resultTags.begin(), resultTags.end(), tag) == resultTags.end())
{
resultTags.emplace_back(tag);
}
}
}
return resultTags;
}
std::vector<string_t> Manifest::GetAggregatedCommands() const
{
std::vector<string_t> resultCommands;
for (const auto& installer : Installers)
{
for (const auto& command : installer.Commands)
{
if (std::find(resultCommands.begin(), resultCommands.end(), command) == resultCommands.end())
{
resultCommands.emplace_back(command);
}
}
}
return resultCommands;
}
} | 1,406 |
358 | {
"require": {
"fzaninotto/Faker": "1.2.*",
"laravel/framework": "4.1.*",
"league/fractal": "0.7.*",
"guzzlehttp/guzzle": "4.*",
"itsgoingd/clockwork": "~1.3"
},
"require-dev": {
"phpunit/phpunit": "3.7.*"
},
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
],
"psr-0": {
"App": "app/src/"
}
},
"config": {
"preferred-install": "dist"
},
"minimum-stability": "dev"
}
| 272 |
1,558 | {
"author": "Microsoft",
"name": "Map",
"description": "La page Plans s'appuie sur la commande Plan de Windows. Le code inclut l'ajout d'une icône Plan et une fonction de géolocalisation.",
"identity": "ts.Page.Map"
} | 84 |
2,338 | <gh_stars>1000+
// RUN: %libomptarget-compilexx-run-and-check-generic
// amdgcn does not have printf definition
// XFAIL: amdgcn-amd-amdhsa
#include <cstdio>
#include <cstdlib>
typedef struct {
int a;
double *b;
} C;
#pragma omp declare mapper(id1 : C s) map(to : s.a) map(from : s.b [0:2])
typedef struct {
int e;
C f;
int h;
short *g;
} D;
#pragma omp declare mapper(default \
: D r) map(from \
: r.e) map(mapper(id1), tofrom \
: r.f) map(tofrom \
: r.g [0:r.h])
int main() {
constexpr int N = 10;
D s;
s.e = 111;
s.f.a = 222;
double x[2];
x[1] = 20;
short y[N];
y[1] = 30;
s.f.b = &x[0];
s.g = &y[0];
s.h = N;
D *sp = &s;
D **spp = &sp;
printf("%d %d %4.5f %d %d %d\n", spp[0][0].e, spp[0][0].f.a, spp[0][0].f.b[1],
spp[0][0].f.b == &x[0] ? 1 : 0, spp[0][0].g[1],
spp[0][0].g == &y[0] ? 1 : 0);
// CHECK: 111 222 20.00000 1 30 1
__intptr_t p = reinterpret_cast<__intptr_t>(&x[0]),
p1 = reinterpret_cast<__intptr_t>(&y[0]);
#pragma omp target map(tofrom : spp[0][0]) firstprivate(p, p1)
{
printf("%d %d %d %d\n", spp[0][0].f.a,
spp[0][0].f.b == reinterpret_cast<void *>(p) ? 1 : 0, spp[0][0].g[1],
spp[0][0].g == reinterpret_cast<void *>(p1) ? 1 : 0);
// CHECK: 222 0 30 0
spp[0][0].e = 333;
spp[0][0].f.a = 444;
spp[0][0].f.b[1] = 40;
spp[0][0].g[1] = 50;
}
printf("%d %d %4.5f %d %d %d\n", spp[0][0].e, spp[0][0].f.a, spp[0][0].f.b[1],
spp[0][0].f.b == &x[0] ? 1 : 0, spp[0][0].g[1],
spp[0][0].g == &y[0] ? 1 : 0);
// CHECK: 333 222 40.00000 1 50 1
}
| 1,181 |
1,428 | <filename>worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/package-info.java
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Experimental, in-testing, snapshot API. Do NOT rely on this API in plugin releases, as it will
* move to the existing snapshot package when testing is complete.
*
* <p>
* The existing snapshot API will be removed when this API is made official. It aims to have 100%
* compatibility with old snapshot storage, bar some odd date formats.
* </p>
*/
package com.sk89q.worldedit.world.snapshot.experimental;
// TODO Un-experimentalize when ready.
| 367 |
7,482 | <filename>bsp/hc32f4a0/board/board.h
/*
* Copyright (C) 2020, Huada Semiconductor Co., Ltd.
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-10-30 CDT first version
* 2021-01-18 CDT MOdify SRAM_SIZE
*/
#ifndef __BOARD_H__
#define __BOARD_H__
#include <rtthread.h>
#include "hc32_ddl.h"
#include "drv_gpio.h"
/* board configuration */
#define SRAM_BASE 0x1FFE0000
#define SRAM_SIZE 0x80000
#define SRAM_END (SRAM_BASE + SRAM_SIZE)
/* High speed sram. */
#ifdef __CC_ARM
extern int Image$$RW_IRAM1$$ZI$$Limit;
#define HEAP_BEGIN (&Image$$RW_IRAM1$$ZI$$Limit)
#elif __ICCARM__
#pragma section="HEAP"
#define HEAP_BEGIN (__segment_end("HEAP"))
#else
extern int __bss_end;
#define HEAP_BEGIN (&__bss_end)
#endif
#ifdef __ICCARM__
// Use *.icf ram symbal, to avoid hardcode.
extern char __ICFEDIT_region_RAM_end__;
#define HEAP_END (&__ICFEDIT_region_RAM_end__)
#else
#define HEAP_END SRAM_END
#endif
void Peripheral_WE(void);
void Peripheral_WP(void);
void rt_hw_board_init(void);
void rt_hw_us_delay(rt_uint32_t us);
#endif
// <<< Use Configuration Wizard in Context Menu >>>
| 583 |
1,475 | <reponame>mhansonp/geode
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.internal.index;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.apache.geode.cache.EvictionAction;
import org.apache.geode.cache.EvictionAttributes;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.RegionEntry;
public class IndexManagerTest {
private IndexManager indexManager;
@Before
public void setUp() {
Region region = mock(Region.class);
RegionAttributes regionAttributes = mock(RegionAttributes.class);
when(regionAttributes.getIndexMaintenanceSynchronous()).thenReturn(true);
when(regionAttributes.getEvictionAttributes()).thenReturn(mock(EvictionAttributes.class));
when(regionAttributes.getEvictionAttributes().getAction())
.thenReturn(EvictionAction.DEFAULT_EVICTION_ACTION);
when(region.getAttributes()).thenReturn(regionAttributes);
indexManager = new IndexManager(mock(InternalCache.class), region);
}
@Test
public void addIndexMappingShouldMarkIndexAsInvalidWhenAddMappingOperationFails()
throws IMQException {
RegionEntry mockEntry = mock(RegionEntry.class);
AbstractIndex mockIndex = mock(AbstractIndex.class);
mockIndex.prIndex = mock(AbstractIndex.class);
when(mockIndex.addIndexMapping(any())).thenThrow(new IMQException("Mock Exception"));
assertThatCode(() -> indexManager.addIndexMapping(mockEntry, mockIndex))
.doesNotThrowAnyException();
verify(mockIndex, times(1)).markValid(false);
verify((AbstractIndex) mockIndex.prIndex, times(1)).markValid(false);
}
@Test
public void removeIndexMappingShouldMarkIndexAsInvalidWhenRemoveMappingOperationFails()
throws IMQException {
RegionEntry mockEntry = mock(RegionEntry.class);
AbstractIndex mockIndex = mock(AbstractIndex.class);
mockIndex.prIndex = mock(AbstractIndex.class);
when(mockIndex.removeIndexMapping(mockEntry, 1)).thenThrow(new IMQException("Mock Exception"));
assertThatCode(() -> indexManager.removeIndexMapping(mockEntry, mockIndex, 1))
.doesNotThrowAnyException();
verify(mockIndex, times(1)).markValid(false);
verify((AbstractIndex) mockIndex.prIndex, times(1)).markValid(false);
}
}
| 1,021 |
1,178 | #ifndef __ASM_X86_BITSPERLONG_H
#define __ASM_X86_BITSPERLONG_H
#ifdef __x86_64__
# define __BITS_PER_LONG 64
#else
# define __BITS_PER_LONG 32
#endif
#include <asm-generic/bitsperlong.h>
#endif /* __ASM_X86_BITSPERLONG_H */
| 112 |
611 | //
// TestMakeDestinationViewController.h
// ZIKRouterDemo
//
// Created by zuik on 2017/7/5.
// Copyright © 2017 zuik. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TestMakeDestinationViewController : UIViewController
@end
| 87 |
348 | <gh_stars>100-1000
{"nom":"Goulien","circ":"7ème circonscription","dpt":"Finistère","inscrits":348,"abs":146,"votants":202,"blancs":8,"nuls":3,"exp":191,"res":[{"nuance":"REM","nom":"<NAME>","voix":110},{"nuance":"LR","nom":"<NAME>","voix":81}]} | 98 |
626 | <gh_stars>100-1000
/* inflate_p.h -- Private inline functions and macros shared with more than one deflate method
*
*/
#ifndef INFLATE_P_H
#define INFLATE_P_H
#include "zbuild.h"
#include "functable.h"
/* Architecture-specific hooks. */
#ifdef S390_DFLTCC_INFLATE
# include "arch/s390/dfltcc_inflate.h"
#else
/* Memory management for the inflate state. Useful for allocating arch-specific extension blocks. */
# define ZALLOC_STATE(strm, items, size) ZALLOC(strm, items, size)
# define ZFREE_STATE(strm, addr) ZFREE(strm, addr)
# define ZCOPY_STATE(dst, src, size) memcpy(dst, src, size)
/* Memory management for the window. Useful for allocation the aligned window. */
# define ZALLOC_WINDOW(strm, items, size) ZALLOC(strm, items, size)
# define ZFREE_WINDOW(strm, addr) ZFREE(strm, addr)
/* Invoked at the end of inflateResetKeep(). Useful for initializing arch-specific extension blocks. */
# define INFLATE_RESET_KEEP_HOOK(strm) do {} while (0)
/* Invoked at the beginning of inflatePrime(). Useful for updating arch-specific buffers. */
# define INFLATE_PRIME_HOOK(strm, bits, value) do {} while (0)
/* Invoked at the beginning of each block. Useful for plugging arch-specific inflation code. */
# define INFLATE_TYPEDO_HOOK(strm, flush) do {} while (0)
/* Returns whether zlib-ng should compute a checksum. Set to 0 if arch-specific inflation code already does that. */
# define INFLATE_NEED_CHECKSUM(strm) 1
/* Returns whether zlib-ng should flush the window to the output buffer.
Set to 0 if arch-specific inflation code already does that. */
# define INFLATE_NEED_WINDOW_OUTPUT_FLUSH(strm) 1
/* Invoked at the beginning of inflateMark(). Useful for updating arch-specific pointers and offsets. */
# define INFLATE_MARK_HOOK(strm) do {} while (0)
/* Invoked at the beginning of inflateSyncPoint(). Useful for performing arch-specific state checks. */
# define INFLATE_SYNC_POINT_HOOK(strm) do {} while (0)
/* Invoked at the beginning of inflateSetDictionary(). Useful for checking arch-specific window data. */
# define INFLATE_SET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
/* Invoked at the beginning of inflateGetDictionary(). Useful for adjusting arch-specific window data. */
# define INFLATE_GET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
#endif
/*
* Macros shared by inflate() and inflateBack()
*/
/* check macros for header crc */
#ifdef GUNZIP
# define CRC2(check, word) \
do { \
hbuf[0] = (unsigned char)(word); \
hbuf[1] = (unsigned char)((word) >> 8); \
check = PREFIX(crc32)(check, hbuf, 2); \
} while (0)
# define CRC4(check, word) \
do { \
hbuf[0] = (unsigned char)(word); \
hbuf[1] = (unsigned char)((word) >> 8); \
hbuf[2] = (unsigned char)((word) >> 16); \
hbuf[3] = (unsigned char)((word) >> 24); \
check = PREFIX(crc32)(check, hbuf, 4); \
} while (0)
#endif
/* Load registers with state in inflate() for speed */
#define LOAD() \
do { \
put = state->window + state->wsize + state->wnext; \
left = strm->avail_out; \
next = strm->next_in; \
have = strm->avail_in; \
hold = state->hold; \
bits = state->bits; \
} while (0)
/* Load registers with state in inflateBack() for speed */
#define LOAD_BACK() \
do { \
put = strm->next_out; \
left = strm->avail_out; \
next = strm->next_in; \
have = strm->avail_in; \
hold = state->hold; \
bits = state->bits; \
} while (0)
/* Restore state from registers in inflate() */
#define RESTORE() \
do { \
state->wnext = (uint32_t)(put - (state->window + state->wsize)); \
strm->avail_out = left; \
strm->next_in = (z_const unsigned char *)next; \
strm->avail_in = have; \
state->hold = hold; \
state->bits = bits; \
} while (0)
/* Restore state from registers in inflateBack() */
#define RESTORE_BACK() \
do { \
strm->next_out = put; \
strm->avail_out = left; \
strm->next_in = (z_const unsigned char *)next; \
strm->avail_in = have; \
state->hold = hold; \
state->bits = bits; \
} while (0)
/* Clear the input bit accumulator */
#define INITBITS() \
do { \
hold = 0; \
bits = 0; \
} while (0)
/* Ensure that there is at least n bits in the bit accumulator. If there is
not enough available input to do that, then return from inflate()/inflateBack(). */
#define NEEDBITS(n) \
do { \
while (bits < (unsigned)(n)) \
PULLBYTE(); \
} while (0)
/* Return the low n bits of the bit accumulator (n < 16) */
#define BITS(n) \
(hold & ((1U << (unsigned)(n)) - 1))
/* Remove n bits from the bit accumulator */
#define DROPBITS(n) \
do { \
hold >>= (n); \
bits -= (unsigned)(n); \
} while (0)
/* Remove zero to seven bits as needed to go to a byte boundary */
#define BYTEBITS() \
do { \
hold >>= bits & 7; \
bits -= bits & 7; \
} while (0)
#endif
/* Set mode=BAD and prepare error message */
#define SET_BAD(errmsg) \
do { \
state->mode = BAD; \
strm->msg = (char *)errmsg; \
} while (0)
static inline void inf_crc_copy(PREFIX3(stream) *strm, unsigned char *const dst,
const unsigned char *const src, size_t len) {
struct inflate_state *const state = (struct inflate_state *const)strm->state;
if (!INFLATE_NEED_CHECKSUM(strm))
return;
/* compute checksum if not in raw mode */
if (state->wrap & 4) {
/* check flags to use adler32() for zlib or crc32() for gzip */
#ifdef GUNZIP
if (state->flags)
functable.crc32_fold_copy(&state->crc_fold, dst, src, len);
else
#endif
{
memcpy(dst, src, len);
strm->adler = state->check = functable.adler32(state->check, dst, len);
}
} else {
memcpy(dst, src, len);
}
}
static inline void window_output_flush(PREFIX3(stream) *strm) {
struct inflate_state *const state = (struct inflate_state *const)strm->state;
size_t write_offset, read_offset, copy_size;
uint32_t out_bytes;
if (state->wnext > strm->avail_out) {
out_bytes = strm->avail_out;
copy_size = state->wnext - out_bytes;
} else {
out_bytes = state->wnext;
copy_size = 0;
}
/* Copy from pending buffer to stream output */
inf_crc_copy(strm, strm->next_out, state->window + state->wsize, out_bytes);
strm->avail_out -= out_bytes;
strm->next_out += out_bytes;
/* Discard bytes in sliding window */
if (state->whave + out_bytes > state->wsize) {
write_offset = 0;
read_offset = out_bytes;
copy_size += state->wsize;
} else {
read_offset = state->wsize - state->whave;
write_offset = read_offset - out_bytes;
copy_size += state->whave + out_bytes;
}
memmove(state->window + write_offset, state->window + read_offset, copy_size);
state->wnext -= out_bytes;
state->whave += out_bytes;
state->whave = MIN(state->whave, state->wsize);
}
| 2,927 |
772 | <reponame>code-dot-org/code-dot-org
{
"category": "Poetry - Text",
"config": {
"func": "showText",
"blockText": "show text"
}
} | 63 |
1,517 | /*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the Apache 2.0 License.
* See the accompanying LICENSE file for terms.
*/
package com.yahoo.squidb.processor.plugins.defaults.properties.generators;
import com.yahoo.aptutils.model.CoreTypes;
import com.yahoo.aptutils.model.DeclaredTypeName;
import com.yahoo.aptutils.utils.AptUtils;
import com.yahoo.aptutils.writer.JavaFileWriter;
import com.yahoo.aptutils.writer.parameters.MethodDeclarationParameters;
import com.yahoo.squidb.processor.data.ModelSpec;
import com.yahoo.squidb.processor.plugins.defaults.properties.TableModelSpecFieldPlugin;
import java.io.IOException;
import javax.lang.model.element.VariableElement;
/**
* Special case of BasicLongPropertyGenerator specific to ROWID or INTEGER PRIMARY KEY properties
*/
public class RowidPropertyGenerator extends BasicLongPropertyGenerator {
public RowidPropertyGenerator(ModelSpec<?> modelSpec, String columnName, AptUtils utils) {
super(modelSpec, columnName, utils);
}
public RowidPropertyGenerator(ModelSpec<?> modelSpec, String columnName,
String propertyName, AptUtils utils) {
super(modelSpec, columnName, propertyName, utils);
}
public RowidPropertyGenerator(ModelSpec<?> modelSpec, VariableElement field, AptUtils utils) {
super(modelSpec, field, utils);
}
@Override
public DeclaredTypeName getTypeForAccessors() {
return CoreTypes.PRIMITIVE_LONG;
}
@Override
public String getterMethodName() {
// Camel case translation doesn't quite work in this case, so override
if (TableModelSpecFieldPlugin.DEFAULT_ROWID_PROPERTY_NAME.equals(propertyName)) {
return "getRowId";
}
return super.getterMethodName();
}
@Override
public String setterMethodName() {
// Camel case translation doesn't quite work in this case, so override
if (TableModelSpecFieldPlugin.DEFAULT_ROWID_PROPERTY_NAME.equals(propertyName)) {
return "setRowId";
}
return super.setterMethodName();
}
@Override
protected void writeGetterBody(JavaFileWriter writer, MethodDeclarationParameters params) throws IOException {
writer.writeStringStatement("return super.getRowId()");
}
@Override
protected void writeSetterBody(JavaFileWriter writer, MethodDeclarationParameters params) throws IOException {
writer.writeStringStatement("super.setRowId(" + params.getArgumentNames().get(0) + ")");
writer.writeStringStatement("return this");
}
}
| 877 |
930 | <reponame>akshaykumarpatil-tudip/deploymentmanager-samples
# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates a Container VM with the provided Container manifest."""
COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'
def GlobalComputeUrl(project, collection, name):
return ''.join([COMPUTE_URL_BASE, 'projects/', project,
'/global/', collection, '/', name])
def ZonalComputeUrl(project, zone, collection, name):
return ''.join([COMPUTE_URL_BASE, 'projects/', project,
'/zones/', zone, '/', collection, '/', name])
def GenerateConfig(context):
"""Generate configuration."""
res = []
base_name = (context.env['deployment'] + '-' +
context.env['name'])
# Properties for the container-based instance.
instance = {
'zone': context.properties['zone'],
'machineType': ZonalComputeUrl(context.env['project'],
context.properties['zone'],
'machineTypes',
'n1-standard-1'),
'metadata': {
'items': [{
'key': 'gce-container-declaration',
'value': context.imports[
context.properties['containerManifest']],
}]
},
'disks': [{
'deviceName': 'boot',
'type': 'PERSISTENT',
'autoDelete': True,
'boot': True,
'initializeParams': {
'diskName': base_name + '-disk',
'sourceImage': GlobalComputeUrl('cos-cloud',
'images',
context.properties[
'containerImage'])
},
}],
'networkInterfaces': [{
'accessConfigs': [{
'name': 'external-nat',
'type': 'ONE_TO_ONE_NAT'
}],
'network': GlobalComputeUrl(context.env['project'],
'networks',
'default')
}],
'serviceAccounts': [{
'email': 'default',
'scopes': [
"https://www.googleapis.com/auth/logging.write",
"https://www.googleapis.com/auth/monitoring.write"
]
}]
}
res.append({
'name': base_name,
'type': 'compute.v1.instance',
'properties': instance
})
# Resources to return.
resources = {
'resources': res,
}
return resources
| 1,472 |
313 | //
// YBLStoreViewModel.h
// YBL365
//
// Created by 乔同新 on 2017/3/7.
// Copyright © 2017年 乔同新. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "YBLShopFixtrueModel.h"
#import "YBLShopModel.h"
#import "YBLPerPageBaseViewModel.h"
typedef NS_ENUM(NSInteger,StoreType) {
StoreTypeOpen = 0,//
StoreTypePersonal //个人店铺
};
@interface YBLStoreViewModel : YBLPerPageBaseViewModel
@property (nonatomic, assign) StoreType storeType;
@property (nonatomic, strong) NSString *shopid;
@property (nonatomic, strong) shop *shopinfo;
@property (nonatomic, strong) NSMutableDictionary *goodCategoryDataDict;
@property (nonatomic, strong) NSMutableArray *nummberValueArray;
- (RACSignal *)signalForGetShopFixtrue;
- (RACSignal *)signalForUploadShopLogoWithImage:(UIImage *)image;
+ (RACSignal *)signalForShopDataWithID:(NSString *)shopID isReload:(BOOL)isReload;
- (RACSignal *)signalForShopDataWithIsReload:(BOOL)isReload;
- (RACSignal *)signalForShopDataWithID:(NSString *)shopID
category_id:(NSString *)category_id
isReload:(BOOL)isReload;
+ (RACSignal *)signalForStore:(NSString *)storeID isFollow:(BOOL)isFollow;
- (RACSignal *)signalForStoreFollow:(BOOL)isFollow;
- (BOOL)isHasBriberyMoney;
@end
| 535 |
302 | <filename>Engine/scriptworkerfactory.h<gh_stars>100-1000
#ifndef SCRIPTWORKERFACTORY_H
#define SCRIPTWORKERFACTORY_H
#include "engine_global.h"
#include "iworkerfactory.h"
namespace BrowserAutomationStudioFramework
{
class ENGINESHARED_EXPORT ScriptWorkerFactory : public IWorkerFactory
{
Q_OBJECT
public:
explicit ScriptWorkerFactory(QObject *parent = 0);
virtual IWorker *CreateWorker();
signals:
public slots:
};
}
#endif // SCRIPTWORKERFACTORY_H
| 197 |
3,053 | from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("sites", "0001_initial"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="SitePermission",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"sites",
models.ManyToManyField(
to="sites.Site", verbose_name="Sites", blank=True
),
),
(
"user",
models.ForeignKey(
related_name="sitepermissions",
verbose_name="Author",
to=settings.AUTH_USER_MODEL,
unique=True,
on_delete=models.CASCADE,
),
),
],
options={
"verbose_name": "Site permission",
"verbose_name_plural": "Site permissions",
},
bases=(models.Model,),
),
]
| 901 |
1,724 | /*
* Copyright 2008-present MongoDB, 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.mongodb.internal.connection;
import com.mongodb.connection.ConnectionDescription;
import com.mongodb.connection.ServerDescription;
public class InternalConnectionInitializationDescription {
private final ConnectionDescription connectionDescription;
private final ServerDescription serverDescription;
public InternalConnectionInitializationDescription(final ConnectionDescription connectionDescription,
final ServerDescription serverDescription) {
this.connectionDescription = connectionDescription;
this.serverDescription = serverDescription;
}
public ConnectionDescription getConnectionDescription() {
return connectionDescription;
}
public ServerDescription getServerDescription() {
return serverDescription;
}
public InternalConnectionInitializationDescription withConnectionDescription(final ConnectionDescription connectionDescription) {
return new InternalConnectionInitializationDescription(connectionDescription, serverDescription);
}
}
| 451 |
1,131 | //
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.agent.api;
import com.cloud.storage.VolumeStats;
public class VolumeStatsEntry implements VolumeStats {
String volumeUuid;
long physicalsize = 0;
long virtualSize = 0;
public VolumeStatsEntry(String volumeUuid, long physicalsize, long virtualSize) {
this.volumeUuid = volumeUuid;
this.physicalsize = physicalsize;
this.virtualSize = virtualSize;
}
public String getVolumeUuid() {
return volumeUuid;
}
public void setVolumeUuid(String volumeUuid) {
this.volumeUuid = volumeUuid;
}
public long getPhysicalSize() {
return physicalsize;
}
public void setPhysicalSize(long size) {
this.physicalsize = size;
}
public long getVirtualSize() {
return virtualSize;
}
public void setVirtualSize(long virtualSize) {
this.virtualSize = virtualSize;
}
@Override
public String toString() {
return "VolumeStatsEntry [volumeUuid=" + volumeUuid + ", size=" + physicalsize + ", virtualSize=" + virtualSize + "]";
}
}
| 598 |
1,863 | //
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxvGlobals.h"
#include "PxsContext.h"
#include "PxcContactMethodImpl.h"
#include "GuContactMethodImpl.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXGpu.h"
physx::PxPhysXGpu* gPxPhysXGpu;
#endif
namespace physx
{
PxvOffsetTable gPxvOffsetTable;
bool PxcLegacyContactSphereHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcLegacyContactCapsuleHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcLegacyContactBoxHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcLegacyContactConvexHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcPCMContactSphereHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcPCMContactCapsuleHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcPCMContactBoxHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcPCMContactConvexHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcContactSphereHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcContactCapsuleHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcContactBoxHeightField (GU_CONTACT_METHOD_ARGS);
bool PxcContactConvexHeightField (GU_CONTACT_METHOD_ARGS);
bool gUnifiedHeightfieldCollision = false;
void PxvRegisterHeightFields()
{
g_ContactMethodTable[PxGeometryType::eSPHERE][PxGeometryType::eHEIGHTFIELD] = PxcContactSphereHeightField;
g_ContactMethodTable[PxGeometryType::eCAPSULE][PxGeometryType::eHEIGHTFIELD] = PxcContactCapsuleHeightField;
g_ContactMethodTable[PxGeometryType::eBOX][PxGeometryType::eHEIGHTFIELD] = PxcContactBoxHeightField;
g_ContactMethodTable[PxGeometryType::eCONVEXMESH][PxGeometryType::eHEIGHTFIELD] = PxcContactConvexHeightField;
g_PCMContactMethodTable[PxGeometryType::eSPHERE][PxGeometryType::eHEIGHTFIELD] = PxcPCMContactSphereHeightField;
g_PCMContactMethodTable[PxGeometryType::eCAPSULE][PxGeometryType::eHEIGHTFIELD] = PxcPCMContactCapsuleHeightField;
g_PCMContactMethodTable[PxGeometryType::eBOX][PxGeometryType::eHEIGHTFIELD] = PxcPCMContactBoxHeightField;
g_PCMContactMethodTable[PxGeometryType::eCONVEXMESH][PxGeometryType::eHEIGHTFIELD] = PxcPCMContactConvexHeightField;
gUnifiedHeightfieldCollision = true;
}
void PxvRegisterLegacyHeightFields()
{
g_ContactMethodTable[PxGeometryType::eSPHERE][PxGeometryType::eHEIGHTFIELD] = PxcLegacyContactSphereHeightField;
g_ContactMethodTable[PxGeometryType::eCAPSULE][PxGeometryType::eHEIGHTFIELD] = PxcLegacyContactCapsuleHeightField;
g_ContactMethodTable[PxGeometryType::eBOX][PxGeometryType::eHEIGHTFIELD] = PxcLegacyContactBoxHeightField;
g_ContactMethodTable[PxGeometryType::eCONVEXMESH][PxGeometryType::eHEIGHTFIELD] = PxcLegacyContactConvexHeightField;
g_PCMContactMethodTable[PxGeometryType::eSPHERE][PxGeometryType::eHEIGHTFIELD] = PxcLegacyContactSphereHeightField;
g_PCMContactMethodTable[PxGeometryType::eCAPSULE][PxGeometryType::eHEIGHTFIELD] = PxcLegacyContactCapsuleHeightField;
g_PCMContactMethodTable[PxGeometryType::eBOX][PxGeometryType::eHEIGHTFIELD] = PxcLegacyContactBoxHeightField;
g_PCMContactMethodTable[PxGeometryType::eCONVEXMESH][PxGeometryType::eHEIGHTFIELD] = PxcLegacyContactConvexHeightField;
gUnifiedHeightfieldCollision = false;
}
void PxvInit(const PxvOffsetTable& offsetTable)
{
#if PX_SUPPORT_GPU_PHYSX
gPxPhysXGpu = NULL;
#endif
gPxvOffsetTable = offsetTable;
}
void PxvTerm()
{
#if PX_SUPPORT_GPU_PHYSX
if (gPxPhysXGpu)
{
gPxPhysXGpu->release();
gPxPhysXGpu = NULL;
}
#endif
}
}
#if PX_SUPPORT_GPU_PHYSX
namespace physx
{
//forward declare stuff from PxPhysXGpuModuleLoader.cpp
void PxLoadPhysxGPUModule(const char* appGUID);
typedef physx::PxPhysXGpu* (PxCreatePhysXGpu_FUNC)();
extern PxCreatePhysXGpu_FUNC* g_PxCreatePhysXGpu_Func;
PxPhysXGpu* PxvGetPhysXGpu(bool createIfNeeded)
{
if (!gPxPhysXGpu && createIfNeeded)
{
PxLoadPhysxGPUModule(NULL);
if (g_PxCreatePhysXGpu_Func)
{
gPxPhysXGpu = g_PxCreatePhysXGpu_Func();
}
}
return gPxPhysXGpu;
}
}
#endif
| 2,027 |
421 | <filename>samples/snippets/cpp/VS_Snippets_CLR_System/system.version.revision/cpp/rev.cpp
//<snippet1>
// This example demonstrates the Version.Revision,
// MajorRevision, and MinorRevision properties.
using namespace System;
int main()
{
String^ formatStandard = "Standard version:\n" +
" major.minor.build.revision = {0}.{1}.{2}.{3}";
String^ formatInterim = "Interim version:\n" +
" major.minor.build.majRev/minRev = {0}.{1}.{2}.{3}/{4}";
Version^ standardVersion = gcnew Version(2, 4, 1128, 2);
Version^ interimVersion = gcnew Version(2, 4, 1128, (100 << 16) + 2);
Console::WriteLine(formatStandard, standardVersion->Major,
standardVersion->Minor, standardVersion->Build,
standardVersion->Revision);
Console::WriteLine(formatInterim, interimVersion->Major,
interimVersion->Minor, interimVersion->Build,
interimVersion->MajorRevision, interimVersion->MinorRevision);
};
/*
This code example produces the following results:
Standard version:
major.minor.build.revision = 2.4.1128.2
Interim version:
major.minor.build.majRev/minRev = 2.4.1128.100/2
*/
//</snippet1>
| 459 |
3,084 | /*++
Copyright (c) 2005 Microsoft Corporation
All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
File Name:
xdsmplptprov.h
Abstract:
Definition of the PrintTicket provider plugin. This is responsible for
handling PrintTicket features that are too complex for the GPD->PrintTicket
automapping facility.
--*/
#pragma once
#include "cunknown.h"
#include "schema.h"
#include "ftrdmptcnv.h"
typedef vector<IFeatureDMPTConvert*> DMPTConvCollection;
class CXDSmplPTProvider : public CUnknown<IPrintOemPrintTicketProvider>
{
public:
CXDSmplPTProvider();
virtual ~CXDSmplPTProvider();
//
// IPrintOemPrintTicketProvider methods
//
virtual HRESULT STDMETHODCALLTYPE
GetSupportedVersions(
_In_ HANDLE hPrinter,
_Outptr_result_buffer_(*pcVersions) INT* ppVersions[],
_Out_ INT* pcVersions
);
virtual HRESULT STDMETHODCALLTYPE
BindPrinter(
_In_ HANDLE hPrinter,
INT version,
_Out_ POEMPTOPTS pOptions,
_Out_ INT* pcNamespaces,
_Outptr_result_buffer_maybenull_(*pcNamespaces) BSTR** ppNamespaces
);
virtual HRESULT STDMETHODCALLTYPE
PublishPrintTicketHelperInterface(
_In_ IUnknown* pHelper
);
virtual HRESULT STDMETHODCALLTYPE
QueryDeviceDefaultNamespace(
_Out_ BSTR* pbstrNamespaceUri
);
virtual HRESULT STDMETHODCALLTYPE
ConvertPrintTicketToDevMode(
_In_ IXMLDOMDocument2* pPrintTicket,
ULONG cbDevmode,
_Inout_updates_bytes_(cbDevmode)
PDEVMODE pDevmode,
ULONG cbDrvPrivateSize,
_Inout_ PVOID pPrivateDevmode
);
virtual HRESULT STDMETHODCALLTYPE
ConvertDevModeToPrintTicket(
ULONG cbDevmode,
_Inout_updates_bytes_(cbDevmode)
PDEVMODE pDevmode,
ULONG cbDrvPrivateSize,
_Inout_ PVOID pPrivateDevmode,
_Inout_ IXMLDOMDocument2* pPrintTicket
);
virtual HRESULT STDMETHODCALLTYPE
CompletePrintCapabilities(
_In_opt_ IXMLDOMDocument2* pPrintTicket,
_Inout_ IXMLDOMDocument2* pCapabilities
);
virtual HRESULT STDMETHODCALLTYPE
ExpandIntentOptions(
_Inout_ IXMLDOMDocument2* pPrintTicket
);
virtual HRESULT STDMETHODCALLTYPE
ValidatePrintTicket(
_Inout_ IXMLDOMDocument2* pPrintTicket
);
private:
HRESULT
DeleteConverters(
VOID
);
HRESULT
AddConverter(
_In_opt_ __drv_aliasesMem IFeatureDMPTConvert* pHandler
);
private:
HANDLE m_hPrinterCached;
CComPtr<IPrintCoreHelperUni> m_pCoreHelper;
DMPTConvCollection m_vectFtrDMPTConverters;
CComBSTR m_bstrPrivateNS;
};
| 1,817 |
537 | <reponame>amanya/suro<filename>suro-elasticsearch/src/main/java/com/netflix/suro/sink/elasticsearch/TimestampField.java
package com.netflix.suro.sink.elasticsearch;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Strings;
import org.joda.time.*;
import org.joda.time.field.DividedDateTimeField;
import org.joda.time.field.OffsetDateTimeField;
import org.joda.time.field.ScaledDurationField;
import org.joda.time.format.*;
import java.util.Locale;
import java.util.Map;
public class TimestampField {
private final String fieldName;
private final FormatDateTimeFormatter formatter;
@JsonCreator
public TimestampField(@JsonProperty("field") String fieldName, @JsonProperty("format") String format) {
if (format == null) {
format = "dateOptionalTime";
}
this.fieldName = fieldName;
this.formatter = Joda.forPattern(format);
}
public long get(Map<String, Object> msg) {
Object value = msg.get(fieldName);
if (value instanceof Number) {
return ((Number) value).longValue();
}
return formatter.parser().parseMillis(value.toString());
}
public static class Joda {
public static FormatDateTimeFormatter forPattern(String input) {
return forPattern(input, Locale.ROOT);
}
/**
* Parses a joda based pattern, including some named ones (similar to the built in Joda ISO ones).
*/
public static FormatDateTimeFormatter forPattern(String input, Locale locale) {
if (!Strings.isNullOrEmpty(input)) {
input = input.trim();
}
if (input == null || input.length() == 0) {
throw new IllegalArgumentException("No date pattern provided");
}
DateTimeFormatter formatter;
if ("basicDate".equals(input) || "basic_date".equals(input)) {
formatter = ISODateTimeFormat.basicDate();
} else if ("basicDateTime".equals(input) || "basic_date_time".equals(input)) {
formatter = ISODateTimeFormat.basicDateTime();
} else if ("basicDateTimeNoMillis".equals(input) || "basic_date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicDateTimeNoMillis();
} else if ("basicOrdinalDate".equals(input) || "basic_ordinal_date".equals(input)) {
formatter = ISODateTimeFormat.basicOrdinalDate();
} else if ("basicOrdinalDateTime".equals(input) || "basic_ordinal_date_time".equals(input)) {
formatter = ISODateTimeFormat.basicOrdinalDateTime();
} else if ("basicOrdinalDateTimeNoMillis".equals(input) || "basic_ordinal_date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicOrdinalDateTimeNoMillis();
} else if ("basicTime".equals(input) || "basic_time".equals(input)) {
formatter = ISODateTimeFormat.basicTime();
} else if ("basicTimeNoMillis".equals(input) || "basic_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicTimeNoMillis();
} else if ("basicTTime".equals(input) || "basic_t_Time".equals(input)) {
formatter = ISODateTimeFormat.basicTTime();
} else if ("basicTTimeNoMillis".equals(input) || "basic_t_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicTTimeNoMillis();
} else if ("basicWeekDate".equals(input) || "basic_week_date".equals(input)) {
formatter = ISODateTimeFormat.basicWeekDate();
} else if ("basicWeekDateTime".equals(input) || "basic_week_date_time".equals(input)) {
formatter = ISODateTimeFormat.basicWeekDateTime();
} else if ("basicWeekDateTimeNoMillis".equals(input) || "basic_week_date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicWeekDateTimeNoMillis();
} else if ("date".equals(input)) {
formatter = ISODateTimeFormat.date();
} else if ("dateHour".equals(input) || "date_hour".equals(input)) {
formatter = ISODateTimeFormat.dateHour();
} else if ("dateHourMinute".equals(input) || "date_hour_minute".equals(input)) {
formatter = ISODateTimeFormat.dateHourMinute();
} else if ("dateHourMinuteSecond".equals(input) || "date_hour_minute_second".equals(input)) {
formatter = ISODateTimeFormat.dateHourMinuteSecond();
} else if ("dateHourMinuteSecondFraction".equals(input) || "date_hour_minute_second_fraction".equals(input)) {
formatter = ISODateTimeFormat.dateHourMinuteSecondFraction();
} else if ("dateHourMinuteSecondMillis".equals(input) || "date_hour_minute_second_millis".equals(input)) {
formatter = ISODateTimeFormat.dateHourMinuteSecondMillis();
} else if ("dateOptionalTime".equals(input) || "date_optional_time".equals(input)) {
// in this case, we have a separate parser and printer since the dataOptionalTimeParser can't print
// this sucks we should use the root local by default and not be dependent on the node
return new FormatDateTimeFormatter(input,
ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC),
ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC), locale);
} else if ("dateTime".equals(input) || "date_time".equals(input)) {
formatter = ISODateTimeFormat.dateTime();
} else if ("dateTimeNoMillis".equals(input) || "date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.dateTimeNoMillis();
} else if ("hour".equals(input)) {
formatter = ISODateTimeFormat.hour();
} else if ("hourMinute".equals(input) || "hour_minute".equals(input)) {
formatter = ISODateTimeFormat.hourMinute();
} else if ("hourMinuteSecond".equals(input) || "hour_minute_second".equals(input)) {
formatter = ISODateTimeFormat.hourMinuteSecond();
} else if ("hourMinuteSecondFraction".equals(input) || "hour_minute_second_fraction".equals(input)) {
formatter = ISODateTimeFormat.hourMinuteSecondFraction();
} else if ("hourMinuteSecondMillis".equals(input) || "hour_minute_second_millis".equals(input)) {
formatter = ISODateTimeFormat.hourMinuteSecondMillis();
} else if ("ordinalDate".equals(input) || "ordinal_date".equals(input)) {
formatter = ISODateTimeFormat.ordinalDate();
} else if ("ordinalDateTime".equals(input) || "ordinal_date_time".equals(input)) {
formatter = ISODateTimeFormat.ordinalDateTime();
} else if ("ordinalDateTimeNoMillis".equals(input) || "ordinal_date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.ordinalDateTimeNoMillis();
} else if ("time".equals(input)) {
formatter = ISODateTimeFormat.time();
} else if ("tTime".equals(input) || "t_time".equals(input)) {
formatter = ISODateTimeFormat.tTime();
} else if ("tTimeNoMillis".equals(input) || "t_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.tTimeNoMillis();
} else if ("weekDate".equals(input) || "week_date".equals(input)) {
formatter = ISODateTimeFormat.weekDate();
} else if ("weekDateTime".equals(input) || "week_date_time".equals(input)) {
formatter = ISODateTimeFormat.weekDateTime();
} else if ("weekyear".equals(input) || "week_year".equals(input)) {
formatter = ISODateTimeFormat.weekyear();
} else if ("weekyearWeek".equals(input)) {
formatter = ISODateTimeFormat.weekyearWeek();
} else if ("year".equals(input)) {
formatter = ISODateTimeFormat.year();
} else if ("yearMonth".equals(input) || "year_month".equals(input)) {
formatter = ISODateTimeFormat.yearMonth();
} else if ("yearMonthDay".equals(input) || "year_month_day".equals(input)) {
formatter = ISODateTimeFormat.yearMonthDay();
} else if (!Strings.isNullOrEmpty(input) && input.contains("||")) {
String[] formats = input.split("\\|\\|");
DateTimeParser[] parsers = new DateTimeParser[formats.length];
if (formats.length == 1) {
formatter = forPattern(input, locale).parser();
} else {
DateTimeFormatter dateTimeFormatter = null;
for (int i = 0; i < formats.length; i++) {
FormatDateTimeFormatter currentFormatter = forPattern(formats[i], locale);
DateTimeFormatter currentParser = currentFormatter.parser();
if (dateTimeFormatter == null) {
dateTimeFormatter = currentFormatter.printer();
}
parsers[i] = currentParser.getParser();
}
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder().append(dateTimeFormatter.withZone(DateTimeZone.UTC).getPrinter(), parsers);
formatter = builder.toFormatter();
}
} else {
try {
formatter = DateTimeFormat.forPattern(input);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid format: [" + input + "]: " + e.getMessage(), e);
}
}
return new FormatDateTimeFormatter(input, formatter.withZone(DateTimeZone.UTC), locale);
}
public static final DurationFieldType Quarters = new DurationFieldType("quarters") {
private static final long serialVersionUID = -8167713675442491871L;
public DurationField getField(Chronology chronology) {
return new ScaledDurationField(chronology.months(), Quarters, 3);
}
};
public static final DateTimeFieldType QuarterOfYear = new DateTimeFieldType("quarterOfYear") {
private static final long serialVersionUID = -5677872459807379123L;
public DurationFieldType getDurationType() {
return Quarters;
}
public DurationFieldType getRangeDurationType() {
return DurationFieldType.years();
}
public DateTimeField getField(Chronology chronology) {
return new OffsetDateTimeField(new DividedDateTimeField(new OffsetDateTimeField(chronology.monthOfYear(), -1), QuarterOfYear, 3), 1);
}
};
}
public static class FormatDateTimeFormatter {
private final String format;
private final DateTimeFormatter parser;
private final DateTimeFormatter printer;
private final Locale locale;
public FormatDateTimeFormatter(String format, DateTimeFormatter parser, Locale locale) {
this(format, parser, parser, locale);
}
public FormatDateTimeFormatter(String format, DateTimeFormatter parser, DateTimeFormatter printer, Locale locale) {
this.format = format;
this.locale = locale;
this.printer = locale == null ? printer.withDefaultYear(1970) : printer.withLocale(locale).withDefaultYear(1970);
this.parser = locale == null ? parser.withDefaultYear(1970) : parser.withLocale(locale).withDefaultYear(1970);
}
public String format() {
return format;
}
public DateTimeFormatter parser() {
return parser;
}
public DateTimeFormatter printer() {
return this.printer;
}
public Locale locale() {
return locale;
}
}
}
| 5,349 |
775 | from __future__ import annotations
import typing
from abc import abstractmethod
if typing.TYPE_CHECKING:
from pandasgui.gui import PandasGui
from pandasgui.widgets.filter_viewer import FilterViewer
from pandasgui.widgets.dataframe_viewer import DataFrameViewer
from pandasgui.widgets.dataframe_explorer import DataFrameExplorer
from pandasgui.widgets.navigator import Navigator
from dataclasses import dataclass, field
from typing import Iterable, List, Union
from typing_extensions import Literal
import pandas as pd
from pandas import DataFrame
from PyQt5 import QtCore, QtWidgets
import traceback
from datetime import datetime
from pandasgui.utility import unique_name, in_interactive_console, refactor_variable, clean_dataframe, nunique, \
parse_cell, parse_all_dates, parse_date, get_movements
from pandasgui.constants import LOCAL_DATA_DIR
import os
from enum import Enum
import json
import inspect
import logging
import contextlib
logger = logging.getLogger(__name__)
# JSON file that stores persistent user preferences
preferences_path = os.path.join(LOCAL_DATA_DIR, 'preferences.json')
def read_saved_settings():
if not os.path.exists(preferences_path):
write_saved_settings({})
return {}
else:
try:
with open(preferences_path, 'r') as f:
saved_settings = json.load(f)
return saved_settings
except Exception as e:
logger.warning("Error occurred reading preferences. Resetting to defaults\n" + traceback.format_exc())
write_saved_settings({})
return {}
def write_saved_settings(settings):
with open(preferences_path, 'w') as f:
json.dump(settings, f)
class DictLike:
def __getitem__(self, key):
return getattr(self, key)
def __setitem__(self, key, value):
setattr(self, key, value)
class Setting(DictLike):
def __init__(self, label, value, description, dtype, persist):
self.label: str = label
self.value: any = value
self.description: str = description
self.dtype: Union[type(str), type(bool), Enum] = dtype
self.persist: bool = persist
def __setattr__(self, key, value):
try:
if self.persist:
settings = read_saved_settings()
settings[self.label] = value
write_saved_settings(settings)
except AttributeError:
# Get attribute error because of __setattr__ happening in __init__ before self.persist is set
pass
super().__setattr__(key, value)
DEFAULT_SETTINGS = {'editable': True,
'block': None,
'theme': 'light',
'auto_finish': True,
'refresh_statistics': True,
'render_mode': 'auto',
'aggregation': 'mean',
'title_format': "{name}: {title_columns}{title_dimensions}{names}{title_y}{title_z}{over_by}"
"{title_x} {selection}<br><sub>{groupings}{filters} {title_trendline}</sub>"
}
@dataclass
class SettingsStore(DictLike, QtCore.QObject):
settingsChanged = QtCore.pyqtSignal()
block: Setting
editable: Setting
theme: Setting
auto_finish: Setting
render_mode: Setting
aggregation: Setting
title_format: Setting
def __init__(self, **settings):
super().__init__()
saved_settings = read_saved_settings()
for setting_name in DEFAULT_SETTINGS.keys():
# Fill settings values if not provided
if setting_name not in settings.keys():
if setting_name in saved_settings.keys():
settings[setting_name] = saved_settings[setting_name]
else:
settings[setting_name] = DEFAULT_SETTINGS[setting_name]
if in_interactive_console():
# Don't block if in an interactive console (so you can view GUI and still continue running commands)
settings['block'] = False
else:
# If in a script, block or else the script will continue and finish without allowing GUI interaction
settings['block'] = True
self.block = Setting(label="block",
value=settings['block'],
description="Should GUI block code execution until closed?",
dtype=bool,
persist=False)
self.editable = Setting(label="editable",
value=settings['editable'],
description="Are table cells editable?",
dtype=bool,
persist=True)
self.theme = Setting(label="theme",
value=settings['theme'],
description="UI theme",
dtype=Literal['light', 'dark', 'classic'],
persist=True)
self.refresh_statistics = Setting(label="refresh_statistics",
value=settings['refresh_statistics'],
description="Recalculate statistics when data changes",
dtype=bool,
persist=True)
# Settings related to Grapher
self.auto_finish = Setting(label="auto_finish",
value=settings['auto_finish'],
description="Automatically renders plot after each drag and drop",
dtype=bool,
persist=True)
self.render_mode = Setting(label="render_mode",
value=settings['render_mode'],
description="render_mode",
dtype=Literal['auto', 'webgl', 'svg'],
persist=True)
self.aggregation = Setting(label="aggregation",
value=settings['aggregation'],
description="aggregation",
dtype=Literal['mean', 'median', 'min', 'max', 'sum', None],
persist=True)
self.title_format = Setting(label="title_format",
value=settings['title_format'],
description="title_format",
dtype=dict,
persist=True)
def reset_to_defaults(self):
for setting_name, setting_value in DEFAULT_SETTINGS.items():
self[setting_name].value = setting_value
def __repr__(self):
return '\n'.join([f"{key} = {val.value}" for key, val in self.__dict__.items()])
@dataclass
class Filter:
expr: str
enabled: bool
failed: bool
@dataclass
class HistoryItem:
comment: str
code: str
time: str
def __init__(self, comment, code):
self.comment = comment
self.code = code
self.time = datetime.now().strftime("%H:%M:%S")
# Use this decorator on PandasGuiStore or PandasGuiDataFrameStore to display a status bar message during a method run
def status_message_decorator(message):
def decorator(function):
def status_message_wrapper(self, *args, **kwargs):
if not (issubclass(type(self), PandasGuiStore) or issubclass(type(self), PandasGuiDataFrameStore)):
raise ValueError
full_kwargs = kwargs.copy()
# Allow putting method argument values in the status message by putting them in curly braces
args_spec = inspect.getfullargspec(function).args
args_spec.pop(0) # Removes self
for ix, arg_name in enumerate(args_spec):
# Need to check length because if the param has default value it may be in args_spec but not args
if ix < len(args):
full_kwargs[arg_name] = args[ix]
new_message = message
for arg_name in full_kwargs.keys():
new_message = new_message.replace('{' + arg_name + '}', str(full_kwargs[arg_name]))
if self.gui is not None:
original_status = self.gui.statusBar().currentMessage()
self.gui.statusBar().showMessage(new_message)
self.gui.statusBar().repaint()
QtWidgets.QApplication.instance().processEvents()
try:
result = function(self, *args, **kwargs)
finally:
self.gui.statusBar().showMessage(original_status)
self.gui.statusBar().repaint()
QtWidgets.QApplication.instance().processEvents()
else:
result = function(self, *args, **kwargs)
return result
return status_message_wrapper
return decorator
# Objects to display in the PandasGuiStore must inherit this class
class PandasGuiStoreItem:
def __init__(self):
self.name = None
@abstractmethod
def pg_widget(self):
raise NotImplementedError
class PandasGuiDataFrameStore(PandasGuiStoreItem):
"""
All methods that modify the data should modify self.df_unfiltered, then self.df gets computed from that
"""
def __init__(self, df: DataFrame, name: str = 'Untitled'):
super().__init__()
df = df.copy()
self.df: DataFrame = df
self.df_unfiltered: DataFrame = df
self.name = name
self.history: List[HistoryItem] = []
self.history_imports = {"import pandas as pd"}
# References to other object instances that may be assigned later
self.settings: SettingsStore = SETTINGS_STORE
self.store: Union[PandasGuiStore, None] = None
self.gui: Union[PandasGui, None] = None
self.dataframe_explorer: DataFrameExplorer = None
self.dataframe_viewer: Union[DataFrameViewer, None] = None
self.stats_viewer: Union[DataFrameViewer, None] = None
self.filter_viewer: Union[FilterViewer, None] = None
self.sorted_column_name: Union[str, None] = None
self.sorted_index_level: Union[int, None] = None
self.sort_state: Literal['Asc', 'Desc', 'None'] = 'None'
self.filters: List[Filter] = []
self.filtered_index_map = df.reset_index().index
# Statistics
self.column_statistics = None
self.row_statistics = None
self.statistics_outdated = True
self.data_changed()
@property
def sorted_column_ix(self):
try:
return list(self.df_unfiltered.columns).index(self.sorted_column_name)
except ValueError:
return None
def __setattr__(self, name, value):
if name == 'df':
value.pgdf = self
super().__setattr__(name, value)
def pg_widget(self):
return self.dataframe_explorer
@status_message_decorator("Refreshing statistics...")
def refresh_statistics(self, force=False):
if force or self.settings.refresh_statistics.value:
df = self.df
self.column_statistics = pd.DataFrame({
"Type": df.dtypes.astype(str),
"Count": df.count(),
"N Unique": nunique(df),
"Mean": df.mean(numeric_only=True),
"StdDev": df.std(numeric_only=True),
"Min": df.min(numeric_only=True),
"Max": df.max(numeric_only=True),
}, index=df.columns
)
df = self.df.transpose()
df_numeric = self.df.select_dtypes('number').transpose()
self.row_statistics = pd.DataFrame({
# "Type": df.dtypes.astype(str),
# "Count": df.count(),
# "N Unique": nunique(df),
# "Mean": df_numeric.mean(numeric_only=True),
# "StdDev": df_numeric.std(numeric_only=True),
# "Min": df_numeric.min(numeric_only=True),
"Max": df_numeric.max(numeric_only=True),
}, index=df.columns
)
if self.dataframe_explorer is not None:
self.dataframe_explorer.statistics_viewer.refresh_statistics()
###################################
# Code history
@status_message_decorator("Generating code export...")
def code_export(self):
if len(self.history) == 0 and not any([filt.enabled for filt in self.filters]):
return f"# No actions have been recorded yet on this DataFrame ({self.name})"
code_history = "# 'df' refers to the DataFrame passed into 'pandasgui.show'\n\n"
# Add imports to setup
code_history += '\n'.join(self.history_imports) + '\n\n'
for history_item in self.history:
code_history += f'# {history_item.comment}\n'
code_history += history_item.code
code_history += "\n\n"
if any([filt.enabled for filt in self.filters]):
code_history += f"# Filters\n"
for filt in self.filters:
if filt.enabled:
code_history += f"df = df.query('{filt.expr}')\n"
return code_history
def add_history_item(self, comment, code):
history_item = HistoryItem(comment, code)
self.history.append(history_item)
if self.gui is not None:
self.gui.update_code_export()
###################################
# Editing cell data
@status_message_decorator("Applying cell edit...")
def edit_data(self, row, col, text):
column_dtype = self.df.dtypes[col].type
# type should always be str when being called from PyQt GUI but someone might call this directly
if type(text) == str:
value = parse_cell(text, column_dtype)
# Map the row number in the filtered df (which the user interacts with) to the unfiltered one
row = self.filtered_index_map[row]
old_val = self.df_unfiltered.iat[row, col]
if old_val != value and not (pd.isna(old_val) and pd.isna(value)):
self.df_unfiltered.iat[row, col] = value
self.apply_filters()
self.add_history_item("edit_data",
f"df.iat[{row}, {col}] = {repr(value)}")
@status_message_decorator("Pasting data...")
def paste_data(self, top_row, left_col, df_to_paste):
new_df = self.df_unfiltered.copy()
# Not using iat here because it won't work with MultiIndex
for i in range(df_to_paste.shape[0]):
for j in range(df_to_paste.shape[1]):
value = df_to_paste.iloc[i, j]
new_df.at[self.df.index[top_row + i],
self.df.columns[left_col + j]] = value
self.df_unfiltered = new_df
self.apply_filters()
self.add_history_item("paste_data", inspect.cleandoc(
f"""
df_to_paste = pd.DataFrame({df_to_paste.to_dict(orient='list')})
for i in range(df_to_paste.shape[0]):
for j in range(df_to_paste.shape[1]):
value = df_to_paste.iloc[i, j]
df.at[df.index[{top_row} + i],
df.columns[{left_col} + j]] = value
"""))
###################################
# Changing columns
@status_message_decorator("Deleting column...")
def delete_column(self, ix: int):
col_name = self.df_unfiltered.columns[ix]
self.df_unfiltered = self.df_unfiltered.drop(col_name, axis=1)
# Need to inform the PyQt model too so column widths properly shift
self.dataframe_viewer._remove_column(ix)
self.add_history_item("delete_column",
f"df = df.drop('{col_name}', axis=1)")
self.apply_filters()
@status_message_decorator("Moving columns...")
def move_column(self, src: int, dest: int):
cols = list(self.df_unfiltered.columns)
cols.insert(dest, cols.pop(src))
self.df_unfiltered = self.df_unfiltered.reindex(cols, axis=1)
self.add_history_item("move_column",
(f"cols = list(df.columns)"
f"cols.insert({dest}, cols.pop({src}))"
f"df = df.reindex(cols, axis=1)"))
self.dataframe_viewer.setUpdatesEnabled(False)
# Need to inform the PyQt model too so column widths properly shift
self.dataframe_viewer._move_column(src, dest)
self.apply_filters()
self.dataframe_viewer.setUpdatesEnabled(True)
@status_message_decorator("Reordering columns...")
def reorder_columns(self, columns: List[str]):
if sorted(list(columns)) != sorted(list(self.df_unfiltered.columns)):
raise ValueError("Provided column names do not match DataFrame")
original_columns = list(self.df_unfiltered.columns)
self.df_unfiltered = self.df_unfiltered.reindex(columns=columns)
self.dataframe_viewer.setUpdatesEnabled(False)
# Move columns around in TableView to maintain column widths
for (src, dest) in get_movements(original_columns, columns):
self.dataframe_viewer._move_column(src, dest, refresh=False)
self.apply_filters()
self.dataframe_viewer.setUpdatesEnabled(True)
self.add_history_item("reorder_columns",
f"df = df.reindex(columns={columns})")
###################################
# Sorting
@status_message_decorator("Sorting column...")
def sort_column(self, ix: int, next_sort_state: Literal['Asc', 'Desc', 'None'] = None):
col_name = self.df_unfiltered.columns[ix]
# Determine next sorting state by current state
if next_sort_state is None:
# Clicked an unsorted column
if ix != self.sorted_column_ix:
next_sort_state = 'Asc'
# Clicked a sorted column
elif ix == self.sorted_column_ix and self.sort_state == 'Asc':
next_sort_state = 'Desc'
# Clicked a reverse sorted column - reset to sorted by index
elif ix == self.sorted_column_ix:
next_sort_state = 'None'
if next_sort_state == 'Asc':
self.df_unfiltered = self.df_unfiltered.sort_values(col_name, ascending=True, kind='mergesort')
self.sorted_column_name = self.df_unfiltered.columns[ix]
self.sort_state = 'Asc'
self.add_history_item("sort_column",
f"df = df.sort_values('{self.df_unfiltered.columns[ix]}', ascending=True, kind='mergesort')")
elif next_sort_state == 'Desc':
self.df_unfiltered = self.df_unfiltered.sort_values(col_name, ascending=False, kind='mergesort')
self.sorted_column_name = self.df_unfiltered.columns[ix]
self.sort_state = 'Desc'
self.add_history_item("sort_column",
f"df = df.sort_values('{self.df_unfiltered.columns[ix]}', ascending=False, kind='mergesort')")
elif next_sort_state == 'None':
self.df_unfiltered = self.df_unfiltered.sort_index(ascending=True, kind='mergesort')
self.sorted_column_name = None
self.sort_state = 'None'
self.add_history_item("sort_column",
"df = df.sort_index(ascending=True, kind='mergesort')")
self.sorted_index_level = None
self.apply_filters()
@status_message_decorator("Sorting index...")
def sort_index(self, ix: int):
# Clicked an unsorted index level
if ix != self.sorted_index_level:
self.df_unfiltered = self.df_unfiltered.sort_index(level=ix, ascending=True, kind='mergesort')
self.sorted_index_level = ix
self.sort_state = 'Asc'
self.add_history_item("sort_index",
f"df = df.sort_index(level={ix}, ascending=True, kind='mergesort')")
# Clicked a sorted index level
elif ix == self.sorted_index_level and self.sort_state == 'Asc':
self.df_unfiltered = self.df_unfiltered.sort_index(level=ix, ascending=False, kind='mergesort')
self.sorted_index_level = ix
self.sort_state = 'Desc'
self.add_history_item("sort_index",
f"df = df.sort_index(level={ix}, ascending=False, kind='mergesort')")
# Clicked a reverse sorted index level - reset to sorted by full index
elif ix == self.sorted_index_level:
self.df_unfiltered = self.df_unfiltered.sort_index(ascending=True, kind='mergesort')
self.sorted_index_level = None
self.sort_state = 'None'
self.add_history_item("sort_index",
"df = df.sort_index(ascending=True, kind='mergesort')")
self.sorted_column = None
self.apply_filters()
def change_column_type(self, ix: int, type):
name = self.df_unfiltered.columns[ix]
self.df_unfiltered[name] = self.df_unfiltered[name].astype(type)
self.apply_filters()
self.add_history_item("change_column_type",
f"df[{name}] = df[{name}].astype({type})")
###################################
# Filters
def any_filtered(self):
return any(filt.enabled for filt in self.filters)
def add_filter(self, expr: str, enabled=True):
filt = Filter(expr=expr, enabled=enabled, failed=False)
self.filters.append(filt)
self.apply_filters()
def remove_filter(self, index: int):
self.filters.pop(index)
self.apply_filters()
def edit_filter(self, index: int, expr: str):
filt = self.filters[index]
filt.expr = expr
filt.failed = False
self.apply_filters()
def toggle_filter(self, index: int):
self.filters[index].enabled = not self.filters[index].enabled
self.apply_filters()
@status_message_decorator("Applying filters...")
def apply_filters(self):
df = self.df_unfiltered.copy()
df['_temp_range_index'] = df.reset_index().index
for ix, filt in enumerate(self.filters):
if filt.enabled and not filt.failed:
try:
df = df.query(filt.expr)
# Handle case where filter returns only one row
if isinstance(df, pd.Series):
df = df.to_frame().T
except Exception as e:
self.filters[ix].failed = True
logger.exception(e)
# self.filtered_index_map is used elsewhere to map unfiltered index to filtered index
self.filtered_index_map = df['_temp_range_index'].reset_index(drop=True)
df = df.drop('_temp_range_index', axis=1)
self.df = df
self.data_changed()
# Convert all columns to datetime where possible
def parse_all_dates(self):
df = self.df_unfiltered
converted_names = []
dtypes_old = df.dtypes
df = parse_all_dates(df)
dtypes_new = df.dtypes
for ix in range(len(dtypes_new)):
col_name = df.columns[ix]
# Pandas is sometimes buggy when comparing dtypes
try:
if dtypes_old[ix] != dtypes_new[ix]:
converted_names.append(str(col_name))
except:
pass
if converted_names:
logger.info(f"In {self.name}, converted columns to datetime: {', '.join(converted_names)}")
else:
logger.warning(f"In {self.name}, unable to parse any columns as datetime")
self.df_unfiltered = df
self.apply_filters()
# Convert a single column to date
def parse_date(self, ix):
df = self.df_unfiltered
name = list(df.columns)[ix]
dtype_old = df[name].dtype
df[name] = parse_date(df[name])
dtype_new = df[name].dtype
if dtype_old != dtype_new:
logger.info(f"In {self.name}, converted {name} to datetime")
else:
logger.warning(f"In {self.name}, unable to convert {name} to datetime")
self.df_unfiltered = df
self.apply_filters()
###################################
# Other
def data_changed(self):
self.refresh_ui()
self.refresh_statistics()
# Remake Grapher plot
if self.dataframe_explorer is not None:
self.dataframe_explorer.grapher.on_dragger_finished()
# Refresh PyQt models when the underlying pgdf is changed in anyway that needs to be reflected in the GUI
def refresh_ui(self):
self.models = []
if self.filter_viewer is not None:
self.models += [self.filter_viewer.list_model]
for model in self.models:
model.beginResetModel()
model.endResetModel()
if self.dataframe_viewer is not None:
self.dataframe_viewer.refresh_ui()
@staticmethod
def cast(df: Union[PandasGuiDataFrameStore, pd.DataFrame, pd.Series, Iterable]):
if isinstance(df, PandasGuiDataFrameStore):
return df
if isinstance(df, pd.DataFrame):
return PandasGuiDataFrameStore(df.copy())
elif isinstance(df, pd.Series):
return PandasGuiDataFrameStore(df.to_frame())
else:
try:
return PandasGuiDataFrameStore(pd.DataFrame(df))
except:
raise TypeError(f"Could not convert {type(df)} to DataFrame")
@dataclass
class PandasGuiStore:
"""This class stores all state data of the PandasGUI main GUI.
Attributes:
settings Settings as defined in SettingsStore
data A dict of PandasGuiDataFrameStore instances which wrap DataFrames. These show up in left nav
data A dict of other widgets that can show up in the left nav such as JsonViewer and FigureViewer
gui A reference to the PandasGui widget instance
navigator A reference to the Navigator widget instance
selected_pgdf The PandasGuiDataFrameStore currently selected in the nav
"""
settings: Union[SettingsStore, None] = None
data: typing.OrderedDict[str, Union[PandasGuiStoreItem, PandasGuiDataFrameStore]] = field(default_factory=dict)
gui: Union[PandasGui, None] = None
navigator: Union[Navigator, None] = None
selected_pgdf: Union[PandasGuiDataFrameStore, None] = None
def __post_init__(self):
self.settings = SETTINGS_STORE
###################################
# IPython magic
@status_message_decorator("Executing IPython command...")
def eval_magic(self, line):
dataframes_affected = []
command = line
for name in self.data.keys():
command = refactor_variable(command, name, f"self.data['{name}'].df_unfiltered")
if name in command:
dataframes_affected.append(name)
exec(command)
for name in dataframes_affected:
self.data[name].apply_filters()
self.data[name].add_history_item("iPython magic",
refactor_variable(line, name, 'df'))
return line
###################################
# Use this context to display a status message for a block. self should be a PandasGuiStore or PandasGuiDataFrameStore
@contextlib.contextmanager
def status_message_context(self, message):
if self.gui is not None:
original_status = self.gui.statusBar().currentMessage()
self.gui.statusBar().showMessage(message)
self.gui.statusBar().repaint()
QtWidgets.QApplication.instance().processEvents()
try:
yield
finally:
self.gui.statusBar().showMessage(original_status)
self.gui.statusBar().repaint()
QtWidgets.QApplication.instance().processEvents()
###################################
def add_item(self, item: PandasGuiStoreItem,
name: str = "Untitled", shape: str = ""):
# Add it to store and create widgets
self.data[name] = item
self.gui.stacked_widget.addWidget(item.pg_widget())
# Add to nav
nav_item = QtWidgets.QTreeWidgetItem(self.navigator, [name, shape])
self.navigator.itemSelectionChanged.emit()
self.navigator.setCurrentItem(nav_item)
self.navigator.apply_tree_settings()
def remove_item(self, name_or_index):
if type(name_or_index) == int:
ix = name_or_index
name = list(self.data.keys())[ix]
elif type(name_or_index) == str:
name = name_or_index
else:
raise ValueError
item = self.data[name]
if isinstance(item, PandasGuiDataFrameStore):
widget = item.dataframe_explorer
else:
widget = item
self.data.pop(name)
self.gui.navigator.remove_item(name)
self.gui.stacked_widget.removeWidget(widget)
@status_message_decorator("Adding DataFrame...")
def add_dataframe(self, pgdf: Union[DataFrame, PandasGuiDataFrameStore],
name: str = "Untitled"):
name = unique_name(name, self.get_dataframes().keys())
with self.status_message_context("Adding DataFrame (Creating DataFrame store)..."):
pgdf = PandasGuiDataFrameStore.cast(pgdf)
pgdf.settings = self.settings
pgdf.name = name
pgdf.store = self
pgdf.gui = self.gui
with self.status_message_context("Cleaning DataFrame..."):
pgdf.df = clean_dataframe(pgdf.df, name)
pgdf.data_changed()
if pgdf.dataframe_explorer is None:
from pandasgui.widgets.dataframe_explorer import DataFrameExplorer
pgdf.dataframe_explorer = DataFrameExplorer(pgdf)
# Add to nav
shape = pgdf.df.shape
shape = f"{shape[0]:,} x {shape[1]:,}"
self.add_item(pgdf, name, shape)
def remove_dataframe(self, name_or_index):
self.remove_item(name_or_index)
@status_message_decorator('Importing file "{path}"...')
def import_file(self, path):
if not os.path.isfile(path):
logger.warning("Path is not a file: " + path)
elif path.endswith(".csv"):
filename = os.path.split(path)[1].split('.csv')[0]
df = pd.read_csv(path, engine='python')
self.add_dataframe(df, filename)
elif path.endswith(".xlsx"):
filename = os.path.split(path)[1].split('.csv')[0]
df_dict = pd.read_excel(path, sheet_name=None)
for sheet_name in df_dict.keys():
df_name = f"{filename} - {sheet_name}"
self.add_dataframe(df_dict[sheet_name], df_name)
elif path.endswith(".parquet"):
filename = os.path.split(path)[1].split('.parquet')[0]
df = pd.read_parquet(path, engine='pyarrow')
self.add_dataframe(df, filename)
elif path.endswith(".json"):
filename = os.path.split(path)[1].split('.json')[0]
with open(path) as f:
data = json.load(f)
from pandasgui.widgets.json_viewer import JsonViewer
jv = JsonViewer(data)
self.add_item(jv, filename)
elif path.endswith(".pkl"):
filename = os.path.split(path)[1].split('.pkl')[0]
df = pd.read_pickle(path)
self.add_dataframe(df, filename)
else:
logger.warning("Can only import csv / xlsx / parquet. Invalid file: " + path)
def get_dataframes(self, names: Union[None, str, list, int] = None):
if type(names) == str:
return self.data[names].df
elif type(names) == int:
return self.data.items()[names]
df_dict = {}
for pgdf in [item for item in self.data.values() if isinstance(item, PandasGuiDataFrameStore)]:
if names is None or pgdf.name in names:
df_dict[pgdf.name] = pgdf.df
return df_dict
def select_pgdf(self, name):
pgdf = self.data[name]
self.gui.stacked_widget.setCurrentWidget(pgdf.pg_widget())
self.selected_pgdf = pgdf
def to_dict(self):
import json
return json.loads(json.dumps(self, default=lambda o: o.__dict__))
SETTINGS_STORE = SettingsStore()
| 15,377 |
26,879 | <reponame>ZacSweers/butterknife<filename>butterknife-lint/src/main/java/butterknife/lint/InvalidR2UsageDetector.java<gh_stars>1000+
package butterknife.lint;
import com.android.tools.lint.client.api.UElementHandler;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.LintUtils;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.jetbrains.uast.UAnnotation;
import org.jetbrains.uast.UClass;
import org.jetbrains.uast.UElement;
import org.jetbrains.uast.UExpression;
import org.jetbrains.uast.UFile;
import org.jetbrains.uast.UQualifiedReferenceExpression;
import org.jetbrains.uast.USimpleNameReferenceExpression;
import org.jetbrains.uast.visitor.AbstractUastVisitor;
/**
* Custom lint rule to make sure that generated R2 is not referenced outside annotations.
*/
public class InvalidR2UsageDetector extends Detector implements Detector.UastScanner {
private static final String LINT_ERROR_BODY = "R2 should only be used inside annotations";
private static final String LINT_ERROR_TITLE = "Invalid usage of R2";
private static final String ISSUE_ID = "InvalidR2Usage";
private static final Set<String> SUPPORTED_TYPES =
ImmutableSet.of("array", "attr", "bool", "color", "dimen", "drawable", "id", "integer",
"string");
static final Issue ISSUE =
Issue.create(ISSUE_ID, LINT_ERROR_TITLE, LINT_ERROR_BODY, Category.CORRECTNESS, 6,
Severity.ERROR, new Implementation(InvalidR2UsageDetector.class, Scope.JAVA_FILE_SCOPE));
private static final String R2 = "R2";
@Override public List<Class<? extends UElement>> getApplicableUastTypes() {
return Collections.singletonList(UClass.class);
}
@Override public UElementHandler createUastHandler(final JavaContext context) {
return new UElementHandler() {
@Override public void visitClass(UClass node) {
node.accept(new R2UsageVisitor(context));
}
};
}
private static class R2UsageVisitor extends AbstractUastVisitor {
private final JavaContext context;
R2UsageVisitor(JavaContext context) {
this.context = context;
}
@Override public boolean visitAnnotation(UAnnotation annotation) {
// skip annotations
return true;
}
@Override public boolean visitQualifiedReferenceExpression(UQualifiedReferenceExpression node) {
detectR2(context, node);
return super.visitQualifiedReferenceExpression(node);
}
@Override
public boolean visitSimpleNameReferenceExpression(USimpleNameReferenceExpression node) {
detectR2(context, node);
return super.visitSimpleNameReferenceExpression(node);
}
private static void detectR2(JavaContext context, UElement node) {
UFile sourceFile = context.getUastFile();
List<UClass> classes = sourceFile.getClasses();
if (!classes.isEmpty() && classes.get(0).getName() != null) {
String qualifiedName = classes.get(0).getName();
if (qualifiedName.contains("_ViewBinder")
|| qualifiedName.contains("_ViewBinding")
|| qualifiedName.equals(R2)) {
// skip generated files and R2
return;
}
}
boolean isR2 = isR2Expression(node);
if (isR2 && !context.isSuppressedWithComment(node, ISSUE)) {
context.report(ISSUE, node, context.getLocation(node), LINT_ERROR_BODY);
}
}
private static boolean isR2Expression(UElement node) {
UElement parentNode = node.getUastParent();
if (parentNode == null) {
return false;
}
String text = node.asSourceString();
UElement parent = LintUtils.skipParentheses(parentNode);
return (text.equals(R2) || text.contains(".R2"))
&& parent instanceof UExpression
&& endsWithAny(parent.asSourceString(), SUPPORTED_TYPES);
}
private static boolean endsWithAny(String text, Set<String> possibleValues) {
String[] tokens = text.split("\\.");
return tokens.length > 1 && possibleValues.contains(tokens[tokens.length - 1]);
}
}
}
| 1,594 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.java.api.common.queries;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ant.AntArtifact;
import org.netbeans.modules.java.api.common.impl.MultiModule;
import org.netbeans.modules.java.api.common.project.ProjectProperties;
import org.netbeans.spi.project.ant.AntArtifactProvider;
import org.netbeans.spi.project.support.ant.AntProjectHelper;
import org.netbeans.spi.project.support.ant.PropertyEvaluator;
import org.netbeans.spi.project.support.ant.PropertyUtils;
import org.openide.util.Parameters;
/**
*
* @author <NAME>
*/
final class MultiModuleAntArtifactProvider implements AntArtifactProvider {
private final AntProjectHelper helper;
private final PropertyEvaluator eval;
private final MultiModule srcModules;
private final String buildTarget;
private final String cleanTarget;
MultiModuleAntArtifactProvider(
@NonNull final AntProjectHelper helper,
@NonNull final PropertyEvaluator eval,
@NonNull final MultiModule model,
@NonNull final String buildTarget,
@NonNull final String cleanTarget) {
Parameters.notNull("helper", helper); //NOI18N
Parameters.notNull("eval", eval); //NOI18N
Parameters.notNull("model", model); //NOI18N
Parameters.notNull("buildTarget", buildTarget); //NOI18N
Parameters.notNull("cleanTarget", cleanTarget); //NOI18N
this.helper = helper;
this.eval = eval;
this.srcModules = model;
this.buildTarget = buildTarget;
this.cleanTarget = cleanTarget;
}
@Override
public AntArtifact[] getBuildArtifacts() {
final List<AntArtifact> artifacts = new ArrayList<>();
final EvaluatorPropertyProvider pp = new EvaluatorPropertyProvider(eval);
for (String modName : srcModules.getModuleNames()) {
final String moduleDistJarKey = String.format(
"module.%s.dist.jar", //NOI18N
modName);
final String moduleDistJarVal = String.format(
"${%s}/%s.jar", //NOI18N
ProjectProperties.DIST_DIR,
modName);
final PropertyEvaluator extEval = PropertyUtils.sequentialPropertyEvaluator(
null,
pp,
PropertyUtils.fixedPropertyProvider(Collections.singletonMap(
moduleDistJarKey,
moduleDistJarVal)));
final AntArtifact artifact = helper.createSimpleAntArtifact(
JavaProjectConstants.ARTIFACT_TYPE_JAR,
moduleDistJarKey,
extEval,
buildTarget,
cleanTarget,
ProjectProperties.BUILD_SCRIPT);
artifacts.add(new ModuleIdDecorator(modName, artifact));
}
return artifacts.toArray(new AntArtifact[artifacts.size()]);
}
private static final class ModuleIdDecorator extends AntArtifact {
private final String moduleName;
private final AntArtifact delegate;
ModuleIdDecorator(
String moduleName,
AntArtifact delegate) {
Parameters.notNull("moduleName", moduleName); //NOI18N
Parameters.notNull("delegate", delegate); //NOI18N
this.moduleName = moduleName;
this.delegate = delegate;
}
@Override
public String getType() {
return delegate.getType();
}
@Override
public File getScriptLocation() {
return delegate.getScriptLocation();
}
@Override
public String getTargetName() {
return delegate.getTargetName();
}
@Override
public String getCleanTargetName() {
return delegate.getCleanTargetName();
}
@Override
public URI[] getArtifactLocations() {
return delegate.getArtifactLocations();
}
@Override
public URI getArtifactLocation() {
return delegate.getArtifactLocation();
}
@Override
public Project getProject() {
return delegate.getProject();
}
@Override
public Properties getProperties() {
return delegate.getProperties();
}
@Override
public String getID() {
return String.format(
"%s.%s", //NOI18N
moduleName,
super.getID());
}
}
}
| 2,361 |
3,579 | <filename>querydsl-core/src/main/java/com/querydsl/core/group/AbstractGroupByTransformer.java<gh_stars>1000+
/*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* 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.querydsl.core.group;
import java.util.ArrayList;
import java.util.List;
import com.querydsl.core.ResultTransformer;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.*;
/**
* Base class for GroupBy result transformers
*
* @author tiwe
*
* @param <K>
* @param <T>
*/
public abstract class AbstractGroupByTransformer<K, T> implements ResultTransformer<T> {
private static final class FactoryExpressionAdapter<T> extends ExpressionBase<T> implements FactoryExpression<T> {
private final FactoryExpression<T> expr;
private final List<Expression<?>> args;
private FactoryExpressionAdapter(FactoryExpression<T> expr, List<Expression<?>> args) {
super(expr.getType());
this.expr = expr;
this.args = args;
}
@Override
public <R, C> R accept(Visitor<R, C> v, C context) {
return expr.accept(v, context);
}
@Override
public List<Expression<?>> getArgs() {
return args;
}
@Override
public T newInstance(Object... args) {
return expr.newInstance(args);
}
}
protected final List<GroupExpression<?, ?>> groupExpressions = new ArrayList<GroupExpression<?, ?>>();
protected final List<QPair<?,?>> maps = new ArrayList<QPair<?,?>>();
protected final Expression<?>[] expressions;
@SuppressWarnings("unchecked")
protected AbstractGroupByTransformer(Expression<K> key, Expression<?>... expressions) {
List<Expression<?>> projection = new ArrayList<Expression<?>>(expressions.length);
groupExpressions.add(new GOne<K>(key));
projection.add(key);
for (Expression<?> expr : expressions) {
if (expr instanceof GroupExpression<?,?>) {
GroupExpression<?,?> groupExpr = (GroupExpression<?,?>) expr;
groupExpressions.add(groupExpr);
Expression<?> colExpression = groupExpr.getExpression();
if (colExpression instanceof Operation && ((Operation) colExpression).getOperator() == Ops.ALIAS) {
projection.add(((Operation) colExpression).getArg(0));
} else {
projection.add(colExpression);
}
if (groupExpr instanceof GMap) {
maps.add((QPair<?, ?>) colExpression);
}
} else {
groupExpressions.add(new GOne(expr));
projection.add(expr);
}
}
this.expressions = projection.toArray(new Expression[0]);
}
protected static FactoryExpression<Tuple> withoutGroupExpressions(final FactoryExpression<Tuple> expr) {
List<Expression<?>> args = new ArrayList<Expression<?>>(expr.getArgs().size());
for (Expression<?> arg : expr.getArgs()) {
if (arg instanceof GroupExpression) {
args.add(((GroupExpression) arg).getExpression());
} else {
args.add(arg);
}
}
return new FactoryExpressionAdapter<Tuple>(expr, args);
}
}
| 1,555 |
382 | <gh_stars>100-1000
package com.netflix.spinnaker.clouddriver.orchestration;
/** Marker interface for inputs to an {@link AtomicOperation}. */
public interface OperationDescription {}
| 51 |
2,382 | <filename>tests/test_minimum_clearance.py
"""
Tests for the minimum clearance property.
"""
import math
import pytest
from shapely.wkt import loads as load_wkt
from shapely.geos import geos_version
requires_geos_36 = pytest.mark.skipif(geos_version < (3, 6, 0), reason="GEOS > 3.6.0 is required.")
@requires_geos_36
def test_point():
point = load_wkt("POINT (0 0)")
assert point.minimum_clearance == math.inf
@requires_geos_36
def test_linestring():
line = load_wkt('LINESTRING (0 0, 1 1, 2 2)')
assert round(line.minimum_clearance, 6) == 1.414214
@requires_geos_36
def test_simple_polygon():
poly = load_wkt('POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))')
assert poly.minimum_clearance == 1.0
@requires_geos_36
def test_more_complicated_polygon():
poly = load_wkt('POLYGON ((20 20, 34 124, 70 140, 130 130, 70 100, 110 70, 170 20, 90 10, 20 20))')
assert round(poly.minimum_clearance, 6) == 35.777088
| 369 |
1,125 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.mapper;
import org.elasticsearch.Version;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.test.ESSingleNodeTestCase;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
public class LegacyDynamicMappingTests extends ESSingleNodeTestCase {
@Override
protected boolean forbidPrivateIndexSettings() {
return false;
}
public void testMixTemplateMultiFieldMultiTypeAndMappingReuse() throws Exception {
IndexService indexService = createIndex("test", Settings.builder().put("index.version.created", Version.V_5_6_0).build());
XContentBuilder mappings1 = jsonBuilder().startObject()
.startObject("type1")
.startArray("dynamic_templates")
.startObject()
.startObject("template1")
.field("match_mapping_type", "string")
.startObject("mapping")
.field("type", "text")
.startObject("fields")
.startObject("raw")
.field("type", "keyword")
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.endArray()
.endObject().endObject();
indexService.mapperService().merge("type1", new CompressedXContent(BytesReference.bytes(mappings1)),
MapperService.MergeReason.MAPPING_UPDATE, false);
XContentBuilder mappings2 = jsonBuilder().startObject()
.startObject("type2")
.startObject("properties")
.startObject("field")
.field("type", "text")
.endObject()
.endObject()
.endObject().endObject();
indexService
.mapperService()
.merge("type2", new CompressedXContent(BytesReference.bytes(mappings2)), MapperService.MergeReason.MAPPING_UPDATE, false);
XContentBuilder json = XContentFactory.jsonBuilder().startObject()
.field("field", "foo")
.endObject();
SourceToParse source = SourceToParse.source("test", "type1", "1", BytesReference.bytes(json), json.contentType());
DocumentMapper mapper = indexService.mapperService().documentMapper("type1");
assertNull(mapper.mappers().getMapper("field.raw"));
ParsedDocument parsed = mapper.parse(source);
assertNotNull(parsed.dynamicMappingsUpdate());
indexService
.mapperService()
.merge(
"type1",
new CompressedXContent(parsed.dynamicMappingsUpdate().toString()), MapperService.MergeReason.MAPPING_UPDATE, false);
mapper = indexService.mapperService().documentMapper("type1");
assertNotNull(mapper.mappers().getMapper("field.raw"));
parsed = mapper.parse(source);
assertNull(parsed.dynamicMappingsUpdate());
}
}
| 1,632 |
1,056 | <reponame>arusinha/incubator-netbeans
/*
* 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.openide.loaders;
import org.openide.filesystems.*;
import org.openide.loaders.*;
import java.beans.*;
import java.io.IOException;
import junit.textui.TestRunner;
import org.netbeans.junit.*;
/*
* Tries to reproduce NPE from #35897 issue.
*/
public class NullPointer35897Test extends NbTestCase {
private FileSystem lfs;
private FileObject file;
private L loader;
private D obj;
public NullPointer35897Test (String name) {
super (name);
}
protected void setUp () throws Exception {
TestUtilHid.destroyLocalFileSystem (getName ());
String fsstruct [] = new String [] {
"dir/simple.simple"
};
lfs = TestUtilHid.createLocalFileSystem (getWorkDir(), fsstruct);
Repository.getDefault ().addFileSystem (lfs);
file = lfs.findResource (fsstruct[0]);
loader = (L)DataLoader.getLoader (L.class);
AddLoaderManuallyHid.addRemoveLoader (loader, true);
}
//Clear all stuff when the test finish
protected void tearDown () throws Exception {
AddLoaderManuallyHid.addRemoveLoader (loader, false);
TestUtilHid.destroyLocalFileSystem (getName ());
}
public void test35897 () throws Exception {
class InitObj implements Runnable {
public void run () {
try {
obj = (D)DataObject.find (file);
} catch (DataObjectNotFoundException ex) {
ex.printStackTrace();
fail ("Unexpected exception");
}
}
}
InitObj init = new InitObj ();
org.openide.util.RequestProcessor.Task task;
synchronized (loader) {
task = org.openide.util.RequestProcessor.getDefault ().post (init);
loader.wait ();
}
assertTrue ("The creation of DataObject is blocked in constructor", loader.waitingInConstructor);
Repository.getDefault ().removeFileSystem (lfs);
synchronized (loader) {
loader.notifyAll ();
}
task.waitFinished ();
assertNotNull ("The object has been finished", obj);
}
private static class D extends MultiDataObject {
private boolean constructorFinished;
public D (FileObject pf, L loader) throws IOException {
super(pf, loader);
synchronized (loader) {
try {
loader.waitingInConstructor = true;
loader.notifyAll ();
loader.wait (2000);
} catch (InterruptedException ex) {
ex.printStackTrace();
fail ("No interruptions please");
} finally {
loader.waitingInConstructor = false;
constructorFinished = true;
}
}
}
protected org.openide.nodes.Node createNodeDelegate() {
return org.openide.nodes.Node.EMPTY;
}
public java.util.Set files () {
assertTrue ("This can be called only if the constructor is finished", constructorFinished);
return super.files ();
}
}
private static class L extends MultiFileLoader {
public boolean waitingInConstructor;
public L () {
super(D.class.getName());
}
protected String displayName() {
return "L";
}
protected FileObject findPrimaryFile (FileObject obj) {
return obj.hasExt ("simple") ? obj : null;
}
protected MultiDataObject createMultiObject(FileObject pf) throws IOException {
return new D(pf, this);
}
protected MultiDataObject.Entry createSecondaryEntry (MultiDataObject x, FileObject obj) {
throw new IllegalStateException ();
}
protected MultiDataObject.Entry createPrimaryEntry (MultiDataObject x, FileObject obj) {
return new org.openide.loaders.FileEntry (x, obj);
}
}
}
| 2,113 |
5,594 | package com.tale.test.service;
import com.blade.ioc.annotation.Inject;
import com.tale.service.OptionsService;
import com.tale.test.BaseTest;
import org.junit.Assert;
import org.junit.Test;
/**
* @author biezhi
* @date 2018/6/3
*/
public class OptionsServiceTest extends BaseTest {
@Inject
private OptionsService optionsService;
@Test
public void testSaveOption() {
optionsService.saveOption("hello2", "world2");
String value = optionsService.getOption("hello2");
Assert.assertEquals("world2", value);
}
@Test
public void testGetOption() {
optionsService.saveOption("hello3", "world3");
optionsService.deleteOption("hello3");
String value = optionsService.getOption("hello3");
Assert.assertNull(value);
}
}
| 298 |
353 | #include <stdio.h>
struct IntValue {
int i;
const char *s;
};
static const struct IntValue IntValues[] = {{123, "123"},{456, "456"}};
static void compare_structure(const struct IntValue *v1, const struct IntValue *v2)
{
if (v1->i >= v2->i) {
printf("%s >= %s\n", v1->s, v2->s);
} else {
printf("%s < %s\n", v1->s, v2->s);
}
}
int main(int argc, char *argv[])
{
if (argc == 1) {
compare_structure(&IntValues[0], &IntValues[1]);
} else {
compare_structure(&IntValues[1], &IntValues[0]);
}
return 0;
}
| 270 |
1,103 | <filename>hollow-jsonadapter/src/main/java/com/netflix/hollow/jsonadapter/HollowJsonToFlatRecordTask.java
/*
* Copyright 2016-2019 Netflix, 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.netflix.hollow.jsonadapter;
import com.fasterxml.jackson.core.JsonParser;
import com.netflix.hollow.core.write.objectmapper.flatrecords.FlatRecord;
import com.netflix.hollow.core.write.objectmapper.flatrecords.FlatRecordWriter;
import com.netflix.hollow.core.write.objectmapper.flatrecords.HollowSchemaIdentifierMapper;
import java.io.IOException;
import java.io.Reader;
import java.util.function.Consumer;
public class HollowJsonToFlatRecordTask extends AbstractHollowJsonAdaptorTask {
private final HollowJsonAdapter adapter;
private final HollowSchemaIdentifierMapper schemaIdMapper;
private final Consumer<FlatRecord> action;
private final ThreadLocal<FlatRecordWriter> flatRecordWriter;
public HollowJsonToFlatRecordTask(HollowJsonAdapter adapter,
HollowSchemaIdentifierMapper schemaIdMapper,
Consumer<FlatRecord> action) {
super(adapter.getTypeName());
this.adapter = adapter;
this.schemaIdMapper = schemaIdMapper;
this.flatRecordWriter = new ThreadLocal<>();
this.action = action;
}
public void process(Reader jsonReader) throws Exception {
processFile(jsonReader, Integer.MAX_VALUE);
}
@Override
protected int processRecord(JsonParser parser) throws IOException {
FlatRecordWriter recWriter = getFlatRecordWriter();
int ordinal = adapter.processRecord(parser, recWriter);
FlatRecord rec = recWriter.generateFlatRecord();
action.accept(rec);
return ordinal;
}
private FlatRecordWriter getFlatRecordWriter() {
FlatRecordWriter writer = flatRecordWriter.get();
if(writer == null) {
writer = new FlatRecordWriter(adapter.stateEngine, schemaIdMapper);
flatRecordWriter.set(writer);
}
writer.reset();
return writer;
}
}
| 965 |
921 | #!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.path.join(__file__, '..', '..'))
sys.path.insert(0, os.path.dirname(__file__))
from django.core.management import execute_from_command_line
from reviewboard import finalize_setup
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reviewboard.settings')
def scan_resource(resource):
for child in resource.item_child_resources:
scan_resource(child)
for child in resource.list_child_resources:
scan_resource(child)
if __name__ == '__main__':
if sys.argv[1] == 'createdb':
execute_from_command_line([sys.argv[0]] +
['evolve', '--noinput', '--execute'])
finalize_setup(register_scmtools=False)
else:
execute_from_command_line()
| 326 |
32,544 | <gh_stars>1000+
package com.baeldung.exceptions.nosuchmethoderror;
public class SpecialToday {
private static String desert = "Chocolate Cake";
public static String getDesert() {
return desert;
}
}
| 84 |
3,102 | <gh_stars>1000+
// RUN: %clang_cc1 -x c -debug-info-kind=line-tables-only -emit-llvm -fsanitize=returns-nonnull-attribute -o - %s | FileCheck %s
// The UBSAN function call in the epilogue needs to have a debug location.
__attribute__((returns_nonnull)) void *allocate() {}
// CHECK: define {{.*}}nonnull i8* @allocate(){{.*}} !dbg
// CHECK: call void @__ubsan_handle_nonnull_return_v1_abort
// CHECK-SAME: !dbg ![[LOC:[0-9]+]]
// CHECK: ret i8*
// CHECK-SAME: !dbg ![[LOC]]
| 196 |
384 | <reponame>hejamu/gromacs
#include "../gmx_lapack.h"
#define DORGLQ_BLOCKSIZE 32
#define DORGLQ_MINBLOCKSIZE 2
#define DORGLQ_CROSSOVER 128
void
F77_FUNC(dorglq,DORGLQ)(int *m,
int *n,
int *k,
double *a,
int *lda,
double *tau,
double *work,
int *lwork,
int *info)
{
int a_dim1, a_offset, i__1, i__2, i__3;
int i__, j, l, ib, nb, ki, kk, nx, iws, nbmin, iinfo;
int ldwork, lwkopt;
int lquery;
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--tau;
--work;
*info = 0;
ki = 0;
nb = DORGLQ_BLOCKSIZE;
lwkopt = (*m) * nb;
work[1] = (double) lwkopt;
lquery = *lwork == -1;
if (*m < 0) {
*info = -1;
} else if (*n < *m) {
*info = -2;
} else if (*k < 0 || *k > *m) {
*info = -3;
} else if (*lda < (*m)) {
*info = -5;
} else if (*lwork < (*m) && ! lquery) {
*info = -8;
}
if (*info != 0) {
i__1 = -(*info);
return;
} else if (lquery) {
return;
}
if (*m <= 0) {
work[1] = 1.;
return;
}
nbmin = 2;
nx = 0;
iws = *m;
if (nb > 1 && nb < *k) {
nx = DORGLQ_CROSSOVER;
if (nx < *k) {
ldwork = *m;
iws = ldwork * nb;
if (*lwork < iws) {
nb = *lwork / ldwork;
nbmin = DORGLQ_MINBLOCKSIZE;
}
}
}
if (nb >= nbmin && nb < *k && nx < *k) {
ki = (*k - nx - 1) / nb * nb;
i__1 = *k, i__2 = ki + nb;
kk = (i__1<i__2) ? i__1 : i__2;
i__1 = kk;
for (j = 1; j <= i__1; ++j) {
i__2 = *m;
for (i__ = kk + 1; i__ <= i__2; ++i__) {
a[i__ + j * a_dim1] = 0.;
}
}
} else {
kk = 0;
}
if (kk < *m) {
i__1 = *m - kk;
i__2 = *n - kk;
i__3 = *k - kk;
F77_FUNC(dorgl2,DORGL2)(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, &
tau[kk + 1], &work[1], &iinfo);
}
if (kk > 0) {
i__1 = -nb;
for (i__ = ki + 1; i__1 < 0 ? i__ >= 1 : i__ <= 1; i__ += i__1) {
i__2 = nb, i__3 = *k - i__ + 1;
ib = (i__2<i__3) ? i__2 : i__3;
if (i__ + ib <= *m) {
i__2 = *n - i__ + 1;
F77_FUNC(dlarft,DLARFT)("Forward", "Rowwise", &i__2, &ib, &a[i__ + i__ *
a_dim1], lda, &tau[i__], &work[1], &ldwork);
i__2 = *m - i__ - ib + 1;
i__3 = *n - i__ + 1;
F77_FUNC(dlarfb,DLARFB)("Right", "Transpose", "Forward", "Rowwise", &i__2, &
i__3, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], &
ldwork, &a[i__ + ib + i__ * a_dim1], lda, &work[ib +
1], &ldwork);
}
i__2 = *n - i__ + 1;
F77_FUNC(dorgl2,DORGL2)(&ib, &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &
work[1], &iinfo);
i__2 = i__ - 1;
for (j = 1; j <= i__2; ++j) {
i__3 = i__ + ib - 1;
for (l = i__; l <= i__3; ++l) {
a[l + j * a_dim1] = 0.;
}
}
}
}
work[1] = (double) iws;
return;
}
| 1,625 |
1,016 | /**
*
*/
package com.thinkbiganalytics.spark.mergetable;
import java.io.Serializable;
/*-
* #%L
* thinkbig-nifi-core-processors
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Stores the identifier of a partition and the record count
*/
public class PartitionBatch implements Serializable {
private static final long serialVersionUID = 1L;
private Long records;
private List<String> partitionValues;
private PartitionSpec partitionSpec;
public PartitionBatch(PartitionBatch orig) {
this(orig.getRecordCount(), orig.getPartitionSpec(), orig.getPartitionValues());
}
public PartitionBatch(Long records, PartitionSpec partitionSpec, Collection<String> partitionValues) {
this.records = records;
this.partitionValues = new ArrayList<>(partitionValues);
this.partitionSpec = partitionSpec;
}
public static List<PartitionBatch> toPartitionBatchesForAlias(List<PartitionBatch> batches, String alias) {
ArrayList<PartitionBatch> newBatches = new ArrayList<>();
for (PartitionBatch batch : batches) {
newBatches.add(batch.newForAlias(alias));
}
return newBatches;
}
public Long getRecordCount() {
return records;
}
public List<String> getPartitionValues() {
return partitionValues;
}
public PartitionSpec getPartitionSpec() {
return partitionSpec;
}
private void setPartitionSpec(PartitionSpec spec) {
this.partitionSpec = spec;
}
public String getBatchDescription() {
return partitionSpec.toPartitionSpec(partitionValues);
}
public PartitionBatch newForAlias(String alias) {
PartitionBatch batch = new PartitionBatch(this);
batch.setPartitionSpec(partitionSpec.withAlias(alias));
return batch;
}
}
| 849 |
442 | #include <vili/node.hpp>
namespace vili::writer
{
enum class delimiter_newline_policy
{
never,
only_if_multiline,
always
};
enum class comma_spacing_policy
{
left_side,
right_side,
both
};
enum class object_style
{
braces,
indent
};
struct dump_options
{
unsigned int indent = 4;
struct array
{
unsigned int items_per_line = 0;
unsigned int max_line_length = 0;
delimiter_newline_policy starts_with_newline
= delimiter_newline_policy::only_if_multiline;
delimiter_newline_policy ends_with_newline
= delimiter_newline_policy::only_if_multiline;
unsigned int left_bracket_spacing = 0;
unsigned int right_bracket_spacing = 0;
unsigned int inline_spacing = 1;
comma_spacing_policy comma_spacing = comma_spacing_policy::right_side;
};
array array;
struct object
{
unsigned int items_per_line = 0;
unsigned int max_line_length = 0;
delimiter_newline_policy starts_with_newline
= delimiter_newline_policy::only_if_multiline;
delimiter_newline_policy ends_with_newline
= delimiter_newline_policy::only_if_multiline;
unsigned int left_brace_spacing = 0;
unsigned int right_brace_spacing = 0;
unsigned int affectation_left_spaces = 0;
unsigned int affectation_right_spaces = 1;
unsigned int inline_spacing = 1;
comma_spacing_policy comma_spacing = comma_spacing_policy::right_side;
object_style style = object_style::indent;
};
object object;
bool root = true;
};
std::string dump_integer(const vili::node& data);
std::string dump_number(const vili::node& data);
std::string dump_boolean(const vili::node& data);
std::string dump_string(const vili::node& data);
std::string dump_array(
const vili::node& data, const dump_options& options = dump_options {});
std::string dump_object(
const vili::node& data, const dump_options& options = dump_options {});
std::string dump(
const vili::node& data, const dump_options& options = dump_options {});
} | 1,085 |
392 | <filename>setup.py
#!/usr/bin/env python
import os
from setuptools import setup
def read(*parts):
"""Reads the content of the file located at path created from *parts*."""
try:
return open(os.path.join(*parts), "r", encoding="utf-8").read()
except OSError:
return ""
tests_require = []
requirements = read("requirements", "main.txt").splitlines()
extras_require = {
"docs": read("requirements", "docs.txt").splitlines(),
"tests": tests_require,
}
setup(
# Dependencies are here for GitHub's dependency graph.
use_scm_version={"write_to": "pytest_flask/_version.py"},
install_requires=requirements,
tests_require=tests_require,
extras_require=extras_require,
)
| 260 |
2,138 | /*
* Copyright (C) 2017 Original Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.csanchez.jenkins.plugins.kubernetes.pipeline;
import hudson.model.TaskListener;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import java.io.Closeable;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Resources {
private static final transient Logger LOGGER = Logger.getLogger(ContainerStepExecution.class.getName());
static void closeQuietly(StepContext context, Closeable... closeables) {
for (Closeable c : closeables) {
if (c != null) {
try {
c.close();
} catch (IOException e) {
try {
context.get(TaskListener.class).error("Error while closing: [" + c + "]");
} catch (IOException | InterruptedException e1) {
LOGGER.log(Level.WARNING, "Error writing to task listener", e);
}
}
}
}
}
}
| 624 |
320 | from sample_factory.runner.run_description import RunDescription, Experiment, ParamGrid
_params = ParamGrid([
('gamma', [0.995]),
('gae_lambda', [1.0]),
('ppo_clip_value', [10]),
('with_vtrace', ['False']),
('learning_rate', [0.0001]),
('max_grad_norm', [100.0]),
('use_rnn', ['False']),
('recurrence', [1]),
('num_minibatches_to_accumulate', [0]),
('device', ['gpu']),
('actor_critic_share_weights', ['False']),
('max_policy_lag', [1000000]),
('adaptive_stddev', ['False']),
('ppo_epochs', [20]),
('ppo_clip_ratio', [0.3]),
('batch_size', [1024]),
('num_batches_per_iteration', [10]),
('rollout', [128]),
('nonlinearity', ['tanh']),
('exploration_loss_coeff', [0.0]),
])
_experiment = Experiment(
'mujoco_hopper',
'python -m sample_factory.run_algorithm --env=mujoco_hopper --train_for_env_steps=7000000 --algo=APPO --num_workers=16 --num_envs_per_worker=4 --benchmark=False --with_pbt=False',
_params.generate_params(randomize=False),
)
RUN_DESCRIPTION = RunDescription('mujoco_hopper_v94', experiments=[_experiment])
# python -m runner.run --run=mujoco_halfcheetah_grid_search --runner=processes --max_parallel=8 --pause_between=1 --experiments_per_gpu=10000 --num_gpus=1
| 522 |
2,453 | <reponame>haozhiyu1990/XVim2<gh_stars>1000+
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <Foundation/NSURLSession.h>
@interface NSURLSession (DVTMainThreadLatencyCheckerAdditions)
+ (id)__DVTMainThreadLatencyChecker__sessionWithConfiguration:(id)arg1 delegate:(id)arg2 delegateQueue:(id)arg3;
- (void)__DVTMainThreadLatencyChecker__getAllTasksWithCompletionHandler:(CDUnknownBlockType)arg1;
- (void)__DVTMainThreadLatencyChecker__getTasksWithCompletionHandler:(CDUnknownBlockType)arg1;
- (void)__DVTMainThreadLatencyChecker__flushWithCompletionHandler:(CDUnknownBlockType)arg1;
- (void)__DVTMainThreadLatencyChecker__resetWithCompletionHandler:(CDUnknownBlockType)arg1;
@end
| 270 |
14,668 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <cstdint>
#include <memory>
#include <vector>
#include "base/check.h"
#include "chromecast/public/cast_media_shlib.h"
#include "chromecast/public/media/external_audio_pipeline_shlib.h"
#include "chromecast/public/media/mixer_output_stream.h"
using ExternalMediaMetadataChangeObserver = chromecast::media::
ExternalAudioPipelineShlib::ExternalMediaMetadataChangeObserver;
namespace chromecast {
namespace media {
class TestLoopBack {
public:
void OnData(const float* data,
int data_size,
MixerOutputStream* stream,
int channels) {
auto delay = stream->GetRenderingDelay();
int64_t delay_ms = delay.timestamp_microseconds + delay.delay_microseconds;
for (auto* observer : observers_) {
observer->OnLoopbackAudio(
delay_ms, kSampleFormatF32, stream->GetSampleRate(), channels,
reinterpret_cast<uint8_t*>(const_cast<float*>(data)),
data_size * sizeof(float));
}
}
void AddObserver(
ExternalAudioPipelineShlib::LoopbackAudioObserver* observer) {
observers_.push_back(observer);
}
void RemoveObserver(
ExternalAudioPipelineShlib::LoopbackAudioObserver* observer) {
auto it = std::find(observers_.begin(), observers_.end(), observer);
if (it != observers_.end()) {
observers_.erase(it);
}
observer->OnRemoved();
}
private:
std::vector<ExternalAudioPipelineShlib::LoopbackAudioObserver*> observers_;
};
TestLoopBack g_test_loop_back;
class MixerOutputStreamTest : public MixerOutputStream {
public:
explicit MixerOutputStreamTest(TestLoopBack* test_loop_back)
: stream_(MixerOutputStream::Create()), test_loop_back_(test_loop_back) {
DCHECK(test_loop_back_);
}
bool Start(int requested_sample_rate, int channels) override {
channels_ = channels;
return stream_->Start(requested_sample_rate, channels);
}
int GetSampleRate() override { return stream_->GetSampleRate(); }
MediaPipelineBackend::AudioDecoder::RenderingDelay GetRenderingDelay()
override {
return stream_->GetRenderingDelay();
}
int OptimalWriteFramesCount() override {
return stream_->OptimalWriteFramesCount();
}
bool Write(const float* data,
int data_size,
bool* out_playback_interrupted) override {
test_loop_back_->OnData(data, data_size, this, channels_);
return stream_->Write(data, data_size, out_playback_interrupted);
}
void Stop() override { return stream_->Stop(); }
private:
std::unique_ptr<MixerOutputStream> stream_;
TestLoopBack* test_loop_back_;
int channels_ = 0;
};
bool ExternalAudioPipelineShlib::IsSupported() {
return true;
}
void ExternalAudioPipelineShlib::AddExternalMediaVolumeChangeRequestObserver(
ExternalMediaVolumeChangeRequestObserver* observer) {}
void ExternalAudioPipelineShlib::RemoveExternalMediaVolumeChangeRequestObserver(
ExternalMediaVolumeChangeRequestObserver* observer) {}
void ExternalAudioPipelineShlib::SetExternalMediaVolume(float level) {}
void ExternalAudioPipelineShlib::SetExternalMediaMuted(bool muted) {}
void ExternalAudioPipelineShlib::AddExternalLoopbackAudioObserver(
LoopbackAudioObserver* observer) {
g_test_loop_back.AddObserver(observer);
}
void ExternalAudioPipelineShlib::RemoveExternalLoopbackAudioObserver(
LoopbackAudioObserver* observer) {
g_test_loop_back.RemoveObserver(observer);
}
void ExternalAudioPipelineShlib::AddExternalMediaMetadataChangeObserver(
ExternalMediaMetadataChangeObserver* observer) {}
void ExternalAudioPipelineShlib::RemoveExternalMediaMetadataChangeObserver(
ExternalMediaMetadataChangeObserver* observer) {}
std::unique_ptr<MixerOutputStream>
ExternalAudioPipelineShlib::CreateMixerOutputStream() {
return std::make_unique<MixerOutputStreamTest>(&g_test_loop_back);
}
} // namespace media
} // namespace chromecast
| 1,369 |
5,547 | /*!
\file gd32f1x0_usart.h
\brief definitions for the USART
*/
/*
Copyright (C) 2017 GigaDevice
2014-12-26, V1.0.0, platform GD32F1x0(x=3,5)
2016-01-15, V2.0.0, platform GD32F1x0(x=3,5,7,9)
2016-04-30, V3.0.0, firmware update for GD32F1x0(x=3,5,7,9)
2017-06-19, V3.1.0, firmware update for GD32F1x0(x=3,5,7,9)
*/
#ifndef GD32F1X0_USART_H
#define GD32F1X0_USART_H
#include "gd32f1x0.h"
/* USARTx(x=0,1) definitions */
#define USART0 (USART_BASE + 0x0000F400U)
#define USART1 USART_BASE
/* registers definitions */
#define USART_CTL0(usartx) REG32((usartx) + 0x00U) /*!< USART control register 0 */
#define USART_CTL1(usartx) REG32((usartx) + 0x04U) /*!< USART control register 1 */
#define USART_CTL2(usartx) REG32((usartx) + 0x08U) /*!< USART control register 2 */
#define USART_BAUD(usartx) REG32((usartx) + 0x0CU) /*!< USART baud rate register */
#define USART_GP(usartx) REG32((usartx) + 0x10U) /*!< USART guard time and prescaler register */
#define USART_RT(usartx) REG32((usartx) + 0x14U) /*!< USART receiver timeout register */
#define USART_CMD(usartx) REG32((usartx) + 0x18U) /*!< USART command register */
#define USART_STAT(usartx) REG32((usartx) + 0x1CU) /*!< USART status register */
#define USART_INTC(usartx) REG32((usartx) + 0x20U) /*!< USART status clear register */
#define USART_RDATA(usartx) REG32((usartx) + 0x24U) /*!< USART receive data register */
#define USART_TDATA(usartx) REG32((usartx) + 0x28U) /*!< USART transmit data register */
/* bits definitions */
/* USARTx_CTL0 */
#define USART_CTL0_UEN BIT(0) /*!< USART enable */
#define USART_CTL0_UESM BIT(1) /*!< USART enable in deep-sleep mode */
#define USART_CTL0_REN BIT(2) /*!< receiver enable */
#define USART_CTL0_TEN BIT(3) /*!< transmitter enable */
#define USART_CTL0_IDLEIE BIT(4) /*!< idle line detected interrupt enable */
#define USART_CTL0_RBNEIE BIT(5) /*!< read data buffer not empty interrupt and overrun error interrupt enable */
#define USART_CTL0_TCIE BIT(6) /*!< transmission complete interrupt enable */
#define USART_CTL0_TBEIE BIT(7) /*!< transmitter register empty interrupt enable */
#define USART_CTL0_PERRIE BIT(8) /*!< parity error interrupt enable */
#define USART_CTL0_PM BIT(9) /*!< parity mode */
#define USART_CTL0_PCEN BIT(10) /*!< parity control enable */
#define USART_CTL0_WM BIT(11) /*!< wakeup method in mute mode */
#define USART_CTL0_WL BIT(12) /*!< word length */
#define USART_CTL0_MEN BIT(13) /*!< mute mode enable */
#define USART_CTL0_AMIE BIT(14) /*!< address match interrupt enable */
#define USART_CTL0_OVSMOD BIT(15) /*!< oversample mode */
#define USART_CTL0_DED BITS(16,20) /*!< driver enable deassertion time */
#define USART_CTL0_DEA BITS(21,25) /*!< driver enable assertion time */
#define USART_CTL0_RTIE BIT(26) /*!< receiver timeout interrupt enable */
#define USART_CTL0_EBIE BIT(27) /*!< end of block interrupt enable */
/* USARTx_CTL1 */
#define USART_CTL1_ADDM BIT(4) /*!< address detection mode */
#define USART_CTL1_LBLEN BIT(5) /*!< LIN break frame length */
#define USART_CTL1_LBDIE BIT(6) /*!< LIN break detection interrupt enable */
#define USART_CTL1_CLEN BIT(8) /*!< last bit clock pulse */
#define USART_CTL1_CPH BIT(9) /*!< clock phase */
#define USART_CTL1_CPL BIT(10) /*!< clock polarity */
#define USART_CTL1_CKEN BIT(11) /*!< ck pin enable */
#define USART_CTL1_STB BITS(12,13) /*!< stop bits length */
#define USART_CTL1_LMEN BIT(14) /*!< LIN mode enable */
#define USART_CTL1_STRP BIT(15) /*!< swap TX/RX pins */
#define USART_CTL1_RINV BIT(16) /*!< RX pin level inversion */
#define USART_CTL1_TINV BIT(17) /*!< TX pin level inversion */
#define USART_CTL1_DINV BIT(18) /*!< data bit level inversion */
#define USART_CTL1_MSBF BIT(19) /*!< most significant bit first */
#define USART_CTL1_ABDEN BIT(20) /*!< auto baud rate enable */
#define USART_CTL1_ABDM BITS(21,22) /*!< auto baud rate mode */
#define USART_CTL1_RTEN BIT(23) /*!< receiver timeout enable */
#define USART_CTL1_ADDR BITS(24,31) /*!< address of the USART terminal */
/* USARTx_CTL2 */
#define USART_CTL2_ERRIE BIT(0) /*!< error interrupt enable in multibuffer communication */
#define USART_CTL2_IREN BIT(1) /*!< IrDA mode enable */
#define USART_CTL2_IRLP BIT(2) /*!< IrDA low-power */
#define USART_CTL2_HDEN BIT(3) /*!< half-duplex enable */
#define USART_CTL2_NKEN BIT(4) /*!< NACK enable in smartcard mode */
#define USART_CTL2_SCEN BIT(5) /*!< smartcard mode enable */
#define USART_CTL2_DENR BIT(6) /*!< DMA enable for reception */
#define USART_CTL2_DENT BIT(7) /*!< DMA enable for transmission */
#define USART_CTL2_RTSEN BIT(8) /*!< RTS enable */
#define USART_CTL2_CTSEN BIT(9) /*!< CTS enable */
#define USART_CTL2_CTSIE BIT(10) /*!< CTS interrupt enable */
#define USART_CTL2_OSB BIT(11) /*!< one sample bit mode */
#define USART_CTL2_OVRD BIT(12) /*!< overrun disable */
#define USART_CTL2_DDRE BIT(13) /*!< disable DMA on reception error */
#define USART_CTL2_DEM BIT(14) /*!< driver enable mode */
#define USART_CTL2_DEP BIT(15) /*!< driver enable polarity mode */
#define USART_CTL2_SCRTNUM BITS(17,19) /*!< smartcard auto-retry number */
#define USART_CTL2_WUM BITS(20,21) /*!< wakeup mode from deep-sleep mode */
#define USART_CTL2_WUIE BIT(22) /*!< wakeup from deep-sleep mode interrupt enable */
/* USARTx_BAUD */
#define USART_BAUD_FRADIV BITS(0,3) /*!< fraction of baud-rate divider */
#define USART_BAUD_INTDIV BITS(4,15) /*!< integer of baud-rate divider */
/* USARTx_GP */
#define USART_GP_PSC BITS(0,7) /*!< prescaler value for dividing the system clock */
#define USART_GP_GUAT BITS(8,15) /*!< guard time value in smartcard mode */
/* USARTx_RT */
#define USART_RT_RT BITS(0,23) /*!< receiver timeout threshold */
#define USART_RT_BL BITS(24,31) /*!< block length */
/* USARTx_CMD */
#define USART_CMD_ABDCMD BIT(0) /*!< auto baudrate detection command */
#define USART_CMD_SBKCMD BIT(1) /*!< send break command */
#define USART_CMD_MMCMD BIT(2) /*!< mute mode command */
#define USART_CMD_RXFCMD BIT(3) /*!< receive data flush command */
#define USART_CMD_TXFCMD BIT(4) /*!< transmit data flush request */
/* USARTx_STAT */
#define USART_STAT_PERR BIT(0) /*!< parity error flag */
#define USART_STAT_FERR BIT(1) /*!< frame error flag */
#define USART_STAT_NERR BIT(2) /*!< noise error flag */
#define USART_STAT_ORERR BIT(3) /*!< overrun error */
#define USART_STAT_IDLEF BIT(4) /*!< idle line detected flag */
#define USART_STAT_RBNE BIT(5) /*!< read data buffer not empty */
#define USART_STAT_TC BIT(6) /*!< transmission completed */
#define USART_STAT_TBE BIT(7) /*!< transmit data register empty */
#define USART_STAT_LBDF BIT(8) /*!< LIN break detected flag */
#define USART_STAT_CTSF BIT(9) /*!< CTS change flag */
#define USART_STAT_CTS BIT(10) /*!< CTS level */
#define USART_STAT_RTF BIT(11) /*!< receiver timeout flag */
#define USART_STAT_EBF BIT(12) /*!< end of block flag */
#define USART_STAT_ABDE BIT(14) /*!< auto baudrate detection error */
#define USART_STAT_ABDF BIT(15) /*!< auto baudrate detection flag */
#define USART_STAT_BSY BIT(16) /*!< busy flag */
#define USART_STAT_AMF BIT(17) /*!< address match flag */
#define USART_STAT_SBF BIT(18) /*!< send break flag */
#define USART_STAT_RWU BIT(19) /*!< receiver wakeup from mute mode */
#define USART_STAT_WUF BIT(20) /*!< wakeup from deep-sleep mode flag */
#define USART_STAT_TEA BIT(21) /*!< transmit enable acknowledge flag */
#define USART_STAT_REA BIT(22) /*!< receive enable acknowledge flag */
/* USARTx_INTC */
#define USART_INTC_PEC BIT(0) /*!< parity error clear */
#define USART_INTC_FEC BIT(1) /*!< frame error flag clear */
#define USART_INTC_NEC BIT(2) /*!< noise detected clear */
#define USART_INTC_OREC BIT(3) /*!< overrun error clear */
#define USART_INTC_IDLEC BIT(4) /*!< idle line detected clear */
#define USART_INTC_TCC BIT(6) /*!< transmission complete clear */
#define USART_INTC_LBDC BIT(8) /*!< LIN break detected clear */
#define USART_INTC_CTSC BIT(9) /*!< CTS change clear */
#define USART_INTC_RTC BIT(11) /*!< receiver timeout clear */
#define USART_INTC_EBC BIT(12) /*!< end of timeout clear */
#define USART_INTC_AMC BIT(17) /*!< address match clear */
#define USART_INTC_WUC BIT(20) /*!< wakeup from deep-sleep mode clear */
/* USARTx_RDATA */
#define USART_RDATA_RDATA BITS(0,8) /*!< receive data value */
/* USARTx_TDATA */
#define USART_TDATA_TDATA BITS(0,8) /*!< transmit data value */
/* constants definitions */
/* define the USART bit position and its register index offset */
#define USART_REGIDX_BIT(regidx, bitpos) (((uint32_t)(regidx) << 6) | (uint32_t)(bitpos))
#define USART_REG_VAL(usartx, offset) (REG32((usartx) + (((uint32_t)(offset) & 0xFFFFU) >> 6)))
#define USART_BIT_POS(val) ((uint32_t)(val) & 0x1FU)
#define USART_REGIDX_BIT2(regidx, bitpos, regidx2, bitpos2) (((uint32_t)(regidx2) << 22) | (uint32_t)((bitpos2) << 16)\
| (((uint32_t)(regidx) << 6) | (uint32_t)(bitpos)))
#define USART_REG_VAL2(usartx, offset) (REG32((usartx) + ((uint32_t)(offset) >> 22)))
#define USART_BIT_POS2(val) (((uint32_t)(val) & 0x1F0000U) >> 16)
/* register offset */
#define USART_CTL0_REG_OFFSET 0x00U /*!< CTL0 register offset */
#define USART_CTL1_REG_OFFSET 0x04U /*!< CTL1 register offset */
#define USART_CTL2_REG_OFFSET 0x08U /*!< CTL2 register offset */
#define USART_STAT_REG_OFFSET 0x1CU /*!< STAT register offset */
/* USART flags */
typedef enum{
/* flags in STAT register */
USART_FLAG_REA = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 22U), /*!< receive enable acknowledge flag */
USART_FLAG_TEA = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 21U), /*!< transmit enable acknowledge flag */
USART_FLAG_WU = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 20U), /*!< wakeup from Deep-sleep mode flag */
USART_FLAG_RWU = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 19U), /*!< receiver wakeup from mute mode */
USART_FLAG_SB = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 18U), /*!< send break flag */
USART_FLAG_AM = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 17U), /*!< ADDR match flag */
USART_FLAG_BSY = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 16U), /*!< busy flag */
USART_FLAG_ABD = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 15U), /*!< auto baudrate detection flag */
USART_FLAG_ABDE = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 14U), /*!< auto baudrate detection error */
USART_FLAG_EB = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 12U), /*!< end of block flag */
USART_FLAG_RT = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 11U), /*!< receiver timeout flag */
USART_FLAG_CTS = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 10U), /*!< CTS level */
USART_FLAG_CTSF = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 9U), /*!< CTS change flag */
USART_FLAG_LBD = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 8U), /*!< LIN break detected flag */
USART_FLAG_TBE = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 7U), /*!< transmit data buffer empty */
USART_FLAG_TC = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 6U), /*!< transmission complete */
USART_FLAG_RBNE = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 5U), /*!< read data buffer not empty */
USART_FLAG_IDLE = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 4U), /*!< IDLE line detected flag */
USART_FLAG_ORERR = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 3U), /*!< overrun error */
USART_FLAG_NERR = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 2U), /*!< noise error flag */
USART_FLAG_FERR = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 1U), /*!< frame error flag */
USART_FLAG_PERR = USART_REGIDX_BIT(USART_STAT_REG_OFFSET, 0U), /*!< parity error flag */
}usart_flag_enum;
/* USART interrupt flags */
typedef enum
{
/* interrupt flags in CTL0 register */
USART_INT_FLAG_EB = USART_REGIDX_BIT2(USART_CTL0_REG_OFFSET, 27U, USART_STAT_REG_OFFSET, 12U), /*!< end of block interrupt and flag */
USART_INT_FLAG_RT = USART_REGIDX_BIT2(USART_CTL0_REG_OFFSET, 26U, USART_STAT_REG_OFFSET, 11U), /*!< receiver timeout interrupt and flag */
USART_INT_FLAG_AM = USART_REGIDX_BIT2(USART_CTL0_REG_OFFSET, 14U, USART_STAT_REG_OFFSET, 17U), /*!< address match interrupt and flag */
USART_INT_FLAG_PERR = USART_REGIDX_BIT2(USART_CTL0_REG_OFFSET, 8U, USART_STAT_REG_OFFSET, 0U), /*!< parity error interrupt and flag */
USART_INT_FLAG_TBE = USART_REGIDX_BIT2(USART_CTL0_REG_OFFSET, 7U, USART_STAT_REG_OFFSET, 7U), /*!< transmitter buffer empty interrupt and flag */
USART_INT_FLAG_TC = USART_REGIDX_BIT2(USART_CTL0_REG_OFFSET, 6U, USART_STAT_REG_OFFSET, 6U), /*!< transmission complete interrupt and flag */
USART_INT_FLAG_RBNE = USART_REGIDX_BIT2(USART_CTL0_REG_OFFSET, 5U, USART_STAT_REG_OFFSET, 5U), /*!< read data buffer not empty interrupt and flag */
USART_INT_FLAG_RBNE_ORERR = USART_REGIDX_BIT2(USART_CTL0_REG_OFFSET, 5U, USART_STAT_REG_OFFSET, 3U), /*!< read data buffer not empty interrupt and overrun error flag */
USART_INT_FLAG_IDLE = USART_REGIDX_BIT2(USART_CTL0_REG_OFFSET, 4U, USART_STAT_REG_OFFSET, 4U), /*!< IDLE line detected interrupt and flag */
/* interrupt flags in CTL1 register */
USART_INT_FLAG_LBD = USART_REGIDX_BIT2(USART_CTL1_REG_OFFSET, 6U, USART_STAT_REG_OFFSET, 8U), /*!< LIN break detected interrupt and flag */
/* interrupt flags in CTL2 register */
USART_INT_FLAG_WU = USART_REGIDX_BIT2(USART_CTL2_REG_OFFSET, 22U, USART_STAT_REG_OFFSET, 20U), /*!< wakeup from deep-sleep mode interrupt and flag */
USART_INT_FLAG_CTS = USART_REGIDX_BIT2(USART_CTL2_REG_OFFSET, 10U, USART_STAT_REG_OFFSET, 9U), /*!< CTS interrupt and flag */
USART_INT_FLAG_ERR_NERR = USART_REGIDX_BIT2(USART_CTL2_REG_OFFSET, 0U, USART_STAT_REG_OFFSET, 2U), /*!< error interrupt and noise error flag */
USART_INT_FLAG_ERR_ORERR = USART_REGIDX_BIT2(USART_CTL2_REG_OFFSET, 0U, USART_STAT_REG_OFFSET, 3U), /*!< error interrupt and overrun error */
USART_INT_FLAG_ERR_FERR = USART_REGIDX_BIT2(USART_CTL2_REG_OFFSET, 0U, USART_STAT_REG_OFFSET, 1U), /*!< error interrupt and frame error flag */
}usart_interrupt_flag_enum;
/* USART interrupt enable or disable */
typedef enum
{
/* interrupt in CTL0 register */
USART_INT_EB = USART_REGIDX_BIT(USART_CTL0_REG_OFFSET, 27U), /*!< end of block interrupt */
USART_INT_RT = USART_REGIDX_BIT(USART_CTL0_REG_OFFSET, 26U), /*!< receiver timeout interrupt */
USART_INT_AM = USART_REGIDX_BIT(USART_CTL0_REG_OFFSET, 14U), /*!< address match interrupt */
USART_INT_PERR = USART_REGIDX_BIT(USART_CTL0_REG_OFFSET, 8U), /*!< parity error interrupt */
USART_INT_TBE = USART_REGIDX_BIT(USART_CTL0_REG_OFFSET, 7U), /*!< transmitter buffer empty interrupt */
USART_INT_TC = USART_REGIDX_BIT(USART_CTL0_REG_OFFSET, 6U), /*!< transmission complete interrupt */
USART_INT_RBNE = USART_REGIDX_BIT(USART_CTL0_REG_OFFSET, 5U), /*!< read data buffer not empty interrupt and overrun error interrupt */
USART_INT_IDLE = USART_REGIDX_BIT(USART_CTL0_REG_OFFSET, 4U), /*!< IDLE line detected interrupt */
/* interrupt in CTL1 register */
USART_INT_LBD = USART_REGIDX_BIT(USART_CTL1_REG_OFFSET, 6U), /*!< LIN break detected interrupt */
/* interrupt in CTL2 register */
USART_INT_WU = USART_REGIDX_BIT(USART_CTL2_REG_OFFSET, 22U), /*!< wakeup from deep-sleep mode interrupt */
USART_INT_CTS = USART_REGIDX_BIT(USART_CTL2_REG_OFFSET, 10U), /*!< CTS interrupt */
USART_INT_ERR = USART_REGIDX_BIT(USART_CTL2_REG_OFFSET, 0U), /*!< error interrupt */
}usart_interrupt_enum;
/* USART invert configure */
typedef enum {
/* data bit level inversion */
USART_DINV_ENABLE, /*!< data bit level inversion */
USART_DINV_DISABLE, /*!< data bit level not inversion */
/* TX pin level inversion */
USART_TXPIN_ENABLE, /*!< TX pin level inversion */
USART_TXPIN_DISABLE, /*!< TX pin level not inversion */
/* RX pin level inversion */
USART_RXPIN_ENABLE, /*!< RX pin level inversion */
USART_RXPIN_DISABLE, /*!< RX pin level not inversion */
/* swap TX/RX pins */
USART_SWAP_ENABLE, /*!< swap TX/RX pins */
USART_SWAP_DISABLE, /*!< not swap TX/RX pins */
}usart_invert_enum;
/* USART receiver configure */
#define CTL0_REN(regval) (BIT(2) & ((uint32_t)(regval) << 2))
#define USART_RECEIVE_ENABLE CTL0_REN(1) /*!< enable receiver */
#define USART_RECEIVE_DISABLE CTL0_REN(0) /*!< disable receiver */
/* USART transmitter configure */
#define CTL0_TEN(regval) (BIT(3) & ((uint32_t)(regval) << 3))
#define USART_TRANSMIT_ENABLE CTL0_TEN(1) /*!< enable transmitter */
#define USART_TRANSMIT_DISABLE CTL0_TEN(0) /*!< disable transmitter */
/* USART parity bits definitions */
#define CTL0_PM(regval) (BITS(9,10) & ((uint32_t)(regval) << 9))
#define USART_PM_NONE CTL0_PM(0) /*!< no parity */
#define USART_PM_EVEN CTL0_PM(2) /*!< even parity */
#define USART_PM_ODD CTL0_PM(3) /*!< odd parity */
/* USART wakeup method in mute mode */
#define CTL0_WM(regval) (BIT(11) & ((uint32_t)(regval) << 11))
#define USART_WM_IDLE CTL0_WM(0) /*!< idle line */
#define USART_WM_ADDR CTL0_WM(1) /*!< address match */
/* USART word length definitions */
#define CTL0_WL(regval) (BIT(12) & ((uint32_t)(regval) << 12))
#define USART_WL_8BIT CTL0_WL(0) /*!< 8 bits */
#define USART_WL_9BIT CTL0_WL(1) /*!< 9 bits */
/* USART oversample mode */
#define CTL0_OVSMOD(regval) (BIT(15) & ((uint32_t)(regval) << 15))
#define USART_OVSMOD_8 CTL0_OVSMOD(1) /*!< oversampling by 8 */
#define USART_OVSMOD_16 CTL0_OVSMOD(0) /*!< oversampling by 16 */
/* USART address detection mode */
#define CTL1_ADDM(regval) (BIT(4) & ((uint32_t)(regval) << 4))
#define USART_ADDM_4BIT CTL1_ADDM(0) /*!< 4-bit address detection */
#define USART_ADDM_FULLBIT CTL1_ADDM(1) /*!< full-bit address detection */
/* USART LIN break frame length */
#define CTL1_LBLEN(regval) (BIT(5) & ((uint32_t)(regval) << 5))
#define USART_LBLEN_10B CTL1_LBLEN(0) /*!< 10 bits break detection */
#define USART_LBLEN_11B CTL1_LBLEN(1) /*!< 11 bits break detection */
/* USART last bit clock pulse */
#define CTL1_CLEN(regval) (BIT(8) & ((uint32_t)(regval) << 8))
#define USART_CLEN_NONE CTL1_CLEN(0) /*!< clock pulse of the last data bit (MSB) is not output to the CK pin */
#define USART_CLEN_EN CTL1_CLEN(1) /*!< clock pulse of the last data bit (MSB) is output to the CK pin */
/* USART clock phase */
#define CTL1_CPH(regval) (BIT(9) & ((uint32_t)(regval) << 9))
#define USART_CPH_1CK CTL1_CPH(0) /*!< first clock transition is the first data capture edge */
#define USART_CPH_2CK CTL1_CPH(1) /*!< second clock transition is the first data capture edge */
/* USART clock polarity */
#define CTL1_CPL(regval) (BIT(10) & ((uint32_t)(regval) << 10))
#define USART_CPL_LOW CTL1_CPL(0) /*!< steady low value on CK pin */
#define USART_CPL_HIGH CTL1_CPL(1) /*!< steady high value on CK pin */
/* USART stop bits definitions */
#define CTL1_STB(regval) (BITS(12,13) & ((uint32_t)(regval) << 12))
#define USART_STB_1BIT CTL1_STB(0) /*!< 1 bit */
#define USART_STB_2BIT CTL1_STB(2) /*!< 2 bits */
#define USART_STB_1_5BIT CTL1_STB(3) /*!< 1.5 bits */
/* USART data is transmitted/received with the LSB/MSB first */
#define CTL1_MSBF(regval) (BIT(19) & ((uint32_t)(regval) << 19))
#define USART_MSBF_LSB CTL1_MSBF(0) /*!< LSB first */
#define USART_MSBF_MSB CTL1_MSBF(1) /*!< MSB first */
/* USART auto baud rate detection mode bits definitions */
#define CTL1_ABDM(regval) (BITS(21,22) & ((uint32_t)(regval) << 21))
#define USART_ABDM_FTOR CTL1_ABDM(0) /*!< falling edge to rising edge measurement */
#define USART_ABDM_FTOF CTL1_ABDM(1) /*!< falling edge to falling edge measurement */
/* USART IrDA low-power enable */
#define CTL2_IRLP(regval) (BIT(2) & ((uint32_t)(regval) << 2))
#define USART_IRLP_LOW CTL2_IRLP(1) /*!< low-power */
#define USART_IRLP_NORMAL CTL2_IRLP(0) /*!< normal */
/* DMA enable for reception */
#define CTL2_DENR(regval) (BIT(6) & ((uint32_t)(regval) << 6))
#define USART_DENR_ENABLE CTL2_DENR(1) /*!< enable for reception */
#define USART_DENR_DISABLE CTL2_DENR(0) /*!< disable for reception */
/* DMA enable for transmission */
#define CTL2_DENT(regval) (BIT(7) & ((uint32_t)(regval) << 7))
#define USART_DENT_ENABLE CTL2_DENT(1) /*!< enable for transmission */
#define USART_DENT_DISABLE CTL2_DENT(0) /*!< disable for transmission */
/* USART RTS hardware flow control configure */
#define CTL2_RTSEN(regval) (BIT(8) & ((uint32_t)(regval) << 8))
#define USART_RTS_ENABLE CTL2_RTSEN(1) /*!< RTS hardware flow control enabled */
#define USART_RTS_DISABLE CTL2_RTSEN(0) /*!< RTS hardware flow control disabled */
/* USART CTS hardware flow control configure */
#define CTL2_CTSEN(regval) (BIT(9) & ((uint32_t)(regval) << 9))
#define USART_CTS_ENABLE CTL2_CTSEN(1) /*!< CTS hardware flow control enabled */
#define USART_CTS_DISABLE CTL2_CTSEN(0) /*!< CTS hardware flow control disabled */
/* USART one sample bit method configure */
#define CTL2_OSB(regval) (BIT(11) & ((uint32_t)(regval) << 11))
#define USART_OSB_1BIT CTL2_OSB(1) /*!< 1 sample bit */
#define USART_OSB_3BIT CTL2_OSB(0) /*!< 3 sample bits */
/* USART driver enable polarity mode */
#define CTL2_DEP(regval) (BIT(15) & ((uint32_t)(regval) << 15))
#define USART_DEP_HIGH CTL2_DEP(0) /*!< DE signal is active high */
#define USART_DEP_LOW CTL2_DEP(1) /*!< DE signal is active low */
/* USART wakeup mode from deep-sleep mode */
#define CTL2_WUM(regval) (BITS(20,21) & ((uint32_t)(regval) << 20))
#define USART_WUM_ADDR CTL2_WUM(0) /*!< WUF active on address match */
#define USART_WUM_STARTB CTL2_WUM(2) /*!< WUF active on start bit */
#define USART_WUM_RBNE CTL2_WUM(3) /*!< WUF active on RBNE */
/* function declarations */
/* initialization functions */
/* reset USART */
void usart_deinit(uint32_t usart_periph);
/* configure USART baud rate value */
void usart_baudrate_set(uint32_t usart_periph, uint32_t baudval);
/* configure USART parity function */
void usart_parity_config(uint32_t usart_periph, uint32_t paritycfg);
/* configure USART word length */
void usart_word_length_set(uint32_t usart_periph, uint32_t wlen);
/* configure USART stop bit length */
void usart_stop_bit_set(uint32_t usart_periph, uint32_t stblen);
/* USART normal mode communication */
/* enable USART */
void usart_enable(uint32_t usart_periph);
/* disable USART */
void usart_disable(uint32_t usart_periph);
/* configure USART transmitter */
void usart_transmit_config(uint32_t usart_periph, uint32_t txconfig);
/* configure USART receiver */
void usart_receive_config(uint32_t usart_periph, uint32_t rxconfig);
/* USART transmit data function */
void usart_data_transmit(uint32_t usart_periph, uint32_t data);
/* USART receive data function */
uint16_t usart_data_receive(uint32_t usart_periph);
/* data is transmitted/received with the LSB/MSB first */
void usart_data_first_config(uint32_t usart_periph, uint32_t msbf);
/* configure USART inverted */
void usart_invert_config(uint32_t usart_periph, usart_invert_enum invertpara);
/* overrun function is enabled */
void usart_overrun_enable(uint32_t usart_periph);
/* overrun function is disabled */
void usart_overrun_disable(uint32_t usart_periph);
/* configure the USART oversample mode */
void usart_oversample_config(uint32_t usart_periph, uint32_t oversamp);
/* sample bit method configure */
void usart_sample_bit_config(uint32_t usart_periph, uint32_t osb);
/* auto baud rate detection */
/* auto baud rate detection enable */
void usart_autobaud_detection_enable(uint32_t usart_periph);
/* auto baud rate detection disable */
void usart_autobaud_detection_disable(uint32_t usart_periph);
/* auto baud rate detection mode configure */
void usart_autobaud_detection_mode_config(uint32_t usart_periph, uint32_t abdmod);
/* multi-processor communication */
/* enable mute mode */
void usart_mute_mode_enable(uint32_t usart_periph);
/* disable mute mode */
void usart_mute_mode_disable(uint32_t usart_periph);
/* configure wakeup method in mute mode */
void usart_mute_mode_wakeup_config(uint32_t usart_periph, uint32_t wmethod);
/* address detection mode configure */
void usart_address_detection_mode_config(uint32_t usart_periph, uint32_t addmod);
/* configure address of the USART */
void usart_address_config(uint32_t usart_periph, uint8_t addr);
/* enable receiver timeout */
void usart_receiver_timeout_enable(uint32_t usart_periph);
/* disable receiver timeout */
void usart_receiver_timeout_disable(uint32_t usart_periph);
/* configure receiver timeout threshold */
void usart_receiver_timeout_config(uint32_t usart_periph, uint32_t rtimeout);
/* LIN mode communication */
/* LIN mode enable */
void usart_lin_mode_enable(uint32_t usart_periph);
/* LIN mode disable */
void usart_lin_mode_disable(uint32_t usart_periph);
/* LIN break detection length */
void usart_lin_break_dection_length_config(uint32_t usart_periph, uint32_t lblen);
/* half-duplex communication */
/* half-duplex enable */
void usart_halfduplex_enable(uint32_t usart_periph);
/* half-duplex disable */
void usart_halfduplex_disable(uint32_t usart_periph);
/* synchronous communication */
/* clock enable */
void usart_clock_enable(uint32_t usart_periph);
/* clock disable*/
void usart_clock_disable(uint32_t usart_periph);
/* configure USART synchronous mode parameters */
void usart_synchronous_clock_config(uint32_t usart_periph, uint32_t clen, uint32_t cph, uint32_t cpl);
/* smartcard communication */
/* smartcard mode enable */
void usart_smartcard_mode_enable(uint32_t usart_periph);
/* smartcard mode disable */
void usart_smartcard_mode_disable(uint32_t usart_periph);
/* NACK enable in smartcard mode */
void usart_smartcard_mode_nack_enable(uint32_t usart_periph);
/* NACK disable in smartcard mode */
void usart_smartcard_mode_nack_disable(uint32_t usart_periph);
/* guard time value configure in smartcard mode */
void usart_guard_time_config(uint32_t usart_periph, uint32_t guat);
/* block length configure */
void usart_block_length_config(uint32_t usart_periph, uint32_t bl);
/* smartcard auto-retry number configure */
void usart_smartcard_autoretry_config(uint32_t usart_periph, uint32_t scrtnum);
/* IrDA communication */
/* enable IrDA mode */
void usart_irda_mode_enable(uint32_t usart_periph);
/* disable IrDA mode */
void usart_irda_mode_disable(uint32_t usart_periph);
/* configure IrDA low-power */
void usart_irda_lowpower_config(uint32_t usart_periph, uint32_t irlp);
/* configure the peripheral clock prescaler */
void usart_prescaler_config(uint32_t usart_periph, uint32_t psc);
/* hardware flow communication */
/* configure hardware flow control RTS */
void usart_hardware_flow_rts_config(uint32_t usart_periph, uint32_t rtsconfig);
/* configure hardware flow control CTS */
void usart_hardware_flow_cts_config(uint32_t usart_periph, uint32_t ctsconfig);
/* RS485 driver enable */
void usart_rs485_driver_enable(uint32_t usart_periph);
/* RS485 driver disable */
void usart_rs485_driver_disable(uint32_t usart_periph);
/* driver enable assertion time configure */
void usart_driver_assertime_config(uint32_t usart_periph, uint32_t deatime);
/* driver enable de-assertion time configure */
void usart_driver_deassertime_config(uint32_t usart_periph, uint32_t dedtime);
/* configure driver enable polarity mode */
void usart_depolarity_config(uint32_t usart_periph, uint32_t dep);
/* USART DMA */
/* configure USART DMA for reception */
void usart_dma_receive_config(uint32_t usart_periph, uint32_t dmacmd);
/* configure USART DMA for transmission */
void usart_dma_transmit_config(uint32_t usart_periph, uint32_t dmacmd);
/* disable DMA on reception error */
void usart_reception_error_dma_disable(uint32_t usart_periph);
/* enable DMA on reception error */
void usart_reception_error_dma_enable(uint32_t usart_periph);
/* USART be able to wake up the mcu from deep-sleep mode */
void usart_wakeup_enable(uint32_t usart_periph);
/* USART be not able to wake up the mcu from deep-sleep mode */
void usart_wakeup_disable(uint32_t usart_periph);
/* wakeup mode from deep-sleep mode */
void usart_wakeup_mode_config(uint32_t usart_periph, uint32_t wum);
/* flag functions */
/* get flag in STAT register */
FlagStatus usart_flag_get(uint32_t usart_periph, usart_flag_enum flag);
/* clear flag in STAT register */
void usart_flag_clear(uint32_t usart_periph, usart_flag_enum flag);
/* enable USART interrupt */
void usart_interrupt_enable(uint32_t usart_periph, uint32_t inttype);
/* disable USART interrupt */
void usart_interrupt_disable(uint32_t usart_periph, uint32_t inttype);
/* enable USART command */
void usart_command_enable(uint32_t usart_periph, uint32_t cmdtype);
/* get USART interrupt and flag status */
FlagStatus usart_interrupt_flag_get(uint32_t usart_periph, uint32_t int_flag);
/* clear interrupt flag in STAT register */
void usart_interrupt_flag_clear(uint32_t usart_periph, uint32_t flag);
#endif /* GD32F1X0_USART_H */
| 16,367 |
335 | <reponame>Safal08/Hacktoberfest-1
{
"word": "Unconformable",
"definitions": [
"(of rock strata in contact) marking a discontinuity in the geological record, and typically not having the same direction of stratification."
],
"parts-of-speech": "Adjective"
} | 99 |
667 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open("README") as file:
long_description = file.read()
setup(
name="flask-restful-swagger",
version="0.20.2",
url="https://github.com/rantav/flask-restful-swagger",
zip_safe=False,
packages=["flask_restful_swagger"],
package_data={
"flask_restful_swagger": [
"static/*.*",
"static/css/*.*",
"static/images/*.*",
"static/lib/*.*",
"static/lib/shred/*.*",
]
},
description="Extract swagger specs from your flask-restful project",
author="<NAME>",
license="MIT",
long_description=long_description,
install_requires=[
"Jinja2>=2.10.1,<3.0.0",
"Flask-RESTful>=0.3.6",
],
)
| 385 |
369 | <reponame>hubert-thieriot/gee_tools
# coding=utf-8
""" ee.Array helpers """
import ee
def constant2DArray(width, height, value):
""" Create an array of width x height with a fixed value """
cols = ee.List.repeat(value, height)
rows = ee.List.repeat(value, width)
return ee.Array(cols.map(lambda n: rows))
def set2DValue(array, position, value):
""" set the x and y values in a 2-D array """
xpos = ee.Number(ee.List(position).get(0))
ypos = ee.Number(ee.List(position).get(1))
value = ee.Number(value)
alist = ee.Array(array).toList()
row = ee.List(alist.get(ypos))
newrow = row.set(xpos, value)
newlist = alist.set(ypos, newrow)
return ee.Array(newlist)
| 292 |
852 | <reponame>ckamtsikis/cmssw<gh_stars>100-1000
//
//
#include "PhysicsTools/PatUtils/interface/TriggerHelper.h"
#include "DataFormats/Common/interface/AssociativeIterator.h"
using namespace pat;
using namespace pat::helper;
// Methods
// Get a reference to the trigger objects matched to a certain physics object given by a reference for a certain matcher module
// ... by resulting association
TriggerObjectRef TriggerMatchHelper::triggerMatchObject(const reco::CandidateBaseRef& candRef,
const TriggerObjectMatch* matchResult,
const edm::Event& event,
const TriggerEvent& triggerEvent) const {
if (matchResult) {
auto it = edm::makeAssociativeIterator<reco::CandidateBaseRef>(*matchResult, event);
auto itEnd = it.end();
while (it != itEnd) {
if (it->first.isNonnull() && it->second.isNonnull() && it->second.isAvailable()) {
if (it->first.id() == candRef.id() && it->first.key() == candRef.key()) {
return TriggerObjectRef(it->second);
}
}
++it;
}
}
return TriggerObjectRef();
}
// ... by matcher module label
TriggerObjectRef TriggerMatchHelper::triggerMatchObject(const reco::CandidateBaseRef& candRef,
const std::string& labelMatcher,
const edm::Event& event,
const TriggerEvent& triggerEvent) const {
return triggerMatchObject(candRef, triggerEvent.triggerObjectMatchResult(labelMatcher), event, triggerEvent);
}
// Get a table of references to all trigger objects matched to a certain physics object given by a reference
TriggerObjectMatchMap TriggerMatchHelper::triggerMatchObjects(const reco::CandidateBaseRef& candRef,
const edm::Event& event,
const TriggerEvent& triggerEvent) const {
TriggerObjectMatchMap theContainer;
const std::vector<std::string> matchers(triggerEvent.triggerMatchers());
for (size_t iMatch = 0; iMatch < matchers.size(); ++iMatch) {
theContainer[matchers.at(iMatch)] = triggerMatchObject(candRef, matchers.at(iMatch), event, triggerEvent);
}
return theContainer;
}
// Get a vector of references to the phyics objects matched to a certain trigger object given by a reference for a certain matcher module
// ... by resulting association
reco::CandidateBaseRefVector TriggerMatchHelper::triggerMatchCandidates(const TriggerObjectRef& objectRef,
const TriggerObjectMatch* matchResult,
const edm::Event& event,
const TriggerEvent& triggerEvent) const {
reco::CandidateBaseRefVector theCands;
if (matchResult) {
auto it = edm::makeAssociativeIterator<reco::CandidateBaseRef>(*matchResult, event);
auto itEnd = it.end();
while (it != itEnd) {
if (it->first.isNonnull() && it->second.isNonnull() && it->second.isAvailable()) {
if (it->second == objectRef) {
theCands.push_back(it->first);
}
}
++it;
}
}
return theCands;
}
// ... by matcher module label
reco::CandidateBaseRefVector TriggerMatchHelper::triggerMatchCandidates(const TriggerObjectRef& objectRef,
const std::string& labelMatcher,
const edm::Event& event,
const TriggerEvent& triggerEvent) const {
return triggerMatchCandidates(objectRef, triggerEvent.triggerObjectMatchResult(labelMatcher), event, triggerEvent);
}
// Get a vector of references to the phyics objects matched to a certain trigger object given by a collection and index for a certain matcher module
// ... by resulting association
reco::CandidateBaseRefVector TriggerMatchHelper::triggerMatchCandidates(
const edm::Handle<TriggerObjectCollection>& trigCollHandle,
const size_t iTrig,
const TriggerObjectMatch* matchResult,
const edm::Event& event,
const TriggerEvent& triggerEvent) const {
return triggerMatchCandidates(TriggerObjectRef(trigCollHandle, iTrig), matchResult, event, triggerEvent);
}
// ... by matcher module label
reco::CandidateBaseRefVector TriggerMatchHelper::triggerMatchCandidates(
const edm::Handle<TriggerObjectCollection>& trigCollHandle,
const size_t iTrig,
const std::string& labelMatcher,
const edm::Event& event,
const TriggerEvent& triggerEvent) const {
return triggerMatchCandidates(TriggerObjectRef(trigCollHandle, iTrig),
triggerEvent.triggerObjectMatchResult(labelMatcher),
event,
triggerEvent);
}
| 2,266 |
1,609 | package com.mossle.humantask.listener;
import javax.annotation.Resource;
import com.mossle.api.delegate.DelegateConnector;
import com.mossle.humantask.persistence.domain.TaskInfo;
public class DelegateHumanTaskListener implements HumanTaskListener {
private DelegateConnector delegateConnector;
@Override
public void onCreate(TaskInfo taskInfo) {
// 自动委托
String humanTaskId = Long.toString(taskInfo.getId());
String assignee = taskInfo.getAssignee();
String processDefinitionId = taskInfo.getProcessDefinitionId();
String tenantId = taskInfo.getTenantId();
String attorney = delegateConnector.findAttorney(assignee,
processDefinitionId, taskInfo.getCode(), tenantId);
if (attorney != null) {
taskInfo.setOwner(assignee);
taskInfo.setAssignee(attorney);
// new DelegateTaskCmd(delegateTask.getId(), attorney).execute(Context
// .getCommandContext());
delegateConnector.recordDelegate(assignee, attorney, humanTaskId,
tenantId);
}
}
@Override
public void onComplete(TaskInfo taskInfo) throws Exception {
}
@Resource
public void setDelegateConnector(DelegateConnector delegateConnector) {
this.delegateConnector = delegateConnector;
}
}
| 517 |
5,937 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//-----------------------------------------------------------------------------
//
//
// Description:
//
// Contains implementation of CSnappingFrame class
//
#include "precomp.hpp"
MtDefine(CGuidelineCollection, MILRender, "CGuidelineCollection");
MtDefine(CSnappingFrame, MILRender, "CSnappingFrame");
//=========================================================================
//
// class CGuidelineCollection
//
//=========================================================================
//+------------------------------------------------------------------------
//
// Member:
// static CGuidelineCollection::Create
//
// Synopsis:
// Create the instance of CStaticGuidelineCollection or
// CDynamicGuidelineCollection, depending on "fDynamic" argument.
//
//-------------------------------------------------------------------------
HRESULT CGuidelineCollection::Create(
UINT16 uCountX,
UINT16 uCountY,
__in_ecount(uCountX + uCountY) const float *prgData,
bool fDynamic,
__deref_out_ecount(1) CGuidelineCollection **ppGuidelineCollection
)
{
return fDynamic
? CDynamicGuidelineCollection::Create(
uCountX,
uCountY,
prgData,
ppGuidelineCollection
)
: CStaticGuidelineCollection::Create(
uCountX,
uCountY,
prgData,
ppGuidelineCollection
)
;
}
//+------------------------------------------------------------------------
//
// Member:
// static CGuidelineCollection::CreateFromDoubles
//
// Synopsis:
// Create the instance of CStaticGuidelineCollection or
// CDynamicGuidelineCollection, depending on "fDynamic" argument.
//
//-------------------------------------------------------------------------
HRESULT CGuidelineCollection::CreateFromDoubles(
UINT16 uCountX,
UINT16 uCountY,
__in_ecount_opt(uCountX) const double *prgDataX,
__in_ecount_opt(uCountY) const double *prgDataY,
BOOL fDynamic,
__deref_out_ecount(1) CGuidelineCollection **ppGuidelineCollection
)
{
return fDynamic
? CDynamicGuidelineCollection::CreateFromDoubles(
uCountX,
uCountY,
prgDataX,
prgDataY,
ppGuidelineCollection
)
: CStaticGuidelineCollection::CreateFromDoubles(
uCountX,
uCountY,
prgDataX,
prgDataY,
ppGuidelineCollection
)
;
}
//=========================================================================
//
// class CStaticGuidelineCollection
//
//=========================================================================
//+------------------------------------------------------------------------
//
// Member:
// static CStaticGuidelineCollection::Create
//
// Synopsis:
// Create the instance of CStaticGuidelineCollection, filled with given data.
// Ensure that coordinate arrays are given in increasing order.
// If not so, reject with WGXERR_MALFORMED_GUIDELINE_DATA.
//
//-------------------------------------------------------------------------
HRESULT
CStaticGuidelineCollection::Create(
UINT16 uCountX,
UINT16 uCountY,
__in_ecount(uCountX + uCountY) const float *prgData,
__deref_out_ecount(1) CGuidelineCollection **ppGuidelineCollection
)
{
HRESULT hr = S_OK;
CStaticGuidelineCollection *pThis = NULL;
UINT32 uCount = static_cast<UINT32>(uCountX) + static_cast<UINT32>(uCountY);
Assert(uCount); // Should not create empty collections
// Create the instance with data memory attached
{
void *pMem = WPFAlloc(
ProcessHeap,
Mt(CGuidelineCollection),
sizeof(CStaticGuidelineCollection) + sizeof(float) * uCount
);
IFCOOM(pMem);
pThis = new(pMem) CStaticGuidelineCollection(uCountX, uCountY);
}
if (uCountX)
{
IFC(pThis->StoreRange(0, uCountX, prgData));
}
if (uCountY)
{
IFC(pThis->StoreRange(uCountX, uCountY, prgData + uCountX));
}
*ppGuidelineCollection = pThis;
pThis = NULL;
Cleanup:
delete pThis;
return hr;
}
//+------------------------------------------------------------------------
//
// Member:
// static CStaticGuidelineCollection::CreateFromDoubles
//
// Synopsis:
// Create the instance of CStaticGuidelineCollection, filled with given data.
// Ensure that coordinate arrays are given in increasing order.
// If not so, reject with WGXERR_MALFORMED_GUIDELINE_DATA.
//
//-------------------------------------------------------------------------
HRESULT
CStaticGuidelineCollection::CreateFromDoubles(
UINT16 uCountX,
UINT16 uCountY,
__in_ecount_opt(uCountX) const double *prgDataX,
__in_ecount_opt(uCountY) const double *prgDataY,
__deref_out_ecount(1) CGuidelineCollection **ppGuidelineCollection
)
{
HRESULT hr = S_OK;
CStaticGuidelineCollection *pThis = NULL;
UINT32 uCount = static_cast<UINT32>(uCountX) + static_cast<UINT32>(uCountY);
Assert(uCount > 0); // Should not create empty collections
// Create the instance with data memory attached
{
void *pMem = WPFAlloc(
ProcessHeap,
Mt(CGuidelineCollection),
sizeof(CStaticGuidelineCollection) + sizeof(float) * uCount
);
IFCOOM(pMem);
pThis = new(pMem) CStaticGuidelineCollection(uCountX, uCountY);
}
if (uCountX)
{
IFC(pThis->StoreRangeFromDoubles(0, uCountX, prgDataX));
}
if (uCountY)
{
IFC(pThis->StoreRangeFromDoubles(uCountX, uCountY, prgDataY));
}
*ppGuidelineCollection = pThis;
pThis = NULL;
Cleanup:
delete pThis;
return hr;
}
//+------------------------------------------------------------------------
//
// Member:
// CStaticGuidelineCollection::StoreRange
//
// Synopsis:
// Private helper for CStaticGuidelineCollection::Create().
// Handles the range of guideline coordinate array, either X or Y.
//
//-------------------------------------------------------------------------
HRESULT
CStaticGuidelineCollection::StoreRange(
UINT uIndex,
UINT uCount,
__in_ecount(uCount) const float *prgSrc
)
{
Assert(uCount > 0);
HRESULT hr = S_OK;
float *prgDst = Data() + uIndex;
// check prgSrc[0] for NaN
if (prgSrc[0] != prgSrc[0])
{
IFC(WGXERR_MALFORMED_GUIDELINE_DATA);
}
prgDst[0] = prgSrc[0];
for (UINT i = 1; i < uCount; i++)
{
// Check for increasing order and NaN.
if (!(prgSrc[i-1] <= prgSrc[i]))
{
IFC(WGXERR_MALFORMED_GUIDELINE_DATA);
}
prgDst[i] = prgSrc[i];
}
Cleanup:
return hr;
}
//+------------------------------------------------------------------------
//
// Member:
// CStaticGuidelineCollection::StoreRangeFromDoubles
//
// Synopsis:
// Private helper for CStaticGuidelineCollection::CreateFromDoubles().
// Handles the range of guideline coordinate array, either X or Y.
//
//-------------------------------------------------------------------------
HRESULT
CStaticGuidelineCollection::StoreRangeFromDoubles(
UINT uIndex,
UINT uCount,
__in_ecount(uCount) const double *prgSrc
)
{
Assert(uCount > 0);
HRESULT hr = S_OK;
float *prgDst = Data() + uIndex;
// check prgSrc[0] for NaN
if (prgSrc[0] != prgSrc[0])
{
IFC(WGXERR_MALFORMED_GUIDELINE_DATA);
}
prgDst[0] = static_cast<float>(prgSrc[0]);
for (UINT i = 1; i < uCount; i++)
{
// Check for increasing order and NaN.
if (!(prgSrc[i-1] <= prgSrc[i]))
{
IFC(WGXERR_MALFORMED_GUIDELINE_DATA);
}
prgDst[i] = static_cast<float>(prgSrc[i]);
}
Cleanup:
return hr;
}
//=========================================================================
//
// class CDynamicGuidelineCollection
//
//=========================================================================
//+------------------------------------------------------------------------
//
// Member:
// static CDynamicGuidelineCollection::Create
//
// Synopsis:
// Create the instance of CDynamicGuidelineCollection, filled with given data.
// Ensure that coordinate arrays are given in increasing order.
// If not so, reject with WGXERR_MALFORMED_GUIDELINE_DATA.
//
//-------------------------------------------------------------------------
HRESULT CDynamicGuidelineCollection::Create(
UINT16 uCountX,
UINT16 uCountY,
__in_ecount(uCountX + uCountY) const float *prgData,
__deref_out_ecount(1) CGuidelineCollection **ppGuidelineCollection
)
{
HRESULT hr = S_OK;
CDynamicGuidelineCollection *pThis = NULL;
UINT16 uCountXPairs = uCountX >> 1;
UINT16 uCountYPairs = uCountY >> 1;
UINT32 uCount = static_cast<UINT32>(uCountXPairs) + static_cast<UINT32>(uCountYPairs);
Assert(uCount); // Should not create empty collections
// Create the instance with data memory attached
{
void *pMem = WPFAlloc(
ProcessHeap,
Mt(CGuidelineCollection),
sizeof(CDynamicGuidelineCollection) + sizeof(CDynamicGuideline) * uCount
);
IFCOOM(pMem);
pThis = new(pMem) CDynamicGuidelineCollection(uCountXPairs, uCountYPairs);
}
if (uCountXPairs)
{
IFC(pThis->StoreRange(0, uCountXPairs, prgData));
}
if (uCountYPairs)
{
IFC(pThis->StoreRange(uCountXPairs, uCountYPairs, prgData + uCountX));
}
*ppGuidelineCollection = pThis;
pThis = NULL;
Cleanup:
delete pThis;
return hr;
}
//+------------------------------------------------------------------------
//
// Member:
// static CDynamicGuidelineCollection::CreateFromDoubles
//
// Synopsis:
// Create the instance of CDynamicGuidelineCollection, filled with given data.
// Ensure that coordinate arrays are given in increasing order.
//
//-------------------------------------------------------------------------
HRESULT CDynamicGuidelineCollection::CreateFromDoubles(
UINT16 uCountX,
UINT16 uCountY,
__in_ecount_opt(uCountX) const double *prgDataX,
__in_ecount_opt(uCountY) const double *prgDataY,
__deref_out_ecount(1) CGuidelineCollection **ppGuidelineCollection
)
{
HRESULT hr = S_OK;
CDynamicGuidelineCollection *pThis = NULL;
UINT16 uCountXPairs = uCountX >> 1;
UINT16 uCountYPairs = uCountY >> 1;
UINT32 uCount = static_cast<UINT32>(uCountXPairs) + static_cast<UINT32>(uCountYPairs);
Assert(uCount); // Should not create empty collections
// Create the instance with data memory attached
{
void *pMem = WPFAlloc(
ProcessHeap,
Mt(CGuidelineCollection),
sizeof(CDynamicGuidelineCollection) + sizeof(CDynamicGuideline) * uCount
);
IFCOOM(pMem);
pThis = new(pMem) CDynamicGuidelineCollection(uCountXPairs, uCountYPairs);
}
if (uCountXPairs)
{
IFC(pThis->StoreRangeFromDoubles(0, uCountXPairs, prgDataX));
}
if (uCountYPairs)
{
IFC(pThis->StoreRangeFromDoubles(uCountXPairs, uCountYPairs, prgDataY));
}
*ppGuidelineCollection = pThis;
pThis = NULL;
Cleanup:
delete pThis;
return hr;
}
//+------------------------------------------------------------------------
//
// Member:
// CDynamicGuidelineCollection::StoreRange
//
// Synopsis:
// Private helper for CDynamicGuidelineCollection::Create().
// Handles the range of guideline coordinate array, either X or Y.
//
//-------------------------------------------------------------------------
HRESULT
CDynamicGuidelineCollection::StoreRange(
UINT16 uIndex,
UINT16 uCount,
__in_ecount(2*uCount) const float *prgSrc
)
{
Assert(uCount > 0);
HRESULT hr = S_OK;
CDynamicGuideline *prgDst = Data() + uIndex;
// check prgSrc[0] && prgSrc[1] for NaNs
if (prgSrc[0] != prgSrc[0] ||
prgSrc[1] != prgSrc[1])
{
IFC(WGXERR_MALFORMED_GUIDELINE_DATA);
}
new (&prgDst[0]) CDynamicGuideline(prgSrc[0], prgSrc[1]);
for (UINT16 k = 1; k < uCount; k++)
{
UINT i = 2*k;
// Check for increasing order and NaN.
if (!(prgSrc[i-2] + prgSrc[i-1] <= prgSrc[i] + prgSrc[i]))
{
IFC(WGXERR_MALFORMED_GUIDELINE_DATA);
}
new (&prgDst[k]) CDynamicGuideline(prgSrc[i], prgSrc[i+1]);
}
Cleanup:
return hr;
}
//+------------------------------------------------------------------------
//
// Member:
// CDynamicGuidelineCollection::StoreRangeFromDoubles
//
// Synopsis:
// Private helper for CDynamicGuidelineCollection::CreateFromDoubles().
// Handles the range of guideline coordinate array, either X or Y.
//
//-------------------------------------------------------------------------
HRESULT
CDynamicGuidelineCollection::StoreRangeFromDoubles(
UINT16 uIndex,
UINT16 uCount,
__in_ecount(2*uCount) const double *prgSrc
)
{
Assert(uCount > 0);
HRESULT hr = S_OK;
CDynamicGuideline *prgDst = Data() + uIndex;
// check prgSrc[0] and prgSrc[1] for NaNs
if (prgSrc[0] != prgSrc[0] ||
prgSrc[1] != prgSrc[1])
{
IFC(WGXERR_MALFORMED_GUIDELINE_DATA);
}
new (&prgDst[0]) CDynamicGuideline(
static_cast<float>(prgSrc[0]),
static_cast<float>(prgSrc[1])
);
for (UINT16 k = 1; k < uCount; k++)
{
UINT i = 2*k;
// Check for increasing order and NaN.
if (!(prgSrc[i-2] + prgSrc[i-1] <= prgSrc[i] + prgSrc[i]))
{
IFC(WGXERR_MALFORMED_GUIDELINE_DATA);
}
new (&prgDst[k]) CDynamicGuideline(
static_cast<float>(prgSrc[i]),
static_cast<float>(prgSrc[i+1])
);
}
Cleanup:
return hr;
}
//=========================================================================
//
// class CSnappingFrame
//
//=========================================================================
//+------------------------------------------------------------------------
//
// Member:
// static CSnappingFrame::PushFrame
//
// Synopsis:
// Create an instance of one of CSnappingFrame derivatives and attach
// it to frame stack.
//
// When given pGuidelineCollection == NULL then empty frame is created.
//
// Given transformation is checked for being only scale and translate.
// If not so, we also create empty frame.
//
// Otherwise, the size of arrays in pGuidelineCollection are inspected.
// When possible, optimized transform-based snapping frame is used.
//
// *****
//
// The argument "fNeedMoreCycles" makes sense for dynamic guidelines only.
// Dynamic guideline collection might happen to be in progress of moving
// from animated (non-snapped) position to stabilized (snapped) one.
// To complete the transition, this routine should be called, maybe several
// times, even if nothing changes in the scene. Caller is reponsible for
// scheduling additional rendering pass after getting fNeedMoreCycles = true.
//
//-------------------------------------------------------------------------
HRESULT
CSnappingFrame::PushFrame(
__inout_ecount_opt(1) CGuidelineCollection *pGuidelineCollection,
__in_ecount(1) const CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::PageInPixels> &mat,
UINT uCurrentTime,
__out_ecount(1) bool & fNeedMoreCycles,
bool fSuppressAnimation,
__deref_inout_ecount(1) CSnappingFrame **ppSnappingStack
)
{
Assert(ppSnappingStack);
HRESULT hr = S_OK;
UINT16 uCountX = 0;
UINT16 uCountY = 0;
CStaticGuidelineCollection *pStaticGuidelineCollection = NULL;
CDynamicGuidelineCollection *pDynamicGuidelineCollection = NULL;
fNeedMoreCycles = false;
if (pGuidelineCollection != NULL)
{
pStaticGuidelineCollection = pGuidelineCollection->CastToStatic();
pDynamicGuidelineCollection = pGuidelineCollection->CastToDynamic();
}
// Check whether we need snapping.
BOOL fTransformIsScaleAndTranslate = mat.IsTranslateOrScale();
//
// When fSuppressAnimation is given "true" when guideline set
// can be involved in several scene paths. For now we can't
// handle multiple path scenario with animation detection, because
// it requires storing per-path data (m_uTimeAndPhase, m_rLastGivenCoord
// and m_rLastOffset in CDynamicGuideline) while we have no room
// to keep these data (i.e. we dont have a way to identify current
// path and associate it with some storage that persists from frame to
// frame). Consequent calls to SubpixelAnimationCorrection()
// with different transformation matrices might be accepted as animation
// and cause infinite scene re-rendering.
//
// We should consider ways to support multiple path scenario.
// For now, we use fSuppressAnimation to prohibit subpixel animation
// correction, as a workaround.
//
if (pDynamicGuidelineCollection && !fSuppressAnimation)
{
//
// When current transformation is not not only scale and translate
// (i.e. involves rotation or skew), pixel snapping does not make sense.
// We should not call SubpixelAnimationCorrection() but we need
// to notify guideline collection that this case has been happened
// so that it'll remember the history proper way.
if (fTransformIsScaleAndTranslate)
{
pDynamicGuidelineCollection->SubpixelAnimationCorrection(mat, uCurrentTime, fNeedMoreCycles);
}
else
{
pDynamicGuidelineCollection->NotifyNonSnappableState(uCurrentTime);
}
}
if (pGuidelineCollection && fTransformIsScaleAndTranslate)
{
uCountX = pGuidelineCollection->CountX();
uCountY = pGuidelineCollection->CountY();
}
if (uCountX == 0 && uCountY == 0)
{
// handle empty frame push
IFC( CSnappingFrameEmpty::PushFrame(ppSnappingStack) );
}
else
{
// Allocate memory slot for the instance of CSnappingFrame, followed by:
// float GuidesX[uCountX];
// float SnapsX[uCountX];
// float GuidesY[uCountY];
// float SnapsY[uCountY];
UINT32 uCount = static_cast<UINT32>(uCountX) + static_cast<UINT32>(uCountY);
void *pMem = WPFAlloc(
ProcessHeap,
Mt(CSnappingFrame),
sizeof(CSnappingFrame) + sizeof(float) * uCount * 2
);
IFCOOM(pMem);
{
// Create the instance
CSnappingFrame *pThis =
new(pMem) CSnappingFrame(uCountX, uCountY);
// Hook up the instance to the stack list
pThis->HookupToStack(ppSnappingStack);
// Populate instance with data
if (pStaticGuidelineCollection)
{
pThis->PushFrameStatic(
pStaticGuidelineCollection,
mat
);
}
else
{
// We should not get here with NULLs in both
// pStaticGuidelineCollection and pDynamicGuidelineCollection.
Assert(pDynamicGuidelineCollection);
pThis->PushFrameDynamic(
pDynamicGuidelineCollection,
fSuppressAnimation,
mat
);
}
#if DBG
{
// snapping offsets should never exceed 1 pixel
float const *prgOffsetsX = pThis->GuidesX() + pThis->m_uCountX;
for (UINT i = 0; i < pThis->m_uCountX; i++)
{
Assert(fabs(prgOffsetsX[i]) <= 1.f);
}
float const *prgOffsetsY = pThis->GuidesY() + pThis->m_uCountY;
for (UINT i = 0; i < pThis->m_uCountY; i++)
{
Assert(fabs(prgOffsetsY[i]) <= 1.f);
}
}
#endif
}
}
Cleanup:
RRETURN(hr);
}
//+------------------------------------------------------------------------
//
// Member:
// static CSnappingFrame::PopFrame
//
// Synopsis:
// Undo PushFrame().
//
//-------------------------------------------------------------------------
void
CSnappingFrame::PopFrame(
__deref_inout_ecount(1) CSnappingFrame **ppSnappingStack
)
{
Assert(ppSnappingStack);
CSnappingFrame *pCurrentFrame = *ppSnappingStack;
if (pCurrentFrame)
{
if (pCurrentFrame->IsEmpty())
{
CSnappingFrameEmpty *pFrameEmpty = pCurrentFrame->CastToEmpty();
if (--pFrameEmpty->m_uIdlePushCount)
return;
}
pCurrentFrame->UnhookFromStack(ppSnappingStack);
delete pCurrentFrame;
}
}
//+------------------------------------------------------------------------
//
// Member:
// static CSnappingFrame::StoreRangeStatic
//
// Synopsis:
// Helper for CSnappingFrame::PushFrame(), see comments there.
//
//-------------------------------------------------------------------------
void
CSnappingFrame::StoreRangeStatic(
__out_ecount(2*uCount) float *prgDst,
__in_ecount(uCount) const float *prgSrc,
__range(>=, 1) UINT16 uCount,
float rScale,
float rOffset
)
{
// Take care of increasing order:
// reverse the array if given rScale is negative.
int iStep = 1;
const float *pSrc = prgSrc;
if (rScale < 0)
{
iStep = -1;
pSrc += (uCount - 1);
}
for (UINT16 i = 0; i < uCount; i++, pSrc += iStep)
{
float rCoordLocal = *pSrc;
float rCoordDevice = rScale*rCoordLocal + rOffset;
float rSnap = CFloatFPU::OffsetToRounded(rCoordDevice);
prgDst[ i] = rCoordDevice;
prgDst[i + uCount] = rSnap;
}
}
//+------------------------------------------------------------------------
//
// Member:
// static CSnappingFrame::StoreRangeDynamic
//
// Synopsis:
// Helper for CSnappingFrame::PushFrame(), see comments there.
//
//-------------------------------------------------------------------------
void
CSnappingFrame::StoreRangeDynamic(
__out_ecount(2*uCount) float *prgDst,
__range(>=, 1) UINT16 uCount,
__in_ecount(uCount) const CDynamicGuideline *prgSrc,
bool fSuppressAnimation,
float rScale,
float rOffset
)
{
// Take care of increasing order:
// reverse the array if given rScale is negative.
int iStep = 1;
const CDynamicGuideline *pSrc = prgSrc;
if (rScale < 0)
{
iStep = -1;
pSrc += (uCount - 1);
}
for (UINT i = 0; i < uCount; i++, pSrc += iStep)
{
const CDynamicGuideline &guideline = *pSrc;
float rLeading, rLeadingSnappingOffset;
if (fSuppressAnimation)
{
//
// Use untransformed coordinate in local space that's
// same for all the usages in multiple path scenario.
// Generate snapping offset right here as we do
// for static guidelines.
//
rLeading = guideline.GetLocalCoordinate() * rScale + rOffset;
rLeadingSnappingOffset = CFloatFPU::OffsetToRounded(rLeading);
}
else
{
//
// Use coordinate that's transformed to device space, and
// snapping offset that's possibly affected with subpixel
// animation. This works for only one path.
//
rLeading = guideline.GetGivenCoordinate();
rLeadingSnappingOffset = guideline.GetSnappingOffset();
}
float rShift = guideline.GetShift() * rScale;
float rShiftSnappingOffset = CFloatFPU::OffsetToRounded(rShift);
//
// Calculate guideline location in device space.
// It is composed of the coordinate of leading guideline
// and the shift from leading to driven.
//
float rDriven = rLeading + rShift;
//
// Calculate snapping offset that will affect all the points in the area
// surrounding the guideline. It is composed of the snapping offset for leading
// guideline and the offset for rShift.
//
float rDrivenSnappingOffset = rLeadingSnappingOffset + rShiftSnappingOffset;
// When there is no animation,
// rLeading + rLeadingSnappingOffset = integer
// and
// rShift + rShiftSnappingOffset = integer
// so that
// rDriven + rDrivenSnappingOffset = integer.
//
// Note that
// rLeading + rLeadingSnappingOffset = Round(rLeading)
// and
// rShift + rShiftSnappingOffset = Round(rShift)
// but
// rDriven + rDrivenSnappingOffset != Round(rDriven).
//
// The value of rDrivenSnappingOffset can reach 1 pixel, negative or positive.
// This is the cost that we pay for desired "gap stabilization".
//
// Example: text + decorator (say, underline).
//
// When rendering the text, we use the guideline with leading coordinate
// on text baseline and zero shift. So leading and driven coincide, and
// text baseline goes to the pixel boundary.
//
// When rendering the decorator, we use another guideline that has same
// leading coordinate as for text, but with some nonzero shift that's
// the desired gap between text baseline and decorator's edge.
//
// We need the edge of the decorator to be on pixel boundary also.
// The calculation below guarantee that
// actualGap = Round(givenGap)
// regardless of fractional parts of non-snapped positions for text and
// decorator.
//
// Animation will affect rLeadingSnappingOffset so that both text baseline
// and decorator's edge will be blurred; however the gap will not be affected.
//
// Pack guideline location and snapping offset that will be used
// in CSnappingFrame::SnapPoint for snapping points of 2d primitives.
//
prgDst[ i] = rDriven;
prgDst[uCount + i] = rDrivenSnappingOffset;
}
}
//+------------------------------------------------------------------------
//
// Member:
// CSnappingFrame::SnapPoint
//
// Synopsis:
// Do pixel snapping for given point.
//
// We look for the pair of vertical and horizontal guidelines that are
// closest to the point, and use the offsets corresponding to these
// guidelines to adjust the point.
//
//-------------------------------------------------------------------------
void
CSnappingFrame::SnapPoint(
__inout_ecount(1) MilPoint2F &point
)
{
SnapCoordinate(point.X, m_uCountX, GuidesX());
SnapCoordinate(point.Y, m_uCountY, GuidesY());
}
//+------------------------------------------------------------------------
//
// Member:
// static CSnappingFrame::SnapCoordinate
//
// Synopsis:
// Helper for CSnappingFrame::SnapPoint().
// Handles either X or Y coordinate represented
// by argument 'z'.
//
// This function executes the binary search algorithm
// to detect guideline which coordinate is closest to
// given coordinate 'z'. Then it changes 'z' by adding
// the offset value precalculated for this guideline.
//
// Guideline coordinates and offsets are packed into
// single array prgData[2*uCount]. First uCount values
// are guideline coordinates that follow in increasing order:
// prgData[i] <= prgData[j] when i < j.
//
// Remaining uCount values are guideline offsets.
// Offsets follows in the same order as coordinales, so that
// for guideline indexed by 'i' coordinate lays in prgData[i]
// and offset resides in prgData[uCount+i].
//
//-------------------------------------------------------------------------
void
CSnappingFrame::SnapCoordinate(
__inout_ecount(1) float &z,
UINT uCount,
__in_ecount(2*uCount) const float* prgData
)
{
if (uCount == 0) return;
//
// Following code uses indices 'a' and 'b' to specify
// the range in given data array. At any moment 'z'
// lays in this range:
// prgData[a] <= z <= prgData[b].
// The search procedure splits the range (a,b) into ranges
// (a,c) and (c,b) then chooses one of these parts that contains z.
// Variables va, vb and vc are the values fetched from data array,
// so that vi = prgData[i].
//
UINT a = 0;
float va = prgData[0];
// Check input coordinate value and array size.
// If the value is less than prgData[0] then guideline #0 is
// closest, as far as given data are sorted and prgData[0] is
// minimum of prgData[i].
// We also need not search when there is only one guideline in array.
if (uCount > 1 && z > va)
{
UINT b = uCount-1;
float vb = prgData[b];
// Check opposite end of range. If given 'z' is greater
// than maximum guideline coordinate prgData[uCount-1] then use
// the offset of this guideline.
if (z > vb)
{
a = b;
}
else
{
// Apply binary search algorithm.
// It will move indices 'a' and 'b' toward one another
// so eventually the condition below will stop looping.
while (b - a > 1)
{
// Split the range (a,b) by new index 'c'.
UINT c = (a + b) >> 1;
float vc = prgData[c];
// Look if 'z' lays in (a,c) or (c,b).
if (z > vc)
{
// 'z' belongs to the range (c,b);
// We are interested in this range only;
// replace (a,b) with (c,b) and repeat.
a = c;
va = vc;
}
else
{
// 'z' belongs to the range (a,c);
// We are interested in this range only;
// replace (a,b) with (a,c) and repeat.
b = c;
vb = vc;
}
}
// We've reached the minimal range (a,b) represented
// by neighboring guidelines, i.e. b == a+1.
// Now we need to choose which one is closer to given 'z'.
if (vb - z < z - va)
{
// The guideline 'b' is closer; replace 'a' with 'b'
// and allow code below to execute snapping.
a = b;
}
}
}
// Apply the offset corresponding to guideline indexed by 'a'.
float offset = prgData[a + uCount];
z += offset;
}
//+------------------------------------------------------------------------
//
// Member:
// CSnappingFrame::SnapTransform
//
// Synopsis:
// Performance optimization for simple guideline collection
// that has not more than one vertical and one horizontal
// guideline. Instead of handling separate points, we
// are correcting the matrix transform that used for all the points.
//
//-------------------------------------------------------------------------
void
CSnappingFrame::SnapTransform(
__inout_ecount(1) CBaseMatrix &mat
)
{
Assert(IsSimple());
if (m_uCountX)
{
mat._41 += GuidesX()[m_uCountX];
}
if (m_uCountY)
{
mat._42 += GuidesY()[m_uCountY];
}
}
//+------------------------------------------------------------------------
//
// Member:
// static CSnappingFrameEmpty::PushFrame
//
// Synopsis:
// Helper for CSnappingFrame::PushFrame().
//
//-------------------------------------------------------------------------
HRESULT
CSnappingFrameEmpty::PushFrame(
__deref_opt_inout_ecount(1) CSnappingFrame **ppSnappingStack
)
{
HRESULT hr = S_OK;
CSnappingFrame *pCurrentFrame = *ppSnappingStack;
if (pCurrentFrame == NULL)
{
// Stack is empty, do nothing.
// We don't care about counting the amount of
// idle pushes.
}
else if (pCurrentFrame->IsEmpty())
{
// We already have an instance of CSnappingFrameEmpty
// on the top of the stack.
// Don't allocate new one, just increase counter.
CSnappingFrameEmpty *pEmptyFrame = pCurrentFrame->CastToEmpty();
pEmptyFrame->m_uIdlePushCount++;
}
else
{
pCurrentFrame = new CSnappingFrameEmpty;
IFCOOM(pCurrentFrame);
// hook up this entry to the stack list
pCurrentFrame->HookupToStack(ppSnappingStack);
}
Cleanup:
return hr;
}
//+------------------------------------------------------------------------
//
// Member:
// CSnappingFrame::PushFrameStatic
//
// Synopsis:
// Helper for CSnappingFrame::PushFrame().
// Populates frame with data taken from static guideline collection.
//
//-------------------------------------------------------------------------
void
CSnappingFrame::PushFrameStatic(
__inout_ecount(1) CStaticGuidelineCollection *pGuidelineCollection,
__in_ecount(1) const CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::PageInPixels> &mat
)
{
Assert(pGuidelineCollection);
Assert(m_uCountX == pGuidelineCollection->CountX());
Assert(m_uCountY == pGuidelineCollection->CountY());
if (m_uCountX)
{
StoreRangeStatic(GuidesX(), pGuidelineCollection->GuidesX(), m_uCountX, mat._11, mat._41);
}
if (m_uCountY)
{
StoreRangeStatic(GuidesY(), pGuidelineCollection->GuidesY(), m_uCountY, mat._22, mat._42);
}
}
//+------------------------------------------------------------------------
//
// Member:
// CSnappingFrame::PushFrameDynamic
//
// Synopsis:
// Helper for CSnappingFrame::PushFrame().
// Populates frame with data taken from dynamic guideline collection.
//
//-------------------------------------------------------------------------
void
CSnappingFrame::PushFrameDynamic(
__inout_ecount(1) CDynamicGuidelineCollection *pGuidelineCollection,
bool fSuppressAnimation,
__in_ecount(1) const CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::PageInPixels> &mat
)
{
Assert(pGuidelineCollection);
Assert(m_uCountX == pGuidelineCollection->CountX());
Assert(m_uCountY == pGuidelineCollection->CountY());
if (m_uCountX)
{
StoreRangeDynamic(
GuidesX(),
m_uCountX,
pGuidelineCollection->GuidesX(),
fSuppressAnimation,
mat._11,
mat._41
);
}
if (m_uCountY)
{
StoreRangeDynamic(
GuidesY(),
m_uCountY,
pGuidelineCollection->GuidesY(),
fSuppressAnimation,
mat._22,
mat._42
);
}
}
//+------------------------------------------------------------------------
//
// Member:
// CDynamicGuidelineCollection::SubpixelAnimationCorrection
//
// Synopsis:
// Execute subpixel animation algorithm for every guideline in arrays.
//
//-------------------------------------------------------------------------
void
CDynamicGuidelineCollection::SubpixelAnimationCorrection(
__in_ecount(1) const CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::PageInPixels> &mat,
UINT uCurrentTime,
__out_ecount(1) bool & fNeedMoreCycles
)
{
CDynamicGuideline* pGuidelinesX = Data();
for (UINT i = 0, n = CountX(); i < n; i++)
{
pGuidelinesX[i].SubpixelAnimationCorrection(mat._11, mat._41, uCurrentTime, fNeedMoreCycles);
}
CDynamicGuideline* pGuidelinesY = pGuidelinesX + CountX();
for (UINT i = 0, n = CountY(); i < n; i++)
{
pGuidelinesY[i].SubpixelAnimationCorrection(mat._22, mat._42, uCurrentTime, fNeedMoreCycles);
}
}
//+------------------------------------------------------------------------
//
// Member:
// CDynamicGuidelineCollection::NotifyNonSnappableState
//
// Synopsis:
// Notify every guideline that the rendering is happening with a translation
// that's not scale-and-translation-only.
//
//-------------------------------------------------------------------------
void
CDynamicGuidelineCollection::NotifyNonSnappableState(
UINT uCurrentTime
)
{
CDynamicGuideline* pGuidelines = Data();
UINT uCountX = CountX(); // implicit convertion from UINT16
UINT uCountY = CountY(); // implicit convertion from UINT16
for (UINT i = 0, n = uCountX + uCountY; i < n; i++)
{
pGuidelines[i].NotifyNonSnappableState(uCurrentTime);
}
}
//+------------------------------------------------------------------------
//
// Member:
// CDynamicGuideline::SubpixelAnimationCorrection
//
// Synopsis:
// Detect animation state and correct guideline position correspondingly.
// Glyph run animation states are distinguished by animation phases:
//
// APH_Start: "Start" phase. This is initial state when no history is available.
// After the very first rendering pass the history becames known,
// and next, "quiet" phase is established.
//
// APH_Quiet: "Quiet" phase. As long as guideline stays at the same place on the
// screen (possibly being re-rendered many times), we conclude it is
// immoveable and so needs to be as crisp as possible. To get that,
// Y-coordinate of anchor point is snapped to pixel grid. This offset
// never exceeds +- 1/2 of pixel size. If the location is changed,
// we are leaving this phase and switch to "animation" one. However
// the detection is lazy: seldom jumps don't switch. We only consider
// animation started if two consecutive displacements happened during
// short time.
//
// APH_Animation: "Animation" phase. As long as position is changing frequently,
// we consider animation phase is on. We don't snap to pixel grid
// during animation phase. If we do, then we'll never get an
// impression of smooth moving. Animation phase is getting finished
// when we'll figure out that position has not been changed during
// some critical time. At this moment we switch to "Landing" phase.
//
// APH_Landing: "Landing" phase. The purpose of it is smooth transition from
// animation to quiet. We don't switch at once from origin guideline
// location to the one that's snapped to pixel grid. If we'll
// do so, then we'll obtain a jerk that is pretty noticeable and
// typically is accepted as a bug. Instead, we are making several
// smaller steps toward snapped position. This takes several frame
// re-rendering passes during a second or so. Each step is practically
// not noticeable by human perception, and eventually the guideline
// is getting settled onto pixel snapped position and we switch back
// "quiet" phase.
//
// APH_Flight: "In complicated flight" phase. Current transformation is not
// scale_and_translation-only, so it is impossible to calculate
// coordinate in device space. Both m_rLastGivenCoord and m_rLastOffset
// are unknown so far.
//
//-------------------------------------------------------------------------
void
CDynamicGuideline::SubpixelAnimationCorrection(
float rScale,
float rOffset,
UINT32 uCurrentTime,
__out_ecount(1) bool & fNeedMoreCycles
)
{
static const float sc_rAllowedStep = 0.05f; // pixel
static const float sc_rBigJumpThreshold = 3.0f; // pixels
// convert coordinate to device space
float rNewCoord = m_rCoord * rScale + rOffset;
switch (GetAnimationPhase())
{
case APH_Start:
{ // "Start" phase: the very first rendering pass.
// store recent coordinate as given
m_rLastGivenCoord = rNewCoord;
// set actual coordinate snapped to pixel grid
m_rLastOffset = CFloatFPU::OffsetToRounded(rNewCoord);
SetBumpTime(uCurrentTime);
// Go to "quiet" phase. We'll never return to "Start" phase.
SetAnimationPhase(APH_Quiet);
}
break;
case APH_Quiet:
{ // "Quiet" phase: look what's going on and possibly switch
// to "Animation" phase.
// look how far ago we've got previous bump
bool fBumpedRecently = BumpedRecently(uCurrentTime);
// look if requested location has been changed
float rOldCoord = m_rLastGivenCoord;
bool fBumpedNow = (rOldCoord != rNewCoord);
if (fBumpedNow)
{
// look how far the guideline has been moved
bool fBigJump = fabs(rNewCoord - rOldCoord) >= sc_rBigJumpThreshold;
if (fBigJump)
{
// don't animate big jump
fBumpedNow = false;
// set m_uLastBumpTime so that fBumpedRecently will be false on next frame
SetBumpTime(uCurrentTime - sc_uCriticalTime);
}
else
{
// remember that we've been bumped
SetBumpTime(uCurrentTime);
}
m_rLastGivenCoord = rNewCoord;
}
// if second bump received during little time, infer animation started
bool fInAnimation = fBumpedNow && fBumpedRecently;
if (fInAnimation)
{
// goto "animation" phase
SetAnimationPhase(APH_Animation);
// don't snap to pixel grid since we're in animation
// There is a trouble here. Suppose given coordinate stayed at 0.45
// during long time, then animation started and we've received
// following sequence: 0.55, 0.65, 0.75, etc.
// First bump to 0.55 would not be considered as animation so
// we'll render at 0.00, 1.00, 0.65, 0.75, etc. Thus, with this
// bad luck, we'll get unpleasant virtual jump from 0.00 to 1.00
// then back to 0.65. I have no idea how to suppress it. At the
// moment when 0.55 is received we may suppose that it is just
// single jump and guideline is going to stay here for a long time.
// If we'll goto 0.55 immediately on the bump, we'll distort
// single-jump scenario that will get virtual blur with following
// landing. I suppose it would be worse than forth-and-back jerk
// on the beginning of animation.
m_rLastOffset = 0;
// need more cycles to detect animation finish
fNeedMoreCycles = true;
}
else
{
// stay in "quiet" phase
// snap to pixel grid
m_rLastOffset = CFloatFPU::OffsetToRounded(rNewCoord);
}
}
break;
case APH_Animation:
{ // "Animation" phase: look what's going on, possibly switch
// to "landing" phase.
// Look how far ago we've got previous bump.
bool fBumpedRecently = BumpedRecently(uCurrentTime);
// look if requested location has been changed
float rOldCoord = m_rLastGivenCoord;
bool fBumpedNow = (rOldCoord != rNewCoord);
if (fBumpedNow)
{
// remember that we've been bumped
SetBumpTime(uCurrentTime);
m_rLastGivenCoord = rNewCoord;
}
// if we've received bump right now or recently, stay animated
bool fInAnimation = fBumpedNow || fBumpedRecently;
if (!fInAnimation)
{
// goto "landing" phase
SetAnimationPhase(APH_Landing);
}
// don't snap to pixel grid since we're in animation
m_rLastOffset = 0;
// need more cycles to detect animation finish
fNeedMoreCycles = true;
}
break;
case APH_Landing:
{ // "Landing" phase: smooth transition from "animation" to "quiet".
// look if requered location has been changed
float rOldCoord = m_rLastGivenCoord;
bool fBumpedNow = (rOldCoord != rNewCoord);
if (fBumpedNow)
{
// remember that we've been bumped
SetBumpTime(uCurrentTime);
m_rLastGivenCoord = rNewCoord;
}
// if we've received bump during "landing", go back to "animation" phase
bool fInAnimation = fBumpedNow;
if (fInAnimation)
{
// goto "animation" phase
SetAnimationPhase(APH_Animation);
// don't snap to pixel grid since we're in animation
m_rLastOffset = 0;
// need more cycles to detect animation finish
fNeedMoreCycles = true;
}
else
{
// make a step toward snapped position
// Note 2005/02/01 mikhaill:
// Previous version used to calculate the step taking
// into account frame rate and maximal allowed speed.
// This became irrelevant due to changes in threading
// model that throttles frame rate so that it is never
// more 64 frames per second.
// Now we only have the step value limit.
float rFinalOffset = CFloatFPU::OffsetToRounded(rNewCoord);
float rDistance = rFinalOffset - m_rLastOffset;
if (fabs(rDistance) > sc_rAllowedStep)
{
// make a step
m_rLastOffset += static_cast<float>(_copysign(sc_rAllowedStep, rDistance));
// stay in "landing" phase
fNeedMoreCycles = true;
}
else
{
// we've arrived already to snapped position
m_rLastOffset = rFinalOffset;
// switch to "quiet" phase
SetAnimationPhase(APH_Quiet);
}
}
}
break;
case APH_Flight:
{ // "In complicated flight" phase.
// Both m_rLastGivenCoord and m_rLastOffset are unknown.
// We do know recent bump time, but it's uncertain how we
// can make a sense of it.
// So - do the same things as on APH_Start phase.
// store recent coordinate as given
m_rLastGivenCoord = rNewCoord;
// set actual coordinate snapped to pixel grid
m_rLastOffset = CFloatFPU::OffsetToRounded(rNewCoord);
SetBumpTime(uCurrentTime);
// Go to "quiet" phase. We'll never return to "Start" phase.
SetAnimationPhase(APH_Quiet);
}
break;
default:
NO_DEFAULT("Wrong subpixel animation phase");
}
}
//+------------------------------------------------------------------------
//
// Member:
// CDynamicGuideline::NotifyNonSnappableState
//
// Synopsis:
// Register the fact that rendering is happening with a translation
// that's not scale-and-translation-only.
//
//-------------------------------------------------------------------------
void
CDynamicGuideline::NotifyNonSnappableState(
UINT uCurrentTime
)
{
SetAnimationPhase(APH_Flight);
SetBumpTime(uCurrentTime);
}
| 19,753 |
450 | <gh_stars>100-1000
//===- MsgHandler.h -------------------------------------------------------===//
//
// The ONNC Project
//
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef ONNC_DIAGNOSTIC_MSGHANDLER_H
#define ONNC_DIAGNOSTIC_MSGHANDLER_H
#include <cstdio>
#include <cstring>
#include <onnc/ADT/StringRef.h>
#include <onnc/Support/DataTypes.h>
#include <onnc/Support/Path.h>
#include <onnc/Support/ErrorCode.h>
#include <onnc/Diagnostic/EngineFwd.h>
namespace onnc {
namespace diagnostic {
class Engine;
/** \class onnc::MsgHandler
* \brief handles the timing of reporting a diagnostic result.
*
* MsgHandler controls the process to display the message. The message is
* emitted when calling MsgHandler's destructor.
*/
class MsgHandler
{
public:
/// Constructor. Use named diagnostic message
MsgHandler(Engine& pEngine);
/// Destructor. Emission of message happens.
~MsgHandler();
/// emit the message
bool emit();
/// add an argument as a std::string.
void addString(const std::string& pStr) const;
/// add an argument with tagged value.
void addTaggedValue(intptr_t pValue, ArgumentKind pKind) const;
private:
void flushCounts();
private:
Engine& m_Engine;
mutable unsigned int m_NumOfArgs;
};
} // namespace of diagnostic
//===----------------------------------------------------------------------===//
// Non-member functions
//===----------------------------------------------------------------------===//
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, StringRef pStr)
{
pHandler.addString(pStr.str());
return pHandler;
}
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, const std::string& pStr)
{
pHandler.addString(pStr);
return pHandler;
}
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, const Path& pStr)
{
pHandler.addString(pStr.native());
return pHandler;
}
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, SystemError pError)
{
if (SystemError::kNotStartedYet == pError.code())
pHandler.addString("not started yet");
else if (SystemError::kSuccess == pError.code())
pHandler.addString("success");
else
pHandler.addString(::strerror(pError.code()));
return pHandler;
}
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, const char* pStr)
{
pHandler.addString(pStr);
return pHandler;
}
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, int32_t pValue)
{
pHandler.addTaggedValue(pValue, diagnostic::ak_sint32);
return pHandler;
}
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, uint32_t pValue)
{
pHandler.addTaggedValue(pValue, diagnostic::ak_uint32);
return pHandler;
}
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, int64_t pValue)
{
pHandler.addTaggedValue(pValue, diagnostic::ak_sint64);
return pHandler;
}
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, uint64_t pValue)
{
pHandler.addTaggedValue(pValue, diagnostic::ak_uint64);
return pHandler;
}
inline const diagnostic::MsgHandler&
operator<<(const diagnostic::MsgHandler& pHandler, bool pValue)
{
pHandler.addTaggedValue(pValue, diagnostic::ak_bool);
return pHandler;
}
} // namespace of onnc
#endif
| 1,099 |
1,214 | package com.youth.xframe.utils;
import com.youth.xframe.XFrame;
/**
* 此内用于框架系统打印输出控制,使用者用XLog格式化体验更好。
*
*/
public class XPrintUtils {
private XPrintUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
private static String tag = XFrame.tag;
private static boolean log = XFrame.isDebug;
public static void setLog(boolean log) {
XPrintUtils.log = log;
}
public static void i(String msg) {
if (log)
android.util.Log.i(tag, msg);
}
public static void i(String tag, String msg) {
if (log)
android.util.Log.i(tag, msg);
}
public static void d(String msg) {
if (log)
android.util.Log.d(tag, msg);
}
public static void d(String tag, String msg) {
if (log)
android.util.Log.d(tag, msg);
}
public static void w(String msg) {
if (log)
android.util.Log.w(tag, msg);
}
public static void w(String tag, String msg) {
if (log)
android.util.Log.w(tag, msg);
}
public static void v(String msg) {
if (log)
android.util.Log.v(tag, msg);
}
public static void v(String tag, String msg) {
if (log)
android.util.Log.v(tag, msg);
}
public static void e(String msg) {
android.util.Log.e(tag, msg);
}
public static void e(String tag, String msg) {
android.util.Log.e(tag, msg);
}
}
| 736 |
5,169 | <gh_stars>1000+
{
"name": "ChocolatePlatform-Mediation-AdColony",
"version": "2.6.2",
"authors": "<NAME>.",
"license": {
"type": "Commercial",
"text": "You must accept the terms and conditions on the AdColony website by registering in order to legally use the AdColony SDK. U.S. based companies will need to complete the W-9 form and send it to us, as well as complete the section on payment information on clients.adcolony.com, before publisher payments can be issued."
},
"homepage": "http://www.adcolony.com",
"summary": "Copy of AdColony iOS SDK version 2.6.2",
"platforms": {
"ios": "8.0"
},
"vendored_frameworks": "Mediation/AdColony.framework",
"frameworks": "AdColony",
"libraries": "z",
"source": {
"git": "https://github.com/chocolateplatform/pod-builds.git",
"tag": "adcolony_mediation_v2.6.2"
}
}
| 304 |
4,812 | <filename>llvm/lib/MC/MCSectionMachO.cpp
//===- lib/MC/MCSectionMachO.cpp - MachO Code Section Representation ------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCContext.h"
#include "llvm/Support/raw_ostream.h"
#include <cctype>
using namespace llvm;
/// SectionTypeDescriptors - These are strings that describe the various section
/// types. This *must* be kept in order with and stay synchronized with the
/// section type list.
static constexpr struct {
StringLiteral AssemblerName, EnumName;
} SectionTypeDescriptors[MachO::LAST_KNOWN_SECTION_TYPE + 1] = {
{StringLiteral("regular"), StringLiteral("S_REGULAR")}, // 0x00
{StringLiteral(""), StringLiteral("S_ZEROFILL")}, // 0x01
{StringLiteral("cstring_literals"),
StringLiteral("S_CSTRING_LITERALS")}, // 0x02
{StringLiteral("4byte_literals"),
StringLiteral("S_4BYTE_LITERALS")}, // 0x03
{StringLiteral("8byte_literals"),
StringLiteral("S_8BYTE_LITERALS")}, // 0x04
{StringLiteral("literal_pointers"),
StringLiteral("S_LITERAL_POINTERS")}, // 0x05
{StringLiteral("non_lazy_symbol_pointers"),
StringLiteral("S_NON_LAZY_SYMBOL_POINTERS")}, // 0x06
{StringLiteral("lazy_symbol_pointers"),
StringLiteral("S_LAZY_SYMBOL_POINTERS")}, // 0x07
{StringLiteral("symbol_stubs"), StringLiteral("S_SYMBOL_STUBS")}, // 0x08
{StringLiteral("mod_init_funcs"),
StringLiteral("S_MOD_INIT_FUNC_POINTERS")}, // 0x09
{StringLiteral("mod_term_funcs"),
StringLiteral("S_MOD_TERM_FUNC_POINTERS")}, // 0x0A
{StringLiteral("coalesced"), StringLiteral("S_COALESCED")}, // 0x0B
{StringLiteral("") /*FIXME??*/, StringLiteral("S_GB_ZEROFILL")}, // 0x0C
{StringLiteral("interposing"), StringLiteral("S_INTERPOSING")}, // 0x0D
{StringLiteral("16byte_literals"),
StringLiteral("S_16BYTE_LITERALS")}, // 0x0E
{StringLiteral("") /*FIXME??*/, StringLiteral("S_DTRACE_DOF")}, // 0x0F
{StringLiteral("") /*FIXME??*/,
StringLiteral("S_LAZY_DYLIB_SYMBOL_POINTERS")}, // 0x10
{StringLiteral("thread_local_regular"),
StringLiteral("S_THREAD_LOCAL_REGULAR")}, // 0x11
{StringLiteral("thread_local_zerofill"),
StringLiteral("S_THREAD_LOCAL_ZEROFILL")}, // 0x12
{StringLiteral("thread_local_variables"),
StringLiteral("S_THREAD_LOCAL_VARIABLES")}, // 0x13
{StringLiteral("thread_local_variable_pointers"),
StringLiteral("S_THREAD_LOCAL_VARIABLE_POINTERS")}, // 0x14
{StringLiteral("thread_local_init_function_pointers"),
StringLiteral("S_THREAD_LOCAL_INIT_FUNCTION_POINTERS")}, // 0x15
};
/// SectionAttrDescriptors - This is an array of descriptors for section
/// attributes. Unlike the SectionTypeDescriptors, this is not directly indexed
/// by attribute, instead it is searched.
static constexpr struct {
unsigned AttrFlag;
StringLiteral AssemblerName, EnumName;
} SectionAttrDescriptors[] = {
#define ENTRY(ASMNAME, ENUM) \
{ MachO::ENUM, StringLiteral(ASMNAME), StringLiteral(#ENUM) },
ENTRY("pure_instructions", S_ATTR_PURE_INSTRUCTIONS)
ENTRY("no_toc", S_ATTR_NO_TOC)
ENTRY("strip_static_syms", S_ATTR_STRIP_STATIC_SYMS)
ENTRY("no_dead_strip", S_ATTR_NO_DEAD_STRIP)
ENTRY("live_support", S_ATTR_LIVE_SUPPORT)
ENTRY("self_modifying_code", S_ATTR_SELF_MODIFYING_CODE)
ENTRY("debug", S_ATTR_DEBUG)
ENTRY("" /*FIXME*/, S_ATTR_SOME_INSTRUCTIONS)
ENTRY("" /*FIXME*/, S_ATTR_EXT_RELOC)
ENTRY("" /*FIXME*/, S_ATTR_LOC_RELOC)
#undef ENTRY
{ 0, StringLiteral("none"), StringLiteral("") }, // used if section has no attributes but has a stub size
};
MCSectionMachO::MCSectionMachO(StringRef Segment, StringRef Section,
unsigned TAA, unsigned reserved2, SectionKind K,
MCSymbol *Begin)
: MCSection(SV_MachO, K, Begin), TypeAndAttributes(TAA),
Reserved2(reserved2) {
assert(Segment.size() <= 16 && Section.size() <= 16 &&
"Segment or section string too long");
for (unsigned i = 0; i != 16; ++i) {
if (i < Segment.size())
SegmentName[i] = Segment[i];
else
SegmentName[i] = 0;
if (i < Section.size())
SectionName[i] = Section[i];
else
SectionName[i] = 0;
}
}
void MCSectionMachO::PrintSwitchToSection(const MCAsmInfo &MAI, const Triple &T,
raw_ostream &OS,
const MCExpr *Subsection) const {
OS << "\t.section\t" << getSegmentName() << ',' << getSectionName();
// Get the section type and attributes.
unsigned TAA = getTypeAndAttributes();
if (TAA == 0) {
OS << '\n';
return;
}
MachO::SectionType SectionType = getType();
assert(SectionType <= MachO::LAST_KNOWN_SECTION_TYPE &&
"Invalid SectionType specified!");
if (!SectionTypeDescriptors[SectionType].AssemblerName.empty()) {
OS << ',';
OS << SectionTypeDescriptors[SectionType].AssemblerName;
} else {
// If we have no name for the attribute, stop here.
OS << '\n';
return;
}
// If we don't have any attributes, we're done.
unsigned SectionAttrs = TAA & MachO::SECTION_ATTRIBUTES;
if (SectionAttrs == 0) {
// If we have a S_SYMBOL_STUBS size specified, print it along with 'none' as
// the attribute specifier.
if (Reserved2 != 0)
OS << ",none," << Reserved2;
OS << '\n';
return;
}
// Check each attribute to see if we have it.
char Separator = ',';
for (unsigned i = 0;
SectionAttrs != 0 && SectionAttrDescriptors[i].AttrFlag;
++i) {
// Check to see if we have this attribute.
if ((SectionAttrDescriptors[i].AttrFlag & SectionAttrs) == 0)
continue;
// Yep, clear it and print it.
SectionAttrs &= ~SectionAttrDescriptors[i].AttrFlag;
OS << Separator;
if (!SectionAttrDescriptors[i].AssemblerName.empty())
OS << SectionAttrDescriptors[i].AssemblerName;
else
OS << "<<" << SectionAttrDescriptors[i].EnumName << ">>";
Separator = '+';
}
assert(SectionAttrs == 0 && "Unknown section attributes!");
// If we have a S_SYMBOL_STUBS size specified, print it.
if (Reserved2 != 0)
OS << ',' << Reserved2;
OS << '\n';
}
bool MCSectionMachO::UseCodeAlign() const {
return hasAttribute(MachO::S_ATTR_PURE_INSTRUCTIONS);
}
bool MCSectionMachO::isVirtualSection() const {
return (getType() == MachO::S_ZEROFILL ||
getType() == MachO::S_GB_ZEROFILL ||
getType() == MachO::S_THREAD_LOCAL_ZEROFILL);
}
/// ParseSectionSpecifier - Parse the section specifier indicated by "Spec".
/// This is a string that can appear after a .section directive in a mach-o
/// flavored .s file. If successful, this fills in the specified Out
/// parameters and returns an empty string. When an invalid section
/// specifier is present, this returns a string indicating the problem.
std::string MCSectionMachO::ParseSectionSpecifier(StringRef Spec, // In.
StringRef &Segment, // Out.
StringRef &Section, // Out.
unsigned &TAA, // Out.
bool &TAAParsed, // Out.
unsigned &StubSize) { // Out.
TAAParsed = false;
SmallVector<StringRef, 5> SplitSpec;
Spec.split(SplitSpec, ',');
// Remove leading and trailing whitespace.
auto GetEmptyOrTrim = [&SplitSpec](size_t Idx) -> StringRef {
return SplitSpec.size() > Idx ? SplitSpec[Idx].trim() : StringRef();
};
Segment = GetEmptyOrTrim(0);
Section = GetEmptyOrTrim(1);
StringRef SectionType = GetEmptyOrTrim(2);
StringRef Attrs = GetEmptyOrTrim(3);
StringRef StubSizeStr = GetEmptyOrTrim(4);
// Verify that the segment is present and not too long.
if (Segment.empty() || Segment.size() > 16)
return "mach-o section specifier requires a segment whose length is "
"between 1 and 16 characters";
// Verify that the section is present and not too long.
if (Section.empty())
return "mach-o section specifier requires a segment and section "
"separated by a comma";
if (Section.size() > 16)
return "mach-o section specifier requires a section whose length is "
"between 1 and 16 characters";
// If there is no comma after the section, we're done.
TAA = 0;
StubSize = 0;
if (SectionType.empty())
return "";
// Figure out which section type it is.
auto TypeDescriptor = std::find_if(
std::begin(SectionTypeDescriptors), std::end(SectionTypeDescriptors),
[&](decltype(*SectionTypeDescriptors) &Descriptor) {
return SectionType == Descriptor.AssemblerName;
});
// If we didn't find the section type, reject it.
if (TypeDescriptor == std::end(SectionTypeDescriptors))
return "mach-o section specifier uses an unknown section type";
// Remember the TypeID.
TAA = TypeDescriptor - std::begin(SectionTypeDescriptors);
TAAParsed = true;
// If we have no comma after the section type, there are no attributes.
if (Attrs.empty()) {
// S_SYMBOL_STUBS always require a symbol stub size specifier.
if (TAA == MachO::S_SYMBOL_STUBS)
return "mach-o section specifier of type 'symbol_stubs' requires a size "
"specifier";
return "";
}
// The attribute list is a '+' separated list of attributes.
SmallVector<StringRef, 1> SectionAttrs;
Attrs.split(SectionAttrs, '+', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
for (StringRef &SectionAttr : SectionAttrs) {
auto AttrDescriptorI = std::find_if(
std::begin(SectionAttrDescriptors), std::end(SectionAttrDescriptors),
[&](decltype(*SectionAttrDescriptors) &Descriptor) {
return SectionAttr.trim() == Descriptor.AssemblerName;
});
if (AttrDescriptorI == std::end(SectionAttrDescriptors))
return "mach-o section specifier has invalid attribute";
TAA |= AttrDescriptorI->AttrFlag;
}
// Okay, we've parsed the section attributes, see if we have a stub size spec.
if (StubSizeStr.empty()) {
// S_SYMBOL_STUBS always require a symbol stub size specifier.
if (TAA == MachO::S_SYMBOL_STUBS)
return "mach-o section specifier of type 'symbol_stubs' requires a size "
"specifier";
return "";
}
// If we have a stub size spec, we must have a sectiontype of S_SYMBOL_STUBS.
if ((TAA & MachO::SECTION_TYPE) != MachO::S_SYMBOL_STUBS)
return "mach-o section specifier cannot have a stub size specified because "
"it does not have type 'symbol_stubs'";
// Convert the stub size from a string to an integer.
if (StubSizeStr.getAsInteger(0, StubSize))
return "mach-o section specifier has a malformed stub size";
return "";
}
| 4,627 |
698 | #!/usr/bin/env python2.7
import numpy as np
import time
grid_size = (512, )
def laplacian(grid):
return np.roll(grid, +1) + np.roll(grid, -1) - 2 * grid
def evolve(grid, dt, D=1):
return grid + dt * D * laplacian(grid)
def run_experiment(num_iterations):
grid = np.zeros(grid_size)
block_low = int(grid_size[0] * .4)
block_high = int(grid_size[0] * .5)
grid[block_low:block_high] = 0.005
start = time.time()
for i in range(num_iterations):
grid = evolve(grid, 0.1)
return time.time() - start
if __name__ == "__main__":
run_experiment(500)
| 265 |
529 | from typing import Type
from psqlextra.models import PostgresMaterializedViewModel
from .view import PostgresViewModelState
class PostgresMaterializedViewModelState(PostgresViewModelState):
"""Represents the state of a :see:PostgresMaterializedViewModel in the
migrations."""
@classmethod
def _get_base_model_class(self) -> Type[PostgresMaterializedViewModel]:
"""Gets the class to use as a base class for rendered models."""
return PostgresMaterializedViewModel
| 152 |
1,069 | from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from th_slack.api import views
urlpatterns = [
url(r'', views.slack,)
]
urlpatterns = format_suffix_patterns(urlpatterns)
| 79 |
1,044 | /* HFGlyphTrie is used to represent a trie of glyphs that allows multiple concurrent readers, along with one writer. */
#import <ApplicationServices/ApplicationServices.h>
/* BranchFactor is in bits */
#define kHFGlyphTrieBranchFactor 4
#define kHFGlyphTrieBranchCount (1 << kHFGlyphTrieBranchFactor)
typedef uint16_t HFGlyphFontIndex;
#define kHFGlyphFontIndexInvalid ((HFGlyphFontIndex)(-1))
#define kHFGlyphInvalid kCGFontIndexInvalid
struct HFGlyph_t {
HFGlyphFontIndex fontIndex;
CGGlyph glyph;
};
static inline BOOL HFGlyphEqualsGlyph(struct HFGlyph_t a, struct HFGlyph_t b) __attribute__((unused));
static inline BOOL HFGlyphEqualsGlyph(struct HFGlyph_t a, struct HFGlyph_t b) {
return a.glyph == b.glyph && a.fontIndex == b.fontIndex;
}
struct HFGlyphTrieBranch_t {
__strong void *children[kHFGlyphTrieBranchCount];
};
struct HFGlyphTrieLeaf_t {
struct HFGlyph_t glyphs[kHFGlyphTrieBranchCount];
};
struct HFGlyphTrie_t {
uint8_t branchingDepth;
struct HFGlyphTrieBranch_t root;
};
/* Initializes a trie witha given key size */
__private_extern__ void HFGlyphTrieInitialize(struct HFGlyphTrie_t *trie, uint8_t keySize);
/* Inserts a glyph into the trie */
__private_extern__ void HFGlyphTrieInsert(struct HFGlyphTrie_t *trie, NSUInteger key, struct HFGlyph_t value);
/* Attempts to fetch a glyph. If the glyph is not present, returns an HFGlyph_t set to all bits 0. */
__private_extern__ struct HFGlyph_t HFGlyphTrieGet(const struct HFGlyphTrie_t *trie, NSUInteger key);
/* Frees all storage associated with a glyph tree. This is not necessary to call under GC. */
__private_extern__ void HFGlyphTreeFree(struct HFGlyphTrie_t * trie);
| 638 |
601 | <gh_stars>100-1000
{
"@microsoft/generator-sharepoint": {
"libraryName": "bootstrap-slider",
"framework": "none",
"version": "1.0.0",
"libraryId": "aea96b80-92f9-49e4-9f29-34acc9990af5"
}
} | 99 |
2,453 | <filename>XVim2/XcodeHeader/IDEKit/IDELayoutControlView.h
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <AppKit/NSView.h>
@interface IDELayoutControlView : NSView
{
double _maxContentWidth;
long long _alignment;
}
@property(nonatomic) long long alignment; // @synthesize alignment=_alignment;
@property(nonatomic) double maxContentWidth; // @synthesize maxContentWidth=_maxContentWidth;
- (void)_constrainChildViewWidthWithAlignment:(long long)arg1;
- (void)layout;
- (void)setFrameSize:(struct CGSize)arg1;
@end
| 225 |
980 | {"recorded_with": "betamax/0.8.0", "http_interactions": [{"request": {"method": "GET", "headers": {"Accept-Encoding": "gzip, deflate", "Accept": "application/vnd.github.v3.full+json", "Content-Type": "application/json", "User-Agent": "github3.py/1.0.0a4", "Connection": "keep-alive", "Accept-Charset": "utf-8"}, "uri": "https://api.github.com/search/code?q=HTTPAdapter+in%3Afile+language%3Apython+repo%3Akennethreitz%2Frequests&per_page=100", "body": {"string": "", "encoding": "utf-8"}}, "recorded_at": "2017-02-07T02:43:33", "response": {"headers": {"X-XSS-Protection": "1; mode=block", "Server": "GitHub.com", "Access-Control-Allow-Origin": "*", "X-RateLimit-Reset": "1486435473", "Transfer-Encoding": "chunked", "X-Served-By": "626ed3a9050b8faa02ef5f3c540b508d", "X-Frame-Options": "deny", "X-GitHub-Request-Id": "927A:2C95:DC84D80:1173FA54:58993455", "Cache-Control": "no-cache", "X-Content-Type-Options": "nosniff", "X-RateLimit-Limit": "10", "Date": "Tue, 07 Feb 2017 02:43:33 GMT", "Content-Security-Policy": "default-src 'none'", "Status": "200 OK", "Strict-Transport-Security": "max-age=31536000; includeSubdomains; preload", "Content-Type": "application/json; charset=utf-8", "Access-Control-Expose-Headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "Vary": "Accept-Encoding", "Content-Encoding": "gzip", "X-RateLimit-Remaining": "9", "X-GitHub-Media-Type": "github.v3; param=full; format=json"}, "status": {"message": "OK", "code": 200}, "url": "https://api.github.com/search/code?q=HTTPAdapter+in%3Afile+language%3Apython+repo%3Akennethreitz%2Frequests&per_page=100", "body": {"base64_string": "<KEY> "string": "", "encoding": "utf-8"}}}]}
| 697 |
435 | <reponame>Accumulo-S3/datawave
package datawave.query.jexl.functions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import datawave.data.normalizer.AbstractGeometryNormalizer;
import datawave.data.normalizer.GeoNormalizer;
import datawave.data.normalizer.GeometryNormalizer;
import datawave.data.normalizer.PointNormalizer;
import datawave.data.type.GeoType;
import datawave.data.type.GeometryType;
import datawave.data.type.PointType;
import datawave.data.type.Type;
import datawave.query.attributes.AttributeFactory;
import datawave.query.config.ShardQueryConfiguration;
import datawave.query.jexl.ArithmeticJexlEngines;
import datawave.query.jexl.JexlASTHelper;
import datawave.query.jexl.JexlNodeFactory;
import datawave.query.jexl.functions.arguments.JexlArgumentDescriptor;
import datawave.query.jexl.nodes.BoundedRange;
import datawave.query.jexl.visitors.EventDataQueryExpressionVisitor;
import datawave.query.util.DateIndexHelper;
import datawave.query.util.GeoWaveUtils;
import datawave.query.util.MetadataHelper;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.commons.jexl2.parser.ASTEQNode;
import org.apache.commons.jexl2.parser.ASTFunctionNode;
import org.apache.commons.jexl2.parser.ASTGENode;
import org.apache.commons.jexl2.parser.ASTLENode;
import org.apache.commons.jexl2.parser.JexlNode;
import org.apache.commons.jexl2.parser.ParserTreeConstants;
import org.apache.log4j.Logger;
import org.locationtech.geowave.core.geotime.util.GeometryUtils;
import org.locationtech.geowave.core.index.ByteArrayRange;
import org.locationtech.geowave.core.index.sfc.data.MultiDimensionalNumericData;
import org.locationtech.geowave.core.store.api.Index;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* This is the descriptor class for performing geowave functions. It supports basic spatial relationships, and decomposes the bounding box of the relationship
* geometry into a set of geowave ranges. It currently caps this range decomposition to 8 ranges per tier for GeometryType and 32 ranges total for PointType.
*
*/
public class GeoWaveFunctionsDescriptor implements JexlFunctionArgumentDescriptorFactory {
private enum IndexType {
GEOWAVE_GEOMETRY, GEOWAVE_POINT, GEO_POINT, UNKNOWN
}
/**
* This is the argument descriptor which can be used to normalize and optimize function node queries
*
*/
protected static final String[] SPATIAL_RELATION_OPERATIONS = new String[] {"contains", "covers", "covered_by", "crosses", "intersects", "overlaps",
"within"};
private static final Logger LOGGER = Logger.getLogger(GeoWaveFunctionsDescriptor.class);
public static class GeoWaveJexlArgumentDescriptor implements JexlArgumentDescriptor {
protected final String name;
protected final List<JexlNode> args;
public GeoWaveJexlArgumentDescriptor(ASTFunctionNode node, String name, List<JexlNode> args) {
this.name = name;
this.args = args;
}
@Override
public JexlNode getIndexQuery(ShardQueryConfiguration config, MetadataHelper helper, DateIndexHelper dateIndexHelper, Set<String> datatypeFilter) {
int maxEnvelopes = Math.max(1, config.getGeoWaveMaxEnvelopes());
if (isSpatialRelationship(name)) {
Geometry geom = AbstractGeometryNormalizer.parseGeometry(args.get(1).image);
List<Envelope> envelopes = getSeparateEnvelopes(geom, maxEnvelopes);
if (!envelopes.isEmpty()) {
JexlNode indexNode;
if (envelopes.size() == 1) {
indexNode = getIndexNode(args.get(0), geom, envelopes.get(0), config, helper);
} else {
indexNode = getIndexNode(args.get(0), geom, envelopes, config, helper);
}
return indexNode;
}
}
// return the true node if unable to parse arguments
return TRUE_NODE;
}
private static Set<IndexType> getIndexTypes(String field, MetadataHelper helper) {
Set<IndexType> dataTypes = new HashSet<>();
try {
for (Type<?> type : helper.getDatatypesForField(field)) {
dataTypes.add(typeToIndexType(type));
}
} catch (IllegalAccessException | InstantiationException | TableNotFoundException e) {
LOGGER.debug("Unable to retrieve data types for field " + field);
}
return dataTypes;
}
private static IndexType typeToIndexType(Type<?> type) {
IndexType indexType = IndexType.UNKNOWN;
if (type instanceof GeometryType) {
indexType = IndexType.GEOWAVE_GEOMETRY;
} else if (type instanceof PointType) {
indexType = IndexType.GEOWAVE_POINT;
} else if (type instanceof GeoType) {
indexType = IndexType.GEO_POINT;
}
return indexType;
}
protected static JexlNode getIndexNode(JexlNode node, Geometry geometry, Envelope env, ShardQueryConfiguration config, MetadataHelper helper) {
if (node.jjtGetNumChildren() > 0) {
List<JexlNode> list = Lists.newArrayList();
for (int i = 0; i < node.jjtGetNumChildren(); i++) {
JexlNode kid = node.jjtGetChild(i);
if (kid.image != null) {
list.add(getIndexNode(kid.image, geometry, env, config, helper));
}
}
if (!list.isEmpty()) {
return JexlNodeFactory.createOrNode(list);
}
} else if (node.image != null) {
return getIndexNode(node.image, geometry, env, config, helper);
}
return node;
}
protected static JexlNode getIndexNode(JexlNode node, Geometry geometry, List<Envelope> envs, ShardQueryConfiguration config, MetadataHelper helper) {
if (node.jjtGetNumChildren() > 0) {
List<JexlNode> list = Lists.newArrayList();
for (int i = 0; i < node.jjtGetNumChildren(); i++) {
JexlNode kid = node.jjtGetChild(i);
if (kid.image != null) {
list.add(getIndexNode(kid.image, geometry, envs, config, helper));
}
}
if (!list.isEmpty()) {
return JexlNodeFactory.createOrNode(list);
}
} else if (node.image != null) {
return getIndexNode(node.image, geometry, envs, config, helper);
}
return node;
}
protected static JexlNode getIndexNode(String fieldName, Geometry geometry, Envelope env, ShardQueryConfiguration config, MetadataHelper helper) {
List<Envelope> envs = new ArrayList<>();
envs.add(env);
return getIndexNode(fieldName, geometry, envs, config, helper);
}
protected static JexlNode getIndexNode(String fieldName, Geometry geometry, List<Envelope> envs, ShardQueryConfiguration config, MetadataHelper helper) {
List<JexlNode> indexNodes = new ArrayList<>();
Set<IndexType> indexTypes = getIndexTypes(fieldName, helper);
// generate ranges for geowave geometries and points
if (indexTypes.remove(IndexType.GEOWAVE_GEOMETRY)) {
// point index ranges are covered by geometry index
// ranges so we can remove GEOWAVE_POINT
indexTypes.remove(IndexType.GEOWAVE_POINT);
indexNodes.add(generateGeoWaveRanges(fieldName, geometry, envs, config, GeometryNormalizer.index, config.getGeometryMaxExpansion()));
}
// generate ranges for geowave points
else if (indexTypes.remove(IndexType.GEOWAVE_POINT)) {
indexNodes.add(generateGeoWaveRanges(fieldName, geometry, envs, config, PointNormalizer.index, config.getPointMaxExpansion()));
}
// generate ranges for geo points
if (indexTypes.remove(IndexType.GEO_POINT)) {
indexNodes.add(generateGeoRanges(fieldName, envs));
}
JexlNode indexNode;
if (!indexNodes.isEmpty()) {
if (indexNodes.size() > 1) {
indexNode = JexlNodeFactory.createOrNode(indexNodes);
} else {
indexNode = indexNodes.get(0);
}
} else {
throw new IllegalArgumentException("Unable to create index node for geowave function.");
}
return indexNode;
}
protected static JexlNode generateGeoWaveRanges(String fieldName, Geometry geometry, List<Envelope> envs, ShardQueryConfiguration config, Index index,
int maxExpansion) {
Collection<ByteArrayRange> allRanges = new ArrayList<>();
int maxRanges = maxExpansion / envs.size();
for (Envelope env : envs) {
for (MultiDimensionalNumericData range : GeometryUtils.basicConstraintsFromEnvelope(env).getIndexConstraints(index)) {
List<ByteArrayRange> byteArrayRanges = index.getIndexStrategy().getQueryRanges(range, maxRanges).getCompositeQueryRanges();
if (config.isOptimizeGeoWaveRanges()) {
byteArrayRanges = GeoWaveUtils.optimizeByteArrayRanges(geometry, byteArrayRanges, config.getGeoWaveRangeSplitThreshold(),
config.getGeoWaveMaxRangeOverlap());
}
allRanges.addAll(byteArrayRanges);
}
}
allRanges = ByteArrayRange.mergeIntersections(allRanges, ByteArrayRange.MergeOperation.UNION);
Iterable<JexlNode> rangeNodes = Iterables.transform(allRanges, new ByteArrayRangeToJexlNode(fieldName));
// now link em up
return JexlNodeFactory.createOrNode(rangeNodes);
}
protected static JexlNode generateGeoRanges(String fieldName, List<Envelope> envs) {
JexlNode indexNode;
List<JexlNode> indexNodes = new ArrayList<>();
for (Envelope env : envs) {
// @formatter:off
indexNodes.add(
GeoFunctionsDescriptor.GeoJexlArgumentDescriptor.getIndexNode(
fieldName,
env.getMinX(),
env.getMaxX(),
env.getMinY(),
env.getMaxY(),
GeoNormalizer.separator));
// @formatter:on
}
if (!indexNodes.isEmpty()) {
if (indexNodes.size() > 1) {
indexNode = JexlNodeFactory.createOrNode(indexNodes);
} else {
indexNode = indexNodes.get(0);
}
} else {
throw new IllegalArgumentException("Failed to generate index nodes for geo field using geowave function.");
}
return indexNode;
}
@Override
public void addFilters(AttributeFactory attributeFactory, Map<String,EventDataQueryExpressionVisitor.ExpressionFilter> filterMap) {
// noop, covered by getIndexQuery (see comments on interface)
}
@Override
public Set<String> fieldsForNormalization(MetadataHelper helper, Set<String> datatypeFilter, int arg) {
// no normalization required
return Collections.emptySet();
}
@Override
public Set<String> fields(MetadataHelper helper, Set<String> datatypeFilter) {
return JexlASTHelper.getIdentifierNames(args.get(0));
}
@Override
public Set<Set<String>> fieldSets(MetadataHelper helper, Set<String> datatypeFilter) {
return Fields.product(args.get(0));
}
@Override
public boolean useOrForExpansion() {
return true;
}
@Override
public boolean regexArguments() {
return false;
}
@Override
public boolean allowIvaratorFiltering() {
return false;
}
public String getWkt() {
return args.get(1).image;
}
}
@Override
public JexlArgumentDescriptor getArgumentDescriptor(ASTFunctionNode node) {
FunctionJexlNodeVisitor fvis = new FunctionJexlNodeVisitor();
fvis.visit(node, null);
Class<?> functionClass = (Class<?>) ArithmeticJexlEngines.functions().get(fvis.namespace());
if (!GeoWaveFunctions.GEOWAVE_FUNCTION_NAMESPACE.equals(node.jjtGetChild(0).image))
throw new IllegalArgumentException("Calling " + this.getClass().getSimpleName() + ".getJexlNodeDescriptor with an unexpected namespace of "
+ node.jjtGetChild(0).image);
if (!functionClass.equals(GeoWaveFunctions.class))
throw new IllegalArgumentException("Calling " + this.getClass().getSimpleName() + ".getJexlNodeDescriptor with node for a function in "
+ functionClass);
verify(fvis.name(), fvis.args().size());
return new GeoWaveJexlArgumentDescriptor(node, fvis.name(), fvis.args());
}
protected static void verify(String name, int numArgs) {
if (isSpatialRelationship(name)) {
// two arguments in the form <spatial_relation_function>(fieldName,
// geometryString
verify(name, numArgs, new String[] {"fieldName", "geometryString"});
} else {
throw new IllegalArgumentException("Unknown GeoWave function: " + name);
}
}
private static boolean isSpatialRelationship(String name) {
for (String op : SPATIAL_RELATION_OPERATIONS) {
if (op.equals(name)) {
return true;
}
}
return false;
}
protected static void verify(String name, int numArgs, String[] parameterNames) {
if (numArgs != parameterNames.length) {
StringBuilder exception = new StringBuilder("Wrong number of arguments to GeoWave's ");
exception.append(name).append(" function; correct use is '").append(name).append("(");
if (parameterNames.length > 0) {
exception.append(parameterNames[0]);
}
for (int i = 1; i < parameterNames.length; i++) {
exception.append(", ").append(parameterNames[i]);
}
exception.append(")'");
throw new IllegalArgumentException(exception.toString());
}
}
private static class ByteArrayRangeToJexlNode implements com.google.common.base.Function<ByteArrayRange,JexlNode> {
private final String fieldName;
public ByteArrayRangeToJexlNode(String fieldName) {
this.fieldName = fieldName;
}
@Override
public JexlNode apply(ByteArrayRange input) {
if (Arrays.equals(input.getStart(), input.getEnd())) {
return JexlNodeFactory.buildNode(new ASTEQNode(ParserTreeConstants.JJTEQNODE), fieldName,
AbstractGeometryNormalizer.getEncodedStringFromIndexBytes(input.getStart()));
} else {
JexlNode geNode = JexlNodeFactory.buildNode(new ASTGENode(ParserTreeConstants.JJTGENODE), fieldName,
AbstractGeometryNormalizer.getEncodedStringFromIndexBytes(input.getStart()));
JexlNode leNode = JexlNodeFactory.buildNode(new ASTLENode(ParserTreeConstants.JJTLENODE), fieldName,
AbstractGeometryNormalizer.getEncodedStringFromIndexBytes(input.getEnd()));
// now link em up
return BoundedRange.create(JexlNodeFactory.createAndNode(Arrays.asList(geNode, leNode)));
}
}
}
protected static List<Geometry> getAllEnvelopeGeometries(Geometry geom) {
List<Geometry> geometries = new ArrayList<>();
if (geom.getNumGeometries() > 1)
for (int geoIdx = 0; geoIdx < geom.getNumGeometries(); geoIdx++)
geometries.addAll(getAllEnvelopeGeometries(geom.getGeometryN(geoIdx)));
else
geometries.add(geom.getEnvelope());
return geometries;
}
protected static boolean combineIntersectedGeometries(List<Geometry> geometries, List<Geometry> combinedGeometries, int maxEnvelopes) {
while (!geometries.isEmpty() && combinedGeometries.size() < maxEnvelopes)
combinedGeometries.add(findIntersectedGeoms(geometries.remove(0), geometries));
return geometries.isEmpty();
}
protected static Geometry findIntersectedGeoms(Geometry srcGeom, List<Geometry> geometries) {
List<Geometry> intersected = new ArrayList<>();
// find all geometries which intersect with with srcGeom
Iterator<Geometry> geomIter = geometries.iterator();
while (geomIter.hasNext()) {
Geometry geom = geomIter.next();
if (geom.intersects(srcGeom)) {
geomIter.remove();
intersected.add(geom);
}
}
// compute the envelope for the intersected geometries and the source geometry, and look for more intersections
if (!intersected.isEmpty()) {
intersected.add(srcGeom);
Geometry mergedGeom = new GeometryCollection(intersected.toArray(new Geometry[0]), new GeometryFactory()).getEnvelope();
return findIntersectedGeoms(mergedGeom, geometries);
}
return srcGeom;
}
protected static List<Envelope> getSeparateEnvelopes(Geometry geom, int maxEnvelopes) {
if (geom.getNumGeometries() > 0) {
List<Geometry> geometries = getAllEnvelopeGeometries(geom);
List<Geometry> intersectedGeometries = new ArrayList<>();
if (combineIntersectedGeometries(geometries, intersectedGeometries, maxEnvelopes))
return intersectedGeometries.stream().map(Geometry::getEnvelopeInternal).collect(Collectors.toList());
}
return Collections.singletonList(geom.getEnvelopeInternal());
}
}
| 8,943 |
1,073 | <gh_stars>1000+
// RUN: %clang_cc1 -analyze -analyzer-checker=core,cplusplus.NewDeleteLeaks -verify %s
class A0 {};
class A1 {
public:
A1(int);
};
struct S{
int i;
};
class A2 {
public:
A2();
A2(S);
A2(int*);
A2(S*);
A2(S&, int);
A2(int, S**);
};
void test() {
new int; // expected-warning@+1 {{Potential memory leak}}
new A0; // expected-warning@+1 {{Potential memory leak}}
new A1(0); // expected-warning@+1 {{Potential memory leak}}
new A2; // expected-warning@+1 {{Potential memory leak}}
S s;
s.i = 1;
S* ps = new S;
new A2(s); // expected-warning@+1 {{Potential memory leak}}
new A2(&(s.i)); // expected-warning@+1 {{Potential memory leak}}
new A2(ps); // no warning
new A2(*ps, 1); // no warning
new A2(1, &ps); // no warning
// Tests to ensure that leaks are reported for consumed news no matter what the arguments are.
A2 *a2p1 = new A2; // expected-warning@+1 {{Potential leak of memory}}
A2 *a2p2 = new A2(ps); // expected-warning@+1 {{Potential leak of memory}}
A2 *a2p3 = new A2(*ps, 1); // expected-warning@+1 {{Potential leak of memory}}
A2 *a2p4 = new A2(1, &ps); // expected-warning@+1 {{Potential leak of memory}}
}
| 471 |
420 | #pragma once
namespace rawaccel {
constexpr double minsd(double a, double b)
{
return (a < b) ? a : b;
}
constexpr double maxsd(double a, double b)
{
return (b < a) ? a : b;
}
constexpr double clampsd(double v, double lo, double hi)
{
return minsd(maxsd(v, lo), hi);
}
template <typename T>
constexpr const T& min(const T& a, const T& b)
{
return (b < a) ? b : a;
}
template <typename T>
constexpr const T& max(const T& a, const T& b)
{
return (b < a) ? a : b;
}
template <typename T>
constexpr const T& clamp(const T& v, const T& lo, const T& hi)
{
return (v < lo) ? lo : (hi < v) ? hi : v;
}
// returns the unbiased exponent of x if x is normal
inline int ilogb(double x)
{
union { double f; unsigned long long i; } u = { x };
return static_cast<int>((u.i >> 52) & 0x7ff) - 0x3ff;
}
// returns x * 2^n if n is in [-1022, 1023]
inline double scalbn(double x, int n)
{
union { double f; unsigned long long i; } u;
u.i = static_cast<unsigned long long>(0x3ff + n) << 52;
return x * u.f;
}
inline bool infnan(double x)
{
return ilogb(x) == 0x400;
}
struct noop {
template <typename... Ts>
constexpr void operator()(Ts&&...) const noexcept {}
};
template <typename T> struct remove_ref { using type = T; };
template <typename T> struct remove_ref<T&> { using type = T; };
template <typename T> struct remove_ref<T&&> { using type = T; };
template <typename T>
using remove_ref_t = typename remove_ref<T>::type;
template <typename T, typename U>
struct is_same { static constexpr bool value = false; };
template <typename T>
struct is_same<T, T> { static constexpr bool value = true; };
template <typename T, typename U>
inline constexpr bool is_same_v = is_same<T, U>::value;
template <class T> struct is_rvalue_ref { static constexpr bool value = false; };
template <class T> struct is_rvalue_ref<T&&> { static constexpr bool value = true; };
template <class T>
inline constexpr bool is_rvalue_ref_v = is_rvalue_ref<T>::value;
}
| 961 |
498 | <reponame>hwlhwl2006/CoinExchange_CryptoExchange_Java<gh_stars>100-1000
package com.bizzan.bitrade.dao;
import java.util.List;
import com.bizzan.bitrade.constant.BooleanEnum;
import com.bizzan.bitrade.constant.CertifiedBusinessStatus;
import com.bizzan.bitrade.dao.base.BaseDao;
import com.bizzan.bitrade.entity.BusinessAuthApply;
import com.bizzan.bitrade.entity.Member;
/**
* @author Shaoxianjun
* @date 2019/5/7
*/
public interface BusinessAuthApplyDao extends BaseDao<BusinessAuthApply> {
List<BusinessAuthApply> findByMemberOrderByIdDesc(Member member);
List<BusinessAuthApply> findByMemberAndCertifiedBusinessStatusOrderByIdDesc(Member member, CertifiedBusinessStatus certifiedBusinessStatus);
long countAllByCertifiedBusinessStatus(CertifiedBusinessStatus status);
}
| 258 |
511 | /*****************************************************************************
*
* Copyright 2017 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#include "platform_mif_module.h"
#include "platform_mif.h"
#include <errno.h>
#include <tinyara/kmalloc.h>
/* Implements */
#include "scsc_mif_abs.h"
#include "utils_misc.h"
/* Variables */
struct mif_abs_node {
struct slsi_dlist_head list;
struct scsc_mif_abs *mif_abs;
};
struct mif_driver_node {
struct slsi_dlist_head list;
struct scsc_mif_abs_driver *driver;
};
struct mif_mmap_node {
struct slsi_dlist_head list;
struct scsc_mif_mmap_driver *driver;
};
static struct platform_mif_module {
struct slsi_dlist_head mif_abs_list;
struct slsi_dlist_head mif_driver_list;
struct slsi_dlist_head mif_mmap_list;
} mif_module = {
.mif_abs_list = SLSI_DLIST_HEAD_INIT(mif_module.mif_abs_list), .mif_driver_list = SLSI_DLIST_HEAD_INIT(mif_module.mif_driver_list), .mif_mmap_list = SLSI_DLIST_HEAD_INIT(mif_module.mif_mmap_list),
};
/* Private Functions */
static void platform_mif_module_probe_registered_clients(struct scsc_mif_abs *mif_abs)
{
struct mif_driver_node *mif_driver_node, *next;
bool driver_registered = false;
/* Traverse Linked List for each mif_driver node */
slsi_dlist_for_each_entry_safe(mif_driver_node, next, &mif_module.mif_driver_list, list) {
mif_driver_node->driver->probe(mif_driver_node->driver, mif_abs);
driver_registered = true;
}
}
//static int platform_mif_module_probe(struct platform_device *pdev)
int platform_mif_module_probe(void)
{
struct mif_abs_node *mif_node;
struct scsc_mif_abs *mif_abs;
/* ADD EARLY BOARD INITIALIZATIONS IF REQUIRED */
/* platform_mif_init(); */
mif_node = kmm_zalloc(sizeof(*mif_node));
if (!mif_node) {
return -ENODEV;
}
mif_abs = platform_mif_create();
if (!mif_abs) {
pr_err("%s: Error creating platform interface\n", __func__);
kmm_free(mif_node);
return -ENODEV;
}
/* Add node */
mif_node->mif_abs = mif_abs;
slsi_dlist_add_tail(&mif_node->list, &mif_module.mif_abs_list);
platform_mif_module_probe_registered_clients(mif_abs);
return 0;
}
static int platform_mif_module_remove(/*struct platform_device *pdev */ void)
{
return 0;
}
/* Public Functions */
void scsc_mif_abs_register(struct scsc_mif_abs_driver *driver)
{
struct mif_driver_node *mif_driver_node;
struct mif_abs_node *mif_node;
/* Add node in driver linked list */
mif_driver_node = kmm_zalloc(sizeof(*mif_driver_node));
if (!mif_driver_node) {
return;
}
mif_driver_node->driver = driver;
slsi_dlist_add_tail(&mif_driver_node->list, &mif_module.mif_driver_list);
/* Traverse Linked List for each mif_abs node */
slsi_dlist_for_each_entry(mif_node, &mif_module.mif_abs_list, list) {
driver->probe(driver, mif_node->mif_abs);
}
}
void scsc_mif_abs_unregister(struct scsc_mif_abs_driver *driver)
{
struct mif_driver_node *mif_driver_node, *next;
/* Traverse Linked List for each mif_driver node */
slsi_dlist_for_each_entry_safe(mif_driver_node, next, &mif_module.mif_driver_list, list) {
if (mif_driver_node->driver == driver) {
slsi_dlist_del(&mif_driver_node->list);
kmm_free(mif_driver_node);
}
}
}
/* Register a mmap - debug driver - for this specific transport*/
void scsc_mif_mmap_register(struct scsc_mif_mmap_driver *mmap_driver)
{
struct mif_mmap_node *mif_mmap_node;
struct mif_abs_node *mif_node;
/* Add node in driver linked list */
mif_mmap_node = kmm_zalloc(sizeof(*mif_mmap_node));
if (!mif_mmap_node) {
return;
}
mif_mmap_node->driver = mmap_driver;
slsi_dlist_add_tail(&mif_mmap_node->list, &mif_module.mif_mmap_list);
/* Traverse Linked List for each mif_abs node */
slsi_dlist_for_each_entry(mif_node, &mif_module.mif_abs_list, list) {
mmap_driver->probe(mmap_driver, mif_node->mif_abs);
}
}
/* Unregister a mmap - debug driver - for this specific transport*/
void scsc_mif_mmap_unregister(struct scsc_mif_mmap_driver *mmap_driver)
{
struct mif_mmap_node *mif_mmap_node, *next;
/* Traverse Linked List for each mif_driver node */
slsi_dlist_for_each_entry_safe(mif_mmap_node, next, &mif_module.mif_mmap_list, list) {
if (mif_mmap_node->driver == mmap_driver) {
slsi_dlist_del(&mif_mmap_node->list);
kmm_free(mif_mmap_node);
}
}
}
| 1,924 |
2,293 | /*
* Copyright (C) 2010-2021 Arm Limited or its affiliates.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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
*
* 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.
*/
// Generated by generate_test_data.py using TFL version 2.6.0 as reference.
#pragma once
#include <stdint.h>
const q7_t conv_out_activation_weights[36] = {-4, -65, -85, -9, -108, -106, -17, 17, 93, -97, -127, 23,
-81, 42, -12, 0, 29, 40, -90, -74, -10, -42, 74, -104,
-58, 74, 17, 5, -58, 123, -127, 59, -90, -5, 16, -104};
| 437 |
478 | /*
Copyright (c) 2014 Aerys
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "minko/Common.hpp"
#include "minko/Signal.hpp"
#include "minko/component/AbstractAnimation.hpp"
#include "minko/component/AbstractRebindableComponent.hpp"
namespace minko
{
namespace component
{
class MasterAnimation :
public AbstractAnimation
{
public:
typedef std::shared_ptr<MasterAnimation> Ptr;
private:
typedef std::shared_ptr<Animation> AnimationPtr;
typedef std::shared_ptr<AbstractAnimation> AbstractAnimationPtr;
typedef std::shared_ptr<scene::Node> NodePtr;
typedef std::shared_ptr<AbstractComponent> AbsCmpPtr;
private:
std::vector<AbstractAnimationPtr> _animations;
public:
inline static
Ptr
create(bool isLooping = true)
{
Ptr ptr(new MasterAnimation(isLooping));
return ptr;
}
AbstractAnimation::Ptr
play();
AbstractAnimation::Ptr
stop();
AbstractAnimationPtr
seek(uint time);
AbstractAnimation::Ptr
seek(const std::string& labelName);
AbsCmpPtr
clone(const CloneOption& option);
AbstractAnimation::Ptr
addLabel(const std::string& name, uint time);
AbstractAnimation::Ptr
changeLabel(const std::string& name, const std::string& newName);
AbstractAnimation::Ptr
setTimeForLabel(const std::string& name, uint newTime);
AbstractAnimation::Ptr
removeLabel(const std::string& name);
AbstractAnimation::Ptr
setPlaybackWindow(uint, uint, bool forceRestart = false);
AbstractAnimation::Ptr
setPlaybackWindow(const std::string&, const std::string&, bool forceRestart = false);
AbstractAnimation::Ptr
resetPlaybackWindow();
void
initAnimations();
void
rebindDependencies(std::map<AbsCmpPtr, AbsCmpPtr>& componentsMap, std::map<NodePtr, NodePtr>& nodeMap, CloneOption option);
inline
void
timeFunction(const std::function<uint(uint)>& func)
{
AbstractAnimation::timeFunction(func);
for (auto& animation : _animations)
animation->timeFunction(func);
}
inline
void
isReversed(bool value)
{
AbstractAnimation::isReversed(value);
for (auto& animation : _animations)
animation->isReversed(value);
}
protected:
MasterAnimation(bool isLooping);
MasterAnimation(const MasterAnimation& masterAnim, const CloneOption& option);
void
targetAdded(NodePtr target);
void
targetRemoved(NodePtr target);
virtual
void
addedHandler(NodePtr node, NodePtr target, NodePtr parent);
virtual
void
removedHandler(NodePtr node, NodePtr target, NodePtr parent);
void
update();
};
}
}
| 1,391 |
5,362 | <gh_stars>1000+
from pokemongo_bot import inventory
from pokemongo_bot.inventory import Pokemon
from pokemongo_bot.inventory import Pokemons
from pokemongo_bot.human_behaviour import sleep, action_delay
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.worker_result import WorkerResult
from datetime import datetime, timedelta
class BadPokemon(BaseTask):
SUPPORTED_TASK_API_VERSION = 1
def __init__(self, bot, config):
super(BadPokemon, self).__init__(bot, config)
def initialize(self):
self.config_transfer = self.config.get('transfer', False)
self.config_bulktransfer_enabled = self.config.get('bulktransfer_enabled', True)
self.config_action_wait_min = self.config.get("action_wait_min", 3)
self.config_action_wait_max = self.config.get("action_wait_max", 5)
self.min_interval = self.config.get('min_interval', 120)
self.config_max_bulktransfer = self.config.get('max_bulktransfer', 100)
self.next_update = None
def work(self):
bad_pokemons = [p for p in inventory.pokemons().all() if p.is_bad]
if len(bad_pokemons) > 0:
if self._should_print():
self.logger.warning("You have %s bad (slashed) Pokemon!" % len(bad_pokemons))
self._compute_next_update()
sleep(1)
if self.config_transfer:
self.transfer_pokemon(bad_pokemons)
return WorkerResult.SUCCESS
def _should_print(self):
return self.next_update is None or datetime.now() >= self.next_update
def _compute_next_update(self):
self.next_update = datetime.now() + timedelta(seconds=self.min_interval)
def transfer_pokemon(self, pokemons, skip_delay=False):
error_codes = {
0: 'UNSET',
1: 'SUCCESS',
2: 'POKEMON_DEPLOYED',
3: 'FAILED',
4: 'ERROR_POKEMON_IS_EGG',
5: 'ERROR_POKEMON_IS_BUDDY'
}
if self.config_bulktransfer_enabled and len(pokemons) > 1:
while len(pokemons) > 0:
action_delay(self.config_action_wait_min, self.config_action_wait_max)
pokemon_ids = []
count = 0
transfered = []
while len(pokemons) > 0 and count < self.config_max_bulktransfer:
pokemon = pokemons.pop()
transfered.append(pokemon)
pokemon_ids.append(pokemon.unique_id)
count = count + 1
try:
if self.config_transfer:
request = self.bot.api.create_request()
request.release_pokemon(pokemon_ids=pokemon_ids)
response_dict = request.call()
result = response_dict['responses']['RELEASE_POKEMON']['result']
if result != 1:
self.logger.error(u'Error while transfer pokemon: {}'.format(error_codes[result]))
return False
except Exception:
return False
for pokemon in transfered:
candy = inventory.candies().get(pokemon.pokemon_id)
if self.config_transfer and (not self.bot.config.test):
candy.add(1)
self.emit_event("pokemon_release",
formatted="Exchanged {pokemon} [IV {iv}] [CP {cp}] [{candy} candies]",
data={"pokemon": pokemon.name,
"iv": pokemon.iv,
"cp": pokemon.cp,
"candy": candy.quantity})
if self.config_transfer:
inventory.pokemons().remove(pokemon.unique_id)
with self.bot.database as db:
cursor = db.cursor()
cursor.execute("SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name='transfer_log'")
db_result = cursor.fetchone()
if db_result[0] == 1:
db.execute("INSERT INTO transfer_log (pokemon, iv, cp) VALUES (?, ?, ?)", (pokemon.name, pokemon.iv, pokemon.cp))
else:
for pokemon in pokemons:
if self.config_transfer and (not self.bot.config.test):
request = self.bot.api.create_request()
request.release_pokemon(pokemon_id=pokemon.unique_id)
response_dict = request.call()
else:
response_dict = {"responses": {"RELEASE_POKEMON": {"candy_awarded": 0}}}
if not response_dict:
return False
candy_awarded = response_dict.get("responses", {}).get("RELEASE_POKEMON", {}).get("candy_awarded", 0)
candy = inventory.candies().get(pokemon.pokemon_id)
if self.config_transfer and (not self.bot.config.test):
candy.add(candy_awarded)
self.emit_event("pokemon_release",
formatted="Exchanged {pokemon} [IV {iv}] [CP {cp}] [{candy} candies]",
data={"pokemon": pokemon.name,
"iv": pokemon.iv,
"cp": pokemon.cp,
"candy": candy.quantity})
if self.config_transfer and (not self.bot.config.test):
inventory.pokemons().remove(pokemon.unique_id)
with self.bot.database as db:
cursor = db.cursor()
cursor.execute("SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name='transfer_log'")
db_result = cursor.fetchone()
if db_result[0] == 1:
db.execute("INSERT INTO transfer_log (pokemon, iv, cp) VALUES (?, ?, ?)", (pokemon.name, pokemon.iv, pokemon.cp))
if not skip_delay:
action_delay(self.config_action_wait_min, self.config_action_wait_max)
return True
| 3,275 |
1,467 | <reponame>akshatkarani/iroha
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_SHARED_MODEL_PROTO_ROLES_RESPONSE_HPP
#define IROHA_SHARED_MODEL_PROTO_ROLES_RESPONSE_HPP
#include "interfaces/query_responses/roles_response.hpp"
#include "qry_responses.pb.h"
namespace shared_model {
namespace proto {
class RolesResponse final : public interface::RolesResponse {
public:
explicit RolesResponse(iroha::protocol::QueryResponse &query_response);
const RolesIdType &roles() const override;
private:
const iroha::protocol::RolesResponse &roles_response_;
const RolesIdType roles_;
};
} // namespace proto
} // namespace shared_model
#endif // IROHA_SHARED_MODEL_PROTO_ROLES_RESPONSE_HPP
| 317 |
923 | <filename>engine/utils/Utils.hpp
// Ouzel by <NAME>
#ifndef OUZEL_UTILS_UTILS_HPP
#define OUZEL_UTILS_UTILS_HPP
#include <cstdint>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>
namespace ouzel
{
template <class T>
auto getVectorSize(const T& vec) noexcept
{
return sizeof(typename T::value_type) * vec.size();
}
template <typename T, typename Iterator>
std::enable_if_t<std::is_unsigned_v<T>, T> decodeBigEndian(Iterator iterator) noexcept
{
T result = T(0);
for (std::size_t i = 0; i < sizeof(T); ++i, ++iterator)
result |= static_cast<T>(static_cast<std::uint8_t>(*iterator) << ((sizeof(T) - i - 1) * 8));
return result;
}
template <typename T, typename Iterator>
std::enable_if_t<std::is_unsigned_v<T>, T> decodeLittleEndian(Iterator iterator) noexcept
{
T result = T(0);
for (std::size_t i = 0; i < sizeof(T); ++i, ++iterator)
result |= static_cast<T>(static_cast<std::uint8_t>(*iterator) << (i * 8));
return result;
}
template <typename T, std::enable_if_t<std::is_unsigned_v<T>>* = nullptr>
void encodeBigEndian(std::uint8_t* buffer, const T value) noexcept
{
for (std::size_t i = 0; i < sizeof(T); ++i)
buffer[i] = static_cast<std::uint8_t>(value >> ((sizeof(T) - i - 1) * 8));
}
template <typename T, std::enable_if_t<std::is_unsigned_v<T>>* = nullptr>
void encodeLittleEndian(std::uint8_t* buffer, const T value) noexcept
{
for (std::size_t i = 0; i < sizeof(T); ++i)
buffer[i] = static_cast<std::uint8_t>(value >> (i * 8));
}
inline auto explodeString(std::string_view str, char delimiter = ' ')
{
std::vector<std::string> result;
for (std::size_t position = 0, beginPosition = 0; position != std::string::npos; beginPosition = position + 1)
{
position = str.find(delimiter, beginPosition);
const std::size_t endPosition = (position == std::string::npos) ? str.size() : position;
if (endPosition != beginPosition)
result.push_back(std::string{str.substr(beginPosition, endPosition - beginPosition)});
}
return result;
}
}
#endif // OUZEL_UTILS_UTILS_HPP
| 1,024 |
462 | def hola():
import builtins
print(builtins.__aiotasks__) | 31 |
10,340 | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.logstash.instrument.metrics.counter;
import org.junit.Before;
import org.junit.Test;
import org.logstash.instrument.metrics.MetricType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link LongCounter}
*/
public class LongCounterTest {
private final long INITIAL_VALUE = 0l;
private LongCounter longCounter;
@Before
public void _setup() {
longCounter = new LongCounter("bar");
}
@Test
public void getValue() {
assertThat(longCounter.getValue()).isEqualTo(INITIAL_VALUE);
}
@Test
public void increment() {
longCounter.increment();
assertThat(longCounter.getValue()).isEqualTo(INITIAL_VALUE + 1);
}
@Test(expected = IllegalArgumentException.class)
public void incrementByNegativeValue() {
longCounter.increment(-100l);
}
@Test(expected = IllegalArgumentException.class)
public void incrementByNegativeLongValue() {
longCounter.increment(Long.valueOf(-100));
}
@Test
public void incrementByValue() {
longCounter.increment(100l);
assertThat(longCounter.getValue()).isEqualTo(INITIAL_VALUE + 100);
longCounter.increment(Long.valueOf(100));
assertThat(longCounter.getValue()).isEqualTo(INITIAL_VALUE + 200);
}
@Test
public void noInitialValue() {
LongCounter counter = new LongCounter("bar");
counter.increment();
assertThat(counter.getValue()).isEqualTo(1l);
}
@Test
@SuppressWarnings("deprecation")
public void type() {
assertThat(longCounter.type()).isEqualTo(MetricType.COUNTER_LONG.asString());
}
}
| 849 |
777 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_WIN_JUMPLIST_FACTORY_H_
#define CHROME_BROWSER_WIN_JUMPLIST_FACTORY_H_
#include "base/memory/singleton.h"
#include "chrome/browser/win/jumplist.h"
#include "components/keyed_service/content/refcounted_browser_context_keyed_service_factory.h"
class JumpListFactory : public RefcountedBrowserContextKeyedServiceFactory {
public:
static scoped_refptr<JumpList> GetForProfile(Profile* profile);
static JumpListFactory* GetInstance();
private:
friend struct base::DefaultSingletonTraits<JumpListFactory>;
JumpListFactory();
~JumpListFactory() override;
// BrowserContextKeyedServiceFactory:
scoped_refptr<RefcountedKeyedService> BuildServiceInstanceFor(
content::BrowserContext* context) const override;
};
#endif // CHROME_BROWSER_WIN_JUMPLIST_FACTORY_H_
| 313 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.