max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
4,036 | <reponame>vadi2/codeql<gh_stars>1000+
package org.owasp.esapi;
public interface Encoder {
String encodeForLDAP(String input);
}
| 49 |
854 | <filename>Python3/1024.py
__________________________________________________________________________________________________
sample 28 ms submission
class Solution:
def videoStitching(self, clips: List[List[int]], T: int) -> int:
clips.sort()
count = 0
stitched_end = 0
candidate_end = 0
for start, end in clips+[[float('inf'), float('inf')]]:
if start > stitched_end: # no overlap
stitched_end = candidate_end
count += 1
if stitched_end >= T:
break
if start <= stitched_end: # overlap, with stitched_end
# adjusted or unadujsted
candidate_end = max(candidate_end, end)
return count if stitched_end>=T else -1
__________________________________________________________________________________________________
sample 13248 kb submission
class Solution:
def videoStitching(self, clips, T: int) -> int:
cnt=0
total=0
select=True
while total<T and select:# and len(clips)<
select=False
aa=[]
for k in clips:
if k[0]<=total and k[1]>total:
aa.append(k[1])
select=True
cnt+=1
if select:
total=max(total,max(aa))
return -1 if T>total else cnt
__________________________________________________________________________________________________
| 692 |
24,939 | import recorder
addons = [recorder.Recorder("c")]
| 17 |
14,668 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_PERFORMANCE_MANAGER_PERSISTENCE_SITE_DATA_SITE_DATA_CACHE_INSPECTOR_H_
#define COMPONENTS_PERFORMANCE_MANAGER_PERSISTENCE_SITE_DATA_SITE_DATA_CACHE_INSPECTOR_H_
#include <cstdint>
#include <memory>
#include <vector>
#include "base/callback.h"
#include "base/supports_user_data.h"
#include "components/performance_manager/persistence/site_data/site_data.pb.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/origin.h"
namespace performance_manager {
class SiteDataCache;
// An interface that allows LocalSite data cachess to expose diagnostic
// information for the associated web UI.
class SiteDataCacheInspector {
public:
// Returns the name of the data cache, which should uniquely identify the kind
// of storage it implements.
virtual const char* GetDataCacheName() = 0;
// Retrieves the origins that are current represented by in-memory data
// at the present time.
virtual std::vector<url::Origin> GetAllInMemoryOrigins() = 0;
// Retrieves the number of rows and the on-disk size of the store. Invokes
// the |on_have_data| callback once the data has been collected, or once it's
// determined that the data can't be retrieved.
// On callback |num_rows| is the number of rows in the database, or -1 if
// the number can't be determined. |on_disk_size_kb| is the on-disk size of
// the database, or -1 if the on-disk size can't be determined.
using DataStoreSizeCallback =
base::OnceCallback<void(absl::optional<int64_t> num_rows,
absl::optional<int64_t> on_disk_size_kb)>;
virtual void GetDataStoreSize(DataStoreSizeCallback on_have_data) = 0;
// Retrieves the in-memory data for a given origin.
// On return |data| contains the available data for |origin| if available,
// and |is_dirty| is true if the entry needs flushing to disk.
// Returns true if an entry exists for |origin|.
virtual bool GetDataForOrigin(const url::Origin& origin,
bool* is_dirty,
std::unique_ptr<SiteDataProto>* data) = 0;
// Retrieves the data cache this inspector is associated with.
virtual SiteDataCache* GetDataCache() = 0;
};
} // namespace performance_manager
#endif // COMPONENTS_PERFORMANCE_MANAGER_PERSISTENCE_SITE_DATA_SITE_DATA_CACHE_INSPECTOR_H_
| 860 |
342 | <filename>mobile-client-android/sentinel_android/app/src/main/java/sentinelgroup/io/sentinel/network/model/BookmarkEntity.java<gh_stars>100-1000
package sentinelgroup.io.sentinel.network.model;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Index;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
@Entity(tableName = "bookmark_entity", indices = {@Index(value = {"accountAddress"}, unique = true)})
public class BookmarkEntity implements Serializable {
@PrimaryKey
@NonNull
@SerializedName("account_addr")
private String accountAddress;
private String ip;
public BookmarkEntity(@NonNull String accountAddress, String ip) {
this.accountAddress = accountAddress;
this.ip = ip;
}
@NonNull
public String getAccountAddress() {
return accountAddress;
}
public void setAccountAddress(@NonNull String accountAddress) {
this.accountAddress = accountAddress;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Override
public boolean equals(@Nullable Object obj) {
return obj instanceof BookmarkEntity && this.accountAddress.equals(((BookmarkEntity) obj).accountAddress) && this.ip.equals(((BookmarkEntity) obj).ip);
}
@Override
public int hashCode() {
return (accountAddress + ip).hashCode();
}
}
| 548 |
2,323 | {
"author": "ReactJS.NET contributors",
"classifications": [
"Web"
],
"name": "React.NET Webpack Starter Template",
"identity": "React.Template.NetCore.Webpack",
"shortName": "reactnet-webpack",
"tags": {
"language": "C#"
},
"preferNameDirectory": "true"
}
| 109 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef TimestampCollection_h
#define TimestampCollection_h
#pragma once
#if defined(USING_BEHAVIOR_TREE_TIMESTAMP_DEBUGGING) || defined(USING_BEHAVIOR_TREE_EDITOR)
#define STORE_EXTRA_TIMESTAMP_DATA
#endif
#if defined(USING_BEHAVIOR_TREE_SERIALIZATION)
#include <Serialization/StringList.h>
#endif
namespace BehaviorTree
{
// Unique identifier for a timestamp. (The CRC of the timestamp name.)
struct TimestampID
{
TimestampID()
: id(0)
{
}
TimestampID(const char* name)
{
#ifdef STORE_EXTRA_TIMESTAMP_DATA
timestampName = name;
#endif
id = CCrc32::Compute(name);
}
bool operator == (const TimestampID& rhs) const
{
return id == rhs.id;
}
operator bool () const
{
return id != 0;
}
#ifdef STORE_EXTRA_TIMESTAMP_DATA
string timestampName;
#endif
unsigned int id;
};
struct Timestamp;
typedef std::vector<Timestamp> Timestamps;
// A timestamp is a small piece of information on when a certain event
// occurred. For example, this is useful if you want to query when
// a character was last shot at or hit, or maybe when he last could
// see the player. Or when he last moved to a new cover location.
//
// Optional:
// Timestamps can be declared as exclusive to each other. For example,
// <EnemySeenTime> could be said to be exclusive to <EnemyLostTime>.
// You can't see the player and at the same time consider him lost.
struct Timestamp
{
Timestamp()
: hasBeenSetAtLeastOnce(false)
{
Invalidate();
}
TimestampID id;
TimestampID exclusiveTo;
CTimeValue time;
uint32 setOnEventNameCRC32;
bool hasBeenSetAtLeastOnce;
#if defined(STORE_EXTRA_TIMESTAMP_DATA)
string setOnEventName;
#endif
bool IsValid() const
{
return time.GetMilliSecondsAsInt64() >= 0;
}
void Invalidate()
{
time = CTimeValue(-1.0f);
}
#if defined (USING_BEHAVIOR_TREE_SERIALIZATION)
void Serialize(Serialization::IArchive& archive)
{
archive(id.timestampName, "name", "^<Name");
archive(setOnEventName, "setOnEventName", "^<Set on event");
if (id.timestampName.empty())
{
archive.Error(id.timestampName, "Name must be specified");
}
if (setOnEventName.empty())
{
archive.Error(setOnEventName, "Event must be specified");
}
bool refenreceFound = false;
Serialization::StringList exclusiveToTimestampList;
exclusiveToTimestampList.push_back("");
Timestamps* timestamps = archive.FindContext<Timestamps>();
for (Timestamps::const_iterator it = timestamps->begin(), end = timestamps->end(); it != end; ++it)
{
const Timestamp& timestamp = *it;
if (timestamp.id.timestampName == id.timestampName)
{
if (refenreceFound)
{
archive.Error(id.timestampName, "Duplicated timestamp name");
}
refenreceFound = true;
continue;
}
exclusiveToTimestampList.push_back(timestamp.id.timestampName);
}
Serialization::StringListValue exclusiveToStringListValue(exclusiveToTimestampList, exclusiveTo.timestampName);
archive(exclusiveToStringListValue, "exclusiveTo", "^<Exclusive To");
exclusiveTo.timestampName = exclusiveToStringListValue.c_str();
}
bool operator < (const Timestamp& rhs) const
{
return (id.timestampName < rhs.id.timestampName);
}
#endif
};
// Contains information about when certain events occurred.
// Allows us to get answers to the following questions:
// Q: How long was it since X happened?
// Q: How long has Y been going on?
class TimestampCollection
{
struct MatchesID
{
const TimestampID& id;
MatchesID(const TimestampID& _id)
: id(_id) {}
bool operator () (const Timestamp& timestamp) const { return timestamp.id == id; }
};
public:
bool HasBeenSetAtLeastOnce(const TimestampID& id) const
{
const Timestamps::const_iterator it = std::find_if(m_timestamps.begin(), m_timestamps.end(), MatchesID(id));
if (it != m_timestamps.end())
{
return it->hasBeenSetAtLeastOnce;
}
return false;
}
void GetElapsedTimeSince(const TimestampID& id, CTimeValue& elapsedTime, bool& valid) const
{
const Timestamps::const_iterator it = std::find_if(m_timestamps.begin(), m_timestamps.end(), MatchesID(id));
if (it != m_timestamps.end())
{
if (it->IsValid())
{
valid = true;
elapsedTime = gEnv->pTimer->GetFrameStartTime() - it->time;
return;
}
}
valid = false;
elapsedTime = CTimeValue(0.0f);
}
void HandleEvent(uint32 eventNameCRC32)
{
TimestampIDs timestampsToInvalidate;
{
// Go through timestamps, refresh the time value and see if there
// are any exclusive timestamps that should be removed.
Timestamps::iterator it = m_timestamps.begin();
Timestamps::iterator end = m_timestamps.end();
for (; it != end; ++it)
{
Timestamp& timestamp = *it;
if (timestamp.setOnEventNameCRC32 == eventNameCRC32)
{
timestamp.time = gEnv->pTimer->GetFrameStartTime();
timestamp.hasBeenSetAtLeastOnce = true;
if (timestamp.exclusiveTo)
{
timestampsToInvalidate.push_back(timestamp.exclusiveTo);
}
}
}
}
{
// Invalidate the timestamps that were pushed out via exclusivity
TimestampIDs::iterator it = timestampsToInvalidate.begin();
TimestampIDs::iterator end = timestampsToInvalidate.end();
for (; it != end; ++it)
{
Timestamps::iterator timestamp = std::find_if(m_timestamps.begin(), m_timestamps.end(), MatchesID(*it));
if (timestamp != m_timestamps.end())
{
timestamp->Invalidate();
}
}
}
}
void LoadFromXml(const XmlNodeRef& xml)
{
for (int i = 0; i < xml->getChildCount(); ++i)
{
XmlNodeRef child = xml->getChild(i);
const char* name = child->getAttr("name");
const char* setOnEvent = child->getAttr("setOnEvent");
const char* exclusiveTo = child->getAttr("exclusiveTo");
if (!name)
{
gEnv->pLog->LogError("Missing 'name' attribute at line %d.", xml->getLine());
continue;
}
Timestamp timestamp;
timestamp.id = TimestampID(name);
timestamp.setOnEventNameCRC32 = CCrc32::Compute(setOnEvent);
timestamp.exclusiveTo = TimestampID(exclusiveTo);
#if defined (STORE_EXTRA_TIMESTAMP_DATA)
timestamp.setOnEventName = setOnEvent;
#endif
m_timestamps.push_back(timestamp);
}
}
const Timestamps& GetTimestamps() const { return m_timestamps; }
#if defined (USING_BEHAVIOR_TREE_SERIALIZATION)
void Serialize(Serialization::IArchive& archive)
{
if (archive.IsOutput())
{
std::sort(m_timestamps.begin(), m_timestamps.end());
}
Serialization::SContext<Timestamps> variableDeclarations(archive, &m_timestamps);
archive(m_timestamps, "timestamps", "^[<>]");
}
#endif
#if defined (USING_BEHAVIOR_TREE_XML_DESCRIPTION_CREATION)
XmlNodeRef CreateXmlDescription()
{
if (m_timestamps.size() == 0)
{
return XmlNodeRef();
}
XmlNodeRef timestampsXml = GetISystem()->CreateXmlNode("Timestamps");
for (Timestamps::const_iterator it = m_timestamps.begin(), end = m_timestamps.end(); it != end; ++it)
{
const Timestamp& timestamp = *it;
XmlNodeRef timestampXml = GetISystem()->CreateXmlNode("Timestamp");
timestampXml->setAttr("name", timestamp.id.timestampName);
timestampXml->setAttr("setOnEvent", timestamp.setOnEventName);
if (!timestamp.exclusiveTo.timestampName.empty())
{
timestampXml->setAttr("exclusiveTo", timestamp.exclusiveTo.timestampName);
}
timestampsXml->addChild(timestampXml);
}
return timestampsXml;
}
#endif
private:
typedef std::vector<TimestampID> TimestampIDs;
Timestamps m_timestamps;
};
}
#endif // TimestampCollection_h | 5,003 |
2,151 | <reponame>UCLA-SEAL/JShrink<filename>code/jshrink/jshrink-lib/src/test/resources/junit4/src/main/java/org/junit/runners/model/TestTimedOutException.java<gh_stars>1000+
package org.junit.runners.model;
import java.util.concurrent.TimeUnit;
/**
* Exception thrown when a test fails on timeout.
*
* @since 4.12
*
*/
public class TestTimedOutException extends Exception {
private static final long serialVersionUID = 31935685163547539L;
private final TimeUnit timeUnit;
private final long timeout;
/**
* Creates exception with a standard message "test timed out after [timeout] [timeUnit]"
*
* @param timeout the amount of time passed before the test was interrupted
* @param timeUnit the time unit for the timeout value
*/
public TestTimedOutException(long timeout, TimeUnit timeUnit) {
super(String.format("test timed out after %d %s",
timeout, timeUnit.name().toLowerCase()));
this.timeUnit = timeUnit;
this.timeout = timeout;
}
/**
* Gets the time passed before the test was interrupted
*/
public long getTimeout() {
return timeout;
}
/**
* Gets the time unit for the timeout value
*/
public TimeUnit getTimeUnit() {
return timeUnit;
}
}
| 469 |
1,682 | /*
Copyright (c) 2012 LinkedIn Corp.
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.linkedin.d2.jmx;
import java.net.URISyntaxException;
import java.util.List;
public interface SimpleLoadBalancerStateJmxMBean
{
int getUriCount();
int getClusterCount();
int getServiceCount();
long getVersion();
int getClusterListenCount();
int getServiceListenCount();
int getListenerCount();
List<String> getSupportedStrategies();
List<String> getSupportedSchemes();
int getTrackerClientCount(String clusterName);
String getUriProperty(String clusterName);
String getClusterProperty(String clusterName);
String getServiceProperty(String serviceName);
boolean isListeningToCluster(String clusterName);
boolean isListeningToService(String serviceName);
void setVersion(long version);
void listenToService(final String serviceName);
void listenToCluster(final String clusterName);
long getDelayedExecution();
void setDelayedExecution(long milliseconds);
/**
* @param serviceName this can be obtained through serviceProperty
* @return returns a list of tracker clients URI (this will include banned URI for the cluster)
*/
String getServerUrisForServiceName(String serviceName);
/**
*
* @param trackerClientUri the URI for trackerClient
* @param serviceName this can be obtained through serviceProperty
* @return the trackerClient information for that URI
*/
String getTrackerClientInformation(String trackerClientUri, String serviceName) throws URISyntaxException;
/**
* get what services are mapped to this cluster according to the state's internal mapping. Useful for debugging.
* @param clusterName
*/
String getInternalMappingServicesForClusterName(String clusterName);
}
| 614 |
10,948 | <filename>examples/ace/ttcp/ttcp_asio_sync.cc
#include "examples/ace/ttcp/common.h"
#include "muduo/base/Logging.h"
#include <boost/asio.hpp>
#include <stdio.h>
using boost::asio::ip::tcp;
void transmit(const Options& opt)
{
try
{
}
catch (std::exception& e)
{
LOG_ERROR << e.what();
}
}
void receive(const Options& opt)
{
try
{
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), opt.port));
tcp::socket socket(io_service);
acceptor.accept(socket);
struct SessionMessage sessionMessage = { 0, 0 };
boost::system::error_code error;
size_t nr = boost::asio::read(socket, boost::asio::buffer(&sessionMessage, sizeof sessionMessage),
#if BOOST_VERSION < 104700L
boost::asio::transfer_all(),
#endif
error);
if (nr != sizeof sessionMessage)
{
LOG_ERROR << "read session message: " << error.message();
exit(1);
}
sessionMessage.number = ntohl(sessionMessage.number);
sessionMessage.length = ntohl(sessionMessage.length);
printf("receive number = %d\nreceive length = %d\n",
sessionMessage.number, sessionMessage.length);
const int total_len = static_cast<int>(sizeof(int32_t) + sessionMessage.length);
PayloadMessage* payload = static_cast<PayloadMessage*>(::malloc(total_len));
std::unique_ptr<PayloadMessage, void (*)(void*)> freeIt(payload, ::free);
assert(payload);
for (int i = 0; i < sessionMessage.number; ++i)
{
payload->length = 0;
if (boost::asio::read(socket, boost::asio::buffer(&payload->length, sizeof(payload->length)),
#if BOOST_VERSION < 104700L
boost::asio::transfer_all(),
#endif
error) != sizeof(payload->length))
{
LOG_ERROR << "read length: " << error.message();
exit(1);
}
payload->length = ntohl(payload->length);
assert(payload->length == sessionMessage.length);
if (boost::asio::read(socket, boost::asio::buffer(payload->data, payload->length),
#if BOOST_VERSION < 104700L
boost::asio::transfer_all(),
#endif
error) != static_cast<size_t>(payload->length))
{
LOG_ERROR << "read payload data: " << error.message();
exit(1);
}
int32_t ack = htonl(payload->length);
if (boost::asio::write(socket, boost::asio::buffer(&ack, sizeof(ack))) != sizeof(ack))
{
LOG_ERROR << "write ack: " << error.message();
exit(1);
}
}
}
catch (std::exception& e)
{
LOG_ERROR << e.what();
}
}
| 1,169 |
761 | <reponame>l1kw1d/stashboard<filename>tests/runner.py<gh_stars>100-1000
#!/usr/bin/python
import sys
import nose
import os
SDK_PATH = os.environ.get("APPENGINE_SDK", "/usr/local/google_appengine/")
def main():
#logging.basicConfig(level=logging.DEBUG)
sys.path.insert(0, SDK_PATH)
sys.path.insert(0, "stashboard")
sys.path.insert(0, "stashboard/contrib")
import dev_appserver
dev_appserver.fix_sys_path()
nose.main()
if __name__ == '__main__':
main()
| 206 |
589 | package rocks.inspectit.shared.cs.cmr.property.configuration.validator.impl;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang.StringUtils;
import rocks.inspectit.shared.all.util.EMailUtils;
import rocks.inspectit.shared.cs.cmr.property.configuration.SingleProperty;
import rocks.inspectit.shared.cs.cmr.property.configuration.validator.AbstractSinglePropertyValidator;
import rocks.inspectit.shared.cs.cmr.property.configuration.validator.ISinglePropertyValidator;
/**
* Checks a comma separated list (in a string) whether it contains an invalid e-mail address.
*
* @author <NAME>
*
*/
@XmlRootElement(name = "isValidEMailList")
public class EMailListValidator extends AbstractSinglePropertyValidator<String> implements ISinglePropertyValidator<String> {
/**
* {@inheritDoc}
*/
@Override
protected boolean prove(String value) {
return value.isEmpty() || (getInvalidEmailAddress(value) == null);
}
/**
* {@inheritDoc}
*/
@Override
protected String getErrorMessage(SingleProperty<? extends String> property) {
return "At least one entry in property '" + property.getName() + "' is not a valid e-mail address";
}
/**
* Checks whether the given comma separated list string contains an invalid e-mail address.
*
* @param commaSeparatedList
* String to check.
* @return Returns the first invalid e-mail address or null if all e-mail addresses are valid.
*/
private String getInvalidEmailAddress(String commaSeparatedList) {
String[] strArray = StringUtils.splitPreserveAllTokens(commaSeparatedList, ',');
for (int i = 0; i < strArray.length; i++) {
if (!EMailUtils.isValidEmailAddress(strArray[i])) {
return strArray[i];
}
}
return null;
}
}
| 565 |
1,405 | <filename>sample4/recompiled_java/sources/com/lenovo/safecenter/database/AppUtil.java
package com.lenovo.safecenter.database;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.lenovo.install.PackageUtil;
import com.lenovo.providers.querypermissions.QueryPermissions;
import com.lenovo.safecenter.R;
import com.lenovo.safecenter.support.AppInfo;
import com.lenovo.safecenter.support.MD5Util;
import com.lenovo.safecenter.support.WhiteAppsList;
import com.lenovo.safecenter.utils.Const;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class AppUtil {
public static int PERM_TOTAL = 15;
private static int a = 8;
private static int b = 3;
private static int c = 2;
public static List<ApplicationInfo> getInstalledThirdApps(Context context) {
PackageManager pm = context.getPackageManager();
ArrayList<ApplicationInfo> third_apps = new ArrayList<>();
List<ApplicationInfo> installedAppList = pm.getInstalledApplications(8192);
if (installedAppList == null) {
return Collections.emptyList();
}
for (ApplicationInfo applicationInfo : installedAppList) {
if (isThirdpartApp(applicationInfo) && !Const.LENOVO_APKS.contains(applicationInfo.packageName + "\n")) {
third_apps.add(applicationInfo);
}
}
return third_apps;
}
public static boolean isThirdpartApp(ApplicationInfo appInfo) {
if ((appInfo.flags & 128) == 0 && (appInfo.flags & 1) != 0) {
return false;
}
return true;
}
private static int a(int[] selected, int start, int len) {
for (int i = start; i < start + len; i++) {
if (selected[i] == 1) {
return 1;
}
}
return 0;
}
public static HashMap<String, String> getAppPermissionConfigurs(ContentResolver resolver, String pkgname) {
HashMap<String, String> map = new HashMap<>();
map.put(AppDatabase.PERM_TYPE_PRIVCY, "-1");
map.put(AppDatabase.PERM_TYPE_DEVICE, "-1");
map.put("location", "-1");
map.put(AppDatabase.DB_APP_SENDMESSAGE, "-1");
map.put(AppDatabase.DB_APP_CALL, "-1");
Cursor cursor = null;
try {
Cursor cursor2 = resolver.query(Uri.parse("content://com.lenovo.providers.querypermissions/pkgname/" + pkgname), null, null, null, null);
if (cursor2.moveToFirst()) {
int[] selected = new int[PERM_TOTAL];
for (int i = 0; i < selected.length; i++) {
String tmp = cursor2.getString(i + 2);
if (TextUtils.isEmpty(tmp)) {
selected[i] = 0;
} else {
selected[i] = Integer.valueOf(tmp).intValue();
}
}
map.put(AppDatabase.PERM_TYPE_PRIVCY, Integer.toString(a(selected, 0, a)));
map.put(AppDatabase.PERM_TYPE_DEVICE, Integer.toString(a(selected, a, c)));
map.put("location", Integer.toString(a(selected, a + c, b)));
if (selected[PERM_TOTAL - 2] == -1) {
selected[PERM_TOTAL - 2] = 2;
}
map.put(AppDatabase.DB_APP_SENDMESSAGE, Integer.toString(selected[PERM_TOTAL - 2]));
if (selected[PERM_TOTAL - 1] == -1) {
selected[PERM_TOTAL - 1] = 0;
}
map.put(AppDatabase.DB_APP_CALL, Integer.toString(selected[PERM_TOTAL - 1]));
}
if (cursor2 != null) {
cursor2.close();
}
} catch (Exception e) {
e.printStackTrace();
if (0 != 0) {
cursor.close();
}
} catch (Throwable th) {
if (0 != 0) {
cursor.close();
}
throw th;
}
return map;
}
public static boolean checkPkgExit(ContentResolver resolver, String pkgname) {
boolean exit = false;
Cursor cursor = null;
try {
cursor = resolver.query(Uri.parse("content://com.lenovo.providers.querypermissions/pkgname/" + pkgname), null, null, null, null);
if (cursor.getCount() > 0) {
exit = true;
}
if (cursor != null) {
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
if (cursor != null) {
cursor.close();
}
} catch (Throwable th) {
if (cursor != null) {
cursor.close();
}
throw th;
}
return exit;
}
public static int getAppPermissionConfigurs(ContentResolver resolver, String pkgname, String type) {
int select;
Cursor cursor = null;
try {
Cursor cursor2 = resolver.query(Uri.parse("content://com.lenovo.providers.querypermissions/pkgname/" + pkgname + "/type/" + type), null, null, null, null);
if (cursor2.moveToFirst()) {
select = Integer.valueOf(cursor2.getString(cursor2.getColumnIndex(QueryPermissions.RECOMMENDEDACTION))).intValue();
} else if (type.equals(AppDatabase.DB_APP_SENDMESSAGE)) {
select = 2;
} else {
select = 1;
}
if (cursor2 != null) {
cursor2.close();
}
} catch (Exception e) {
e.printStackTrace();
if (type.equals(AppDatabase.DB_APP_SENDMESSAGE)) {
select = 2;
} else {
select = 0;
}
if (0 != 0) {
cursor.close();
}
} catch (Throwable th) {
if (0 != 0) {
cursor.close();
}
throw th;
}
return select;
}
public static ContentValues getContentValues(AppInfo app) {
ContentValues value = new ContentValues();
value.put("uid", Integer.valueOf(app.uid));
value.put("name", app.name);
value.put(AppDatabase.DB_SELECTED, Integer.valueOf(app.selected));
value.put(AppDatabase.APP_PKG_NAME, app.packageName);
value.put(AppDatabase.APP_PER_TYPE, app.appType);
value.put("pername", app.perName);
value.put(AppDatabase.DB_TRUSTED, Integer.valueOf(app.trusted));
value.put(AppDatabase.DB_SUGGEST, Integer.valueOf(app.suggest));
value.put("isupload", Integer.valueOf(app.isupload));
return value;
}
public static void insertApp(SQLiteDatabase db, AppInfo app) {
ContentValues value = new ContentValues();
value.put("uid", Integer.valueOf(app.uid));
value.put("name", app.name);
value.put(AppDatabase.DB_SELECTED, Integer.valueOf(app.selected));
value.put(AppDatabase.APP_PKG_NAME, app.packageName);
value.put(AppDatabase.APP_PER_TYPE, app.appType);
value.put("pername", app.perName);
value.put(AppDatabase.DB_TRUSTED, Integer.valueOf(app.trusted));
value.put(AppDatabase.DB_SUGGEST, Integer.valueOf(app.suggest));
value.put("isupload", Integer.valueOf(app.isupload));
db.insert(AppDatabase.DB_APP, "name", value);
}
public static boolean isNotExist(ArrayList<AppInfo> target, AppInfo appInfo) {
boolean flag = true;
Iterator i$ = target.iterator();
while (i$.hasNext()) {
if (i$.next().uid == appInfo.uid) {
flag = false;
}
}
return flag;
}
public static String getPerDescription(Context context, String perType) {
if (perType.equals("android.permission.READ_SMS") || perType.equals("android.permission.RECEIVE_SMS")) {
return context.getString(R.string.perm_rsms);
}
if (perType.equals("android.permission.READ_CONTACTS")) {
return context.getString(R.string.perm_rcontacts);
}
if (perType.equals("android.permission.READ_CALENDAR")) {
return context.getString(R.string.perm_calendar);
}
if (perType.equals("android.permission.ACCESS_COARSE_LOCATION")) {
return context.getString(R.string.perm_c_location);
}
if (perType.equals("android.permission.ACCESS_FINE_LOCATION")) {
return context.getString(R.string.perm_c_location);
}
if (perType.equals("android.permission.ACCESS_LOCATION_EXTRA_COMMANDS")) {
return context.getString(R.string.perm_c_location);
}
if (perType.equals("com.android.browser.permission.READ_HISTORY_BOOKMARKS")) {
return context.getString(R.string.perm_history);
}
if (perType.equals("android.permission.RECORD_AUDIO")) {
return context.getString(R.string.perm_record);
}
if (perType.equals("android.permission.CAMERA")) {
return context.getString(R.string.perm_camera);
}
if (perType.equals("android.permission.SEND_SMS")) {
return context.getString(R.string.perm_send_sms);
}
if (perType.equals("android.permission.CALL_PHONE")) {
return context.getString(R.string.perm_call);
}
if (perType.equals("android.permission.CALL_PRIVILEGED")) {
return context.getString(R.string.perm_call);
}
if (perType.equals("android.permission.INTERNET")) {
return context.getString(R.string.perm_internet);
}
if (perType.equals("android.permission.WRITE_SMS")) {
return context.getString(R.string.perm_wsms);
}
if (perType.equals("android.permission.WRITE_CONTACTS")) {
return context.getString(R.string.perm_wcontact);
}
return null;
}
public static String getDescriptionByType(Context context, AppDatabase database, String pkgname, String perType) {
if (perType.equals(AppDatabase.PERM_TYPE_PRIVCY)) {
return context.getString(R.string.perm_privacy_info);
}
if (perType.equals("location")) {
return context.getString(R.string.perm_c_location);
}
if (perType.equals(AppDatabase.PERM_TYPE_DEVICE)) {
return context.getString(R.string.perm_tap_calling);
}
if (perType.equals(AppDatabase.DB_APP_SENDMESSAGE)) {
return context.getString(R.string.perm_send_sms);
}
if (perType.equals(AppDatabase.DB_APP_CALL)) {
return context.getString(R.string.perm_call);
}
if (perType.equals(AppDatabase.DB_APP_INTERNET)) {
return context.getString(R.string.perm_internet);
}
return null;
}
public static String getDescriptionByPid(Context context, int pid) {
switch (pid) {
case 1:
return context.getString(R.string.perm_rsms);
case 2:
return context.getString(R.string.perm_rcalllogs);
case 3:
return context.getString(R.string.perm_rcontact);
case 4:
return context.getString(R.string.perm_calendar);
case 5:
case 48:
return context.getString(R.string.perm_c_location);
case 6:
return context.getString(R.string.perm_record);
case 7:
return context.getString(R.string.perm_camera);
case 8:
return context.getString(R.string.perm_call);
case 9:
return context.getString(R.string.perm_history);
case 11:
return context.getString(R.string.perm_send_sms);
case 44:
return context.getString(R.string.perm_wsms);
case 45:
return context.getString(R.string.perm_wcontact);
default:
return "";
}
}
public static int isSelected(ArrayList<AppInfo> list, int uid) {
if (list.size() == 0) {
return 0;
}
Iterator i$ = list.iterator();
while (i$.hasNext()) {
AppInfo appInfo = i$.next();
if (appInfo.uid == uid) {
return appInfo.selected;
}
}
return 0;
}
public static void getAppsForBoot(Context ctx, PackageManager pm, SQLiteDatabase db, ApplicationInfo appinfo, String permName, String typeName, boolean contains, boolean version, int suggest) {
int uid = appinfo.uid;
String pkgname = appinfo.packageName;
String name = pm.getApplicationLabel(appinfo).toString();
if (pm.checkPermission(permName, pkgname) == 0) {
Cursor cursor = db.rawQuery("select * from appname where uid=? and apptype=? and pername=?", new String[]{Integer.toString(uid), typeName, permName});
if (cursor.getCount() == 0) {
AppInfo app = new AppInfo();
app.packageName = pkgname;
app.uid = uid;
app.name = name;
app.appType = typeName;
app.perName = permName;
if (contains) {
app.trusted = 1;
app.selected = 0;
} else {
app.trusted = 0;
if (version) {
app.selected = 0;
} else if (suggest >= 0) {
app.selected = suggest;
} else if (typeName.equals(AppDatabase.DB_APP_SENDMESSAGE)) {
app.selected = 2;
} else if (app.appType.equals(AppDatabase.PERM_TYPE_PRIVCY)) {
app.selected = 1;
} else {
app.selected = 0;
}
}
insertApp(db, app);
}
cursor.close();
}
}
public static void getAppsForBoot(PackageManager pm, SQLiteDatabase db, String perName, String appType, AppInfo app, int selected, int suggest) {
if (pm.checkPermission(perName, app.packageName) == 0) {
app.perName = perName;
app.appType = appType;
app.selected = selected;
app.suggest = suggest;
ContentValues values = getContentValues(app);
if (db.update(AppDatabase.DB_APP, values, "packagename=? and pername=?", new String[]{app.packageName, app.perName}) <= 0) {
db.insert(AppDatabase.DB_APP, "name", values);
}
}
}
public static void configurateAppsPermission(Context context, PackageManager pm, SQLiteDatabase db, ContentResolver resolver, List<String> whiteApps, ApplicationInfo appinfo, boolean version) {
String pkgname = appinfo.packageName;
boolean contains = whiteApps.contains(pkgname);
HashMap<String, String> map = getAppPermissionConfigurs(resolver, pkgname);
int priSelect = Integer.valueOf(map.get(AppDatabase.PERM_TYPE_PRIVCY)).intValue();
getAppsForBoot(context, pm, db, appinfo, "android.permission.READ_SMS", AppDatabase.PERM_TYPE_PRIVCY, contains, version, priSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.WRITE_SMS", AppDatabase.PERM_TYPE_PRIVCY, contains, version, priSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.RECEIVE_SMS", AppDatabase.PERM_TYPE_PRIVCY, contains, version, priSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.READ_CONTACTS", AppDatabase.PERM_TYPE_PRIVCY, contains, version, priSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.WRITE_CONTACTS", AppDatabase.PERM_TYPE_PRIVCY, contains, version, priSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.READ_CALENDAR", AppDatabase.PERM_TYPE_PRIVCY, contains, version, priSelect);
getAppsForBoot(context, pm, db, appinfo, "com.android.browser.permission.READ_HISTORY_BOOKMARKS", AppDatabase.PERM_TYPE_PRIVCY, contains, version, priSelect);
int locSelect = Integer.valueOf(map.get("location")).intValue();
getAppsForBoot(context, pm, db, appinfo, "android.permission.ACCESS_COARSE_LOCATION", "location", contains, version, locSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.ACCESS_FINE_LOCATION", "location", contains, version, locSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS", "location", contains, version, locSelect);
int devSelect = Integer.valueOf(map.get(AppDatabase.PERM_TYPE_DEVICE)).intValue();
getAppsForBoot(context, pm, db, appinfo, "android.permission.RECORD_AUDIO", AppDatabase.PERM_TYPE_DEVICE, contains, version, devSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.CAMERA", AppDatabase.PERM_TYPE_DEVICE, contains, version, devSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.SEND_SMS", AppDatabase.DB_APP_SENDMESSAGE, contains, version, Integer.valueOf(map.get(AppDatabase.DB_APP_SENDMESSAGE)).intValue());
int callSelect = Integer.valueOf(map.get(AppDatabase.DB_APP_CALL)).intValue();
getAppsForBoot(context, pm, db, appinfo, "android.permission.CALL_PHONE", AppDatabase.DB_APP_CALL, contains, version, callSelect);
getAppsForBoot(context, pm, db, appinfo, "android.permission.CALL_PRIVILEGED", AppDatabase.DB_APP_CALL, contains, version, callSelect);
}
public static int getTrust(Map<String, AppInfo> permMap) {
if (permMap.get(AppDatabase.PERM_TYPE_PRIVCY) != null) {
return permMap.get(AppDatabase.PERM_TYPE_PRIVCY).trusted;
}
if (permMap.get("location") != null) {
return permMap.get("location").trusted;
}
if (permMap.get(AppDatabase.PERM_TYPE_DEVICE) != null) {
return permMap.get(AppDatabase.PERM_TYPE_DEVICE).trusted;
}
if (permMap.get(AppDatabase.DB_APP_CALL) != null) {
return permMap.get(AppDatabase.DB_APP_CALL).trusted;
}
if (permMap.get(AppDatabase.DB_APP_SENDMESSAGE) != null) {
return permMap.get(AppDatabase.DB_APP_SENDMESSAGE).trusted;
}
return 0;
}
public static void configurateAppsPermission(Context context, PackageManager pm, SQLiteDatabase db, ContentResolver resolver, ApplicationInfo appinfo, Map<String, AppInfo> permMap) {
int priSelect;
int locSelect;
String pkgname = appinfo.packageName;
HashMap<String, String> map = getAppPermissionConfigurs(resolver, pkgname);
AppInfo app = new AppInfo();
app.uid = appinfo.uid;
app.packageName = pkgname;
app.name = pm.getApplicationLabel(appinfo).toString();
app.trusted = getTrust(permMap);
if (permMap.get(AppDatabase.PERM_TYPE_PRIVCY) == null) {
priSelect = 0;
} else {
priSelect = permMap.get(AppDatabase.PERM_TYPE_PRIVCY).selected;
}
int priSuggest = Integer.valueOf(map.get(AppDatabase.PERM_TYPE_PRIVCY)).intValue();
Log.d("test", pkgname + ", priSelect:" + priSelect + ", priSuggest:" + priSuggest);
getAppsForBoot(pm, db, "android.permission.READ_SMS", AppDatabase.PERM_TYPE_PRIVCY, app, priSelect, priSuggest);
getAppsForBoot(pm, db, "android.permission.WRITE_SMS", AppDatabase.PERM_TYPE_PRIVCY, app, priSelect, priSuggest);
getAppsForBoot(pm, db, "android.permission.RECEIVE_SMS", AppDatabase.PERM_TYPE_PRIVCY, app, priSelect, priSuggest);
getAppsForBoot(pm, db, "android.permission.READ_CONTACTS", AppDatabase.PERM_TYPE_PRIVCY, app, priSelect, priSuggest);
getAppsForBoot(pm, db, "android.permission.WRITE_CONTACTS", AppDatabase.PERM_TYPE_PRIVCY, app, priSelect, priSuggest);
getAppsForBoot(pm, db, "android.permission.READ_CALENDAR", AppDatabase.PERM_TYPE_PRIVCY, app, priSelect, priSuggest);
getAppsForBoot(pm, db, "com.android.browser.permission.READ_HISTORY_BOOKMARKS", AppDatabase.PERM_TYPE_PRIVCY, app, priSelect, priSuggest);
if (permMap.get("location") == null) {
locSelect = 0;
} else {
locSelect = permMap.get("location").selected;
}
int locSuggest = Integer.valueOf(map.get("location")).intValue();
Log.d("test", pkgname + ", locSelect:" + locSelect + ", locSuggest:" + locSuggest);
getAppsForBoot(pm, db, "android.permission.ACCESS_COARSE_LOCATION", "location", app, locSelect, locSuggest);
getAppsForBoot(pm, db, "android.permission.ACCESS_FINE_LOCATION", "location", app, locSelect, locSuggest);
getAppsForBoot(pm, db, "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS", "location", app, locSelect, locSuggest);
int devSelect = permMap.get(AppDatabase.PERM_TYPE_DEVICE) == null ? 0 : permMap.get(AppDatabase.PERM_TYPE_DEVICE).selected;
int devSuggest = Integer.valueOf(map.get(AppDatabase.PERM_TYPE_DEVICE)).intValue();
Log.d("test", pkgname + ", devSelect:" + devSelect + ", devSuggest:" + devSuggest);
getAppsForBoot(pm, db, "android.permission.RECORD_AUDIO", AppDatabase.PERM_TYPE_DEVICE, app, devSelect, devSuggest);
getAppsForBoot(pm, db, "android.permission.CAMERA", AppDatabase.PERM_TYPE_DEVICE, app, devSelect, devSuggest);
int smsSelect = permMap.get(AppDatabase.DB_APP_SENDMESSAGE) == null ? 0 : permMap.get(AppDatabase.DB_APP_SENDMESSAGE).selected;
int smsSuggest = Integer.valueOf(map.get(AppDatabase.DB_APP_SENDMESSAGE)).intValue();
Log.d("test", pkgname + ", smsSelect:" + smsSelect + ", smsSuggest:" + smsSuggest);
getAppsForBoot(pm, db, "android.permission.SEND_SMS", AppDatabase.DB_APP_SENDMESSAGE, app, smsSelect, smsSuggest);
int callSelect = permMap.get(AppDatabase.DB_APP_CALL) == null ? 0 : permMap.get(AppDatabase.DB_APP_CALL).selected;
int callSuggest = Integer.valueOf(map.get(AppDatabase.DB_APP_CALL)).intValue();
Log.d("test", pkgname + ", callSelect:" + callSelect + ", callSuggest:" + callSuggest);
getAppsForBoot(pm, db, "android.permission.CALL_PHONE", AppDatabase.DB_APP_CALL, app, callSelect, callSuggest);
getAppsForBoot(pm, db, "android.permission.CALL_PRIVILEGED", AppDatabase.DB_APP_CALL, app, callSelect, callSuggest);
}
public static void batchOperateDBForBoot(Context context, AppDatabase database, boolean versionCode) {
PackageManager pm = context.getPackageManager();
ContentResolver resolver = context.getContentResolver();
List<String> whiteApps = WhiteAppsList.getThirdWhiteAppsList(context);
List<ApplicationInfo> installed = getInstalledThirdApps(context);
SQLiteDatabase db = database.getWritableDatabase();
db.beginTransaction();
try {
for (ApplicationInfo appinfo : installed) {
configurateAppsPermission(context, pm, db, resolver, whiteApps, appinfo, versionCode);
}
db.setTransactionSuccessful();
} catch (IllegalStateException e) {
e.printStackTrace();
} finally {
db.endTransaction();
db.close();
}
Log.d("test", "batchOperateDBForBoot end...");
}
public static void batchOperateDB(AppDatabase database, Context context, PackageManager pm, ApplicationInfo appinfo) {
ContentResolver resolver = context.getContentResolver();
SQLiteDatabase db = database.getWritableDatabase();
db.beginTransaction();
try {
String pkgname = appinfo.packageName;
if (PackageUtil.newAppMap.get(pkgname) == null) {
configurateAppsPermission(context, pm, db, resolver, WhiteAppsList.getThirdWhiteAppsList(context), appinfo, Const.getPreInstalledVersion());
} else {
configurateAppsPermission(context, pm, db, resolver, appinfo, PackageUtil.newAppMap.get(pkgname));
}
db.setTransactionSuccessful();
} catch (IllegalStateException e) {
e.printStackTrace();
} finally {
db.endTransaction();
db.close();
}
}
public static boolean isTariff(String permName) {
HashSet<String> tariffPermissionNameList = new HashSet<>();
tariffPermissionNameList.add("android.permission.CALL_PHONE");
tariffPermissionNameList.add("android.permission.SEND_SMS");
tariffPermissionNameList.add("android.permission.CALL_PRIVILEGED");
if (tariffPermissionNameList.contains(permName)) {
return true;
}
return false;
}
public static boolean isTariffType(String permType) {
HashSet<String> tariffPermissionNameList = new HashSet<>();
tariffPermissionNameList.add(AppDatabase.DB_APP_INTERNET);
tariffPermissionNameList.add(AppDatabase.DB_APP_SENDMESSAGE);
tariffPermissionNameList.add(AppDatabase.DB_APP_CALL);
if (tariffPermissionNameList.contains(permType)) {
return true;
}
return false;
}
public static String getCretMD5(Context Context, String packName) {
String md5 = null;
try {
Signature[] sigs = Context.getPackageManager().getPackageInfo(packName, 64).signatures;
for (int i = 0; i < sigs.length; i++) {
String str1 = sigs[i].toCharsString();
md5 = MD5Util.getMD5String(sigs[i].toByteArray()).toUpperCase();
Log.i("info", "str1==" + str1 + ">>>>>>>>str===" + md5);
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return md5;
}
public static boolean isNacExist(Context context) {
ApplicationInfo info = null;
try {
info = context.getPackageManager().getApplicationInfo("com.lenovo.leos.nac", 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (info != null) {
return true;
}
return false;
}
public static boolean isAntiVirusExist(Context context) {
ApplicationInfo info = null;
try {
info = context.getPackageManager().getApplicationInfo("com.lenovo.antivirus", 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (info != null) {
return true;
}
return false;
}
public static boolean isHarassExist(Context context) {
ApplicationInfo info = null;
try {
info = context.getPackageManager().getApplicationInfo("com.lenovo.safecenter.lenovoAntiSpam", 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (info != null) {
return true;
}
return false;
}
public static boolean isAppExistence(Context context, String pkgName) {
PackageInfo packageInfo;
try {
packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
} catch (PackageManager.NameNotFoundException e) {
packageInfo = null;
e.printStackTrace();
}
if (packageInfo != null) {
return true;
}
return false;
}
public static int getAppVersionCode(Context context, String pkgName) {
try {
return context.getPackageManager().getPackageInfo(pkgName, 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return -1;
}
}
}
| 12,788 |
4,047 | #!/usr/bin/env python3
import sys
f = open(sys.argv[1], 'w')
f.write('#define RETURN_VALUE 0')
f.close()
| 48 |
2,757 | #!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:#www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import random
import sys
FLAG = "flag{MixingOfGoldenBits}"
if len(FLAG) >= 31:
sys.exit("flag too long")
bits = list(range(256))
random.shuffle(bits)
flips = [random.randint(0, 1) for x in range(256)]
flag = FLAG.ljust(32, '\0')
flag = bytearray(flag)
output = bytearray(32)
for i in range(256):
bit = bits[i] % 8
byte = bits[i] / 8
b = (flag[byte] >> bit) & 1
if flips[i]:
b ^= 1
bit = i % 8
byte = i / 8
output[byte] |= b << bit
with open("mixer.c", "w") as f:
f.write("uint8_t mix_bits[] = { ")
f.write(','.join(["%u" % x for x in bits]))
f.write(" };\n")
f.write("uint8_t mix_flips[] = { ")
f.write(','.join(["%u" % x for x in flips]))
f.write(" };\n")
f.write("uint8_t flag[] = { ")
f.write(','.join(["%u" % x for x in output]))
f.write(" };\n")
| 521 |
542 | <filename>src/utest/crypto/tv_sha1.h
// SHA-1 test vectors
struct TV_SHA1 {
const char* message;
uint8_t hash[20];
};
static const TV_SHA1 tv_sha1 [] = {
{
"abc",
{0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A,
0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C,
0x9C, 0xD0, 0xD8, 0x9D},
},
{
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
{0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E,
0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5,
0xE5, 0x46, 0x70, 0xF1},
},
};
| 383 |
971 | #include "self_driving/planning/seq_tuning/sequence_tuning.h"
#include "common/managed_pointer.h"
#include "loggers/selfdriving_logger.h"
#include "planner/plannodes/abstract_plan_node.h"
#include "self_driving/planning/action/create_index_action.h"
#include "self_driving/planning/action/generators/change_knob_action_generator.h"
#include "self_driving/planning/action/generators/index_action_generator.h"
#include "self_driving/planning/pilot.h"
#include "self_driving/planning/pilot_util.h"
#include "self_driving/planning/seq_tuning/graph_solver.h"
#include "self_driving/planning/seq_tuning/path_solution.h"
namespace noisepage::selfdriving::pilot {
SequenceTuning::SequenceTuning(common::ManagedPointer<PlanningContext> planning_context,
common::ManagedPointer<selfdriving::WorkloadForecast> forecast,
uint64_t end_segment_index)
: planning_context_(planning_context), forecast_(forecast), end_segment_index_(end_segment_index) {
std::vector<std::unique_ptr<planner::AbstractPlanNode>> plans;
// vector of query plans that the search tree is responsible for
PilotUtil::GetQueryPlans(*planning_context_, common::ManagedPointer(forecast_), end_segment_index, &plans);
std::vector<action_id_t> candidate_actions;
// populate structure_map_, candidate_structures_
IndexActionGenerator().GenerateActions(plans, planning_context_->GetSettingsManager(), &structure_map_,
&candidate_actions);
for (auto &action : candidate_actions)
if (structure_map_.at(action)->GetActionType() == ActionType::CREATE_INDEX) {
candidate_structures_.emplace_back(action);
auto create_action = reinterpret_cast<CreateIndexAction *>(structure_map_.at(action).get());
auto drop_action = reinterpret_cast<DropIndexAction *>(
structure_map_.at(structure_map_.at(action)->GetReverseActions().at(0)).get());
PilotUtil::EstimateCreateIndexAction(planning_context_.Get(), create_action, drop_action);
SELFDRIVING_LOG_DEBUG("Candidate structure: ID {} Command {}", action,
structure_map_.at(action)->GetSQLCommand());
}
for (const auto &it UNUSED_ATTRIBUTE : structure_map_) {
SELFDRIVING_LOG_DEBUG("Generated action: ID {} Command {}", it.first, it.second->GetSQLCommand());
}
std::vector<double> default_segment_cost;
// first compute the cost of each segment when no action is applied
for (uint64_t segment_index = 0; segment_index <= end_segment_index_; segment_index++) {
default_segment_cost.emplace_back(PilotUtil::ComputeCost(planning_context_.Get(), forecast_, segment_index,
segment_index, std::nullopt, std::nullopt));
}
default_segment_cost_ = default_segment_cost;
}
void SequenceTuning::BestAction(
uint64_t memory_constraint,
std::vector<std::set<std::pair<const std::string, catalog::db_oid_t>>> *best_actions_seq) {
// cost-based pruning for each individual action
std::map<action_id_t, PathSolution> best_path_for_structure;
for (auto structure_id : candidate_structures_) {
PathSolution best_solution;
std::set<std::set<action_id_t>> singleton_action = {{structure_id}};
std::vector<std::set<std::set<action_id_t>>> singleton_action_repeated(end_segment_index_ + 1, singleton_action);
double best_path_cost UNUSED_ATTRIBUTE =
GraphSolver(planning_context_.Get(), forecast_, end_segment_index_, structure_map_, default_segment_cost_,
singleton_action_repeated, memory_constraint)
.RecoverShortestPath(&best_solution);
SELFDRIVING_LOG_INFO("[cost-based pruning] for structure \"{}\" finds best path distance {} with {} configs",
structure_map_.at(structure_id)->GetSQLCommand(), best_path_cost,
best_solution.unique_config_on_path_.size());
best_path_for_structure.emplace(structure_id, std::move(best_solution));
}
// since we only have one sequence (no split step), directly apply greedy-sequence algo to merge individual paths to
// get the final solution, (no merge step at the end)
PathSolution best_final_path;
GreedySeq(best_path_for_structure, memory_constraint, &best_final_path);
ExtractActionsFromConfigPath(best_final_path.config_on_path_, best_actions_seq);
}
double SequenceTuning::UnionPair(const PathSolution &path_one, const PathSolution &path_two, uint64_t memory_constraint,
PathSolution *merged_solution) {
std::vector<std::set<std::set<action_id_t>>> candidate_structures_by_segment;
auto const &seq_one = path_one.config_on_path_;
auto const &seq_two = path_two.config_on_path_;
NOISEPAGE_ASSERT(seq_one.size() == seq_two.size() && seq_one.size() == end_segment_index_ + 2,
"UnionPair requires two sequences both of length end_segment_index_ + 2");
// merge the configurations for each segment, here we skip index 0 that corresponds to the dummy source
for (uint64_t structure_idx = 1; structure_idx < seq_one.size(); structure_idx++) {
std::set<std::set<action_id_t>> curr_level;
curr_level.insert(seq_one.at(structure_idx));
curr_level.insert(seq_two.at(structure_idx));
std::set<action_id_t> unioned_config;
unioned_config.insert(seq_one.at(structure_idx).begin(), seq_one.at(structure_idx).end());
unioned_config.insert(seq_two.at(structure_idx).begin(), seq_two.at(structure_idx).end());
curr_level.insert(unioned_config);
candidate_structures_by_segment.push_back(std::move(curr_level));
}
double best_unioned_dist = GraphSolver(planning_context_.Get(), forecast_, end_segment_index_, structure_map_,
default_segment_cost_, candidate_structures_by_segment, memory_constraint)
.RecoverShortestPath(merged_solution);
return best_unioned_dist;
}
void SequenceTuning::GreedySeq(const std::map<action_id_t, PathSolution> &best_path_for_structure,
uint64_t memory_constraint, PathSolution *best_final_path) {
std::set<std::set<action_id_t>> global_config_set;
// set of solutions P, used to find the candidate configurations in GREEDY-SEQ
std::multiset<PathSolution> global_path_set;
// initialize global_path_set as the set of all paths found in cost-based pruning
// initialize global_config_set to contain empty or singleton configs for each potential structure
for (auto const &path_it : best_path_for_structure) {
auto const &config_set = path_it.second.unique_config_on_path_;
global_config_set.insert(config_set.begin(), config_set.end());
global_path_set.emplace(path_it.second);
}
// execute the while loop in step 3 of the paper to find the set of configurations in final graph
MergeConfigs(&global_path_set, &global_config_set, memory_constraint);
std::set<std::set<action_id_t>> candidate_structures;
candidate_structures.insert(global_config_set.begin(), global_config_set.end());
// construct the sequence of set of candidate structures to be used in the final graph search
std::vector<std::set<std::set<action_id_t>>> candidate_structures_by_segment(end_segment_index_ + 1,
candidate_structures);
// find best solution in the final graph
double final_soln_cost UNUSED_ATTRIBUTE =
GraphSolver(planning_context_.Get(), forecast_, end_segment_index_, structure_map_, default_segment_cost_,
candidate_structures_by_segment, memory_constraint)
.RecoverShortestPath(best_final_path);
SELFDRIVING_LOG_DEBUG("[GREEDY-SEQ] final solution cost {}", final_soln_cost);
}
std::set<action_id_t> SequenceTuning::ExtractActionsFromConfigTransition(
const std::map<pilot::action_id_t, std::unique_ptr<pilot::AbstractAction>> &structure_map,
const std::set<action_id_t> &start_config, const std::set<action_id_t> &end_config) {
std::set<action_id_t> actions;
// include actions that added structures
for (auto structure_id : end_config)
if (start_config.find(structure_id) == start_config.end()) actions.emplace(structure_id);
// include reverse actions for dropped structures
for (auto structure_id : start_config)
if (end_config.find(structure_id) == end_config.end()) {
auto drop_action = structure_map.at(structure_id)->GetReverseActions().at(0);
actions.emplace(drop_action);
}
return actions;
}
void SequenceTuning::ExtractActionsFromConfigPath(
const std::vector<std::set<action_id_t>> &best_final_config_path,
std::vector<std::set<std::pair<const std::string, catalog::db_oid_t>>> *best_actions_seq) {
for (uint64_t config_idx = 1; config_idx < best_final_config_path.size(); config_idx++) {
std::set<std::pair<const std::string, catalog::db_oid_t>> action_set;
auto action_id_set = ExtractActionsFromConfigTransition(structure_map_, best_final_config_path.at(config_idx - 1),
best_final_config_path.at(config_idx));
for (auto action_id : action_id_set)
action_set.emplace(structure_map_.at(action_id)->GetSQLCommand(), structure_map_.at(action_id)->GetDatabaseOid());
best_actions_seq->push_back(std::move(action_set));
}
}
double SequenceTuning::ConfigTransitionCost(
const std::map<pilot::action_id_t, std::unique_ptr<pilot::AbstractAction>> &structure_map,
const std::set<pilot::action_id_t> &start_config, const std::set<pilot::action_id_t> &end_config) {
auto action_id_set = ExtractActionsFromConfigTransition(structure_map, start_config, end_config);
double total_cost = 0.0;
for (auto action_id : action_id_set) total_cost += structure_map.at(action_id)->GetEstimatedElapsedUs();
return total_cost;
}
void SequenceTuning::MergeConfigs(std::multiset<PathSolution> *global_path_set,
std::set<std::set<action_id_t>> *global_config_set, uint64_t memory_constraint) {
while (!global_path_set->empty()) {
// find the least cost path and add its configurations to the global set of configurations
auto least_cost_path = *(global_path_set->begin());
// remove the least-cost path
global_path_set->erase(global_path_set->begin());
auto best_couple_pair_it = global_path_set->begin();
double best_union_cost = least_cost_path.path_length_;
auto config_set = least_cost_path.unique_config_on_path_;
global_config_set->insert(config_set.begin(), config_set.end());
// go through each solution in P to see if there's another path where their unioned solution is better
PathSolution best_merged_solution;
for (auto path_it = global_path_set->begin(); path_it != global_path_set->end(); ++path_it) {
PathSolution merged_solution;
double union_cost = UnionPair(least_cost_path, *path_it, memory_constraint, &merged_solution);
if (union_cost < best_union_cost) {
best_couple_pair_it = path_it;
best_union_cost = union_cost;
best_merged_solution = std::move(merged_solution);
}
}
// if there's a pair whose unioned solution is better than the least-cost solution alone, remove the other path and
// add the combined solution to P
if (best_union_cost < least_cost_path.path_length_) {
global_path_set->erase(best_couple_pair_it);
SELFDRIVING_LOG_DEBUG("[GreedySeq] new path added to global_path_set with distance {} number of config {}",
best_union_cost, best_merged_solution.unique_config_on_path_.size());
global_path_set->emplace(std::move(best_merged_solution));
} else {
// if there's no combination that's better than the least cost path alone, break out of step 3
break;
}
}
}
} // namespace noisepage::selfdriving::pilot
| 4,596 |
956 | #!/router/bin/python
import trex_root_path
from client.trex_stateless_client import *
from common.trex_exceptions import *
import cmd
from termstyle import termstyle
# import termstyle
import os
from argparse import ArgumentParser
import socket
import errno
import ast
import json
class InteractiveStatelessTRex(cmd.Cmd):
intro = termstyle.green("\nInteractive shell to play with Cisco's TRex stateless API.\
\nType help to view available pre-defined scenarios\n(c) All rights reserved.\n")
prompt = '> '
def __init__(self, trex_host, trex_port, virtual, verbose):
cmd.Cmd.__init__(self)
self.verbose = verbose
self.virtual = virtual
self.trex = STLClient(trex_host, trex_port, self.virtual)
self.DEFAULT_RUN_PARAMS = dict(m=1.5,
nc=True,
p=True,
d=100,
f='avl/sfr_delay_10_1g.yaml',
l=1000)
self.run_params = dict(self.DEFAULT_RUN_PARAMS)
def do_transmit(self, line):
"""Transmits a request over using a given link to server.\
\nuse: transmit [method_name] [method_params]"""
if line == "":
print "\nUsage: [method name] [param dict as string]\n"
print "Example: rpc test_add {'x': 12, 'y': 17}\n"
return
args = line.split(' ', 1) # args will have max length of 2
method_name = args[0]
params = None
bad_parse = False
try:
params = ast.literal_eval(args[1])
if not isinstance(params, dict):
bad_parse = True
except ValueError as e1:
bad_parse = True
except SyntaxError as e2:
bad_parse = True
if bad_parse:
print "\nValue should be a valid dict: '{0}'".format(args[1])
print "\nUsage: [method name] [param dict as string]\n"
print "Example: rpc test_add {'x': 12, 'y': 17}\n"
return
response = self.trex.transmit(method_name, params)
if not self.virtual:
# expect response
rc, msg = response
if rc:
print "\nServer Response:\n\n" + json.dumps(msg) + "\n"
else:
print "\n*** " + msg + "\n"
def do_push_files(self, filepaths):
"""Pushes a custom file to be stored locally on TRex server.\
\nPush multiple files by specifying their path separated by ' ' (space)."""
try:
filepaths = filepaths.split(' ')
print termstyle.green("*** Starting pushing files ({trex_files}) to TRex. ***".format(
trex_files=', '.join(filepaths))
)
ret_val = self.trex.push_files(filepaths)
if ret_val:
print termstyle.green("*** End of TRex push_files method (success) ***")
else:
print termstyle.magenta("*** End of TRex push_files method (failed) ***")
except IOError as inst:
print termstyle.magenta(inst)
if __name__ == "__main__":
parser = ArgumentParser(description=termstyle.cyan('Run TRex client stateless API demos and scenarios.'),
usage="client_interactive_example [options]")
parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0 \t (C) Cisco Systems Inc.\n')
parser.add_argument("-t", "--trex-host", required = True, dest="trex_host",
action="store", help="Specify the hostname or ip to connect with TRex server.",
metavar="HOST" )
parser.add_argument("-p", "--trex-port", type=int, default = 5050, metavar="PORT", dest="trex_port",
help="Select port on which the TRex server listens. Default port is 5050.", action="store")
# parser.add_argument("-m", "--maxhist", type=int, default = 100, metavar="SIZE", dest="hist_size",
# help="Specify maximum history size saved at client side. Default size is 100.", action="store")
parser.add_argument("--virtual", dest="virtual",
action="store_true",
help="Switch ON virtual option at TRex client. Default is: OFF.",
default=False)
parser.add_argument("--verbose", dest="verbose",
action="store_true",
help="Switch ON verbose option at TRex client. Default is: OFF.",
default=False)
args = parser.parse_args()
try:
InteractiveStatelessTRex(**vars(args)).cmdloop()
except KeyboardInterrupt:
print termstyle.cyan('Bye Bye!')
exit(-1)
except socket.error, e:
if e.errno == errno.ECONNREFUSED:
raise socket.error(errno.ECONNREFUSED,
"Connection from TRex server was terminated. \
Please make sure the server is up.")
| 2,361 |
1,338 | <reponame>Kirishikesan/haiku<filename>src/system/boot/platform/openfirmware/machine.h<gh_stars>1000+
/*
* Copyright 2003, <NAME>, <EMAIL>. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef MACHINE_H
#define MACHINE_H
#include <SupportDefs.h>
// Possible gMachine OpenFirmware platforms
#define MACHINE_UNKNOWN 0x0000
#define MACHINE_CHRP 0x0001
#define MACHINE_MAC 0x0002
#define MACHINE_PEGASOS 0x0100
#define MACHINE_QEMU 0x0200
#define MACHINE_SPARC 0x0300
extern uint32 gMachine;
// stores the machine type
#endif /* MACHINE_H */
| 224 |
576 | //
// Custom Casts
//
namespace {
$(when measurements $(foreach measurements
$(if itk_get or ( active and ( custom_cast or label_map ) ) then
OUT=[[
template<typename FilterType>
struct ${name}CustomCast
{
]]
if custom_cast then
OUT=OUT..[[
template <typename T>
static ${type} Helper( const T & value ) { return ${custom_cast}; }
]]
end
OUT=OUT..[[
static ${type} CustomCast($(if not non_const then OUT=' const' end) FilterType *f]]
if parameters then
for inum=1,#parameters do
OUT=OUT..', '..parameters[inum].type..' '..parameters[inum].name
end
end
OUT=OUT..[[ )
{
return ]]
if custom_cast then
OUT=OUT..[[${name}CustomCast::Helper(]]
end
if itk_get then
OUT=OUT..[[${itk_get}]]
elseif label_map then
OUT=OUT..[[f->GetOutput()->GetLabelObject(label)->Get${name}()]]
else
OUT=OUT..[[f->Get${name}(${parameters[1].name})]]
end
if custom_cast then
OUT=OUT..')'
end
OUT=OUT..';'..[[
}
};
]]
end)))
}
| 360 |
1,331 | <gh_stars>1000+
package com.metasploit.meterpreter.core;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import com.metasploit.meterpreter.Transport;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class core_negotiate_tlv_encryption implements Command {
private static final SecureRandom sr = new SecureRandom();
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
byte[] der = request.getRawValue(TLVType.TLV_TYPE_RSA_PUB_KEY);
int encType;
byte[] aesKey;
if (Cipher.getMaxAllowedKeyLength("AES") < 256) {
encType = Transport.ENC_AES128;
aesKey = new byte[16];
} else {
encType = Transport.ENC_AES256;
aesKey = new byte[32];
}
sr.nextBytes(aesKey);
try
{
PublicKey pubKey = getPublicKey(der);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
response.add(TLVType.TLV_TYPE_ENC_SYM_KEY, cipher.doFinal(aesKey));
}
catch(Exception e)
{
response.add(TLVType.TLV_TYPE_SYM_KEY, aesKey);
}
response.add(TLVType.TLV_TYPE_SYM_KEY_TYPE, encType);
meterpreter.getTransports().current().setAesEncryptionKey(aesKey);
return ERROR_SUCCESS;
}
private PublicKey getPublicKey(byte[] der) {
try
{
X509EncodedKeySpec spec = new X509EncodedKeySpec(der);
return KeyFactory.getInstance("RSA").generatePublic(spec);
}
catch(Exception e)
{
return null;
}
}
}
| 890 |
606 | <gh_stars>100-1000
int NetManInitRPCServer(void);
void NetManDeinitRPCServer(void);
int NetManRPCAllocRxBuffers(void);
| 47 |
369 | // Copyright (c) 2017-2021, Mudit<NAME>. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "BedtimeSettingsListItemProvider.hpp"
#include "BellSettingsStyle.hpp"
#include <common/widgets/list_items/Numeric.hpp>
#include <common/widgets/list_items/Text.hpp>
#include <apps-common/ApplicationCommon.hpp>
#include <gui/widgets/ListViewEngine.hpp>
namespace app::bell_settings
{
using namespace gui;
BedtimeSettingsListItemProvider::BedtimeSettingsListItemProvider(std::shared_ptr<AbstractBedtimeModel> model,
std::vector<UTF8> chimeToneRange)
: model{model}
{
buildListItems(std::move(chimeToneRange));
}
void BedtimeSettingsListItemProvider::buildListItems(std::vector<UTF8> chimeToneRange)
{
constexpr auto itemCount = 2U;
internalData.reserve(itemCount);
auto chimeTone = new list_items::Text(std::move(chimeToneRange),
model->getBedtimeTone(),
utils::translate("app_bell_settings_bedtime_settings_tone"));
chimeTone->set_on_value_change_cb([this](const auto &val) {
if (onToneChange) {
onToneChange(val);
}
});
chimeTone->onEnter = [this, chimeTone]() {
if (onToneEnter) {
onToneEnter(chimeTone->value());
}
};
chimeTone->onExit = [this, chimeTone]() {
if (onToneExit) {
onToneExit(chimeTone->value());
}
};
internalData.emplace_back(chimeTone);
constexpr auto volumeStep = 1U;
constexpr auto volumeMin = 1U;
constexpr auto volumeMax = 10U;
auto volume =
new list_items::Numeric(list_items::Numeric::spinner_type::range{volumeMin, volumeMax, volumeStep},
model->getBedtimeVolume(),
utils::translate("app_bell_settings_bedtime_settings_volume"));
volume->set_on_value_change_cb([this](const auto &val) {
if (onVolumeChange) {
onVolumeChange(val);
}
});
volume->onEnter = [this, chimeTone]() {
if (onVolumeEnter) {
onVolumeEnter(chimeTone->value());
}
};
volume->onExit = [this, volume]() {
if (onVolumeExit) {
onVolumeExit(volume->value());
}
};
internalData.emplace_back(volume);
for (auto item : internalData) {
item->deleteByList = false;
}
}
} // namespace app::bell_settings
| 1,395 |
1,144 | /*
* Atheros AP83 board support
*
* Copyright (C) 2008-2012 <NAME> <<EMAIL>>
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/spi/spi.h>
#include <linux/spi/spi_gpio.h>
#include <linux/spi/vsc7385.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include <asm/mach-ath79/ath79.h>
#include "dev-eth.h"
#include "dev-gpio-buttons.h"
#include "dev-leds-gpio.h"
#include "dev-usb.h"
#include "dev-wmac.h"
#include "machtypes.h"
#define AP83_GPIO_LED_WLAN 6
#define AP83_GPIO_LED_POWER 14
#define AP83_GPIO_LED_JUMPSTART 15
#define AP83_GPIO_BTN_JUMPSTART 12
#define AP83_GPIO_BTN_RESET 21
#define AP83_050_GPIO_VSC7385_CS 1
#define AP83_050_GPIO_VSC7385_MISO 3
#define AP83_050_GPIO_VSC7385_MOSI 16
#define AP83_050_GPIO_VSC7385_SCK 17
#define AP83_KEYS_POLL_INTERVAL 20 /* msecs */
#define AP83_KEYS_DEBOUNCE_INTERVAL (3 * AP83_KEYS_POLL_INTERVAL)
static struct mtd_partition ap83_flash_partitions[] = {
{
.name = "u-boot",
.offset = 0,
.size = 0x040000,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "u-boot-env",
.offset = 0x040000,
.size = 0x020000,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "kernel",
.offset = 0x060000,
.size = 0x140000,
}, {
.name = "rootfs",
.offset = 0x1a0000,
.size = 0x650000,
}, {
.name = "art",
.offset = 0x7f0000,
.size = 0x010000,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "firmware",
.offset = 0x060000,
.size = 0x790000,
}
};
static struct physmap_flash_data ap83_flash_data = {
.width = 2,
.parts = ap83_flash_partitions,
.nr_parts = ARRAY_SIZE(ap83_flash_partitions),
};
static struct resource ap83_flash_resources[] = {
[0] = {
.start = AR71XX_SPI_BASE,
.end = AR71XX_SPI_BASE + AR71XX_SPI_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device ap83_flash_device = {
.name = "ar91xx-flash",
.id = -1,
.resource = ap83_flash_resources,
.num_resources = ARRAY_SIZE(ap83_flash_resources),
.dev = {
.platform_data = &ap83_flash_data,
}
};
static struct gpio_led ap83_leds_gpio[] __initdata = {
{
.name = "ap83:green:jumpstart",
.gpio = AP83_GPIO_LED_JUMPSTART,
.active_low = 0,
}, {
.name = "ap83:green:power",
.gpio = AP83_GPIO_LED_POWER,
.active_low = 0,
}, {
.name = "ap83:green:wlan",
.gpio = AP83_GPIO_LED_WLAN,
.active_low = 0,
},
};
static struct gpio_keys_button ap83_gpio_keys[] __initdata = {
{
.desc = "soft_reset",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = AP83_KEYS_DEBOUNCE_INTERVAL,
.gpio = AP83_GPIO_BTN_RESET,
.active_low = 1,
}, {
.desc = "jumpstart",
.type = EV_KEY,
.code = KEY_WPS_BUTTON,
.debounce_interval = AP83_KEYS_DEBOUNCE_INTERVAL,
.gpio = AP83_GPIO_BTN_JUMPSTART,
.active_low = 1,
}
};
static struct resource ap83_040_spi_resources[] = {
[0] = {
.start = AR71XX_SPI_BASE,
.end = AR71XX_SPI_BASE + AR71XX_SPI_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device ap83_040_spi_device = {
.name = "ap83-spi",
.id = 0,
.resource = ap83_040_spi_resources,
.num_resources = ARRAY_SIZE(ap83_040_spi_resources),
};
static struct spi_gpio_platform_data ap83_050_spi_data = {
.miso = AP83_050_GPIO_VSC7385_MISO,
.mosi = AP83_050_GPIO_VSC7385_MOSI,
.sck = AP83_050_GPIO_VSC7385_SCK,
.num_chipselect = 1,
};
static struct platform_device ap83_050_spi_device = {
.name = "spi_gpio",
.id = 0,
.dev = {
.platform_data = &ap83_050_spi_data,
}
};
static void ap83_vsc7385_reset(void)
{
ath79_device_reset_set(AR71XX_RESET_GE1_PHY);
udelay(10);
ath79_device_reset_clear(AR71XX_RESET_GE1_PHY);
mdelay(50);
}
static struct vsc7385_platform_data ap83_vsc7385_data = {
.reset = ap83_vsc7385_reset,
.ucode_name = "vsc7385_ucode_ap83.bin",
.mac_cfg = {
.tx_ipg = 6,
.bit2 = 0,
.clk_sel = 3,
},
};
static struct spi_board_info ap83_spi_info[] = {
{
.bus_num = 0,
.chip_select = 0,
.max_speed_hz = 25000000,
.modalias = "spi-vsc7385",
.platform_data = &ap83_vsc7385_data,
.controller_data = (void *) AP83_050_GPIO_VSC7385_CS,
}
};
static void __init ap83_generic_setup(void)
{
u8 *eeprom = (u8 *) KSEG1ADDR(0x1fff1000);
ath79_register_mdio(0, 0xfffffffe);
ath79_init_mac(ath79_eth0_data.mac_addr, eeprom, 0);
ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII;
ath79_eth0_data.phy_mask = 0x1;
ath79_register_eth(0);
ath79_init_mac(ath79_eth1_data.mac_addr, eeprom, 1);
ath79_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII;
ath79_eth1_data.speed = SPEED_1000;
ath79_eth1_data.duplex = DUPLEX_FULL;
ath79_eth1_pll_data.pll_1000 = 0x1f000000;
ath79_register_eth(1);
ath79_register_leds_gpio(-1, ARRAY_SIZE(ap83_leds_gpio),
ap83_leds_gpio);
ath79_register_gpio_keys_polled(-1, AP83_KEYS_POLL_INTERVAL,
ARRAY_SIZE(ap83_gpio_keys),
ap83_gpio_keys);
ath79_register_usb();
ath79_register_wmac(eeprom, NULL);
platform_device_register(&ap83_flash_device);
spi_register_board_info(ap83_spi_info, ARRAY_SIZE(ap83_spi_info));
}
static void ap83_040_flash_lock(struct platform_device *pdev)
{
ath79_flash_acquire();
}
static void ap83_040_flash_unlock(struct platform_device *pdev)
{
ath79_flash_release();
}
static void __init ap83_040_setup(void)
{
ap83_flash_data.lock = ap83_040_flash_lock;
ap83_flash_data.unlock = ap83_040_flash_unlock;
ap83_generic_setup();
platform_device_register(&ap83_040_spi_device);
}
static void __init ap83_050_setup(void)
{
ap83_generic_setup();
platform_device_register(&ap83_050_spi_device);
}
static void __init ap83_setup(void)
{
u8 *board_id = (u8 *) KSEG1ADDR(0x1fff1244);
unsigned int board_version;
board_version = (unsigned int)(board_id[0] - '0');
board_version += ((unsigned int)(board_id[1] - '0')) * 10;
switch (board_version) {
case 40:
ap83_040_setup();
break;
case 50:
ap83_050_setup();
break;
default:
printk(KERN_WARNING "AP83-%03u board is not yet supported\n",
board_version);
}
}
MIPS_MACHINE(ATH79_MACH_AP83, "AP83", "Atheros AP83", ap83_setup);
| 3,073 |
335 | <gh_stars>100-1000
{
"word": "Unmanageable",
"definitions": [
"Difficult or impossible to manage, manipulate, or control."
],
"parts-of-speech": "Adjective"
} | 76 |
5,169 | {
"name": "BRCLucene",
"version": "1.0.0-beta1",
"summary": "CLucene as a Pod",
"description": "This project provides provides a pod for the\n[CLucene](http://clucene.sourceforge.net/) search framework.",
"homepage": "https://github.com/Blue-Rocket/clucene",
"license": "Apache License, Version 2.0",
"authors": {
"<NAME>": "<EMAIL>"
},
"platforms": {
"ios": "5.1",
"osx": "10.7"
},
"source": {
"git": "https://github.com/Blue-Rocket/clucene.git",
"tag": "1.0.0-beta1"
},
"libraries": [
"c++",
"z"
],
"compiler_flags": [
"-Wmost",
"-fvisibility=default",
"-fPIC",
"-D_UCS2",
"-D_UNICODE",
"-D_REENTRANT",
"-DNDEBUG"
],
"xcconfig": {
"GCC_PREPROCESSOR_DEFINITIONS": "_WCHAR_H_CPLUSPLUS_98_CONFORMANCE_"
},
"requires_arc": false,
"default_subspecs": "CLucene",
"subspecs": [
{
"name": "CLucene",
"dependencies": {
"BRCLucene/CLucene-Shared": [
],
"BRCLucene/CLucene-Core": [
],
"BRCLucene/CLucene-Contribs-Lib": [
]
}
},
{
"name": "CLucene-Config",
"requires_arc": false,
"source_files": "BRCLucene/src/CLucene/*",
"header_mappings_dir": "BRCLucene/src"
},
{
"name": "CLucene-Core-API",
"requires_arc": false,
"source_files": [
"src/core/CLucene.h",
"src/core/CLucene/**/*.h"
],
"header_mappings_dir": "src/core",
"exclude_files": [
"src/core/CLucene/CLMonolithic.*",
"src/core/CLucene/search/FilterResultCache.*",
"src/core/CLucene/queryParser/legacy"
],
"dependencies": {
"BRCLucene/CLucene-Config": [
]
}
},
{
"name": "CLucene-Shared",
"requires_arc": false,
"source_files": "src/shared/CLucene/**/*.{h,c,cpp}",
"header_mappings_dir": "src/shared",
"exclude_files": [
"src/shared/CLucene/CLSharedMonolithic.*",
"src/shared/CLucene/util/deflate.*"
],
"dependencies": {
"BRCLucene/CLucene-Core-API": [
]
}
},
{
"name": "CLucene-Core",
"requires_arc": false,
"source_files": "src/core/CLucene/**/*.{c,cpp}",
"header_mappings_dir": "src/core",
"exclude_files": [
"src/core/CLucene/CLMonolithic.*",
"src/core/CLucene/search/FilterResultCache.*",
"src/core/CLucene/queryParser/legacy"
],
"dependencies": {
"BRCLucene/CLucene-Core-API": [
],
"BRCLucene/CLucene-Shared": [
]
}
},
{
"name": "CLucene-Contribs-Lib",
"requires_arc": false,
"source_files": "src/contribs-lib/CLucene/**/*.{h,c,cpp}",
"header_mappings_dir": "src/contribs-lib",
"dependencies": {
"BRCLucene/CLucene-Core": [
],
"BRCLucene/CLucene-Shared": [
]
}
}
]
}
| 1,530 |
8,054 | #include "vxnotebookconfigmgr.h"
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QDebug>
#include <notebookbackend/inotebookbackend.h>
#include <notebook/notebookparameters.h>
#include <notebook/vxnode.h>
#include <notebook/externalnode.h>
#include <notebook/bundlenotebook.h>
#include <notebook/notebookdatabaseaccess.h>
#include <utils/utils.h>
#include <utils/fileutils.h>
#include <utils/pathutils.h>
#include <exception.h>
#include <core/configmgr.h>
#include <core/editorconfig.h>
#include <core/coreconfig.h>
#include <utils/contentmediautils.h>
#include "vxnodeconfig.h"
#include "vxnotebookconfigmgrfactory.h"
using namespace vnotex;
using namespace vnotex::vx_node_config;
const QString VXNotebookConfigMgr::c_nodeConfigName = "vx.json";
bool VXNotebookConfigMgr::s_initialized = false;
QVector<QRegExp> VXNotebookConfigMgr::s_externalNodeExcludePatterns;
VXNotebookConfigMgr::VXNotebookConfigMgr(const QSharedPointer<INotebookBackend> &p_backend, QObject *p_parent)
: BundleNotebookConfigMgr(p_backend, p_parent)
{
if (!s_initialized) {
s_initialized = true;
const auto &patterns = ConfigMgr::getInst().getCoreConfig().getExternalNodeExcludePatterns();
s_externalNodeExcludePatterns.reserve(patterns.size());
for (const auto &pat : patterns) {
if (!pat.isEmpty()) {
s_externalNodeExcludePatterns.push_back(QRegExp(pat, Qt::CaseInsensitive, QRegExp::Wildcard));
}
}
}
}
QString VXNotebookConfigMgr::getName() const
{
return VXNotebookConfigMgrFactory::c_name;
}
QString VXNotebookConfigMgr::getDisplayName() const
{
return VXNotebookConfigMgrFactory::c_displayName;
}
QString VXNotebookConfigMgr::getDescription() const
{
return VXNotebookConfigMgrFactory::c_description;
}
void VXNotebookConfigMgr::createEmptySkeleton(const NotebookParameters &p_paras)
{
BundleNotebookConfigMgr::createEmptySkeleton(p_paras);
createEmptyRootNode();
}
void VXNotebookConfigMgr::createEmptyRootNode()
{
auto currentTime = QDateTime::currentDateTimeUtc();
NodeConfig node(getCodeVersion(),
Node::InvalidId,
Node::InvalidId,
currentTime,
currentTime);
writeNodeConfig(c_nodeConfigName, node);
}
QSharedPointer<Node> VXNotebookConfigMgr::loadRootNode()
{
auto nodeConfig = readNodeConfig("");
QSharedPointer<Node> root = nodeConfigToNode(*nodeConfig, "", nullptr);
root->setUse(Node::Use::Root);
root->setExists(true);
Q_ASSERT(root->isLoaded());
if (static_cast<BundleNotebook *>(getNotebook())->getConfigVersion() < 3) {
removeLegacyRecycleBinNode(root);
}
return root;
}
void VXNotebookConfigMgr::removeLegacyRecycleBinNode(const QSharedPointer<Node> &p_root)
{
// Do not support recycle bin node as it complicates everything.
auto node = p_root->findChild(QStringLiteral("vx_recycle_bin"),
FileUtils::isPlatformNameCaseSensitive());
if (node) {
removeNode(node, true, true);
}
}
void VXNotebookConfigMgr::markNodeReadOnly(Node *p_node) const
{
if (p_node->isReadOnly()) {
return;
}
p_node->setReadOnly(true);
for (const auto &child : p_node->getChildrenRef()) {
markNodeReadOnly(child.data());
}
}
QSharedPointer<NodeConfig> VXNotebookConfigMgr::readNodeConfig(const QString &p_path) const
{
auto backend = getBackend();
if (!backend->exists(p_path)) {
Exception::throwOne(Exception::Type::InvalidArgument,
QString("node path (%1) does not exist").arg(p_path));
}
if (backend->isFile(p_path)) {
Exception::throwOne(Exception::Type::InvalidArgument,
QString("node (%1) is a file node without config").arg(p_path));
} else {
auto configPath = PathUtils::concatenateFilePath(p_path, c_nodeConfigName);
auto data = backend->readFile(configPath);
auto nodeConfig = QSharedPointer<NodeConfig>::create();
nodeConfig->fromJson(QJsonDocument::fromJson(data).object());
return nodeConfig;
}
return nullptr;
}
QString VXNotebookConfigMgr::getNodeConfigFilePath(const Node *p_node) const
{
Q_ASSERT(p_node->isContainer());
return PathUtils::concatenateFilePath(p_node->fetchPath(), c_nodeConfigName);
}
void VXNotebookConfigMgr::writeNodeConfig(const QString &p_path, const NodeConfig &p_config) const
{
getBackend()->writeFile(p_path, p_config.toJson());
}
void VXNotebookConfigMgr::writeNodeConfig(const Node *p_node)
{
auto config = nodeToNodeConfig(p_node);
writeNodeConfig(getNodeConfigFilePath(p_node), *config);
}
QSharedPointer<Node> VXNotebookConfigMgr::nodeConfigToNode(const NodeConfig &p_config,
const QString &p_name,
Node *p_parent)
{
auto node = QSharedPointer<VXNode>::create(p_name, getNotebook(), p_parent);
loadFolderNode(node.data(), p_config);
return node;
}
void VXNotebookConfigMgr::loadFolderNode(Node *p_node, const NodeConfig &p_config)
{
QVector<QSharedPointer<Node>> children;
children.reserve(p_config.m_files.size() + p_config.m_folders.size());
const auto basePath = p_node->fetchPath();
bool needUpdateConfig = false;
for (const auto &folder : p_config.m_folders) {
if (folder.m_name.isEmpty()) {
// Skip empty name node.
qWarning() << "skipped loading node with empty name under" << p_node->fetchPath();
continue;
}
auto folderNode = QSharedPointer<VXNode>::create(folder.m_name,
getNotebook(),
p_node);
inheritNodeFlags(p_node, folderNode.data());
folderNode->setExists(getBackend()->existsDir(PathUtils::concatenateFilePath(basePath, folder.m_name)));
children.push_back(folderNode);
}
for (const auto &file : p_config.m_files) {
if (file.m_name.isEmpty()) {
// Skip empty name node.
qWarning() << "skipped loading node with empty name under" << p_node->fetchPath();
continue;
}
// For compability only.
needUpdateConfig = needUpdateConfig || file.m_signature == Node::InvalidId;
auto fileNode = QSharedPointer<VXNode>::create(file.m_name,
file.toNodeParameters(),
getNotebook(),
p_node);
inheritNodeFlags(p_node, fileNode.data());
fileNode->setExists(getBackend()->existsFile(PathUtils::concatenateFilePath(basePath, file.m_name)));
children.push_back(fileNode);
}
p_node->loadCompleteInfo(p_config.toNodeParameters(), children);
needUpdateConfig = needUpdateConfig || p_config.m_signature == Node::InvalidId;
if (needUpdateConfig) {
writeNodeConfig(p_node);
}
}
QSharedPointer<Node> VXNotebookConfigMgr::newNode(Node *p_parent,
Node::Flags p_flags,
const QString &p_name,
const QString &p_content)
{
Q_ASSERT(p_parent && p_parent->isContainer() && !p_name.isEmpty());
QSharedPointer<Node> node;
if (p_flags & Node::Flag::Content) {
Q_ASSERT(!(p_flags & Node::Flag::Container));
node = newFileNode(p_parent, p_name, p_content, true, NodeParameters());
} else {
node = newFolderNode(p_parent, p_name, true, NodeParameters());
}
return node;
}
QSharedPointer<Node> VXNotebookConfigMgr::addAsNode(Node *p_parent,
Node::Flags p_flags,
const QString &p_name,
const NodeParameters &p_paras)
{
Q_ASSERT(p_parent && p_parent->isContainer());
// TODO: reuse the config if available.
QSharedPointer<Node> node;
if (p_flags & Node::Flag::Content) {
Q_ASSERT(!(p_flags & Node::Flag::Container));
node = newFileNode(p_parent, p_name, "", false, p_paras);
} else {
node = newFolderNode(p_parent, p_name, false, p_paras);
}
return node;
}
QSharedPointer<Node> VXNotebookConfigMgr::copyAsNode(Node *p_parent,
Node::Flags p_flags,
const QString &p_path)
{
Q_ASSERT(p_parent && p_parent->isContainer());
QSharedPointer<Node> node;
if (p_flags & Node::Flag::Content) {
Q_ASSERT(!(p_flags & Node::Flag::Container));
node = copyFileAsChildOf(p_path, p_parent);
} else {
node = copyFolderAsChildOf(p_path, p_parent);
}
return node;
}
QSharedPointer<Node> VXNotebookConfigMgr::newFileNode(Node *p_parent,
const QString &p_name,
const QString &p_content,
bool p_create,
const NodeParameters &p_paras)
{
ensureNodeInDatabase(p_parent);
auto notebook = getNotebook();
// Create file node.
auto node = QSharedPointer<VXNode>::create(p_name,
p_paras,
notebook,
p_parent);
// Write empty file.
if (p_create) {
if (getBackend()->childExistsCaseInsensitive(p_parent->fetchPath(), p_name)) {
// File already exists. Exception.
Exception::throwOne(Exception::Type::FileExistsOnCreate,
QString("file (%1) already exists when creating new node").arg(node->fetchPath()));
return nullptr;
}
getBackend()->writeFile(node->fetchPath(), p_content);
node->setExists(true);
} else {
node->setExists(getBackend()->existsFile(node->fetchPath()));
}
addChildNode(p_parent, node);
writeNodeConfig(p_parent);
addNodeToDatabase(node.data());
return node;
}
QSharedPointer<Node> VXNotebookConfigMgr::newFolderNode(Node *p_parent,
const QString &p_name,
bool p_create,
const NodeParameters &p_paras)
{
ensureNodeInDatabase(p_parent);
auto notebook = getNotebook();
// Create folder node.
auto node = QSharedPointer<VXNode>::create(p_name, notebook, p_parent);
node->loadCompleteInfo(p_paras, QVector<QSharedPointer<Node>>());
// Make folder.
if (p_create) {
if (getBackend()->childExistsCaseInsensitive(p_parent->fetchPath(), p_name)) {
// Dir already exists. Exception.
Exception::throwOne(Exception::Type::DirExistsOnCreate,
QString("dir (%1) already exists when creating new node").arg(node->fetchPath()));
return nullptr;
}
getBackend()->makePath(node->fetchPath());
node->setExists(true);
} else {
node->setExists(getBackend()->existsDir(node->fetchPath()));
}
writeNodeConfig(node.data());
addChildNode(p_parent, node);
writeNodeConfig(p_parent);
addNodeToDatabase(node.data());
return node;
}
QSharedPointer<NodeConfig> VXNotebookConfigMgr::nodeToNodeConfig(const Node *p_node) const
{
Q_ASSERT(p_node->isContainer());
Q_ASSERT(p_node->isLoaded());
auto config = QSharedPointer<NodeConfig>::create(getCodeVersion(),
p_node->getId(),
p_node->getSignature(),
p_node->getCreatedTimeUtc(),
p_node->getModifiedTimeUtc());
for (const auto &child : p_node->getChildrenRef()) {
if (child->hasContent()) {
NodeFileConfig fileConfig;
fileConfig.m_name = child->getName();
fileConfig.m_id = child->getId();
fileConfig.m_signature = child->getSignature();
fileConfig.m_createdTimeUtc = child->getCreatedTimeUtc();
fileConfig.m_modifiedTimeUtc = child->getModifiedTimeUtc();
fileConfig.m_attachmentFolder = child->getAttachmentFolder();
fileConfig.m_tags = child->getTags();
config->m_files.push_back(fileConfig);
} else {
Q_ASSERT(child->isContainer());
NodeFolderConfig folderConfig;
folderConfig.m_name = child->getName();
config->m_folders.push_back(folderConfig);
}
}
return config;
}
void VXNotebookConfigMgr::loadNode(Node *p_node)
{
if (p_node->isLoaded() || !p_node->exists()) {
return;
}
auto config = readNodeConfig(p_node->fetchPath());
Q_ASSERT(p_node->isContainer());
loadFolderNode(p_node, *config);
}
void VXNotebookConfigMgr::saveNode(const Node *p_node)
{
if (p_node->isContainer()) {
writeNodeConfig(p_node);
} else {
Q_ASSERT(!p_node->isRoot());
writeNodeConfig(p_node->getParent());
}
}
void VXNotebookConfigMgr::renameNode(Node *p_node, const QString &p_name)
{
Q_ASSERT(!p_node->isRoot());
if (p_node->isContainer()) {
getBackend()->renameDir(p_node->fetchPath(), p_name);
} else {
getBackend()->renameFile(p_node->fetchPath(), p_name);
}
p_node->setName(p_name);
writeNodeConfig(p_node->getParent());
ensureNodeInDatabase(p_node);
updateNodeInDatabase(p_node);
}
// Do not touch DB here since it will be called at different scenarios.
void VXNotebookConfigMgr::addChildNode(Node *p_parent, const QSharedPointer<Node> &p_child) const
{
if (p_child->isContainer()) {
int idx = 0;
const auto &children = p_parent->getChildrenRef();
for (; idx < children.size(); ++idx) {
if (!children[idx]->isContainer()) {
break;
}
}
p_parent->insertChild(idx, p_child);
} else {
p_parent->addChild(p_child);
}
inheritNodeFlags(p_parent, p_child.data());
}
QSharedPointer<Node> VXNotebookConfigMgr::loadNodeByPath(const QSharedPointer<Node> &p_root, const QString &p_relativePath)
{
auto p = PathUtils::cleanPath(p_relativePath);
auto paths = p.split('/', QString::SkipEmptyParts);
auto node = p_root;
for (auto &pa : paths) {
// Find child @pa in @node.
if (!node->isLoaded()) {
loadNode(node.data());
}
auto child = node->findChild(pa, FileUtils::isPlatformNameCaseSensitive());
if (!child) {
return nullptr;
}
node = child;
}
return node;
}
// @p_src may belong to different notebook or different kind of configmgr.
// TODO: we could constrain @p_src within the same configrmgr?
QSharedPointer<Node> VXNotebookConfigMgr::copyNodeAsChildOf(const QSharedPointer<Node> &p_src,
Node *p_dest,
bool p_move)
{
return copyNodeAsChildOf(p_src, p_dest, p_move, true);
}
QSharedPointer<Node> VXNotebookConfigMgr::copyNodeAsChildOf(const QSharedPointer<Node> &p_src,
Node *p_dest,
bool p_move,
bool p_updateDatabase)
{
Q_ASSERT(p_dest->isContainer());
if (!p_src->exists()) {
if (p_move) {
// It is OK to always update the database.
p_src->getNotebook()->removeNode(p_src);
}
return nullptr;
}
QSharedPointer<Node> node;
if (p_src->isContainer()) {
node = copyFolderNodeAsChildOf(p_src, p_dest, p_move, p_updateDatabase);
} else {
node = copyFileNodeAsChildOf(p_src, p_dest, p_move, p_updateDatabase);
}
return node;
}
QSharedPointer<Node> VXNotebookConfigMgr::copyFileNodeAsChildOf(const QSharedPointer<Node> &p_src,
Node *p_dest,
bool p_move,
bool p_updateDatabase)
{
QString destFilePath;
QString attachmentFolder;
copyFilesOfFileNode(p_src, p_dest->fetchPath(), destFilePath, attachmentFolder);
// Create a file node.
auto notebook = getNotebook();
const bool sameNotebook = p_src->getNotebook() == notebook;
if (p_updateDatabase) {
ensureNodeInDatabase(p_dest);
if (sameNotebook) {
ensureNodeInDatabase(p_src.data());
}
}
NodeParameters paras;
if (p_move && sameNotebook) {
paras.m_id = p_src->getId();
paras.m_signature = p_src->getSignature();
}
paras.m_createdTimeUtc = p_src->getCreatedTimeUtc();
paras.m_modifiedTimeUtc = p_src->getModifiedTimeUtc();
paras.m_tags = p_src->getTags();
paras.m_attachmentFolder = attachmentFolder;
auto destNode = QSharedPointer<VXNode>::create(PathUtils::fileName(destFilePath),
paras,
notebook,
p_dest);
destNode->setExists(true);
addChildNode(p_dest, destNode);
writeNodeConfig(p_dest);
if (p_updateDatabase) {
if (p_move && sameNotebook) {
updateNodeInDatabase(destNode.data());
} else {
addNodeToDatabase(destNode.data());
}
Q_ASSERT(nodeExistsInDatabase(destNode.data()));
}
if (p_move) {
if (sameNotebook) {
// The same notebook. Do not directly call removeNode() since we already update the record
// in database directly.
removeNode(p_src, false, false, false);
} else {
p_src->getNotebook()->removeNode(p_src);
}
}
return destNode;
}
QSharedPointer<Node> VXNotebookConfigMgr::copyFolderNodeAsChildOf(const QSharedPointer<Node> &p_src,
Node *p_dest,
bool p_move,
bool p_updateDatabase)
{
auto destFolderPath = PathUtils::concatenateFilePath(p_dest->fetchPath(), p_src->getName());
destFolderPath = getBackend()->renameIfExistsCaseInsensitive(destFolderPath);
// Make folder.
getBackend()->makePath(destFolderPath);
// Create a folder node.
auto notebook = getNotebook();
const bool sameNotebook = p_src->getNotebook() == notebook;
if (p_updateDatabase) {
ensureNodeInDatabase(p_dest);
if (sameNotebook) {
ensureNodeInDatabase(p_src.data());
}
}
auto destNode = QSharedPointer<VXNode>::create(PathUtils::fileName(destFolderPath),
notebook,
p_dest);
{
NodeParameters paras;
if (p_move && sameNotebook) {
paras.m_id = p_src->getId();
paras.m_signature = p_src->getSignature();
}
paras.m_createdTimeUtc = p_src->getCreatedTimeUtc();
paras.m_modifiedTimeUtc = p_src->getModifiedTimeUtc();
destNode->loadCompleteInfo(paras, QVector<QSharedPointer<Node>>());
}
destNode->setExists(true);
writeNodeConfig(destNode.data());
addChildNode(p_dest, destNode);
writeNodeConfig(p_dest);
if (p_updateDatabase) {
if (p_move && sameNotebook) {
p_updateDatabase = false;
updateNodeInDatabase(destNode.data());
} else {
addNodeToDatabase(destNode.data());
}
}
// Copy children node.
auto children = p_src->getChildren();
for (const auto &childNode : children) {
copyNodeAsChildOf(childNode, destNode.data(), p_move, p_updateDatabase);
}
if (p_move) {
if (sameNotebook) {
removeNode(p_src, false, false, false);
} else {
p_src->getNotebook()->removeNode(p_src);
}
}
return destNode;
}
void VXNotebookConfigMgr::removeNode(const QSharedPointer<Node> &p_node, bool p_force, bool p_configOnly)
{
removeNode(p_node, p_force, p_configOnly, true);
}
void VXNotebookConfigMgr::removeNode(const QSharedPointer<Node> &p_node,
bool p_force,
bool p_configOnly,
bool p_updateDatabase)
{
if (!p_configOnly && p_node->exists()) {
// Remove all children.
auto children = p_node->getChildren();
for (const auto &childNode : children) {
// With DELETE CASCADE, we could just touch the DB at parent level.
removeNode(childNode, p_force, p_configOnly, false);
}
try {
removeFilesOfNode(p_node.data(), p_force);
} catch (Exception &p_e) {
qWarning() << "failed to remove files of node" << p_node->fetchPath() << p_e.what();
}
}
if (p_updateDatabase) {
// Remove it from data base before modifying the parent.
removeNodeFromDatabase(p_node.data());
}
if (auto parentNode = p_node->getParent()) {
parentNode->removeChild(p_node);
writeNodeConfig(parentNode);
}
}
void VXNotebookConfigMgr::removeFilesOfNode(Node *p_node, bool p_force)
{
Q_ASSERT(p_node->getNotebook() == getNotebook());
if (!p_node->isContainer()) {
// Delete attachment.
if (!p_node->getAttachmentFolder().isEmpty()) {
getBackend()->removeDir(p_node->fetchAttachmentFolderPath());
}
// Delete media files fetched from content.
ContentMediaUtils::removeMediaFiles(p_node);
// Delete node file itself.
auto filePath = p_node->fetchPath();
getBackend()->removeFile(filePath);
} else {
Q_ASSERT(p_node->getChildrenCount() == 0);
// Delete node config file and the dir if it is empty.
auto configFilePath = getNodeConfigFilePath(p_node);
getBackend()->removeFile(configFilePath);
auto folderPath = p_node->fetchPath();
if (p_force) {
getBackend()->removeDir(folderPath);
} else {
getBackend()->removeEmptyDir(folderPath);
bool deleted = getBackend()->removeDirIfEmpty(folderPath);
if (!deleted) {
qWarning() << "folder is not deleted since it is not empty" << folderPath;
}
}
}
}
void VXNotebookConfigMgr::removeNodeToFolder(const QSharedPointer<Node> &p_node, const QString &p_destFolder)
{
if (p_node->isContainer()) {
removeFolderNodeToFolder(p_node, p_destFolder);
} else {
removeFileNodeToFolder(p_node, p_destFolder);
}
}
void VXNotebookConfigMgr::removeFolderNodeToFolder(const QSharedPointer<Node> &p_node, const QString &p_destFolder)
{
auto destFolderPath = PathUtils::concatenateFilePath(p_destFolder, p_node->getName());
destFolderPath = getBackend()->renameIfExistsCaseInsensitive(destFolderPath);
// Make folder.
getBackend()->makePath(destFolderPath);
// Children.
auto children = p_node->getChildren();
for (const auto &child : children) {
removeNodeToFolder(child, destFolderPath);
}
removeNode(p_node, false, false);
}
void VXNotebookConfigMgr::removeFileNodeToFolder(const QSharedPointer<Node> &p_node, const QString &p_destFolder)
{
// Use a wrapper folder.
auto destFolderPath = PathUtils::concatenateFilePath(p_destFolder, p_node->getName());
destFolderPath = getBackend()->renameIfExistsCaseInsensitive(destFolderPath);
// Make folder.
getBackend()->makePath(destFolderPath);
QString destFilePath;
QString attachmentFolder;
copyFilesOfFileNode(p_node, destFolderPath, destFilePath, attachmentFolder);
removeNode(p_node, false, false);
}
void VXNotebookConfigMgr::copyFilesOfFileNode(const QSharedPointer<Node> &p_node,
const QString &p_destFolder,
QString &p_destFilePath,
QString &p_attachmentFolder)
{
// Copy source file itself.
auto nodeFilePath = p_node->fetchAbsolutePath();
p_destFilePath = PathUtils::concatenateFilePath(p_destFolder, PathUtils::fileName(nodeFilePath));
p_destFilePath = getBackend()->renameIfExistsCaseInsensitive(p_destFilePath);
getBackend()->copyFile(nodeFilePath, p_destFilePath);
// Copy media files fetched from content.
ContentMediaUtils::copyMediaFiles(p_node.data(), getBackend().data(), p_destFilePath);
// Copy attachment folder. Rename attachment folder if conflicts.
p_attachmentFolder = p_node->getAttachmentFolder();
if (!p_attachmentFolder.isEmpty()) {
auto destAttachmentFolderPath = fetchNodeAttachmentFolder(p_destFilePath, p_attachmentFolder);
ContentMediaUtils::copyAttachment(p_node.data(), getBackend().data(), p_destFilePath, destAttachmentFolderPath);
}
}
QString VXNotebookConfigMgr::fetchNodeImageFolderPath(Node *p_node)
{
auto pa = PathUtils::concatenateFilePath(PathUtils::parentDirPath(p_node->fetchAbsolutePath()),
getNotebook()->getImageFolder());
// Do not make the folder when it is a folder node request.
if (p_node->hasContent()) {
getBackend()->makePath(pa);
}
return pa;
}
QString VXNotebookConfigMgr::fetchNodeAttachmentFolderPath(Node *p_node)
{
auto notebookFolder = PathUtils::concatenateFilePath(PathUtils::parentDirPath(p_node->fetchAbsolutePath()),
getNotebook()->getAttachmentFolder());
if (p_node->hasContent()) {
auto nodeFolder = p_node->getAttachmentFolder();
if (nodeFolder.isEmpty()) {
auto folderPath = fetchNodeAttachmentFolder(p_node->fetchAbsolutePath(), nodeFolder);
p_node->setAttachmentFolder(nodeFolder);
saveNode(p_node);
getBackend()->makePath(folderPath);
return folderPath;
} else {
return PathUtils::concatenateFilePath(notebookFolder, nodeFolder);
}
} else {
// Do not make the folder when it is a folder node request.
return notebookFolder;
}
}
QString VXNotebookConfigMgr::fetchNodeAttachmentFolder(const QString &p_nodePath, QString &p_folderName)
{
auto notebookFolder = PathUtils::concatenateFilePath(PathUtils::parentDirPath(p_nodePath),
getNotebook()->getAttachmentFolder());
if (p_folderName.isEmpty()) {
p_folderName = FileUtils::generateUniqueFileName(notebookFolder, QString(), QString());
} else if (FileUtils::childExistsCaseInsensitive(notebookFolder, p_folderName)) {
p_folderName = FileUtils::generateFileNameWithSequence(notebookFolder, p_folderName, QString());
}
return PathUtils::concatenateFilePath(notebookFolder, p_folderName);
}
bool VXNotebookConfigMgr::isBuiltInFile(const Node *p_node, const QString &p_name) const
{
static const QString backupFileExtension = ConfigMgr::getInst().getEditorConfig().getBackupFileExtension().toLower();
const auto name = p_name.toLower();
if (name == c_nodeConfigName
|| name == QStringLiteral("_vnote.json")
|| name.endsWith(backupFileExtension)) {
return true;
}
return BundleNotebookConfigMgr::isBuiltInFile(p_node, p_name);
}
bool VXNotebookConfigMgr::isBuiltInFolder(const Node *p_node, const QString &p_name) const
{
const auto name = p_name.toLower();
const auto &nb = getNotebook();
if (name == nb->getImageFolder().toLower()
|| name == nb->getAttachmentFolder().toLower()
|| name == QStringLiteral("_v_images")
|| name == QStringLiteral("_v_attachments")
|| name == QStringLiteral("vx_images")
|| name == QStringLiteral("vx_attachments")) {
return true;
}
return BundleNotebookConfigMgr::isBuiltInFolder(p_node, p_name);
}
QSharedPointer<Node> VXNotebookConfigMgr::copyFileAsChildOf(const QString &p_srcPath, Node *p_dest)
{
// Skip copy if it already locates in dest folder.
auto destFilePath = PathUtils::concatenateFilePath(p_dest->fetchAbsolutePath(),
PathUtils::fileName(p_srcPath));
if (!PathUtils::areSamePaths(p_srcPath, destFilePath)) {
// Copy source file itself.
destFilePath = getBackend()->renameIfExistsCaseInsensitive(destFilePath);
getBackend()->copyFile(p_srcPath, destFilePath);
// Copy media files fetched from content.
ContentMediaUtils::copyMediaFiles(p_srcPath, getBackend().data(), destFilePath);
}
ensureNodeInDatabase(p_dest);
const auto name = PathUtils::fileName(destFilePath);
auto destNode = p_dest->findChild(name, true);
if (destNode) {
// Already have the node.
ensureNodeInDatabase(destNode.data());
return destNode;
}
// Create a file node.
destNode = QSharedPointer<VXNode>::create(name,
NodeParameters(),
getNotebook(),
p_dest);
destNode->setExists(true);
addChildNode(p_dest, destNode);
writeNodeConfig(p_dest);
addNodeToDatabase(destNode.data());
return destNode;
}
QSharedPointer<Node> VXNotebookConfigMgr::copyFolderAsChildOf(const QString &p_srcPath, Node *p_dest)
{
// Skip copy if it already locates in dest folder.
auto destFolderPath = PathUtils::concatenateFilePath(p_dest->fetchAbsolutePath(),
PathUtils::fileName(p_srcPath));
if (!PathUtils::areSamePaths(p_srcPath, destFolderPath)) {
destFolderPath = getBackend()->renameIfExistsCaseInsensitive(destFolderPath);
// Copy folder.
getBackend()->copyDir(p_srcPath, destFolderPath);
}
ensureNodeInDatabase(p_dest);
const auto name = PathUtils::fileName(destFolderPath);
auto destNode = p_dest->findChild(name, true);
if (destNode) {
// Already have the node.
ensureNodeInDatabase(destNode.data());
return destNode;
}
// Create a folder node.
auto notebook = getNotebook();
destNode = QSharedPointer<VXNode>::create(name, notebook, p_dest);
destNode->loadCompleteInfo(NodeParameters(), QVector<QSharedPointer<Node>>());
destNode->setExists(true);
writeNodeConfig(destNode.data());
addChildNode(p_dest, destNode);
writeNodeConfig(p_dest);
addNodeToDatabase(destNode.data());
return destNode;
}
void VXNotebookConfigMgr::inheritNodeFlags(const Node *p_node, Node *p_child) const
{
if (p_node->isReadOnly()) {
markNodeReadOnly(p_child);
}
}
QVector<QSharedPointer<ExternalNode>> VXNotebookConfigMgr::fetchExternalChildren(Node *p_node) const
{
Q_ASSERT(p_node->isContainer());
QVector<QSharedPointer<ExternalNode>> externalNodes;
auto dir = p_node->toDir();
// Folders.
{
const auto folders = dir.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
for (const auto &folder : folders) {
if (isBuiltInFolder(p_node, folder)) {
continue;
}
if (isExcludedFromExternalNode(folder)) {
continue;
}
if (p_node->containsContainerChild(folder)) {
continue;
}
externalNodes.push_back(QSharedPointer<ExternalNode>::create(p_node, folder, ExternalNode::Type::Folder));
}
}
// Files.
{
const auto files = dir.entryList(QDir::Files);
for (const auto &file : files) {
if (isBuiltInFile(p_node, file)) {
continue;
}
if (isExcludedFromExternalNode(file)) {
continue;
}
if (p_node->containsContentChild(file)) {
continue;
}
externalNodes.push_back(QSharedPointer<ExternalNode>::create(p_node, file, ExternalNode::Type::File));
}
}
return externalNodes;
}
bool VXNotebookConfigMgr::isExcludedFromExternalNode(const QString &p_name) const
{
for (const auto ®Exp : s_externalNodeExcludePatterns) {
if (regExp.exactMatch(p_name)) {
return true;
}
}
return false;
}
bool VXNotebookConfigMgr::checkNodeExists(Node *p_node)
{
bool exists = getBackend()->exists(p_node->fetchPath());
p_node->setExists(exists);
return exists;
}
QStringList VXNotebookConfigMgr::scanAndImportExternalFiles(Node *p_node)
{
QStringList files;
if (!p_node->isContainer()) {
return files;
}
// External nodes.
auto dir = p_node->toDir();
auto externalNodes = fetchExternalChildren(p_node);
for (const auto &node : externalNodes) {
Node::Flags flags = Node::Flag::Content;
if (node->isFolder()) {
if (isLikelyImageFolder(dir.filePath(node->getName()))) {
qWarning() << "skip importing folder containing only images" << node->getName();
continue;
}
flags = Node::Flag::Container;
}
addAsNode(p_node, flags, node->getName(), NodeParameters());
files << dir.filePath(node->getName());
}
// Children folders (including newly-added external nodes).
for (const auto &child : p_node->getChildrenRef()) {
if (child->isContainer()) {
files << scanAndImportExternalFiles(child.data());
}
}
return files;
}
bool VXNotebookConfigMgr::isLikelyImageFolder(const QString &p_dirPath)
{
QDir dir(p_dirPath);
const auto folders = dir.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
if (!folders.isEmpty()) {
return false;
}
const auto files = dir.entryList(QDir::Files);
if (files.isEmpty()) {
return false;
}
for (const auto &file : files) {
if (!FileUtils::isImage(dir.filePath(file))) {
return false;
}
}
return true;
}
NotebookDatabaseAccess *VXNotebookConfigMgr::getDatabaseAccess() const
{
return static_cast<BundleNotebook *>(getNotebook())->getDatabaseAccess();
}
void VXNotebookConfigMgr::updateNodeInDatabase(Node *p_node)
{
Q_ASSERT(sameNotebook(p_node));
getDatabaseAccess()->updateNode(p_node);
}
void VXNotebookConfigMgr::ensureNodeInDatabase(Node *p_node)
{
if (!p_node) {
return;
}
Q_ASSERT(sameNotebook(p_node));
auto db = getDatabaseAccess();
if (db->existsNode(p_node)) {
return;
}
ensureNodeInDatabase(p_node->getParent());
db->addNode(p_node, false);
db->clearObsoleteNodes();
}
void VXNotebookConfigMgr::addNodeToDatabase(Node *p_node)
{
Q_ASSERT(sameNotebook(p_node));
auto db = getDatabaseAccess();
db->addNode(p_node, false);
db->clearObsoleteNodes();
}
bool VXNotebookConfigMgr::nodeExistsInDatabase(const Node *p_node)
{
Q_ASSERT(sameNotebook(p_node));
return getDatabaseAccess()->existsNode(p_node);
}
void VXNotebookConfigMgr::removeNodeFromDatabase(const Node *p_node)
{
Q_ASSERT(sameNotebook(p_node));
getDatabaseAccess()->removeNode(p_node);
}
bool VXNotebookConfigMgr::sameNotebook(const Node *p_node) const
{
return p_node ? p_node->getNotebook() == getNotebook() : true;
}
| 16,869 |
8,772 | <gh_stars>1000+
package org.apereo.cas.ticket.registry;
import lombok.NoArgsConstructor;
/**
* This is {@link NoOpTicketRegistryCleaner} that disables support for ticket cleanup.
*
* @author <NAME>
* @since 5.1.0
*/
@NoArgsConstructor
public class NoOpTicketRegistryCleaner implements TicketRegistryCleaner {
private static TicketRegistryCleaner INSTANCE;
/**
* Gets instance.
*
* @return the instance
*/
public static TicketRegistryCleaner getInstance() {
if (INSTANCE == null) {
INSTANCE = new NoOpTicketRegistryCleaner();
}
return INSTANCE;
}
}
| 240 |
852 | <filename>PhysicsTools/PatAlgos/interface/HemisphereAlgo.h
#ifndef HemisphereAlgo_h
#define HemisphereAlgo_h
/* \class HemisphereAlgo
*
* Class that, given the 4-momenta of the objects in the event,
* allows to split up the event into two "hemispheres" according
* to different criteria (see below)/
*
* Authors: <NAME> & <NAME> Date: July 2005
* Updated: July 2006
* Updated: 15 Sept 2006
Transported to PAT by <NAME> and <NAME>
*
*/
#include "DataFormats/Candidate/interface/Candidate.h"
#include <vector>
#include <iostream>
#include <cmath>
class HemisphereAlgo {
public:
// There are 2 constructors:
// 1. Constructor taking as argument vectors of Px, Py, Pz and E of the objects in
// the event that should be separated, the seeding method and the hemisphere
// association method,
// 2. Constructor taking as argument vectors of Px, Py, Pz and E of the objects in
// the event that should be separated. The seeding method and the hemisphere
// association method should then be defined by SetMethod(seeding_method, association_method).
//
// Seeding method: choice of 2 inital axes
// 1: 1st: max P ; 2nd: max P * delta R wrt first one
// 2: 2 objects who give maximal invariant mass (recommended)
//
// HemisphereAlgo association method:
// 1: maximum pt longitudinal projected on the axes
// 2: minimal mass squared sum of the hemispheres
// 3: minimal Lund distance (recommended)
//
// Note that SetMethod also allows the seeding and/or association method to be
// redefined for an existing hemisphere object. The GetAxis or GetGrouping is
// then recomputed using the newly defined methods.
//
HemisphereAlgo(const std::vector<reco::CandidatePtr>& componentRefs_,
const int seed_method = 0,
const int hemisphere_association_method = 0);
// Destructor
~HemisphereAlgo(){};
std::vector<float> getAxis1(); // returns Nx, Ny, Nz, P, E of the axis of group 1
std::vector<float> getAxis2(); // returns Nx, Ny, Nz, P, E of the axis of group 2
// where Nx, Ny, Nz are the direction cosines e.g. Nx = Px/P,
// P is the momentum, E is the energy
std::vector<int> getGrouping(); // returns vector with "1" and "2"'s according to
// which group the object belongs
// (order of objects in vector is same as input)
void SetMethod(int seed_method, int hemisphere_association_method) {
seed_meth = seed_method;
hemi_meth = hemisphere_association_method;
status = 0;
} // sets or overwrites the seed and association methods
void SetNoSeed(int object_number) {
Object_Noseed[object_number] = 1;
status = 0;
}
// prevents an object from being used as a seed
// (method introduced on 15/09/06)
private:
int reconstruct(); // the hemisphere separation algorithm
std::vector<reco::CandidatePtr> Object;
std::vector<int> Object_Group;
std::vector<int> Object_Noseed;
std::vector<float> Axis1;
std::vector<float> Axis2;
//static const float hemivsn = 1.01;
int seed_meth;
int hemi_meth;
int status;
};
#endif
| 1,153 |
475 | <gh_stars>100-1000
package org.micro.neural.limiter;
/**
* The Excess Exception of Limiter.
*
* @author lry
*/
public class LimiterExceedException extends RuntimeException {
private static final long serialVersionUID = -8228538343786169063L;
public LimiterExceedException(String message) {
super(message);
}
}
| 116 |
8,107 | <reponame>abhicantdraw/pandas-profiling<gh_stars>1000+
"""This file add the console interface to the package."""
import argparse
from pathlib import Path
from typing import Any, List, Optional
from pandas_profiling.__init__ import ProfileReport, __version__
from pandas_profiling.utils.dataframe import read_pandas
def parse_args(args: Optional[List[Any]] = None) -> argparse.Namespace:
"""Parse the command line arguments for the `pandas_profiling` binary.
Args:
args: List of input arguments. (Default value=None).
Returns:
Namespace with parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Profile the variables in a CSV file and generate a HTML report."
)
# Version
parser.add_argument(
"--version", action="version", version=f"%(prog)s {__version__}"
)
# Console specific
parser.add_argument(
"-s",
"--silent",
help="Only generate but do not open report",
action="store_true",
)
parser.add_argument(
"-m",
"--minimal",
help="Minimal configuration for big data sets",
action="store_true",
)
parser.add_argument(
"-e",
"--explorative",
help="Explorative configuration featuring unicode, file and image analysis",
action="store_true",
)
# Config
parser.add_argument(
"--pool_size", type=int, default=0, help="Number of CPU cores to use"
)
parser.add_argument(
"--title",
type=str,
default="Pandas Profiling Report",
help="Title for the report",
)
parser.add_argument(
"--infer_dtypes",
default=False,
action="store_true",
help="To infer dtypes of the dataframe",
)
parser.add_argument(
"--no-infer_dtypes",
dest="infer_dtypes",
action="store_false",
help="To read dtypes as read by pandas",
)
parser.add_argument(
"--config_file",
type=str,
default=None,
help="Specify a yaml config file. Have a look at the 'config_default.yaml' as a starting point.",
)
parser.add_argument(
"input_file",
type=str,
help="CSV file (or other file type supported by pandas) to profile",
)
parser.add_argument(
"output_file",
type=str,
nargs="?",
help="Output report file. If empty, replaces the input_file's extension with .html and uses that.",
default=None,
)
return parser.parse_args(args)
def main(args: Optional[List[Any]] = None) -> None:
"""Run the `pandas_profiling` package.
Args:
args: Arguments for the programme (Default value=None).
"""
# Parse the arguments
parsed_args = parse_args(args)
kwargs = vars(parsed_args)
input_file = Path(kwargs.pop("input_file"))
output_file = kwargs.pop("output_file")
if output_file is None:
output_file = str(input_file.with_suffix(".html"))
silent = kwargs.pop("silent")
# read the DataFrame
df = read_pandas(input_file)
# Generate the profiling report
p = ProfileReport(
df,
**kwargs,
)
p.to_file(Path(output_file), silent=silent)
| 1,340 |
619 | /*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.javakaffee.web.msm;
import static de.javakaffee.web.msm.integration.TestUtils.createSession;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import redis.clients.jedis.BinaryJedis;
import redis.embedded.RedisServer;
import de.javakaffee.web.msm.BackupSessionTask.BackupResult;
import de.javakaffee.web.msm.integration.TestUtils;
import de.javakaffee.web.msm.integration.TomcatBuilder;
import de.javakaffee.web.msm.storage.RedisStorageClient;
/**
* @author @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public abstract class RedisIntegrationTest {
private static final Log LOG = LogFactory.getLog(RedisIntegrationTest.class);
private RedisServer embeddedRedisServer;
private BinaryJedis redisClient;
private TomcatBuilder<?> _tomcat1;
private final int _portTomcat1 = 18888;
private boolean redisProvided;
private TranscoderService transcoderService;
abstract TestUtils<?> getTestUtils();
@BeforeMethod
public void setUp(final Method testMethod) throws Throwable {
redisProvided = Boolean.parseBoolean(System.getProperty("redis.provided", "false"));
final int redisPort = Integer.parseInt(System.getProperty("redis.port", "16379"));
if (!redisProvided) {
embeddedRedisServer = new RedisServer(redisPort);
embeddedRedisServer.start();
}
try {
System.setProperty( "org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true" );
_tomcat1 = getTestUtils().tomcatBuilder().port(_portTomcat1).memcachedNodes("redis://localhost:"+ redisPort)
.sticky(true).buildAndStart();
} catch ( final Throwable e ) {
LOG.error( "could not start tomcat.", e );
throw e;
}
redisClient = new BinaryJedis("localhost", redisPort);
transcoderService = new TranscoderService(new JavaSerializationTranscoder(_tomcat1.getManager()));
}
@AfterMethod
public void tearDown() throws Exception {
if (redisClient != null) {
redisClient.close();
redisClient = null;
}
if (embeddedRedisServer != null) {
embeddedRedisServer.stop();
embeddedRedisServer = null;
}
_tomcat1.stop();
}
@Test
public void testBackupSessionInRedis()
throws InterruptedException, ExecutionException, UnsupportedEncodingException, ClassNotFoundException, IOException {
final MemcachedSessionService service = _tomcat1.getService();
final MemcachedBackupSession session = createSession( service );
final String sessionId = "12345";
session.setId(sessionId);
session.setAttribute( "foo", "bar" );
final BackupResult backupResult = service.backupSession( session.getIdInternal(), false, null ).get();
assertEquals(backupResult.getStatus(), BackupResultStatus.SUCCESS);
final MemcachedBackupSession loadedSession = transcoderService.deserialize(
redisClient.get(sessionId.getBytes("UTF-8")), _tomcat1.getManager());
checkSession(loadedSession, session);
}
private void checkSession(final MemcachedBackupSession actual, final MemcachedBackupSession expected) {
assertNotNull(actual);
assertEquals(actual.getId(), expected.getId());
assertEquals(actual.getAttributesInternal(), expected.getAttributesInternal());
}
}
| 1,687 |
4,756 | // Copyright 2018 The MACE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include "mace/benchmark_utils/test_benchmark.h"
#include "mace/ops/ops_test_util.h"
namespace mace {
namespace ops {
namespace test {
namespace {
template <RuntimeType D, typename T>
void PNormBenchmark(int iters, int n, int h, int w, int p, int ow) {
mace::testing::StopTiming();
OpsTestNet net;
// Add input data
net.AddRandomInput<D, float>("Input", {n, h, w});
OpDefBuilder("PNorm", "PNormBM")
.Input("Input")
.AddIntArg("p", p)
.AddIntArg("output_dim", ow)
.Output("Output")
.Finalize(net.NewOperatorDef());
// Warm-up
net.Setup(D);
for (int i = 0; i < 5; ++i) {
net.Run();
}
net.Sync();
mace::testing::StartTiming();
while (iters--) {
net.Run();
}
net.Sync();
}
} // namespace
#define MACE_BM_PNORM_MACRO(N, H, W, P, OW, TYPE, DEVICE) \
static void \
MACE_BM_PNORM_##N##_##H##_##W##_##P##_##OW##_##TYPE##_##DEVICE( \
int iters) { \
const int64_t tot = static_cast<int64_t>(iters) * N * H * W; \
mace::testing::BytesProcessed(tot *(sizeof(TYPE))); \
PNormBenchmark<DEVICE, TYPE>(iters, N, H, W, P, OW); \
} \
MACE_BENCHMARK( \
MACE_BM_PNORM_##N##_##H##_##W##_##P##_##OW##_##TYPE##_##DEVICE)
#define MACE_BM_PNORM(N, H, W, P, OW) \
MACE_BM_PNORM_MACRO(N, H, W, P, OW, float, RT_CPU);
MACE_BM_PNORM(1, 10, 256, 0, 128);
MACE_BM_PNORM(1, 20, 128, 1, 64);
MACE_BM_PNORM(1, 10, 128, 2, 64);
MACE_BM_PNORM(1, 16, 256, 0, 128);
MACE_BM_PNORM(1, 32, 128, 1, 64);
MACE_BM_PNORM(1, 10, 512, 2, 256);
} // namespace test
} // namespace ops
} // namespace mace
| 1,147 |
17,702 | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#pragma once
#include "ColumnQuantizer.h"
#include "QuantizedMatrix.h"
#include "MatrixQuantizerImpl.h"
namespace Microsoft { namespace MSR { namespace CNTK {
// This type does the quantization on a matrix
// This is a technique to reduce the cost of communicating
// the gradient matrices during aggregation across all nodes in
// data-parallel SGD training, at the end of each minibatch.
// Refer this paper http://research.microsoft.com/apps/pubs/?id=230137
// for details.
class MatrixQuantizerBase
{};
template <class ElemType>
class MatrixQuantizer final : public MatrixQuantizerBase
{
public:
MatrixQuantizer(size_t numRows, size_t numCols, int deviceId, bool useAsync) : MatrixQuantizer(deviceId, useAsync)
{
m_residual = std::make_shared<Matrix<ElemType>>(numRows, numCols, deviceId, DENSE);
}
MatrixQuantizer(int deviceId, bool useAsync) : m_residual(nullptr)
{
m_quantizerImpl.reset(MatrixQuantizerImpl<ElemType>::Create(deviceId, useAsync));
}
// Disallow copy and move construction and assignment
DISABLE_COPY_AND_MOVE(MatrixQuantizer);
void QuantizeAsync(const Matrix<ElemType>& inMatrix, QuantizedMatrix<ElemType>& outQMatrix, bool zeroThresholdFor1Bit)
{
m_quantizerImpl->QuantizeAsync(inMatrix, *m_residual, outQMatrix, *m_residual, zeroThresholdFor1Bit);
}
void QuantizeAsync(const Matrix<ElemType>& inMatrix, const Matrix<ElemType>& inResidual, QuantizedMatrix<ElemType>& outQMatrix, Matrix<ElemType>& outResidual, bool zeroThresholdFor1Bit)
{
m_quantizerImpl->QuantizeAsync(inMatrix, inResidual, outQMatrix, outResidual, zeroThresholdFor1Bit);
}
void WaitQuantizeAsyncDone()
{
m_quantizerImpl->WaitQuantizeAsyncDone();
}
void UnquantizeAsync(QuantizedMatrix<ElemType>& inQMatrix, Matrix<ElemType>& outMatrix, bool add = false)
{
m_quantizerImpl->UnquantizeAsync(inQMatrix, outMatrix, add);
}
void WaitUnquantizeAsyncDone()
{
m_quantizerImpl->WaitUnquantizeAsyncDone();
}
int GetDeviceId() const
{
return m_quantizerImpl->GetDeviceId();
}
void ResetResidue()
{
m_residual->SetValue(0.0);
}
const Matrix<ElemType>& GetResidualMatrix() const
{
return *m_residual;
}
private:
std::unique_ptr<MatrixQuantizerImpl<ElemType>> m_quantizerImpl;
// the residual matrix
std::shared_ptr<Matrix<ElemType>> m_residual;
};
} } }
| 972 |
1,013 | """!
@brief Examples of usage and demonstration of abilities of algorithm (based on modified Sync) in graph coloring.
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
"""
from pyclustering.gcolor.sync import syncgcolor;
from pyclustering.nnet import *;
from pyclustering.utils import draw_dynamics;
from pyclustering.utils.graph import read_graph, draw_graph;
from pyclustering.samples.definitions import GRAPH_SIMPLE_SAMPLES;
def template_graph_coloring(positive_weight, negative_weight, filename, reduction = None, title = None):
if (title is None): title = filename;
print("\nGraph Coloring: ", title);
graph = read_graph(filename);
network = syncgcolor(graph.data, positive_weight, negative_weight, reduction);
analyser = network.process(order = 0.999, solution = solve_type.FAST, collect_dynamic = True);
sync.sync_visualizer.show_output_dynamic(analyser);
clusters = analyser.allocate_color_clusters();
for index in range(0, len(clusters)):
print("Color #", index, ": ", clusters[index]);
coloring_map = analyser.allocate_map_coloring();
print("Number colors: ", max(coloring_map));
draw_graph(graph, coloring_map);
# Check validity of colors
for index_node in range(len(graph.data)):
color_neighbors = [ coloring_map[index] for index in range(len(graph.data[index_node])) if graph.data[index_node][index] != 0 and index_node != index];
#print(index_node, map_coloring[index_node], color_neighbors, assigned_colors, map_coloring, "\n\n");
if (coloring_map[index_node] in color_neighbors):
print("Warining: Incorrect coloring");
return;
def run_all_graph_simple_samples():
template_graph_coloring(1, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_ONE_CIRCLE1, None, "Circle 1");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_ONE_CIRCLE2, None, "Circle 2");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_ONE_CIRCLE3, None, "Circle 3");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_BROKEN_CIRCLE1, None, "Broken Circle 1");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_BROKEN_CIRCLE2, None, "Broken Circle 2");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_ONE_CROSSROAD, None, "One Crossroad");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_FIVE_POINTED_STAR, None, "Five Pointed Star");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_ONE_LINE, None, "One Line");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_TWO_CROSSROADS, None, "Two Interconnected Stars");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_FIVE_POINTED_FRAME_STAR, None, "Five Pointed Star With Frame");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_FULL1, None, "Full interconneted graph 1 (all-to-all)");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_FULL2, None, "Full interconneted graph 2 (all-to-all)");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_SIMPLE1, None, "Simple 1");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_SIMPLE2, None, "Simple 2");
template_graph_coloring(0, -1, GRAPH_SIMPLE_SAMPLES.GRAPH_SIMPLE3, None, "Simple 3");
run_all_graph_simple_samples(); | 1,435 |
383 | <gh_stars>100-1000
package org.gitlab.api.models;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonProperty;
public class GitlabNote {
public static final String URL = "/notes";
private Integer id;
private String body;
private String attachment;
private GitlabUser author;
private boolean system;
private boolean upvote;
private boolean downvote;
@JsonProperty("created_at")
private Date createdAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public GitlabUser getAuthor() {
return author;
}
public void setAuthor(GitlabUser author) {
this.author = author;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public boolean isSystem() {
return system;
}
public void setSystem(boolean system) {
this.system = system;
}
public boolean isUpvote() {
return upvote;
}
public void setUpvote(boolean upvote) {
this.upvote = upvote;
}
public boolean isDownvote() {
return downvote;
}
public void setDownvote(boolean downvote) {
this.downvote = downvote;
}
}
| 646 |
15,684 | <reponame>gonencmete/IQKeyboardManager
//
// SettingsViewController.h
// IQKeyboard
//
// Created by Iftekhar on 27/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SettingsViewController : UITableViewController
@end
| 96 |
5,169 | {
"name": "VBAnimator",
"version": "1.0.0",
"summary": "Animator helps you to adding animation for presenting controller",
"description": "Animator helps you to adding animation for presenting controller\nLess coding",
"homepage": "https://github.com/BusyDeveloper-Bhavin/Animator",
"license": "MIT",
"authors": {
"Bhavin": "<EMAIL>"
},
"platforms": {
"ios": "12.0"
},
"source": {
"git": "https://github.com/BusyDeveloper-Bhavin/Animator.git",
"tag": "1.0.0"
},
"vendored_frameworks": "Animator.xcframework"
}
| 209 |
706 | <reponame>deepmining7/RadeonRays_SDK
#pragma once
#include <chrono>
#include <iostream>
#include <stack>
#include "gtest/gtest.h"
#include "mesh_data.h"
#include "radeonrays_vlk.h"
#include "stb_image_write.h"
//#define USE_RENDERDOC
#ifdef USE_RENDERDOC
#define NOMINMAX
#include <windows.h>
#include "C:\\Program Files\\RenderDoc\\renderdoc_app.h"
#endif
#define CHECK_RR_CALL(x) ASSERT_EQ((x), RR_SUCCESS)
using namespace std::chrono;
template <typename T>
using VkScopedObject = std::shared_ptr<std::remove_pointer_t<T>>;
class InternalResourcesTest : public ::testing::Test
{
public:
void SetUp() override;
void TearDown() override {}
#ifdef USE_RENDERDOC
RENDERDOC_API_1_4_0* rdoc_api_ = NULL;
#endif
};
void InternalResourcesTest::SetUp()
{
#ifdef USE_RENDERDOC
// At init, on windows
if (HMODULE mod = LoadLibraryA("C:\\Program Files\\RenderDoc\\renderdoc.dll"))
{
pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)GetProcAddress(mod, "RENDERDOC_GetAPI");
int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_4_0, (void**)&rdoc_api_);
assert(ret == 1);
}
#endif
}
TEST_F(InternalResourcesTest, CreateContext)
{
RRContext context = nullptr;
CHECK_RR_CALL(rrCreateContext(RR_API_VERSION, RR_API_VK, &context));
CHECK_RR_CALL(rrDestroyContext(context));
}
TEST_F(InternalResourcesTest, BuildObj)
{
RRContext context = nullptr;
CHECK_RR_CALL(rrCreateContext(RR_API_VERSION, RR_API_VK, &context));
#ifdef USE_RENDERDOC
if (rdoc_api_)
{
rdoc_api_->StartFrameCapture(nullptr, nullptr);
}
#endif
MeshData mesh_data("../../resources/sponza.obj");
/// memory management to pass buffers to builder
// get radeonrays ptrs to triangle description
RRDevicePtr vertex_ptr = nullptr;
RRDevicePtr index_ptr = nullptr;
CHECK_RR_CALL(rrAllocateDeviceBuffer(context, mesh_data.positions.size() * sizeof(float), &vertex_ptr));
CHECK_RR_CALL(rrAllocateDeviceBuffer(context, mesh_data.indices.size() * sizeof(uint32_t), &index_ptr));
void* ptr = nullptr;
CHECK_RR_CALL(rrMapDevicePtr(context, vertex_ptr, &ptr));
float* pos_ptr = (float*)ptr;
for (const auto& pos : mesh_data.positions)
{
*pos_ptr = pos;
pos_ptr++;
}
CHECK_RR_CALL(rrUnmapDevicePtr(context, vertex_ptr, &ptr));
CHECK_RR_CALL(rrMapDevicePtr(context, index_ptr, &ptr));
uint32_t* ind_ptr = (uint32_t*)ptr;
for (const auto& ind : mesh_data.indices)
{
*ind_ptr = ind;
ind_ptr++;
}
CHECK_RR_CALL(rrUnmapDevicePtr(context, index_ptr, &ptr));
auto triangle_count = (uint32_t)mesh_data.indices.size() / 3;
RRGeometryBuildInput geometry_build_input = {};
RRTriangleMeshPrimitive mesh = {};
geometry_build_input.triangle_mesh_primitives = &mesh;
geometry_build_input.primitive_type = RR_PRIMITIVE_TYPE_TRIANGLE_MESH;
geometry_build_input.triangle_mesh_primitives->vertices = vertex_ptr;
geometry_build_input.triangle_mesh_primitives->vertex_count = uint32_t(mesh_data.positions.size() / 3);
geometry_build_input.triangle_mesh_primitives->vertex_stride = 3 * sizeof(float);
geometry_build_input.triangle_mesh_primitives->triangle_indices = index_ptr;
geometry_build_input.triangle_mesh_primitives->triangle_count = triangle_count;
geometry_build_input.triangle_mesh_primitives->index_type = RR_INDEX_TYPE_UINT32;
geometry_build_input.primitive_count = 1u;
std::cout << "Triangle count " << triangle_count << "\n";
RRBuildOptions options;
options.build_flags = 0u;
RRMemoryRequirements geometry_reqs;
CHECK_RR_CALL(rrGetGeometryBuildMemoryRequirements(context, &geometry_build_input, &options, &geometry_reqs));
// allocate buffers for builder and resulting geometry
RRDevicePtr scratch_ptr = nullptr;
RRDevicePtr geometry_ptr = nullptr;
CHECK_RR_CALL(rrAllocateDeviceBuffer(context, geometry_reqs.temporary_build_buffer_size, &scratch_ptr));
CHECK_RR_CALL(rrAllocateDeviceBuffer(context, geometry_reqs.result_buffer_size, &geometry_ptr));
std::cout << "Scratch buffer size: " << (float)geometry_reqs.temporary_build_buffer_size / 1000000 << "Mb\n";
std::cout << "Result buffer size: " << (float)geometry_reqs.result_buffer_size / 1000000 << "Mb\n";
RRCommandStream command_stream = nullptr;
CHECK_RR_CALL(rrAllocateCommandStream(context, &command_stream));
CHECK_RR_CALL(rrCmdBuildGeometry(
context, RR_BUILD_OPERATION_BUILD, &geometry_build_input, &options, scratch_ptr, geometry_ptr, command_stream));
RREvent wait_event = nullptr;
CHECK_RR_CALL(rrSumbitCommandStream(context, command_stream, nullptr, &wait_event));
CHECK_RR_CALL(rrWaitEvent(context, wait_event));
CHECK_RR_CALL(rrReleaseEvent(context, wait_event));
CHECK_RR_CALL(rrReleaseCommandStream(context, command_stream));
// built-in intersection
using Ray = RRRay;
using Hit = RRHit;
constexpr uint32_t kResolution = 640;
std::vector<Ray> rays(kResolution * kResolution);
std::vector<Hit> hits(kResolution * kResolution);
for (int x = 0; x < kResolution; ++x)
{
for (int y = 0; y < kResolution; ++y)
{
auto i = kResolution * y + x;
rays[i].origin[0] = 0.f;
rays[i].origin[1] = 15.f;
rays[i].origin[2] = 0.f;
rays[i].direction[0] = -1.f;
rays[i].direction[1] = -1.f + (2.f / kResolution) * y;
rays[i].direction[2] = -1.f + (2.f / kResolution) * x;
rays[i].min_t = 0.001f;
rays[i].max_t = 100000.f;
}
}
RRDevicePtr rays_ptr, hits_ptr, scratch_trace_ptr;
CHECK_RR_CALL(rrAllocateDeviceBuffer(context, rays.size() * sizeof(Ray), &rays_ptr));
CHECK_RR_CALL(rrAllocateDeviceBuffer(context, hits.size() * sizeof(Hit), &hits_ptr));
size_t scratch_trace_size;
CHECK_RR_CALL(rrGetTraceMemoryRequirements(context, kResolution * kResolution, &scratch_trace_size));
CHECK_RR_CALL(rrAllocateDeviceBuffer(context, scratch_trace_size, &scratch_trace_ptr));
CHECK_RR_CALL(rrMapDevicePtr(context, rays_ptr, &ptr));
std::memcpy(ptr, rays.data(), sizeof(Ray) * rays.size());
CHECK_RR_CALL(rrUnmapDevicePtr(context, rays_ptr, &ptr));
RRCommandStream trace_command_stream = nullptr;
CHECK_RR_CALL(rrAllocateCommandStream(context, &trace_command_stream));
CHECK_RR_CALL(rrCmdIntersect(context,
geometry_ptr,
RR_INTERSECT_QUERY_CLOSEST,
rays_ptr,
kResolution * kResolution,
nullptr,
RR_INTERSECT_QUERY_OUTPUT_FULL_HIT,
hits_ptr,
scratch_trace_ptr,
trace_command_stream));
CHECK_RR_CALL(rrSumbitCommandStream(context, trace_command_stream, nullptr, &wait_event));
CHECK_RR_CALL(rrWaitEvent(context, wait_event));
CHECK_RR_CALL(rrReleaseEvent(context, wait_event));
CHECK_RR_CALL(rrReleaseCommandStream(context, trace_command_stream));
// Map staging ray buffer.
CHECK_RR_CALL(rrMapDevicePtr(context, hits_ptr, &ptr));
Hit* mapped_ptr = (Hit*)ptr;
std::vector<uint32_t> data(kResolution * kResolution);
for (int y = 0; y < kResolution; ++y)
{
for (int x = 0; x < kResolution; ++x)
{
int wi = kResolution * (kResolution - 1 - y) + x;
int i = kResolution * y + x;
if (mapped_ptr[i].inst_id != ~0u)
{
data[wi] = 0xff000000 | (uint32_t(mapped_ptr[i].uv[0] * 255) << 8) |
(uint32_t(mapped_ptr[i].uv[1] * 255) << 16);
} else
{
data[wi] = 0xff101010;
}
}
}
CHECK_RR_CALL(rrUnmapDevicePtr(context, hits_ptr, &ptr));
stbi_write_jpg("test_vk_sponza_geom_isect_internal.jpg", kResolution, kResolution, 4, data.data(), 120);
CHECK_RR_CALL(rrReleaseDevicePtr(context, hits_ptr));
CHECK_RR_CALL(rrReleaseDevicePtr(context, rays_ptr));
CHECK_RR_CALL(rrReleaseDevicePtr(context, scratch_trace_ptr));
#ifdef USE_RENDERDOC
if (rdoc_api_)
{
rdoc_api_->EndFrameCapture(nullptr, nullptr);
}
#endif
CHECK_RR_CALL(rrReleaseDevicePtr(context, scratch_ptr));
CHECK_RR_CALL(rrReleaseDevicePtr(context, geometry_ptr));
CHECK_RR_CALL(rrReleaseDevicePtr(context, index_ptr));
CHECK_RR_CALL(rrReleaseDevicePtr(context, vertex_ptr));
CHECK_RR_CALL(rrDestroyContext(context));
}
| 4,030 |
321 | <reponame>AppSecAI-TEST/qalingo-engine
/**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - <EMAIL>
*
*/
package org.hoteia.qalingo.web.mvc.controller.user;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.hoteia.qalingo.core.Constants;
import org.hoteia.qalingo.core.ModelConstants;
import org.hoteia.qalingo.core.RequestConstants;
import org.hoteia.qalingo.core.domain.MarketArea;
import org.hoteia.qalingo.core.domain.User;
import org.hoteia.qalingo.core.domain.enumtype.BoUrls;
import org.hoteia.qalingo.core.web.mvc.controller.AbstractBackofficeQalingoController;
import org.hoteia.qalingo.core.web.mvc.form.UserForm;
import org.hoteia.qalingo.core.web.mvc.viewbean.UserViewBean;
import org.hoteia.qalingo.core.web.resolver.RequestData;
import org.hoteia.qalingo.core.web.servlet.ModelAndViewThemeDevice;
import org.hoteia.qalingo.core.web.servlet.view.RedirectView;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* User details
*/
@Controller("userController")
public class UserController extends AbstractBackofficeQalingoController {
@RequestMapping(value = BoUrls.USER_LIST_URL, method = RequestMethod.GET)
public ModelAndView userList(final HttpServletRequest request, final Model model) throws Exception {
ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), BoUrls.USER_LIST.getVelocityPage());
final RequestData requestData = requestUtil.getRequestData(request);
final MarketArea marketArea = requestData.getMarketArea();
displayList(request, model, requestData);
Object[] params = {marketArea.getName() + " (" + marketArea.getCode() + ")"};
overrideDefaultMainContentTitle(request, modelAndView, BoUrls.USER_LIST.getKey() + "", params);
return modelAndView;
}
@RequestMapping(value = BoUrls.USER_DETAILS_URL, method = RequestMethod.GET)
public ModelAndView userDetails(final HttpServletRequest request, final Model model) throws Exception {
ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), BoUrls.USER_DETAILS.getVelocityPage());
final RequestData requestData = requestUtil.getRequestData(request);
final String userCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_USER_CODE);
final User user = userService.getUserByCode(userCode);
UserViewBean userViewBean = backofficeViewBeanFactory.buildViewBeanUser(requestData, user);
if(userViewBean == null){
final String url = requestUtil.getLastRequestUrl(request);
return new ModelAndView(new RedirectView(url));
}
model.addAttribute(ModelConstants.URL_BACK, backofficeUrlService.generateUrl(BoUrls.USER_LIST, requestData));
request.setAttribute(ModelConstants.USER_VIEW_BEAN, userViewBean);
Object[] params = {user.getLastname() + " " + user.getFirstname() + " (" + user.getLogin() + ")"};
overrideDefaultMainContentTitle(request, modelAndView, BoUrls.USER_DETAILS.getKey(), params);
return modelAndView;
}
@RequestMapping(value = BoUrls.USER_EDIT_URL, method = RequestMethod.GET)
public ModelAndView userEdit(final HttpServletRequest request, final Model model, @ModelAttribute(ModelConstants.USER_FORM) UserForm userForm) throws Exception {
ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), BoUrls.USER_EDIT.getVelocityPage());
final RequestData requestData = requestUtil.getRequestData(request);
final String userCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_USER_CODE);
final User user = userService.getUserByCode(userCode);
UserViewBean userViewBean = backofficeViewBeanFactory.buildViewBeanUser(requestData, user);
if(userViewBean == null){
final String url = requestUtil.getLastRequestUrl(request);
return new ModelAndView(new RedirectView(url));
}
model.addAttribute(ModelConstants.URL_BACK, backofficeUrlService.generateUrl(BoUrls.USER_DETAILS, requestData, user));
request.setAttribute(ModelConstants.USER_VIEW_BEAN, userViewBean);
Object[] params = {user.getLastname() + " " + user.getFirstname() + " (" + user.getLogin() + ")"};
overrideDefaultMainContentTitle(request, modelAndView, BoUrls.USER_DETAILS.getKey(), params);
return modelAndView;
}
@RequestMapping(value = BoUrls.USER_EDIT_URL, method = RequestMethod.POST)
public ModelAndView submitUserEdit(final HttpServletRequest request, @Valid @ModelAttribute(ModelConstants.USER_FORM) UserForm userForm,
BindingResult result, final Model model) throws Exception {
if (result.hasErrors()) {
return userEdit(request, model, userForm);
}
final String userCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_USER_CODE);
final User user = userService.getUserByCode(userCode);
// Update the user
webBackofficeService.createOrUpdateUser(user, userForm);
final String urlRedirect = backofficeUrlService.generateUrl(BoUrls.USER_DETAILS, requestUtil.getRequestData(request), user);
return new ModelAndView(new RedirectView(urlRedirect));
}
/**
*
*/
@ModelAttribute(ModelConstants.USER_FORM)
protected UserForm initUserForm(final HttpServletRequest request, final Model model) throws Exception {
final RequestData requestData = requestUtil.getRequestData(request);
final String userCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_USER_CODE);
if(StringUtils.isNotEmpty(userCode)){
final User userEdit = userService.getUserByCode(userCode);
return backofficeFormFactory.buildUserForm(requestData, userEdit);
}
return backofficeFormFactory.buildUserForm(requestData, null);
}
protected void displayList(final HttpServletRequest request, final Model model, final RequestData requestData) throws Exception {
String url = request.getRequestURI();
String page = request.getParameter(Constants.PAGINATION_PAGE_PARAMETER);
String sessionKey = "PagedListHolder_Users";
PagedListHolder<UserViewBean> userViewBeanPagedListHolder = new PagedListHolder<UserViewBean>();
if(StringUtils.isEmpty(page)){
userViewBeanPagedListHolder = initList(request, sessionKey, requestData);
} else {
userViewBeanPagedListHolder = (PagedListHolder) request.getSession().getAttribute(sessionKey);
if (userViewBeanPagedListHolder == null) {
userViewBeanPagedListHolder = initList(request, sessionKey, requestData);
}
int pageTarget = new Integer(page).intValue() - 1;
int pageCurrent = userViewBeanPagedListHolder.getPage();
if (pageCurrent < pageTarget) {
for (int i = pageCurrent; i < pageTarget; i++) {
userViewBeanPagedListHolder.nextPage();
}
} else if (pageCurrent > pageTarget) {
for (int i = pageTarget; i < pageCurrent; i++) {
userViewBeanPagedListHolder.previousPage();
}
}
}
model.addAttribute(Constants.PAGINATION_PAGE_URL, url);
model.addAttribute(Constants.PAGINATION_PAGE_PAGED_LIST_HOLDER, userViewBeanPagedListHolder);
}
protected PagedListHolder<UserViewBean> initList(final HttpServletRequest request, String sessionKey, final RequestData requestData) throws Exception {
final MarketArea marketArea = requestData.getMarketArea();
List<User> users = userService.findUsers();
PagedListHolder<UserViewBean> userViewBeanPagedListHolder = new PagedListHolder<UserViewBean>();
final List<UserViewBean> userViewBeans = new ArrayList<UserViewBean>();
for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
User userIt = (User) iterator.next();
userViewBeans.add(backofficeViewBeanFactory.buildViewBeanUser(requestData, userIt));
}
userViewBeanPagedListHolder = new PagedListHolder<UserViewBean>(userViewBeans);
userViewBeanPagedListHolder.setPageSize(Constants.PAGE_SIZE);
request.getSession().setAttribute(sessionKey, userViewBeanPagedListHolder);
return userViewBeanPagedListHolder;
}
} | 3,907 |
333 | //
// VIDMoviePlayerViewController.h
// SuperProject
//
// Created by NShunJian on 2018/4/20.
// Copyright © 2018年 superMan. All rights reserved.
//
#import "SUPBaseViewController.h"
@interface VIDMoviePlayerViewController : SUPBaseViewController
/** <#digest#> */
@property (nonatomic, copy) NSString *videoURL;
@end
| 109 |
348 | {"nom":"<NAME>","circ":"10ème circonscription","dpt":"Bouches-du-Rhône","inscrits":2640,"abs":1300,"votants":1340,"blancs":30,"nuls":3,"exp":1307,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":388},{"nuance":"FN","nom":"<NAME>","voix":340},{"nuance":"UDI","nom":"M. <NAME>","voix":131},{"nuance":"DVD","nom":"M. <NAME>","voix":131},{"nuance":"FI","nom":"M. <NAME>","voix":130},{"nuance":"DLF","nom":"<NAME>","voix":32},{"nuance":"COM","nom":"M. <NAME>","voix":31},{"nuance":"ECO","nom":"M. <NAME>","voix":29},{"nuance":"ECO","nom":"M. <NAME>","voix":28},{"nuance":"EXD","nom":"M. <NAME>","voix":17},{"nuance":"SOC","nom":"M. <NAME>","voix":13},{"nuance":"EXG","nom":"M. <NAME>","voix":10},{"nuance":"DIV","nom":"Mme <NAME>","voix":8},{"nuance":"DIV","nom":"<NAME>","voix":7},{"nuance":"DIV","nom":"M. <NAME>","voix":7},{"nuance":"DVG","nom":"Mme <NAME>","voix":5},{"nuance":"ECO","nom":"Mme <NAME>","voix":0}]} | 376 |
416 | package org.springframework.roo.classpath.customdata.tagkeys;
import java.util.List;
import org.springframework.roo.classpath.details.InvocableMemberMetadata;
import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
/**
* {@link InvocableMemberMetadata}-specific implementation of
* {@link IdentifiableAnnotatedJavaStructureCustomDataKey}.
*
* @author <NAME>
* @since 1.1.3
*/
public abstract class InvocableMemberMetadataCustomDataKey<T extends InvocableMemberMetadata>
extends IdentifiableAnnotatedJavaStructureCustomDataKey<T> {
private List<JavaSymbolName> parameterNames;
private List<AnnotatedJavaType> parameterTypes;
private List<JavaType> throwsTypes;
protected InvocableMemberMetadataCustomDataKey() {
super();
}
protected InvocableMemberMetadataCustomDataKey(final Integer modifier,
final List<AnnotationMetadata> annotations, final List<AnnotatedJavaType> parameterTypes,
final List<JavaSymbolName> parameterNames, final List<JavaType> throwsTypes) {
super(modifier, annotations);
this.parameterTypes = parameterTypes;
this.parameterNames = parameterNames;
this.throwsTypes = throwsTypes;
}
public List<JavaSymbolName> getParameterNames() {
return parameterNames;
}
public List<AnnotatedJavaType> getParameterTypes() {
return parameterTypes;
}
public List<JavaType> getThrowsTypes() {
return throwsTypes;
}
@Override
public boolean meets(final T invocableMemberMetadata) throws IllegalStateException {
// TODO: Add in validation logic for parameterTypes, parameterNames,
// throwsTypes
return super.meets(invocableMemberMetadata);
}
}
| 560 |
372 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.osconfig.v1.model;
/**
* A resource that manages a system package.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud OS Config API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class PackageResource extends com.google.api.client.json.GenericJson {
/**
* A package managed by Apt.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PackageResourceAPT apt;
/**
* A deb package file.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PackageResourceDeb deb;
/**
* The desired_state the agent should maintain for this package. The default is to ensure the
* package is installed.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String desiredState;
/**
* A package managed by GooGet.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PackageResourceGooGet googet;
/**
* An MSI package.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PackageResourceMSI msi;
/**
* An rpm package file.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PackageResourceRPM rpm;
/**
* A package managed by YUM.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PackageResourceYUM yum;
/**
* A package managed by Zypper.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PackageResourceZypper zypper;
/**
* A package managed by Apt.
* @return value or {@code null} for none
*/
public PackageResourceAPT getApt() {
return apt;
}
/**
* A package managed by Apt.
* @param apt apt or {@code null} for none
*/
public PackageResource setApt(PackageResourceAPT apt) {
this.apt = apt;
return this;
}
/**
* A deb package file.
* @return value or {@code null} for none
*/
public PackageResourceDeb getDeb() {
return deb;
}
/**
* A deb package file.
* @param deb deb or {@code null} for none
*/
public PackageResource setDeb(PackageResourceDeb deb) {
this.deb = deb;
return this;
}
/**
* The desired_state the agent should maintain for this package. The default is to ensure the
* package is installed.
* @return value or {@code null} for none
*/
public java.lang.String getDesiredState() {
return desiredState;
}
/**
* The desired_state the agent should maintain for this package. The default is to ensure the
* package is installed.
* @param desiredState desiredState or {@code null} for none
*/
public PackageResource setDesiredState(java.lang.String desiredState) {
this.desiredState = desiredState;
return this;
}
/**
* A package managed by GooGet.
* @return value or {@code null} for none
*/
public PackageResourceGooGet getGooget() {
return googet;
}
/**
* A package managed by GooGet.
* @param googet googet or {@code null} for none
*/
public PackageResource setGooget(PackageResourceGooGet googet) {
this.googet = googet;
return this;
}
/**
* An MSI package.
* @return value or {@code null} for none
*/
public PackageResourceMSI getMsi() {
return msi;
}
/**
* An MSI package.
* @param msi msi or {@code null} for none
*/
public PackageResource setMsi(PackageResourceMSI msi) {
this.msi = msi;
return this;
}
/**
* An rpm package file.
* @return value or {@code null} for none
*/
public PackageResourceRPM getRpm() {
return rpm;
}
/**
* An rpm package file.
* @param rpm rpm or {@code null} for none
*/
public PackageResource setRpm(PackageResourceRPM rpm) {
this.rpm = rpm;
return this;
}
/**
* A package managed by YUM.
* @return value or {@code null} for none
*/
public PackageResourceYUM getYum() {
return yum;
}
/**
* A package managed by YUM.
* @param yum yum or {@code null} for none
*/
public PackageResource setYum(PackageResourceYUM yum) {
this.yum = yum;
return this;
}
/**
* A package managed by Zypper.
* @return value or {@code null} for none
*/
public PackageResourceZypper getZypper() {
return zypper;
}
/**
* A package managed by Zypper.
* @param zypper zypper or {@code null} for none
*/
public PackageResource setZypper(PackageResourceZypper zypper) {
this.zypper = zypper;
return this;
}
@Override
public PackageResource set(String fieldName, Object value) {
return (PackageResource) super.set(fieldName, value);
}
@Override
public PackageResource clone() {
return (PackageResource) super.clone();
}
}
| 1,966 |
3,934 | # This sample tests that a descriptor returned by a __getattr__ method
# is not applied as part of a member access expression evaluation.
from typing import Any, Generic, TypeVar
_T = TypeVar("_T")
class A:
pass
class Descriptor:
def __get__(self, instance: object, owner: Any) -> A:
return A()
class CollectionThing(Generic[_T]):
thing: _T
def __getitem__(self, key: str) -> _T:
return self.thing
def __getattr__(self, key: str) -> _T:
return self.thing
c1: CollectionThing[Descriptor] = CollectionThing()
reveal_type(c1["key"], expected_text="Descriptor")
reveal_type(c1.key, expected_text="Descriptor")
| 243 |
602 | package com.stevesouza.jdk;
import java.sql.*;
/**
* Class that does simple jdbc interactions with an embedded hsqldb database. It is used to demontrate jdbc monitoring.
*/
public class JdbcInteraction {
private Connection conn;
public JdbcInteraction() throws ClassNotFoundException {
Class.forName("org.hsqldb.jdbcDriver");
}
public void runQueries() throws Exception {
conn = DriverManager.getConnection("jdbc:hsqldb:.", "sa", "");
queryDataTypes();
testPreparedStatement();
generateSqlException();
conn.close();
}
// just does a simple query with a statement on a known table
private void queryDataTypes() throws SQLException {
String dataTypes = executeQuery("select * from INFORMATION_SCHEMA.SYSTEM_TYPEINFO order by 1 desc");
System.out.println(" ** Hsqldb datatypes: "+dataTypes);
}
// Execute the passed in query. Note resources aren't properly closed which is ok for this demo. Monitoring would show that
// resources are not be closed when an exception is thrown.
private String executeQuery(String query) throws SQLException {
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery(query);
StringBuilder results = new StringBuilder();
while (rs.next()) {
results.append(rs.getObject(1)).append(",");
}
rs.close();
st.close();
return results.toString();
}
// Purposefully throw an exception. Automon monitoring will detect this.
private void generateSqlException() {
try {
// get a query to throw an Exception.
executeQuery("select * from i_do_not_exist");
} catch (Exception e) {
System.out.println(" ** sql exception thrown: "+e);
}
}
private void testPreparedStatement() throws SQLException {
PreparedStatement ps=conn.prepareStatement("select * from INFORMATION_SCHEMA.SYSTEM_TYPEINFO where LOCAL_TYPE_NAME=?");
ps.setString(1, "INTEGER");
ResultSet rs = null;
int LOOP_SIZE = 2;
for (int i=0;i<LOOP_SIZE;i++) {
rs = ps.executeQuery();
}
System.out.println(" ** PreparedStatement query was run "+LOOP_SIZE+" times, and has "+rs.getMetaData().getColumnCount() + " columns");
}
public static void main(String[] args) throws Exception {
JdbcInteraction jdbc = new JdbcInteraction();
jdbc.runQueries();
}
}
| 967 |
354 | /*
* Copyright (C) 2017 <NAME> Software & Consulting (dlsc.com)
*
* 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.calendarfx.view;
import impl.com.calendarfx.view.TimeFieldSkin;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Skin;
import org.controlsfx.control.PropertySheet;
import org.controlsfx.control.PropertySheet.Item;
import java.time.LocalTime;
import java.util.Optional;
/**
* A control for editing a {@link LocalTime}.
*
* <img src="doc-files/time-field.png" alt="Time Field">
*
*/
public class TimeField extends CalendarFXControl {
/**
* Constructs a new field.
*/
public TimeField() {
}
@Override
protected Skin<?> createDefaultSkin() {
return new TimeFieldSkin(this);
}
private final BooleanProperty rollOver = new SimpleBooleanProperty(this,
"rollOver", true);
/**
* Determines if the field for hours will jump from 23 to 0 when the user
* increases the hour value (and vice versa when decreasing). Same for
* minutes.
*
* @return the roll over flag
*/
public final BooleanProperty rollOverProperty() {
return rollOver;
}
/**
* Returns the value of {@link #rollOverProperty()}.
*
* @return true if the fields will roll over
*/
public final boolean isRollOver() {
return rollOver.get();
}
/**
* Sets the value of {@link #rollOverProperty()}.
*
* @param roll if true the fields will roll over (e.g. from 23 to 0 or from 59 to 0).
*/
public final void setRollOver(boolean roll) {
rollOver.set(roll);
}
private final ObjectProperty<LocalTime> value = new SimpleObjectProperty<>(
this, "value", LocalTime.now());
/**
* The current local time value of the field.
*
* @return the local time value
*/
public final ObjectProperty<LocalTime> valueProperty() {
return this.value;
}
/**
* Returns the value of {@link #valueProperty()}.
*
* @return the local time value
*/
public final LocalTime getValue() {
return valueProperty().get();
}
/**
* Sets the value of {@link #valueProperty()}.
*
* @param localTime the new time
*/
public final void setValue(LocalTime localTime) {
valueProperty().set(localTime);
}
private static final String TIME_FIELD_CATEGORY = "Time Field";
/**
* Returns a list of property items that can be shown by the
* {@link PropertySheet} of ControlsFX.
*
* @return the property sheet items
*/
public ObservableList<Item> getPropertySheetItems() {
ObservableList<Item> items = FXCollections.observableArrayList();
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(rollOverProperty());
}
@Override
public void setValue(Object value) {
setRollOver((boolean) value);
}
@Override
public Object getValue() {
return isRollOver();
}
@Override
public Class<?> getType() {
return Boolean.class;
}
@Override
public String getName() {
return "Roll Over";
}
@Override
public String getDescription() {
return "Roll Over";
}
@Override
public String getCategory() {
return TIME_FIELD_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(valueProperty());
}
@Override
public void setValue(Object value) {
TimeField.this.setValue((LocalTime) value);
}
@Override
public Object getValue() {
return TimeField.this.getValue();
}
@Override
public Class<?> getType() {
return LocalTime.class;
}
@Override
public String getName() {
return "Value";
}
@Override
public String getDescription() {
return "Local Time";
}
@Override
public String getCategory() {
return TIME_FIELD_CATEGORY;
}
});
return items;
}
}
| 2,301 |
2,338 | <filename>clang-tools-extra/test/clang-tidy/checkers/bugprone-macro-repeated-side-effects.c<gh_stars>1000+
// RUN: %check_clang_tidy %s bugprone-macro-repeated-side-effects %t
#define badA(x,y) ((x)+((x)+(y))+(y))
void bad(int ret, int a, int b) {
ret = badA(a++, b);
// CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x' are repeated in macro expansion [bugprone-macro-repeated-side-effects]
// CHECK-NOTES: :[[@LINE-4]]:9: note: macro 'badA' defined here
ret = badA(++a, b);
// CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x'
// CHECK-NOTES: :[[@LINE-7]]:9: note: macro 'badA' defined here
ret = badA(a--, b);
// CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x'
// CHECK-NOTES: :[[@LINE-10]]:9: note: macro 'badA' defined here
ret = badA(--a, b);
// CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x'
// CHECK-NOTES: :[[@LINE-13]]:9: note: macro 'badA' defined here
ret = badA(a, b++);
// CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
// CHECK-NOTES: :[[@LINE-16]]:9: note: macro 'badA' defined here
ret = badA(a, ++b);
// CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
// CHECK-NOTES: :[[@LINE-19]]:9: note: macro 'badA' defined here
ret = badA(a, b--);
// CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
// CHECK-NOTES: :[[@LINE-22]]:9: note: macro 'badA' defined here
ret = badA(a, --b);
// CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
// CHECK-NOTES: :[[@LINE-25]]:9: note: macro 'badA' defined here
}
#define MIN(A,B) ((A) < (B) ? (A) : (B)) // single ?:
#define LIMIT(X,A,B) ((X) < (A) ? (A) : ((X) > (B) ? (B) : (X))) // two ?:
void question(int x) {
MIN(x++, 12);
// CHECK-NOTES: :[[@LINE-1]]:7: warning: side effects in the 1st macro argument 'A'
// CHECK-NOTES: :[[@LINE-5]]:9: note: macro 'MIN' defined here
MIN(34, x++);
// CHECK-NOTES: :[[@LINE-1]]:11: warning: side effects in the 2nd macro argument 'B'
// CHECK-NOTES: :[[@LINE-8]]:9: note: macro 'MIN' defined here
LIMIT(x++, 0, 100);
// CHECK-NOTES: :[[@LINE-1]]:9: warning: side effects in the 1st macro argument 'X'
// CHECK-NOTES: :[[@LINE-10]]:9: note: macro 'LIMIT' defined here
LIMIT(20, x++, 100);
// CHECK-NOTES: :[[@LINE-1]]:13: warning: side effects in the 2nd macro argument 'A'
// CHECK-NOTES: :[[@LINE-13]]:9: note: macro 'LIMIT' defined here
LIMIT(20, 0, x++);
// CHECK-NOTES: :[[@LINE-1]]:16: warning: side effects in the 3rd macro argument 'B'
// CHECK-NOTES: :[[@LINE-16]]:9: note: macro 'LIMIT' defined here
}
// False positive: Repeated side effects is intentional.
// It is hard to know when it's done by intention so right now we warn.
#define UNROLL(A) {A A}
void fp1(int i) {
UNROLL({ i++; });
// CHECK-NOTES: :[[@LINE-1]]:10: warning: side effects in the 1st macro argument 'A'
// CHECK-NOTES: :[[@LINE-4]]:9: note: macro 'UNROLL' defined here
}
// Do not produce a false positive on a strchr() macro. Explanation; Currently the '?'
// triggers the test to bail out, because it cannot evaluate __builtin_constant_p(c).
# define strchrs(s, c) \
(__extension__ (__builtin_constant_p (c) && !__builtin_constant_p (s) \
&& (c) == '\0' \
? (char *) __rawmemchr (s, c) \
: __builtin_strchr (s, c)))
char* __rawmemchr(char* a, char b) {
return a;
}
void pass(char* pstr, char ch) {
strchrs(pstr, ch++); // No error.
}
// Check large arguments (t=20, u=21).
#define largeA(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, x, y, z) \
((a) + (a) + (b) + (b) + (c) + (c) + (d) + (d) + (e) + (e) + (f) + (f) + (g) + (g) + \
(h) + (h) + (i) + (i) + (j) + (j) + (k) + (k) + (l) + (l) + (m) + (m) + (n) + (n) + \
(o) + (o) + (p) + (p) + (q) + (q) + (r) + (r) + (s) + (s) + (t) + (t) + (u) + (u) + \
(v) + (v) + (x) + (x) + (y) + (y) + (z) + (z))
void large(int a) {
largeA(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a++, 0, 0, 0, 0, 0, 0);
// CHECK-NOTES: :[[@LINE-1]]:64: warning: side effects in the 19th macro argument 's'
// CHECK-NOTES: :[[@LINE-8]]:9: note: macro 'largeA' defined here
largeA(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a++, 0, 0, 0, 0, 0);
// CHECK-NOTES: :[[@LINE-1]]:67: warning: side effects in the 20th macro argument 't'
// CHECK-NOTES: :[[@LINE-11]]:9: note: macro 'largeA' defined here
largeA(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a++, 0, 0, 0, 0);
// CHECK-NOTES: :[[@LINE-1]]:70: warning: side effects in the 21st macro argument 'u'
// CHECK-NOTES: :[[@LINE-14]]:9: note: macro 'largeA' defined here
}
// Passing macro argument as argument to __builtin_constant_p and macros.
#define builtinbad(x) (__builtin_constant_p(x) + (x) + (x))
#define builtingood1(x) (__builtin_constant_p(x) + (x))
#define builtingood2(x) ((__builtin_constant_p(x) && (x)) || (x))
#define macrobad(x) (builtingood1(x) + (x) + (x))
#define macrogood(x) (builtingood1(x) + (x))
void builtins(int ret, int a) {
ret += builtinbad(a++);
// CHECK-NOTES: :[[@LINE-1]]:21: warning: side effects in the 1st macro argument 'x'
// CHECK-NOTES: :[[@LINE-8]]:9: note: macro 'builtinbad' defined here
ret += builtingood1(a++);
ret += builtingood2(a++);
ret += macrobad(a++);
// CHECK-NOTES: :[[@LINE-1]]:19: warning: side effects in the 1st macro argument 'x'
// CHECK-NOTES: :[[@LINE-12]]:9: note: macro 'macrobad' defined here
ret += macrogood(a++);
}
// Bail out for conditionals.
#define condB(x,y) if(x) {x=y;} else {x=y + 1;}
void conditionals(int a, int b)
{
condB(a, b++);
}
void log(const char *s, int v);
#define LOG(val) log(#val, (val))
void test_log(int a) {
LOG(a++);
}
| 2,661 |
2,441 | <reponame>shawwn/cpython<filename>Lib/idlelib/idle_test/test_pyshell.py
"Test pyshell, coverage 12%."
# Plus coverage of test_warning. Was 20% with test_openshell.
from idlelib import pyshell
import unittest
from test.support import requires
from tkinter import Tk
class FunctionTest(unittest.TestCase):
# Test stand-alone module level non-gui functions.
def test_restart_line_wide(self):
eq = self.assertEqual
for file, mul, extra in (('', 22, ''), ('finame', 21, '=')):
width = 60
bar = mul * '='
with self.subTest(file=file, bar=bar):
file = file or 'Shell'
line = pyshell.restart_line(width, file)
eq(len(line), width)
eq(line, f"{bar+extra} RESTART: {file} {bar}")
def test_restart_line_narrow(self):
expect, taglen = "= RESTART: Shell", 16
for width in (taglen-1, taglen, taglen+1):
with self.subTest(width=width):
self.assertEqual(pyshell.restart_line(width, ''), expect)
self.assertEqual(pyshell.restart_line(taglen+2, ''), expect+' =')
class PyShellFileListTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
@classmethod
def tearDownClass(cls):
#cls.root.update_idletasks()
## for id in cls.root.tk.call('after', 'info'):
## cls.root.after_cancel(id) # Need for EditorWindow.
cls.root.destroy()
del cls.root
def test_init(self):
psfl = pyshell.PyShellFileList(self.root)
self.assertEqual(psfl.EditorWindow, pyshell.PyShellEditorWindow)
self.assertIsNone(psfl.pyshell)
# The following sometimes causes 'invalid command name "109734456recolorize"'.
# Uncommenting after_cancel above prevents this, but results in
# TclError: bad window path name ".!listedtoplevel.!frame.text"
# which is normally prevented by after_cancel.
## def test_openshell(self):
## pyshell.use_subprocess = False
## ps = pyshell.PyShellFileList(self.root).open_shell()
## self.assertIsInstance(ps, pyshell.PyShell)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 987 |
3,428 | <reponame>ghalimi/stdlib<filename>lib/node_modules/@stdlib/datasets/spam-assassin/data/spam-1/00021.effe1449462a9d7ad7af0f1c94b1a237.json<gh_stars>1000+
{"id":"00021","group":"spam-1","checksum":{"type":"MD5","value":"effe1449462a9d7ad7af0f1c94b1a237"},"text":"From <EMAIL> Fri Aug 23 11:08:03 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: zzzz<EMAIL>.spamassassin.taint.org\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.spamassassin.taint.org (Postfix) with ESMTP id D843A4416F\n\tfor <zzzz@localhost>; Fri, 23 Aug 2002 06:06:37 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor zzzz@localhost (single-drop); Fri, 23 Aug 2002 11:06:37 +0100 (IST)\nReceived: from lugh.tuatha.org (<EMAIL> [194.125.145.45]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g7N7fDZ14920 for\n <<EMAIL>>; Fri, 23 Aug 2002 08:41:13 +0100\nReceived: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id IAA13857; Fri, 23 Aug 2002 08:38:52 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host root@localhost [127.0.0.1]\n claimed to be lugh\nReceived: from relay.dub-t3-1.nwcgroup.com\n (<EMAIL> [172.16.58.36]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id IAA13820 for <<EMAIL>>; Fri,\n 23 Aug 2002 08:38:43 +0100\nReceived: from mail.com (unknown [64.86.155.148]) by\n relay.dub-t3-1.nwcgroup.com (Postfix) with SMTP id 1AE6470047 for\n <<EMAIL>>; Fri, 23 Aug 2002 08:38:15 +0100 (IST)\nFrom: \"<NAME>\" <<EMAIL>>\nTo: <<EMAIL>>\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"ISO-8859-1\"\nDate: Fri, 23 Aug 2002 20:41:55 +0100\nReply-To: \"<NAME>\" <<EMAIL>>\nMessage-Id: <<EMAIL>073815.<EMAIL>>\nSubject: [ILUG] BUSINESS\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]\nContent-Transfer-Encoding: 8bit\n\nCENTRAL BANK OF NIGERIA\nFOREIGN REMITTANCE DEPT.\nTINUBU SQUARE, LAGOS NIGERIA\nEMAIL-<EMAIL>\n23TH OF August 2002\n\nATTN:PRESIDENT/CEO\n\n\n STRICTLY PRIVATE BUSINESS PROPOSAL\nI am <NAME>, the bills and exchange Director at the\nForeignRemittance Department of the Central Bank of Nigeria. I am \nwritingyou\nthis letter to ask for your support and cooperation to carrying thisbusiness\nopportunity in my department. We discovered abandoned the sumof\nUS$37,400,000.00 (Thirty seven million four hundred thousand unitedstates\ndollars) in an account that belong to one of our foreign customers,an\nAmerican\nlate Engr. John Creek (Junior) an oil merchant with the federal government\nof\nNigeria who died along with his entire family of a wifeand two children in\nKenya Airbus (A310-300) flight KQ430 in November2000.\n\nSince we heard of his death, we have been expecting his next of kin tocome\nover\nand put claims for his money as the heir, because we cannotrelease the fund\nfrom his account unless someone applies for claims asthe next of kin to the\ndeceased as indicated in our banking guidelines. Unfortunately, neither\ntheir\nfamily member nor distant relative hasappeared to claim the said fund. Upon\nthis discovery, I and other officialsin my department have agreed to make\nbusiness with you release the totalamount into your account as the heir of\nthe\nfund since no one came forit or discovered either maintained account with\nour\nbank, other wisethe fund will be returned to the bank treasury as unclaimed\nfund.\n\nWe have agreed that our ratio of sharing will be as stated thus: 30%for\nyou as\nforeign partner and 70% for us the officials in my department.\n\nUpon the successful completion of this transfer, my colleague and I\nwillcome to\nyour country and mind our share. It is from our 60% we intendto import\ncomputer\naccessories into my country as way of recycling thefund. To commence this\ntransaction we require you to immediately indicateyour interest by calling\nme\nor sending me a fax immediately on the aboveTelefax # and enclose your\nprivate\ncontact Telephone #, Fax #, full nameand address and your designated\nbanking co-\n ordinates to enable us fileletter of claim to the appropriate department\nfor\nnecessary approvalsbefore the transfer can be made.\n\nNote also, this transaction must be kept strictly confidential becauseof its\nnature.\n\nNB: Please remember to give me your Phone and Fax No\n\n<NAME> Abu\n\n-- \nIrish Linux Users' Group: <EMAIL>\nhttp://www.linux.ie/mailman/listinfo/ilug for (un)subscription information.\nList maintainer: <EMAIL>\n\n"} | 1,626 |
338 | <reponame>vu-luong/ezyfox-server
package com.tvd12.ezyfoxserver.nio.testing.socket;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.annotations.Test;
import com.tvd12.ezyfox.codec.EzyByteToObjectDecoder;
import com.tvd12.ezyfox.codec.EzyMessage;
import com.tvd12.ezyfox.codec.EzyMessageHeader;
import com.tvd12.ezyfox.codec.EzySimpleMessage;
import com.tvd12.ezyfox.codec.EzySimpleMessageHeader;
import com.tvd12.ezyfox.collect.Sets;
import com.tvd12.ezyfox.concurrent.EzyExecutors;
import com.tvd12.ezyfox.factory.EzyEntityFactory;
import com.tvd12.ezyfoxserver.EzySimpleServer;
import com.tvd12.ezyfoxserver.codec.EzyCodecFactory;
import com.tvd12.ezyfoxserver.constant.EzyCommand;
import com.tvd12.ezyfoxserver.constant.EzyConnectionType;
import com.tvd12.ezyfoxserver.context.EzySimpleServerContext;
import com.tvd12.ezyfoxserver.nio.builder.impl.EzyHandlerGroupBuilderFactoryImpl;
import com.tvd12.ezyfoxserver.nio.factory.EzyHandlerGroupBuilderFactory;
import com.tvd12.ezyfoxserver.nio.socket.EzyNioSocketAcceptor;
import com.tvd12.ezyfoxserver.nio.socket.EzyNioSocketChannel;
import com.tvd12.ezyfoxserver.nio.socket.EzyNioSocketReader;
import com.tvd12.ezyfoxserver.nio.socket.EzySocketDataReceiver;
import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager;
import com.tvd12.ezyfoxserver.nio.wrapper.EzyNioSessionManager;
import com.tvd12.ezyfoxserver.nio.wrapper.impl.EzyHandlerGroupManagerImpl;
import com.tvd12.ezyfoxserver.nio.wrapper.impl.EzyNioSessionManagerImpl;
import com.tvd12.ezyfoxserver.service.impl.EzySimpleSessionTokenGenerator;
import com.tvd12.ezyfoxserver.setting.EzySimpleSessionManagementSetting;
import com.tvd12.ezyfoxserver.setting.EzySimpleSettings;
import com.tvd12.ezyfoxserver.setting.EzySimpleStreamingSetting;
import com.tvd12.ezyfoxserver.socket.EzyBlockingSessionTicketsQueue;
import com.tvd12.ezyfoxserver.socket.EzyBlockingSocketDisconnectionQueue;
import com.tvd12.ezyfoxserver.socket.EzyBlockingSocketStreamQueue;
import com.tvd12.ezyfoxserver.socket.EzyChannel;
import com.tvd12.ezyfoxserver.socket.EzySessionTicketsQueue;
import com.tvd12.ezyfoxserver.socket.EzySessionTicketsRequestQueues;
import com.tvd12.ezyfoxserver.socket.EzySocketDisconnectionQueue;
import com.tvd12.ezyfoxserver.socket.EzySocketStreamQueue;
import com.tvd12.ezyfoxserver.statistics.EzySimpleStatistics;
import com.tvd12.ezyfoxserver.statistics.EzyStatistics;
import com.tvd12.test.base.BaseTest;
public class EzyNioSocketReaderTest extends BaseTest {
@Test
public void test() throws Exception {
EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager();
EzySocketDataReceiver socketDataReceiver = EzySocketDataReceiver.builder()
.threadPoolSize(1)
.handlerGroupManager(handlerGroupManager)
.build();
Selector ownSelector = spy(ExSelector.class);
when(ownSelector.selectNow()).thenReturn(1);
SelectionKey selectionKey1 = spy(ExSelectionKey.class);
SelectionKey selectionKey2 = spy(ExSelectionKey.class);
SelectionKey selectionKey3 = spy(ExSelectionKey.class);
SelectionKey selectionKey4 = spy(ExSelectionKey.class);
SelectionKey selectionKey5 = spy(ExSelectionKey.class);
when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet(
selectionKey1,
selectionKey2,
selectionKey3, selectionKey4, selectionKey5));
when(selectionKey1.isValid()).thenReturn(true);
when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_READ);
when(selectionKey2.isValid()).thenReturn(true);
when(selectionKey2.readyOps()).thenReturn(SelectionKey.OP_WRITE);
when(selectionKey3.isValid()).thenReturn(false);
when(selectionKey4.isValid()).thenReturn(true);
when(selectionKey4.readyOps()).thenReturn(SelectionKey.OP_READ);
when(selectionKey5.isValid()).thenReturn(true);
when(selectionKey5.readyOps()).thenReturn(SelectionKey.OP_READ);
SocketChannel socketChannel1 = mock(SocketChannel.class);
EzyChannel channel1 = new EzyNioSocketChannel(socketChannel1);
handlerGroupManager.newHandlerGroup(channel1, EzyConnectionType.SOCKET);
when(selectionKey1.channel()).thenReturn(socketChannel1);
when(socketChannel1.isConnected()).thenReturn(true);
when(socketChannel1.read(any(ByteBuffer.class))).then(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
ByteBuffer buffer = invocation.getArgumentAt(0, ByteBuffer.class);
buffer.put("hello".getBytes());
return "hello".length();
}
});
SocketChannel socketChannel4 = mock(SocketChannel.class);
when(selectionKey4.channel()).thenReturn(socketChannel4);
SocketChannel socketChannel5 = spy(ExSocketChannel.class);
EzyChannel channel5 = new EzyNioSocketChannel(socketChannel5);
when(selectionKey5.channel()).thenReturn(socketChannel5);
doNothing().when(socketChannel5).close();
handlerGroupManager.newHandlerGroup(channel5, EzyConnectionType.SOCKET);
when(selectionKey5.channel()).thenReturn(socketChannel5);
when(socketChannel5.isConnected()).thenReturn(true);
when(socketChannel5.read(any(ByteBuffer.class))).then(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
return -1;
}
});
EzyNioSocketAcceptor socketAcceptor = new EzyNioSocketAcceptor();
socketAcceptor.setReadSelector(ownSelector);
socketAcceptor.setHandlerGroupManager(handlerGroupManager);
socketAcceptor.setAcceptableConnections(new ArrayList<>());
EzyNioSocketReader socketReader = new EzyNioSocketReader();
socketReader.setOwnSelector(ownSelector);
socketReader.setAcceptableConnectionsHandler(socketAcceptor);
socketReader.setSocketDataReceiver(socketDataReceiver);
socketReader.handleEvent();
}
@Test
public void testExceptionCase() throws Exception {
EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager();
EzySocketDataReceiver socketDataReceiver = EzySocketDataReceiver.builder()
.threadPoolSize(1)
.handlerGroupManager(handlerGroupManager)
.build();
Selector ownSelector = spy(ExSelector.class);
when(ownSelector.selectNow()).thenReturn(1);
SelectionKey selectionKey1 = spy(ExSelectionKey.class);
when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey1));
when(selectionKey1.isValid()).thenReturn(true);
when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_READ);
SocketChannel socketChannel1 = mock(SocketChannel.class);
EzyChannel channel1 = new EzyNioSocketChannel(socketChannel1);
handlerGroupManager.newHandlerGroup(channel1, EzyConnectionType.SOCKET);
when(selectionKey1.channel()).thenReturn(socketChannel1);
when(socketChannel1.isConnected()).thenReturn(true);
when(socketChannel1.read(any(ByteBuffer.class))).then(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
throw new IllegalStateException("server maintain");
}
});
EzyNioSocketAcceptor socketAcceptor = new EzyNioSocketAcceptor();
socketAcceptor.setReadSelector(ownSelector);
socketAcceptor.setHandlerGroupManager(handlerGroupManager);
socketAcceptor.setAcceptableConnections(new ArrayList<>());
EzyNioSocketReader socketReader = new EzyNioSocketReader();
socketReader.setOwnSelector(ownSelector);
socketReader.setAcceptableConnectionsHandler(socketAcceptor);
socketReader.setSocketDataReceiver(socketDataReceiver);
socketReader.handleEvent();
}
private EzyHandlerGroupManager newHandlerGroupManager() {
EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder()
.maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond())
.tokenGenerator(new EzySimpleSessionTokenGenerator())
.build();
ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder();
EzyCodecFactory codecFactory = mock(EzyCodecFactory.class);
when(codecFactory.newDecoder(any())).thenReturn(decoder);
ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats");
EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue();
EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue();
EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues();
EzySimpleSettings settings = new EzySimpleSettings();
EzySimpleStreamingSetting streaming = settings.getStreaming();
streaming.setEnable(true);
EzySimpleServer server = new EzySimpleServer();
server.setSettings(settings);
server.setSessionManager(sessionManager);
EzySimpleServerContext serverContext = new EzySimpleServerContext();
serverContext.setServer(server);
serverContext.init();
EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue();
EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue();
EzyStatistics statistics = new EzySimpleStatistics();
EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder()
.statistics(statistics)
.statsThreadPool(statsThreadPool)
.streamQueue(streamQueue)
.disconnectionQueue(disconnectionQueue)
.codecFactory(codecFactory)
.serverContext(serverContext)
.socketSessionTicketsQueue(socketSessionTicketsQueue)
.webSocketSessionTicketsQueue(webSocketSessionTicketsQueue)
.sessionTicketsRequestQueues(sessionTicketsRequestQueues)
.build();
EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder()
.handlerGroupBuilderFactory(handlerGroupBuilderFactory)
.build();
return handlerGroupManager;
}
public static abstract class ExSocketChannel extends SocketChannel {
public ExSocketChannel() {
super(SelectorProvider.provider());
}
}
public static abstract class ExSelector extends Selector {
public ExSelector() {}
}
public static abstract class ExSelectionKey extends SelectionKey {
public ExSelectionKey() {}
}
public static class ExEzyByteToObjectDecoder implements EzyByteToObjectDecoder {
@Override
public void reset() {}
@Override
public Object decode(EzyMessage message) throws Exception {
return EzyEntityFactory.newArrayBuilder()
.append(EzyCommand.PING.getId())
.build();
}
@Override
public void decode(ByteBuffer bytes, Queue<EzyMessage> queue) throws Exception {
EzyMessageHeader header = new EzySimpleMessageHeader(false, false, false, false, false, false);
byte[] content = new byte[bytes.remaining()];
bytes.get(content);
EzyMessage message = new EzySimpleMessage(header, content, content.length);
queue.add(message);
}
}
}
| 3,769 |
12,718 | /**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#ifndef W32KAPI
#define W32KAPI
#endif
#define TRACE_SURFACE_ALLOCS (DBG || 0)
#define FL_UFI_PRIVATEFONT 1
#define FL_UFI_DESIGNVECTOR_PFF 2
#define FL_UFI_MEMORYFONT 4
W32KAPI WINBOOL WINAPI NtGdiInit();
W32KAPI int WINAPI NtGdiSetDIBitsToDeviceInternal(HDC hdcDest,int xDst,int yDst,DWORD cx,DWORD cy,int xSrc,int ySrc,DWORD iStartScan,DWORD cNumScan,LPBYTE pInitBits,LPBITMAPINFO pbmi,DWORD iUsage,UINT cjMaxBits,UINT cjMaxInfo,WINBOOL bTransformCoordinates,HANDLE hcmXform);
W32KAPI WINBOOL WINAPI NtGdiGetFontResourceInfoInternalW(LPWSTR pwszFiles,ULONG cwc,ULONG cFiles,UINT cjIn,LPDWORD pdwBytes,LPVOID pvBuf,DWORD iType);
W32KAPI DWORD WINAPI NtGdiGetGlyphIndicesW(HDC hdc,LPWSTR pwc,int cwc,LPWORD pgi,DWORD iMode);
W32KAPI DWORD WINAPI NtGdiGetGlyphIndicesWInternal(HDC hdc,LPWSTR pwc,int cwc,LPWORD pgi,DWORD iMode,WINBOOL bSubset);
W32KAPI HPALETTE WINAPI NtGdiCreatePaletteInternal(LPLOGPALETTE pLogPal,UINT cEntries);
W32KAPI WINBOOL WINAPI NtGdiArcInternal(ARCTYPE arctype,HDC hdc,int x1,int y1,int x2,int y2,int x3,int y3,int x4,int y4);
W32KAPI int WINAPI NtGdiStretchDIBitsInternal(HDC hdc,int xDst,int yDst,int cxDst,int cyDst,int xSrc,int ySrc,int cxSrc,int cySrc,LPBYTE pjInit,LPBITMAPINFO pbmi,DWORD dwUsage,DWORD dwRop4,UINT cjMaxInfo,UINT cjMaxBits,HANDLE hcmXform);
W32KAPI ULONG WINAPI NtGdiGetOutlineTextMetricsInternalW(HDC hdc,ULONG cjotm,OUTLINETEXTMETRICW *potmw,TMDIFF *ptmd);
W32KAPI WINBOOL WINAPI NtGdiGetAndSetDCDword(HDC hdc,UINT u,DWORD dwIn,DWORD *pdwResult);
W32KAPI HANDLE WINAPI NtGdiGetDCObject(HDC hdc,int itype);
W32KAPI HDC WINAPI NtGdiGetDCforBitmap(HBITMAP hsurf);
W32KAPI WINBOOL WINAPI NtGdiGetMonitorID(HDC hdc,DWORD dwSize,LPWSTR pszMonitorID);
W32KAPI INT WINAPI NtGdiGetLinkedUFIs(HDC hdc,PUNIVERSAL_FONT_ID pufiLinkedUFIs,INT BufferSize);
W32KAPI WINBOOL WINAPI NtGdiSetLinkedUFIs(HDC hdc,PUNIVERSAL_FONT_ID pufiLinks,ULONG uNumUFIs);
W32KAPI WINBOOL WINAPI NtGdiGetUFI(HDC hdc,PUNIVERSAL_FONT_ID pufi,DESIGNVECTOR *pdv,ULONG *pcjDV,ULONG *pulBaseCheckSum,FLONG *pfl);
W32KAPI WINBOOL WINAPI NtGdiForceUFIMapping(HDC hdc,PUNIVERSAL_FONT_ID pufi);
W32KAPI WINBOOL WINAPI NtGdiGetUFIPathname(PUNIVERSAL_FONT_ID pufi,ULONG *pcwc,LPWSTR pwszPathname,ULONG *pcNumFiles,FLONG fl,WINBOOL *pbMemFont,ULONG *pcjView,PVOID pvView,WINBOOL *pbTTC,ULONG *piTTC);
W32KAPI WINBOOL WINAPI NtGdiAddRemoteFontToDC(HDC hdc,PVOID pvBuffer,ULONG cjBuffer,PUNIVERSAL_FONT_ID pufi);
W32KAPI HANDLE WINAPI NtGdiAddFontMemResourceEx(PVOID pvBuffer,DWORD cjBuffer,DESIGNVECTOR *pdv,ULONG cjDV,DWORD *pNumFonts);
W32KAPI WINBOOL WINAPI NtGdiRemoveFontMemResourceEx(HANDLE hMMFont);
W32KAPI WINBOOL WINAPI NtGdiUnmapMemFont(PVOID pvView);
W32KAPI WINBOOL WINAPI NtGdiRemoveMergeFont(HDC hdc,UNIVERSAL_FONT_ID *pufi);
W32KAPI WINBOOL WINAPI NtGdiAnyLinkedFonts();
W32KAPI WINBOOL WINAPI NtGdiGetEmbUFI(HDC hdc,PUNIVERSAL_FONT_ID pufi,DESIGNVECTOR *pdv,ULONG *pcjDV,ULONG *pulBaseCheckSum,FLONG *pfl,KERNEL_PVOID *embFontID);
W32KAPI ULONG WINAPI NtGdiGetEmbedFonts();
W32KAPI WINBOOL WINAPI NtGdiChangeGhostFont(KERNEL_PVOID *pfontID,WINBOOL bLoad);
W32KAPI WINBOOL WINAPI NtGdiAddEmbFontToDC(HDC hdc,VOID **pFontID);
W32KAPI WINBOOL WINAPI NtGdiFontIsLinked(HDC hdc);
W32KAPI ULONG_PTR WINAPI NtGdiPolyPolyDraw(HDC hdc,PPOINT ppt,PULONG pcpt,ULONG ccpt,int iFunc);
W32KAPI LONG WINAPI NtGdiDoPalette(HPALETTE hpal,WORD iStart,WORD cEntries,PALETTEENTRY *pPalEntries,DWORD iFunc,WINBOOL bInbound);
W32KAPI WINBOOL WINAPI NtGdiComputeXformCoefficients(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiGetWidthTable(HDC hdc,ULONG cSpecial,WCHAR *pwc,ULONG cwc,USHORT *psWidth,WIDTHDATA *pwd,FLONG *pflInfo);
W32KAPI int WINAPI NtGdiDescribePixelFormat(HDC hdc,int ipfd,UINT cjpfd,PPIXELFORMATDESCRIPTOR ppfd);
W32KAPI WINBOOL WINAPI NtGdiSetPixelFormat(HDC hdc,int ipfd);
W32KAPI WINBOOL WINAPI NtGdiSwapBuffers(HDC hdc);
W32KAPI int WINAPI NtGdiSetupPublicCFONT(HDC hdc,HFONT hf,ULONG ulAve);
W32KAPI DWORD WINAPI NtGdiDxgGenericThunk(ULONG_PTR ulIndex,ULONG_PTR ulHandle,SIZE_T *pdwSizeOfPtr1,PVOID pvPtr1,SIZE_T *pdwSizeOfPtr2,PVOID pvPtr2);
W32KAPI DWORD WINAPI NtGdiDdAddAttachedSurface(HANDLE hSurface,HANDLE hSurfaceAttached,PDD_ADDATTACHEDSURFACEDATA puAddAttachedSurfaceData);
W32KAPI WINBOOL WINAPI NtGdiDdAttachSurface(HANDLE hSurfaceFrom,HANDLE hSurfaceTo);
W32KAPI DWORD WINAPI NtGdiDdBlt(HANDLE hSurfaceDest,HANDLE hSurfaceSrc,PDD_BLTDATA puBltData);
W32KAPI DWORD WINAPI NtGdiDdCanCreateSurface(HANDLE hDirectDraw,PDD_CANCREATESURFACEDATA puCanCreateSurfaceData);
W32KAPI DWORD WINAPI NtGdiDdColorControl(HANDLE hSurface,PDD_COLORCONTROLDATA puColorControlData);
W32KAPI HANDLE WINAPI NtGdiDdCreateDirectDrawObject(HDC hdc);
W32KAPI DWORD WINAPI NtGdiDdCreateSurface(HANDLE hDirectDraw,HANDLE *hSurface,DDSURFACEDESC *puSurfaceDescription,DD_SURFACE_GLOBAL *puSurfaceGlobalData,DD_SURFACE_LOCAL *puSurfaceLocalData,DD_SURFACE_MORE *puSurfaceMoreData,DD_CREATESURFACEDATA *puCreateSurfaceData,HANDLE *puhSurface);
W32KAPI HANDLE WINAPI NtGdiDdCreateSurfaceObject(HANDLE hDirectDrawLocal,HANDLE hSurface,PDD_SURFACE_LOCAL puSurfaceLocal,PDD_SURFACE_MORE puSurfaceMore,PDD_SURFACE_GLOBAL puSurfaceGlobal,WINBOOL bComplete);
W32KAPI WINBOOL WINAPI NtGdiDdDeleteSurfaceObject(HANDLE hSurface);
W32KAPI WINBOOL WINAPI NtGdiDdDeleteDirectDrawObject(HANDLE hDirectDrawLocal);
W32KAPI DWORD WINAPI NtGdiDdDestroySurface(HANDLE hSurface,WINBOOL bRealDestroy);
W32KAPI DWORD WINAPI NtGdiDdFlip(HANDLE hSurfaceCurrent,HANDLE hSurfaceTarget,HANDLE hSurfaceCurrentLeft,HANDLE hSurfaceTargetLeft,PDD_FLIPDATA puFlipData);
W32KAPI DWORD WINAPI NtGdiDdGetAvailDriverMemory(HANDLE hDirectDraw,PDD_GETAVAILDRIVERMEMORYDATA puGetAvailDriverMemoryData);
W32KAPI DWORD WINAPI NtGdiDdGetBltStatus(HANDLE hSurface,PDD_GETBLTSTATUSDATA puGetBltStatusData);
W32KAPI HDC WINAPI NtGdiDdGetDC(HANDLE hSurface,PALETTEENTRY *puColorTable);
W32KAPI DWORD WINAPI NtGdiDdGetDriverInfo(HANDLE hDirectDraw,PDD_GETDRIVERINFODATA puGetDriverInfoData);
W32KAPI DWORD WINAPI NtGdiDdGetFlipStatus(HANDLE hSurface,PDD_GETFLIPSTATUSDATA puGetFlipStatusData);
W32KAPI DWORD WINAPI NtGdiDdGetScanLine(HANDLE hDirectDraw,PDD_GETSCANLINEDATA puGetScanLineData);
W32KAPI DWORD WINAPI NtGdiDdSetExclusiveMode(HANDLE hDirectDraw,PDD_SETEXCLUSIVEMODEDATA puSetExclusiveModeData);
W32KAPI DWORD WINAPI NtGdiDdFlipToGDISurface(HANDLE hDirectDraw,PDD_FLIPTOGDISURFACEDATA puFlipToGDISurfaceData);
W32KAPI DWORD WINAPI NtGdiDdLock(HANDLE hSurface,PDD_LOCKDATA puLockData,HDC hdcClip);
W32KAPI WINBOOL WINAPI NtGdiDdQueryDirectDrawObject(HANDLE hDirectDrawLocal,PDD_HALINFO pHalInfo,DWORD *pCallBackFlags,LPD3DNTHAL_CALLBACKS puD3dCallbacks,LPD3DNTHAL_GLOBALDRIVERDATA puD3dDriverData,PDD_D3DBUFCALLBACKS puD3dBufferCallbacks,LPDDSURFACEDESC puD3dTextureFormats,DWORD *puNumHeaps,VIDEOMEMORY *puvmList,DWORD *puNumFourCC,DWORD *puFourCC);
W32KAPI WINBOOL WINAPI NtGdiDdReenableDirectDrawObject(HANDLE hDirectDrawLocal,WINBOOL *pubNewMode);
W32KAPI WINBOOL WINAPI NtGdiDdReleaseDC(HANDLE hSurface);
W32KAPI WINBOOL WINAPI NtGdiDdResetVisrgn(HANDLE hSurface,HWND hwnd);
W32KAPI DWORD WINAPI NtGdiDdSetColorKey(HANDLE hSurface,PDD_SETCOLORKEYDATA puSetColorKeyData);
W32KAPI DWORD WINAPI NtGdiDdSetOverlayPosition(HANDLE hSurfaceSource,HANDLE hSurfaceDestination,PDD_SETOVERLAYPOSITIONDATA puSetOverlayPositionData);
W32KAPI VOID WINAPI NtGdiDdUnattachSurface(HANDLE hSurface,HANDLE hSurfaceAttached);
W32KAPI DWORD WINAPI NtGdiDdUnlock(HANDLE hSurface,PDD_UNLOCKDATA puUnlockData);
W32KAPI DWORD WINAPI NtGdiDdUpdateOverlay(HANDLE hSurfaceDestination,HANDLE hSurfaceSource,PDD_UPDATEOVERLAYDATA puUpdateOverlayData);
W32KAPI DWORD WINAPI NtGdiDdWaitForVerticalBlank(HANDLE hDirectDraw,PDD_WAITFORVERTICALBLANKDATA puWaitForVerticalBlankData);
W32KAPI HANDLE WINAPI NtGdiDdGetDxHandle(HANDLE hDirectDraw,HANDLE hSurface,WINBOOL bRelease);
W32KAPI WINBOOL WINAPI NtGdiDdSetGammaRamp(HANDLE hDirectDraw,HDC hdc,LPVOID lpGammaRamp);
W32KAPI DWORD WINAPI NtGdiDdLockD3D(HANDLE hSurface,PDD_LOCKDATA puLockData);
W32KAPI DWORD WINAPI NtGdiDdUnlockD3D(HANDLE hSurface,PDD_UNLOCKDATA puUnlockData);
W32KAPI DWORD WINAPI NtGdiDdCreateD3DBuffer(HANDLE hDirectDraw,HANDLE *hSurface,DDSURFACEDESC *puSurfaceDescription,DD_SURFACE_GLOBAL *puSurfaceGlobalData,DD_SURFACE_LOCAL *puSurfaceLocalData,DD_SURFACE_MORE *puSurfaceMoreData,DD_CREATESURFACEDATA *puCreateSurfaceData,HANDLE *puhSurface);
W32KAPI DWORD WINAPI NtGdiDdCanCreateD3DBuffer(HANDLE hDirectDraw,PDD_CANCREATESURFACEDATA puCanCreateSurfaceData);
W32KAPI DWORD WINAPI NtGdiDdDestroyD3DBuffer(HANDLE hSurface);
W32KAPI DWORD WINAPI NtGdiD3dContextCreate(HANDLE hDirectDrawLocal,HANDLE hSurfColor,HANDLE hSurfZ,D3DNTHAL_CONTEXTCREATEI *pdcci);
W32KAPI DWORD WINAPI NtGdiD3dContextDestroy(LPD3DNTHAL_CONTEXTDESTROYDATA);
W32KAPI DWORD WINAPI NtGdiD3dContextDestroyAll(LPD3DNTHAL_CONTEXTDESTROYALLDATA pdcdad);
W32KAPI DWORD WINAPI NtGdiD3dValidateTextureStageState(LPD3DNTHAL_VALIDATETEXTURESTAGESTATEDATA pData);
W32KAPI DWORD WINAPI NtGdiD3dDrawPrimitives2(HANDLE hCmdBuf,HANDLE hVBuf,LPD3DNTHAL_DRAWPRIMITIVES2DATA pded,FLATPTR *pfpVidMemCmd,DWORD *pdwSizeCmd,FLATPTR *pfpVidMemVtx,DWORD *pdwSizeVtx);
W32KAPI DWORD WINAPI NtGdiDdGetDriverState(PDD_GETDRIVERSTATEDATA pdata);
W32KAPI DWORD WINAPI NtGdiDdCreateSurfaceEx(HANDLE hDirectDraw,HANDLE hSurface,DWORD dwSurfaceHandle);
W32KAPI DWORD WINAPI NtGdiDvpCanCreateVideoPort(HANDLE hDirectDraw,PDD_CANCREATEVPORTDATA puCanCreateVPortData);
W32KAPI DWORD WINAPI NtGdiDvpColorControl(HANDLE hVideoPort,PDD_VPORTCOLORDATA puVPortColorData);
W32KAPI HANDLE WINAPI NtGdiDvpCreateVideoPort(HANDLE hDirectDraw,PDD_CREATEVPORTDATA puCreateVPortData);
W32KAPI DWORD WINAPI NtGdiDvpDestroyVideoPort(HANDLE hVideoPort,PDD_DESTROYVPORTDATA puDestroyVPortData);
W32KAPI DWORD WINAPI NtGdiDvpFlipVideoPort(HANDLE hVideoPort,HANDLE hDDSurfaceCurrent,HANDLE hDDSurfaceTarget,PDD_FLIPVPORTDATA puFlipVPortData);
W32KAPI DWORD WINAPI NtGdiDvpGetVideoPortBandwidth(HANDLE hVideoPort,PDD_GETVPORTBANDWIDTHDATA puGetVPortBandwidthData);
W32KAPI DWORD WINAPI NtGdiDvpGetVideoPortField(HANDLE hVideoPort,PDD_GETVPORTFIELDDATA puGetVPortFieldData);
W32KAPI DWORD WINAPI NtGdiDvpGetVideoPortFlipStatus(HANDLE hDirectDraw,PDD_GETVPORTFLIPSTATUSDATA puGetVPortFlipStatusData);
W32KAPI DWORD WINAPI NtGdiDvpGetVideoPortInputFormats(HANDLE hVideoPort,PDD_GETVPORTINPUTFORMATDATA puGetVPortInputFormatData);
W32KAPI DWORD WINAPI NtGdiDvpGetVideoPortLine(HANDLE hVideoPort,PDD_GETVPORTLINEDATA puGetVPortLineData);
W32KAPI DWORD WINAPI NtGdiDvpGetVideoPortOutputFormats(HANDLE hVideoPort,PDD_GETVPORTOUTPUTFORMATDATA puGetVPortOutputFormatData);
W32KAPI DWORD WINAPI NtGdiDvpGetVideoPortConnectInfo(HANDLE hDirectDraw,PDD_GETVPORTCONNECTDATA puGetVPortConnectData);
W32KAPI DWORD WINAPI NtGdiDvpGetVideoSignalStatus(HANDLE hVideoPort,PDD_GETVPORTSIGNALDATA puGetVPortSignalData);
W32KAPI DWORD WINAPI NtGdiDvpUpdateVideoPort(HANDLE hVideoPort,HANDLE *phSurfaceVideo,HANDLE *phSurfaceVbi,PDD_UPDATEVPORTDATA puUpdateVPortData);
W32KAPI DWORD WINAPI NtGdiDvpWaitForVideoPortSync(HANDLE hVideoPort,PDD_WAITFORVPORTSYNCDATA puWaitForVPortSyncData);
W32KAPI DWORD WINAPI NtGdiDvpAcquireNotification(HANDLE hVideoPort,HANDLE *hEvent,LPDDVIDEOPORTNOTIFY pNotify);
W32KAPI DWORD WINAPI NtGdiDvpReleaseNotification(HANDLE hVideoPort,HANDLE hEvent);
W32KAPI DWORD WINAPI NtGdiDdGetMoCompGuids(HANDLE hDirectDraw,PDD_GETMOCOMPGUIDSDATA puGetMoCompGuidsData);
W32KAPI DWORD WINAPI NtGdiDdGetMoCompFormats(HANDLE hDirectDraw,PDD_GETMOCOMPFORMATSDATA puGetMoCompFormatsData);
W32KAPI DWORD WINAPI NtGdiDdGetMoCompBuffInfo(HANDLE hDirectDraw,PDD_GETMOCOMPCOMPBUFFDATA puGetBuffData);
W32KAPI DWORD WINAPI NtGdiDdGetInternalMoCompInfo(HANDLE hDirectDraw,PDD_GETINTERNALMOCOMPDATA puGetInternalData);
W32KAPI HANDLE WINAPI NtGdiDdCreateMoComp(HANDLE hDirectDraw,PDD_CREATEMOCOMPDATA puCreateMoCompData);
W32KAPI DWORD WINAPI NtGdiDdDestroyMoComp(HANDLE hMoComp,PDD_DESTROYMOCOMPDATA puDestroyMoCompData);
W32KAPI DWORD WINAPI NtGdiDdBeginMoCompFrame(HANDLE hMoComp,PDD_BEGINMOCOMPFRAMEDATA puBeginFrameData);
W32KAPI DWORD WINAPI NtGdiDdEndMoCompFrame(HANDLE hMoComp,PDD_ENDMOCOMPFRAMEDATA puEndFrameData);
W32KAPI DWORD WINAPI NtGdiDdRenderMoComp(HANDLE hMoComp,PDD_RENDERMOCOMPDATA puRenderMoCompData);
W32KAPI DWORD WINAPI NtGdiDdQueryMoCompStatus(HANDLE hMoComp,PDD_QUERYMOCOMPSTATUSDATA puQueryMoCompStatusData);
W32KAPI DWORD WINAPI NtGdiDdAlphaBlt(HANDLE hSurfaceDest,HANDLE hSurfaceSrc,PDD_BLTDATA puBltData);
W32KAPI WINBOOL WINAPI NtGdiAlphaBlend(HDC hdcDst,LONG DstX,LONG DstY,LONG DstCx,LONG DstCy,HDC hdcSrc,LONG SrcX,LONG SrcY,LONG SrcCx,LONG SrcCy,BLENDFUNCTION BlendFunction,HANDLE hcmXform);
W32KAPI WINBOOL WINAPI NtGdiGradientFill(HDC hdc,PTRIVERTEX pVertex,ULONG nVertex,PVOID pMesh,ULONG nMesh,ULONG ulMode);
W32KAPI WINBOOL WINAPI NtGdiSetIcmMode(HDC hdc,ULONG nCommand,ULONG ulMode);
#define ICM_SET_MODE 1
#define ICM_SET_CALIBRATE_MODE 2
#define ICM_SET_COLOR_MODE 3
#define ICM_CHECK_COLOR_MODE 4
typedef struct _LOGCOLORSPACEEXW {
LOGCOLORSPACEW lcsColorSpace;
DWORD dwFlags;
} LOGCOLORSPACEEXW,*PLOGCOLORSPACEEXW;
#define LCSEX_ANSICREATED 0x0001
#define LCSEX_TEMPPROFILE 0x0002
W32KAPI HANDLE WINAPI NtGdiCreateColorSpace(PLOGCOLORSPACEEXW pLogColorSpace);
W32KAPI WINBOOL WINAPI NtGdiDeleteColorSpace(HANDLE hColorSpace);
W32KAPI WINBOOL WINAPI NtGdiSetColorSpace(HDC hdc,HCOLORSPACE hColorSpace);
W32KAPI HANDLE WINAPI NtGdiCreateColorTransform(HDC hdc,LPLOGCOLORSPACEW pLogColorSpaceW,PVOID pvSrcProfile,ULONG cjSrcProfile,PVOID pvDestProfile,ULONG cjDestProfile,PVOID pvTargetProfile,ULONG cjTargetProfile);
W32KAPI WINBOOL WINAPI NtGdiDeleteColorTransform(HDC hdc,HANDLE hColorTransform);
W32KAPI WINBOOL WINAPI NtGdiCheckBitmapBits(HDC hdc,HANDLE hColorTransform,PVOID pvBits,ULONG bmFormat,DWORD dwWidth,DWORD dwHeight,DWORD dwStride,PBYTE paResults);
W32KAPI ULONG WINAPI NtGdiColorCorrectPalette(HDC hdc,HPALETTE hpal,ULONG FirstEntry,ULONG NumberOfEntries,PALETTEENTRY *ppalEntry,ULONG Command);
W32KAPI ULONG_PTR WINAPI NtGdiGetColorSpaceforBitmap(HBITMAP hsurf);
typedef enum _COLORPALETTEINFO {
ColorPaletteQuery,ColorPaletteSet
} COLORPALETTEINFO,*PCOLORPALETTEINFO;
W32KAPI WINBOOL WINAPI NtGdiGetDeviceGammaRamp(HDC hdc,LPVOID lpGammaRamp);
W32KAPI WINBOOL WINAPI NtGdiSetDeviceGammaRamp(HDC hdc,LPVOID lpGammaRamp);
W32KAPI WINBOOL WINAPI NtGdiIcmBrushInfo(HDC hdc,HBRUSH hbrush,PBITMAPINFO pbmiDIB,PVOID pvBits,ULONG *pulBits,DWORD *piUsage,WINBOOL *pbAlreadyTran,ULONG Command);
typedef enum _ICM_DIB_INFO_CMD {
IcmQueryBrush,IcmSetBrush
} ICM_DIB_INFO,*PICM_DIB_INFO;
W32KAPI VOID WINAPI NtGdiFlush();
W32KAPI HDC WINAPI NtGdiCreateMetafileDC(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiMakeInfoDC(HDC hdc,WINBOOL bSet);
W32KAPI HANDLE WINAPI NtGdiCreateClientObj(ULONG ulType);
W32KAPI WINBOOL WINAPI NtGdiDeleteClientObj(HANDLE h);
W32KAPI LONG WINAPI NtGdiGetBitmapBits(HBITMAP hbm,ULONG cjMax,PBYTE pjOut);
W32KAPI WINBOOL WINAPI NtGdiDeleteObjectApp(HANDLE hobj);
W32KAPI int WINAPI NtGdiGetPath(HDC hdc,LPPOINT pptlBuf,LPBYTE pjTypes,int cptBuf);
W32KAPI HDC WINAPI NtGdiCreateCompatibleDC(HDC hdc);
W32KAPI HBITMAP WINAPI NtGdiCreateDIBitmapInternal(HDC hdc,INT cx,INT cy,DWORD fInit,LPBYTE pjInit,LPBITMAPINFO pbmi,DWORD iUsage,UINT cjMaxInitInfo,UINT cjMaxBits,FLONG f,HANDLE hcmXform);
W32KAPI HBITMAP WINAPI NtGdiCreateDIBSection(HDC hdc,HANDLE hSectionApp,DWORD dwOffset,LPBITMAPINFO pbmi,DWORD iUsage,UINT cjHeader,FLONG fl,ULONG_PTR dwColorSpace,PVOID *ppvBits);
W32KAPI HBRUSH WINAPI NtGdiCreateSolidBrush(COLORREF cr,HBRUSH hbr);
W32KAPI HBRUSH WINAPI NtGdiCreateDIBBrush(PVOID pv,FLONG fl,UINT cj,WINBOOL b8X8,WINBOOL bPen,PVOID pClient);
W32KAPI HBRUSH WINAPI NtGdiCreatePatternBrushInternal(HBITMAP hbm,WINBOOL bPen,WINBOOL b8X8);
W32KAPI HBRUSH WINAPI NtGdiCreateHatchBrushInternal(ULONG ulStyle,COLORREF clrr,WINBOOL bPen);
W32KAPI HPEN WINAPI NtGdiExtCreatePen(ULONG flPenStyle,ULONG ulWidth,ULONG iBrushStyle,ULONG ulColor,ULONG_PTR lClientHatch,ULONG_PTR lHatch,ULONG cstyle,PULONG pulStyle,ULONG cjDIB,WINBOOL bOldStylePen,HBRUSH hbrush);
W32KAPI HRGN WINAPI NtGdiCreateEllipticRgn(int xLeft,int yTop,int xRight,int yBottom);
W32KAPI HRGN WINAPI NtGdiCreateRoundRectRgn(int xLeft,int yTop,int xRight,int yBottom,int xWidth,int yHeight);
W32KAPI HANDLE WINAPI NtGdiCreateServerMetaFile(DWORD iType,ULONG cjData,LPBYTE pjData,DWORD mm,DWORD xExt,DWORD yExt);
W32KAPI HRGN WINAPI NtGdiExtCreateRegion(LPXFORM px,DWORD cj,LPRGNDATA prgn);
W32KAPI ULONG WINAPI NtGdiMakeFontDir(FLONG flEmbed,PBYTE pjFontDir,unsigned cjFontDir,LPWSTR pwszPathname,unsigned cjPathname);
W32KAPI WINBOOL WINAPI NtGdiPolyDraw(HDC hdc,LPPOINT ppt,LPBYTE pjAttr,ULONG cpt);
W32KAPI WINBOOL WINAPI NtGdiPolyTextOutW(HDC hdc,POLYTEXTW *pptw,UINT cStr,DWORD dwCodePage);
W32KAPI ULONG WINAPI NtGdiGetServerMetaFileBits(HANDLE hmo,ULONG cjData,LPBYTE pjData,PDWORD piType,PDWORD pmm,PDWORD pxExt,PDWORD pyExt);
W32KAPI WINBOOL WINAPI NtGdiEqualRgn(HRGN hrgn1,HRGN hrgn2);
W32KAPI WINBOOL WINAPI NtGdiGetBitmapDimension(HBITMAP hbm,LPSIZE psize);
W32KAPI UINT WINAPI NtGdiGetNearestPaletteIndex(HPALETTE hpal,COLORREF crColor);
W32KAPI WINBOOL WINAPI NtGdiPtVisible(HDC hdc,int x,int y);
W32KAPI WINBOOL WINAPI NtGdiRectVisible(HDC hdc,LPRECT prc);
W32KAPI WINBOOL WINAPI NtGdiRemoveFontResourceW(WCHAR *pwszFiles,ULONG cwc,ULONG cFiles,ULONG fl,DWORD dwPidTid,DESIGNVECTOR *pdv);
W32KAPI WINBOOL WINAPI NtGdiResizePalette(HPALETTE hpal,UINT cEntry);
W32KAPI WINBOOL WINAPI NtGdiSetBitmapDimension(HBITMAP hbm,int cx,int cy,LPSIZE psizeOut);
W32KAPI int WINAPI NtGdiOffsetClipRgn(HDC hdc,int x,int y);
W32KAPI int WINAPI NtGdiSetMetaRgn(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiSetTextJustification(HDC hdc,int lBreakExtra,int cBreak);
W32KAPI int WINAPI NtGdiGetAppClipBox(HDC hdc,LPRECT prc);
W32KAPI WINBOOL WINAPI NtGdiGetTextExtentExW(HDC hdc,LPWSTR lpwsz,ULONG cwc,ULONG dxMax,ULONG *pcCh,PULONG pdxOut,LPSIZE psize,FLONG fl);
W32KAPI WINBOOL WINAPI NtGdiGetCharABCWidthsW(HDC hdc,UINT wchFirst,ULONG cwch,PWCHAR pwch,FLONG fl,PVOID pvBuf);
W32KAPI DWORD WINAPI NtGdiGetCharacterPlacementW(HDC hdc,LPWSTR pwsz,int nCount,int nMaxExtent,LPGCP_RESULTSW pgcpw,DWORD dwFlags);
W32KAPI WINBOOL WINAPI NtGdiAngleArc(HDC hdc,int x,int y,DWORD dwRadius,DWORD dwStartAngle,DWORD dwSweepAngle);
W32KAPI WINBOOL WINAPI NtGdiBeginPath(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiSelectClipPath(HDC hdc,int iMode);
W32KAPI WINBOOL WINAPI NtGdiCloseFigure(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiEndPath(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiAbortPath(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiFillPath(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiStrokeAndFillPath(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiStrokePath(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiWidenPath(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiFlattenPath(HDC hdc);
W32KAPI HRGN WINAPI NtGdiPathToRegion(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiSetMiterLimit(HDC hdc,DWORD dwNew,PDWORD pdwOut);
W32KAPI WINBOOL WINAPI NtGdiSetFontXform(HDC hdc,DWORD dwxScale,DWORD dwyScale);
W32KAPI WINBOOL WINAPI NtGdiGetMiterLimit(HDC hdc,PDWORD pdwOut);
W32KAPI WINBOOL WINAPI NtGdiEllipse(HDC hdc,int xLeft,int yTop,int xRight,int yBottom);
W32KAPI WINBOOL WINAPI NtGdiRectangle(HDC hdc,int xLeft,int yTop,int xRight,int yBottom);
W32KAPI WINBOOL WINAPI NtGdiRoundRect(HDC hdc,int x1,int y1,int x2,int y2,int x3,int y3);
W32KAPI WINBOOL WINAPI NtGdiPlgBlt(HDC hdcTrg,LPPOINT pptlTrg,HDC hdcSrc,int xSrc,int ySrc,int cxSrc,int cySrc,HBITMAP hbmMask,int xMask,int yMask,DWORD crBackColor);
W32KAPI WINBOOL WINAPI NtGdiMaskBlt(HDC hdc,int xDst,int yDst,int cx,int cy,HDC hdcSrc,int xSrc,int ySrc,HBITMAP hbmMask,int xMask,int yMask,DWORD dwRop4,DWORD crBackColor);
W32KAPI WINBOOL WINAPI NtGdiExtFloodFill(HDC hdc,INT x,INT y,COLORREF crColor,UINT iFillType);
W32KAPI WINBOOL WINAPI NtGdiFillRgn(HDC hdc,HRGN hrgn,HBRUSH hbrush);
W32KAPI WINBOOL WINAPI NtGdiFrameRgn(HDC hdc,HRGN hrgn,HBRUSH hbrush,int xWidth,int yHeight);
W32KAPI COLORREF WINAPI NtGdiSetPixel(HDC hdcDst,int x,int y,COLORREF crColor);
W32KAPI DWORD WINAPI NtGdiGetPixel(HDC hdc,int x,int y);
W32KAPI WINBOOL WINAPI NtGdiStartPage(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiEndPage(HDC hdc);
W32KAPI int WINAPI NtGdiStartDoc(HDC hdc,DOCINFOW *pdi,WINBOOL *pbBanding,INT iJob);
W32KAPI WINBOOL WINAPI NtGdiEndDoc(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiAbortDoc(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiUpdateColors(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiGetCharWidthW(HDC hdc,UINT wcFirst,UINT cwc,PWCHAR pwc,FLONG fl,PVOID pvBuf);
W32KAPI WINBOOL WINAPI NtGdiGetCharWidthInfo(HDC hdc,PCHWIDTHINFO pChWidthInfo);
W32KAPI int WINAPI NtGdiDrawEscape(HDC hdc,int iEsc,int cjIn,LPSTR pjIn);
W32KAPI int WINAPI NtGdiExtEscape(HDC hdc,PWCHAR pDriver,int nDriver,int iEsc,int cjIn,LPSTR pjIn,int cjOut,LPSTR pjOut);
W32KAPI ULONG WINAPI NtGdiGetFontData(HDC hdc,DWORD dwTable,DWORD dwOffset,PVOID pvBuf,ULONG cjBuf);
W32KAPI ULONG WINAPI NtGdiGetGlyphOutline(HDC hdc,WCHAR wch,UINT iFormat,LPGLYPHMETRICS pgm,ULONG cjBuf,PVOID pvBuf,LPMAT2 pmat2,WINBOOL bIgnoreRotation);
W32KAPI WINBOOL WINAPI NtGdiGetETM(HDC hdc,EXTTEXTMETRIC *petm);
W32KAPI WINBOOL WINAPI NtGdiGetRasterizerCaps(LPRASTERIZER_STATUS praststat,ULONG cjBytes);
W32KAPI ULONG WINAPI NtGdiGetKerningPairs(HDC hdc,ULONG cPairs,KERNINGPAIR *pkpDst);
W32KAPI WINBOOL WINAPI NtGdiMonoBitmap(HBITMAP hbm);
W32KAPI HBITMAP WINAPI NtGdiGetObjectBitmapHandle(HBRUSH hbr,UINT *piUsage);
W32KAPI ULONG WINAPI NtGdiEnumObjects(HDC hdc,int iObjectType,ULONG cjBuf,PVOID pvBuf);
W32KAPI WINBOOL WINAPI NtGdiResetDC(HDC hdc,LPDEVMODEW pdm,PBOOL pbBanding,VOID *pDriverInfo2,VOID *ppUMdhpdev);
W32KAPI DWORD WINAPI NtGdiSetBoundsRect(HDC hdc,LPRECT prc,DWORD f);
W32KAPI WINBOOL WINAPI NtGdiGetColorAdjustment(HDC hdc,PCOLORADJUSTMENT pcaOut);
W32KAPI WINBOOL WINAPI NtGdiSetColorAdjustment(HDC hdc,PCOLORADJUSTMENT pca);
W32KAPI WINBOOL WINAPI NtGdiCancelDC(HDC hdc);
W32KAPI HDC WINAPI NtGdiOpenDCW(PUNICODE_STRING pustrDevice,DEVMODEW *pdm,PUNICODE_STRING pustrLogAddr,ULONG iType,HANDLE hspool,VOID *pDriverInfo2,VOID *pUMdhpdev);
W32KAPI WINBOOL WINAPI NtGdiGetDCDword(HDC hdc,UINT u,DWORD *Result);
W32KAPI WINBOOL WINAPI NtGdiGetDCPoint(HDC hdc,UINT iPoint,PPOINTL pptOut);
W32KAPI WINBOOL WINAPI NtGdiScaleViewportExtEx(HDC hdc,int xNum,int xDenom,int yNum,int yDenom,LPSIZE pszOut);
W32KAPI WINBOOL WINAPI NtGdiScaleWindowExtEx(HDC hdc,int xNum,int xDenom,int yNum,int yDenom,LPSIZE pszOut);
W32KAPI WINBOOL WINAPI NtGdiSetVirtualResolution(HDC hdc,int cxVirtualDevicePixel,int cyVirtualDevicePixel,int cxVirtualDeviceMm,int cyVirtualDeviceMm);
W32KAPI WINBOOL WINAPI NtGdiSetSizeDevice(HDC hdc,int cxVirtualDevice,int cyVirtualDevice);
W32KAPI WINBOOL WINAPI NtGdiGetTransform(HDC hdc,DWORD iXform,LPXFORM pxf);
W32KAPI WINBOOL WINAPI NtGdiModifyWorldTransform(HDC hdc,LPXFORM pxf,DWORD iXform);
W32KAPI WINBOOL WINAPI NtGdiCombineTransform(LPXFORM pxfDst,LPXFORM pxfSrc1,LPXFORM pxfSrc2);
W32KAPI WINBOOL WINAPI NtGdiTransformPoints(HDC hdc,PPOINT pptIn,PPOINT pptOut,int c,int iMode);
W32KAPI LONG WINAPI NtGdiConvertMetafileRect(HDC hdc,PRECTL prect);
W32KAPI int WINAPI NtGdiGetTextCharsetInfo(HDC hdc,LPFONTSIGNATURE lpSig,DWORD dwFlags);
W32KAPI WINBOOL WINAPI NtGdiDoBanding(HDC hdc,WINBOOL bStart,POINTL *pptl,PSIZE pSize);
W32KAPI ULONG WINAPI NtGdiGetPerBandInfo(HDC hdc,PERBANDINFO *ppbi);
#define GS_NUM_OBJS_ALL 0
#define GS_HANDOBJ_CURRENT 1
#define GS_HANDOBJ_MAX 2
#define GS_HANDOBJ_ALLOC 3
#define GS_LOOKASIDE_INFO 4
W32KAPI NTSTATUS WINAPI NtGdiGetStats(HANDLE hProcess,int iIndex,int iPidType,PVOID pResults,UINT cjResultSize);
W32KAPI WINBOOL WINAPI NtGdiSetMagicColors(HDC hdc,PALETTEENTRY peMagic,ULONG Index);
W32KAPI HBRUSH WINAPI NtGdiSelectBrush(HDC hdc,HBRUSH hbrush);
W32KAPI HPEN WINAPI NtGdiSelectPen(HDC hdc,HPEN hpen);
W32KAPI HBITMAP WINAPI NtGdiSelectBitmap(HDC hdc,HBITMAP hbm);
W32KAPI HFONT WINAPI NtGdiSelectFont(HDC hdc,HFONT hf);
W32KAPI int WINAPI NtGdiExtSelectClipRgn(HDC hdc,HRGN hrgn,int iMode);
W32KAPI HPEN WINAPI NtGdiCreatePen(int iPenStyle,int iPenWidth,COLORREF cr,HBRUSH hbr);
#ifndef _WINDOWBLT_NOTIFICATION_
#define _WINDOWBLT_NOTIFICATION_
#endif
W32KAPI WINBOOL WINAPI NtGdiBitBlt(HDC hdcDst,int x,int y,int cx,int cy,HDC hdcSrc,int xSrc,int ySrc,DWORD rop4,DWORD crBackColor,FLONG fl);
W32KAPI WINBOOL WINAPI NtGdiTileBitBlt(HDC hdcDst,RECTL *prectDst,HDC hdcSrc,RECTL *prectSrc,POINTL *pptlOrigin,DWORD rop4,DWORD crBackColor);
W32KAPI WINBOOL WINAPI NtGdiTransparentBlt(HDC hdcDst,int xDst,int yDst,int cxDst,int cyDst,HDC hdcSrc,int xSrc,int ySrc,int cxSrc,int cySrc,COLORREF TransColor);
W32KAPI WINBOOL WINAPI NtGdiGetTextExtent(HDC hdc,LPWSTR lpwsz,int cwc,LPSIZE psize,UINT flOpts);
W32KAPI WINBOOL WINAPI NtGdiGetTextMetricsW(HDC hdc,TMW_INTERNAL *ptm,ULONG cj);
W32KAPI int WINAPI NtGdiGetTextFaceW(HDC hdc,int cChar,LPWSTR pszOut,WINBOOL bAliasName);
W32KAPI int WINAPI NtGdiGetRandomRgn(HDC hdc,HRGN hrgn,int iRgn);
W32KAPI WINBOOL WINAPI NtGdiExtTextOutW(HDC hdc,int x,int y,UINT flOpts,LPRECT prcl,LPWSTR pwsz,int cwc,LPINT pdx,DWORD dwCodePage);
W32KAPI int WINAPI NtGdiIntersectClipRect(HDC hdc,int xLeft,int yTop,int xRight,int yBottom);
W32KAPI HRGN WINAPI NtGdiCreateRectRgn(int xLeft,int yTop,int xRight,int yBottom);
W32KAPI WINBOOL WINAPI NtGdiPatBlt(HDC hdcDst,int x,int y,int cx,int cy,DWORD rop4);
typedef struct _POLYPATBLT POLYPATBLT,*PPOLYPATBLT;
W32KAPI WINBOOL WINAPI NtGdiPolyPatBlt(HDC hdc,DWORD rop4,PPOLYPATBLT pPoly,DWORD Count,DWORD Mode);
W32KAPI WINBOOL WINAPI NtGdiUnrealizeObject(HANDLE h);
W32KAPI HANDLE WINAPI NtGdiGetStockObject(int iObject);
W32KAPI HBITMAP WINAPI NtGdiCreateCompatibleBitmap(HDC hdc,int cx,int cy);
W32KAPI WINBOOL WINAPI NtGdiLineTo(HDC hdc,int x,int y);
W32KAPI WINBOOL WINAPI NtGdiMoveTo(HDC hdc,int x,int y,LPPOINT pptOut);
W32KAPI int WINAPI NtGdiExtGetObjectW(HANDLE h,int cj,LPVOID pvOut);
W32KAPI int WINAPI NtGdiGetDeviceCaps(HDC hdc,int i);
W32KAPI WINBOOL WINAPI NtGdiGetDeviceCapsAll (HDC hdc,PDEVCAPS pDevCaps);
W32KAPI WINBOOL WINAPI NtGdiStretchBlt(HDC hdcDst,int xDst,int yDst,int cxDst,int cyDst,HDC hdcSrc,int xSrc,int ySrc,int cxSrc,int cySrc,DWORD dwRop,DWORD dwBackColor);
W32KAPI WINBOOL WINAPI NtGdiSetBrushOrg(HDC hdc,int x,int y,LPPOINT pptOut);
W32KAPI HBITMAP WINAPI NtGdiCreateBitmap(int cx,int cy,UINT cPlanes,UINT cBPP,LPBYTE pjInit);
W32KAPI HPALETTE WINAPI NtGdiCreateHalftonePalette(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiRestoreDC(HDC hdc,int iLevel);
W32KAPI int WINAPI NtGdiExcludeClipRect(HDC hdc,int xLeft,int yTop,int xRight,int yBottom);
W32KAPI int WINAPI NtGdiSaveDC(HDC hdc);
W32KAPI int WINAPI NtGdiCombineRgn(HRGN hrgnDst,HRGN hrgnSrc1,HRGN hrgnSrc2,int iMode);
W32KAPI WINBOOL WINAPI NtGdiSetRectRgn(HRGN hrgn,int xLeft,int yTop,int xRight,int yBottom);
W32KAPI LONG WINAPI NtGdiSetBitmapBits(HBITMAP hbm,ULONG cj,PBYTE pjInit);
W32KAPI int WINAPI NtGdiGetDIBitsInternal(HDC hdc,HBITMAP hbm,UINT iStartScan,UINT cScans,LPBYTE pBits,LPBITMAPINFO pbmi,UINT iUsage,UINT cjMaxBits,UINT cjMaxInfo);
W32KAPI int WINAPI NtGdiOffsetRgn(HRGN hrgn,int cx,int cy);
W32KAPI int WINAPI NtGdiGetRgnBox(HRGN hrgn,LPRECT prcOut);
W32KAPI WINBOOL WINAPI NtGdiRectInRegion(HRGN hrgn,LPRECT prcl);
W32KAPI DWORD WINAPI NtGdiGetBoundsRect(HDC hdc,LPRECT prc,DWORD f);
W32KAPI WINBOOL WINAPI NtGdiPtInRegion(HRGN hrgn,int x,int y);
W32KAPI COLORREF WINAPI NtGdiGetNearestColor(HDC hdc,COLORREF cr);
W32KAPI UINT WINAPI NtGdiGetSystemPaletteUse(HDC hdc);
W32KAPI UINT WINAPI NtGdiSetSystemPaletteUse(HDC hdc,UINT ui);
W32KAPI DWORD WINAPI NtGdiGetRegionData(HRGN hrgn,DWORD nCount,LPRGNDATA lpRgnData);
W32KAPI WINBOOL WINAPI NtGdiInvertRgn(HDC hdc,HRGN hrgn);
int W32KAPI WINAPI NtGdiAddFontResourceW(WCHAR *pwszFiles,ULONG cwc,ULONG cFiles,FLONG f,DWORD dwPidTid,DESIGNVECTOR *pdv);
W32KAPI HFONT WINAPI NtGdiHfontCreate(ENUMLOGFONTEXDVW *pelfw,ULONG cjElfw,LFTYPE lft,FLONG fl,PVOID pvCliData);
W32KAPI ULONG WINAPI NtGdiSetFontEnumeration(ULONG ulType);
W32KAPI WINBOOL WINAPI NtGdiEnumFontClose(ULONG_PTR idEnum);
W32KAPI WINBOOL WINAPI NtGdiEnumFontChunk(HDC hdc,ULONG_PTR idEnum,ULONG cjEfdw,ULONG *pcjEfdw,PENUMFONTDATAW pefdw);
W32KAPI ULONG_PTR WINAPI NtGdiEnumFontOpen(HDC hdc,ULONG iEnumType,FLONG flWin31Compat,ULONG cwchMax,LPWSTR pwszFaceName,ULONG lfCharSet,ULONG *pulCount);
#define TYPE_ENUMFONTS 1
#define TYPE_ENUMFONTFAMILIES 2
#define TYPE_ENUMFONTFAMILIESEX 3
W32KAPI INT WINAPI NtGdiQueryFonts(PUNIVERSAL_FONT_ID pufiFontList,ULONG nBufferSize,PLARGE_INTEGER pTimeStamp);
W32KAPI WINBOOL WINAPI NtGdiConsoleTextOut(HDC hdc,POLYTEXTW *lpto,UINT nStrings,RECTL *prclBounds);
W32KAPI NTSTATUS WINAPI NtGdiFullscreenControl(FULLSCREENCONTROL FullscreenCommand,PVOID FullscreenInput,DWORD FullscreenInputLength,PVOID FullscreenOutput,PULONG FullscreenOutputLength);
W32KAPI DWORD NtGdiGetCharSet(HDC hdc);
W32KAPI WINBOOL WINAPI NtGdiEnableEudc(WINBOOL);
W32KAPI WINBOOL WINAPI NtGdiEudcLoadUnloadLink(LPCWSTR pBaseFaceName,UINT cwcBaseFaceName,LPCWSTR pEudcFontPath,UINT cwcEudcFontPath,INT iPriority,INT iFontLinkType,WINBOOL bLoadLin);
W32KAPI UINT WINAPI NtGdiGetStringBitmapW(HDC hdc,LPWSTR pwsz,UINT cwc,BYTE *lpSB,UINT cj);
W32KAPI ULONG WINAPI NtGdiGetEudcTimeStampEx(LPWSTR lpBaseFaceName,ULONG cwcBaseFaceName,WINBOOL bSystemTimeStamp);
W32KAPI ULONG WINAPI NtGdiQueryFontAssocInfo(HDC hdc);
W32KAPI DWORD NtGdiGetFontUnicodeRanges(HDC hdc,LPGLYPHSET pgs);
#ifdef LANGPACK
W32KAPI WINBOOL NtGdiGetRealizationInfo(HDC hdc,PREALIZATION_INFO pri,HFONT hf);
#endif
typedef struct tagDOWNLOADDESIGNVECTOR {
UNIVERSAL_FONT_ID ufiBase;
DESIGNVECTOR dv;
} DOWNLOADDESIGNVECTOR;
W32KAPI WINBOOL NtGdiAddRemoteMMInstanceToDC(HDC hdc,DOWNLOADDESIGNVECTOR *pddv,ULONG cjDDV);
W32KAPI WINBOOL WINAPI NtGdiUnloadPrinterDriver(LPWSTR pDriverName,ULONG cbDriverName);
W32KAPI WINBOOL WINAPI NtGdiEngAssociateSurface(HSURF hsurf,HDEV hdev,FLONG flHooks);
W32KAPI WINBOOL WINAPI NtGdiEngEraseSurface(SURFOBJ *pso,RECTL *prcl,ULONG iColor);
W32KAPI HBITMAP WINAPI NtGdiEngCreateBitmap(SIZEL sizl,LONG lWidth,ULONG iFormat,FLONG fl,PVOID pvBits);
W32KAPI WINBOOL WINAPI NtGdiEngDeleteSurface(HSURF hsurf);
W32KAPI SURFOBJ *WINAPI NtGdiEngLockSurface(HSURF hsurf);
W32KAPI VOID WINAPI NtGdiEngUnlockSurface(SURFOBJ *);
W32KAPI WINBOOL WINAPI NtGdiEngMarkBandingSurface(HSURF hsurf);
W32KAPI HSURF WINAPI NtGdiEngCreateDeviceSurface(DHSURF dhsurf,SIZEL sizl,ULONG iFormatCompat);
W32KAPI HBITMAP WINAPI NtGdiEngCreateDeviceBitmap(DHSURF dhsurf,SIZEL sizl,ULONG iFormatCompat);
W32KAPI WINBOOL WINAPI NtGdiEngCopyBits(SURFOBJ *psoDst,SURFOBJ *psoSrc,CLIPOBJ *pco,XLATEOBJ *pxlo,RECTL *prclDst,POINTL *pptlSrc);
W32KAPI WINBOOL WINAPI NtGdiEngStretchBlt(SURFOBJ *psoDest,SURFOBJ *psoSrc,SURFOBJ *psoMask,CLIPOBJ *pco,XLATEOBJ *pxlo,COLORADJUSTMENT *pca,POINTL *pptlHTOrg,RECTL *prclDest,RECTL *prclSrc,POINTL *pptlMask,ULONG iMode);
W32KAPI WINBOOL WINAPI NtGdiEngBitBlt(SURFOBJ *psoDst,SURFOBJ *psoSrc,SURFOBJ *psoMask,CLIPOBJ *pco,XLATEOBJ *pxlo,RECTL *prclDst,POINTL *pptlSrc,POINTL *pptlMask,BRUSHOBJ *pbo,POINTL *pptlBrush,ROP4 rop4);
W32KAPI WINBOOL WINAPI NtGdiEngPlgBlt(SURFOBJ *psoTrg,SURFOBJ *psoSrc,SURFOBJ *psoMsk,CLIPOBJ *pco,XLATEOBJ *pxlo,COLORADJUSTMENT *pca,POINTL *pptlBrushOrg,POINTFIX *pptfxDest,RECTL *prclSrc,POINTL *pptlMask,ULONG iMode);
W32KAPI HPALETTE WINAPI NtGdiEngCreatePalette(ULONG iMode,ULONG cColors,ULONG *pulColors,FLONG flRed,FLONG flGreen,FLONG flBlue);
W32KAPI WINBOOL WINAPI NtGdiEngDeletePalette(HPALETTE hPal);
W32KAPI WINBOOL WINAPI NtGdiEngStrokePath(SURFOBJ *pso,PATHOBJ *ppo,CLIPOBJ *pco,XFORMOBJ *pxo,BRUSHOBJ *pbo,POINTL *pptlBrushOrg,LINEATTRS *plineattrs,MIX mix);
W32KAPI WINBOOL WINAPI NtGdiEngFillPath(SURFOBJ *pso,PATHOBJ *ppo,CLIPOBJ *pco,BRUSHOBJ *pbo,POINTL *pptlBrushOrg,MIX mix,FLONG flOptions);
W32KAPI WINBOOL WINAPI NtGdiEngStrokeAndFillPath(SURFOBJ *pso,PATHOBJ *ppo,CLIPOBJ *pco,XFORMOBJ *pxo,BRUSHOBJ *pboStroke,LINEATTRS *plineattrs,BRUSHOBJ *pboFill,POINTL *pptlBrushOrg,MIX mix,FLONG flOptions);
W32KAPI WINBOOL WINAPI NtGdiEngPaint(SURFOBJ *pso,CLIPOBJ *pco,BRUSHOBJ *pbo,POINTL *pptlBrushOrg,MIX mix);
W32KAPI WINBOOL WINAPI NtGdiEngLineTo(SURFOBJ *pso,CLIPOBJ *pco,BRUSHOBJ *pbo,LONG x1,LONG y1,LONG x2,LONG y2,RECTL *prclBounds,MIX mix);
W32KAPI WINBOOL WINAPI NtGdiEngAlphaBlend(SURFOBJ *psoDest,SURFOBJ *psoSrc,CLIPOBJ *pco,XLATEOBJ *pxlo,RECTL *prclDest,RECTL *prclSrc,BLENDOBJ *pBlendObj);
W32KAPI WINBOOL WINAPI NtGdiEngGradientFill(SURFOBJ *psoDest,CLIPOBJ *pco,XLATEOBJ *pxlo,TRIVERTEX *pVertex,ULONG nVertex,PVOID pMesh,ULONG nMesh,RECTL *prclExtents,POINTL *pptlDitherOrg,ULONG ulMode);
W32KAPI WINBOOL WINAPI NtGdiEngTransparentBlt(SURFOBJ *psoDst,SURFOBJ *psoSrc,CLIPOBJ *pco,XLATEOBJ *pxlo,RECTL *prclDst,RECTL *prclSrc,ULONG iTransColor,ULONG ulReserved);
W32KAPI WINBOOL WINAPI NtGdiEngTextOut(SURFOBJ *pso,STROBJ *pstro,FONTOBJ *pfo,CLIPOBJ *pco,RECTL *prclExtra,RECTL *prclOpaque,BRUSHOBJ *pboFore,BRUSHOBJ *pboOpaque,POINTL *pptlOrg,MIX mix);
W32KAPI WINBOOL WINAPI NtGdiEngStretchBltROP(SURFOBJ *psoTrg,SURFOBJ *psoSrc,SURFOBJ *psoMask,CLIPOBJ *pco,XLATEOBJ *pxlo,COLORADJUSTMENT *pca,POINTL *pptlBrushOrg,RECTL *prclTrg,RECTL *prclSrc,POINTL *pptlMask,ULONG iMode,BRUSHOBJ *pbo,ROP4 rop4);
W32KAPI ULONG WINAPI NtGdiXLATEOBJ_cGetPalette(XLATEOBJ *pxlo,ULONG iPal,ULONG cPal,ULONG *pPal);
W32KAPI ULONG WINAPI NtGdiCLIPOBJ_cEnumStart(CLIPOBJ *pco,WINBOOL bAll,ULONG iType,ULONG iDirection,ULONG cLimit);
W32KAPI WINBOOL WINAPI NtGdiCLIPOBJ_bEnum(CLIPOBJ *pco,ULONG cj,ULONG *pul);
W32KAPI PATHOBJ *WINAPI NtGdiCLIPOBJ_ppoGetPath(CLIPOBJ *pco);
W32KAPI CLIPOBJ *WINAPI NtGdiEngCreateClip();
W32KAPI VOID WINAPI NtGdiEngDeleteClip(CLIPOBJ*pco);
W32KAPI PVOID WINAPI NtGdiBRUSHOBJ_pvAllocRbrush(BRUSHOBJ *pbo,ULONG cj);
W32KAPI PVOID WINAPI NtGdiBRUSHOBJ_pvGetRbrush(BRUSHOBJ *pbo);
W32KAPI ULONG WINAPI NtGdiBRUSHOBJ_ulGetBrushColor(BRUSHOBJ *pbo);
W32KAPI HANDLE WINAPI NtGdiBRUSHOBJ_hGetColorTransform(BRUSHOBJ *pbo);
W32KAPI WINBOOL WINAPI NtGdiXFORMOBJ_bApplyXform(XFORMOBJ *pxo,ULONG iMode,ULONG cPoints,PVOID pvIn,PVOID pvOut);
W32KAPI ULONG WINAPI NtGdiXFORMOBJ_iGetXform(XFORMOBJ *pxo,XFORML *pxform);
W32KAPI VOID WINAPI NtGdiFONTOBJ_vGetInfo(FONTOBJ *pfo,ULONG cjSize,FONTINFO *pfi);
W32KAPI ULONG WINAPI NtGdiFONTOBJ_cGetGlyphs(FONTOBJ *pfo,ULONG iMode,ULONG cGlyph,HGLYPH *phg,PVOID *ppvGlyph);
W32KAPI XFORMOBJ *WINAPI NtGdiFONTOBJ_pxoGetXform(FONTOBJ *pfo);
W32KAPI IFIMETRICS *WINAPI NtGdiFONTOBJ_pifi(FONTOBJ *pfo);
W32KAPI FD_GLYPHSET *WINAPI NtGdiFONTOBJ_pfdg(FONTOBJ *pfo);
W32KAPI ULONG WINAPI NtGdiFONTOBJ_cGetAllGlyphHandles(FONTOBJ *pfo,HGLYPH *phg);
W32KAPI PVOID WINAPI NtGdiFONTOBJ_pvTrueTypeFontFile(FONTOBJ *pfo,ULONG *pcjFile);
W32KAPI PFD_GLYPHATTR WINAPI NtGdiFONTOBJ_pQueryGlyphAttrs(FONTOBJ *pfo,ULONG iMode);
W32KAPI WINBOOL WINAPI NtGdiSTROBJ_bEnum(STROBJ *pstro,ULONG *pc,PGLYPHPOS *ppgpos);
W32KAPI WINBOOL WINAPI NtGdiSTROBJ_bEnumPositionsOnly(STROBJ *pstro,ULONG *pc,PGLYPHPOS *ppgpos);
W32KAPI VOID WINAPI NtGdiSTROBJ_vEnumStart(STROBJ *pstro);
W32KAPI DWORD WINAPI NtGdiSTROBJ_dwGetCodePage(STROBJ *pstro);
W32KAPI WINBOOL WINAPI NtGdiSTROBJ_bGetAdvanceWidths(STROBJ*pstro,ULONG iFirst,ULONG c,POINTQF*pptqD);
W32KAPI FD_GLYPHSET *WINAPI NtGdiEngComputeGlyphSet(INT nCodePage,INT nFirstChar,INT cChars);
W32KAPI ULONG WINAPI NtGdiXLATEOBJ_iXlate(XLATEOBJ *pxlo,ULONG iColor);
W32KAPI HANDLE WINAPI NtGdiXLATEOBJ_hGetColorTransform(XLATEOBJ *pxlo);
W32KAPI VOID WINAPI NtGdiPATHOBJ_vGetBounds(PATHOBJ *ppo,PRECTFX prectfx);
W32KAPI WINBOOL WINAPI NtGdiPATHOBJ_bEnum(PATHOBJ *ppo,PATHDATA *ppd);
W32KAPI VOID WINAPI NtGdiPATHOBJ_vEnumStart(PATHOBJ *ppo);
W32KAPI VOID WINAPI NtGdiEngDeletePath(PATHOBJ *ppo);
W32KAPI VOID WINAPI NtGdiPATHOBJ_vEnumStartClipLines(PATHOBJ *ppo,CLIPOBJ *pco,SURFOBJ *pso,LINEATTRS *pla);
W32KAPI WINBOOL WINAPI NtGdiPATHOBJ_bEnumClipLines(PATHOBJ *ppo,ULONG cb,CLIPLINE *pcl);
W32KAPI WINBOOL WINAPI NtGdiEngCheckAbort(SURFOBJ *pso);
W32KAPI DHPDEV NtGdiGetDhpdev(HDEV hdev);
W32KAPI LONG WINAPI NtGdiHT_Get8BPPFormatPalette(LPPALETTEENTRY pPaletteEntry,USHORT RedGamma,USHORT GreenGamma,USHORT BlueGamma);
W32KAPI LONG WINAPI NtGdiHT_Get8BPPMaskPalette(LPPALETTEENTRY pPaletteEntry,WINBOOL Use8BPPMaskPal,BYTE CMYMask,USHORT RedGamma,USHORT GreenGamma,USHORT BlueGamma);
W32KAPI WINBOOL NtGdiUpdateTransform(HDC hdc);
W32KAPI DWORD WINAPI NtGdiSetLayout(HDC hdc,LONG wox,DWORD dwLayout);
W32KAPI WINBOOL WINAPI NtGdiMirrorWindowOrg(HDC hdc);
W32KAPI LONG WINAPI NtGdiGetDeviceWidth(HDC hdc);
W32KAPI WINBOOL NtGdiSetPUMPDOBJ(HUMPD humpd,WINBOOL bStoreID,HUMPD *phumpd,WINBOOL *pbWOW64);
W32KAPI WINBOOL NtGdiBRUSHOBJ_DeleteRbrush(BRUSHOBJ *pbo,BRUSHOBJ *pboB);
W32KAPI WINBOOL NtGdiUMPDEngFreeUserMem(KERNEL_PVOID *ppv);
W32KAPI HBITMAP WINAPI NtGdiSetBitmapAttributes(HBITMAP hbm,DWORD dwFlags);
W32KAPI HBITMAP WINAPI NtGdiClearBitmapAttributes(HBITMAP hbm,DWORD dwFlags);
W32KAPI HBRUSH WINAPI NtGdiSetBrushAttributes(HBRUSH hbm,DWORD dwFlags);
W32KAPI HBRUSH WINAPI NtGdiClearBrushAttributes(HBRUSH hbm,DWORD dwFlags);
W32KAPI WINBOOL WINAPI NtGdiDrawStream(HDC hdcDst,ULONG cjIn,VOID *pvIn);
W32KAPI WINBOOL WINAPI NtGdiMakeObjectXferable(HANDLE h,DWORD dwProcessId);
W32KAPI WINBOOL WINAPI NtGdiMakeObjectUnXferable(HANDLE h);
| 16,881 |
348 | {"nom":"Boitron","circ":"1ère circonscription","dpt":"Orne","inscrits":237,"abs":150,"votants":87,"blancs":7,"nuls":0,"exp":80,"res":[{"nuance":"DVD","nom":"<NAME>","voix":45},{"nuance":"SOC","nom":"M. <NAME>","voix":35}]} | 90 |
488 | <gh_stars>100-1000
// Copyright 2005,2006,2007 <NAME>, <NAME>
// $Id: Rule.h,v 1.2 2007-03-08 15:36:49 markus Exp $
#ifndef H_RULE
#define H_RULE
#include <string>
#include <sstream>
#include "spec.h"
class Rule
{
private:
std::string rulename, nodename;
isn type, constr, consti, field, fieldi, ftype;
unsigned int varno;
public:
Rule(std::string rulename, std::string nodename, isn type,
isn constr, isn consti, isn field, isn fieldi,
isn ftype);
bool matches(std::string &type, std::string &constr,
unsigned long consti, std::string &field, unsigned long fieldi,
std::string &ftype);
bool is_catchall() const;
bool clashes_with(const Rule &r);
std::string stringize();
std::string macrohead(unsigned int i);
std::string get_rulename();
std::string get_nodename();
bool extern_c;
bool per_constructor;
bool islist;
bool macro;
std::string get_field() const;
std::string get_ftype() const;
};
typedef std::pair<Rule *, std::string> RuleDef;
#endif
| 440 |
384 | <filename>qd3dt/models/detectrackers/tracker/tracker_model.py
import numpy as np
import torch
from filterpy.kalman import KalmanFilter
class KalmanBox3DTracker(object):
"""
This class represents the internel state of individual tracked objects
observed as bbox.
"""
count = 0
def __init__(self, bbox3D, info):
"""
Initialises a tracker using initial bounding box.
"""
# define constant velocity model
# coord3d - array of detections [x,y,z,theta,l,w,h]
# X,Y,Z,theta, l, w, h, dX, dY, dZ
self.kf = KalmanFilter(dim_x=10, dim_z=7)
self.kf.F = np.array([
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0], # state transition matrix
[0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
])
self.kf.H = np.array([
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], # measurement function,
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
])
# state uncertainty, give high uncertainty to
self.kf.P[7:, 7:] *= 1000.
# the unobservable initial velocities, covariance matrix
self.kf.P *= 10.
# self.kf.Q[-1,-1] *= 0.01 # process uncertainty
self.kf.Q[7:, 7:] *= 0.01
self.kf.x[:7] = bbox3D.reshape((7, 1))
self.time_since_update = 0
self.id = KalmanBox3DTracker.count
KalmanBox3DTracker.count += 1
self.nfr = 5
self.history = []
self.prev_ref = bbox3D
self.hits = 1 # number of total hits including the first detection
self.hit_streak = 1 # number of continuing hit considering the first
# detection
self.age = 0
self.info = info # other info
@property
def obj_state(self):
return self.kf.x.flatten()
def _update_history(self, bbox3D):
self.history = self.history[1:] + [bbox3D - self.prev_ref]
def _init_history(self, bbox3D):
self.history = [bbox3D - self.prev_ref] * self.nfr
def update(self, bbox3D, info):
"""
Updates the state vector with observed bbox.
"""
self.hits += 1
self.hit_streak += 1 # number of continuing hit
self.time_since_update = 0
# orientation correction
if self.kf.x[3] >= np.pi:
self.kf.x[3] -= np.pi * 2 # make the theta still in the range
if self.kf.x[3] < -np.pi:
self.kf.x[3] += np.pi * 2
new_theta = bbox3D[3]
if new_theta >= np.pi:
new_theta -= np.pi * 2 # make the theta still in the range
if new_theta < -np.pi:
new_theta += np.pi * 2
bbox3D[3] = new_theta
predicted_theta = self.kf.x[3]
# if the angle of two theta is not acute angle
if np.pi / 2.0 < abs(new_theta - predicted_theta) < np.pi * 3 / 2.0:
self.kf.x[3] += np.pi
if self.kf.x[3] > np.pi:
self.kf.x[3] -= np.pi * 2 # make the theta still in the range
if self.kf.x[3] < -np.pi:
self.kf.x[3] += np.pi * 2
# now the angle is acute: < 90 or > 270, convert the case of > 270 to
# < 90
if abs(new_theta - self.kf.x[3]) >= np.pi * 3 / 2.0:
if new_theta > 0:
self.kf.x[3] += np.pi * 2
else:
self.kf.x[3] -= np.pi * 2
# Update the bbox3D
self.kf.update(bbox3D)
if self.kf.x[3] >= np.pi:
self.kf.x[3] -= np.pi * 2 # make the theta still in the range
if self.kf.x[3] < -np.pi:
self.kf.x[3] += np.pi * 2
self.info = info
self.prev_ref = self.kf.x.flatten()[:7]
def predict(self, update_state: bool = True):
"""
Advances the state vector and returns the predicted bounding box
estimate.
"""
self.kf.predict()
if self.kf.x[3] >= np.pi: self.kf.x[3] -= np.pi * 2
if self.kf.x[3] < -np.pi: self.kf.x[3] += np.pi * 2
self.age += 1
if self.time_since_update > 0:
self.hit_streak = 0
self.time_since_update += 1
return self.kf.x.flatten()
def get_state(self):
"""
Returns the current bounding box estimate.
"""
return self.kf.x.flatten()
def get_history(self):
"""
Returns the history of estimates.
"""
return self.history
class LSTM3DTracker(object):
"""
This class represents the internel state of individual tracked objects
observed as bbox.
"""
count = 0
def __init__(self, device, lstm, bbox3D, info):
"""
Initialises a tracker using initial bounding box.
"""
# define constant velocity model
# coord3d - array of detections [x,y,z,theta,l,w,h]
# X,Y,Z,theta, l, w, h, dX, dY, dZ
self.device = device
self.lstm = lstm
self.loc_dim = self.lstm.loc_dim
self.id = LSTM3DTracker.count
LSTM3DTracker.count += 1
self.nfr = 5
self.hits = 1
self.hit_streak = 0
self.time_since_update = 0
self.init_flag = True
self.age = 0
self.obj_state = np.hstack([bbox3D.reshape((7, )), np.zeros((3, ))])
self.history = np.tile(
np.zeros_like(bbox3D[:self.loc_dim]), (self.nfr, 1))
self.ref_history = np.tile(bbox3D[:self.loc_dim], (self.nfr + 1, 1))
self.avg_angle = bbox3D[3]
self.avg_dim = np.array(bbox3D[4:])
self.prev_obs = bbox3D.copy()
self.prev_ref = bbox3D[:self.loc_dim].copy()
self.info = info
self.hidden_pred = self.lstm.init_hidden(self.device)
self.hidden_ref = self.lstm.init_hidden(self.device)
@staticmethod
def fix_alpha(angle: float) -> float:
return (angle + np.pi) % (2 * np.pi) - np.pi
@staticmethod
def update_array(origin_array: np.ndarray,
input_array: np.ndarray) -> np.ndarray:
new_array = origin_array.copy()
new_array[:-1] = origin_array[1:]
new_array[-1:] = input_array
return new_array
def _update_history(self, bbox3D):
self.ref_history = self.update_array(self.ref_history, bbox3D)
self.history = self.update_array(
self.history, self.ref_history[-1] - self.ref_history[-2])
# align orientation history
self.history[:, 3] = self.history[-1, 3]
self.prev_ref[:self.loc_dim] = self.obj_state[:self.loc_dim]
if self.loc_dim > 3:
self.avg_angle = self.fix_alpha(self.ref_history[:,
3]).mean(axis=0)
self.avg_dim = self.ref_history.mean(axis=0)[4:]
else:
self.avg_angle = self.prev_obs[3]
self.avg_dim = np.array(self.prev_obs[4:])
def _init_history(self, bbox3D):
self.ref_history = self.update_array(self.ref_history, bbox3D)
self.history = np.tile([self.ref_history[-1] - self.ref_history[-2]],
(self.nfr, 1))
self.prev_ref[:self.loc_dim] = self.obj_state[:self.loc_dim]
if self.loc_dim > 3:
self.avg_angle = self.fix_alpha(self.ref_history[:,
3]).mean(axis=0)
self.avg_dim = self.ref_history.mean(axis=0)[4:]
else:
self.avg_angle = self.prev_obs[3]
self.avg_dim = np.array(self.prev_obs[4:])
def update(self, bbox3D, info):
"""
Updates the state vector with observed bbox.
"""
self.time_since_update = 0
self.hits += 1
self.hit_streak += 1
if self.age == 1:
self.obj_state[:self.loc_dim] = bbox3D[:self.loc_dim].copy()
if self.loc_dim > 3:
# orientation correction
self.obj_state[3] = self.fix_alpha(self.obj_state[3])
bbox3D[3] = self.fix_alpha(bbox3D[3])
# if the angle of two theta is not acute angle
# make the theta still in the range
curr_yaw = bbox3D[3]
if np.pi / 2.0 < abs(curr_yaw -
self.obj_state[3]) < np.pi * 3 / 2.0:
self.obj_state[3] += np.pi
if self.obj_state[3] > np.pi:
self.obj_state[3] -= np.pi * 2
if self.obj_state[3] < -np.pi:
self.obj_state[3] += np.pi * 2
# now the angle is acute: < 90 or > 270,
# convert the case of > 270 to < 90
if abs(curr_yaw - self.obj_state[3]) >= np.pi * 3 / 2.0:
if curr_yaw > 0:
self.obj_state[3] += np.pi * 2
else:
self.obj_state[3] -= np.pi * 2
with torch.no_grad():
refined_loc, self.hidden_ref = self.lstm.refine(
torch.from_numpy(self.obj_state[:self.loc_dim]).view(
1, self.loc_dim).float().to(self.device),
torch.from_numpy(bbox3D[:self.loc_dim]).view(
1, self.loc_dim).float().to(self.device),
torch.from_numpy(self.prev_ref[:self.loc_dim]).view(
1, self.loc_dim).float().to(self.device),
torch.from_numpy(info).view(1, 1).float().to(self.device),
self.hidden_ref)
refined_obj = refined_loc.cpu().numpy().flatten()
if self.loc_dim > 3:
refined_obj[3] = self.fix_alpha(refined_obj[3])
self.obj_state[:self.loc_dim] = refined_obj
self.prev_obs = bbox3D
if np.pi / 2.0 < abs(bbox3D[3] - self.avg_angle) < np.pi * 3 / 2.0:
for r_indx in range(len(self.ref_history)):
self.ref_history[r_indx][3] = self.fix_alpha(
self.ref_history[r_indx][3] + np.pi)
if self.init_flag:
self._init_history(refined_obj)
self.init_flag = False
else:
self._update_history(refined_obj)
self.info = info
def predict(self, update_state: bool = True):
"""
Advances the state vector and returns the predicted bounding box
estimate.
"""
with torch.no_grad():
pred_loc, hidden_pred = self.lstm.predict(
torch.from_numpy(self.history[..., :self.loc_dim]).view(
self.nfr, -1, self.loc_dim).float().to(self.device),
torch.from_numpy(self.obj_state[:self.loc_dim]).view(
-1, self.loc_dim).float().to(self.device),
self.hidden_pred)
pred_state = self.obj_state.copy()
pred_state[:self.loc_dim] = pred_loc.cpu().numpy().flatten()
pred_state[7:] = pred_state[:3] - self.prev_ref[:3]
if self.loc_dim > 3:
pred_state[3] = self.fix_alpha(pred_state[3])
if update_state:
self.hidden_pred = hidden_pred
self.obj_state = pred_state
self.age += 1
if self.time_since_update > 0:
self.hit_streak = 0
self.time_since_update += 1
return pred_state.flatten()
def get_state(self):
"""
Returns the current bounding box estimate.
"""
return self.obj_state.flatten()
def get_history(self):
"""
Returns the history of estimates.
"""
return self.history
class DummyTracker(object):
"""
This class represents the internel state of individual tracked objects
observed as bbox.
"""
count = 0
def __init__(self, bbox3D, info):
"""
Initialises a tracker using initial bounding box.
"""
# define constant velocity model
# coord3d - array of detections [x,y,z,theta,l,w,h]
self.nfr = 5
self.hits = 1
self.hit_streak = 0
self.time_since_update = 0
self.age = 0
self.obj_state = np.hstack([bbox3D.reshape((7, )), np.zeros((3, ))])
self.history = [np.zeros_like(bbox3D)] * self.nfr
self.prev_ref = bbox3D
self.motion_momentum = 0.9
self.info = info
def _update_history(self, bbox3D):
self.history = self.history[1:] + [bbox3D - self.prev_ref]
def _init_history(self, bbox3D):
self.history = [bbox3D - self.prev_ref] * self.nfr
def update(self, bbox3D, info):
"""
Updates the state vector with observed bbox.
"""
# Update the bbox3D
self.hits += 1
self.hit_streak += 1 # number of continuing hit
self.obj_state += self.motion_momentum * (
np.hstack([bbox3D.reshape(
(7, )), np.zeros((3, ))]) - self.obj_state)
self.prev_ref = bbox3D
self.info = info
def predict(self, update_state: bool = True):
"""
Advances the state vector and returns the predicted bounding box
estimate.
"""
self.age += 1
if self.time_since_update > 0:
self.hit_streak = 0
self.time_since_update += 1
return self.obj_state.flatten()
def get_state(self):
"""
Returns the current bounding box estimate.
"""
return self.obj_state.flatten()
def get_history(self):
"""
Returns the history of estimates.
"""
return self.history
TRACKER_MODEL_ZOO = {
'KalmanBox3DTracker': KalmanBox3DTracker,
'LSTM3DTracker': LSTM3DTracker,
'DummyTracker': DummyTracker,
}
def get_tracker(tracker_model_name) -> object:
tracker_model = TRACKER_MODEL_ZOO.get(tracker_model_name, None)
if tracker_model is None:
raise NotImplementedError
return tracker_model
| 7,515 |
988 | <reponame>JoachimRohde/netbeans<gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.nativeexecution.api.util;
import com.jcraft.jsch.Channel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.netbeans.modules.nativeexecution.api.ExecutionEnvironment;
import org.netbeans.modules.nativeexecution.jsch.MeasurableSocketFactory;
import org.netbeans.modules.nativeexecution.jsch.MeasurableSocketFactory.IOListener;
import org.openide.modules.OnStop;
import org.openide.util.Exceptions;
import org.openide.util.RequestProcessor;
import org.openide.util.RequestProcessor.Task;
@OnStop
public final class RemoteStatistics implements Callable<Boolean> {
public static final boolean COLLECT_STATISTICS = Boolean.parseBoolean(System.getProperty("jsch.statistics", "false")); // NOI18N
public static final boolean COLLECT_TRAFFIC = Boolean.parseBoolean(System.getProperty("jsch.statistics.traffic", "true")); // NOI18N
public static final boolean COLLECT_STACKS = COLLECT_STATISTICS && Boolean.parseBoolean(System.getProperty("jsch.statistics.stacks", "false")); // NOI18N
private static final String BREAK_UPLOADS_FLAG_FILE = System.getProperty("break.uploads"); // NOI18N
private static final TrafficCounters trafficCounters = new TrafficCounters();
private static final RemoteMeasurementsRef unnamed = new RemoteMeasurementsRef("uncategorized", new RemoteMeasurements("uncategorized"), null, 0); // NOI18N
private static final AtomicReference<RemoteMeasurementsRef> currentStatRef = new AtomicReference<>(unnamed);
private static final BlockingQueue<Task> queue = new ArrayBlockingQueue<>(1);
private static final RemoteIOListener listener = new RemoteIOListener();
private static final AtomicBoolean trafficDetected = new AtomicBoolean();
static {
if (COLLECT_STATISTICS && COLLECT_TRAFFIC) {
MeasurableSocketFactory.getInstance().addIOListener(listener);
}
}
public abstract static class ActivityID {
/*package*/ ActivityID() {}
}
public RemoteStatistics() {
}
/**
* Start a new measurement.
*
* It is assumed that this method is called before an action that results in
* network activity.
*
* When this method is called it:
*
* <ul> <li>blocks thread waiting that all current network activity is done
* (quietPrePeriodMillis without any traffic).</li>
*
* <li>associates all further traffic with a named (see description)
* 'counters'</li>
*
* <li>once quietPostPeriodMillis passed without any traffic it dumps named
* (see description) 'counters' into appropriate file.</li> </ul>
*
* Note that there could not be several measurements done in parallel.
* Subsequent call to startTest() will block called thread until after
* previous measurement is done.
*
* @TheadSafe
*
* @param description - description to be used in output file name
* @param continuation - runnable to invoke once measurements are done
* @param quietPrePeriodMillis - quiet period (in milliseconds) of network
* inactivity before measurements start.
* @param quietPostPeriodMillis - quiet period (in milliseconds) of network
* inactivity before consider that measurements are done.
*/
public static void startTest(final String description, final Runnable continuation, final int quietPrePeriodMillis, final int quietPostPeriodMillis) {
if (!COLLECT_STATISTICS) {
if (continuation != null) {
continuation.run();
}
return;
}
final Task newTask = RequestProcessor.getDefault().create(new Runnable() {
@Override
public void run() {
try {
stopAction();
queue.poll();
} finally {
if (continuation != null) {
continuation.run();
}
}
}
});
try {
queue.put(newTask);
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
}
// At this point only a single thread runs.
while (true) {
synchronized (trafficDetected) {
try {
if (quietPrePeriodMillis > 0) {
trafficDetected.wait(quietPrePeriodMillis);
}
if (!trafficDetected.getAndSet(false)) {
break;
}
} catch (InterruptedException ex) {
break;
}
}
}
newTask.schedule(quietPostPeriodMillis);
currentStatRef.set(new RemoteMeasurementsRef(description, new RemoteMeasurements(description), newTask, quietPostPeriodMillis));
}
static boolean stopAction() {
RemoteMeasurementsRef stopped = currentStatRef.getAndSet(unnamed);
PrintStream output = getOutput(stopped.name);
try {
stopped.stat.dump(output);
} finally {
if (!output.equals(System.out)) {
output.close();
}
}
return unnamed.equals(stopped);
}
public static ActivityID startChannelActivity(CharSequence category, CharSequence... args) {
if (!COLLECT_STATISTICS) {
return null;
}
return currentStatRef.get().stat.startChannelActivity(category, args);
}
public static void stopChannelActivity(RemoteStatistics.ActivityID activityID) {
stopChannelActivity(activityID, 0);
}
public static void stopChannelActivity(RemoteStatistics.ActivityID activityID, long supposedTraffic) {
if (!COLLECT_STATISTICS) {
return;
}
if (activityID == null) {
return;
}
currentStatRef.get().stat.stopChannelActivity(activityID, supposedTraffic);
}
private static RemoteMeasurementsRef reschedule() {
RemoteMeasurementsRef ref = currentStatRef.get();
if (ref.task != null) {
ref.task.schedule(ref.quietPostPeriodMillis);
}
return ref;
}
private static PrintStream getOutput(String name) {
String OUTPUT = COLLECT_STATISTICS ? System.getProperty("jsch.statistics.output", null) : null; // NOI18N
if (OUTPUT == null) {
return System.out;
}
try {
File dir = new File(OUTPUT);
if (!dir.isDirectory()) {
throw new IOException(OUTPUT + " is not a directory!"); // NOI18N
}
if (!dir.canWrite()) {
throw new IOException(OUTPUT + " is not writable!"); // NOI18N
}
return new PrintStream(new File(dir, name));
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
return System.out;
}
}
@Override
public Boolean call() throws Exception {
if (COLLECT_STATISTICS) {
while (!stopAction()) {
}
PrintStream output = getOutput("totalTraffic"); // NOI18N
try {
trafficCounters.dump(output); // NOI18N
} finally {
if (!output.equals(System.out)) {
output.close();
}
}
}
return true;
}
private static class TrafficCounters {
private final AtomicLong up = new AtomicLong();
private final AtomicLong down = new AtomicLong();
public TrafficCounters() {
if (!COLLECT_STATISTICS) {
return;
}
MeasurableSocketFactory.getInstance().addIOListener(new IOListener() {
@Override
public void bytesUploaded(int bytes) {
up.addAndGet(bytes);
synchronized (trafficDetected) {
trafficDetected.set(true);
trafficDetected.notifyAll();
}
reschedule();
}
@Override
public void bytesDownloaded(int bytes) {
down.addAndGet(bytes);
synchronized (trafficDetected) {
trafficDetected.set(true);
trafficDetected.notifyAll();
}
reschedule();
}
});
}
private void dump(PrintStream out) {
out.println("Total upload traffic [bytes]: " + up.get()); // NOI18N
out.println("Total download traffic [bytes]: " + down.get()); // NOI18N
}
}
private static class RemoteIOListener implements IOListener {
@Override
public void bytesUploaded(int bytes) {
RemoteMeasurementsRef stat = reschedule();
stat.stat.bytesUploaded(bytes);
checkBreakUploads();
}
/** Allows broken upload testing */
private void checkBreakUploads() {
if (BREAK_UPLOADS_FLAG_FILE != null && new File(BREAK_UPLOADS_FLAG_FILE).exists()) {
boolean isOpenW = false;
for (StackTraceElement el : Thread.currentThread().getStackTrace()) {
if (el.getClassName().endsWith(".ChannelSftp")) { // NOI18N
if (el.getMethodName().equals("sendOPENW")) { // NOI18N
isOpenW = true;
break;
}
}
}
if (isOpenW) {
List<ExecutionEnvironment> recentConnections = ConnectionManager.getInstance().getRecentConnections();
for (ExecutionEnvironment env : recentConnections) {
ConnectionManager.getInstance().disconnect(env);
}
}
}
}
@Override
public void bytesDownloaded(int bytes) {
RemoteMeasurementsRef stat = reschedule();
stat.stat.bytesDownloaded(bytes);
}
}
private static class RemoteMeasurementsRef {
private final String name;
private final int quietPostPeriodMillis;
private final Task task;
private final RemoteMeasurements stat;
public RemoteMeasurementsRef(String name, RemoteMeasurements stat, Task task, int quietPostPeriodMillis) {
this.name = name + "_" + System.currentTimeMillis(); // NOI18N
this.task = task;
this.stat = stat;
this.quietPostPeriodMillis = quietPostPeriodMillis;
}
}
}
| 5,100 |
406 | <reponame>israel-dryer/ttkbootstrap
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
class ScrolledText(ttk.Frame):
"""A text widget with a vertical scrollbar."""
def __init__(self, master=None, padding=2, bootstyle=DEFAULT, **kwargs):
"""
Parameters:
master (Widget):
The parent widget.
padding (int):
The amount of empty space to create on the outside of the
widget.
bootstyle (str):
A style keyword used to set the color and style of the vertical
scrollbar. Available options include -> primary, secondary,
success, info, warning, danger, dark, light.
**kwargs (Dict[str, Any]):
Other keyword arguments passed to the `Text` widget.
"""
super().__init__(master, padding=padding)
# setup text widget
kwargs['master'] = self
self._text = ttk.Text(**kwargs)
self._text.pack(side=LEFT, fill=BOTH, expand=YES)
# delegate text methods to frame widget
for method in vars(ttk.Text).keys():
if any(['pack' in method, 'grid' in method, 'place' in method]):
pass
else:
setattr(self, method, getattr(self._text, method))
# setup scrollbar
self._scrollbar = ttk.Scrollbar(
master=self,
bootstyle=bootstyle,
command=self._text.yview
)
self._scrollbar.pack(side=RIGHT, fill=Y)
self._text.configure(yscrollcommand=self._scrollbar.set)
if __name__ == '__main__':
app = ttk.Window()
nb = ttk.Notebook(app)
t = ScrolledText(nb, padding=20, bootstyle='info-round')
t.insert(END, 'What is this?')
nb.add(t, text="My Text")
nb.pack()
app.mainloop()
| 864 |
364 | <gh_stars>100-1000
package com.linkedin.dagli.reducer;
import com.linkedin.dagli.producer.Producer;
import com.linkedin.dagli.transformer.TransformerVariadic;
import java.util.List;
/**
* Reduces the case where a variadic transformer is effectively a no-op (the input is equivalent to the output) when it
* has a single input, in which case the no-op transformer is removed from the graph.
*
* Note that while input should be <em>equivalent</em> to the output, it does not have been satisfy
* {@link Object#equals(Object)}. For example, {@code CompositeSparseVector} is effectively a no-op with a single
* input vector, since even though the output of the transformer would be a different sparse vector, it would be an
* arbitrary re-mapping of the elements (and {@code CompositeSparseVector} does not promise any specific re-mapping).
*
* Conversely, {@code DensifiedVector} is <strong>not</strong> a no-op with a single input (even if that input is a
* dense vector), since it remaps vector elements in a prescribed manner into a contiguous index space.
*/
public class RemoveIfUnaryReducer<R> implements Reducer<TransformerVariadic<? extends R, R>> {
@Override
public Level getLevel() {
return Level.ESSENTIAL; // high value relative to the cost
}
@Override
public void reduce(TransformerVariadic<? extends R, R> target, Context context) {
List<? extends Producer<? extends R>> parents = context.getParents(target);
if (parents.size() == 1) {
context.tryReplaceUnviewed(target, () -> context.getParents(target).get(0));
}
}
@Override
public boolean equals(Object o) {
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return 0x773f771d; // arbitrary random value
}
}
| 523 |
3,638 | /*
* Copyright 2012 GitHub 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.github.mobile.ui.user;
import static com.github.mobile.ui.user.UserViewActivity.TAB_ACTIVITY;
import static com.github.mobile.ui.user.UserViewActivity.TAB_FOLLOWEES;
import static com.github.mobile.ui.user.UserViewActivity.TAB_FOLLOWERS;
import static com.github.mobile.ui.user.UserViewActivity.TAB_REPOSITORIES;
import static com.github.mobile.ui.user.UserViewActivity.TAB_STARS;
import android.content.res.Resources;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import com.github.mobile.R;
import com.github.mobile.ui.FragmentPagerAdapter;
import com.github.mobile.ui.repo.UserOwnedRepositoryListFragment;
import com.github.mobile.ui.repo.UserStarredRepositoryListFragment;
import com.github.mobile.ui.team.TeamListFragment;
/**
* Pager adapter for a user's different views
*/
public class UserPagerAdapter extends FragmentPagerAdapter {
private final boolean isOrg;
private final boolean isMember;
private final Resources resources;
/**
* @param activity
*/
public UserPagerAdapter(final AppCompatActivity activity, final boolean isOrg, final boolean isMember) {
super(activity);
resources = activity.getResources();
this.isOrg = isOrg;
this.isMember = isMember;
}
@Override
public Fragment getItem(final int position) {
switch (position) {
case TAB_ACTIVITY:
return new UserCreatedNewsFragment();
case TAB_REPOSITORIES:
return new UserOwnedRepositoryListFragment();
case TAB_STARS:
return isOrg ? new OrgMembersFragment() : new UserStarredRepositoryListFragment();
case TAB_FOLLOWERS:
return isOrg ? new TeamListFragment() : new UserFollowersFragment();
case TAB_FOLLOWEES:
return new UserFollowingFragment();
default:
return null;
}
}
@Override
public int getCount() {
if (isOrg) {
return isMember ? 4: 3;
}
return 5;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case TAB_ACTIVITY:
return resources.getString(R.string.tab_news);
case TAB_REPOSITORIES:
return resources.getString(R.string.tab_repositories);
case TAB_STARS:
return resources.getString(isOrg ? R.string.tab_members : R.string.tab_stars);
case TAB_FOLLOWERS:
return resources.getString(isOrg ? R.string.tab_teams : R.string.tab_followers);
case TAB_FOLLOWEES:
return resources.getString(R.string.tab_following);
default:
return null;
}
}
}
| 1,255 |
3,372 | <reponame>MC-JY/aws-sdk-java<gh_stars>1000+
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lexmodelsv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Provides configuration information for the AMAZON.KendraSearchIntent intent. When you use this intent, Amazon Lex
* searches the specified Amazon Kendra index and returns documents from the index that match the user's utterance.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/models.lex.v2-2020-08-07/KendraConfiguration" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class KendraConfiguration implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The Amazon Resource Name (ARN) of the Amazon Kendra index that you want the AMAZON.KendraSearchIntent intent to
* search. The index must be in the same account and Region as the Amazon Lex bot.
* </p>
*/
private String kendraIndex;
/**
* <p>
* Determines whether the AMAZON.KendraSearchIntent intent uses a custom query string to query the Amazon Kendra
* index.
* </p>
*/
private Boolean queryFilterStringEnabled;
/**
* <p>
* A query filter that Amazon Lex sends to Amazon Kendra to filter the response from a query. The filter is in the
* format defined by Amazon Kendra. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/filtering.html">Filtering queries</a>.
* </p>
*/
private String queryFilterString;
/**
* <p>
* The Amazon Resource Name (ARN) of the Amazon Kendra index that you want the AMAZON.KendraSearchIntent intent to
* search. The index must be in the same account and Region as the Amazon Lex bot.
* </p>
*
* @param kendraIndex
* The Amazon Resource Name (ARN) of the Amazon Kendra index that you want the AMAZON.KendraSearchIntent
* intent to search. The index must be in the same account and Region as the Amazon Lex bot.
*/
public void setKendraIndex(String kendraIndex) {
this.kendraIndex = kendraIndex;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the Amazon Kendra index that you want the AMAZON.KendraSearchIntent intent to
* search. The index must be in the same account and Region as the Amazon Lex bot.
* </p>
*
* @return The Amazon Resource Name (ARN) of the Amazon Kendra index that you want the AMAZON.KendraSearchIntent
* intent to search. The index must be in the same account and Region as the Amazon Lex bot.
*/
public String getKendraIndex() {
return this.kendraIndex;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the Amazon Kendra index that you want the AMAZON.KendraSearchIntent intent to
* search. The index must be in the same account and Region as the Amazon Lex bot.
* </p>
*
* @param kendraIndex
* The Amazon Resource Name (ARN) of the Amazon Kendra index that you want the AMAZON.KendraSearchIntent
* intent to search. The index must be in the same account and Region as the Amazon Lex bot.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KendraConfiguration withKendraIndex(String kendraIndex) {
setKendraIndex(kendraIndex);
return this;
}
/**
* <p>
* Determines whether the AMAZON.KendraSearchIntent intent uses a custom query string to query the Amazon Kendra
* index.
* </p>
*
* @param queryFilterStringEnabled
* Determines whether the AMAZON.KendraSearchIntent intent uses a custom query string to query the Amazon
* Kendra index.
*/
public void setQueryFilterStringEnabled(Boolean queryFilterStringEnabled) {
this.queryFilterStringEnabled = queryFilterStringEnabled;
}
/**
* <p>
* Determines whether the AMAZON.KendraSearchIntent intent uses a custom query string to query the Amazon Kendra
* index.
* </p>
*
* @return Determines whether the AMAZON.KendraSearchIntent intent uses a custom query string to query the Amazon
* Kendra index.
*/
public Boolean getQueryFilterStringEnabled() {
return this.queryFilterStringEnabled;
}
/**
* <p>
* Determines whether the AMAZON.KendraSearchIntent intent uses a custom query string to query the Amazon Kendra
* index.
* </p>
*
* @param queryFilterStringEnabled
* Determines whether the AMAZON.KendraSearchIntent intent uses a custom query string to query the Amazon
* Kendra index.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KendraConfiguration withQueryFilterStringEnabled(Boolean queryFilterStringEnabled) {
setQueryFilterStringEnabled(queryFilterStringEnabled);
return this;
}
/**
* <p>
* Determines whether the AMAZON.KendraSearchIntent intent uses a custom query string to query the Amazon Kendra
* index.
* </p>
*
* @return Determines whether the AMAZON.KendraSearchIntent intent uses a custom query string to query the Amazon
* Kendra index.
*/
public Boolean isQueryFilterStringEnabled() {
return this.queryFilterStringEnabled;
}
/**
* <p>
* A query filter that Amazon Lex sends to Amazon Kendra to filter the response from a query. The filter is in the
* format defined by Amazon Kendra. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/filtering.html">Filtering queries</a>.
* </p>
*
* @param queryFilterString
* A query filter that Amazon Lex sends to Amazon Kendra to filter the response from a query. The filter is
* in the format defined by Amazon Kendra. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/filtering.html">Filtering queries</a>.
*/
public void setQueryFilterString(String queryFilterString) {
this.queryFilterString = queryFilterString;
}
/**
* <p>
* A query filter that Amazon Lex sends to Amazon Kendra to filter the response from a query. The filter is in the
* format defined by Amazon Kendra. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/filtering.html">Filtering queries</a>.
* </p>
*
* @return A query filter that Amazon Lex sends to Amazon Kendra to filter the response from a query. The filter is
* in the format defined by Amazon Kendra. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/filtering.html">Filtering queries</a>.
*/
public String getQueryFilterString() {
return this.queryFilterString;
}
/**
* <p>
* A query filter that Amazon Lex sends to Amazon Kendra to filter the response from a query. The filter is in the
* format defined by Amazon Kendra. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/filtering.html">Filtering queries</a>.
* </p>
*
* @param queryFilterString
* A query filter that Amazon Lex sends to Amazon Kendra to filter the response from a query. The filter is
* in the format defined by Amazon Kendra. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/filtering.html">Filtering queries</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KendraConfiguration withQueryFilterString(String queryFilterString) {
setQueryFilterString(queryFilterString);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getKendraIndex() != null)
sb.append("KendraIndex: ").append(getKendraIndex()).append(",");
if (getQueryFilterStringEnabled() != null)
sb.append("QueryFilterStringEnabled: ").append(getQueryFilterStringEnabled()).append(",");
if (getQueryFilterString() != null)
sb.append("QueryFilterString: ").append(getQueryFilterString());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof KendraConfiguration == false)
return false;
KendraConfiguration other = (KendraConfiguration) obj;
if (other.getKendraIndex() == null ^ this.getKendraIndex() == null)
return false;
if (other.getKendraIndex() != null && other.getKendraIndex().equals(this.getKendraIndex()) == false)
return false;
if (other.getQueryFilterStringEnabled() == null ^ this.getQueryFilterStringEnabled() == null)
return false;
if (other.getQueryFilterStringEnabled() != null && other.getQueryFilterStringEnabled().equals(this.getQueryFilterStringEnabled()) == false)
return false;
if (other.getQueryFilterString() == null ^ this.getQueryFilterString() == null)
return false;
if (other.getQueryFilterString() != null && other.getQueryFilterString().equals(this.getQueryFilterString()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getKendraIndex() == null) ? 0 : getKendraIndex().hashCode());
hashCode = prime * hashCode + ((getQueryFilterStringEnabled() == null) ? 0 : getQueryFilterStringEnabled().hashCode());
hashCode = prime * hashCode + ((getQueryFilterString() == null) ? 0 : getQueryFilterString().hashCode());
return hashCode;
}
@Override
public KendraConfiguration clone() {
try {
return (KendraConfiguration) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.lexmodelsv2.model.transform.KendraConfigurationMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| 4,149 |
830 | # Copyright 2021 JD.com, Inc., JD AI
"""
@author: <NAME>
@contact: <EMAIL>
"""
from abc import ABCMeta, abstractmethod
import torch
import torch.nn as nn
from torch.autograd import Variable
from xmodaler.config import kfg
__all__ = ["Decoder"]
class Decoder(nn.Module, metaclass=ABCMeta):
def __init__(self):
super().__init__()
@abstractmethod
def forward(self):
pass
def preprocess(self, batched_inputs):
return batched_inputs
def init_states(self, batch_size):
return {
kfg.G_HIDDEN_STATES: [Variable(torch.zeros(batch_size, self.hidden_size).cuda()) for _ in range(self.num_layers)],
kfg.G_CELL_STATES: [Variable(torch.zeros(batch_size, self.hidden_size).cuda()) for _ in range(self.num_layers)]
}
| 328 |
7,629 | <reponame>FeliciaLim/oss-fuzz
/* Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <sys_defs.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <vstring.h>
#include "lex_822.h"
#include "quote_822_local.h"
#include "tok822.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);
int
LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
char *new_str = (char *)malloc(size+1);
if (new_str == NULL){
return 0;
}
memcpy(new_str, data, size);
new_str[size] = '\0';
VSTRING *vp = vstring_alloc(100);
TOK822 *list = NULL;
list = tok822_parse_limit(new_str, 10);
tok822_internalize(vp, list, TOK822_STR_DEFL);
tok822_externalize(vp, list,TOK822_STR_DEFL | TOK822_STR_TRNC);
tok822_externalize(vp, list,TOK822_STR_DEFL | TOK822_STR_LINE | TOK822_STR_TRNC);
tok822_free_tree(list);
vstring_free(vp);
free(new_str);
return 0;
}
| 592 |
903 | <filename>jphp-core/src/org/develnext/jphp/core/compiler/jvm/statement/expr/EchoRawCompiler.java
package org.develnext.jphp.core.compiler.jvm.statement.expr;
import org.develnext.jphp.core.compiler.jvm.statement.ExpressionStmtCompiler;
import org.develnext.jphp.core.tokenizer.token.stmt.EchoRawToken;
import php.runtime.env.Environment;
public class EchoRawCompiler extends BaseStatementCompiler<EchoRawToken> {
public EchoRawCompiler(ExpressionStmtCompiler exprCompiler) {
super(exprCompiler);
}
@Override
public void write(EchoRawToken token) {
if (!token.getMeta().getWord().isEmpty()){
expr.writePushEnv();
expr.writePushString(token.getMeta().getWord());
expr.writeSysDynamicCall(Environment.class, "echo", void.class, String.class);
}
}
}
| 325 |
491 | <reponame>rahulchaudhary2244/encog-java-core
/*
* Encog(tm) Core v3.4 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2017 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.ml.train.strategy.end;
/*
* Encog(tm) Core v3.3 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2014 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
import org.encog.Encog;
import org.encog.ml.MLRegression;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.train.MLTrain;
import org.encog.ml.train.strategy.end.EndTrainingStrategy;
import org.encog.util.obj.SerializeObject;
import org.encog.util.simple.EncogUtility;
import java.io.Serializable;
/**
* A simple early stopping strategy that halts training when the training set no longer improves.
*/
public class StoppingStrategy implements EndTrainingStrategy {
/**
* The trainer.
*/
private MLTrain train;
/**
* Has training stopped.
*/
private boolean stop;
/**
* Current validation error.
*/
private double lastError;
/**
* The model that is being trained.
*/
private MLRegression model;
/**
* The number of iterations that the validation is allowed to remain stagnant/degrading for.
*/
private int allowedStagnantIterations;
private int stagnantIterations;
/**
* The best model so far.
*/
private MLRegression bestModel;
private boolean saveBest;
private double bestError;
private double minimumImprovement = Encog.DEFAULT_DOUBLE_EQUAL;
public StoppingStrategy(MLDataSet theValidationSet) {
this(50);
}
public StoppingStrategy(int theAllowedStagnantIterations) {
this.allowedStagnantIterations = theAllowedStagnantIterations;
}
/**
* {@inheritDoc}
*/
@Override
public void init(MLTrain theTrain) {
this.train = theTrain;
this.model = (MLRegression) train.getMethod();
this.stop = false;
this.lastError = Double.POSITIVE_INFINITY;
}
/**
* {@inheritDoc}
*/
@Override
public void preIteration() {
}
/**
* {@inheritDoc}
*/
@Override
public void postIteration() {
double trainingError = this.train.getError();
double improve = this.bestError-trainingError;
improve = Math.max(improve,0);
if( Double.isInfinite(trainingError) || Double.isNaN(trainingError) ) {
stop = true;
} else if( this.bestError<=trainingError
&& !Double.isInfinite(this.lastError)
&& improve<this.minimumImprovement) {
// No improvement
this.stagnantIterations++;
if(this.stagnantIterations>this.allowedStagnantIterations) {
stop = true;
}
} else {
// Improvement
if( this.saveBest ) {
this.bestModel = (MLRegression) SerializeObject.serializeClone((Serializable) this.model);
}
this.bestError = trainingError;
this.stagnantIterations=0;
}
this.lastError = trainingError;
}
/**
* @return Returns true if we should stop.
*/
@Override
public boolean shouldStop() {
return stop;
}
public int getStagnantIterations() {
return stagnantIterations;
}
public void setStagnantIterations(int stagnantIterations) {
this.stagnantIterations = stagnantIterations;
}
public int getAllowedStagnantIterations() {
return allowedStagnantIterations;
}
public void setAllowedStagnantIterations(int allowedStagnantIterations) {
this.allowedStagnantIterations = allowedStagnantIterations;
}
public boolean isSaveBest() {
return saveBest;
}
public void setSaveBest(boolean saveBest) {
this.saveBest = saveBest;
}
public MLRegression getBestModel() {
return bestModel;
}
public double getMinimumImprovement() {
return minimumImprovement;
}
public void setMinimumImprovement(double minimumImprovement) {
this.minimumImprovement = minimumImprovement;
}
}
| 2,074 |
743 | package pl.allegro.tech.hermes.consumers.queue;
import org.jctools.queues.MessagePassingQueue;
public interface MpscQueue<T> {
boolean offer(T element);
void drain(MessagePassingQueue.Consumer<T> consumer);
int size();
int capacity();
}
| 90 |
1,144 | <filename>backend/de.metas.util/src/main/java/org/adempiere/util/proxy/impl/InvocationContext.java
package org.adempiere.util.proxy.impl;
/*
* #%L
* de.metas.util
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.adempiere.util.proxy.IInvocationContext;
import com.google.common.base.Throwables;
/* package */final class InvocationContext implements IInvocationContext
{
private final Method method;
private final Object[] methodArgs;
private final Object target;
public InvocationContext(final Method method, final Object[] methodArgs, final Object target)
{
super();
this.method = method;
this.methodArgs = methodArgs;
this.target = target;
}
@Override
public String toString()
{
return "InvocationContext ["
+ "method=" + method
+ ", args=" + Arrays.toString(methodArgs)
+ ", target=" + target
+ "]";
}
@Override
public Object proceed() throws Throwable
{
if (!method.isAccessible())
{
method.setAccessible(true);
}
try
{
return method.invoke(target, methodArgs);
}
catch (InvocationTargetException ite)
{
// unwrap the target implementation's exception to that it can be caught
throw ite.getTargetException();
}
}
@Override
public Object call() throws Exception
{
try
{
final Object result = proceed();
return result == null ? NullResult : result;
}
catch (Exception e)
{
throw e;
}
catch (Throwable e)
{
Throwables.propagateIfPossible(e);
throw Throwables.propagate(e);
}
}
@Override
public Object getTarget()
{
return target;
}
@Override
public Object[] getParameters()
{
return methodArgs;
}
@Override
public Method getMethod()
{
return method;
}
}
| 828 |
2,399 | /*
* 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.commons.lang3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.Test;
/**
* Unit tests {@link org.apache.commons.lang3.CharRange}.
*/
public class CharRangeTest {
@Test
public void testClass() {
// class changed to non-public in 3.0
assertFalse(Modifier.isPublic(CharRange.class.getModifiers()));
assertTrue(Modifier.isFinal(CharRange.class.getModifiers()));
}
@Test
public void testConstructorAccessors_is() {
final CharRange rangea = CharRange.is('a');
assertEquals('a', rangea.getStart());
assertEquals('a', rangea.getEnd());
assertFalse(rangea.isNegated());
assertEquals("a", rangea.toString());
}
@Test
public void testConstructorAccessors_isNot() {
final CharRange rangea = CharRange.isNot('a');
assertEquals('a', rangea.getStart());
assertEquals('a', rangea.getEnd());
assertTrue(rangea.isNegated());
assertEquals("^a", rangea.toString());
}
@Test
public void testConstructorAccessors_isIn_Same() {
final CharRange rangea = CharRange.isIn('a', 'a');
assertEquals('a', rangea.getStart());
assertEquals('a', rangea.getEnd());
assertFalse(rangea.isNegated());
assertEquals("a", rangea.toString());
}
@Test
public void testConstructorAccessors_isIn_Normal() {
final CharRange rangea = CharRange.isIn('a', 'e');
assertEquals('a', rangea.getStart());
assertEquals('e', rangea.getEnd());
assertFalse(rangea.isNegated());
assertEquals("a-e", rangea.toString());
}
@Test
public void testConstructorAccessors_isIn_Reversed() {
final CharRange rangea = CharRange.isIn('e', 'a');
assertEquals('a', rangea.getStart());
assertEquals('e', rangea.getEnd());
assertFalse(rangea.isNegated());
assertEquals("a-e", rangea.toString());
}
@Test
public void testConstructorAccessors_isNotIn_Same() {
final CharRange rangea = CharRange.isNotIn('a', 'a');
assertEquals('a', rangea.getStart());
assertEquals('a', rangea.getEnd());
assertTrue(rangea.isNegated());
assertEquals("^a", rangea.toString());
}
@Test
public void testConstructorAccessors_isNotIn_Normal() {
final CharRange rangea = CharRange.isNotIn('a', 'e');
assertEquals('a', rangea.getStart());
assertEquals('e', rangea.getEnd());
assertTrue(rangea.isNegated());
assertEquals("^a-e", rangea.toString());
}
@Test
public void testConstructorAccessors_isNotIn_Reversed() {
final CharRange rangea = CharRange.isNotIn('e', 'a');
assertEquals('a', rangea.getStart());
assertEquals('e', rangea.getEnd());
assertTrue(rangea.isNegated());
assertEquals("^a-e", rangea.toString());
}
@Test
public void testEquals_Object() {
final CharRange rangea = CharRange.is('a');
final CharRange rangeae = CharRange.isIn('a', 'e');
final CharRange rangenotbf = CharRange.isIn('b', 'f');
assertNotEquals(null, rangea);
assertEquals(rangea, rangea);
assertEquals(rangea, CharRange.is('a'));
assertEquals(rangeae, rangeae);
assertEquals(rangeae, CharRange.isIn('a', 'e'));
assertEquals(rangenotbf, rangenotbf);
assertEquals(rangenotbf, CharRange.isIn('b', 'f'));
assertNotEquals(rangea, rangeae);
assertNotEquals(rangea, rangenotbf);
assertNotEquals(rangeae, rangea);
assertNotEquals(rangeae, rangenotbf);
assertNotEquals(rangenotbf, rangea);
assertNotEquals(rangenotbf, rangeae);
}
@Test
public void testHashCode() {
final CharRange rangea = CharRange.is('a');
final CharRange rangeae = CharRange.isIn('a', 'e');
final CharRange rangenotbf = CharRange.isIn('b', 'f');
assertEquals(rangea.hashCode(), rangea.hashCode());
assertEquals(rangea.hashCode(), CharRange.is('a').hashCode());
assertEquals(rangeae.hashCode(), rangeae.hashCode());
assertEquals(rangeae.hashCode(), CharRange.isIn('a', 'e').hashCode());
assertEquals(rangenotbf.hashCode(), rangenotbf.hashCode());
assertEquals(rangenotbf.hashCode(), CharRange.isIn('b', 'f').hashCode());
assertNotEquals(rangea.hashCode(), rangeae.hashCode());
assertNotEquals(rangea.hashCode(), rangenotbf.hashCode());
assertNotEquals(rangeae.hashCode(), rangea.hashCode());
assertNotEquals(rangeae.hashCode(), rangenotbf.hashCode());
assertNotEquals(rangenotbf.hashCode(), rangea.hashCode());
assertNotEquals(rangenotbf.hashCode(), rangeae.hashCode());
}
@Test
public void testContains_Char() {
CharRange range = CharRange.is('c');
assertFalse(range.contains('b'));
assertTrue(range.contains('c'));
assertFalse(range.contains('d'));
assertFalse(range.contains('e'));
range = CharRange.isIn('c', 'd');
assertFalse(range.contains('b'));
assertTrue(range.contains('c'));
assertTrue(range.contains('d'));
assertFalse(range.contains('e'));
range = CharRange.isIn('d', 'c');
assertFalse(range.contains('b'));
assertTrue(range.contains('c'));
assertTrue(range.contains('d'));
assertFalse(range.contains('e'));
range = CharRange.isNotIn('c', 'd');
assertTrue(range.contains('b'));
assertFalse(range.contains('c'));
assertFalse(range.contains('d'));
assertTrue(range.contains('e'));
assertTrue(range.contains((char) 0));
assertTrue(range.contains(Character.MAX_VALUE));
}
@Test
public void testContains_Charrange() {
final CharRange a = CharRange.is('a');
final CharRange b = CharRange.is('b');
final CharRange c = CharRange.is('c');
final CharRange c2 = CharRange.is('c');
final CharRange d = CharRange.is('d');
final CharRange e = CharRange.is('e');
final CharRange cd = CharRange.isIn('c', 'd');
final CharRange bd = CharRange.isIn('b', 'd');
final CharRange bc = CharRange.isIn('b', 'c');
final CharRange ab = CharRange.isIn('a', 'b');
final CharRange de = CharRange.isIn('d', 'e');
final CharRange ef = CharRange.isIn('e', 'f');
final CharRange ae = CharRange.isIn('a', 'e');
// normal/normal
assertFalse(c.contains(b));
assertTrue(c.contains(c));
assertTrue(c.contains(c2));
assertFalse(c.contains(d));
assertFalse(c.contains(cd));
assertFalse(c.contains(bd));
assertFalse(c.contains(bc));
assertFalse(c.contains(ab));
assertFalse(c.contains(de));
assertTrue(cd.contains(c));
assertTrue(bd.contains(c));
assertTrue(bc.contains(c));
assertFalse(ab.contains(c));
assertFalse(de.contains(c));
assertTrue(ae.contains(b));
assertTrue(ae.contains(ab));
assertTrue(ae.contains(bc));
assertTrue(ae.contains(cd));
assertTrue(ae.contains(de));
final CharRange notb = CharRange.isNot('b');
final CharRange notc = CharRange.isNot('c');
final CharRange notd = CharRange.isNot('d');
final CharRange notab = CharRange.isNotIn('a', 'b');
final CharRange notbc = CharRange.isNotIn('b', 'c');
final CharRange notbd = CharRange.isNotIn('b', 'd');
final CharRange notcd = CharRange.isNotIn('c', 'd');
final CharRange notde = CharRange.isNotIn('d', 'e');
final CharRange notae = CharRange.isNotIn('a', 'e');
final CharRange all = CharRange.isIn((char) 0, Character.MAX_VALUE);
final CharRange allbutfirst = CharRange.isIn((char) 1, Character.MAX_VALUE);
// normal/negated
assertFalse(c.contains(notc));
assertFalse(c.contains(notbd));
assertTrue(all.contains(notc));
assertTrue(all.contains(notbd));
assertFalse(allbutfirst.contains(notc));
assertFalse(allbutfirst.contains(notbd));
// negated/normal
assertTrue(notc.contains(a));
assertTrue(notc.contains(b));
assertFalse(notc.contains(c));
assertTrue(notc.contains(d));
assertTrue(notc.contains(e));
assertTrue(notc.contains(ab));
assertFalse(notc.contains(bc));
assertFalse(notc.contains(bd));
assertFalse(notc.contains(cd));
assertTrue(notc.contains(de));
assertFalse(notc.contains(ae));
assertFalse(notc.contains(all));
assertFalse(notc.contains(allbutfirst));
assertTrue(notbd.contains(a));
assertFalse(notbd.contains(b));
assertFalse(notbd.contains(c));
assertFalse(notbd.contains(d));
assertTrue(notbd.contains(e));
assertTrue(notcd.contains(ab));
assertFalse(notcd.contains(bc));
assertFalse(notcd.contains(bd));
assertFalse(notcd.contains(cd));
assertFalse(notcd.contains(de));
assertFalse(notcd.contains(ae));
assertTrue(notcd.contains(ef));
assertFalse(notcd.contains(all));
assertFalse(notcd.contains(allbutfirst));
// negated/negated
assertFalse(notc.contains(notb));
assertTrue(notc.contains(notc));
assertFalse(notc.contains(notd));
assertFalse(notc.contains(notab));
assertTrue(notc.contains(notbc));
assertTrue(notc.contains(notbd));
assertTrue(notc.contains(notcd));
assertFalse(notc.contains(notde));
assertFalse(notbd.contains(notb));
assertFalse(notbd.contains(notc));
assertFalse(notbd.contains(notd));
assertFalse(notbd.contains(notab));
assertFalse(notbd.contains(notbc));
assertTrue(notbd.contains(notbd));
assertFalse(notbd.contains(notcd));
assertFalse(notbd.contains(notde));
assertTrue(notbd.contains(notae));
}
@Test
public void testContainsNullArg() {
final CharRange range = CharRange.is('a');
final NullPointerException e = assertThrows(NullPointerException.class, () -> range.contains(null));
assertEquals("range", e.getMessage());
}
@Test
public void testIterator() {
final CharRange a = CharRange.is('a');
final CharRange ad = CharRange.isIn('a', 'd');
final CharRange nota = CharRange.isNot('a');
final CharRange emptySet = CharRange.isNotIn((char) 0, Character.MAX_VALUE);
final CharRange notFirst = CharRange.isNotIn((char) 1, Character.MAX_VALUE);
final CharRange notLast = CharRange.isNotIn((char) 0, (char) (Character.MAX_VALUE - 1));
final Iterator<Character> aIt = a.iterator();
assertNotNull(aIt);
assertTrue(aIt.hasNext());
assertEquals(Character.valueOf('a'), aIt.next());
assertFalse(aIt.hasNext());
final Iterator<Character> adIt = ad.iterator();
assertNotNull(adIt);
assertTrue(adIt.hasNext());
assertEquals(Character.valueOf('a'), adIt.next());
assertEquals(Character.valueOf('b'), adIt.next());
assertEquals(Character.valueOf('c'), adIt.next());
assertEquals(Character.valueOf('d'), adIt.next());
assertFalse(adIt.hasNext());
final Iterator<Character> notaIt = nota.iterator();
assertNotNull(notaIt);
assertTrue(notaIt.hasNext());
while (notaIt.hasNext()) {
final Character c = notaIt.next();
assertNotEquals('a', c.charValue());
}
final Iterator<Character> emptySetIt = emptySet.iterator();
assertNotNull(emptySetIt);
assertFalse(emptySetIt.hasNext());
assertThrows(NoSuchElementException.class, emptySetIt::next);
final Iterator<Character> notFirstIt = notFirst.iterator();
assertNotNull(notFirstIt);
assertTrue(notFirstIt.hasNext());
assertEquals(Character.valueOf((char) 0), notFirstIt.next());
assertFalse(notFirstIt.hasNext());
assertThrows(NoSuchElementException.class, notFirstIt::next);
final Iterator<Character> notLastIt = notLast.iterator();
assertNotNull(notLastIt);
assertTrue(notLastIt.hasNext());
assertEquals(Character.valueOf(Character.MAX_VALUE), notLastIt.next());
assertFalse(notLastIt.hasNext());
assertThrows(NoSuchElementException.class, notLastIt::next);
}
@Test
public void testSerialization() {
CharRange range = CharRange.is('a');
assertEquals(range, SerializationUtils.clone(range));
range = CharRange.isIn('a', 'e');
assertEquals(range, SerializationUtils.clone(range));
range = CharRange.isNotIn('a', 'e');
assertEquals(range, SerializationUtils.clone(range));
}
@Test
public void testIteratorRemove() {
final CharRange a = CharRange.is('a');
final Iterator<Character> aIt = a.iterator();
assertThrows(UnsupportedOperationException.class, aIt::remove);
}
}
| 6,045 |
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.openide.loaders;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.netbeans.junit.MockServices;
import org.netbeans.junit.NbTestCase;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileSystem;
import org.openide.filesystems.FileUtil;
import org.openide.nodes.Node;
import org.openide.nodes.NodeAdapter;
import org.openide.nodes.NodeListener;
import org.openide.nodes.NodeReorderEvent;
import org.openide.util.Enumerations;
import org.openide.util.test.TestFileUtils;
/** Does a change in order on folder fire the right properties?
*
* @author <NAME>, <NAME>
*/
public class DataFolderTimeOrderTest extends NbTestCase implements PropertyChangeListener {
private DataFolder aa;
private final ArrayList<String> events = new ArrayList<String>();
private static FileSystem lfs;
public DataFolderTimeOrderTest (String name) {
super (name);
}
@Override
protected Level logLevel() {
return Level.FINE;
}
@Override
protected void setUp () throws Exception {
clearWorkDir();
MockServices.setServices(Pool.class);
String fsstruct [] = new String [] {
"AA/X.txt",
"AA/Y.txt",
};
lfs = TestUtilHid.createLocalFileSystem (getWorkDir (), fsstruct);
final FileObject x = lfs.findResource("AA/X.txt");
assertNotNull("X.txt", x);
Thread.sleep(5);
final FileObject y = lfs.findResource("AA/Y.txt");
assertNotNull("Y.txt", y);
OutputStream os = y.getOutputStream();
os.write("Ahoj".getBytes());
os.close();
org.openide.filesystems.test.TestFileUtils.touch(y, x);
aa = DataFolder.findFolder (lfs.findResource ("AA"));
aa.addPropertyChangeListener (this);
}
@Override
protected void tearDown () throws Exception {
final DataLoader l = DataLoader.getLoader(DataObjectInvalidationTest.SlowDataLoader.class);
aa.removePropertyChangeListener (this);
}
public void testLastModifiedOrderUpdatedAfterFileIsTouched() throws Exception {
aa.setSortMode(DataFolder.SortMode.LAST_MODIFIED);
Node n = aa.getNodeDelegate().cloneNode();
Node[] nodes = n.getChildren().getNodes(true);
assertEquals ("Two nodes", 2, nodes.length);
waitEvents();
assertEquals("Sort mode not changed and children not refreshed: " + events, 2, events.size());
assertTrue(DataFolder.PROP_SORT_MODE + " change not fired", events.contains(DataFolder.PROP_SORT_MODE));
assertTrue(DataFolder.PROP_CHILDREN + " change not fired", events.contains(DataFolder.PROP_CHILDREN));
assertEquals("Y.txt", nodes[0].getName()); // Y is newer
assertEquals("X.txt", nodes[1].getName()); // X is older
events.clear();
final FileObject orig = lfs.findResource("AA/Y.txt");
final FileObject touch = lfs.findResource("AA/X.txt");
// After touching, X.txt will be newer than Y.txt.
TestFileUtils.touch(FileUtil.toFile(touch), FileUtil.toFile(orig));
// It's not enough to wait only for DataFolder event
// because of number of RP tasks run before node children are updated
// must wait for reorder fired by node itself.
final CountDownLatch barrier = new CountDownLatch(1);
NodeListener nodeList = new NodeAdapter() {
@Override
public void childrenReordered (NodeReorderEvent ev) {
barrier.countDown();
}
};
n.addNodeListener(nodeList);
try {
touch.refresh();
waitEvents();
// wait for node reorder event
barrier.await(10, TimeUnit.SECONDS);
} finally {
n.removeNodeListener(nodeList);
}
assertEquals(0, barrier.getCount());
assertTrue(DataFolder.PROP_CHILDREN + " change not fired", events.contains(DataFolder.PROP_CHILDREN));
Node[] newNodes = n.getChildren().getNodes(true);
assertEquals("Node " + nodes[1].getName() + " expected first.", newNodes[0], nodes[1]);
assertEquals("Node " + nodes[0].getName() + " expected second.", newNodes[1], nodes[0]);
}
/** Wait for events list not empty. */
private void waitEvents() throws Exception {
for (int delay = 1; delay < 3000; delay *= 2) {
Thread.sleep(delay);
if (!events.isEmpty()) {
break;
}
}
}
@Override
public synchronized void propertyChange (PropertyChangeEvent evt) {
events.add (evt.getPropertyName ());
}
public static final class Pool extends DataLoaderPool {
@Override
protected Enumeration<? extends org.openide.loaders.DataLoader> loaders() {
return Enumerations.singleton(DataLoader.getLoader(DataObjectInvalidationTest.SlowDataLoader.class));
}
} // end of Pool
}
| 2,317 |
5,238 | #include "../lv_examples.h"
#if LV_USE_BTN && LV_BUILD_EXAMPLES
static lv_style_t style_btn;
static lv_style_t style_btn_pressed;
static lv_style_t style_btn_red;
static lv_color_t darken(const lv_color_filter_dsc_t * dsc, lv_color_t color, lv_opa_t opa)
{
LV_UNUSED(dsc);
return lv_color_darken(color, opa);
}
static void style_init(void)
{
/*Create a simple button style*/
lv_style_init(&style_btn);
lv_style_set_radius(&style_btn, 10);
lv_style_set_bg_opa(&style_btn, LV_OPA_COVER);
lv_style_set_bg_color(&style_btn, lv_palette_lighten(LV_PALETTE_GREY, 3));
lv_style_set_bg_grad_color(&style_btn, lv_palette_main(LV_PALETTE_GREY));
lv_style_set_bg_grad_dir(&style_btn, LV_GRAD_DIR_VER);
lv_style_set_border_color(&style_btn, lv_color_black());
lv_style_set_border_opa(&style_btn, LV_OPA_20);
lv_style_set_border_width(&style_btn, 2);
lv_style_set_text_color(&style_btn, lv_color_black());
/*Create a style for the pressed state.
*Use a color filter to simply modify all colors in this state*/
static lv_color_filter_dsc_t color_filter;
lv_color_filter_dsc_init(&color_filter, darken);
lv_style_init(&style_btn_pressed);
lv_style_set_color_filter_dsc(&style_btn_pressed, &color_filter);
lv_style_set_color_filter_opa(&style_btn_pressed, LV_OPA_20);
/*Create a red style. Change only some colors.*/
lv_style_init(&style_btn_red);
lv_style_set_bg_color(&style_btn_red, lv_palette_main(LV_PALETTE_RED));
lv_style_set_bg_grad_color(&style_btn_red, lv_palette_lighten(LV_PALETTE_RED, 3));
}
/**
* Create styles from scratch for buttons.
*/
void lv_example_get_started_2(void)
{
/*Initialize the style*/
style_init();
/*Create a button and use the new styles*/
lv_obj_t * btn = lv_btn_create(lv_scr_act());
/* Remove the styles coming from the theme
* Note that size and position are also stored as style properties
* so lv_obj_remove_style_all will remove the set size and position too */
lv_obj_remove_style_all(btn);
lv_obj_set_pos(btn, 10, 10);
lv_obj_set_size(btn, 120, 50);
lv_obj_add_style(btn, &style_btn, 0);
lv_obj_add_style(btn, &style_btn_pressed, LV_STATE_PRESSED);
/*Add a label to the button*/
lv_obj_t * label = lv_label_create(btn);
lv_label_set_text(label, "Button");
lv_obj_center(label);
/*Create an other button and use the red style too*/
lv_obj_t * btn2 = lv_btn_create(lv_scr_act());
lv_obj_remove_style_all(btn2); /*Remove the styles coming from the theme*/
lv_obj_set_pos(btn2, 10, 80);
lv_obj_set_size(btn2, 120, 50);
lv_obj_add_style(btn2, &style_btn, 0);
lv_obj_add_style(btn2, &style_btn_red, 0);
lv_obj_add_style(btn2, &style_btn_pressed, LV_STATE_PRESSED);
lv_obj_set_style_radius(btn2, LV_RADIUS_CIRCLE, 0); /*Add a local style too*/
label = lv_label_create(btn2);
lv_label_set_text(label, "Button 2");
lv_obj_center(label);
}
#endif
| 1,328 |
378 | <filename>server/openejb-client/src/main/java/org/apache/openejb/client/EJBHomeHandle.java
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openejb.client;
import javax.ejb.EJBHome;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.rmi.RemoteException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
public class EJBHomeHandle implements java.io.Externalizable, javax.ejb.HomeHandle {
private static final long serialVersionUID = -5221661986423761808L;
protected transient EJBHomeProxy ejbHomeProxy;
protected transient EJBHomeHandler handler;
private transient ProtocolMetaData metaData;
public EJBHomeHandle() {
}
public EJBHomeHandle(final EJBHomeProxy proxy) {
this.ejbHomeProxy = proxy;
this.handler = ejbHomeProxy.getEJBHomeHandler();
}
public void setMetaData(final ProtocolMetaData metaData) {
this.metaData = metaData;
}
protected void setEJBHomeProxy(final EJBHomeProxy ejbHomeProxy) {
this.ejbHomeProxy = ejbHomeProxy;
this.handler = ejbHomeProxy.getEJBHomeHandler();
}
@Override
public EJBHome getEJBHome() throws RemoteException {
return ejbHomeProxy;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
// write out the version of the serialized data for future use
out.writeByte(2);
final boolean hasExec = handler.executor != null && handler.executor != JNDIContext.globalExecutor();
out.writeBoolean(hasExec);
if (hasExec) {
out.writeInt(handler.executor.getMaximumPoolSize());
final BlockingQueue<Runnable> queue = handler.executor.getQueue();
out.writeInt(queue.size() + queue.remainingCapacity());
}
handler.client.setMetaData(metaData);
handler.client.writeExternal(out);
final EJBMetaDataImpl ejb = handler.ejb;
out.writeObject(getClassName(ejb.homeClass));
out.writeObject(getClassName(ejb.remoteClass));
out.writeObject(getClassName(ejb.keyClass));
out.writeByte(ejb.type);
out.writeUTF(ejb.deploymentID);
out.writeShort(ejb.deploymentCode);
handler.server.setMetaData(metaData);
handler.server.writeExternal(out);
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
final byte version = in.readByte(); // future use
ThreadPoolExecutor executorService;
if (version > 1) {
if (in.readBoolean()) {
final int queue = in.readInt();
final BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<Runnable>((queue < 2 ? 2 : queue));
final int threads = in.readInt();
executorService = JNDIContext.newExecutor(threads, blockingQueue);
} else {
executorService = null;
}
} else {
executorService = JNDIContext.globalExecutor();
}
final ClientMetaData client = new ClientMetaData();
final EJBMetaDataImpl ejb = new EJBMetaDataImpl();
final ServerMetaData server = new ServerMetaData();
client.setMetaData(metaData);
client.readExternal(in);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
}
ejb.homeClass = loadClass(classLoader, (String) in.readObject());
ejb.remoteClass = loadClass(classLoader, (String) in.readObject());
ejb.keyClass = loadClass(classLoader, (String) in.readObject());
ejb.type = in.readByte();
ejb.deploymentID = in.readUTF();
ejb.deploymentCode = in.readShort();
server.setMetaData(metaData);
server.readExternal(in);
handler = EJBHomeHandler.createEJBHomeHandler(executorService, ejb, server, client, null);
ejbHomeProxy = handler.createEJBHomeProxy();
}
private static String getClassName(final Class clazz) {
return (clazz == null) ? null : clazz.getName();
}
private static Class loadClass(final ClassLoader classLoader, final String homeClassName) throws ClassNotFoundException {
return (homeClassName == null) ? null : Class.forName(homeClassName, true, classLoader);
}
}
| 1,977 |
1,109 | <gh_stars>1000+
/*******************************************************************************
* Copyright 2016 Intuit
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.intuit.wasabi.assignmentobjects;
import com.intuit.hyrule.Rule;
import com.intuit.wasabi.experimentobjects.Experiment;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class RuleCache {
// FIXME cache can only grow, we need to add a delete routine that removes rule objects for terminated/deleted experiments
// Default 16 standard concurrency update level used
private Map<Experiment.ID, Rule> ruleCache = new ConcurrentHashMap<>();
public void setRule(Experiment.ID key, Rule rule) {
ruleCache.put(key, rule);
}
public Rule getRule(Experiment.ID key) {
return ruleCache.get(key);
}
public boolean containsRule(Experiment.ID key) {
return ruleCache.containsKey(key);
}
public void clearRule(Experiment.ID key) {
ruleCache.remove(key);
}
}
| 469 |
507 | // +build android
#include <android/log.h>
#include <dirent.h>
#include <jni.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define LOG_FATAL(...) __android_log_print(ANDROID_LOG_FATAL, "Fyne", __VA_ARGS__)
static jclass find_class(JNIEnv *env, const char *class_name) {
jclass clazz = (*env)->FindClass(env, class_name);
if (clazz == NULL) {
(*env)->ExceptionClear(env);
LOG_FATAL("cannot find %s", class_name);
return NULL;
}
return clazz;
}
static jmethodID find_method(JNIEnv *env, jclass clazz, const char *name, const char *sig) {
jmethodID m = (*env)->GetMethodID(env, clazz, name, sig);
if (m == 0) {
(*env)->ExceptionClear(env);
LOG_FATAL("cannot find method %s %s", name, sig);
return 0;
}
return m;
}
static jmethodID find_static_method(JNIEnv *env, jclass clazz, const char *name, const char *sig) {
jmethodID m = (*env)->GetStaticMethodID(env, clazz, name, sig);
if (m == 0) {
(*env)->ExceptionClear(env);
LOG_FATAL("cannot find method %s %s", name, sig);
return 0;
}
return m;
}
char* getString(uintptr_t jni_env, uintptr_t ctx, jstring str) {
JNIEnv *env = (JNIEnv*)jni_env;
const char *chars = (*env)->GetStringUTFChars(env, str, NULL);
const char *copy = strdup(chars);
(*env)->ReleaseStringUTFChars(env, str, chars);
return copy;
}
jobject parseURI(uintptr_t jni_env, uintptr_t ctx, char* uriCstr) {
JNIEnv *env = (JNIEnv*)jni_env;
jstring uriStr = (*env)->NewStringUTF(env, uriCstr);
jclass uriClass = find_class(env, "android/net/Uri");
jmethodID parse = find_static_method(env, uriClass, "parse", "(Ljava/lang/String;)Landroid/net/Uri;");
return (jobject)(*env)->CallStaticObjectMethod(env, uriClass, parse, uriStr);
}
// clipboard
jobject getClipboard(uintptr_t jni_env, uintptr_t ctx) {
JNIEnv *env = (JNIEnv*)jni_env;
jclass ctxClass = (*env)->GetObjectClass(env, ctx);
jmethodID getSystemService = find_method(env, ctxClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
jstring service = (*env)->NewStringUTF(env, "clipboard");
jobject ret = (jobject)(*env)->CallObjectMethod(env, ctx, getSystemService, service);
jthrowable err = (*env)->ExceptionOccurred(env);
if (err != NULL) {
LOG_FATAL("cannot lookup clipboard");
(*env)->ExceptionClear(env);
return NULL;
}
return ret;
}
char *getClipboardContent(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx) {
JNIEnv *env = (JNIEnv*)jni_env;
jobject mgr = getClipboard(jni_env, ctx);
if (mgr == NULL) {
return NULL;
}
jclass mgrClass = (*env)->GetObjectClass(env, mgr);
jmethodID getText = find_method(env, mgrClass, "getText", "()Ljava/lang/CharSequence;");
jobject content = (jstring)(*env)->CallObjectMethod(env, mgr, getText);
if (content == NULL) {
return NULL;
}
jclass clzCharSequence = (*env)->GetObjectClass(env, content);
jmethodID toString = (*env)->GetMethodID(env, clzCharSequence, "toString", "()Ljava/lang/String;");
jobject s = (*env)->CallObjectMethod(env, content, toString);
return getString(jni_env, ctx, s);
}
void setClipboardContent(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx, char *content) {
JNIEnv *env = (JNIEnv*)jni_env;
jobject mgr = getClipboard(jni_env, ctx);
if (mgr == NULL) {
return;
}
jclass mgrClass = (*env)->GetObjectClass(env, mgr);
jmethodID setText = find_method(env, mgrClass, "setText", "(Ljava/lang/CharSequence;)V");
jstring str = (*env)->NewStringUTF(env, content);
(*env)->CallVoidMethod(env, mgr, setText, str);
}
// file handling
jobject getContentResolver(uintptr_t jni_env, uintptr_t ctx) {
JNIEnv *env = (JNIEnv*)jni_env;
jclass ctxClass = (*env)->GetObjectClass(env, ctx);
jmethodID getContentResolver = find_method(env, ctxClass, "getContentResolver", "()Landroid/content/ContentResolver;");
return (jobject)(*env)->CallObjectMethod(env, ctx, getContentResolver);
}
void* openStream(uintptr_t jni_env, uintptr_t ctx, char* uriCstr) {
JNIEnv *env = (JNIEnv*)jni_env;
jobject resolver = getContentResolver(jni_env, ctx);
jclass resolverClass = (*env)->GetObjectClass(env, resolver);
jmethodID openInputStream = find_method(env, resolverClass, "openInputStream", "(Landroid/net/Uri;)Ljava/io/InputStream;");
jobject uri = parseURI(jni_env, ctx, uriCstr);
jobject stream = (jobject)(*env)->CallObjectMethod(env, resolver, openInputStream, uri);
jthrowable loadErr = (*env)->ExceptionOccurred(env);
if (loadErr != NULL) {
(*env)->ExceptionClear(env);
return NULL;
}
return (*env)->NewGlobalRef(env, stream);
}
void* saveStream(uintptr_t jni_env, uintptr_t ctx, char* uriCstr) {
JNIEnv *env = (JNIEnv*)jni_env;
jobject resolver = getContentResolver(jni_env, ctx);
jclass resolverClass = (*env)->GetObjectClass(env, resolver);
jmethodID saveOutputStream = find_method(env, resolverClass, "openOutputStream", "(Landroid/net/Uri;Ljava/lang/String;)Ljava/io/OutputStream;");
jobject uri = parseURI(jni_env, ctx, uriCstr);
jstring modes = (*env)->NewStringUTF(env, "wt"); // truncate before write
jobject stream = (jobject)(*env)->CallObjectMethod(env, resolver, saveOutputStream, uri, modes);
jthrowable loadErr = (*env)->ExceptionOccurred(env);
if (loadErr != NULL) {
(*env)->ExceptionClear(env);
return NULL;
}
return (*env)->NewGlobalRef(env, stream);
}
char* readStream(uintptr_t jni_env, uintptr_t ctx, void* stream, int len, int* total) {
JNIEnv *env = (JNIEnv*)jni_env;
jclass streamClass = (*env)->GetObjectClass(env, stream);
jmethodID read = find_method(env, streamClass, "read", "([BII)I");
jbyteArray data = (*env)->NewByteArray(env, len);
int count = (int)(*env)->CallIntMethod(env, stream, read, data, 0, len);
*total = count;
if (count == -1) {
return NULL;
}
char* bytes = malloc(sizeof(char)*count);
(*env)->GetByteArrayRegion(env, data, 0, count, bytes);
return bytes;
}
void writeStream(uintptr_t jni_env, uintptr_t ctx, void* stream, char* buf, int len) {
JNIEnv *env = (JNIEnv*)jni_env;
jclass streamClass = (*env)->GetObjectClass(env, stream);
jmethodID write = find_method(env, streamClass, "write", "([BII)V");
jbyteArray data = (*env)->NewByteArray(env, len);
(*env)->SetByteArrayRegion(env, data, 0, len, buf);
(*env)->CallVoidMethod(env, stream, write, data, 0, len);
free(buf);
}
void closeStream(uintptr_t jni_env, uintptr_t ctx, void* stream) {
JNIEnv *env = (JNIEnv*)jni_env;
jclass streamClass = (*env)->GetObjectClass(env, stream);
jmethodID close = find_method(env, streamClass, "close", "()V");
(*env)->CallVoidMethod(env, stream, close);
(*env)->DeleteGlobalRef(env, stream);
}
bool hasPrefix(char* string, char* prefix) {
size_t lp = strlen(prefix);
size_t ls = strlen(string);
if (ls < lp) {
return false;
}
return memcmp(prefix, string, lp) == 0;
}
bool canListContentURI(uintptr_t jni_env, uintptr_t ctx, char* uriCstr) {
JNIEnv *env = (JNIEnv*)jni_env;
jobject resolver = getContentResolver(jni_env, ctx);
jobject uri = parseURI(jni_env, ctx, uriCstr);
jthrowable loadErr = (*env)->ExceptionOccurred(env);
if (loadErr != NULL) {
(*env)->ExceptionClear(env);
return false;
}
jclass contractClass = find_class(env, "android/provider/DocumentsContract");
if (contractClass == NULL) { // API 19
return false;
}
jmethodID getDoc = find_static_method(env, contractClass, "getTreeDocumentId", "(Landroid/net/Uri;)Ljava/lang/String;");
if (getDoc == NULL) { // API 21
return false;
}
jstring docID = (jobject)(*env)->CallStaticObjectMethod(env, contractClass, getDoc, uri);
jmethodID getTree = find_static_method(env, contractClass, "buildDocumentUriUsingTree", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;");
jobject treeUri = (jobject)(*env)->CallStaticObjectMethod(env, contractClass, getTree, uri, docID);
jclass resolverClass = (*env)->GetObjectClass(env, resolver);
jmethodID getType = find_method(env, resolverClass, "getType", "(Landroid/net/Uri;)Ljava/lang/String;");
jstring type = (jstring)(*env)->CallObjectMethod(env, resolver, getType, treeUri);
if (type == NULL) {
return false;
}
char *str = getString(jni_env, ctx, type);
return strcmp(str, "vnd.android.document/directory") == 0;
}
bool canListFileURI(char* uriCstr) {
// Get file path from URI
size_t length = strlen(uriCstr)-7;// -7 for 'file://'
char* path = malloc(sizeof(char)*(length+1));// +1 for '\0'
memcpy(path, &uriCstr[7], length);
path[length] = '\0';
// Stat path to determine if it points to a directory
struct stat statbuf;
int result = stat(path, &statbuf);
free(path);
return (result == 0) && S_ISDIR(statbuf.st_mode);
}
bool canListURI(uintptr_t jni_env, uintptr_t ctx, char* uriCstr) {
if (hasPrefix(uriCstr, "file://")) {
return canListFileURI(uriCstr);
} else if (hasPrefix(uriCstr, "content://")) {
return canListContentURI(jni_env, ctx, uriCstr);
}
LOG_FATAL("Unrecognized scheme: %s", uriCstr);
return false;
}
char* contentURIGetFileName(uintptr_t jni_env, uintptr_t ctx, char* uriCstr) {
JNIEnv *env = (JNIEnv*)jni_env;
jobject resolver = getContentResolver(jni_env, ctx);
jobject uri = parseURI(jni_env, ctx, uriCstr);
jthrowable loadErr = (*env)->ExceptionOccurred(env);
if (loadErr != NULL) {
(*env)->ExceptionClear(env);
return "";
}
jclass stringClass = find_class(env, "java/lang/String");
jobjectArray project = (*env)->NewObjectArray(env, 1, stringClass, (*env)->NewStringUTF(env, "_display_name"));
jclass resolverClass = (*env)->GetObjectClass(env, resolver);
jmethodID query = find_method(env, resolverClass, "query", "(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;");
jobject cursor = (jobject)(*env)->CallObjectMethod(env, resolver, query, uri, project, NULL, NULL, NULL);
jclass cursorClass = (*env)->GetObjectClass(env, cursor);
jmethodID first = find_method(env, cursorClass, "moveToFirst", "()Z");
jmethodID get = find_method(env, cursorClass, "getString", "(I)Ljava/lang/String;");
if (((jboolean)(*env)->CallBooleanMethod(env, cursor, first)) == JNI_TRUE) {
jstring name = (jstring)(*env)->CallObjectMethod(env, cursor, get, 0);
char *fname = getString(jni_env, ctx, name);
return fname;
}
return NULL;
}
char* listContentURI(uintptr_t jni_env, uintptr_t ctx, char* uriCstr) {
JNIEnv *env = (JNIEnv*)jni_env;
jobject resolver = getContentResolver(jni_env, ctx);
jobject uri = parseURI(jni_env, ctx, uriCstr);
jthrowable loadErr = (*env)->ExceptionOccurred(env);
if (loadErr != NULL) {
(*env)->ExceptionClear(env);
return "";
}
jclass contractClass = find_class(env, "android/provider/DocumentsContract");
if (contractClass == NULL) { // API 19
return "";
}
jmethodID getDoc = find_static_method(env, contractClass, "getTreeDocumentId", "(Landroid/net/Uri;)Ljava/lang/String;");
if (getDoc == NULL) { // API 21
return "";
}
jstring docID = (jobject)(*env)->CallStaticObjectMethod(env, contractClass, getDoc, uri);
jmethodID getChild = find_static_method(env, contractClass, "buildChildDocumentsUriUsingTree", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;");
jobject childrenUri = (jobject)(*env)->CallStaticObjectMethod(env, contractClass, getChild, uri, docID);
jclass stringClass = find_class(env, "java/lang/String");
jobjectArray project = (*env)->NewObjectArray(env, 1, stringClass, (*env)->NewStringUTF(env, "document_id"));
jclass resolverClass = (*env)->GetObjectClass(env, resolver);
jmethodID query = find_method(env, resolverClass, "query", "(Landroid/net/Uri;[Ljava/lang/String;Landroid/os/Bundle;Landroid/os/CancellationSignal;)Landroid/database/Cursor;");
if (getDoc == NULL) { // API 26
return "";
}
jobject cursor = (jobject)(*env)->CallObjectMethod(env, resolver, query, childrenUri, project, NULL, NULL);
jclass cursorClass = (*env)->GetObjectClass(env, cursor);
jmethodID next = find_method(env, cursorClass, "moveToNext", "()Z");
jmethodID get = find_method(env, cursorClass, "getString", "(I)Ljava/lang/String;");
char *ret = NULL;
int len = 0;
while (((jboolean)(*env)->CallBooleanMethod(env, cursor, next)) == JNI_TRUE) {
jstring name = (jstring)(*env)->CallObjectMethod(env, cursor, get, 0);
jobject childUri = (jobject)(*env)->CallStaticObjectMethod(env, contractClass, getChild, uri, name);
jclass uriClass = (*env)->GetObjectClass(env, childUri);
jmethodID toString = (*env)->GetMethodID(env, uriClass, "toString", "()Ljava/lang/String;");
jobject s = (*env)->CallObjectMethod(env, childUri, toString);
char *uid = getString(jni_env, ctx, name);
// append
char *old = ret;
len = len + strlen(uid) + 1;
ret = malloc(sizeof(char)*(len+1));
if (old != NULL) {
strcpy(ret, old);
free(old);
} else {
ret[0] = '\0';
}
strcat(ret, uid);
strcat(ret, "|");
}
if (ret != NULL) {
ret[len-1] = '\0';
}
return ret;
}
char* listFileURI(char* uriCstr) {
size_t uriLength = strlen(uriCstr);
// Get file path from URI
size_t length = uriLength-7;// -7 for 'file://'
char* path = malloc(sizeof(char)*(length+1));// +1 for '\0'
memcpy(path, &uriCstr[7], length);
path[length] = '\0';
char *ret = NULL;
DIR *dfd;
if ((dfd = opendir(path)) != NULL) {
struct dirent *dp;
int len = 0;
while ((dp = readdir(dfd)) != NULL) {
if (strcmp(dp->d_name, ".") == 0) {
// Ignore current directory
continue;
}
if (strcmp(dp->d_name, "..") == 0) {
// Ignore parent directory
continue;
}
// append
char *old = ret;
len = len + uriLength + 1 /* / */ + strlen(dp->d_name) + 1 /* | */;
ret = malloc(sizeof(char)*(len+1));
if (old != NULL) {
strcpy(ret, old);
free(old);
} else {
ret[0] = '\0';
}
strcat(ret, uriCstr);
strcat(ret, "/");
strcat(ret, dp->d_name);
strcat(ret, "|");
}
if (ret != NULL) {
ret[len-1] = '\0';
}
}
free(path);
return ret;
}
char* listURI(uintptr_t jni_env, uintptr_t ctx, char* uriCstr) {
if (hasPrefix(uriCstr, "file://")) {
return listFileURI(uriCstr);
} else if (hasPrefix(uriCstr, "content://")) {
return listContentURI(jni_env, ctx, uriCstr);
}
LOG_FATAL("Unrecognized scheme: %s", uriCstr);
return "";
}
| 5,688 |
28,814 | <gh_stars>1000+
/*
* Copyright 2018 ZXing 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 com.google.zxing.web;
import org.junit.Assert;
import org.junit.Test;
import java.util.Timer;
/**
* Tests {@link DoSTracker}.
*/
public final class DoSTrackerTestCase extends Assert {
@Test
public void testDoS() throws Exception {
Timer timer = new Timer();
long timerTimeMS = 500;
int maxAccessPerTime = 2;
DoSTracker tracker = new DoSTracker(timer, "test", maxAccessPerTime, timerTimeMS, 3, null);
// 2 requests allowed per time; 3rd should be banned
assertFalse(tracker.isBanned("A"));
assertFalse(tracker.isBanned("A"));
assertTrue(tracker.isBanned("A"));
// After max 3 others are tracked, A should be reset/evicted and un-ban
assertFalse(tracker.isBanned("B"));
assertFalse(tracker.isBanned("C"));
assertFalse(tracker.isBanned("D"));
assertFalse(tracker.isBanned("A"));
// After building up a ban again, and letting plenty of time elapse, should un-ban
assertFalse(tracker.isBanned("A"));
assertTrue(tracker.isBanned("A"));
Thread.sleep(timerTimeMS * 3);
assertFalse(tracker.isBanned("A"));
// Build up a lot of hits
for (int i = 0; i < maxAccessPerTime * 5; i++) {
tracker.isBanned("A");
}
// After one interval, should still have enough hits to be banned
Thread.sleep(timerTimeMS * 2);
assertTrue(tracker.isBanned("A"));
}
}
| 671 |
377 | <filename>src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersistenceUnitLoaderTest.java
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.persistence;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.loader.PersistenceXMLLoader;
import com.impetus.kundera.metadata.model.PersistenceUnitMetadata;
/**
* Unit test case to load persistence.xml properties.
*
* @author vivek.mishra
*
*/
public class PersistenceUnitLoaderTest
{
/** logger instance */
private static final Logger log = LoggerFactory.getLogger(PersistenceUnitLoaderTest.class);
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
// do nothing.
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
// do nothing.
}
/**
* Test method on persistence unit loading.
*/
@Test
public void testLoadPersistenceUnitLoading()
{
try
{
Enumeration<URL> xmls = this.getClass().getClassLoader()
.getResources("META-INF/persistence.xml");
while (xmls.hasMoreElements())
{
String[] persistenceUnits = new String[12];
persistenceUnits[0] = "kunderatest";
persistenceUnits[1] = "PropertyTest";
persistenceUnits[2] = "PropertyTestwithvaraiable";
persistenceUnits[3] = "PropertyTestwithabsolutepath";
persistenceUnits[4] = "metaDataTest";
persistenceUnits[5] = "GeneratedValue";
persistenceUnits[6] = "patest";
persistenceUnits[7] = "mappedsu";
persistenceUnits[8] = "invalidmappedsu";
persistenceUnits[9] = "keyspace";
persistenceUnits[10] = "inheritanceTest";
persistenceUnits[11] = "extConfig";
final String _pattern = "/core/target/test-classes/";
List<PersistenceUnitMetadata> metadatas = PersistenceXMLLoader.findPersistenceUnits(xmls.nextElement(), persistenceUnits);
Assert.assertNotNull(metadatas);
Assert.assertEquals(12, metadatas.size());
// commented out to keep ConfiguratorTest happy! as it tries to
// load it.
// Assert.assertEquals(2,
// metadatas.get(0).getJarFiles().size());
Assert.assertEquals(56, metadatas.get(0).getClasses().size());
Assert.assertNotNull(metadatas.get(0).getPersistenceUnitRootUrl());
Assert.assertTrue(metadatas.get(0).getPersistenceUnitRootUrl().getPath().endsWith(_pattern));
}
}
catch (IOException ioex)
{
log.error(ioex.getMessage());
Assert.fail();
}
catch (Exception e)
{
log.error(e.getMessage());
Assert.fail();
}
}
}
| 1,696 |
382 | '''
count_tab - Count reads per gene from flatfile using UMIs
=================================================================
Purpose
-------
The purpose of this command is to count the number of reads per gene
based on the read's gene assignment and UMI. See the count command if
you want to perform per-cell counting using a BAM file input.
The input must be in the following format (tab separated), where the
first column is the read identifier (including UMI) and the second
column is the assigned gene. The input must be sorted by the gene
identifier.
Input template::
read_id[SEP]_UMI gene
Example::
NS500668:144:H5FCJBGXY:2:22309:18356:15843_TCTAA ENSG00000279457.3
NS500668:144:H5FCJBGXY:3:23405:39715:19716_CGATG ENSG00000225972.1
You can perform any required file transformation and pipe the output
directly to count_tab. For example to pipe output from featureCounts
with the '-R CORE' option you can do the following::
awk '$2=="Assigned" {print $1"\t"$4}' my.bam.featureCounts | sort -k2 |
umi_tools count_tab -S gene_counts.tsv -L count.log
The tab file is assumed to contain each read id once only. For paired
end reads with featureCounts you must include the "-p" option so each
read id is included once only.
Per-cell counting can be enable with ``--per-cell``. For per-cell
counting, the input must be in the following format (tab separated),
where the first column is the read identifier (including UMI and Cell
Barcode) and the second column is the assigned gene. The input must be
sorted by the gene identifier:
Input template::
read_id[SEP]_UMI_CB gene
Example::
NS500668:144:H5FCJBGXY:2:22309:18356:15843_TCTAA_AGTCGA ENSG00000279457.3
NS500668:144:H5FCJBGXY:3:23405:39715:19716_CGATG_GGAGAA ENSG00000225972.1
'''
import sys
# required to make iteritems python2 and python3 compatible
from builtins import dict
from functools import partial
import umi_tools.Utilities as U
import umi_tools.Documentation as Documentation
import umi_tools.network as network
import umi_tools.umi_methods as umi_methods
import umi_tools.sam_methods as sam_methods
# add the generic docstring text
__doc__ = __doc__ + Documentation.GENERIC_DOCSTRING_GDC
usage = '''
count_tab - Count reads per gene from flatfile using UMIs
Usage: umi_tools count_tab [OPTIONS] [--stdin=IN_TSV[.gz]] [--stdout=OUT_TSV[.gz]]
note: If --stdin/--stdout are ommited standard in and standard
out are used for input and output. Input/Output will be
(de)compressed if a filename provided to --stdin/--stdout
ends in .gz '''
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
# setup command line parser
parser = U.OptionParser(version="%prog version: $Id$",
usage=usage,
description=globals()["__doc__"])
group = U.OptionGroup(parser, "count_tab-specific options")
group.add_option("--barcode-separator", dest="bc_sep",
type="string", help="separator between read id and UMI "
" and (optionally) the cell barcode", default="_")
group.add_option("--per-cell", dest="per_cell",
action="store_true",
help="Readname includes cell barcode as well as UMI in "
"format: read[sep]UMI[sep]CB")
parser.add_option_group(group)
# add common options (-h/--help, ...) and parse command line
(options, args) = U.Start(parser, argv=argv, add_group_dedup_options=False,
add_sam_options=False)
nInput, nOutput = 0, 0
# set the method with which to extract umis from reads
if options.per_cell:
bc_getter = partial(
sam_methods.get_cell_umi_read_string, sep=options.bc_sep)
else:
bc_getter = partial(
sam_methods.get_umi_read_string, sep=options.bc_sep)
if options.per_cell:
options.stdout.write("%s\t%s\t%s\n" % ("cell", "gene", "count"))
else:
options.stdout.write("%s\t%s\n" % ("gene", "count"))
# set up UMIClusterer functor with methods specific to
# specified options.method
processor = network.UMIClusterer(options.method)
for gene, counts in sam_methods.get_gene_count_tab(
options.stdin,
bc_getter=bc_getter):
for cell in counts.keys():
umis = counts[cell].keys()
nInput += sum(counts[cell].values())
# group the umis
groups = processor(
counts[cell],
threshold=options.threshold)
gene_count = len(groups)
if options.per_cell:
options.stdout.write("%s\t%s\t%i\n" % (cell, gene, gene_count))
else:
options.stdout.write("%s\t%i\n" % (gene, gene_count))
nOutput += gene_count
U.info("Number of reads counted: %i" % nOutput)
U.Stop()
if __name__ == "__main__":
sys.exit(main(sys.argv))
| 2,100 |
584 | <reponame>zueltor/MercuryTrade
package com.mercury.platform.shared.config.descriptor.adr;
public enum AdrTrackerGroupContentType {
ICONS,
PROGRESS_BARS
}
| 64 |
12,333 | <reponame>chinnsenn/PictureSelector
package com.luck.picture.lib.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.viewpager.widget.ViewPager;
/**
* @author:luck
* @date:2016-12-31 22:12
* @describe:PreviewViewPager
*/
public class PreviewViewPager extends ViewPager {
private MyViewPageHelper helper;
public PreviewViewPager(Context context) {
super(context);
}
public PreviewViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
helper = new MyViewPageHelper(this);
}
@Override
public void setCurrentItem(int item) {
setCurrentItem(item, true);
}
@Override
public void setCurrentItem(int item, boolean smoothScroll) {
MScroller scroller = helper.getScroller();
if (Math.abs(getCurrentItem() - item) > 1) {
scroller.setNoDuration(true);
super.setCurrentItem(item, smoothScroll);
scroller.setNoDuration(false);
} else {
scroller.setNoDuration(false);
super.setCurrentItem(item, smoothScroll);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
try {
return super.onTouchEvent(ev);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
try {
return super.onInterceptTouchEvent(ev);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
return false;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
try {
return super.dispatchTouchEvent(ev);
} catch (IllegalArgumentException | ArrayIndexOutOfBoundsException ignored) {
}
return false;
}
}
| 807 |
2,872 | <gh_stars>1000+
from os.path import basename, dirname, splitext, normpath, join
class NodesPackage:
"""
A small container to store meta data about imported node packages.
"""
def __init__(self, directory: str):
self.name = basename(normpath(directory))
self.directory = directory
self.file_path = normpath(join(directory, 'nodes.py'))
def config_data(self):
return {
'name': self.name,
'dir': self.directory,
}
| 205 |
1,056 | <reponame>timfel/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.netbeans.modules.java.j2seplatform.libraries;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.event.ChangeListener;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.java.queries.JavadocForBinaryQuery;
import org.netbeans.api.project.libraries.Library;
import org.netbeans.api.project.libraries.LibraryManager;
import org.netbeans.spi.java.project.support.JavadocAndSourceRootDetection;
import org.netbeans.spi.java.queries.JavadocForBinaryQueryImplementation;
import org.openide.util.WeakListeners;
import org.openide.filesystems.URLMapper;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.ChangeSupport;
import org.openide.util.Exceptions;
/**
* Implementation of Javadoc query for the library.
*/
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.spi.java.queries.JavadocForBinaryQueryImplementation.class, position=150)
public class JavadocForBinaryQueryLibraryImpl implements JavadocForBinaryQueryImplementation {
private final Map<URI,URL> normalizedURLCache = new ConcurrentHashMap<>();
/** Default constructor for lookup. */
public JavadocForBinaryQueryLibraryImpl() {
}
@Override
@CheckForNull
public JavadocForBinaryQuery.Result findJavadoc(@NonNull final URL b) {
final Boolean isNormalizedURL = isNormalizedURL(b);
if (isNormalizedURL != null) {
for (LibraryManager mgr : LibraryManager.getOpenManagers()) {
for (Library lib : mgr.getLibraries()) {
if (!lib.getType().equals(J2SELibraryTypeProvider.LIBRARY_TYPE)) {
continue;
}
for (URL entry : lib.getContent(J2SELibraryTypeProvider.VOLUME_TYPE_CLASSPATH)) {
URL normalizedEntry;
if (isNormalizedURL == Boolean.TRUE) {
normalizedEntry = getNormalizedURL(entry);
} else {
normalizedEntry = entry;
}
if (b.equals(normalizedEntry)) {
return new R(lib);
}
}
}
}
}
return null;
}
private URL getNormalizedURL (URL url) {
//URL is already nornalized, return it
final Boolean isNormalized = isNormalizedURL(url);
if (isNormalized == null) {
return null;
}
if (isNormalized == Boolean.TRUE) {
return url;
}
//Todo: Should listen on the LibrariesManager and cleanup cache
// in this case the search can use the cache onle and can be faster
// from O(n) to O(ln(n))
URI uri = null;
try {
uri = url.toURI();
} catch (URISyntaxException e) {
Exceptions.printStackTrace(e);
}
URL normalizedURL = uri == null ? null : normalizedURLCache.get(uri);
if (normalizedURL == null) {
final FileObject fo = URLMapper.findFileObject(url);
if (fo != null) {
normalizedURL = fo.toURL();
if (uri != null) {
this.normalizedURLCache.put (uri, normalizedURL);
}
}
}
return normalizedURL;
}
/**
* Returns true if the given URL is file based, it is already
* resolved either into file URL or jar URL with file path.
* @param URL url
* @return true if the URL is normal
*/
private static Boolean isNormalizedURL (URL url) {
if ("jar".equals(url.getProtocol())) { //NOI18N
url = FileUtil.getArchiveFile(url);
if (url == null) {
//Broken URL
return null;
}
}
return "file".equals(url.getProtocol()); //NOI18N
}
private static class R implements JavadocForBinaryQuery.Result, PropertyChangeListener {
private final Library lib;
private final ChangeSupport cs = new ChangeSupport(this);
private URL[] cachedRoots;
public R (Library lib) {
this.lib = lib;
this.lib.addPropertyChangeListener (WeakListeners.propertyChange(this,this.lib));
}
@Override
public synchronized URL[] getRoots() {
if (this.cachedRoots == null) {
List<URL> result = new ArrayList<URL>();
for (URL u : lib.getContent(J2SELibraryTypeProvider.VOLUME_TYPE_JAVADOC)) {
result.add (getIndexFolder(u));
}
this.cachedRoots = result.toArray(new URL[result.size()]);
}
return this.cachedRoots;
}
@Override
public void addChangeListener(ChangeListener l) {
assert l != null : "Listener can not be null";
cs.addChangeListener(l);
}
@Override
public void removeChangeListener(ChangeListener l) {
assert l != null : "Listener can not be null";
cs.removeChangeListener(l);
}
@Override
public void propertyChange (PropertyChangeEvent event) {
if (Library.PROP_CONTENT.equals(event.getPropertyName())) {
synchronized (this) {
this.cachedRoots = null;
}
cs.fireChange();
}
}
private static URL getIndexFolder (final URL url) {
assert url != null;
final FileObject root = URLMapper.findFileObject(url);
if (root == null) {
return url;
}
final FileObject index = JavadocAndSourceRootDetection.findJavadocRoot(root);
if (index == null) {
return url;
}
return index.toURL();
}
}
}
| 3,095 |
341 | package com.ccnode.codegenerator.genCode;
import com.ccnode.codegenerator.exception.BizException;
import com.ccnode.codegenerator.pojo.GenCodeResponse;
import com.ccnode.codegenerator.pojoHelper.OnePojoInfoHelper;
import com.ccnode.codegenerator.util.IOUtils;
import com.ccnode.codegenerator.util.LoggerWrapper;
import com.ccnode.codegenerator.exception.BizException;
import com.ccnode.codegenerator.pojo.GenCodeResponse;
import com.ccnode.codegenerator.pojo.OnePojoInfo;
import com.ccnode.codegenerator.pojo.PojoFieldInfo;
import com.ccnode.codegenerator.pojoHelper.GenCodeResponseHelper;
import com.ccnode.codegenerator.pojoHelper.OnePojoInfoHelper;
import com.ccnode.codegenerator.util.GenCodeConfig;
import com.ccnode.codegenerator.util.IOUtils;
import com.ccnode.codegenerator.util.LoggerWrapper;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import java.io.File;
import java.util.List;
/**
* What always stop you is what you always believe.
* <p>
* Created by zhengjun.du on 2016/08/27 11:09
*/
public class InitialService {
private final static Logger LOGGER = LoggerWrapper.getLogger(InitialService.class);
public static GenCodeResponse initPojos(GenCodeResponse response) {
List<OnePojoInfo> contextList = Lists.newArrayList();
response.setPojoInfos(contextList);
for (String pojoName : response.getRequest().getPojoNames()) {
OnePojoInfo onePojoInfo = new OnePojoInfo();
try{
onePojoInfo.setPojoName(pojoName);
onePojoInfo.setPojoClassSimpleName(pojoName);
File pojoFile = IOUtils.matchOnlyOneFile(response.getRequest().getProjectPath(), pojoName + ".java");
if(pojoFile == null){
LOGGER.error("file not exist, path:{}, pojoName:{}",response.getRequest().getProjectPath(), pojoName);
return response.failure("", pojoName + " file not exist, path:" + response.getRequest().getProjectPath());
}
GenCodeConfig config = response.getCodeConfig();
String fullPojoPath = pojoFile.getAbsolutePath();
String pojoDirPath = pojoFile.getParentFile().getAbsolutePath();
onePojoInfo.setPojoDirPath(pojoDirPath);
onePojoInfo.setFullDaoPath(genPath(response, pojoDirPath, config.getDaoDir(), pojoName,(config.getDaoSuffix() == null ? GenCodeConfig.DAO_SUFFIX:config.getDaoSuffix()) + ".java"));
onePojoInfo.setFullServicePath(genPath(response, pojoDirPath, config.getServiceDir(), pojoName,(config.getServiceSuffix() == null ? GenCodeConfig.SERVICE_SUFFIX:config.getServiceSuffix()) + ".java"));
onePojoInfo.setFullSqlPath(genPath(response, pojoDirPath, config.getSqlDir(), pojoName,".sql"));
onePojoInfo.setFullMapperPath(genPath(response, pojoDirPath, config.getMapperDir(), pojoName,(config.getMapperSuffix() == null ? GenCodeConfig.MAPPER_SUFFIX:config.getMapperSuffix()) + ".xml"));
onePojoInfo.setFullPojoPath(fullPojoPath);
OnePojoInfoHelper.parseIdeaFieldInfo(onePojoInfo, response);
// todo fix daoPackage Bug
// onePojoInfo.setDaoPackage(GenCodeUtil
// .deducePackage(StringUtils.defaultIfEmpty(config.getDaoDir(),pojoDirPath) ,onePojoInfo.getPojoPackage()));
// onePojoInfo.setServicePackage(GenCodeUtil.deducePackage(StringUtils.defaultIfEmpty(config.getServiceDir(),pojoDirPath) ,onePojoInfo.getPojoPackage()));
List<PojoFieldInfo> pojoFieldInfos = onePojoInfo.getPojoFieldInfos();
String concat = StringUtils.EMPTY;
for (PojoFieldInfo pojoFieldInfo : pojoFieldInfos) {
concat += "|"+pojoFieldInfo.getFieldName();
}
if(!concat.contains("id")){
LOGGER.error(pojoName + " should has 'id' field");
return response.failure(pojoName + " should has 'id' field");
}
OnePojoInfoHelper.parseFiles(onePojoInfo,response);
OnePojoInfoHelper.deduceDaoPackage(onePojoInfo, response);
OnePojoInfoHelper.deduceServicePackage(onePojoInfo, response);
contextList.add(onePojoInfo);
}catch(BizException e){
LOGGER.error("parse Class,bizException",e);
return response.failure("",e.getMessage());
}catch(Exception e){
LOGGER.error("parse Class:"+pojoName + "failure",e);
return response.failure("","parse Class:"+pojoName + "failure");
}
}
return response;
}
private static String genPath(GenCodeResponse response, String pojoDirPath, String configDir, String pojoName, String fileSuffix) {
String projectPath = GenCodeResponseHelper.getProjectPathWithSplitter(response);
File file = IOUtils.matchOnlyOneFile(projectPath, pojoName + fileSuffix);
if(file != null){
return file.getAbsolutePath();
}
if(StringUtils.isBlank(configDir)){
return pojoDirPath + response.getPathSplitter() +pojoName + fileSuffix;
}
return projectPath + configDir + response.getPathSplitter() +pojoName + fileSuffix;
}
}
| 2,316 |
876 | #pragma once
#include "rapidcheck/gen/Arbitrary.h"
#include "rapidcheck/gen/Numeric.h"
namespace rc {
/// Useful utility class for testing that `Arbitrary` is actually used. The key
/// here is that if the default constructor is used, the value will be undefined
/// but if `Arbitrary` is used, the value will be `X`. An extra member is
/// included so that multiple unique values of the same type can be generated.
struct Predictable {
static constexpr int predictableValue = 1337;
int value; // TODO provide some default value here?
int extra;
};
/// Non-copyable version of `Predictable`.
struct NonCopyable : public Predictable {
NonCopyable() = default;
NonCopyable(const NonCopyable &) = delete;
NonCopyable &operator=(const NonCopyable &) = delete;
NonCopyable(NonCopyable &&other) noexcept {
value = other.value;
extra = other.extra;
}
NonCopyable &operator=(NonCopyable &&other) noexcept {
value = other.value;
extra = other.extra;
return *this;
}
};
// TODO source file!
static inline bool operator==(const Predictable &lhs, const Predictable &rhs) {
return (lhs.value == rhs.value) && (lhs.extra == rhs.extra);
}
static inline bool operator<(const Predictable &lhs, const Predictable &rhs) {
if (lhs.value == rhs.value) {
return lhs.extra < rhs.extra;
}
return lhs.value < rhs.value;
}
static inline bool operator>(const Predictable &lhs, const Predictable &rhs) {
if (lhs.value == rhs.value) {
return lhs.extra > rhs.extra;
}
return lhs.value > rhs.value;
}
static inline bool operator<=(const Predictable &lhs, const Predictable &rhs) {
return (lhs < rhs) || (lhs == rhs);
}
static inline bool operator>=(const Predictable &lhs, const Predictable &rhs) {
return (lhs > rhs) || (lhs == rhs);
}
static inline void show(const Predictable &value, std::ostream &os) {
show(value.value, os);
os << " (" << value.extra << ")";
}
static inline void show(const NonCopyable &value, std::ostream &os) {
show(value.value, os);
os << " (" << value.extra << ")";
}
template <>
struct Arbitrary<Predictable> {
static Gen<Predictable> arbitrary() {
return gen::map(gen::arbitrary<int>(),
[](int extra) {
Predictable predictable;
predictable.value = Predictable::predictableValue;
predictable.extra = extra;
return predictable;
});
}
};
template <>
struct Arbitrary<NonCopyable> {
static Gen<NonCopyable> arbitrary() {
return gen::map(gen::arbitrary<int>(),
[](int extra) {
NonCopyable predictable;
predictable.value = Predictable::predictableValue;
predictable.extra = extra;
return predictable;
});
}
};
// These overloads are useful to test if a value was generated using the
// appropriate `Arbitrary` specialization.
static inline bool isArbitraryPredictable(const Predictable &value) {
return value.value == Predictable::predictableValue;
}
static inline bool
isArbitraryPredictable(const std::pair<const Predictable, Predictable> &value) {
return isArbitraryPredictable(value.first) &&
isArbitraryPredictable(value.second);
}
} // namespace rc
namespace std {
template <>
struct hash<rc::Predictable> {
using argument_type = rc::Predictable;
using value_type = std::size_t;
value_type operator()(const rc::Predictable &value) const {
return std::hash<int>()(value.value) ^ std::hash<int>()(value.extra);
}
};
template <>
struct hash<rc::NonCopyable> {
using argument_type = rc::NonCopyable;
using value_type = std::size_t;
value_type operator()(const rc::NonCopyable &value) const {
return std::hash<rc::Predictable>()(value);
}
};
}
| 1,438 |
517 | package com.groupon.seleniumgridextras.config.driver;
public class EdgeDriver extends DriverInfo {
@Override
public String getExecutablePath() {
return "C:\\Program Files (x86)\\Microsoft Web Driver\\" + getExecutableName();
}
@Override
public String getExecutableName() {
return "MicrosoftWebDriver.exe";
}
}
| 123 |
456 | <reponame>spchal/pwntools-write-ups<filename>2013/pctf/pork/harness.py
#!/usr/bin/env python2
from pwn import *
context.log_level = 1000
with tempfile.NamedTemporaryFile() as fd:
s = randoms(12)
fd.write(s)
fd.flush()
p1 = process(['./pork-patched'])
try:
p2 = process(["./doit.py", "SILENT"])
p2.sendline("base64 " + fd.name)
if p2.recvline().strip() == b64e(s):
print "ok"
else:
print "not ok"
finally:
p1.kill()
| 265 |
682 | /**
* @file timing_place.h
* @brief Interface used by the VPR placer to query information
* from the Tatum timing analyzer.
*
* @class PlacerSetupSlacks
* Queries connection **RAW** setup slacks, which can
* range from negative to positive values. Also maps
* atom pin setup slacks to clb pin setup slacks.
* @class PlacerCriticalities
* Query connection criticalities, which are calculuated
* based on the raw setup slacks and ranges from 0 to 1.
* Also maps atom pin crit. to clb pin crit.
* @class PlacerTimingCosts
* Hierarchical structure used by update_td_costs() to
* maintain the order of addition operation of float values
* (to avoid round-offs) while doing incremental updates.
*
* Calculating criticalities:
* All the raw setup slack values across a single clock domain are gathered
* and rated from the best to the worst in terms of criticalities. In order
* to calculate criticalities, all the slack values need to be non-negative.
* Hence, if the worst slack is negative, all the slack values are shifted
* by the value of the worst slack so that the value is at least 0. If the
* worst slack is positive, then no shift happens.
*
* The best (shifted) slack (the most positive one) will have a criticality of 0.
* The worst (shifted) slack value will have a criticality of 1.
*
* Criticalities are used to calculated timing costs for each connection.
* The formula is cost = delay * criticality.
*
* For a more detailed description on how criticalities are calculated, see
* calc_relaxed_criticality() in `timing_util.cpp`.
*/
#pragma once
#include "vtr_vec_id_set.h"
#include "timing_info_fwd.h"
#include "clustered_netlist_utils.h"
#include "place_delay_model.h"
#include "vpr_net_pins_matrix.h"
/**
* @brief Saves the placement criticality parameters
*
* crit_exponent: The criticality exponent used to sharpen the criticalities
* crit_limit: The limit to consider a pin as timing critical
*/
struct PlaceCritParams {
float crit_exponent;
float crit_limit;
};
/**
* @brief PlacerCriticalities returns the clustered netlist connection criticalities
* used by the placer ('sharpened' by a criticality exponent).
*
* Usage
* =====
* This class also serves to map atom netlist level criticalites (i.e. on AtomPinIds)
* to the clustered netlist (i.e. ClusterPinIds) used during placement.
*
* Criticalities are updated by update_criticalities(), given that `update_enabled` is
* set to true. It will update criticalities based on the atom netlist connection
* criticalities provided by the passed in SetupTimingInfo.
*
* This process can be done incrementally, based on the modified connections/AtomPinIds
* returned by SetupTimingInfo. However, the set returned only reflects the connections
* changed by the last call to the timing info update.
*
* Therefore, if SetupTimingInfo is updated twice in succession without criticalities
* getting updated (update_enabled = false), the returned set cannot account for all
* the connections that have been modified. In this case, we flag `recompute_required`
* as false, and we recompute the criticalities for every connection to ensure that
* they are all up to date. Hence, each time update_setup_slacks_and_criticalities()
* is called, we assign `recompute_required` the opposite value of `update_enabled`.
*
* This class also maps/transforms the modified atom connections/pins returned by the
* timing info into modified clustered netlist connections/pins after calling
* update_criticalities(). The interface then enables users to iterate over this range
* via pins_with_modified_criticalities(). This is useful for incrementally re-calculating
* the timing costs.
*
* The criticalities of individual connections can then be queried by calling the
* criticality() member function.
*
* Implementation
* ==============
* To support incremental re-calculation, the class saves the last criticality exponent
* passed to PlacerCriticalities::update_criticalites(). If the next update uses the same
* exponent, criticalities can be incrementally updated. Otherwise, they must be re-calculated
* from scratch, since a change in exponent changes *all* criticalities.
*/
class PlacerCriticalities {
public: //Types
typedef vtr::vec_id_set<ClusterPinId>::iterator pin_iterator;
typedef vtr::vec_id_set<ClusterNetId>::iterator net_iterator;
typedef vtr::Range<pin_iterator> pin_range;
typedef vtr::Range<net_iterator> net_range;
public: //Lifetime
PlacerCriticalities(const ClusteredNetlist& clb_nlist, const ClusteredPinAtomPinsLookup& netlist_pin_lookup);
PlacerCriticalities(const PlacerCriticalities& clb_nlist) = delete;
PlacerCriticalities& operator=(const PlacerCriticalities& clb_nlist) = delete;
public: //Accessors
///@brief Returns the criticality of the specified connection.
float criticality(ClusterNetId net, int ipin) const { return timing_place_crit_[net][ipin]; }
/**
* @brief Returns the range of clustered netlist pins (i.e. ClusterPinIds) which
* were modified by the last call to PlacerCriticalities::update_criticalities().
*/
pin_range pins_with_modified_criticality() const;
public: //Modifiers
/**
* @brief Updates criticalities based on the atom netlist criticalitites
* provided by timing_info and the provided criticality_exponent.
*
* Should consistently call this method after the most recent timing analysis to
* keep the criticalities stored in this class in sync with the timing analyzer.
* If out of sync, then the criticalities cannot be incrementally updated on
* during the next timing analysis iteration.
*/
void update_criticalities(const SetupTimingInfo* timing_info, const PlaceCritParams& crit_params);
///@bried Enable the recompute_required flag to enforce from scratch update.
void set_recompute_required();
///@brief From scratch update. See timing_place.cpp for more.
void recompute_criticalities();
///@brief Override the criticality of a particular connection.
void set_criticality(ClusterNetId net, int ipin, float crit_val);
///@brief Set `update_enabled` to true.
void enable_update() { update_enabled = true; }
///@brief Set `update_enabled` to true.
void disable_update() { update_enabled = false; }
private: //Data
///@brief The clb netlist in the placement context.
const ClusteredNetlist& clb_nlist_;
///@brief The lookup table that maps atom pins to clb pins.
const ClusteredPinAtomPinsLookup& pin_lookup_;
/**
* @brief The matrix that stores criticality value for each connection.
*
* Index range: [0..cluster_ctx.clb_nlist.nets().size()-1][1..num_pins-1]
*/
ClbNetPinsMatrix<float> timing_place_crit_;
/**
* The criticality exponent when update_criticalites() was last called
* (used to detect if incremental update can be used).
*/
float last_crit_exponent_ = std::numeric_limits<float>::quiet_NaN();
///@brief Set of pins with criticaltites modified by last call to update_criticalities().
vtr::vec_id_set<ClusterPinId> cluster_pins_with_modified_criticality_;
///@brief Incremental update. See timing_place.cpp for more.
void incr_update_criticalities(const SetupTimingInfo* timing_info);
///@brief Flag that turns on/off the update_criticalities() routine.
bool update_enabled = true;
/**
* @brief Flag that checks if criticalities need to be recomputed for all connections.
*
* Used by the method update_criticalities(). They incremental update is not possible
* if this method wasn't called updated after the previous timing info update.
*/
bool recompute_required = true;
/**
* @brief if this is first time to call update_criticality
*
* This can be used for incremental criticality update and also incrementally update the highly critical pins
*/
bool first_time_update_criticality = true;
};
/**
* @brief PlacerSetupSlacks returns the RAW setup slacks of clustered netlist connection.
*
* Usage
* =====
* This class mirrors PlacerCriticalities by both its methods and its members. The only
* difference is that this class deals with RAW setup slacks returned by SetupTimingInfo
* rather than criticalities. See the documentation on PlacerCriticalities for more.
*
* RAW setup slacks are unlike criticalities. Their values are not confined between
* 0 and 1. Their values can be either positive or negative.
*
* This class also provides iterating over the clustered netlist connections/pins that
* have modified setup slacks by the last call to update_setup_slacks(). However, this
* utility is mainly used for incrementally committing the setup slack values into the
* structure `connection_setup_slack` used by many placer routines.
*/
class PlacerSetupSlacks {
public: //Types
typedef vtr::vec_id_set<ClusterPinId>::iterator pin_iterator;
typedef vtr::vec_id_set<ClusterNetId>::iterator net_iterator;
typedef vtr::Range<pin_iterator> pin_range;
typedef vtr::Range<net_iterator> net_range;
public: //Lifetime
PlacerSetupSlacks(const ClusteredNetlist& clb_nlist, const ClusteredPinAtomPinsLookup& netlist_pin_lookup);
PlacerSetupSlacks(const PlacerSetupSlacks& clb_nlist) = delete;
PlacerSetupSlacks& operator=(const PlacerSetupSlacks& clb_nlist) = delete;
public: //Accessors
///@brief Returns the setup slack of the specified connection.
float setup_slack(ClusterNetId net, int ipin) const { return timing_place_setup_slacks_[net][ipin]; }
/**
* @brief Returns the range of clustered netlist pins (i.e. ClusterPinIds)
* which were modified by the last call to PlacerSetupSlacks::update_setup_slacks().
*/
pin_range pins_with_modified_setup_slack() const;
public: //Modifiers
/**
* @brief Updates setup slacks based on the atom netlist setup slacks provided
* by timing_info.
*
* Should consistently call this method after the most recent timing analysis to
* keep the setup slacks stored in this class in sync with the timing analyzer.
* If out of sync, then the setup slacks cannot be incrementally updated on
* during the next timing analysis iteration.
*/
void update_setup_slacks(const SetupTimingInfo* timing_info);
///@bried Enable the recompute_required flag to enforce from scratch update.
void set_recompute_required() { recompute_required = true; }
///@brief Override the setup slack of a particular connection.
void set_setup_slack(ClusterNetId net, int ipin, float slack_val);
///@brief Set `update_enabled` to true.
void enable_update() { update_enabled = true; }
///@brief Set `update_enabled` to true.
void disable_update() { update_enabled = false; }
private: //Data
const ClusteredNetlist& clb_nlist_;
const ClusteredPinAtomPinsLookup& pin_lookup_;
/**
* @brief The matrix that stores raw setup slack values for each connection.
*
* Index range: [0..cluster_ctx.clb_nlist.nets().size()-1][1..num_pins-1]
*/
ClbNetPinsMatrix<float> timing_place_setup_slacks_;
///@brief Set of pins with raw setup slacks modified by last call to update_setup_slacks()
vtr::vec_id_set<ClusterPinId> cluster_pins_with_modified_setup_slack_;
///@brief Incremental update. See timing_place.cpp for more.
void incr_update_setup_slacks(const SetupTimingInfo* timing_info);
///@brief Incremental update. See timing_place.cpp for more.
void recompute_setup_slacks();
///@brief Flag that turns on/off the update_setup_slacks() routine.
bool update_enabled = true;
/**
* @brief Flag that checks if setup slacks need to be recomputed for all connections.
*
* Used by the method update_setup_slacks(). They incremental update is not possible
* if this method wasn't called updated after the previous timing info update.
*/
bool recompute_required = true;
};
/**
* @brief PlacerTimingCosts mimics a 2D array of connection timing costs running from:
* [0..cluster_ctx.clb_nlist.nets().size()-1][1..num_pins-1].
*
* It can be used similar to:
*
* PlacerTimingCosts connection_timing_costs(cluster_ctx.clb_nlist); //Construct
*
* //...
*
* //Modify a connection cost
* connection_timing_costs[net_id][ipin] = new_cost;
*
* //Potentially other modifications...
*
* //Calculate the updated timing cost, of all connections,
* //incrementally based on modifications
* float total_timing_cost = connection_timing_costs.total_cost();
*
* However behind the scenes PlacerTimingCosts tracks when connection costs are modified,
* and efficiently re-calculates the total timing cost incrementally based on the connections
* which have had their cost modified.
*
* Implementation
* ==============
* Internally, PlacerTimingCosts stores all connection costs in a flat array in the last part
* of connection_costs_. To mimic 2d-array like access PlacerTimingCosts also uses two proxy
* classes which allow indexing in the net and pin dimensions (NetProxy and ConnectionProxy
* respectively).
*
* The first part of connection_costs_ stores intermediate sums of the connection costs for
* efficient incremental re-calculation. More concretely, connection_costs_ stores a binary
* tree, where leaves correspond to individual connection costs and intermediate nodes the
* partial sums of the connection costs. (The binary tree is stored implicitly in the
* connection_costs_ vector, using Eytzinger's/BFS layout.) By summing the entire binary
* tree we calculate the total timing cost over all connections.
*
* Using a binary tree allows us to efficiently re-calculate the timing costs when only a subset
* of connections are changed. This is done by 'invalidating' intermediate nodes (from leaves up
* to the root) which have ancestors (leaves) with modified connection costs. When the
* total_cost() method is called, it recursively walks the binary tree to re-calculate the cost.
* Only invalidated nodes are traversed, with valid nodes just returning their previously
* calculated (and unchanged) value.
*
* For a circuit with 'K' connections, of which 'k' have changed (typically k << K), this can
* be done in O(k log K) time.
*
* It is important to note that due to limited floating point precision, floating point
* arithmetic has an order dependence (due to round-off). Using a binary tree to total
* the timing connection costs allows us to incrementally update the total timing cost while
* maintianing the *same order of operations* as if it was re-computed from scratch. This
* ensures we *always* get consistent results regardless of what/when connections are changed.
*
* Proxy Classes
* =============
* NetProxy is returned by PlacerTimingCost's operator[], and stores a pointer to the start of
* internal storage of that net's connection costs.
*
* ConnectionProxy is returned by NetProxy's operator[], and holds a reference to a particular
* element of the internal storage pertaining to a specific connection's cost. ConnectionProxy
* supports assignment, allowing clients to modify the connection cost. It also detects if the
* assigned value differs from the previous value and if so, calls PlacerTimingCosts's
* invalidate() method on that connection cost.
*
* PlacerTimingCosts's invalidate() method marks the cost element's ancestors as invalid (NaN)
* so they will be re-calculated by PlacerTimingCosts' total_cost() method.
*/
class PlacerTimingCosts {
public:
PlacerTimingCosts() = default;
PlacerTimingCosts(const ClusteredNetlist& nlist) {
auto nets = nlist.nets();
net_start_indicies_.resize(nets.size());
//Walk through the netlist to determine how many connections there are.
size_t iconn = 0;
for (ClusterNetId net : nets) {
//The placer always skips 'ignored' nets so they don't effect timing
//costs, so we also skip them here
if (nlist.net_is_ignored(net)) {
net_start_indicies_[net] = OPEN;
continue;
}
//Save the startind index of the current net's connections.
// We use a -1 offset, since sinks indexed from [1..num_net_pins-1]
// (there is no timing cost associated with net drivers)
net_start_indicies_[net] = iconn - 1;
//Reserve space for all this net's connections
iconn += nlist.net_sinks(net).size();
}
size_t num_connections = iconn;
//Determine how many binary tree levels we need to have a leaf
//for each connection cost
size_t ilevel = 0;
while (num_nodes_in_level(ilevel) < num_connections) {
++ilevel;
}
num_levels_ = ilevel + 1;
size_t num_leaves = num_nodes_in_level(ilevel);
size_t num_level_before_leaves = num_nodes_in_level(ilevel - 1);
VTR_ASSERT_MSG(num_leaves >= num_connections, "Need at least as many leaves as connections");
VTR_ASSERT_MSG(
num_connections == 0 || num_level_before_leaves < num_connections,
"Level before should have fewer nodes than connections (to ensure using the smallest binary tree)");
//We don't need to store all possible leaves if we have fewer connections
//(i.e. bottom-right of tree is empty)
size_t last_level_unused_nodes = num_nodes_in_level(ilevel) - num_connections;
size_t num_nodes = num_nodes_up_to_level(ilevel) - last_level_unused_nodes;
//Reserve space for connection costs and intermediate node values
connection_costs_ = std::vector<double>(num_nodes, std::numeric_limits<double>::quiet_NaN());
//The net start indicies we calculated earlier didn't account for intermediate binary tree nodes
//Shift the start indicies after the intermediate nodes
size_t num_intermediate_nodes = num_nodes_up_to_level(ilevel - 1);
for (ClusterNetId net : nets) {
if (nlist.net_is_ignored(net)) continue;
net_start_indicies_[net] = net_start_indicies_[net] + num_intermediate_nodes;
}
}
/**
* @brief Proxy class representing a connection cost.
*
* Supports modification of connection cost while detecting
* changes and reporting them up to PlacerTimingCosts.
*/
class ConnectionProxy {
public:
ConnectionProxy(PlacerTimingCosts* timing_costs, double& connection_cost)
: timing_costs_(timing_costs)
, connection_cost_(connection_cost) {}
///@brief Allow clients to modify the connection cost via assignment.
ConnectionProxy& operator=(double new_cost) {
if (new_cost != connection_cost_) {
//If connection cost changed, update it, and mark it
//as invalidated
connection_cost_ = new_cost;
timing_costs_->invalidate(&connection_cost_);
}
return *this;
}
/**
* @brief Support getting the current connection cost as a double.
*
* Useful for client code operating on the cost values (e.g. difference between costs).
*/
operator double() {
return connection_cost_;
}
private:
PlacerTimingCosts* timing_costs_;
double& connection_cost_;
};
/**
* @brief Proxy class representing the connection costs of a net.
*
* Supports indexing by pin index to retrieve the ConnectionProxy for that pin/connection.
*/
class NetProxy {
public:
NetProxy(PlacerTimingCosts* timing_costs, double* net_sink_costs)
: timing_costs_(timing_costs)
, net_sink_costs_(net_sink_costs) {}
///@brief Indexes into the specific net pin/connection.
ConnectionProxy operator[](size_t ipin) {
return ConnectionProxy(timing_costs_, net_sink_costs_[ipin]);
}
private:
PlacerTimingCosts* timing_costs_;
double* net_sink_costs_;
};
///@brief Indexes into the specific net.
NetProxy operator[](ClusterNetId net_id) {
VTR_ASSERT_SAFE(net_start_indicies_[net_id] >= 0);
double* net_connection_costs = &connection_costs_[net_start_indicies_[net_id]];
return NetProxy(this, net_connection_costs);
}
void clear() {
connection_costs_.clear();
net_start_indicies_.clear();
}
void swap(PlacerTimingCosts& other) {
std::swap(connection_costs_, other.connection_costs_);
std::swap(net_start_indicies_, other.net_start_indicies_);
std::swap(num_levels_, other.num_levels_);
}
/**
* @brief Calculates the total cost of all connections efficiently
* in the face of modified connection costs.
*/
double total_cost() {
float cost = total_cost_recurr(0); //Root
VTR_ASSERT_DEBUG_MSG(cost == total_cost_from_scratch(0),
"Expected incremental and from-scratch costs to be consistent");
return cost;
}
private:
///@brief Recursively calculate and update the timing cost rooted at inode.
double total_cost_recurr(size_t inode) {
//Prune out-of-tree
if (inode > connection_costs_.size() - 1) {
return 0.;
}
//Valid pre-calculated intermediate result or valid leaf
if (!std::isnan(connection_costs_[inode])) {
return connection_costs_[inode];
}
//Recompute recursively
double node_cost = total_cost_recurr(left_child(inode))
+ total_cost_recurr(right_child(inode));
//Save intermedate cost at this node
connection_costs_[inode] = node_cost;
return node_cost;
}
double total_cost_from_scratch(size_t inode) const {
//Prune out-of-tree
if (inode > connection_costs_.size() - 1) {
return 0.;
}
//Recompute recursively
double node_cost = total_cost_from_scratch(left_child(inode))
+ total_cost_from_scratch(right_child(inode));
return node_cost;
}
///@brief Friend-ed so it can call invalidate().
friend ConnectionProxy;
void invalidate(double* invalidated_cost) {
//Check pointer within range of internal storage
VTR_ASSERT_SAFE_MSG(
invalidated_cost >= &connection_costs_[0],
"Connection cost pointer should be after start of internal storage");
VTR_ASSERT_SAFE_MSG(
invalidated_cost <= &connection_costs_[connection_costs_.size() - 1],
"Connection cost pointer should be before end of internal storage");
size_t icost = invalidated_cost - &connection_costs_[0];
VTR_ASSERT_SAFE(icost >= num_nodes_up_to_level(num_levels_ - 2));
//Invalidate parent intermediate costs up to root or first
//already-invalidated parent
size_t iparent = parent(icost);
while (!std::isnan(connection_costs_[iparent])) {
//Invalidate
connection_costs_[iparent] = std::numeric_limits<double>::quiet_NaN();
if (iparent == 0) {
break; //At root
} else {
//Next parent
iparent = parent(iparent);
}
}
VTR_ASSERT_SAFE_MSG(std::isnan(connection_costs_[0]), "Invalidating any connection should have invalidated the root");
}
size_t left_child(size_t i) const {
return 2 * i + 1;
}
size_t right_child(size_t i) const {
return 2 * i + 2;
}
size_t parent(size_t i) const {
return (i - 1) / 2;
}
/**
* @brief Returns the number of nodes in ilevel'th level.
*
* If ilevel is negative, return 0, since the root shouldn't
* be counted as a leaf node candidate.
*/
size_t num_nodes_in_level(int ilevel) const {
return ilevel < 0 ? 0 : (2 << (ilevel));
}
///@brief Returns the total number of nodes in levels [0..ilevel] (inclusive).
size_t num_nodes_up_to_level(int ilevel) const {
return (2 << (ilevel + 1)) - 1;
}
private:
/**
* @brief Vector storing the implicit binary tree of connection costs.
*
* The actual connections are stored at the end of the vector
* (last level of the binary tree). The earlier portions of
* the tree are the intermediate nodes.
*
* The methods left_child()/right_child()/parent() can be used
* to traverse the tree by indicies into this vector.
*/
std::vector<double> connection_costs_;
/**
* @brief Vector storing the indicies of the first connection
* for each net in the netlist, used for indexing by net.
*/
vtr::vector<ClusterNetId, int> net_start_indicies_;
///@brief Number of levels in the binary tree.
size_t num_levels_ = 0;
};
| 8,902 |
314 | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "CDStructures.h"
@interface _IDECoverageProcessedRange : NSObject
{
BOOL _isFirstSubrangeInLine;
BOOL _isLastSubrangeInLine;
unsigned long long _lineNumber;
unsigned long long _startingCol;
struct _NSRange _processedRange;
}
@property BOOL isLastSubrangeInLine; // @synthesize isLastSubrangeInLine=_isLastSubrangeInLine;
@property BOOL isFirstSubrangeInLine; // @synthesize isFirstSubrangeInLine=_isFirstSubrangeInLine;
@property unsigned long long startingCol; // @synthesize startingCol=_startingCol;
@property unsigned long long lineNumber; // @synthesize lineNumber=_lineNumber;
@property struct _NSRange processedRange; // @synthesize processedRange=_processedRange;
@end
| 286 |
464 | import random
import pytest
from ding.utils import SingletonMetaclass
@pytest.mark.unittest
def test_singleton():
global count
count = 0
class A(object, metaclass=SingletonMetaclass):
def __init__(self, t):
self.t = t
self.p = random.randint(0, 10)
global count
count += 1
obj = [A(i) for i in range(3)]
assert count == 1
assert all([o.t == 0 for o in obj])
assert all([o.p == obj[0].p for o in obj])
assert all([id(o) == id(obj[0]) for o in obj])
assert id(A.instance) == id(obj[0])
# subclass test
class B(A):
pass
obj = [B(i) for i in range(3, 6)]
assert count == 2
assert all([o.t == 3 for o in obj])
assert all([o.p == obj[0].p for o in obj])
assert all([id(o) == id(obj[0]) for o in obj])
assert id(B.instance) == id(obj[0])
| 395 |
561 | #ifndef PARALLEL_FOR_H
#define PARALLEL_FOR_H
#include<algorithm>
#include <functional>
#include <thread>
#include <vector>
#if defined(_OPENMP)
#pragma message "Using OpenMP threading."
#define PARALLEL_FOR(nthreads,LOOP_END,O) { \
if (nthreads >1 ) { \
_Pragma("omp parallel num_threads(nthreads)") \
{ \
_Pragma("omp for") \
for (int loop_i=0; loop_i<LOOP_END; loop_i++) { \
O; \
} \
} \
}else{ \
for (int loop_i=0; loop_i<LOOP_END; loop_i++) { \
O; \
} \
} \
}
#else
#define PARALLEL_FOR(nthreads,LOOP_END,O) { \
if (nthreads >1 ) { \
std::vector<std::thread> threads(nthreads); \
for (int t = 0; t < nthreads; t++) { \
threads[t] = std::thread(std::bind( \
[&](const int bi, const int ei, const int t) { \
for(int loop_i = bi;loop_i<ei;loop_i++) { O; } \
},t*LOOP_END/nthreads,(t+1)==nthreads?LOOP_END:(t+1)*LOOP_END/nthreads,t)); \
} \
std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\
}else{ \
for (int loop_i=0; loop_i<LOOP_END; loop_i++) { \
O; \
} \
} \
}
#endif
#endif
| 705 |
310 | {
"name": "Impact 5065",
"description": "A digital amplifier.",
"url": "https://www.amazon.com/sonic-impact-portable-class-t-amplifier/dp/b0014krvqq"
}
| 64 |
4,409 | package org.springframework.security.oauth.examples.tonr;
/**
* @author <NAME>
*/
@SuppressWarnings("serial")
public class SparklrException extends Exception {
public SparklrException(String message) {
super(message);
}
}
| 73 |
953 | package io.spring.sample.graphql.repository;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class ArtifactRepositoriesInitializer implements ApplicationRunner {
private final ArtifactRepositories repositories;
public ArtifactRepositoriesInitializer(ArtifactRepositories repositories) {
this.repositories = repositories;
}
@Override
public void run(ApplicationArguments args) throws Exception {
List<ArtifactRepository> repositoryList = Arrays.asList(
new ArtifactRepository("spring-releases", "Spring Releases", "https://repo.spring.io/libs-releases"),
new ArtifactRepository("spring-milestones", "Spring Milestones", "https://repo.spring.io/libs-milestones"),
new ArtifactRepository("spring-snapshots", "Spring Snapshots", "https://repo.spring.io/libs-snapshots"));
repositories.saveAll(repositoryList);
}
}
| 295 |
8,054 | <reponame>tamlok/vnote
#include "helpunitedentry.h"
#include <widgets/treewidget.h>
#include "entrywidgetfactory.h"
using namespace vnotex;
HelpUnitedEntry::HelpUnitedEntry(UnitedEntryMgr *p_mgr, QObject *p_parent)
: IUnitedEntry("help",
tr("Help information about United Entry"),
p_mgr,
p_parent)
{
}
QSharedPointer<QWidget> HelpUnitedEntry::currentPopupWidget() const
{
return m_infoTree;
}
void HelpUnitedEntry::initOnFirstProcess()
{
m_infoTree = EntryWidgetFactory::createTreeWidget(2);
m_infoTree->setHeaderHidden(false);
m_infoTree->setHeaderLabels(QStringList() << tr("Shortcut") << tr("Description"));
QVector<QStringList> shortcuts = {{"Esc/Ctrl+[", tr("Close United Entry")},
{"Up/Ctrl+K", tr("Go to previous item")},
{"Down/Ctrl+J", tr("Go to next item")},
{"Ctrl+L", tr("Go to the item one level up")},
{"Ctrl+I", tr("Expand/Collapse current item")},
{"Ctrl+B", tr("Expand/Collapse all the items")},
{"Enter", tr("Activate current item")},
{"Ctrl+E", tr("Clear the input except the entry name")},
{"Ctrl+F", tr("Select the entry name")},
{"Ctrl+D", tr("Stop current entry")}};
for (const auto &shortcut : shortcuts) {
m_infoTree->addTopLevelItem(new QTreeWidgetItem(shortcut));
}
}
void HelpUnitedEntry::processInternal(const QString &p_args,
const std::function<void(const QSharedPointer<QWidget> &)> &p_popupWidgetFunc)
{
Q_UNUSED(p_args);
p_popupWidgetFunc(m_infoTree);
}
| 956 |
956 | {
"release_date": "2015-02-02",
"version": "2.0.5",
"maintainer": "<NAME> <<EMAIL>>",
"body": "* Refine compatibility of exceptions for file operations.\n* Specify the text encoding when opening the changelog file.\n"
} | 87 |
764 | <reponame>dchain01/token-profile<gh_stars>100-1000
{
"symbol": "GE",
"address": "0xE8f030D3a6e82C84c73460B46a28016f3d744954",
"overview":{
"en": "In GEChain's entire ecosystem, global users and genetic testing organizations are able to turn their own genetic data into their own value and circulate in the ecosystem in the form of GE. As a value carrier, GE not only circulates in the ecosystem, but also inspires the greater value ecology outside the genetic testing and health industry.",
"zh": "在GEChain的整个生态中,全球的用户和基因检测机构能够让自己拥有的基因数据转化为自身的价值,并以GE的形式在生态中流通。而GE作为价值承载物,不仅在生态系统中流通,更能撬动基因检测和健康产业之外的更大的价值生态。"
},
"email": "<EMAIL>",
"website": "http://www.gechain.io/",
"whitepaper": "http://www.gechain.io/file/GECHAIN%20WHITEPAPER.pdf",
"state": "NORMAL",
"published_on": "2019-07-28",
"initial_price":{
"ETH":"0.0000875 ETH",
"USD":"0.02 USD",
"BTC":"0.0000017 BTC"
},
"links": {
"twitter": "https://twitter.com/ge_chain",
"Telegram": "https://t.me/GEChain_Global"
}
} | 589 |
14,443 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.material.catalog.feature;
import io.material.catalog.R;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.core.view.MarginLayoutParamsCompat;
import androidx.core.view.MenuItemCompat;
import androidx.core.view.ViewCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.TextView;
import androidx.annotation.ArrayRes;
import androidx.annotation.ColorInt;
import androidx.annotation.DimenRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback;
import dagger.android.support.DaggerFragment;
import java.util.Collections;
import java.util.List;
/** Base class that provides a landing screen structure for a single feature demo. */
public abstract class DemoLandingFragment extends DaggerFragment {
private static final String FRAGMENT_DEMO_CONTENT = "fragment_demo_content";
@ColorInt private int menuIconColorUnchecked;
@ColorInt private int menuIconColorChecked;
@Override
public void onCreate(@Nullable Bundle bundle) {
super.onCreate(bundle);
setHasOptionsMenu(true);
}
@SuppressWarnings("RestrictTo")
@Nullable
@Override
public View onCreateView(
LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) {
View view =
layoutInflater.inflate(
R.layout.cat_demo_landing_fragment, viewGroup, false /* attachToRoot */);
Bundle arguments = getArguments();
if (arguments != null) {
String transitionName = arguments.getString(FeatureDemoUtils.ARG_TRANSITION_NAME);
ViewCompat.setTransitionName(view, transitionName);
}
Toolbar toolbar = view.findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setTitle(getTitleResId());
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Context toolbarContext = toolbar.getContext();
TypedArray a =
toolbarContext
.getTheme()
.obtainStyledAttributes(new int[] {R.attr.colorOnSurfaceVariant, R.attr.colorPrimary});
menuIconColorUnchecked = a.getColor(0, 0);
menuIconColorChecked = a.getColor(1, 0);
a.recycle();
TextView descriptionTextView = view.findViewById(R.id.cat_demo_landing_description);
ViewGroup mainDemoContainer = view.findViewById(R.id.cat_demo_landing_main_demo_container);
ViewGroup additionalDemosSection =
view.findViewById(R.id.cat_demo_landing_additional_demos_section);
ViewGroup additionalDemosContainer =
view.findViewById(R.id.cat_demo_landing_additional_demos_container);
// Links should be added whether or not the feature is restricted.
addLinks(layoutInflater, view);
// If this fragments demos is restricted, due to conditions set by the subclass, exit early
// without showing any demos and just show the restricted message.
if (isRestricted()) {
descriptionTextView.setText(getRestrictedMessageId());
mainDemoContainer.setVisibility(View.GONE);
additionalDemosSection.setVisibility(View.GONE);
return view;
}
descriptionTextView.setText(getDescriptionResId());
addDemoView(layoutInflater, mainDemoContainer, getMainDemo(), false);
List<Demo> additionalDemos = getAdditionalDemos();
for (Demo additionalDemo : additionalDemos) {
addDemoView(layoutInflater, additionalDemosContainer, additionalDemo, true);
}
additionalDemosSection.setVisibility(additionalDemos.isEmpty() ? View.GONE : View.VISIBLE);
DemoUtils.addBottomSpaceInsetsIfNeeded((ViewGroup) view, viewGroup);
return view;
}
private void addLinks(LayoutInflater layoutInflater, View view) {
ViewGroup linksSection = view.findViewById(R.id.cat_demo_landing_links_section);
int linksArrayResId = getLinksArrayResId();
if (linksArrayResId != -1) {
String[] linksStringArray = getResources().getStringArray(linksArrayResId);
for (String linkString : linksStringArray) {
addLinkView(layoutInflater, linksSection, linkString);
}
linksSection.setVisibility(View.VISIBLE);
} else {
linksSection.setVisibility(View.GONE);
}
}
private void addLinkView(LayoutInflater layoutInflater, ViewGroup viewGroup, String linkString) {
TextView linkView =
(TextView) layoutInflater.inflate(R.layout.cat_demo_landing_link_entry, viewGroup, false);
linkView.setText(linkString);
viewGroup.addView(linkView);
}
private void addDemoView(
LayoutInflater layoutInflater, ViewGroup demoContainer, Demo demo, boolean isAdditional) {
View demoView = layoutInflater.inflate(R.layout.cat_demo_landing_row, demoContainer, false);
View rootView = demoView.findViewById(R.id.cat_demo_landing_row_root);
TextView titleTextView = demoView.findViewById(R.id.cat_demo_landing_row_title);
TextView subtitleTextView = demoView.findViewById(R.id.cat_demo_landing_row_subtitle);
String transitionName = getString(demo.getTitleResId());
ViewCompat.setTransitionName(rootView, transitionName);
rootView.setOnClickListener(v -> startDemo(v, demo, transitionName));
titleTextView.setText(demo.getTitleResId());
subtitleTextView.setText(getDemoClassName(demo));
if (isAdditional) {
setMarginStart(titleTextView, R.dimen.cat_list_text_margin_from_icon_large);
setMarginStart(subtitleTextView, R.dimen.cat_list_text_margin_from_icon_large);
}
demoContainer.addView(demoView);
}
private String getDemoClassName(Demo demo) {
if (demo.createFragment() != null) {
return demo.createFragment().getClass().getSimpleName();
} else if (demo.createActivityIntent() != null) {
String className = demo.createActivityIntent().getComponent().getClassName();
return className.substring(className.lastIndexOf('.') + 1);
} else {
throw new IllegalStateException("Demo must implement createFragment or createActivityIntent");
}
}
private void startDemo(View sharedElement, Demo demo, String transitionName) {
if (demo.createFragment() != null) {
startDemoFragment(sharedElement, demo.createFragment(), transitionName);
} else if (demo.createActivityIntent() != null) {
startDemoActivity(sharedElement, demo.createActivityIntent(), transitionName);
} else {
throw new IllegalStateException("Demo must implement createFragment or createActivityIntent");
}
}
private void startDemoFragment(View sharedElement, Fragment fragment, String transitionName) {
Bundle args = new Bundle();
args.putString(DemoFragment.ARG_DEMO_TITLE, getString(getTitleResId()));
args.putString(FeatureDemoUtils.ARG_TRANSITION_NAME, transitionName);
fragment.setArguments(args);
FeatureDemoUtils.startFragment(
getActivity(), fragment, FRAGMENT_DEMO_CONTENT, sharedElement, transitionName);
}
private void startDemoActivity(View sharedElement, Intent intent, String transitionName) {
intent.putExtra(DemoActivity.EXTRA_DEMO_TITLE, getString(getTitleResId()));
intent.putExtra(DemoActivity.EXTRA_TRANSITION_NAME, transitionName);
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
// Set up shared element transition and disable overlay so views don't show above system bars
FragmentActivity activity = getActivity();
activity.setExitSharedElementCallback(new MaterialContainerTransformSharedElementCallback());
activity.getWindow().setSharedElementsUseOverlay(false);
ActivityOptions options =
ActivityOptions.makeSceneTransitionAnimation(activity, sharedElement, transitionName);
startActivity(intent, options.toBundle());
} else {
startActivity(intent);
}
}
private void setMarginStart(View view, @DimenRes int marginResId) {
int margin = getResources().getDimensionPixelOffset(marginResId);
MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
MarginLayoutParamsCompat.setMarginStart(layoutParams, margin);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
menuInflater.inflate(R.menu.mtrl_favorite_menu, menu);
super.onCreateOptionsMenu(menu, menuInflater);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.favorite_toggle);
boolean isChecked = FeatureDemoUtils.getDefaultDemo(getContext()).equals(getClass().getName());
setMenuItemChecked(item, isChecked);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.favorite_toggle) {
boolean isChecked = !menuItem.isChecked();
FeatureDemoUtils.saveDefaultDemo(getContext(), isChecked ? getClass().getName() : "");
setMenuItemChecked(menuItem, isChecked);
return true;
}
return super.onOptionsItemSelected(menuItem);
}
private void setMenuItemChecked(MenuItem menuItem, boolean isChecked) {
menuItem.setChecked(isChecked);
MenuItemCompat.setIconTintList(
menuItem,
ColorStateList.valueOf(isChecked ? menuIconColorChecked : menuIconColorUnchecked));
}
/**
* Whether or not the feature shown by this fragment should be flagged as restricted.
*
* <p>Examples of restricted feature could be features which depends on an API level that is
* greater than MDCs min sdk version. If overriding this method, you should also override {@link
* #getRestrictedMessageId()} and provide information about why the feature is restricted.
*/
public boolean isRestricted() {
return false;
}
/**
* The message to display if a feature {@link #isRestricted()}.
*
* <p>This message should provide insight into why the feature is restricted for the device it is
* running on. This message will be displayed in the description area of the demo fragment instead
* of the the provided {@link #getDescriptionResId()}. Additionally, all demos, both the main demo
* and any additional demos will not be shown.
*/
@StringRes
public int getRestrictedMessageId() {
return 0;
}
@StringRes
public abstract int getTitleResId();
@StringRes
public abstract int getDescriptionResId();
public abstract Demo getMainDemo();
@ArrayRes
public int getLinksArrayResId() {
return -1;
}
public List<Demo> getAdditionalDemos() {
return Collections.emptyList();
}
}
| 3,852 |
1,473 | /*
* Copyright 2016 Naver Corp.
*
* 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.navercorp.pinpoint.common.server.bo.codec.stat;
import com.navercorp.pinpoint.common.buffer.Buffer;
import com.navercorp.pinpoint.common.server.bo.codec.strategy.EncodingStrategy;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @author <NAME>
*/
@Component
public class AgentStatDataPointCodec {
public void encodeTimestamps(Buffer buffer, List<Long> timestamps) {
long prevTimestamp = timestamps.get(0);
long prevDelta = 0;
// skip first timestamp as this value is encoded as the qualifier and delta is meaningless
for (int i = 1; i < timestamps.size(); i++) {
long timestamp = timestamps.get(i);
long timestampDelta = timestamp - prevTimestamp;
buffer.putVLong(timestampDelta - prevDelta);
prevTimestamp = timestamp;
prevDelta = timestampDelta;
}
}
public List<Long> decodeTimestamps(long initialTimestamp, Buffer buffer, int numValues) {
List<Long> timestamps = new ArrayList<>(numValues);
timestamps.add(initialTimestamp);
long prevTimestamp = initialTimestamp;
long prevDelta = 0;
// loop through numValues - 1 as the first timestamp is gotten from the qualifier
for (int i = 0; i < numValues - 1; i++) {
long timestampDelta = prevDelta + buffer.readVLong();
long timestamp = prevTimestamp + timestampDelta;
timestamps.add(timestamp);
prevTimestamp = timestamp;
prevDelta = timestampDelta;
}
return timestamps;
}
public <T> void encodeValues(Buffer buffer, EncodingStrategy<T> encodingStrategy, List<T> values) {
encodingStrategy.encodeValues(buffer, values);
}
public <T> List<T> decodeValues(Buffer buffer, EncodingStrategy<T> encodingStrategy, int numValues) {
return encodingStrategy.decodeValues(buffer, numValues);
}
}
| 912 |
3,651 | /**
* Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.
*
* <p>For more information: http://www.orientdb.com
*/
package com.orientechnologies.spatial.functions;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.spatial.BaseSpatialLuceneTest;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
/** Created by <NAME> on 28/09/15. */
public class LuceneSpatialContainsTest extends BaseSpatialLuceneTest {
@Test
public void testContainsNoIndex() {
List<ODocument> execute =
db.command(
new OCommandSQL(
"select ST_Contains(smallc,smallc) as smallinsmall,ST_Contains(smallc, bigc) As smallinbig, ST_Contains(bigc,smallc) As biginsmall from (SELECT ST_Buffer(ST_GeomFromText('POINT(50 50)'), 20) As smallc,ST_Buffer(ST_GeomFromText('POINT(50 50)'), 40) As bigc)"))
.execute();
ODocument next = execute.iterator().next();
Assert.assertTrue(next.field("smallinsmall"));
Assert.assertFalse(next.field("smallinbig"));
Assert.assertTrue(next.field("biginsmall"));
}
@Test
public void testContainsIndex() {
db.command(new OCommandSQL("create class Polygon extends v")).execute();
db.command(new OCommandSQL("create property Polygon.geometry EMBEDDED OPolygon")).execute();
db.command(
new OCommandSQL(
"insert into Polygon set geometry = ST_Buffer(ST_GeomFromText('POINT(50 50)'), 20)"))
.execute();
db.command(
new OCommandSQL(
"insert into Polygon set geometry = ST_Buffer(ST_GeomFromText('POINT(50 50)'), 40)"))
.execute();
db.command(
new OCommandSQL("create index Polygon.g on Polygon (geometry) SPATIAL engine lucene"))
.execute();
List<ODocument> execute =
db.command(
new OCommandSQL(
"SELECT from Polygon where ST_Contains(geometry, 'POINT(50 50)') = true"))
.execute();
Assert.assertEquals(2, execute.size());
execute =
db.command(
new OCommandSQL(
"SELECT from Polygon where ST_Contains(geometry, ST_Buffer(ST_GeomFromText('POINT(50 50)'), 30)) = true"))
.execute();
Assert.assertEquals(1, execute.size());
}
@Test
public void testContainsIndex_GeometryCollection() {
db.command(new OCommandSQL("create class TestInsert extends v")).execute();
db.command(new OCommandSQL("create property TestInsert.geometry EMBEDDED OGeometryCollection"))
.execute();
db.command(
new OCommandSQL(
"insert into TestInsert set geometry = {'@type':'d','@class':'OGeometryCollection','geometries':[{'@type':'d','@class':'OPolygon','coordinates':[[[0,0],[10,0],[10,10],[0,10],[0,0]]]}]}"))
.execute();
db.command(
new OCommandSQL(
"insert into TestInsert set geometry = {'@type':'d','@class':'OGeometryCollection','geometries':[{'@type':'d','@class':'OPolygon','coordinates':[[[11,11],[21,11],[21,21],[11,21],[11,11]]]}]}"))
.execute();
db.command(
new OCommandSQL(
"create index TestInsert.geometry on TestInsert (geometry) SPATIAL engine lucene"))
.execute();
String testGeometry =
"{'@type':'d','@class':'OGeometryCollection','geometries':[{'@type':'d','@class':'OPolygon','coordinates':[[[1,1],[2,1],[2,2],[1,2],[1,1]]]}]}";
List<ODocument> execute =
db.command(
new OCommandSQL(
"SELECT from TestInsert where ST_Contains(geometry, "
+ testGeometry
+ ") = true"))
.execute();
Assert.assertEquals(1, execute.size());
}
}
| 1,799 |
348 | {"nom":"Frétigny","circ":"3ème circonscription","dpt":"Eure-et-Loir","inscrits":421,"abs":228,"votants":193,"blancs":7,"nuls":0,"exp":186,"res":[{"nuance":"LR","nom":"<NAME>","voix":128},{"nuance":"RDG","nom":"<NAME>","voix":58}]} | 95 |
1,068 | <reponame>kriegfrj/assertj-android
package org.assertj.android.api.view;
import android.support.annotation.IntDef;
import android.view.View;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.SOURCE;
@IntDef({
View.SCROLLBARS_INSIDE_INSET,
View.SCROLLBARS_INSIDE_OVERLAY,
View.SCROLLBARS_OUTSIDE_INSET,
View.SCROLLBARS_OUTSIDE_OVERLAY
})
@Retention(SOURCE)
@interface ViewScrollBarStyle {
}
| 178 |
599 | <reponame>masanqi/bk-bcs
# -*- coding: utf-8 -*-
#
# Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
# Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://opensource.org/licenses/MIT
#
# 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.
#
from unittest.mock import patch
import pytest
from backend.tests.resources.conftest import FakeBcsKubeConfigurationService
from backend.tests.testing_utils.base import generate_random_string
from backend.tests.testing_utils.mocks import bcs_perm, paas_cc
fake_data = {"id": 1, "name": generate_random_string(8)}
pytestmark = pytest.mark.django_db
class TestNamespace:
@pytest.fixture(autouse=True)
def pre_patch(self):
with patch("backend.accounts.bcs_perm.Namespace", new=bcs_perm.FakeNamespace), patch(
"backend.resources.namespace.client.get_namespaces_by_cluster_id", new=lambda *args, **kwargs: [fake_data]
), patch("backend.resources.namespace.utils.create_cc_namespace", new=lambda *args, **kwargs: fake_data):
yield
def test_create_k8s_namespace(self, api_client):
"""创建k8s命名空间
NOTE: 针对k8s会返回namespace_id字段
"""
# project_id 与 cluster_id随机,防止项目的缓存,导致获取项目类型错误
url = f"/apis/resources/projects/{generate_random_string(32)}/clusters/{generate_random_string(8)}/namespaces/"
resp = api_client.post(url, data=fake_data)
assert resp.json()["code"] == 0
data = resp.json()["data"]
assert "namespace_id" in data
assert isinstance(data, dict)
assert data["name"] == fake_data["name"]
| 835 |
521 | #pragma once
#include <elle/reactor/Waitable.hh>
namespace elle
{
namespace reactor
{
/// OrWaitable allows for waiting on one Waitable or another.
///
/// \code{.cc}
///
/// elle::reactor::Semaphore s;
/// elle::reactor::Barrier b;
///
/// ...
///
/// // Make the current Thread to wait for s or b to signal.
/// (s || b).wait();
///
/// \endcode.
class OrWaitable
: public Waitable
{
public:
/// Construct an OrWaitable from two Waitables.
///
/// \param lhs First Waitable.
/// \param lhs Second Waitable.
OrWaitable(Waitable& lhs, Waitable& rhs);
virtual
void
print(std::ostream& output) const override;
protected:
virtual
bool
_wait(Thread* t, Waker const& waker) override;
private:
ELLE_ATTRIBUTE(Waitable&, lhs);
ELLE_ATTRIBUTE(Waitable&, rhs);
};
/// Allow for using || (or) operator to create OrWaitables.
reactor::OrWaitable
operator || (reactor::Waitable& lhs, reactor::Waitable& rhs);
}
}
| 456 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.