max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
2,231 | <filename>bullet/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 <NAME> http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btContinuousConvexCollision.h"
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h"
#include "LinearMath/btTransformUtil.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "btGjkPairDetector.h"
#include "btPointCollector.h"
btContinuousConvexCollision::btContinuousConvexCollision ( const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* penetrationDepthSolver)
:m_simplexSolver(simplexSolver),
m_penetrationDepthSolver(penetrationDepthSolver),
m_convexA(convexA),m_convexB(convexB)
{
}
/// This maximum should not be necessary. It allows for untested/degenerate cases in production code.
/// You don't want your game ever to lock-up.
#define MAX_ITERATIONS 64
bool btContinuousConvexCollision::calcTimeOfImpact(
const btTransform& fromA,
const btTransform& toA,
const btTransform& fromB,
const btTransform& toB,
CastResult& result)
{
m_simplexSolver->reset();
/// compute linear and angular velocity for this interval, to interpolate
btVector3 linVelA,angVelA,linVelB,angVelB;
btTransformUtil::calculateVelocity(fromA,toA,btScalar(1.),linVelA,angVelA);
btTransformUtil::calculateVelocity(fromB,toB,btScalar(1.),linVelB,angVelB);
btScalar boundingRadiusA = m_convexA->getAngularMotionDisc();
btScalar boundingRadiusB = m_convexB->getAngularMotionDisc();
btScalar maxAngularProjectedVelocity = angVelA.length() * boundingRadiusA + angVelB.length() * boundingRadiusB;
btVector3 relLinVel = (linVelB-linVelA);
btScalar relLinVelocLength = (linVelB-linVelA).length();
if ((relLinVelocLength+maxAngularProjectedVelocity) == 0.f)
return false;
btScalar radius = btScalar(0.001);
btScalar lambda = btScalar(0.);
btVector3 v(1,0,0);
int maxIter = MAX_ITERATIONS;
btVector3 n;
n.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
bool hasResult = false;
btVector3 c;
btScalar lastLambda = lambda;
//btScalar epsilon = btScalar(0.001);
int numIter = 0;
//first solution, using GJK
btTransform identityTrans;
identityTrans.setIdentity();
btSphereShape raySphere(btScalar(0.0));
raySphere.setMargin(btScalar(0.));
// result.drawCoordSystem(sphereTr);
btPointCollector pointCollector1;
{
btGjkPairDetector gjk(m_convexA,m_convexB,m_convexA->getShapeType(),m_convexB->getShapeType(),m_convexA->getMargin(),m_convexB->getMargin(),m_simplexSolver,m_penetrationDepthSolver);
btGjkPairDetector::ClosestPointInput input;
//we don't use margins during CCD
// gjk.setIgnoreMargin(true);
input.m_transformA = fromA;
input.m_transformB = fromB;
gjk.getClosestPoints(input,pointCollector1,0);
hasResult = pointCollector1.m_hasResult;
c = pointCollector1.m_pointInWorld;
}
if (hasResult)
{
btScalar dist;
dist = pointCollector1.m_distance;
n = pointCollector1.m_normalOnBInWorld;
btScalar projectedLinearVelocity = relLinVel.dot(n);
//not close enough
while (dist > radius)
{
if (result.m_debugDrawer)
{
result.m_debugDrawer->drawSphere(c,0.2f,btVector3(1,1,1));
}
numIter++;
if (numIter > maxIter)
{
return false; //todo: report a failure
}
btScalar dLambda = btScalar(0.);
projectedLinearVelocity = relLinVel.dot(n);
//calculate safe moving fraction from distance / (linear+rotational velocity)
//btScalar clippedDist = GEN_min(angularConservativeRadius,dist);
//btScalar clippedDist = dist;
//don't report time of impact for motion away from the contact normal (or causes minor penetration)
if ((projectedLinearVelocity+ maxAngularProjectedVelocity)<=SIMD_EPSILON)
return false;
dLambda = dist / (projectedLinearVelocity+ maxAngularProjectedVelocity);
lambda = lambda + dLambda;
if (lambda > btScalar(1.))
return false;
if (lambda < btScalar(0.))
return false;
//todo: next check with relative epsilon
if (lambda <= lastLambda)
{
return false;
//n.setValue(0,0,0);
break;
}
lastLambda = lambda;
//interpolate to next lambda
btTransform interpolatedTransA,interpolatedTransB,relativeTrans;
btTransformUtil::integrateTransform(fromA,linVelA,angVelA,lambda,interpolatedTransA);
btTransformUtil::integrateTransform(fromB,linVelB,angVelB,lambda,interpolatedTransB);
relativeTrans = interpolatedTransB.inverseTimes(interpolatedTransA);
if (result.m_debugDrawer)
{
result.m_debugDrawer->drawSphere(interpolatedTransA.getOrigin(),0.2f,btVector3(1,0,0));
}
result.DebugDraw( lambda );
btPointCollector pointCollector;
btGjkPairDetector gjk(m_convexA,m_convexB,m_simplexSolver,m_penetrationDepthSolver);
btGjkPairDetector::ClosestPointInput input;
input.m_transformA = interpolatedTransA;
input.m_transformB = interpolatedTransB;
gjk.getClosestPoints(input,pointCollector,0);
if (pointCollector.m_hasResult)
{
if (pointCollector.m_distance < btScalar(0.))
{
//degenerate ?!
result.m_fraction = lastLambda;
n = pointCollector.m_normalOnBInWorld;
result.m_normal=n;//.setValue(1,1,1);// = n;
result.m_hitPoint = pointCollector.m_pointInWorld;
return true;
}
c = pointCollector.m_pointInWorld;
n = pointCollector.m_normalOnBInWorld;
dist = pointCollector.m_distance;
} else
{
//??
return false;
}
}
if ((projectedLinearVelocity+ maxAngularProjectedVelocity)<=result.m_allowedPenetration)//SIMD_EPSILON)
return false;
result.m_fraction = lambda;
result.m_normal = n;
result.m_hitPoint = c;
return true;
}
return false;
/*
//todo:
//if movement away from normal, discard result
btVector3 move = transBLocalTo.getOrigin() - transBLocalFrom.getOrigin();
if (result.m_fraction < btScalar(1.))
{
if (move.dot(result.m_normal) <= btScalar(0.))
{
}
}
*/
}
| 2,729 |
4,873 | <reponame>alexithor/react-native-windows<gh_stars>1000+
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <Views/FrameworkElementViewManager.h>
namespace Microsoft::ReactNative {
class FlyoutViewManager : public FrameworkElementViewManager {
using Super = FrameworkElementViewManager;
public:
FlyoutViewManager(const Mso::React::IReactContext &context);
const wchar_t *GetName() const override;
ShadowNode *createShadow() const override;
void GetNativeProps(const winrt::Microsoft::ReactNative::IJSValueWriter &writer) const override;
void GetExportedCustomDirectEventTypeConstants(
const winrt::Microsoft::ReactNative::IJSValueWriter &writer) const override;
void SetLayoutProps(
ShadowNodeBase &nodeToUpdate,
const XamlView &viewToUpdate,
float left,
float top,
float width,
float height) override;
protected:
XamlView CreateViewCore(int64_t tag, const winrt::Microsoft::ReactNative::JSValueObject &) override;
friend class FlyoutShadowNode;
};
} // namespace Microsoft::ReactNative
| 381 |
5,169 | {
"name": "Moulinette",
"version": "0.1.0",
"summary": "An internal Xcode audit tool.",
"description": "An internal audit tool used by Prolific Interactive to ensure code quality and standards.",
"homepage": "https://github.com/prolificinteractive/Moulinette",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/prolificinteractive/Moulinette.git",
"tag": "0.1.0"
},
"platforms": {
"ios": "8.0",
"osx": "10.13"
},
"source_files": "Source/**/*"
}
| 235 |
21,382 | import gym
from gym.spaces import Discrete
import random
class RepeatInitialObsEnv(gym.Env):
"""Env in which the initial observation has to be repeated all the time.
Runs for n steps.
r=1 if action correct, -1 otherwise (max. R=100).
"""
def __init__(self, episode_len=100):
self.observation_space = Discrete(2)
self.action_space = Discrete(2)
self.token = None
self.episode_len = episode_len
self.num_steps = 0
def reset(self):
self.token = random.choice([0, 1])
self.num_steps = 0
return self.token
def step(self, action):
if action == self.token:
reward = 1
else:
reward = -1
self.num_steps += 1
done = self.num_steps >= self.episode_len
return 0, reward, done, {}
| 362 |
880 | <reponame>LinZong/logback-android
/**
* Copyright 2019 <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 ch.qos.logback.core.net;
/**
* Constants used by syslog daemon and transitively by {@link SyslogAppenderBase}.
*
* @author <NAME>uml;lcü
**/
public class SyslogConstants {
static public final int SYSLOG_PORT = 514;
// Following constants extracted from RFC 3164, we multiply them by 8
// in order to precompute the facility part of PRI.
// See RFC 3164, Section 4.1.1 for exact details.
/** Emergency: system is unusable */
public static final int EMERGENCY_SEVERITY = 0;
/** Alert: action must be taken immediately */
public static final int ALERT_SEVERITY = 1;
/** Critical: critical conditions */
public static final int CRITICAL_SEVERITY = 2;
/** Error: error conditions */
public static final int ERROR_SEVERITY = 3;
/** Warning: warning conditions */
public static final int WARNING_SEVERITY = 4;
/** Notice: normal but significant condition */
public static final int NOTICE_SEVERITY = 5;
/** Informational: informational messages */
public static final int INFO_SEVERITY = 6;
/** Debug: debug-level messages */
public static final int DEBUG_SEVERITY = 7;
/** kernel messages, numerical code 0. */
public static final int LOG_KERN = 0;
/** user-level messages, numerical code 1. */
public static final int LOG_USER = 1 << 3;
/** mail system, numerical code 2. */
public static final int LOG_MAIL = 2 << 3;
/** system daemons, numerical code 3. */
public static final int LOG_DAEMON = 3 << 3;
/** security/authorization messages, numerical code 4. */
public static final int LOG_AUTH = 4 << 3;
/** messages generated internally by syslogd, numerical code 5. */
public static final int LOG_SYSLOG = 5 << 3;
/** line printer subsystem, numerical code 6. */
public static final int LOG_LPR = 6 << 3;
/** network news subsystem, numerical code 7. */
public static final int LOG_NEWS = 7 << 3;
/** UUCP subsystem, numerical code 8 */
public static final int LOG_UUCP = 8 << 3;
/** clock daemon, numerical code 9. */
public static final int LOG_CRON = 9 << 3;
/** security/authorization messages, numerical code 10. */
public static final int LOG_AUTHPRIV = 10 << 3;
/** ftp daemon, numerical code 11. */
public static final int LOG_FTP = 11 << 3;
/** NTP subsystem, numerical code 12. */
public static final int LOG_NTP = 12 << 3;
/** log audit, numerical code 13. */
public static final int LOG_AUDIT = 13 << 3;
/** log alert, numerical code 14. */
public static final int LOG_ALERT = 14 << 3;
/** clock daemon, numerical code 15. */
public static final int LOG_CLOCK = 15 << 3;
/** reserved for local use, numerical code 16. */
public static final int LOG_LOCAL0 = 16 << 3;
/** reserved for local use, numerical code 17. */
public static final int LOG_LOCAL1 = 17 << 3;
/** reserved for local use, numerical code 18. */
public static final int LOG_LOCAL2 = 18 << 3;
/** reserved for local use, numerical code 19. */
public static final int LOG_LOCAL3 = 19 << 3;
/** reserved for local use, numerical code 20. */
public static final int LOG_LOCAL4 = 20 << 3;
/** reserved for local use, numerical code 21. */
public static final int LOG_LOCAL5 = 21 << 3;
/** reserved for local use, numerical code 22. */
public static final int LOG_LOCAL6 = 22 << 3;
/** reserved for local use, numerical code 23.*/
public static final int LOG_LOCAL7 = 23 << 3;
}
| 1,207 |
320 | <reponame>milesmcc/a17
{
"name": "doc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "TAILWIND_MODE=watch NODE_ENV=development npm-run-all dev:*",
"build": "NODE_ENV=production npm-run-all prod:*",
"dev:twcssw": "./node_modules/tailwindcss/lib/cli.js -i ./assets/css/base.css -o ./assets/css/dist/base.css --jit",
"dev:jekyll": "bundle exec jekyll serve",
"prod:twcss": "./node_modules/tailwindcss/lib/cli.js -i ./assets/css/base.css -o ./assets/css/dist/base.css --jit --minify",
"prod:jekyll": "bundle exec jekyll build"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"a17t": "^0.10.1",
"npm-run-all": "^4.1.5",
"postcss-cli": "^9.1.0",
"tailwindcss": "^3.0.7"
}
}
| 431 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Bieuzy","circ":"3ème circonscription","dpt":"Morbihan","inscrits":562,"abs":252,"votants":310,"blancs":4,"nuls":3,"exp":303,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":92},{"nuance":"FI","nom":"Mme <NAME>","voix":66},{"nuance":"FN","nom":"Mme <NAME>","voix":37},{"nuance":"LR","nom":"Mme <NAME>","voix":26},{"nuance":"UDI","nom":"M. <NAME>","voix":24},{"nuance":"SOC","nom":"Mme <NAME>","voix":16},{"nuance":"ECO","nom":"M. <NAME>","voix":15},{"nuance":"REG","nom":"Mme <NAME>","voix":9},{"nuance":"REG","nom":"M. <NAME>","voix":8},{"nuance":"EXG","nom":"Mme <NAME>","voix":6},{"nuance":"DLF","nom":"M. <NAME>","voix":3},{"nuance":"EXD","nom":"M. <NAME>","voix":1},{"nuance":"DIV","nom":"M. <NAME>","voix":0}]} | 317 |
506 | // Copyright 2020 <NAME>.
#include "Characters/Abilities/GSTargetType.h"
#include "Characters/GSCharacterBase.h"
void UGSTargetType::GetTargets_Implementation(AGSCharacterBase* TargetingCharacter, AActor* TargetingActor, FGameplayEventData EventData, TArray<FGameplayAbilityTargetDataHandle>& OutTargetData, TArray<FHitResult>& OutHitResults, TArray<AActor*>& OutActors) const
{
return;
}
void UGSTargetType_UseOwner::GetTargets_Implementation(AGSCharacterBase* TargetingCharacter, AActor* TargetingActor, FGameplayEventData EventData, TArray<FGameplayAbilityTargetDataHandle>& OutTargetData, TArray<FHitResult>& OutHitResults, TArray<AActor*>& OutActors) const
{
OutActors.Add(TargetingCharacter);
}
void UGSTargetType_UseEventData::GetTargets_Implementation(AGSCharacterBase* TargetingCharacter, AActor* TargetingActor, FGameplayEventData EventData, TArray<FGameplayAbilityTargetDataHandle>& OutTargetData, TArray<FHitResult>& OutHitResults, TArray<AActor*>& OutActors) const
{
const FHitResult* FoundHitResult = EventData.ContextHandle.GetHitResult();
if (FoundHitResult)
{
OutHitResults.Add(*FoundHitResult);
}
else if (EventData.Target)
{
OutActors.Add(const_cast<AActor*>(EventData.Target));
}
}
| 397 |
309 | <gh_stars>100-1000
{
"created_at": "2014-09-19T19:20:56Z",
"description": "You can configure the CPU limits with control parameters.",
"name": "CPU Limits",
"properties": {
"quota:cpu_shares": {
"description": "Specifies the proportional weighted share for the domain. If this element is omitted, the service defaults to the OS provided defaults. There is no unit for the value; it is a relative measure based on the setting of other VMs. For example, a VM configured with value 2048 gets twice as much CPU time as a VM configured with value 1024.",
"title": "Quota: CPU Shares",
"type": "integer"
}
},
"required": [],
"schema": "/v2/schemas/metadefs/object",
"self": "/v2/metadefs/namespaces/OS::Compute::Quota/objects/CPU Limits",
"updated_at": "2014-09-19T19:20:56Z"
}
| 316 |
1,204 | <reponame>DiegoEliasCosta/gs-collections
/*
* Copyright 2015 <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 com.gs.collections.impl.map.sorted.mutable;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.collection.MutableCollection;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.sorted.MutableSortedMap;
import com.gs.collections.api.partition.list.PartitionMutableList;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.procedure.MapCollectProcedure;
import com.gs.collections.impl.collection.mutable.CollectionAdapter;
import com.gs.collections.impl.factory.SortedMaps;
import com.gs.collections.impl.set.mutable.SetAdapter;
import com.gs.collections.impl.utility.ArrayIterate;
import com.gs.collections.impl.utility.MapIterate;
public class TreeSortedMap<K, V>
extends AbstractMutableSortedMap<K, V>
implements Externalizable
{
private static final long serialVersionUID = 1L;
private TreeMap<K, V> treeMap;
public TreeSortedMap()
{
this.treeMap = new TreeMap<K, V>();
}
public TreeSortedMap(Comparator<? super K> comparator)
{
this.treeMap = new TreeMap<K, V>(comparator);
}
public TreeSortedMap(Map<? extends K, ? extends V> map)
{
this.treeMap = new TreeMap<K, V>(map);
}
public TreeSortedMap(Comparator<? super K> comparator, Map<? extends K, ? extends V> map)
{
this.treeMap = new TreeMap<K, V>(comparator);
this.treeMap.putAll(map);
}
public TreeSortedMap(SortedMap<K, ? extends V> map)
{
this.treeMap = new TreeMap<K, V>(map);
}
public TreeSortedMap(Pair<K, V>... pairs)
{
this.treeMap = new TreeMap<K, V>();
ArrayIterate.forEach(pairs, new MapCollectProcedure<Pair<K, V>, K, V>(
this.treeMap,
Functions.<K>firstOfPair(),
Functions.<V>secondOfPair()));
}
public static <K, V> TreeSortedMap<K, V> newMap()
{
return new TreeSortedMap<K, V>();
}
public static <K, V> TreeSortedMap<K, V> newMap(Comparator<? super K> comparator)
{
return new TreeSortedMap<K, V>(comparator);
}
public static <K, V> TreeSortedMap<K, V> newMap(Map<? extends K, ? extends V> map)
{
if (map instanceof SortedMap<?, ?>)
{
return new TreeSortedMap<K, V>((SortedMap<K, V>) map);
}
return new TreeSortedMap<K, V>(map);
}
public static <K, V> TreeSortedMap<K, V> newMap(Comparator<? super K> comparator, Map<? extends K, ? extends V> map)
{
return new TreeSortedMap<K, V>(comparator, map);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(Pair<K, V>... pairs)
{
return new TreeSortedMap<K, V>(pairs);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(Comparator<? super K> comparator, Pair<K, V>... pairs)
{
return new TreeSortedMap<K, V>(comparator).with(pairs);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(K key, V value)
{
return new TreeSortedMap<K, V>().with(key, value);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(K key1, V value1, K key2, V value2)
{
return new TreeSortedMap<K, V>().with(key1, value1, key2, value2);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(K key1, V value1, K key2, V value2, K key3, V value3)
{
return new TreeSortedMap<K, V>().with(key1, value1, key2, value2, key3, value3);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(
K key1, V value1,
K key2, V value2,
K key3, V value3,
K key4, V value4)
{
return new TreeSortedMap<K, V>().with(key1, value1, key2, value2, key3, value3, key4, value4);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(Comparator<? super K> comparator, K key, V value)
{
return new TreeSortedMap<K, V>(comparator).with(key, value);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(Comparator<? super K> comparator, K key1, V value1, K key2, V value2)
{
return new TreeSortedMap<K, V>(comparator).with(key1, value1, key2, value2);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(Comparator<? super K> comparator, K key1, V value1, K key2, V value2, K key3, V value3)
{
return new TreeSortedMap<K, V>(comparator).with(key1, value1, key2, value2, key3, value3);
}
public static <K, V> TreeSortedMap<K, V> newMapWith(Comparator<? super K> comparator,
K key1, V value1,
K key2, V value2,
K key3, V value3,
K key4, V value4)
{
return new TreeSortedMap<K, V>(comparator).with(key1, value1, key2, value2, key3, value3, key4, value4);
}
public TreeSortedMap<K, V> with(K key, V value)
{
this.put(key, value);
return this;
}
public TreeSortedMap<K, V> with(K key1, V value1, K key2, V value2)
{
this.put(key1, value1);
this.put(key2, value2);
return this;
}
public TreeSortedMap<K, V> with(K key1, V value1, K key2, V value2, K key3, V value3)
{
this.put(key1, value1);
this.put(key2, value2);
this.put(key3, value3);
return this;
}
public TreeSortedMap<K, V> with(K key1, V value1, K key2, V value2, K key3, V value3, K key4, V value4)
{
this.put(key1, value1);
this.put(key2, value2);
this.put(key3, value3);
this.put(key4, value4);
return this;
}
@Override
public TreeSortedMap<K, V> with(Pair<K, V>... pairs)
{
ArrayIterate.forEach(pairs, new MapCollectProcedure<Pair<K, V>, K, V>(this, Functions.<K>firstOfPair(), Functions.<V>secondOfPair()));
return this;
}
public int size()
{
return this.treeMap.size();
}
public MutableSortedMap<K, V> newEmpty()
{
return new TreeSortedMap<K, V>(this.comparator());
}
public V removeKey(K key)
{
return this.treeMap.remove(key);
}
@Override
public TreeSortedMap<K, V> clone()
{
return new TreeSortedMap<K, V>(this);
}
@Override
public boolean equals(Object o)
{
return this.treeMap.equals(o);
}
@Override
public int hashCode()
{
return this.treeMap.hashCode();
}
public void forEachKeyValue(Procedure2<? super K, ? super V> procedure2)
{
MapIterate.forEachKeyValue(this.treeMap, procedure2);
}
public K firstKey()
{
return this.treeMap.firstKey();
}
public K lastKey()
{
return this.treeMap.lastKey();
}
public MutableSet<Entry<K, V>> entrySet()
{
return SetAdapter.adapt(this.treeMap.entrySet());
}
public MutableSet<K> keySet()
{
return SetAdapter.adapt(this.treeMap.keySet());
}
public MutableCollection<V> values()
{
return CollectionAdapter.adapt(this.treeMap.values());
}
public Comparator<? super K> comparator()
{
return this.treeMap.comparator();
}
public V get(Object key)
{
return this.treeMap.get(key);
}
public V put(K key, V value)
{
return this.treeMap.put(key, value);
}
public V remove(Object key)
{
return this.treeMap.remove(key);
}
public void putAll(Map<? extends K, ? extends V> map)
{
this.treeMap.putAll(map);
}
public void clear()
{
this.treeMap.clear();
}
public boolean containsKey(Object key)
{
return this.treeMap.containsKey(key);
}
public MutableSortedMap<K, V> headMap(K toKey)
{
return SortedMapAdapter.adapt(this.treeMap.headMap(toKey));
}
public MutableSortedMap<K, V> tailMap(K fromKey)
{
return SortedMapAdapter.adapt(this.treeMap.tailMap(fromKey));
}
public MutableSortedMap<K, V> subMap(K fromKey, K toKey)
{
return SortedMapAdapter.adapt(this.treeMap.subMap(fromKey, toKey));
}
public boolean containsValue(Object value)
{
return this.treeMap.containsValue(value);
}
public MutableSortedMap<K, V> toReversed()
{
throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".toReversed() not implemented yet");
}
public MutableSortedMap<K, V> take(int count)
{
if (count < 0)
{
throw new IllegalArgumentException("Count must be greater than zero, but was: " + count);
}
MutableSortedMap<K, V> output = this.newEmpty();
Iterator<Entry<K, V>> iterator = this.treeMap.entrySet().iterator();
int countCopy = count;
while (iterator.hasNext() && countCopy-- > 0)
{
Entry<K, V> next = iterator.next();
output.put(next.getKey(), next.getValue());
}
return output;
}
public MutableSortedMap<K, V> takeWhile(Predicate<? super V> predicate)
{
throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".takeWhile() not implemented yet");
}
public MutableSortedMap<K, V> drop(int count)
{
if (count < 0)
{
throw new IllegalArgumentException("Count must be greater than zero, but was: " + count);
}
MutableSortedMap<K, V> output = SortedMaps.mutable.of(this.comparator());
Iterator<Entry<K, V>> iterator = this.treeMap.entrySet().iterator();
int start = Math.min(count, this.size());
if (start == this.size())
{
return output;
}
int i = 0;
while (iterator.hasNext())
{
if (i >= start)
{
Entry<K, V> next = iterator.next();
output.put(next.getKey(), next.getValue());
}
else
{
iterator.next();
}
i++;
}
return output;
}
public MutableSortedMap<K, V> dropWhile(Predicate<? super V> predicate)
{
throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".dropWhile() not implemented yet");
}
public PartitionMutableList<V> partitionWhile(Predicate<? super V> predicate)
{
throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".partitionWhile() not implemented yet");
}
public MutableList<V> distinct()
{
throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".distinct() not implemented yet");
}
@Override
public String toString()
{
return this.treeMap.toString();
}
public void writeExternal(ObjectOutput out) throws IOException
{
out.writeObject(this.comparator());
out.writeInt(this.size());
for (Entry<K, V> entry : this.treeMap.entrySet())
{
out.writeObject(entry.getKey());
out.writeObject(entry.getValue());
}
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
this.treeMap = new TreeMap<K, V>((Comparator<? super K>) in.readObject());
int size = in.readInt();
for (int i = 0; i < size; ++i)
{
this.treeMap.put((K) in.readObject(), (V) in.readObject());
}
}
}
| 5,394 |
311 | <reponame>80952556400/java-language-server<gh_stars>100-1000
package org.javacs.rewrite;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.Trees;
import java.nio.file.Path;
import java.util.Map;
import org.javacs.CompilerProvider;
import org.javacs.ParseTask;
import org.javacs.lsp.Position;
import org.javacs.lsp.Range;
import org.javacs.lsp.TextEdit;
public class ConvertVariableToStatement implements Rewrite {
final Path file;
final int position;
public ConvertVariableToStatement(Path file, int position) {
this.file = file;
this.position = position;
}
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
var task = compiler.parse(file);
var trees = Trees.instance(task.task);
var pos = trees.getSourcePositions();
var lines = task.root.getLineMap();
var variable = findVariable(task, position);
if (variable == null) {
return CANCELLED;
}
var expression = variable.getInitializer();
if (expression == null) {
return CANCELLED;
}
if (!isExpressionStatement(expression)) {
return CANCELLED;
}
var start = pos.getStartPosition(task.root, variable);
var end = pos.getStartPosition(task.root, expression);
var startLine = (int) lines.getLineNumber(start);
var startColumn = (int) lines.getColumnNumber(start);
var startPos = new Position(startLine - 1, startColumn - 1);
var endLine = (int) lines.getLineNumber(end);
var endColumn = (int) lines.getColumnNumber(end);
var endPos = new Position(endLine - 1, endColumn - 1);
var delete = new Range(startPos, endPos);
var edit = new TextEdit(delete, "");
TextEdit[] edits = {edit};
return Map.of(file, edits);
}
static VariableTree findVariable(ParseTask task, int position) {
return new FindVariableAt(task.task).scan(task.root, position);
}
/** https://docs.oracle.com/javase/specs/jls/se13/html/jls-14.html#jls-14.8 */
static boolean isExpressionStatement(Tree t) {
switch (t.getKind()) {
case ASSIGNMENT:
case PREFIX_INCREMENT:
case PREFIX_DECREMENT:
case POSTFIX_INCREMENT:
case POSTFIX_DECREMENT:
case METHOD_INVOCATION:
case NEW_CLASS:
return true;
default:
return false;
}
}
}
| 1,092 |
337 | import configparser
import warnings
import os
import pyarrow as pa
class CaseConfigParser(configparser.ConfigParser):
def optionxform(self, optionstr):
return optionstr
def patch_profile(fs_options):
fs_options = fs_options.copy()
if 'profile' in fs_options:
profile = fs_options.pop('profile')
config = CaseConfigParser()
path = os.path.expanduser('~/.aws/credentials')
config.read(path)
warnings.warn(f'Reading key/secret from ~/.aws/credentials using profile: {path}')
fs_options['access_key'] = config[profile]['aws_access_key_id']
fs_options['secret_key'] = config[profile]['aws_secret_access_key']
return fs_options
def parse(path, fs_options, for_arrow=False):
from .s3arrow import parse
fs_options = patch_profile(fs_options)
try:
# raise pa.lib.ArrowNotImplementedError('FOR TESTING')
return parse(path, fs_options, for_arrow=for_arrow)
except pa.lib.ArrowNotImplementedError:
# fallback
from .s3fs import parse
return parse(path, fs_options, for_arrow=for_arrow)
def glob(path, fs_options={}):
from .s3fs import glob
fs_options = patch_profile(fs_options)
return glob(path, fs_options)
| 487 |
6,523 | import unittest
from apex import amp
import random
import torch
from torch import nn
from utils import common_init, HALF
class TestRnnCells(unittest.TestCase):
def setUp(self):
self.handle = amp.init(enabled=True)
common_init(self)
def tearDown(self):
self.handle._deactivate()
def run_cell_test(self, cell, state_tuple=False):
shape = (self.b, self.h)
for typ in [torch.float, torch.half]:
xs = [torch.randn(shape, dtype=typ).requires_grad_()
for _ in range(self.t)]
hidden_fn = lambda: torch.zeros(shape, dtype=typ)
if state_tuple:
hidden = (hidden_fn(), hidden_fn())
else:
hidden = hidden_fn()
outputs = []
for i in range(self.t):
hidden = cell(xs[i], hidden)
if state_tuple:
output = hidden[0]
else:
output = hidden
outputs.append(output)
for y in outputs:
self.assertEqual(y.type(), HALF)
outputs[-1].float().sum().backward()
for i, x in enumerate(xs):
self.assertEqual(x.grad.dtype, x.dtype)
def test_rnn_cell_is_half(self):
cell = nn.RNNCell(self.h, self.h)
self.run_cell_test(cell)
def test_gru_cell_is_half(self):
cell = nn.GRUCell(self.h, self.h)
self.run_cell_test(cell)
def test_lstm_cell_is_half(self):
cell = nn.LSTMCell(self.h, self.h)
self.run_cell_test(cell, state_tuple=True)
class TestRnns(unittest.TestCase):
def setUp(self):
self.handle = amp.init(enabled=True)
common_init(self)
def tearDown(self):
self.handle._deactivate()
def run_rnn_test(self, rnn, layers, bidir, state_tuple=False):
for typ in [torch.float, torch.half]:
x = torch.randn((self.t, self.b, self.h), dtype=typ).requires_grad_()
hidden_fn = lambda: torch.zeros((layers + (layers * bidir),
self.b, self.h), dtype=typ)
if state_tuple:
hidden = (hidden_fn(), hidden_fn())
else:
hidden = hidden_fn()
output, _ = rnn(x, hidden)
self.assertEqual(output.type(), HALF)
output[-1, :, :].float().sum().backward()
self.assertEqual(x.grad.dtype, x.dtype)
def test_rnn_is_half(self):
configs = [(1, False), (2, False), (2, True)]
for layers, bidir in configs:
rnn = nn.RNN(input_size=self.h, hidden_size=self.h, num_layers=layers,
nonlinearity='relu', bidirectional=bidir)
self.run_rnn_test(rnn, layers, bidir)
def test_gru_is_half(self):
configs = [(1, False), (2, False), (2, True)]
for layers, bidir in configs:
rnn = nn.GRU(input_size=self.h, hidden_size=self.h, num_layers=layers,
bidirectional=bidir)
self.run_rnn_test(rnn, layers, bidir)
def test_lstm_is_half(self):
configs = [(1, False), (2, False), (2, True)]
for layers, bidir in configs:
rnn = nn.LSTM(input_size=self.h, hidden_size=self.h, num_layers=layers,
bidirectional=bidir)
self.run_rnn_test(rnn, layers, bidir, state_tuple=True)
def test_rnn_packed_sequence(self):
num_layers = 2
rnn = nn.RNN(input_size=self.h, hidden_size=self.h, num_layers=num_layers)
for typ in [torch.float, torch.half]:
x = torch.randn((self.t, self.b, self.h), dtype=typ).requires_grad_()
lens = sorted([random.randint(self.t // 2, self.t) for _ in range(self.b)],
reverse=True)
# `pack_padded_sequence` breaks if default tensor type is non-CPU
torch.set_default_tensor_type(torch.FloatTensor)
lens = torch.tensor(lens, dtype=torch.int64, device=torch.device('cpu'))
packed_seq = nn.utils.rnn.pack_padded_sequence(x, lens)
torch.set_default_tensor_type(torch.cuda.FloatTensor)
hidden = torch.zeros((num_layers, self.b, self.h), dtype=typ)
output, _ = rnn(packed_seq, hidden)
self.assertEqual(output.data.type(), HALF)
output.data.float().sum().backward()
self.assertEqual(x.grad.dtype, x.dtype)
if __name__ == '__main__':
unittest.main()
| 2,347 |
3,897 | <filename>targets/TARGET_Maxim/TARGET_MAX32625/objects.h
/*******************************************************************************
* Copyright (C) 2016 Maxim Integrated Products, Inc., All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL MAXIM INTEGRATED BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name of Maxim Integrated
* Products, Inc. shall not be used except as stated in the Maxim Integrated
* Products, Inc. Branding Policy.
*
* The mere transfer of this software does not imply any licenses
* of trade secrets, proprietary technology, copyrights, patents,
* trademarks, maskwork rights, or any other form of intellectual
* property whatsoever. Maxim Integrated Products, Inc. retains all
* ownership rights.
*******************************************************************************
*/
#ifndef MBED_OBJECTS_H
#define MBED_OBJECTS_H
#include "cmsis.h"
#include "PortNames.h"
#include "PeripheralNames.h"
#include "PinNames.h"
#include "gpio_object.h"
#include "gpio_regs.h"
#include "uart_regs.h"
#include "i2cm_regs.h"
#include "spim_regs.h"
#include "pt_regs.h"
#include "adc_regs.h"
#include "uart.h"
#include "adc.h"
#ifdef __cplusplus
extern "C" {
#endif
struct port_s {
PortName port;
uint32_t mask;
__IO uint32_t *reg_out;
__I uint32_t *reg_in;
PinMode mode;
};
struct gpio_irq_s {
uint8_t port;
uint8_t pin;
uint8_t rise_en;
uint8_t fall_en;
uint32_t id;
};
struct serial_s {
int index;
mxc_uart_regs_t *uart;
mxc_uart_fifo_regs_t *fifo;
uint32_t id;
uart_cfg_t cfg;
sys_cfg_uart_t sys_cfg;
PinName tx;
PinName rx;
};
struct i2c_s {
mxc_i2cm_regs_t *i2c;
mxc_i2cm_fifo_regs_t *fifo;
int start_pending;
};
struct spi_s {
int index;
mxc_spim_regs_t *spi;
};
struct pwmout_s {
mxc_pt_regs_t *pwm;
int period;
int pulse_width;
};
struct analogin_s {
mxc_adc_regs_t *adc;
mxc_adc_chsel_t channel;
};
typedef struct {
volatile uint32_t *reg_req;
volatile uint32_t *reg_ack;
uint32_t req_val;
uint32_t ack_mask;
} pin_function_t;
#ifdef __cplusplus
}
#endif
#endif
| 1,122 |
6,139 | <reponame>uOOOO/mosby
/*
* Copyright 2015 <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 com.hannesdorfmann.mosby3.sample.mail.login;
import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter;
import com.hannesdorfmann.mosby3.sample.mail.model.account.Account;
import com.hannesdorfmann.mosby3.sample.mail.model.account.AccountManager;
import com.hannesdorfmann.mosby3.sample.mail.model.account.AuthCredentials;
import com.hannesdorfmann.mosby3.sample.mail.model.event.LoginSuccessfulEvent;
import de.greenrobot.event.EventBus;
import javax.inject.Inject;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* @author <NAME>
*/
public class LoginPresenter extends MvpBasePresenter<LoginView> {
private AccountManager accountManager;
private Subscriber<Account> subscriber;
private EventBus eventBus;
@Inject public LoginPresenter(AccountManager accountManager, EventBus eventBus) {
this.accountManager = accountManager;
this.eventBus = eventBus;
}
public void doLogin(AuthCredentials credentials) {
if (isViewAttached()) {
getView().showLoading();
}
// Kind of "callback"
cancelSubscription();
subscriber = new Subscriber<Account>() {
@Override public void onCompleted() {
if (isViewAttached()) {
getView().loginSuccessful();
}
}
@Override public void onError(Throwable e) {
if (isViewAttached()) {
getView().showError();
}
}
@Override public void onNext(Account account) {
eventBus.post(new LoginSuccessfulEvent(account));
}
};
// do the login
accountManager.doLogin(credentials)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
/**
* Cancels any previous callback
*/
private void cancelSubscription() {
if (subscriber != null && !subscriber.isUnsubscribed()) {
subscriber.unsubscribe();
}
}
@Override public void detachView(boolean retainInstance) {
super.detachView(retainInstance);
if (!retainInstance) {
cancelSubscription();
}
}
@Override public void attachView(LoginView view) {
super.attachView(view);
}
}
| 984 |
518 | package io.sdb.config;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author <a href="https://github.com/binarywang"><NAME></a>
*/
@ConfigurationProperties(prefix = "wechat.ma")
@Data
public class WxMaProperties {
/**
* 设置微信小程序的appid
*/
private String appid;
/**
* 设置微信小程序的Secret
*/
private String secret;
/**
* 设置微信小程序的token
*/
private String token;
/**
* 设置微信小程序的EncodingAESKey
*/
private String aesKey;
/**
* 消息格式,XML或者JSON
*/
private String msgDataFormat;
/**
* 开放平台APPID
*/
private String openAppId;
/**
* 开放平台密钥
*/
private String openAppSecret;
/**
* 商户号
*/
private String mchId;
/**
* 商户密钥
*/
private String mchKey;
/**
* 商户证书路径
*/
private String keyPath;
/**
* 微信支付异步通知地址
*/
private String notifyUrl;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
| 648 |
405 | package org.jeecgframework.web.cgform.service.impl.button;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.jeecgframework.web.cgform.entity.button.CgformButtonEntity;
import org.jeecgframework.web.cgform.service.button.CgformButtonServiceI;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
@Service("cgformButtonService")
@Transactional
public class CgformButtonServiceImpl extends CommonServiceImpl implements CgformButtonServiceI {
/**
* 查询按钮list
* @param formId
* @return
*/
public List<CgformButtonEntity> getCgformButtonListByFormId(String formId) {
StringBuilder hql = new StringBuilder("");
hql.append(" from CgformButtonEntity t");
hql.append(" where t.formId=? order by t.orderNum asc");
List<CgformButtonEntity> list = this.findHql(hql.toString(), formId);
return list;
}
/**
* 校验按钮唯一性
* @param cgformButtonEntity
* @return
*/
public List<CgformButtonEntity> checkCgformButton(CgformButtonEntity cgformButtonEntity) {
StringBuilder hql = new StringBuilder("");
hql.append(" from CgformButtonEntity t");
hql.append(" where t.formId='").append(cgformButtonEntity.getFormId()).append("'");
hql.append(" and t.buttonCode ='").append(cgformButtonEntity.getButtonCode()).append("'");
if(cgformButtonEntity.getId()!=null){
hql.append(" and t.id !='").append(cgformButtonEntity.getId()).append("'");
}
List<CgformButtonEntity> list = this.findHql(hql.toString());
return list;
}
} | 581 |
463 | <gh_stars>100-1000
package mockit.asm.methods;
import javax.annotation.*;
import mockit.asm.constantPool.*;
import mockit.asm.util.*;
/**
* Stores the exceptions that can be thrown by a method/constructor, and writes it to the "Exceptions" attribute.
* For each thrown exception, stores the index of the constant pool item containing the internal name of the thrown exception class.
*/
final class ExceptionsWriter extends AttributeWriter
{
@Nonnull private final int[] exceptionIndices;
ExceptionsWriter(@Nonnull ConstantPoolGeneration cp, @Nonnull String[] exceptionTypeDescs) {
super(cp, "Exceptions");
int n = exceptionTypeDescs.length;
exceptionIndices = new int[n];
for (int i = 0; i < n; i++) {
exceptionIndices[i] = cp.newClass(exceptionTypeDescs[i]);
}
}
@Nonnegative @Override
public int getSize() { return 8 + 2 * exceptionIndices.length; }
@Override
public void put(@Nonnull ByteVector out) {
int n = exceptionIndices.length;
put(out, 2 + 2 * n);
out.putShort(n);
for (int exceptionIndex : exceptionIndices) {
out.putShort(exceptionIndex);
}
}
}
| 409 |
56,632 | <gh_stars>1000+
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
// Copyright (C) 2014, Intel, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
#ifndef OPENCV_TS_EXT_HPP
#define OPENCV_TS_EXT_HPP
namespace cvtest {
void checkIppStatus();
extern bool skipUnstableTests;
extern bool runBigDataTests;
extern int testThreads;
extern int debugLevel; //< 0 - no debug, 1 - basic test debug information, >1 - extra debug information
void testSetUp();
void testTearDown();
bool checkBigDataTests();
}
// check for required "opencv_test" namespace
#if !defined(CV_TEST_SKIP_NAMESPACE_CHECK) && defined(__OPENCV_BUILD)
#define CV__TEST_NAMESPACE_CHECK required_opencv_test_namespace = true;
#else
#define CV__TEST_NAMESPACE_CHECK // nothing
#endif
#define CV__TEST_INIT \
CV__TEST_NAMESPACE_CHECK \
::cvtest::testSetUp();
#define CV__TEST_CLEANUP ::cvtest::testTearDown();
#define CV__TEST_BODY_IMPL(name) \
{ \
CV__TRACE_APP_FUNCTION_NAME(name); \
try { \
CV__TEST_INIT \
Body(); \
CV__TEST_CLEANUP \
} \
catch (const cvtest::details::SkipTestExceptionBase& e) \
{ \
printf("[ SKIP ] %s\n", e.what()); \
} \
} \
#undef TEST
#define TEST_(test_case_name, test_name, parent_class, bodyMethodName, BODY_IMPL) \
class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
public:\
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
private:\
virtual void TestBody() CV_OVERRIDE;\
virtual void bodyMethodName();\
static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\
GTEST_DISALLOW_COPY_AND_ASSIGN_(\
GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
};\
\
::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\
::test_info_ =\
::testing::internal::MakeAndRegisterTestInfo(\
#test_case_name, #test_name, NULL, NULL, \
::testing::internal::CodeLocation(__FILE__, __LINE__), \
(::testing::internal::GetTestTypeId()), \
parent_class::SetUpTestCase, \
parent_class::TearDownTestCase, \
new ::testing::internal::TestFactoryImpl<\
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() BODY_IMPL( #test_case_name "_" #test_name ) \
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::bodyMethodName()
#define TEST(test_case_name, test_name) TEST_(test_case_name, test_name, ::testing::Test, Body, CV__TEST_BODY_IMPL)
#define CV__TEST_BIGDATA_BODY_IMPL(name) \
{ \
if (!cvtest::checkBigDataTests()) \
{ \
return; \
} \
CV__TRACE_APP_FUNCTION_NAME(name); \
try { \
CV__TEST_INIT \
Body(); \
CV__TEST_CLEANUP \
} \
catch (const cvtest::details::SkipTestExceptionBase& e) \
{ \
printf("[ SKIP ] %s\n", e.what()); \
} \
} \
// Special type of tests which require / use or validate processing of huge amount of data (>= 2Gb)
#if defined(_M_X64) || defined(_M_ARM64) || defined(__x86_64__) || defined(__aarch64__)
#define BIGDATA_TEST(test_case_name, test_name) TEST_(BigData_ ## test_case_name, test_name, ::testing::Test, Body, CV__TEST_BIGDATA_BODY_IMPL)
#else
#define BIGDATA_TEST(test_case_name, test_name) TEST_(BigData_ ## test_case_name, DISABLED_ ## test_name, ::testing::Test, Body, CV__TEST_BIGDATA_BODY_IMPL)
#endif
#undef TEST_F
#define TEST_F(test_fixture, test_name)\
class GTEST_TEST_CLASS_NAME_(test_fixture, test_name) : public test_fixture {\
public:\
GTEST_TEST_CLASS_NAME_(test_fixture, test_name)() {}\
private:\
virtual void TestBody() CV_OVERRIDE;\
virtual void Body(); \
static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\
GTEST_DISALLOW_COPY_AND_ASSIGN_(\
GTEST_TEST_CLASS_NAME_(test_fixture, test_name));\
};\
\
::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_fixture, test_name)\
::test_info_ =\
::testing::internal::MakeAndRegisterTestInfo(\
#test_fixture, #test_name, NULL, NULL, \
::testing::internal::CodeLocation(__FILE__, __LINE__), \
(::testing::internal::GetTypeId<test_fixture>()), \
test_fixture::SetUpTestCase, \
test_fixture::TearDownTestCase, \
new ::testing::internal::TestFactoryImpl<\
GTEST_TEST_CLASS_NAME_(test_fixture, test_name)>);\
void GTEST_TEST_CLASS_NAME_(test_fixture, test_name)::TestBody() CV__TEST_BODY_IMPL( #test_fixture "_" #test_name ) \
void GTEST_TEST_CLASS_NAME_(test_fixture, test_name)::Body()
// Don't use directly
#define CV__TEST_P(test_case_name, test_name, bodyMethodName, BODY_IMPL/*(name_str)*/) \
class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
: public test_case_name { \
public: \
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \
private: \
virtual void bodyMethodName(); \
virtual void TestBody() CV_OVERRIDE; \
static int AddToRegistry() { \
::testing::UnitTest::GetInstance()->parameterized_test_registry(). \
GetTestCasePatternHolder<test_case_name>(\
#test_case_name, \
::testing::internal::CodeLocation(\
__FILE__, __LINE__))->AddTestPattern(\
#test_case_name, \
#test_name, \
new ::testing::internal::TestMetaFactory< \
GTEST_TEST_CLASS_NAME_(\
test_case_name, test_name)>()); \
return 0; \
} \
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
GTEST_DISALLOW_COPY_AND_ASSIGN_(\
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \
}; \
int GTEST_TEST_CLASS_NAME_(test_case_name, \
test_name)::gtest_registering_dummy_ = \
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() BODY_IMPL( #test_case_name "_" #test_name ) \
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::bodyMethodName()
#undef TEST_P
#define TEST_P(test_case_name, test_name) CV__TEST_P(test_case_name, test_name, Body, CV__TEST_BODY_IMPL)
#define CV_TEST_EXPECT_EXCEPTION_MESSAGE(statement, msg) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
const char* msg_ = msg; \
bool hasException = false; \
try { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} \
catch (const cv::Exception& e) { \
if (NULL == strstr(e.what(), msg_)) \
ADD_FAILURE() << "Unexpected cv::Exception is raised: " << #statement << "\n Expected message substring: '" << msg_ << "'. Actual message:\n" << e.what(); \
hasException = true; \
} \
catch (const std::exception& e) { \
ADD_FAILURE() << "Unexpected std::exception is raised: " << #statement << "\n" << e.what(); \
hasException = true; \
} \
catch (...) { \
ADD_FAILURE() << "Unexpected C++ exception is raised: " << #statement; \
hasException = true; \
} \
if (!hasException) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_test_, __LINE__); \
} \
} else \
GTEST_CONCAT_TOKEN_(gtest_label_test_, __LINE__): \
ADD_FAILURE() << "Failed: Expected: " #statement " throws an '" << msg << "' exception.\n" \
" Actual: it doesn't."
#endif // OPENCV_TS_EXT_HPP
| 3,475 |
28,056 | package com.alibaba.json.bvt.parser.deser.list;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import junit.framework.TestCase;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.ParserConfig;
public class ArrayListStringDeserializerTest extends TestCase {
public void test_null() throws Exception {
Assert.assertNull(JSON.parseObject("null", new TypeReference<List<String>>() {
}));
Assert.assertNull(JSON.parseArray("null", new Type[] {new TypeReference<List<String>>() {
}.getType()}));
Assert.assertNull(JSON.parseArray("null", Entity.class));
Assert.assertNull(JSON.parseArray("null", Entity[].class));
Assert.assertNull(JSON.parseArray("null"));
Assert.assertNull(JSON.parseObject("null"));
Assert.assertNull(JSON.parseObject("null", Object[].class));
Assert.assertNull(JSON.parseObject("null", Entity[].class));
Assert.assertNull(JSON.parseArray("[null]", new Type[] {new TypeReference<List<String>>() {
}.getType()}).get(0));
}
public void test_strings() throws Exception {
Entity a = JSON.parseObject("{units:['NANOSECONDS', 'SECONDS', 3, null]}", Entity.class);
Assert.assertEquals("NANOSECONDS", a.getUnits().get(0));
Assert.assertEquals("SECONDS", a.getUnits().get(1));
Assert.assertEquals("3", a.getUnits().get(2));
Assert.assertEquals(null, a.getUnits().get(3));
}
public void test_strings_() throws Exception {
Entity a = JSON.parseObject("{units:['NANOSECONDS',,,, 'SECONDS', 3, null]}", Entity.class);
Assert.assertEquals("NANOSECONDS", a.getUnits().get(0));
Assert.assertEquals("SECONDS", a.getUnits().get(1));
Assert.assertEquals("3", a.getUnits().get(2));
Assert.assertEquals(null, a.getUnits().get(3));
}
public void test_strings_2() throws Exception {
List<String> list = JSON.parseObject("['NANOSECONDS', 'SECONDS', 3, null]", new TypeReference<List<String>>() {
});
Assert.assertEquals("NANOSECONDS", list.get(0));
Assert.assertEquals("SECONDS", list.get(1));
Assert.assertEquals("3", list.get(2));
Assert.assertEquals(null, list.get(3));
}
public void test_strings_3() throws Exception {
List<String> list = JSON.parseObject("['NANOSECONDS', 'SECONDS', 3, null]", new TypeReference<List<String>>() {
}.getType(), 0, Feature.AllowSingleQuotes);
Assert.assertEquals("NANOSECONDS", list.get(0));
Assert.assertEquals("SECONDS", list.get(1));
Assert.assertEquals("3", list.get(2));
Assert.assertEquals(null, list.get(3));
}
public void test_string_error_not_eof() throws Exception {
JSONException ex = null;
try {
JSON.parseObject("[}", new TypeReference<List<String>>() {
}.getType(), 0, Feature.AllowSingleQuotes);
} catch (JSONException e) {
ex = e;
}
Assert.assertNotNull(ex);
}
public void test_string_error() throws Exception {
JSONException ex = null;
try {
JSON.parseObject("'123'", new TypeReference<List<String>>() {
});
} catch (JSONException e) {
ex = e;
}
Assert.assertNotNull(ex);
}
public void test_string_error_1() throws Exception {
JSONException ex = null;
try {
parseObject("{units:['NANOSECONDS',,,, 'SECONDS', 3, null]}", Entity.class);
} catch (JSONException e) {
ex = e;
}
Assert.assertNotNull(ex);
}
public static final <T> T parseObject(String input, Type clazz, Feature... features) {
if (input == null) {
return null;
}
int featureValues = 0;
for (Feature feature : features) {
featureValues = Feature.config(featureValues, feature, true);
}
DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues);
T value = (T) parser.parseObject(clazz);
if (clazz != JSONArray.class) {
parser.close();
}
return (T) value;
}
public static class Entity {
private List<String> units = new ArrayList<String>();
public List<String> getUnits() {
return units;
}
public void setUnits(List<String> units) {
this.units = units;
}
}
}
| 2,060 |
2,151 | /*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gl/GrGLVaryingHandler.h"
#include "gl/GrGLGpu.h"
#include "gl/builders/GrGLProgramBuilder.h"
GrGLSLVaryingHandler::VaryingHandle GrGLVaryingHandler::addPathProcessingVarying(
const char* name,
GrGLSLVarying* v) {
#ifdef SK_DEBUG
GrGLProgramBuilder* glPB = (GrGLProgramBuilder*) fProgramBuilder;
// This call is not used for non-NVPR backends.
SkASSERT(glPB->gpu()->glCaps().shaderCaps()->pathRenderingSupport() &&
glPB->fPrimProc.isPathRendering() &&
!glPB->fPrimProc.willUseGeoShader() &&
glPB->fPrimProc.numAttribs() == 0);
#endif
this->addVarying(name, v);
auto varyingInfo = fPathProcVaryingInfos.push_back();
varyingInfo.fLocation = fPathProcVaryingInfos.count() - 1;
return VaryingHandle(varyingInfo.fLocation);
}
void GrGLVaryingHandler::onFinalize() {
SkASSERT(fPathProcVaryingInfos.empty() || fPathProcVaryingInfos.count() == fFragInputs.count());
for (int i = 0; i < fPathProcVaryingInfos.count(); ++i) {
fPathProcVaryingInfos[i].fVariable = fFragInputs[i];
}
}
| 644 |
347 | <filename>frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/uicommon/disks/DisksViewColumns.java
package org.ovirt.engine.ui.common.widget.uicommon.disks;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskContentType;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.DiskInterface;
import org.ovirt.engine.core.common.businessentities.storage.DiskStorageType;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.common.businessentities.storage.LunDisk;
import org.ovirt.engine.core.common.businessentities.storage.StorageType;
import org.ovirt.engine.core.common.businessentities.storage.VolumeType;
import org.ovirt.engine.core.common.utils.SizeConverter;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.StringFormat;
import org.ovirt.engine.ui.common.CommonApplicationConstants;
import org.ovirt.engine.ui.common.CommonApplicationResources;
import org.ovirt.engine.ui.common.gin.AssetProvider;
import org.ovirt.engine.ui.common.widget.table.cell.Cell;
import org.ovirt.engine.ui.common.widget.table.cell.StatusCompositeCell;
import org.ovirt.engine.ui.common.widget.table.column.AbstractColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractDiskSizeColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractEnumColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractFullDateTimeColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractImageResourceColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractLinkColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractTextColumn;
import org.ovirt.engine.ui.common.widget.table.column.DiskContainersColumn;
import org.ovirt.engine.ui.common.widget.table.column.DiskProgressColumn;
import org.ovirt.engine.ui.common.widget.table.column.DiskStatusColumn;
import org.ovirt.engine.ui.common.widget.table.column.DiskTransferProgressColumn;
import org.ovirt.engine.ui.common.widget.table.column.StorageDomainsColumn;
import org.ovirt.engine.ui.uicompat.EnumTranslator;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
public class DisksViewColumns {
private static final CommonApplicationResources resources = AssetProvider.getResources();
private static final CommonApplicationConstants constants = AssetProvider.getConstants();
private static final Predicate<Disk> diskImagePredicate =
disk -> disk.getDiskStorageType() == DiskStorageType.IMAGE ||
disk.getDiskStorageType() == DiskStorageType.MANAGED_BLOCK_STORAGE;
public static AbstractTextColumn<Disk> getAliasColumn(String sortBy) {
return getAliasColumn(null, sortBy);
}
public static AbstractTextColumn<Disk> getAliasColumn(FieldUpdater<Disk, String> updater, String sortBy) {
AbstractTextColumn<Disk> column;
if (updater != null) {
column = new AbstractLinkColumn<Disk>(updater) {
@Override
public String getValue(Disk object) {
return object.getName();
}
};
} else {
column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
return object.getName();
}
};
}
return makeSortable(column, sortBy);
}
public static AbstractTextColumn<Disk> getIdColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
return object.getId().toString();
}
};
return makeSortable(column, sortBy);
}
public static AbstractTextColumn<Disk> getQoutaColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
String value = "";
if (object.getDiskStorageType() == DiskStorageType.IMAGE) {
DiskImage diskImage = (DiskImage) object;
List<String> quotaNamesArr = diskImage.getQuotaNames();
if (quotaNamesArr != null) {
value = String.join(", ", quotaNamesArr);//$NON-NLS-1$
}
}
return value;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractImageResourceColumn<Disk> bootableDiskColumn = new AbstractImageResourceColumn<Disk>() {
{
setContextMenuTitle(constants.bootableDisk());
}
@Override
public ImageResource getValue(Disk object) {
if (object.getDiskVmElements().size() == 1) {
if (object.getDiskVmElements().iterator().next().isBoot()) {
return getDefaultImage();
}
}
return null;
}
@Override
public ImageResource getDefaultImage() {
return resources.bootableDiskIcon();
}
@Override
public SafeHtml getTooltip(Disk object) {
if (object.getDiskVmElements().size() == 1) {
if (object.getDiskVmElements().iterator().next().isBoot()) {
return SafeHtmlUtils.fromSafeConstant(constants.bootableDisk());
}
}
return null;
}
};
public static AbstractImageResourceColumn<Disk> getShareableDiskColumn() {
AbstractImageResourceColumn<Disk> shareableDiskColumn = new AbstractImageResourceColumn<Disk>() {
{
setContextMenuTitle(constants.shareable());
}
@Override
public ImageResource getValue(Disk object) {
return object.isShareable() ? getDefaultImage() : null;
}
@Override
public ImageResource getDefaultImage() {
return resources.shareableDiskIcon();
}
@Override
public SafeHtml getTooltip(Disk object) {
if (object.isShareable()) {
return SafeHtmlUtils.fromSafeConstant(constants.shareable());
}
return null;
}
};
shareableDiskColumn.makeSortable(Comparator.comparing(Disk::isShareable));
return shareableDiskColumn;
}
public static final AbstractImageResourceColumn<Disk> readOnlyDiskColumn = new AbstractImageResourceColumn<Disk>() {
{
setContextMenuTitle(constants.readOnly());
}
@Override
public ImageResource getValue(Disk object) {
if (object.getDiskVmElements().size() == 1) {
return object.getDiskVmElements().iterator().next().isReadOnly() ? getDefaultImage() : null;
}
return null;
}
@Override
public ImageResource getDefaultImage() {
return resources.readOnlyDiskIcon();
}
@Override
public SafeHtml getTooltip(Disk object) {
if (object.getDiskVmElements().size() == 1) {
return object.getDiskVmElements().iterator().next().isReadOnly() ?
SafeHtmlUtils.fromSafeConstant(constants.readOnly()) : null;
}
return null;
}
};
public static final AbstractImageResourceColumn<Disk> diskContainersIconColumn = new AbstractImageResourceColumn<Disk>() {
{
setContextMenuTitle(constants.containersIconDisk());
}
@Override
public ImageResource getValue(Disk object) {
if (object.getVmEntityType() == null) {
return null;
}
return object.getVmEntityType().isVmType() ? resources.vmsImage() :
object.getVmEntityType().isTemplateType() ? resources.templatesImage() : null;
}
@Override
public SafeHtml getTooltip(Disk object) {
if (object.getVmEntityType() == null) {
return SafeHtmlUtils.fromSafeConstant(constants.unattachedDisk());
} else {
String status = EnumTranslator.getInstance().translate(object.getVmEntityType());
return SafeHtmlUtils.fromString(status);
}
}
};
public static final DiskStatusColumn diskStatusColumn = new DiskStatusColumn() {
{
setContextMenuTitle(constants.statusDisk());
}
};
public static final DiskContainersColumn getdiskContainersColumn(String sortBy){
DiskContainersColumn diskContainersColumn = new DiskContainersColumn();
makeSortable(diskContainersColumn, sortBy);
return diskContainersColumn;
}
public static final StorageDomainsColumn getStorageDomainsColumn(String sortBy) {
StorageDomainsColumn storageDomainsColumn = new StorageDomainsColumn();
makeSortable(storageDomainsColumn, sortBy);
return storageDomainsColumn;
}
public static final AbstractTextColumn<Disk> storageTypeColumn = new AbstractEnumColumn<Disk, StorageType>() {
@Override
protected StorageType getRawValue(Disk object) {
if (!diskImagePredicate.test(object)) {
return null;
}
DiskImage disk = (DiskImage) object;
return disk.getStorageTypes().isEmpty() ? null : disk.getStorageTypes().get(0);
}
};
public static final AbstractDiskSizeColumn<Disk> getSizeColumn(String sortBy) {
AbstractDiskSizeColumn<Disk> column = new AbstractDiskSizeColumn<Disk>() {
@Override
protected Long getRawValue(Disk object) {
switch (object.getDiskStorageType()) {
case LUN:
return (long) (((LunDisk) object).getLun().getDeviceSize() * Math.pow(1024, 3));
default:
return object.getSize();
}
}
};
return makeSortable(column, sortBy);
}
public static final AbstractDiskSizeColumn<Disk> getActualSizeColumn(String sortBy) {
AbstractDiskSizeColumn<Disk> column = new AbstractDiskSizeColumn<Disk>(SizeConverter.SizeUnit.GiB) {
@Override
protected Long getRawValue(Disk object) {
return diskImagePredicate.test(object) ?
Math.round(((DiskImage) object).getActualDiskWithSnapshotsSize())
: (long) ((LunDisk) object).getLun().getDeviceSize();
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getAllocationColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractEnumColumn<Disk, VolumeType>() {
@Override
protected VolumeType getRawValue(Disk object) {
return diskImagePredicate.test(object) ? ((DiskImage) object).getVolumeType() : null;
}
@Override
public SafeHtml getTooltip(Disk object) {
if (!diskImagePredicate.test(object)) {
return null;
}
VolumeType originalVolumeType = null;
for (DiskImage snapshot : ((DiskImage) object).getSnapshots()) {
if (snapshot.getParentId() == null || snapshot.getParentId().equals(Guid.Empty)) {
originalVolumeType = snapshot.getVolumeType();
break;
}
}
if (originalVolumeType == null) {
return null;
}
return SafeHtmlUtils.fromString(
StringFormat.format("%s: %s", //$NON-NLS-1$
AssetProvider.getConstants().originalAllocationDisk(),
EnumTranslator.getInstance().translate(originalVolumeType)));
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getInterfaceColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractEnumColumn<Disk, DiskInterface>() {
@Override
protected DiskInterface getRawValue(Disk object) {
if (object.getDiskVmElements().size() == 1) {
return object.getDiskVmElements().iterator().next().getDiskInterface();
}
return null;
}
};
return makeSortable(column, sortBy);
}
public static AbstractTextColumn<Disk> getLogicalNameColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
if (object.getDiskVmElements().size() == 1) {
return object.getDiskVmElements().iterator().next().getLogicalName();
}
return null;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractFullDateTimeColumn<Disk> getDateCreatedColumn(String sortBy) {
AbstractFullDateTimeColumn<Disk> column = new AbstractFullDateTimeColumn<Disk>() {
@Override
protected Date getRawValue(Disk object) {
return diskImagePredicate.test(object) ? ((DiskImage) object).getCreationDate() : null;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractFullDateTimeColumn<Disk> getSnapshotCreationDateColumn(String sortBy) {
AbstractFullDateTimeColumn<Disk> column = new AbstractFullDateTimeColumn<Disk>() {
@Override
protected Date getRawValue(Disk object) {
return diskImagePredicate.test(object) ? ((DiskImage) object).getSnapshotCreationDate() : null;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractFullDateTimeColumn<Disk> getDateModifiedColumn(String sortBy) {
AbstractFullDateTimeColumn<Disk> column = new AbstractFullDateTimeColumn<Disk>() {
@Override
protected Date getRawValue(Disk object) {
return diskImagePredicate.test(object) ? ((DiskImage) object).getLastModified() : null;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractColumn<Disk, Disk> getStatusColumn(String sortBy) {
DiskTransferProgressColumn uploadImageProgressColumn = new DiskTransferProgressColumn();
DiskProgressColumn diskProgressColumn = new DiskProgressColumn();
List<HasCell<Disk, ?>> list = new ArrayList<>();
list.add(getStatusOnlyColumn(null));
list.add(uploadImageProgressColumn);
list.add(diskProgressColumn);
Cell<Disk> compositeCell = new StatusCompositeCell<>(list);
AbstractColumn<Disk, Disk> column = new AbstractColumn<Disk, Disk>(compositeCell) {
@Override
public Disk getValue(Disk object) {
return object;
}
};
if (sortBy != null) {
column.makeSortable(sortBy);
}
return column;
}
public static final AbstractTextColumn<Disk> getStatusOnlyColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractEnumColumn<Disk, ImageStatus>() {
@Override
protected ImageStatus getRawValue(Disk object) {
return diskImagePredicate.test(object) ? ((DiskImage) object).getImageStatus() : null;
}
@Override
public String getValue(Disk object) {
if (object.getImageTransferPhase() != null) {
// will be rendered by progress column
return null;
}
return super.getValue(object);
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getDescriptionColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
return object.getDiskDescription();
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getContentColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractEnumColumn<Disk, DiskContentType>() {
@Override
protected DiskContentType getRawValue(Disk object) {
return object.getContentType();
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getLunIdColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
return object.getDiskStorageType() == DiskStorageType.LUN ?
((LunDisk) object).getLun().getLUNId() : null;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getLunVendorIdColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
return object.getDiskStorageType() == DiskStorageType.LUN ?
((LunDisk) object).getLun().getVendorId() : null;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getLunProductIdColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
return object.getDiskStorageType() == DiskStorageType.LUN ?
((LunDisk) object).getLun().getProductId() : null;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getLunSerialColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
return object.getDiskStorageType() == DiskStorageType.LUN ?
((LunDisk) object).getLun().getSerial() : null;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractDiskSizeColumn<Disk> getSnapshotSizeColumn(String sortBy) {
AbstractDiskSizeColumn<Disk> column = new AbstractDiskSizeColumn<Disk>() {
@Override
protected Long getRawValue(Disk object) {
return ((DiskImage) object).getActualSizeInBytes();
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getSnapshotDescriptionColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk object) {
return ((DiskImage) object).getVmSnapshotDescription();
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getDiskSnapshotIDColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() {
@Override
public String getValue(Disk disk) {
return diskImagePredicate.test(disk) ? ((DiskImage) disk).getImageId().toString() : null;
}
};
return makeSortable(column, sortBy);
}
public static final AbstractTextColumn<Disk> getDiskStorageTypeColumn(String sortBy) {
AbstractTextColumn<Disk> column = new AbstractEnumColumn<Disk, DiskStorageType>() {
@Override
protected DiskStorageType getRawValue(Disk object) {
return object.getDiskStorageType();
}
};
return makeSortable(column, sortBy);
}
public static <C extends AbstractTextColumn<T>, T> C makeSortable(C column, String sortBy) {
if (sortBy == null ) {
// Client sorting
column.makeSortable();
} else if (!sortBy.equals(constants.empty())) {
// Server sorting
column.makeSortable(sortBy);
}
return column;
}
}
| 9,115 |
3,631 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.dmn.core.impl;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Optional;
import org.kie.dmn.api.core.DMNContext;
import org.kie.dmn.api.core.DMNMetadata;
import org.kie.dmn.api.core.FEELPropertyAccessible;
import org.kie.dmn.core.impl.DMNContextImpl.ScopeReference;
public class DMNContextFPAImpl implements DMNContext {
private final FEELPropertyAccessible fpa;
private Deque<ScopeReference> stack = new LinkedList<>();
private DMNMetadataImpl metadata;
public DMNContextFPAImpl(FEELPropertyAccessible bean) {
this.fpa = bean;
this.metadata = new DMNMetadataImpl();
}
@Override
public Object set(String name, Object value) {
throw new UnsupportedOperationException();
}
@Override
public Object get(String name) {
return fpa.getFEELProperty(name).toOptional().orElse(null);
}
/**
* Internal utility method
*
* @return FEELPropertyAccessible which represents strongly typed context
*/
public FEELPropertyAccessible getFpa() {
return fpa;
}
private Map<String, Object> getCurrentEntries() {
if (stack.isEmpty()) {
return fpa.allFEELProperties();
} else {
return stack.peek().getRef(); // Intentional, symbol resolution in scope should limit at the top of the stack (for DMN semantic).
}
}
@Override
public void pushScope(String name, String namespace) {
Map<String, Object> scopeRef = (Map<String, Object>) getCurrentEntries().computeIfAbsent(name, s -> new LinkedHashMap<String, Object>());
stack.push(new ScopeReference(name, namespace, scopeRef));
}
@Override
public void popScope() {
stack.pop();
}
@Override
public Optional<String> scopeNamespace() {
if (stack.isEmpty()) {
return Optional.empty();
} else {
return Optional.of(stack.peek().getNamespace());
}
}
@Override
public Map<String, Object> getAll() {
return getCurrentEntries();
}
@Override
public boolean isDefined(String name) {
return getCurrentEntries().containsKey(name);
}
@Override
public DMNMetadata getMetadata() {
return this.metadata;
}
@Override
public DMNContext clone() {
DMNContextImpl newCtx = new DMNContextImpl(fpa.allFEELProperties(), metadata.asMap());
for (ScopeReference e : stack) {
newCtx.pushScope(e.getName(), e.getNamespace());
}
return newCtx;
}
}
| 1,201 |
575 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_BASE_ENUM_SET_H_
#define COMPONENTS_SYNC_BASE_ENUM_SET_H_
#include <bitset>
#include <cstddef>
#include <string>
#include <type_traits>
#include <utility>
#include "base/check_op.h"
namespace syncer {
// Forward declarations needed for friend declarations.
template <typename E, E MinEnumValue, E MaxEnumValue>
class EnumSet;
template <typename E, E Min, E Max>
EnumSet<E, Min, Max> Union(EnumSet<E, Min, Max> set1,
EnumSet<E, Min, Max> set2);
template <typename E, E Min, E Max>
EnumSet<E, Min, Max> Intersection(EnumSet<E, Min, Max> set1,
EnumSet<E, Min, Max> set2);
template <typename E, E Min, E Max>
EnumSet<E, Min, Max> Difference(EnumSet<E, Min, Max> set1,
EnumSet<E, Min, Max> set2);
// An EnumSet is a set that can hold enum values between a min and a
// max value (inclusive of both). It's essentially a wrapper around
// std::bitset<> with stronger type enforcement, more descriptive
// member function names, and an iterator interface.
//
// If you're working with enums with a small number of possible values
// (say, fewer than 64), you can efficiently pass around an EnumSet
// for that enum around by value.
template <typename E, E MinEnumValue, E MaxEnumValue>
class EnumSet {
private:
static_assert(
std::is_enum<E>::value,
"First template parameter of EnumSet must be an enumeration type");
using enum_underlying_type = std::underlying_type_t<E>;
static constexpr enum_underlying_type GetUnderlyingValue(E value) {
return static_cast<enum_underlying_type>(value);
}
public:
using EnumType = E;
static const E kMinValue = MinEnumValue;
static const E kMaxValue = MaxEnumValue;
static const size_t kValueCount =
GetUnderlyingValue(kMaxValue) - GetUnderlyingValue(kMinValue) + 1;
static_assert(kMinValue < kMaxValue, "min value must be less than max value");
private:
// Declaration needed by Iterator.
using EnumBitSet = std::bitset<kValueCount>;
public:
// Iterator is a forward-only read-only iterator for EnumSet. It follows the
// common STL input iterator interface (like std::unordered_set).
//
// Example usage, using a range-based for loop:
//
// EnumSet<SomeType> enums;
// for (SomeType val : enums) {
// Process(val);
// }
//
// Or using an explicit iterator (not recommended):
//
// for (EnumSet<...>::Iterator it = enums.begin(); it != enums.end(); it++) {
// Process(*it);
// }
//
// The iterator must not be outlived by the set. In particular, the following
// is an error:
//
// EnumSet<...> SomeFn() { ... }
//
// /* ERROR */
// for (EnumSet<...>::Iterator it = SomeFun().begin(); ...
//
// Also, there are no guarantees as to what will happen if you
// modify an EnumSet while traversing it with an iterator.
class Iterator {
public:
Iterator() : enums_(nullptr), i_(kValueCount) {}
~Iterator() {}
bool operator==(const Iterator& other) const { return i_ == other.i_; }
bool operator!=(const Iterator& other) const { return !(*this == other); }
E operator*() const {
DCHECK(Good());
return FromIndex(i_);
}
Iterator& operator++() {
DCHECK(Good());
// If there are no more set elements in the bitset, this will result in an
// index equal to kValueCount, which is equivalent to EnumSet.end().
i_ = FindNext(i_ + 1);
return *this;
}
Iterator operator++(int) {
DCHECK(Good());
Iterator old(*this);
// If there are no more set elements in the bitset, this will result in an
// index equal to kValueCount, which is equivalent to EnumSet.end().
i_ = FindNext(i_ + 1);
return std::move(old);
}
private:
friend Iterator EnumSet::begin() const;
explicit Iterator(const EnumBitSet& enums)
: enums_(&enums), i_(FindNext(0)) {}
// Returns true iff the iterator points to an EnumSet and it
// hasn't yet traversed the EnumSet entirely.
bool Good() const { return enums_ && i_ < kValueCount && enums_->test(i_); }
size_t FindNext(size_t i) {
while ((i < kValueCount) && !enums_->test(i)) {
++i;
}
return i;
}
const EnumBitSet* enums_;
size_t i_;
};
EnumSet() {}
~EnumSet() = default;
static constexpr uint64_t single_val_bitstring(E val) {
return 1ULL << (ToIndex(val));
}
template <class... T>
static constexpr uint64_t bitstring(T... values) {
uint64_t converted[] = {single_val_bitstring(values)...};
uint64_t result = 0;
for (uint64_t e : converted)
result |= e;
return result;
}
template <class... T>
constexpr EnumSet(E head, T... tail)
: EnumSet(EnumBitSet(bitstring(head, tail...))) {}
// Returns an EnumSet with all possible values.
static constexpr EnumSet All() {
return EnumSet(EnumBitSet((1ULL << kValueCount) - 1));
}
// Returns an EnumSet with all the values from start to end, inclusive.
static constexpr EnumSet FromRange(E start, E end) {
return EnumSet(EnumBitSet(
((single_val_bitstring(end)) - (single_val_bitstring(start))) |
(single_val_bitstring(end))));
}
// Copy constructor and assignment welcome.
// Set operations. Put, Retain, and Remove are basically
// self-mutating versions of Union, Intersection, and Difference
// (defined below).
// Adds the given value (which must be in range) to our set.
void Put(E value) { enums_.set(ToIndex(value)); }
// Adds all values in the given set to our set.
void PutAll(EnumSet other) { enums_ |= other.enums_; }
// Adds all values in the given range to our set, inclusive.
void PutRange(E start, E end) {
size_t endIndexInclusive = ToIndex(end);
DCHECK_LE(ToIndex(start), endIndexInclusive);
for (size_t current = ToIndex(start); current <= endIndexInclusive;
++current) {
enums_.set(current);
}
}
// There's no real need for a Retain(E) member function.
// Removes all values not in the given set from our set.
void RetainAll(EnumSet other) { enums_ &= other.enums_; }
// If the given value is in range, removes it from our set.
void Remove(E value) {
if (InRange(value)) {
enums_.reset(ToIndex(value));
}
}
// Removes all values in the given set from our set.
void RemoveAll(EnumSet other) { enums_ &= ~other.enums_; }
// Removes all values from our set.
void Clear() { enums_.reset(); }
// Returns true iff the given value is in range and a member of our set.
constexpr bool Has(E value) const {
return InRange(value) && enums_[ToIndex(value)];
}
// Returns true iff the given set is a subset of our set.
bool HasAll(EnumSet other) const {
return (enums_ & other.enums_) == other.enums_;
}
// Returns true iff our set is empty.
bool Empty() const { return !enums_.any(); }
// Returns how many values our set has.
size_t Size() const { return enums_.count(); }
// Returns an iterator pointing to the first element (if any).
Iterator begin() const { return Iterator(enums_); }
// Returns an iterator that does not point to any element, but to the position
// that follows the last element in the set.
Iterator end() const { return Iterator(); }
// Returns true iff our set and the given set contain exactly the same values.
bool operator==(const EnumSet& other) const { return enums_ == other.enums_; }
// Returns true iff our set and the given set do not contain exactly the same
// values.
bool operator!=(const EnumSet& other) const { return enums_ != other.enums_; }
private:
friend EnumSet Union<E, MinEnumValue, MaxEnumValue>(EnumSet set1,
EnumSet set2);
friend EnumSet Intersection<E, MinEnumValue, MaxEnumValue>(EnumSet set1,
EnumSet set2);
friend EnumSet Difference<E, MinEnumValue, MaxEnumValue>(EnumSet set1,
EnumSet set2);
// A bitset can't be constexpr constructed if it has size > 64, since the
// constexpr constructor uses a uint64_t. If your EnumSet has > 64 values, you
// can safely remove the constepxr qualifiers from this file, at the cost of
// some minor optimizations.
explicit constexpr EnumSet(EnumBitSet enums) : enums_(enums) {
static_assert(kValueCount < 64,
"Max number of enum values is 64 for constexpr ");
}
static constexpr bool InRange(E value) {
return (value >= MinEnumValue) && (value <= MaxEnumValue);
}
// Converts a value to/from an index into |enums_|.
static constexpr size_t ToIndex(E value) {
return GetUnderlyingValue(value) - GetUnderlyingValue(MinEnumValue);
}
static E FromIndex(size_t i) {
DCHECK_LT(i, kValueCount);
return static_cast<E>(GetUnderlyingValue(MinEnumValue) + i);
}
EnumBitSet enums_;
};
template <typename E, E MinEnumValue, E MaxEnumValue>
const E EnumSet<E, MinEnumValue, MaxEnumValue>::kMinValue;
template <typename E, E MinEnumValue, E MaxEnumValue>
const E EnumSet<E, MinEnumValue, MaxEnumValue>::kMaxValue;
template <typename E, E MinEnumValue, E MaxEnumValue>
const size_t EnumSet<E, MinEnumValue, MaxEnumValue>::kValueCount;
// The usual set operations.
template <typename E, E Min, E Max>
EnumSet<E, Min, Max> Union(EnumSet<E, Min, Max> set1,
EnumSet<E, Min, Max> set2) {
return EnumSet<E, Min, Max>(set1.enums_ | set2.enums_);
}
template <typename E, E Min, E Max>
EnumSet<E, Min, Max> Intersection(EnumSet<E, Min, Max> set1,
EnumSet<E, Min, Max> set2) {
return EnumSet<E, Min, Max>(set1.enums_ & set2.enums_);
}
template <typename E, E Min, E Max>
EnumSet<E, Min, Max> Difference(EnumSet<E, Min, Max> set1,
EnumSet<E, Min, Max> set2) {
return EnumSet<E, Min, Max>(set1.enums_ & ~set2.enums_);
}
} // namespace syncer
#endif // COMPONENTS_SYNC_BASE_ENUM_SET_H_
| 3,891 |
1,093 | /*
* Copyright 2002-2020 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.util;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.fail;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test;
import org.springframework.integration.test.util.TestUtils;
/**
* @author <NAME>
* @author <NAME>
* @since 2.2
*
*/
public class SimplePoolTests {
@Test
public void testReuseAndStale() {
final Set<String> strings = new HashSet<String>();
final AtomicBoolean stale = new AtomicBoolean();
SimplePool<String> pool = stringPool(2, strings, stale);
String s1 = pool.getItem();
String s2 = pool.getItem();
assertThat(s2).isNotSameAs(s1);
pool.releaseItem(s1);
String s3 = pool.getItem();
assertThat(s3).isSameAs(s1);
stale.set(true);
pool.releaseItem(s3);
s3 = pool.getItem();
assertThat(s3).isNotSameAs(s1);
assertThat(strings.remove(s1)).isFalse();
assertThat(pool.getAllocatedCount()).isEqualTo(2);
}
@Test
public void testOverCommitAndResize() {
final Set<String> strings = new HashSet<String>();
final AtomicBoolean stale = new AtomicBoolean();
SimplePool<String> pool = stringPool(2, strings, stale);
String s1 = pool.getItem();
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(1);
assertThat(pool.getAllocatedCount()).isEqualTo(1);
pool.releaseItem(s1);
assertThat(pool.getIdleCount()).isEqualTo(1);
assertThat(pool.getActiveCount()).isEqualTo(0);
assertThat(pool.getAllocatedCount()).isEqualTo(1);
s1 = pool.getItem();
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(1);
assertThat(pool.getAllocatedCount()).isEqualTo(1);
String s2 = pool.getItem();
assertThat(s2).isNotSameAs(s1);
pool.setWaitTimeout(1);
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(2);
assertThat(pool.getAllocatedCount()).isEqualTo(2);
try {
pool.getItem();
fail("Expected exception");
}
catch (PoolItemNotAvailableException e) {
}
// resize up
pool.setPoolSize(4);
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(2);
assertThat(pool.getAllocatedCount()).isEqualTo(2);
String s3 = pool.getItem();
String s4 = pool.getItem();
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(4);
assertThat(pool.getAllocatedCount()).isEqualTo(4);
pool.releaseItem(s4);
assertThat(pool.getIdleCount()).isEqualTo(1);
assertThat(pool.getActiveCount()).isEqualTo(3);
assertThat(pool.getAllocatedCount()).isEqualTo(4);
// resize down
pool.setPoolSize(2);
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(3);
assertThat(pool.getPoolSize()).isEqualTo(3);
assertThat(pool.getAllocatedCount()).isEqualTo(3);
pool.releaseItem(s3);
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(2);
assertThat(pool.getPoolSize()).isEqualTo(2);
assertThat(pool.getAllocatedCount()).isEqualTo(2);
assertThat(strings.size()).isEqualTo(2);
pool.releaseItem(s2);
pool.releaseItem(s1);
assertThat(pool.getIdleCount()).isEqualTo(2);
assertThat(pool.getActiveCount()).isEqualTo(0);
assertThat(pool.getPoolSize()).isEqualTo(2);
assertThat(strings.size()).isEqualTo(2);
assertThat(pool.getAllocatedCount()).isEqualTo(2);
}
@Test
public void testForeignObject() {
final Set<String> strings = new HashSet<String>();
final AtomicBoolean stale = new AtomicBoolean();
SimplePool<String> pool = stringPool(2, strings, stale);
pool.getItem();
assertThatIllegalArgumentException().isThrownBy(() -> pool.releaseItem("Hello, world!"));
}
@Test
public void testDoubleReturn() {
final Set<String> strings = new HashSet<String>();
final AtomicBoolean stale = new AtomicBoolean();
SimplePool<String> pool = stringPool(2, strings, stale);
Semaphore permits = TestUtils.getPropertyValue(pool, "permits", Semaphore.class);
assertThat(permits.availablePermits()).isEqualTo(2);
String s1 = pool.getItem();
assertThat(permits.availablePermits()).isEqualTo(1);
pool.releaseItem(s1);
assertThat(permits.availablePermits()).isEqualTo(2);
pool.releaseItem(s1);
assertThat(permits.availablePermits()).isEqualTo(2);
}
@Test
public void testSizeUpdateIfNotAllocated() {
SimplePool<String> pool = stringPool(10, new HashSet<>(), new AtomicBoolean());
pool.setWaitTimeout(0);
pool.setPoolSize(5);
assertThat(pool.getPoolSize()).isEqualTo(5);
// allocating all available items to check permits
Set<String> allocatedItems = new HashSet<>();
for (int i = 0; i < 5; i++) {
allocatedItems.add(pool.getItem());
}
assertThat(allocatedItems).hasSize(5);
// no more items can be allocated (indirect check of permits)
assertThatExceptionOfType(PoolItemNotAvailableException.class).isThrownBy(() -> pool.getItem());
}
@Test
public void testSizeUpdateIfPartiallyAllocated() {
SimplePool<String> pool = stringPool(10, new HashSet<>(), new AtomicBoolean());
pool.setWaitTimeout(0);
List<String> allocated = new ArrayList<>();
for (int i = 0; i < 10; i++) {
allocated.add(pool.getItem());
}
// release only 2 items
for (int i = 0; i < 2; i++) {
pool.releaseItem(allocated.get(i));
}
// trying to reduce pool size
pool.setPoolSize(5);
// at this moment the actual pool size can be reduced only partially, because
// only 2 items have been released, so 8 items are in use
assertThat(pool.getPoolSize()).isEqualTo(8);
assertThat(pool.getAllocatedCount()).isEqualTo(8);
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(8);
// releasing 3 items
for (int i = 2; i < 5; i++) {
pool.releaseItem(allocated.get(i));
}
// now pool size should be reduced
assertThat(pool.getPoolSize()).isEqualTo(5);
assertThat(pool.getAllocatedCount()).isEqualTo(5);
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(5);
// no more items can be allocated (indirect check of permits)
assertThatExceptionOfType(PoolItemNotAvailableException.class).isThrownBy(() -> pool.getItem());
}
@Test
public void testSizeUpdateIfFullyAllocated() {
SimplePool<String> pool = stringPool(10, new HashSet<>(), new AtomicBoolean());
pool.setWaitTimeout(0);
List<String> allocated = new ArrayList<>();
for (int i = 0; i < 10; i++) {
allocated.add(pool.getItem());
}
// trying to reduce pool size
pool.setPoolSize(5);
// at this moment the actual pool size cannot be reduced - all in use
assertThat(pool.getPoolSize()).isEqualTo(10);
assertThat(pool.getAllocatedCount()).isEqualTo(10);
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(10);
// releasing 5 items
for (int i = 0; i < 5; i++) {
pool.releaseItem(allocated.get(i));
}
// now pool size should be reduced
assertThat(pool.getPoolSize()).isEqualTo(5);
assertThat(pool.getAllocatedCount()).isEqualTo(5);
assertThat(pool.getIdleCount()).isEqualTo(0);
assertThat(pool.getActiveCount()).isEqualTo(5);
// no more items can be allocated (indirect check of permits)
assertThatExceptionOfType(PoolItemNotAvailableException.class).isThrownBy(() -> pool.getItem());
// releasing remaining items
for (int i = 5; i < 10; i++) {
pool.releaseItem(allocated.get(i));
}
assertThat(pool.getPoolSize()).isEqualTo(5);
assertThat(pool.getAllocatedCount()).isEqualTo(5);
assertThat(pool.getIdleCount()).isEqualTo(5);
assertThat(pool.getActiveCount()).isEqualTo(0);
}
@Test
void testClose() {
SimplePool<String> pool = stringPool(10, new HashSet<>(), new AtomicBoolean());
String item1 = pool.getItem();
String item2 = pool.getItem();
pool.releaseItem(item2);
assertThat(pool.getAllocatedCount()).isEqualTo(2);
pool.close();
pool.releaseItem(item1);
assertThat(pool.getAllocatedCount()).isEqualTo(0);
assertThatIllegalStateException().isThrownBy(pool::getItem);
}
private SimplePool<String> stringPool(int size, final Set<String> strings,
final AtomicBoolean stale) {
SimplePool<String> pool = new SimplePool<String>(size, new SimplePool.PoolItemCallback<String>() {
private int i;
@Override
public String createForPool() {
String string = "String" + i++;
strings.add(string);
return string;
}
@Override
public boolean isStale(String item) {
if (stale.get()) {
strings.remove(item);
}
return stale.get();
}
@Override
public void removedFromPool(String item) {
strings.remove(item);
}
});
return pool;
}
}
| 3,588 |
3,411 | /*
* Copyright 2015 <NAME>, <NAME>, <NAME>, and the JDA contributors
*
* 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 net.dv8tion.jda.internal.entities;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.WebhookClient;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.ComponentLayout;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.WebhookMessageUpdateAction;
import net.dv8tion.jda.api.utils.AttachmentOption;
import net.dv8tion.jda.internal.requests.RestActionImpl;
import net.dv8tion.jda.internal.requests.Route;
import net.dv8tion.jda.internal.requests.restaction.WebhookMessageActionImpl;
import net.dv8tion.jda.internal.requests.restaction.WebhookMessageUpdateActionImpl;
import net.dv8tion.jda.internal.utils.Checks;
import javax.annotation.Nonnull;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public abstract class AbstractWebhookClient<T> implements WebhookClient<T>
{
protected final long id;
protected final JDA api;
protected String token;
protected AbstractWebhookClient(long webhookId, String webhookToken, JDA api)
{
this.id = webhookId;
this.token = webhookToken;
this.api = api;
}
public abstract WebhookMessageActionImpl<T> sendRequest();
public abstract WebhookMessageUpdateActionImpl<T> editRequest(String messageId);
@Nonnull
@Override
public WebhookMessageActionImpl<T> sendMessage(@Nonnull String content)
{
return sendRequest().setContent(content);
}
@Nonnull
@Override
public WebhookMessageActionImpl<T> sendMessageEmbeds(@Nonnull Collection<? extends MessageEmbed> embeds)
{
return sendRequest().addEmbeds(embeds);
}
@Nonnull
@Override
public WebhookMessageActionImpl<T> sendMessage(@Nonnull Message message)
{
return sendRequest().applyMessage(message);
}
@Nonnull
@Override
public WebhookMessageActionImpl<T> sendFile(@Nonnull InputStream data, @Nonnull String name, @Nonnull AttachmentOption... options)
{
return sendRequest().addFile(data, name, options);
}
@Nonnull
@Override
public WebhookMessageUpdateActionImpl<T> editMessageById(@Nonnull String messageId, @Nonnull String content)
{
return (WebhookMessageUpdateActionImpl<T>) editRequest(messageId).setContent(content);
}
@Nonnull
@Override
public WebhookMessageUpdateAction<T> editMessageComponentsById(@Nonnull String messageId, @Nonnull Collection<? extends ComponentLayout> components)
{
Checks.noneNull(components, "Components");
if (components.stream().anyMatch(x -> !(x instanceof ActionRow)))
throw new UnsupportedOperationException("The provided component layout is not supported");
List<ActionRow> actionRows = components.stream().map(ActionRow.class::cast).collect(Collectors.toList());
return editRequest(messageId).setActionRows(actionRows);
}
@Nonnull
@Override
public WebhookMessageUpdateActionImpl<T> editMessageEmbedsById(@Nonnull String messageId, @Nonnull Collection<? extends MessageEmbed> embeds)
{
return (WebhookMessageUpdateActionImpl<T>) editRequest(messageId).setEmbeds(embeds);
}
@Nonnull
@Override
public WebhookMessageUpdateActionImpl<T> editMessageById(@Nonnull String messageId, @Nonnull Message message)
{
return (WebhookMessageUpdateActionImpl<T>) editRequest(messageId).applyMessage(message);
}
@Nonnull
@Override
public WebhookMessageUpdateActionImpl<T> editMessageById(@Nonnull String messageId, @Nonnull InputStream data, @Nonnull String name, @Nonnull AttachmentOption... options)
{
return (WebhookMessageUpdateActionImpl<T>) editRequest(messageId).addFile(data, name, options);
}
@Nonnull
@Override
public RestAction<Void> deleteMessageById(@Nonnull String messageId)
{
Checks.isSnowflake(messageId);
Route.CompiledRoute route = Route.Webhooks.EXECUTE_WEBHOOK_DELETE.compile(Long.toUnsignedString(id), token, messageId);
return new RestActionImpl<>(api, route);
}
}
| 1,820 |
379 | <filename>springdemo/src/main/java/com/example/springdemo/springdemo/controller/PictureController.java
package com.example.springdemo.springdemo.controller;
import com.example.springdemo.springdemo.Exception.NullOrEmptyException;
import com.example.springdemo.springdemo.common.ResponseEntity;
import com.example.springdemo.springdemo.domain.GetInfoFromWebDomain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
/**
* @program: springBootPractice
* @description:
* @author: hu_pf
* @create: 2019-07-18 17:14
**/
@Controller
@Slf4j
public class PictureController {
@RequestMapping("")
public String index(){
return "index";
}
@RequestMapping("/pic")
@ResponseBody
public ResponseEntity<String> pic(MultipartFile [] pictures, GetInfoFromWebDomain getInfoFromWebDomain) throws Exception {
log.info("getInfoFromWebDomain:",getInfoFromWebDomain);
ResponseEntity<String> responseEntity = new ResponseEntity<>();
long count = Arrays.asList(pictures).stream().
map(MultipartFile::getOriginalFilename).
filter(String::isEmpty).count();
if (count == pictures.length){
responseEntity.setCode(ResponseEntity.ERROR);
throw new NullOrEmptyException("图片不能同时为空");
}
responseEntity.setCode(ResponseEntity.OK);
responseEntity.setMessage("上传成功");
return responseEntity;
}
}
| 642 |
593 | <filename>linq/extensions/contains.h
/*=============================================================================
Copyright (c) 2012 <NAME>
contains.h
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef LINQ_GUARD_EXTENSIONS_CONTAINS_H
#define LINQ_GUARD_EXTENSIONS_CONTAINS_H
#include <linq/extensions/extension.h>
#include <linq/extensions/find.h>
#include <boost/range.hpp>
#include <linq/utility.h>
namespace linq {
//
// contains
//
namespace detail {
struct contains_t
{
template<class Range, class T>
bool operator()(Range && r, T && x) const
{ return (r | linq::find(x)) != boost::end(r); };
};
}
namespace {
range_extension<detail::contains_t> contains = {};
}
}
#endif
| 304 |
18,012 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.cache;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Local file interaction class that can back different caches.
* <p>
* All items in local file are of human friendly format.
*/
public class FileCacheStore {
private static final Logger logger = LoggerFactory.getLogger(FileCacheStore.class);
private String cacheFilePath;
private File cacheFile;
private File lockFile;
private FileLock directoryLock;
private FileCacheStore(String cacheFilePath, File cacheFile, File lockFile, FileLock directoryLock) {
this.cacheFilePath = cacheFilePath;
this.cacheFile = cacheFile;
this.lockFile = lockFile;
this.directoryLock = directoryLock;
}
public synchronized Map<String, String> loadCache(int entrySize) throws IOException {
Map<String, String> properties = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader(cacheFile))) {
int count = 1;
String line = reader.readLine();
while (line != null && count <= entrySize) {
// content has '=' need to be encoded before write
if (!line.startsWith("#") && line.contains("=")) {
String[] pairs = line.split("=");
properties.put(pairs[0], pairs[1]);
count++;
}
line = reader.readLine();
}
if (count > entrySize) {
logger.warn("Cache file was truncated for exceeding the maximum entry size " + entrySize);
}
} catch (IOException e) {
logger.warn("Load cache failed ", e);
throw e;
}
return properties;
}
private void unlock() {
if (directoryLock != null && directoryLock.isValid()) {
try {
directoryLock.release();
directoryLock.channel().close();
deleteFile(lockFile);
} catch (IOException e) {
throw new RuntimeException("Failed to release cache path's lock file:" + lockFile, e);
}
}
}
public synchronized void refreshCache(Map<String, String> properties, String comment, long maxFileSize) {
if (CollectionUtils.isEmptyMap(properties)) {
return;
}
try (LimitedLengthBufferedWriter bw =
new LimitedLengthBufferedWriter(
new OutputStreamWriter(
new FileOutputStream(cacheFile, false), StandardCharsets.UTF_8), maxFileSize)) {
bw.write("#" + comment);
bw.newLine();
bw.write("#" + new Date());
bw.newLine();
for (Map.Entry<String, String> e : properties.entrySet()) {
String key = e.getKey();
String val = e.getValue();
bw.write(key + "=" + val);
bw.newLine();
}
bw.flush();
long remainSize = bw.getRemainSize();
if (remainSize < 0) {
logger.info("Cache file was truncated for exceeding the maximum file size " + maxFileSize + " byte. Exceeded by " + (-remainSize) + " byte.");
}
} catch (IOException e) {
logger.warn("Update cache error.");
}
}
private static void deleteFile(File f) {
if (!f.delete()) {
logger.debug("Failed to delete file " + f.getAbsolutePath());
}
}
public synchronized void destroy() {
unlock();
FileCacheStoreFactory.removeCache(cacheFilePath);
}
/**
* for unit test only
*/
@Deprecated
protected String getCacheFilePath() {
return cacheFilePath;
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private String cacheFilePath;
private File cacheFile;
private File lockFile;
private FileLock directoryLock;
private Builder() {
}
public Builder cacheFilePath(String cacheFilePath) {
this.cacheFilePath = cacheFilePath;
return this;
}
public Builder cacheFile(File cacheFile) {
this.cacheFile = cacheFile;
return this;
}
public Builder lockFile(File lockFile) {
this.lockFile = lockFile;
return this;
}
public Builder directoryLock(FileLock directoryLock) {
this.directoryLock = directoryLock;
return this;
}
public FileCacheStore build() {
return new FileCacheStore(cacheFilePath, cacheFile, lockFile, directoryLock);
}
}
protected static class Empty extends FileCacheStore {
private Empty(String cacheFilePath) {
super(cacheFilePath, null, null, null);
}
public static Empty getInstance(String cacheFilePath) {
return new Empty(cacheFilePath);
}
@Override
public Map<String, String> loadCache(int entrySize) throws IOException {
return Collections.emptyMap();
}
@Override
public void refreshCache(Map<String, String> properties, String comment, long maxFileSize) {
}
}
private static class LimitedLengthBufferedWriter extends BufferedWriter {
private long remainSize;
public LimitedLengthBufferedWriter(Writer out, long maxSize) {
super(out);
this.remainSize = maxSize == 0 ? Long.MAX_VALUE : maxSize;
}
@Override
public void write(String str) throws IOException {
remainSize -= str.getBytes(StandardCharsets.UTF_8).length;
if (remainSize < 0) {
return;
}
super.write(str);
}
public long getRemainSize() {
return remainSize;
}
}
}
| 3,008 |
348 | <gh_stars>100-1000
{"nom":"Cahan","circ":"3ème circonscription","dpt":"Orne","inscrits":135,"abs":71,"votants":64,"blancs":4,"nuls":2,"exp":58,"res":[{"nuance":"LR","nom":"M. <NAME>","voix":32},{"nuance":"REM","nom":"Mme <NAME>","voix":26}]} | 100 |
399 | #pragma once
#include "graphics/Program.hpp"
#include "graphics/GPUTypes.hpp"
class Framebuffer;
class Texture;
class Mesh;
/**
\brief Provide helper GUI to display the content of texture and framebuffer attachments.
This can be useful to validate the content rendered to a specific texture zhen debugging.
\ingroup Renderers
*/
class DebugViewer {
public:
/** Constructor.
\param silent if true, don't register or display anything.
*/
explicit DebugViewer();
/** Register a texture for debug.
\param tex the texture to monitor
*/
void track(const Texture * tex);
/** Register a framebuffer for debug. All attachment textures will be visible.
\param buffer the framebuffer to monitor
*/
void track(const Framebuffer * buffer);
/** Register a mesh for debug.
\param mesh the mesh to monitor
*/
void track(const Mesh * mesh);
/** Track the GPU state at the moment of the call. Can be called at each frame to track varying state.
\param name the display name of the state
*/
void trackState(const std::string & name);
/** Stop monitoring a texture.
\param tex the texture to stop tracking
*/
void untrack(const Texture * tex);
/** Stop monitoring a framebuffer.
\param buffer the framebuffer to stop tracking
*/
void untrack(const Framebuffer * buffer);
/** Stop monitoring a mesh.
\param mesh the mesh to stop tracking
*/
void untrack(const Mesh * mesh);
/** Display interface and monitored data. */
void interface();
/** Destructor */
~DebugViewer() = default;
/** Copy constructor.*/
DebugViewer(const DebugViewer &) = delete;
/** Copy assignment.
\return a reference to the object assigned to
*/
DebugViewer & operator=(const DebugViewer &) = delete;
/** Move constructor.*/
DebugViewer(DebugViewer &&) = delete;
/** Move assignment.
\return a reference to the object assigned to
*/
DebugViewer & operator=(DebugViewer &&) = delete;
public:
/** Register a default debug viewer.
\param viewer the viewer to use as default*/
static void setDefault(DebugViewer * viewer);
/** Register a texture for debug.
\param tex the texture to monitor
*/
static void trackDefault(const Texture * tex);
/** Register a framebuffer for debug. All attachment textures will be visible.
\param buffer the framebuffer to monitor
*/
static void trackDefault(const Framebuffer * buffer);
/** Register a mesh for debug.
\param mesh the mesh to monitor
*/
static void trackDefault(const Mesh * mesh);
/** Register current GPU state for debug;
\param name how to name the state in the list
*/
static void trackStateDefault(const std::string & name);
/** Stop monitoring a texture.
\param tex the texture to stop tracking
*/
static void untrackDefault(const Texture * tex);
/** Stop monitoring a framebuffer.
\param buffer the framebuffer to stop tracking
*/
static void untrackDefault(const Framebuffer * buffer);
/** Stop monitoring a mesh.
\param mesh the mesh to stop tracking
*/
static void untrackDefault(const Mesh * mesh);
private:
static DebugViewer * _shared; ///< Optional shared debug viewer.
private:
/** Texture display information */
struct TextureInfos {
const Texture * tex = nullptr; ///< The texture to display.
std::string name; ///< Texture name.
std::unique_ptr<Framebuffer> display; ///< Framebuffer used for visualization.
std::string displayName; ///< Texture name with extra information about the layout,...
glm::vec2 range = glm::vec2(0.0f, 1.0f); ///< Range of values to display normalized.
glm::bvec4 channels = glm::bvec4(true, true, true, false); ///< Channels that should be displayed.
int mip = 0; ///< Mipmap level to display.
int layer = 0; ///< Layer to display for arrays and 3D textures.
bool gamma = false; ///< Should gamma correction be applied.
bool visible = false; ///< Is the texture window visible.
};
/** Framebuffer display information */
struct FramebufferInfos {
const Framebuffer * buffer = nullptr; ///< The framebuffer to track.
std::string name; ///< The framebuffer name.
std::vector<TextureInfos> attachments; ///< Color and depth attachment infos.
};
/** Mesh information. */
struct MeshInfos {
const Mesh * mesh = nullptr; ///< Mesh to track.
std::string name; ///< Mesh display name.
bool visible = false; ///< Are the mesh details displayed.
};
/** Monitored GPU state. */
struct StateInfos {
GPUState state; ///< GPU state to track.
bool visible = false; ///< Is the state window visible.
bool populated = false; ///< Has the state already been queried.
};
/** Display GPU metrics for the last completed frame in a panel.
*/
void displayMetrics();
/** Display GPU state in a panel.
\param name name of the state
\param infos the state to display
*/
void displayState(const std::string & name, StateInfos & infos);
/** Display a mesh information in a panel.
\param mesh the mesh to display
*/
void displayMesh(MeshInfos & mesh);
/** Populate texture information based on an input texture.
\param name the name of the texture
\param tex the texture to monitor
\param infos the information that should be populated
*/
void registerTexture(const std::string & name, const Texture * tex, TextureInfos & infos);
/** Display a texture with some helper GUI.
\param prefix the display name of the texture
\param tex the texture information to display
*/
void displayTexture(const std::string & prefix, TextureInfos & tex);
/** Update the visualization associated to a texture/
\param tex the texture to update the display of
*/
void updateDisplay(const TextureInfos & tex);
std::vector<TextureInfos> _textures; ///< The registered textures.
std::vector<FramebufferInfos> _framebuffers; ///< The registered framebuffers.
std::vector<MeshInfos> _meshes; ///< The registered meshes.
std::unordered_map<std::string, StateInfos> _states; ///< GPU states currently tracked.
Program * _texDisplay; ///< Texture display shader.
uint _textureId = 0; ///< Default texture name counter.
uint _bufferId = 0; ///< Default framebuffer name counter.
uint _meshId = 0; ///< Default mesh name counter.
uint _winId = 0; ///< Internal window counter.
};
| 1,748 |
1,472 | package org.muses.jeeplatform.core.dto.admin;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.muses.jeeplatform.core.entity.admin.Role;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
/**
* <pre>
*
* </pre>
*
* <pre>
* @author mazq
* 修改记录
* 修改后版本: 修改人: 修改日期: 2020/04/27 17:20 修改内容:
* </pre>
*/
@Data
@AllArgsConstructor
public class UserDto implements Serializable {
/** 用户Id**/
private int id;
/** 用户名**/
private String username;
/** 用户密码**/
private String password;
/** 手机号**/
private String phone;
/** 性别**/
private String sex;
/** 邮件**/
private String email;
/** 备注**/
private String mark;
/** 用户级别**/
private String rank;
/** 最后一次时间**/
private Date lastLogin;
/** 登录ip**/
private String loginIp;
/** 图片路径**/
private String imageUrl;
/** 注册时间**/
private Date regTime;
/** 账号是否被锁定**/
private Boolean locked = Boolean.FALSE;
/** 权限**/
private String rights;
private Set<Role> roles;
}
| 559 |
451 | #include "Tree.h"
#define HORSIMAGE "Outside image"
#define VANISHED_TEXT "Vanished"
#define COLOR_OVER "#c89354"
#define NON_SAISIE "#ba5606"
ModelPointGlobal::ModelPointGlobal(QObject *parent, cAppli_SaisiePts *appli):
QAbstractTableModel(parent),
mAppli(appli),
_interface((cQT_Interface*)appli->Interface())
{
}
int ModelPointGlobal::rowCount(const QModelIndex & /*parent*/) const
{
return AllCount();
}
int ModelPointGlobal::columnCount(const QModelIndex & /*parent*/) const
{
return 2;
}
QVariant ModelPointGlobal::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
if(index.row() < PG_Count())
{
cSP_PointGlob * pg = mAppli->PGlob(index.row());
switch (index.column())
{
case 0:
return QString("%1").arg(pg->PG()->Name().c_str());
case 1:
{
if (pg->PG()->P3D().IsInit())
{
Pt3dr *p3d = pg->PG()->P3D().PtrVal();
return QString("%1\t %2\t %3")
.arg(QString::number(p3d->x, 'f' ,2))
.arg(QString::number(p3d->y, 'f' ,2))
.arg(QString::number(p3d->z, 'f' ,2));
}
else
return QString("Not computed"); //Orientation = NONE
}
}
}
else if (index.row() < AllCount())
{
int id = index.row() - PG_Count();
if(id >= 0 && id < CaseNamePointCount())
{
cCaseNamePoint cnPt = mAppli->Interface()->GetCaseNamePoint(id);
switch (index.column())
{
case 0:
return QString("%1").arg(cnPt.mName.c_str());
case 1:
return QString(tr("Not measured"));
}
}
}
}
if (role == Qt::BackgroundColorRole)
{
QColor selectPGlob = QColor(COLOR_OVER);
if(mAppli->PGlob(index.row()) == _interface->currentPGlobal() && _interface->currentPGlobal() && index.column() == 0)
return selectPGlob;
cSP_PointGlob * pg = mAppli->PGlob(index.row());
if (pg != NULL && pg->getPointes().size())
{
QColor NonSaisie(NON_SAISIE);
std::map<std::string,cSP_PointeImage *> ptIs = pg->getPointes();
for
(
std::map<std::string,cSP_PointeImage *>::iterator itM = ptIs.begin();
itM!= ptIs.end();
itM++
)
{
cSP_PointeImage * ptImag = itM->second;
if(ptImag->Saisie()->Etat() == eEPI_NonSaisi && ptImag->Visible() && _interface->idCImage(QString(ptImag->Image()->Name().c_str())) !=-1)
return NonSaisie;
}
}
}
if (role == Qt::TextColorRole)
if(mAppli->PGlob(index.row()) == _interface->currentPGlobal() && _interface->currentPGlobal())
return QColor(Qt::white);
return QVariant();
}
QVariant ModelPointGlobal::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole)
{
if (orientation == Qt::Horizontal)
{
switch (section)
{
case 0:
return QString(tr("Point"));
case 1:
return QString(tr("3D Coordinates"));
}
}
}
return QVariant();
}
bool ModelPointGlobal::setData(const QModelIndex &index, const QVariant &value, int role)
{
QString qnewName = value.toString();
if(qnewName == QString(""))
return false;
if (role == Qt::EditRole)
{
string oldName = mAppli->PGlob(index.row())->PG()->Name();
string newName = qnewName.toStdString();
mAppli->ChangeName(oldName, newName);
emit pGChanged();
}
return true;
}
Qt::ItemFlags ModelPointGlobal::flags(const QModelIndex &index) const
{
switch (index.column())
{
case 0:
if(index.row() < PG_Count())
return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
case 1:
return QAbstractTableModel::flags(index);
}
return QAbstractTableModel::flags(index);
}
bool ModelPointGlobal::insertRows(int row, int count, const QModelIndex &parent)
{
beginInsertRows(QModelIndex(), row, row+count-1);
endInsertRows();
return true;
}
int ModelPointGlobal::AllCount() const
{
return PG_Count() + CaseNamePointCount();
}
int ModelPointGlobal::PG_Count() const
{
return (int)mAppli->PG().size();
}
int ModelPointGlobal::CaseNamePointCount() const
{
return (int)mAppli->Interface()->GetNumCaseNamePoint();
}
cAppli_SaisiePts *ModelPointGlobal::getMAppli() const
{
return mAppli;
}
bool ModelPointGlobal::caseIsSaisie(int idRow)
{
int idCase = idRow - PG_Count();
QString nameCase(mAppli->Interface()->GetCaseNamePoint(idCase).mName.c_str());
for (int i = 0; i < PG_Count(); ++i)
{
if(nameCase == QString(mAppli->PGlob(i)->PG()->Name().c_str()))
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ModelCImage::ModelCImage(QObject *parent, cAppli_SaisiePts *appli)
:QAbstractTableModel(parent),
mAppli(appli),
_interface((cQT_Interface*)appli->Interface())
{
}
int ModelCImage::rowCount(const QModelIndex & /*parent*/) const
{
return (int)mAppli->imagesVis().size();
}
int ModelCImage::columnCount(const QModelIndex & /*parent*/) const
{
return 3;
}
QVariant ModelCImage::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
if(index.row() < (int) mAppli->imagesVis().size())
{
cImage* iImage = mAppli->imageVis(index.row());
switch (index.column())
{
case 0:
return QString("%1").arg(iImage->Name().c_str());
case 1:
{
cSP_PointGlob* pg = _interface->currentPGlobal();
if(!pg)
return QString("");
cSP_PointeImage* pI = iImage->PointeOfNameGlobSVP(pg->PG()->Name());
if(pI)
{
cOneSaisie* cOS = pI->Saisie();
if(cOS)
{
eEtatPointeImage state = cOS->Etat();
switch (state)
{
case eEPI_NonSaisi:
{
if(pI->Visible())
return QString(tr("to validate"));
else
return QString(tr(HORSIMAGE));
}
case eEPI_Refute:
return QString(tr("refuted"));
case eEPI_Douteux:
return QString(tr("dubious"));
case eEPI_Valide:
return QString(tr("valid"));
case eEPI_NonValue:
return QString(tr("no value"));
case eEPI_Disparu:
return QString(tr(VANISHED_TEXT));
case eEPI_Highlight:
return QString(tr("highlighted"));
}
}
}
return QString(tr(HORSIMAGE));
}
case 2:
{
cSP_PointGlob* pg = _interface->currentPGlobal();
if(!pg)
return QString("");
cSP_PointeImage* pI = iImage->PointeOfNameGlobSVP(pg->PG()->Name());
if (pI)
{
cOneSaisie* cOS = pI->Saisie();
if(cOS)
{
if(cOS->Etat() == eEPI_Disparu)
return QString("");
return QString("%1\t %2")
.arg(QString::number(cOS->PtIm().x, 'f' ,1))
.arg(QString::number(cOS->PtIm().y, 'f' ,1));
}
}
return QString("");
}
}
}
}
if (role == Qt::BackgroundColorRole)
{
QColor Red = QColor("#87384c");
QColor NonSaisie = QColor(NON_SAISIE);
QColor Douteux = QColor("#a95b3b");
QColor Valide = QColor("#3c7355");
QColor imageVisible = QColor("#3a819c");
QColor selectPGlob = QColor(COLOR_OVER);
cSP_PointGlob* pg = _interface->currentPGlobal();
if(!pg)
return QVariant(QColor("#5f5f5f"));
cImage* iImage = mAppli->imageVis(index.row());
if(index.column() == 0)
{
if(iImage == _interface->currentCImage() )
return selectPGlob;
else if (_interface->isDisplayed(iImage))
return imageVisible;
}
cSP_PointeImage* pI = iImage->PointeOfNameGlobSVP(pg->PG()->Name());
if(pI)
{
cOneSaisie* cOS = pI->Saisie();
if(cOS)
{
eEtatPointeImage state = cOS->Etat();
switch (state)
{
case eEPI_NonSaisi:
{
if(pI->Visible())
return NonSaisie;
else
return Red;
}
case eEPI_Refute:
return Red;
case eEPI_Douteux:
return Douteux;
case eEPI_Valide:
return Valide;
case eEPI_NonValue:
return Red;
case eEPI_Disparu:
return Red;
case eEPI_Highlight:
return Red;
}
}
}
return Red;
}
if (role == Qt::TextColorRole && index.column() == 0 && _interface->currentPGlobal())
if(index.row() < (int)mAppli->imagesVis().size() && mAppli->imageVis(index.row()) == _interface->currentCImage() )
return QColor(Qt::white);
return QVariant();
}
QVariant ModelCImage::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole)
{
if (orientation == Qt::Horizontal) {
switch (section)
{
case 0:
return QString(tr("Image"));
case 1:
return QString(tr("State"));
case 2:
return QString(tr("Coordinates"));
}
}
}
return QVariant();
}
bool ModelCImage::setData(const QModelIndex &index, const QVariant &value, int role)
{
return false;
}
Qt::ItemFlags ModelCImage::flags(const QModelIndex &index) const
{
switch (index.column())
{
case 0:
return QAbstractTableModel::flags(index) /*| Qt::ItemIsEditable*/;
case 1:
return QAbstractTableModel::flags(index);
}
return QAbstractTableModel::flags(index);
}
bool ModelCImage::insertRows(int row, int count, const QModelIndex &parent)
{
beginInsertRows(QModelIndex(), row, row+count-1);
endInsertRows();
return true;
}
bool ImagesSFModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent);
QString strColl_1 = sourceModel()->data(index1).toString();
if( strColl_1 == "")
return false;
else
return !strColl_1.contains(HORSIMAGE) && !strColl_1.contains(VANISHED_TEXT);
}
bool PointGlobalSFModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
if(mAppli())
{
cQT_Interface * interf = (cQT_Interface*) mAppli()->Interface();
bool saisieBasc = interf->getQTWinMode() == BASC;
if(((int)mAppli()->PG().size() == sourceRow) && !saisieBasc)
return false;
ModelPointGlobal* model = (ModelPointGlobal*)sourceModel();
QModelIndex index1 = model->index(sourceRow, 0, sourceParent);
QString namePG = model->data(index1).toString();
cSP_PointGlob * pg = mAppli()->PGlobOfNameSVP(namePG.toStdString());
if(pg && sourceRow < (int)mAppli()->PG().size())
{
if(!pg->PG()->Disparu().IsInit())
return true;
else if(!pg->PG()->Disparu().Val())
return false;
}
else if(saisieBasc && sourceRow >= (int)mAppli()->PG().size() && mAppli()->Interface()->GetCaseNamePoint(sourceRow-(int)mAppli()->PG().size()).mFree)
return true;
//else if(sourceRow > (int)mAppli()->PG().size() && !model->caseIsSaisie(sourceRow))
else if(sourceRow > (int)mAppli()->PG().size() && mAppli()->Interface()->GetCaseNamePoint(sourceRow-(int)mAppli()->PG().size()).mFree)
return true;
}
return false;
}
cAppli_SaisiePts *PointGlobalSFModel::mAppli() const
{
return ((ModelPointGlobal*)(sourceModel()))->getMAppli();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 7,271 |
310 | <reponame>dreeves/usesthis<gh_stars>100-1000
{
"name": "<NAME>",
"description": "A game about matching yoga poses.",
"url": "https://q_dork.itch.io/wobble-yoga"
}
| 71 |
918 | <reponame>gatarelib/LiquidCore<gh_stars>100-1000
/*
* Copyright (c) 2014 - 2018 <NAME>
*
* Distributed under the MIT License. See LICENSE.md at
* https://github.com/LiquidPlayer/LiquidCore for terms and conditions.
*/
package org.liquidplayer.jstest;
import org.junit.Test;
import org.liquidplayer.javascript.JSArrayBuffer;
import org.liquidplayer.javascript.JSContext;
import org.liquidplayer.javascript.JSDataView;
import static org.junit.Assert.*;
public class JSDataViewTest {
public void testConstructorsAndProperties(JSContext context) {
JSArrayBuffer buffer = new JSArrayBuffer(context,8);
JSDataView view = new JSDataView(buffer);
assertEquals(buffer.byteLength(),view.buffer().byteLength());
assertEquals(view.byteLength(),buffer.byteLength());
assertEquals(view.byteOffset(),0);
JSDataView view2 = new JSDataView(buffer,4);
assertEquals(buffer.byteLength(),view2.buffer().byteLength());
assertEquals(view2.byteLength(),4);
assertEquals(view2.byteOffset(),4);
JSDataView view3 = new JSDataView(buffer,4,2);
assertEquals(buffer.byteLength(),view3.buffer().byteLength());
assertEquals(view3.byteLength(),2);
assertEquals(view3.byteOffset(),4);
JSDataView view4 = new JSDataView(view3);
assertTrue(view4.isStrictEqual(view3));
}
public void testFloat32(JSContext context) {
JSDataView view = new JSDataView(new JSArrayBuffer(context,12));
view.setFloat32(0,5.56f);
view.setFloat32(4,6.87f,true);
view.setFloat32(8,6.87f,false);
assertEquals(Float.valueOf(5.56f), view.getFloat32(0));
assertEquals(Float.valueOf(6.87f), view.getFloat32(4, true));
assertEquals(Float.valueOf(6.87f), view.getFloat32(8, false));
assertNotEquals(6.87f, view.getFloat32(4, false));
assertNotEquals(6.87f, view.getFloat32(8, true));
}
public void testFloat64(JSContext context) {
JSDataView view = new JSDataView(new JSArrayBuffer(context,24));
view.setFloat64(0,5.5678);
view.setFloat64(8,6.8765,true);
view.setFloat64(16,6.8765,false);
assertEquals(Double.valueOf(5.5678), view.getFloat64(0));
assertEquals(Double.valueOf(6.8765), view.getFloat64(8,true));
assertEquals(Double.valueOf(6.8765), view.getFloat64(16,false));
assertNotEquals(6.8765, view.getFloat64(6,false));
assertNotEquals(6.8765, view.getFloat64(16,true));
}
public void testInt32(JSContext context) {
JSDataView view = new JSDataView(new JSArrayBuffer(context,12));
view.setInt32(0,5);
view.setInt32(4,6,true);
view.setInt32(8,6,false);
assertEquals(Integer.valueOf(5), view.getInt32(0));
assertEquals(Integer.valueOf(6), view.getInt32(4,true));
assertEquals(Integer.valueOf(6), view.getInt32(8,false));
assertNotEquals(Integer.valueOf(6), view.getInt32(4,false));
assertNotEquals(Integer.valueOf(6), view.getInt32(8,true));
}
public void testInt16(JSContext context) {
JSDataView view = new JSDataView(new JSArrayBuffer(context,6));
view.setInt16(0,(short)5);
view.setInt16(2,(short)-6,true);
view.setInt16(4,(short)-6,false);
assertEquals(Short.valueOf((short)5), view.getInt16(0));
assertEquals(Short.valueOf((short)-6), view.getInt16(2,true));
assertEquals(Short.valueOf((short)-6), view.getInt16(4,false));
assertNotEquals(Short.valueOf((short)-6), view.getInt16(2,false));
assertNotEquals(Short.valueOf((short)-6), view.getInt16(4,true));
}
public void testInt8(JSContext context) {
JSDataView view = new JSDataView(new JSArrayBuffer(context,2));
view.setInt8(0,(byte)5);
view.setInt8(1,(byte)-6);
assertEquals(Byte.valueOf((byte)5), view.getInt8(0));
assertEquals(Byte.valueOf((byte)-6), view.getInt8(1));
}
public void testUint32(JSContext context) {
JSDataView view = new JSDataView(new JSArrayBuffer(context,12));
view.setUint32(0,0xffffffffL);
view.setUint32(4,6L,true);
view.setUint32(8,6L,false);
assertEquals(0xffffffffL,view.getUint32(0).longValue());
assertEquals(6L, view.getUint32(4,true).longValue());
assertEquals(6L, view.getUint32(8,false).longValue());
assertNotEquals(6L, view.getUint32(4,false).longValue());
assertNotEquals(6L, view.getUint32(8,true).longValue());
}
public void testUint16(JSContext context) {
JSDataView view = new JSDataView(new JSArrayBuffer(context,6));
view.setUint16(0,(short)0xfffe);
view.setUint16(2,(short)6,true);
view.setUint16(4,(short)6,false);
assertEquals(Short.valueOf((short)0xfffe), view.getUint16(0));
assertEquals(Short.valueOf((short)6), view.getUint16(2,true));
assertEquals(Short.valueOf((short)6), view.getUint16(4,false));
assertNotEquals(Short.valueOf((short)6), view.getUint16(2,false));
assertNotEquals(Short.valueOf((short)6), view.getUint16(4,true));
}
public void testUint8(JSContext context) {
JSDataView view = new JSDataView(new JSArrayBuffer(context,2));
view.setUint8(0,(byte)0xfd);
view.setUint8(1,(byte)6);
assertEquals(Byte.valueOf((byte)0xfd), view.getUint8(0));
assertEquals(Byte.valueOf((byte)6), view.getUint8(1));
}
@Test
public void testConstructorsAndProperties() {
JSContext context = new JSContext();
testConstructorsAndProperties(context);
}
@Test
public void testFloat32() {
JSContext context = new JSContext();
testFloat32(context);
}
@Test
public void testFloat64() {
JSContext context = new JSContext();
testFloat64(context);
}
@Test
public void testInt32() {
JSContext context = new JSContext();
testInt32(context);
}
@Test
public void testInt16() {
JSContext context = new JSContext();
testInt16(context);
}
@Test
public void testInt8() {
JSContext context = new JSContext();
testInt8(context);
}
@Test
public void testUint32() {
JSContext context = new JSContext();
testUint32(context);
}
@Test
public void testUint16() {
JSContext context = new JSContext();
testUint16(context);
}
@Test
public void testUint8() {
JSContext context = new JSContext();
testUint8(context);
}
} | 2,882 |
313 | <reponame>leibale/RedisGraph<filename>src/execution_plan/ops/op_apply.h
/*
* Copyright 2018-2022 Redis Labs Ltd. and Contributors
*
* This file is available under the Redis Labs Source Available License Agreement
*/
#pragma once
#include "op.h"
#include "op_argument.h"
#include "../execution_plan.h"
/* The Apply op has a bound left-hand branch
* and a right-hand branch that takes records
* from the left-hand branch as input.
* After retrieving a record from the left-hand branch,
* it pulls data from the right-hand branch and passes
* the merged record upwards until the right-hand branch
* is depleted, at which time data is pulled from the
* left-hand branch and the process repeats. */
typedef struct {
OpBase op;
Record r; // Bound branch record.
OpBase *bound_branch; // Bound branch.
OpBase *rhs_branch; // Right-hand branch.
Argument *op_arg; // Right-hand branch tap.
} Apply;
OpBase *NewApplyOp(const ExecutionPlan *plan);
| 349 |
305 | //===-- runtime/buffer.cpp --------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "buffer.h"
#include <algorithm>
namespace Fortran::runtime::io {
// Here's a very old trick for shifting circular buffer data cheaply
// without a need for a temporary array.
void LeftShiftBufferCircularly(
char *buffer, std::size_t bytes, std::size_t shift) {
// Assume that we start with "efgabcd" and the left shift is 3.
std::reverse(buffer, buffer + shift); // "gfeabcd"
std::reverse(buffer, buffer + bytes); // "dcbaefg"
std::reverse(buffer, buffer + bytes - shift); // "abcdefg"
}
} // namespace Fortran::runtime::io
| 270 |
435 | {
"copyright_text": "Creative Commons Attribution license (reuse allowed)",
"description": "There's a widespread belief among machine learning practitioners that algorithms are objective and allow us to deal with the messy reality in a nice, objective way, without worrying about all the yucky human nature things. This talk will argue that this belief is wrong. Algorithms, just like the humans who create them, can be severely biased and despicable indeed.\n\n**Abstract**\n\nWhen working on a new ML solution to solve a given problem, do you think that you are simply using objective reality to infer a set of unbiased rules that will allow you to predict the future? Do you think that worrying about the morality of your work is something other people should do? If so, this talk is for you.\n\nIn this brief time, I will try to convince you that you hold great power over how the future world will look like and that you should incorporate thinking about morality into the set of ML tools you use every day. We will take a short journey through several problems, which surfaced over the last few years, as ML and AI generally, became more widely used. We will look at bias present in training data, at some real-world consequences of not considering it (including one or two hair-raising stories) and cutting-edge research on how to counteract this.\n\nThe outline of the talk is:\n\n* Intro the problem: ML algos can be biased!\n* Two concrete examples.\n* What's been done so far (i.e. techniques from recently-published papers).\n* What to do next: unanswered questions.",
"duration": 2050,
"language": "eng",
"recorded": "2017-05-20T12:00:00+02:00",
"related_urls": [
{
"label": "schedule",
"url": "https://pydata.org/barcelona2017/schedule/presentation/44/"
}
],
"speakers": [
"<NAME>"
],
"tags": [
"ethics",
"machine learning"
],
"thumbnail_url": "https://i.ytimg.com/vi/8kL71zk4KNk/maxresdefault.jpg",
"title": "Despicable machines: how computers can be assholes",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=8kL71zk4KNk"
}
]
}
| 620 |
395 | <reponame>ritaswc/wechat_app_template<gh_stars>100-1000
package com.mindskip.xzs.viewmodel.student.exam;
import com.mindskip.xzs.base.BasePage;
import javax.validation.constraints.NotNull;
public class ExamPaperPageVM extends BasePage {
@NotNull
private Integer paperType;
private Integer subjectId;
private Integer levelId;
public Integer getPaperType() {
return paperType;
}
public void setPaperType(Integer paperType) {
this.paperType = paperType;
}
public Integer getSubjectId() {
return subjectId;
}
public void setSubjectId(Integer subjectId) {
this.subjectId = subjectId;
}
public Integer getLevelId() {
return levelId;
}
public void setLevelId(Integer levelId) {
this.levelId = levelId;
}
}
| 318 |
13,027 | <reponame>tornado12345/termux-app<filename>termux-shared/src/main/java/com/termux/shared/activities/TextIOActivity.java
package com.termux.shared.activities;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.termux.shared.interact.ShareUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.R;
import com.termux.shared.models.TextIOInfo;
import com.termux.shared.view.KeyboardUtils;
import org.jetbrains.annotations.NotNull;
import java.util.Locale;
/**
* An activity to edit or view text based on config passed as {@link TextIOInfo}.
*
* Add Following to `AndroidManifest.xml` to use in an app:
*
* {@code ` <activity android:name="com.termux.shared.activities.TextIOActivity" android:theme="@style/Theme.AppCompat.TermuxTextIOActivity" />` }
*/
public class TextIOActivity extends AppCompatActivity {
private static final String CLASS_NAME = ReportActivity.class.getCanonicalName();
public static final String EXTRA_TEXT_IO_INFO_OBJECT = CLASS_NAME + ".EXTRA_TEXT_IO_INFO_OBJECT";
private TextView mTextIOLabel;
private View mTextIOLabelSeparator;
private EditText mTextIOText;
private HorizontalScrollView mTextIOHorizontalScrollView;
private LinearLayout mTextIOTextLinearLayout;
private TextView mTextIOTextCharacterUsage;
private TextIOInfo mTextIOInfo;
private Bundle mBundle;
private static final String LOG_TAG = "TextIOActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Logger.logVerbose(LOG_TAG, "onCreate");
setContentView(R.layout.activity_text_io);
mTextIOLabel = findViewById(R.id.text_io_label);
mTextIOLabelSeparator = findViewById(R.id.text_io_label_separator);
mTextIOText = findViewById(R.id.text_io_text);
mTextIOHorizontalScrollView = findViewById(R.id.text_io_horizontal_scroll_view);
mTextIOTextLinearLayout = findViewById(R.id.text_io_text_linear_layout);
mTextIOTextCharacterUsage = findViewById(R.id.text_io_text_character_usage);
Toolbar toolbar = findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
mBundle = null;
Intent intent = getIntent();
if (intent != null)
mBundle = intent.getExtras();
else if (savedInstanceState != null)
mBundle = savedInstanceState;
updateUI();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Logger.logVerbose(LOG_TAG, "onNewIntent");
// Views must be re-created since different configs for isEditingTextDisabled() and
// isHorizontallyScrollable() will not work or at least reliably
finish();
startActivity(intent);
}
@SuppressLint("ClickableViewAccessibility")
private void updateUI() {
if (mBundle == null) {
finish(); return;
}
mTextIOInfo = (TextIOInfo) mBundle.getSerializable(EXTRA_TEXT_IO_INFO_OBJECT);
if (mTextIOInfo == null) {
finish(); return;
}
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
if (mTextIOInfo.getTitle() != null)
actionBar.setTitle(mTextIOInfo.getTitle());
else
actionBar.setTitle("Text Input");
if (mTextIOInfo.shouldShowBackButtonInActionBar()) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
mTextIOLabel.setVisibility(View.GONE);
mTextIOLabelSeparator.setVisibility(View.GONE);
if (mTextIOInfo.isLabelEnabled()) {
mTextIOLabel.setVisibility(View.VISIBLE);
mTextIOLabelSeparator.setVisibility(View.VISIBLE);
mTextIOLabel.setText(mTextIOInfo.getLabel());
mTextIOLabel.setFilters(new InputFilter[] { new InputFilter.LengthFilter(TextIOInfo.LABEL_SIZE_LIMIT_IN_BYTES) });
mTextIOLabel.setTextSize(mTextIOInfo.getLabelSize());
mTextIOLabel.setTextColor(mTextIOInfo.getLabelColor());
mTextIOLabel.setTypeface(Typeface.create(mTextIOInfo.getLabelTypeFaceFamily(), mTextIOInfo.getLabelTypeFaceStyle()));
}
if (mTextIOInfo.isHorizontallyScrollable()) {
mTextIOHorizontalScrollView.setEnabled(true);
mTextIOText.setHorizontallyScrolling(true);
} else {
// Remove mTextIOHorizontalScrollView and add mTextIOText in its place
ViewGroup parent = (ViewGroup) mTextIOHorizontalScrollView.getParent();
if (parent != null && parent.indexOfChild(mTextIOText) < 0) {
ViewGroup.LayoutParams params = mTextIOHorizontalScrollView.getLayoutParams();
int index = parent.indexOfChild(mTextIOHorizontalScrollView);
mTextIOTextLinearLayout.removeAllViews();
mTextIOHorizontalScrollView.removeAllViews();
parent.removeView(mTextIOHorizontalScrollView);
parent.addView(mTextIOText, index, params);
mTextIOText.setHorizontallyScrolling(false);
}
}
mTextIOText.setText(mTextIOInfo.getText());
mTextIOText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(mTextIOInfo.getTextLengthLimit()) });
mTextIOText.setTextSize(mTextIOInfo.getTextSize());
mTextIOText.setTextColor(mTextIOInfo.getTextColor());
mTextIOText.setTypeface(Typeface.create(mTextIOInfo.getTextTypeFaceFamily(), mTextIOInfo.getTextTypeFaceStyle()));
// setTextIsSelectable must be called after changing KeyListener to regain focusability and selectivity
if (mTextIOInfo.isEditingTextDisabled()) {
mTextIOText.setCursorVisible(false);
mTextIOText.setKeyListener(null);
mTextIOText.setTextIsSelectable(true);
}
if (mTextIOInfo.shouldShowTextCharacterUsage()) {
mTextIOTextCharacterUsage.setVisibility(View.VISIBLE);
updateTextIOTextCharacterUsage(mTextIOInfo.getText());
mTextIOText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable editable) {
if (editable != null)
updateTextIOTextCharacterUsage(editable.toString());
}
});
} else {
mTextIOTextCharacterUsage.setVisibility(View.GONE);
mTextIOText.addTextChangedListener(null);
}
}
private void updateTextIOInfoText() {
if (mTextIOText != null)
mTextIOInfo.setText(mTextIOText.getText().toString());
}
private void updateTextIOTextCharacterUsage(String text) {
if (text == null) text = "";
if (mTextIOTextCharacterUsage != null)
mTextIOTextCharacterUsage.setText(String.format(Locale.getDefault(), "%1$d/%2$d", text.length(), mTextIOInfo.getTextLengthLimit()));
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
updateTextIOInfoText();
outState.putSerializable(EXTRA_TEXT_IO_INFO_OBJECT, mTextIOInfo);
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_text_io, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
String text = "";
if (mTextIOText != null)
text = mTextIOText.getText().toString();
int id = item.getItemId();
if (id == android.R.id.home) {
confirm();
} if (id == R.id.menu_item_cancel) {
cancel();
} else if (id == R.id.menu_item_share_text) {
ShareUtils.shareText(this, mTextIOInfo.getTitle(), text);
} else if (id == R.id.menu_item_copy_text) {
ShareUtils.copyTextToClipboard(this, text, null);
}
return false;
}
@Override
public void onBackPressed() {
confirm();
}
/** Confirm current text and send it back to calling {@link Activity}. */
private void confirm() {
updateTextIOInfoText();
KeyboardUtils.hideSoftKeyboard(this, mTextIOText);
setResult(Activity.RESULT_OK, getResultIntent());
finish();
}
/** Cancel current text and notify calling {@link Activity}. */
private void cancel() {
KeyboardUtils.hideSoftKeyboard(this, mTextIOText);
setResult(Activity.RESULT_CANCELED, getResultIntent());
finish();
}
@NotNull
private Intent getResultIntent() {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable(EXTRA_TEXT_IO_INFO_OBJECT, mTextIOInfo);
intent.putExtras(bundle);
return intent;
}
/**
* Get the {@link Intent} that can be used to start the {@link TextIOActivity}.
*
* @param context The {@link Context} for operations.
* @param textIOInfo The {@link TextIOInfo} containing info for the edit text.
*/
public static Intent newInstance(@NonNull final Context context, @NonNull final TextIOInfo textIOInfo) {
Intent intent = new Intent(context, TextIOActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable(EXTRA_TEXT_IO_INFO_OBJECT, textIOInfo);
intent.putExtras(bundle);
return intent;
}
}
| 4,400 |
2,151 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/viz/test/test_context_provider.h"
#include <stddef.h>
#include <stdint.h>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/logging.h"
#include "components/viz/common/gpu/context_cache_controller.h"
#include "components/viz/test/test_gles2_interface.h"
#include "components/viz/test/test_web_graphics_context_3d.h"
#include "gpu/command_buffer/client/raster_implementation_gles.h"
#include "gpu/skia_bindings/grcontext_for_gles2_interface.h"
#include "third_party/skia/include/gpu/GrContext.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
namespace viz {
namespace {
// Various tests rely on functionality (capabilities) enabled by these extension
// strings.
const char* const kExtensions[] = {"GL_EXT_stencil_wrap",
"GL_EXT_texture_format_BGRA8888",
"GL_OES_rgb8_rgba8",
"GL_EXT_texture_norm16",
"GL_CHROMIUM_framebuffer_multisample",
"GL_CHROMIUM_renderbuffer_format_BGRA8888"};
class TestGLES2InterfaceForContextProvider : public TestGLES2Interface {
public:
TestGLES2InterfaceForContextProvider()
: extension_string_(BuildExtensionString()) {}
~TestGLES2InterfaceForContextProvider() override = default;
// TestGLES2Interface:
const GLubyte* GetString(GLenum name) override {
switch (name) {
case GL_EXTENSIONS:
return reinterpret_cast<const GLubyte*>(extension_string_.c_str());
case GL_VERSION:
return reinterpret_cast<const GrGLubyte*>("4.0 Null GL");
case GL_SHADING_LANGUAGE_VERSION:
return reinterpret_cast<const GrGLubyte*>("4.20.8 Null GLSL");
case GL_VENDOR:
return reinterpret_cast<const GrGLubyte*>("Null Vendor");
case GL_RENDERER:
return reinterpret_cast<const GrGLubyte*>("The Null (Non-)Renderer");
}
return nullptr;
}
const GrGLubyte* GetStringi(GrGLenum name, GrGLuint i) override {
if (name == GL_EXTENSIONS && i < arraysize(kExtensions))
return reinterpret_cast<const GLubyte*>(kExtensions[i]);
return nullptr;
}
void GetIntegerv(GLenum name, GLint* params) override {
switch (name) {
case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
*params = 8;
return;
case GL_MAX_TEXTURE_SIZE:
*params = 2048;
break;
case GL_MAX_RENDERBUFFER_SIZE:
*params = 2048;
break;
case GL_MAX_VERTEX_ATTRIBS:
*params = 8;
break;
default:
break;
}
TestGLES2Interface::GetIntegerv(name, params);
}
private:
static std::string BuildExtensionString() {
std::string extension_string = kExtensions[0];
for (size_t i = 1; i < arraysize(kExtensions); ++i) {
extension_string += " ";
extension_string += kExtensions[i];
}
return extension_string;
}
const std::string extension_string_;
DISALLOW_COPY_AND_ASSIGN(TestGLES2InterfaceForContextProvider);
};
} // namespace
// static
scoped_refptr<TestContextProvider> TestContextProvider::Create() {
constexpr bool support_locking = false;
return new TestContextProvider(
std::make_unique<TestContextSupport>(),
std::make_unique<TestGLES2InterfaceForContextProvider>(),
TestWebGraphicsContext3D::Create(), support_locking);
}
// static
scoped_refptr<TestContextProvider> TestContextProvider::CreateWorker() {
constexpr bool support_locking = true;
auto worker_context_provider = base::MakeRefCounted<TestContextProvider>(
std::make_unique<TestContextSupport>(),
std::make_unique<TestGLES2InterfaceForContextProvider>(),
TestWebGraphicsContext3D::Create(), support_locking);
// Worker contexts are bound to the thread they are created on.
auto result = worker_context_provider->BindToCurrentThread();
if (result != gpu::ContextResult::kSuccess)
return nullptr;
return worker_context_provider;
}
// static
scoped_refptr<TestContextProvider> TestContextProvider::Create(
std::unique_ptr<TestWebGraphicsContext3D> context) {
DCHECK(context);
constexpr bool support_locking = false;
return new TestContextProvider(
std::make_unique<TestContextSupport>(),
std::make_unique<TestGLES2InterfaceForContextProvider>(),
std::move(context), support_locking);
}
// static
scoped_refptr<TestContextProvider> TestContextProvider::Create(
std::unique_ptr<TestGLES2Interface> gl) {
DCHECK(gl);
constexpr bool support_locking = false;
return new TestContextProvider(
std::make_unique<TestContextSupport>(), std::move(gl),
TestWebGraphicsContext3D::Create(), support_locking);
}
// static
scoped_refptr<TestContextProvider> TestContextProvider::Create(
std::unique_ptr<TestWebGraphicsContext3D> context,
std::unique_ptr<TestContextSupport> support) {
DCHECK(context);
DCHECK(support);
constexpr bool support_locking = false;
return new TestContextProvider(
std::move(support),
std::make_unique<TestGLES2InterfaceForContextProvider>(),
std::move(context), support_locking);
}
// static
scoped_refptr<TestContextProvider> TestContextProvider::Create(
std::unique_ptr<TestContextSupport> support) {
DCHECK(support);
constexpr bool support_locking = false;
return new TestContextProvider(
std::move(support),
std::make_unique<TestGLES2InterfaceForContextProvider>(),
TestWebGraphicsContext3D::Create(), support_locking);
}
// static
scoped_refptr<TestContextProvider> TestContextProvider::CreateWorker(
std::unique_ptr<TestWebGraphicsContext3D> context,
std::unique_ptr<TestContextSupport> support) {
DCHECK(context);
DCHECK(support);
constexpr bool support_locking = true;
auto worker_context_provider = base::MakeRefCounted<TestContextProvider>(
std::move(support),
std::make_unique<TestGLES2InterfaceForContextProvider>(),
std::move(context), support_locking);
// Worker contexts are bound to the thread they are created on.
auto result = worker_context_provider->BindToCurrentThread();
if (result != gpu::ContextResult::kSuccess)
return nullptr;
return worker_context_provider;
}
// static
scoped_refptr<TestContextProvider> TestContextProvider::CreateWorker(
std::unique_ptr<TestContextSupport> support) {
DCHECK(support);
constexpr bool support_locking = true;
auto worker_context_provider = base::MakeRefCounted<TestContextProvider>(
std::move(support),
std::make_unique<TestGLES2InterfaceForContextProvider>(),
TestWebGraphicsContext3D::Create(), support_locking);
// Worker contexts are bound to the thread they are created on.
auto result = worker_context_provider->BindToCurrentThread();
if (result != gpu::ContextResult::kSuccess)
return nullptr;
return worker_context_provider;
}
TestContextProvider::TestContextProvider(
std::unique_ptr<TestContextSupport> support,
std::unique_ptr<TestGLES2Interface> gl,
std::unique_ptr<TestWebGraphicsContext3D> context,
bool support_locking)
: support_(std::move(support)),
context3d_(std::move(context)),
context_gl_(std::move(gl)),
support_locking_(support_locking),
weak_ptr_factory_(this) {
DCHECK(main_thread_checker_.CalledOnValidThread());
DCHECK(context3d_);
DCHECK(context_gl_);
context_thread_checker_.DetachFromThread();
context_gl_->set_test_context(context3d_.get());
context3d_->set_test_support(support_.get());
raster_context_ = std::make_unique<gpu::raster::RasterImplementationGLES>(
context_gl_.get(), nullptr, context3d_->test_capabilities());
// Just pass nullptr to the ContextCacheController for its task runner.
// Idle handling is tested directly in ContextCacheController's
// unittests, and isn't needed here.
cache_controller_.reset(new ContextCacheController(support_.get(), nullptr));
}
TestContextProvider::~TestContextProvider() {
DCHECK(main_thread_checker_.CalledOnValidThread() ||
context_thread_checker_.CalledOnValidThread());
}
void TestContextProvider::AddRef() const {
base::RefCountedThreadSafe<TestContextProvider>::AddRef();
}
void TestContextProvider::Release() const {
base::RefCountedThreadSafe<TestContextProvider>::Release();
}
gpu::ContextResult TestContextProvider::BindToCurrentThread() {
// This is called on the thread the context will be used.
DCHECK(context_thread_checker_.CalledOnValidThread());
if (!bound_) {
if (context_gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR)
return gpu::ContextResult::kTransientFailure;
context3d_->set_context_lost_callback(base::Bind(
&TestContextProvider::OnLostContext, base::Unretained(this)));
}
bound_ = true;
return gpu::ContextResult::kSuccess;
}
const gpu::Capabilities& TestContextProvider::ContextCapabilities() const {
DCHECK(bound_);
CheckValidThreadOrLockAcquired();
return context3d_->test_capabilities();
}
const gpu::GpuFeatureInfo& TestContextProvider::GetGpuFeatureInfo() const {
DCHECK(bound_);
CheckValidThreadOrLockAcquired();
return gpu_feature_info_;
}
gpu::gles2::GLES2Interface* TestContextProvider::ContextGL() {
DCHECK(context3d_);
DCHECK(bound_);
CheckValidThreadOrLockAcquired();
return context_gl_.get();
}
gpu::raster::RasterInterface* TestContextProvider::RasterInterface() {
return raster_context_.get();
}
gpu::ContextSupport* TestContextProvider::ContextSupport() {
return support();
}
class GrContext* TestContextProvider::GrContext() {
DCHECK(bound_);
CheckValidThreadOrLockAcquired();
if (gr_context_)
return gr_context_->get();
size_t max_resource_cache_bytes;
size_t max_glyph_cache_texture_bytes;
skia_bindings::GrContextForGLES2Interface::DefaultCacheLimitsForTests(
&max_resource_cache_bytes, &max_glyph_cache_texture_bytes);
gr_context_ = std::make_unique<skia_bindings::GrContextForGLES2Interface>(
context_gl_.get(), support_.get(), context3d_->test_capabilities(),
max_resource_cache_bytes, max_glyph_cache_texture_bytes);
cache_controller_->SetGrContext(gr_context_->get());
// If GlContext is already lost, also abandon the new GrContext.
if (ContextGL()->GetGraphicsResetStatusKHR() != GL_NO_ERROR)
gr_context_->get()->abandonContext();
return gr_context_->get();
}
ContextCacheController* TestContextProvider::CacheController() {
CheckValidThreadOrLockAcquired();
return cache_controller_.get();
}
base::Lock* TestContextProvider::GetLock() {
if (!support_locking_)
return nullptr;
return &context_lock_;
}
void TestContextProvider::OnLostContext() {
CheckValidThreadOrLockAcquired();
for (auto& observer : observers_)
observer.OnContextLost();
if (gr_context_)
gr_context_->get()->abandonContext();
}
TestWebGraphicsContext3D* TestContextProvider::TestContext3d() {
DCHECK(bound_);
CheckValidThreadOrLockAcquired();
return context3d_.get();
}
TestWebGraphicsContext3D* TestContextProvider::UnboundTestContext3d() {
return context3d_.get();
}
void TestContextProvider::AddObserver(ContextLostObserver* obs) {
observers_.AddObserver(obs);
}
void TestContextProvider::RemoveObserver(ContextLostObserver* obs) {
observers_.RemoveObserver(obs);
}
} // namespace viz
| 4,068 |
1,066 | <gh_stars>1000+
/*
* Copyright 2017 GcsSloop
*
* 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.
*
* Last modified 2017-03-08 01:01:18
*
* GitHub: https://github.com/GcsSloop
* Website: http://www.gcssloop.com
* Weibo: http://weibo.com/GcsSloop
*/
package com.gcssloop.diycode_sdk.api.notifications.bean;
import com.gcssloop.diycode_sdk.api.topic.bean.Topic;
import com.gcssloop.diycode_sdk.api.user.bean.User;
import java.io.Serializable;
public class Notification implements Serializable {
private int id; // notification id
private String type; // 类型
private Boolean read; // 是否已读
private User actor; // 相关人员
private String mention_type; // 提及类型
private Reply mention; // 提及详情
private Topic topic; // topic
private Reply reply; // 回复
private Node node; // 节点变更
private String created_at; // 创建时间
private String updated_at; // 更新时间
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
public void setRead(Boolean read) {
this.read = read;
}
public Boolean getRead() {
return this.read;
}
public void setActor(User actor) {
this.actor = actor;
}
public User getActor() {
return this.actor;
}
public void setMention_type(String mention_type) {
this.mention_type = mention_type;
}
public String getMention_type() {
return this.mention_type;
}
public void setMention(Reply mention) {
this.mention = mention;
}
public Reply getMention() {
return this.mention;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
public Topic getTopic() {
return this.topic;
}
public void setReply(Reply reply) {
this.reply = reply;
}
public Reply getReply() {
return this.reply;
}
public void setNode(Node node) {
this.node = node;
}
public Node getNode() {
return this.node;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getCreated_at() {
return this.created_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public String getUpdated_at() {
return this.updated_at;
}
} | 1,313 |
1,473 | <filename>Core/src/org/sleuthkit/autopsy/modules/vmextractor/VMExtractorIngestModule.java
/*
* Autopsy Forensic Browser
*
* Copyright 2012-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.modules.vmextractor;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import org.openide.util.NbBundle;
import org.openide.util.NbBundle.Messages;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.GeneralFilter;
import org.sleuthkit.autopsy.casemodule.ImageDSProcessor;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataSourceProcessorCallback;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataSourceProcessorProgressMonitor;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.datamodel.ContentUtils;
import org.sleuthkit.autopsy.ingest.DataSourceIngestModuleAdapter;
import org.sleuthkit.autopsy.ingest.DataSourceIngestModuleProgress;
import org.sleuthkit.autopsy.ingest.IngestJobContext;
import org.sleuthkit.autopsy.ingest.IngestJobSettings;
import org.sleuthkit.autopsy.ingest.IngestManager;
import org.sleuthkit.autopsy.ingest.IngestMessage;
import org.sleuthkit.autopsy.ingest.IngestModule;
import org.sleuthkit.autopsy.ingest.IngestServices;
import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.DataSource;
import org.sleuthkit.datamodel.ReadContentInputStream.ReadContentInputStreamException;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskDataException;
/**
* An ingest module that extracts virtual machine files and adds them to a case
* as data sources.
*/
@NbBundle.Messages({"# {0} - output directory name", "VMExtractorIngestModule.cannotCreateOutputDir.message=Unable to create output directory: {0}."
})
final class VMExtractorIngestModule extends DataSourceIngestModuleAdapter {
private static final Logger logger = Logger.getLogger(VMExtractorIngestModule.class.getName());
private IngestJobContext context;
private Path ingestJobOutputDir;
private String parentDeviceId;
private String parentTimeZone;
private final HashMap<String, String> imageFolderToOutputFolder = new HashMap<>();
private int folderId = 0;
@Messages({"# {0} - data source name", "deviceIdQueryErrMsg=Data source {0} missing Device ID",
"VMExtractorIngestModule.noOpenCase.errMsg=No open case available."})
@Override
public void startUp(IngestJobContext context) throws IngestModuleException {
this.context = context;
long dataSourceObjId = context.getDataSource().getId();
try {
Case currentCase = Case.getCurrentCaseThrows();
SleuthkitCase caseDb = currentCase.getSleuthkitCase();
DataSource dataSource = caseDb.getDataSource(dataSourceObjId);
parentDeviceId = dataSource.getDeviceId();
parentTimeZone = dataSource.getTimeZone();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String timeStamp = dateFormat.format(Calendar.getInstance().getTime());
String ingestJobOutputDirName = context.getDataSource().getName() + "_" + context.getDataSource().getId() + "_" + timeStamp;
ingestJobOutputDirName = ingestJobOutputDirName.replace(':', '_');
ingestJobOutputDir = Paths.get(currentCase.getModuleDirectory(), VMExtractorIngestModuleFactory.getModuleName(), ingestJobOutputDirName);
// create module output folder to write extracted virtual machine files to
Files.createDirectories(ingestJobOutputDir);
} catch (IOException | SecurityException | UnsupportedOperationException ex) {
throw new IngestModule.IngestModuleException(Bundle.VMExtractorIngestModule_cannotCreateOutputDir_message(ex.getLocalizedMessage()), ex);
} catch (TskDataException | TskCoreException ex) {
throw new IngestModule.IngestModuleException(Bundle.deviceIdQueryErrMsg(context.getDataSource().getName()), ex);
} catch (NoCurrentCaseException ex) {
throw new IngestModule.IngestModuleException(Bundle.VMExtractorIngestModule_noOpenCase_errMsg(), ex);
}
}
@Override
public ProcessResult process(Content dataSource, DataSourceIngestModuleProgress progressBar) {
String outputFolderForThisVM;
List<AbstractFile> vmFiles;
// Configure and start progress bar - looking for VM files
progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.searchingImage.message"));
// Not sure how long it will take for search to complete.
progressBar.switchToIndeterminate();
logger.log(Level.INFO, "Looking for virtual machine files in data source {0}", dataSource.getName()); //NON-NLS
try {
// look for all VM files
vmFiles = findVirtualMachineFiles(dataSource);
vmFiles = removeNonVMFiles(vmFiles);
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error querying case database", ex); //NON-NLS
return ProcessResult.ERROR;
} catch (NoCurrentCaseException ex) {
logger.log(Level.SEVERE, "Exception while getting open case.", ex); //NON-NLS
return ProcessResult.ERROR;
}
if (vmFiles.isEmpty()) {
// no VM files found
logger.log(Level.INFO, "No virtual machine files found in data source {0}", dataSource.getName()); //NON-NLS
return ProcessResult.OK;
}
// display progress for saving each VM file to disk
progressBar.switchToDeterminate(vmFiles.size());
progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.exportingToDisk.message"));
int numFilesSaved = 0;
for (AbstractFile vmFile : vmFiles) {
if (context.dataSourceIngestIsCancelled()) {
break;
}
logger.log(Level.INFO, "Saving virtual machine file {0} to disk", vmFile.getName()); //NON-NLS
// get vmFolderPathInsideTheImage to the folder where VM is located
String vmFolderPathInsideTheImage = vmFile.getParentPath();
// check if the vmFolderPathInsideTheImage is already in hashmap
if (imageFolderToOutputFolder.containsKey(vmFolderPathInsideTheImage)) {
// if it is then we have already created output folder to write out all VM files in this parent folder
outputFolderForThisVM = imageFolderToOutputFolder.get(vmFolderPathInsideTheImage);
} else {
// if not - create output folder to write out VM files (can use any unique ID or number for folder name)
folderId++;
outputFolderForThisVM = Paths.get(ingestJobOutputDir.toString(), Integer.toString(folderId)).toString();
// add vmFolderPathInsideTheImage to hashmap
imageFolderToOutputFolder.put(vmFolderPathInsideTheImage, outputFolderForThisVM);
}
// write the vm file to output folder
try {
writeVirtualMachineToDisk(vmFile, outputFolderForThisVM);
} catch (ReadContentInputStreamException ex) {
logger.log(Level.WARNING, String.format("Failed to read virtual machine file '%s' (id=%d).",
vmFile.getName(), vmFile.getId()), ex); //NON-NLS
MessageNotifyUtil.Notify.error(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedExtractVM.title.txt"),
NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedExtractVM.msg.txt", vmFile.getName()));
} catch (Exception ex) {
logger.log(Level.SEVERE, String.format("Failed to write virtual machine file '%s' (id=%d) to folder '%s'.",
vmFile.getName(), vmFile.getId(), outputFolderForThisVM), ex); //NON-NLS
MessageNotifyUtil.Notify.error(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedExtractVM.title.txt"),
NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedExtractVM.msg.txt", vmFile.getName()));
}
// Update progress bar
numFilesSaved++;
progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.exportingToDisk.message"), numFilesSaved);
}
logger.log(Level.INFO, "Finished saving virtual machine files to disk"); //NON-NLS
// update progress bar
progressBar.switchToDeterminate(imageFolderToOutputFolder.size());
progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.queuingIngestJobs.message"));
// this is for progress bar purposes because at this point we only know in advance how many job folders to ingest, not how many data sources.
int numJobsQueued = 0;
// start processing output folders after we are done writing out all vm files
for (String folder : imageFolderToOutputFolder.values()) {
if (context.dataSourceIngestIsCancelled()) {
break;
}
List<String> vmFilesToIngest = VirtualMachineFinder.identifyVirtualMachines(Paths.get(folder));
for (String file : vmFilesToIngest) {
try {
logger.log(Level.INFO, "Ingesting virtual machine file {0} in folder {1}", new Object[]{file, folder}); //NON-NLS
// for extracted virtual machines there is no manifest XML file to read data source ID from so use parent data source ID.
// ingest the data sources
ingestVirtualMachineImage(Paths.get(folder, file));
} catch (InterruptedException ex) {
logger.log(Level.INFO, "Interrupted while ingesting virtual machine file " + file + " in folder " + folder, ex); //NON-NLS
} catch (IOException ex) {
logger.log(Level.SEVERE, "Failed to ingest virtual machine file " + file + " in folder " + folder, ex); //NON-NLS
MessageNotifyUtil.Notify.error(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedIngestVM.title.txt"),
NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedIngestVM.msg.txt", file));
} catch (NoCurrentCaseException ex) {
logger.log(Level.SEVERE, "Exception while getting open case.", ex); //NON-NLS
MessageNotifyUtil.Notify.error(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedIngestVM.title.txt"),
Bundle.VMExtractorIngestModule_noOpenCase_errMsg());
}
}
// Update progress bar
numJobsQueued++;
progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.queuingIngestJobs.message"), numJobsQueued);
}
logger.log(Level.INFO, "VMExtractorIngestModule completed processing of data source {0}", dataSource.getName()); //NON-NLS
return ProcessResult.OK;
}
/**
* Locate all supported virtual machine files, if any, contained in a data
* source.
*
* @param dataSource The data source.
*
* @return A list of virtual machine files, possibly empty.
*
* @throws TskCoreException if there is a problem querying the case
* database.
*/
private static List<AbstractFile> findVirtualMachineFiles(Content dataSource) throws TskCoreException, NoCurrentCaseException {
List<AbstractFile> vmFiles = new ArrayList<>();
for (String vmExtension : GeneralFilter.VIRTUAL_MACHINE_EXTS) {
String searchString = "%" + vmExtension; // want a search string that looks like this "%.vmdk"
vmFiles.addAll(Case.getCurrentCaseThrows().getServices().getFileManager().findFiles(dataSource, searchString));
}
return vmFiles;
}
/**
* Check all the files and if a file is a vhd then check to make sure it is a valid vhd using the mimetype. We are not
* checking the mimetype for VMDK's at this point in time.
*
* @param vmFiles List of virtual machine abstract files to look at
*
* @return List of abstract files of virtual machine files.
*/
private static List<AbstractFile> removeNonVMFiles(List<AbstractFile> vmFiles) {
List<AbstractFile> vFile = new ArrayList<>();
FileTypeDetector fileTypeDetector = null;
for (AbstractFile vmFile : vmFiles) {
if (vmFile.getNameExtension().equalsIgnoreCase("vhd")) {
String fileMimeType = vmFile.getMIMEType();
if (fileMimeType == null) {
try {
fileTypeDetector = new FileTypeDetector();
} catch (FileTypeDetector.FileTypeDetectorInitException ex) {
logger.log(Level.WARNING, String.format("Unable to create file type detector for determining MIME type for file %s with id of %d", vmFile.getName(), vmFile.getId()));
vFile.add(vmFile);
continue;
}
fileMimeType = fileTypeDetector.getMIMEType(vmFile);
try {
vmFile.setMIMEType(fileMimeType);
vmFile.save();
} catch (TskCoreException ex) {
logger.log(Level.WARNING, String.format("Unable to save mimetype of %s for file %s with id of %d", fileMimeType, vmFile.getName(), vmFile.getId()));
}
}
if (fileMimeType.equalsIgnoreCase("application/x-vhd")) {
vFile.add(vmFile);
}
} else {
vFile.add(vmFile);
}
}
return vFile;
}
/**
* Writes out an abstract file to a specified output folder.
*
* @param vmFile Abstract file to write to disk.
* @param outputFolderForThisVM Absolute path to output folder.
*
* @throws IOException General file exception.
* @throws ReadContentInputStreamException Thrown when there's an issue reading the file.
*/
private void writeVirtualMachineToDisk(AbstractFile vmFile, String outputFolderForThisVM) throws ReadContentInputStreamException, IOException {
// TODO: check available disk space first? See IngestMonitor.getFreeSpace()
// check if output folder exists
File destinationFolder = Paths.get(outputFolderForThisVM).toFile();
if (!destinationFolder.exists()) {
destinationFolder.mkdirs();
}
/*
* Write the virtual machine file to disk.
*/
File localFile = Paths.get(outputFolderForThisVM, vmFile.getName()).toFile();
ContentUtils.writeToFile(vmFile, localFile, context::dataSourceIngestIsCancelled);
}
/**
* Add a virtual machine file to the case as a data source and analyze it
* with the ingest modules.
*
* @param vmFile A virtual machine file.
*/
private void ingestVirtualMachineImage(Path vmFile) throws InterruptedException, IOException, NoCurrentCaseException {
/*
* Try to add the virtual machine file to the case as a data source.
*/
UUID taskId = UUID.randomUUID();
Case.getCurrentCaseThrows().notifyAddingDataSource(taskId);
ImageDSProcessor dataSourceProcessor = new ImageDSProcessor();
AddDataSourceCallback dspCallback = new AddDataSourceCallback(vmFile);
synchronized (this) {
dataSourceProcessor.run(parentDeviceId, vmFile.toString(), parentTimeZone, false, new AddDataSourceProgressMonitor(), dspCallback);
/*
* Block the ingest thread until the data source processor finishes.
*/
this.wait();
}
/*
* If the image was added, start analysis on it with the ingest modules for this
* ingest context. Note that this does not wait for ingest to complete.
*/
if (!dspCallback.vmDataSources.isEmpty()) {
Case.getCurrentCaseThrows().notifyDataSourceAdded(dspCallback.vmDataSources.get(0), taskId);
List<Content> dataSourceContent = new ArrayList<>(dspCallback.vmDataSources);
IngestJobSettings ingestJobSettings = new IngestJobSettings(context.getExecutionContext());
for (String warning : ingestJobSettings.getWarnings()) {
logger.log(Level.WARNING, String.format("Ingest job settings warning for virtual machine file %s : %s", vmFile.toString(), warning)); //NON-NLS
}
IngestServices.getInstance().postMessage(IngestMessage.createMessage(IngestMessage.MessageType.INFO,
VMExtractorIngestModuleFactory.getModuleName(),
NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.addedVirtualMachineImage.message", vmFile.toString())));
IngestManager.getInstance().beginIngestJob(dataSourceContent, ingestJobSettings);
} else {
Case.getCurrentCaseThrows().notifyFailedAddingDataSource(taskId);
}
}
/**
* A do nothing data source processor progress monitor.
*/
private static final class AddDataSourceProgressMonitor implements DataSourceProcessorProgressMonitor {
@Override
public void setIndeterminate(final boolean indeterminate) {
}
@Override
public void setProgress(final int progress) {
}
@Override
public void setProgressText(final String text) {
}
}
/**
* A callback for the data source processor that captures the content
* objects for the data source and unblocks the ingest thread.
*/
private final class AddDataSourceCallback extends DataSourceProcessorCallback {
private final Path vmFile;
private final List<Content> vmDataSources;
/**
* Constructs a callback for the data source processor.
*
* @param vmFile The virtual machine file to be added as a data source.
*/
private AddDataSourceCallback(Path vmFile) {
this.vmFile = vmFile;
vmDataSources = new ArrayList<>();
}
@Override
public void done(DataSourceProcessorCallback.DataSourceProcessorResult result, List<String> errList, List<Content> content) {
for (String error : errList) {
String logMessage = String.format("Data source processor error for virtual machine file %s: %s", vmFile.toString(), error); //NON-NLS
if (DataSourceProcessorCallback.DataSourceProcessorResult.CRITICAL_ERRORS == result) {
logger.log(Level.SEVERE, logMessage);
} else {
logger.log(Level.WARNING, logMessage);
}
}
/*
* Save a reference to the content object so it can be used to
* create a new ingest job.
*/
if (!content.isEmpty()) {
vmDataSources.add(content.get(0));
}
/*
* Unblock the ingest thread.
*/
synchronized (VMExtractorIngestModule.this) {
VMExtractorIngestModule.this.notify();
}
}
@Override
public void doneEDT(DataSourceProcessorResult result, List<String> errList, List<Content> newContents) {
done(result, errList, newContents);
}
}
}
| 8,408 |
6,989 | <gh_stars>1000+
#include "fnv.h"
| 17 |
567 | /**********
© Copyright 2021 Xilinx, 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.
**********/
#include <adf.h>
#include "kernel.h"
using namespace adf;
class adaptive_graph : public graph
{
public:
port<direction::in> in;
port<direction::out> dataout;
// Declare the filter kernel
kernel k[2];
adaptive_graph()
{
k[0] = kernel::create(aie_dest1);
source(k[0]) = "aie_dest1.cc";
k[1] = kernel::create(aie_dest2);
source(k[1]) = "aie_dest2.cc";
runtime<ratio>(k[0]) = 0.8;
runtime<ratio>(k[1]) = 0.8;
connect< window<4096> >net0(in, k[0].in[0]);
connect< stream >net1(k[0].out[0], k[1].in[0]);
connect< window<4096> >net2(k[0].out[1], k[1].in[1]);
connect< stream >net3(k[1].out[0], dataout);
fifo_depth(net1)=1024;
}
};
| 484 |
2,056 | import net.qihoo.qconf.Qconf;
import net.qihoo.qconf.QconfException;
import java.util.ArrayList;
import java.util.Map;
public class TestQconfThread extends Thread
{
int pauseTime;
public TestQconfThread(int pTime)
{
this.pauseTime = pTime;
}
public void run()
{
while(true)
{
this.doIt();
try
{
Thread.sleep(pauseTime * 100);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public void doIt()
{
// ********************************Asign Idc Usage******************************
String key = "__qconf_anchor_node";
String idc = "corp";
// Get Conf
try
{
String value = Qconf.getConf(key, idc);
System.out.println("Thread " + pauseTime + " conf :" + value);
}
catch(QconfException e)
{
e.printStackTrace();
}
// get AllHost
try
{
ArrayList<String> hosts = Qconf.getAllHost(key, idc);
for(String host : hosts)
{
System.out.println("Thread " + pauseTime + " allhost : " + host);
}
}
catch(QconfException e)
{
e.printStackTrace();
}
// get Host
try
{
String host = Qconf.getHost(key, idc);
System.out.println("Thread " + pauseTime + " host : " + host);
}
catch(QconfException e)
{
e.printStackTrace();
}
// get Batch Conf
try
{
Map<String, String> confs = Qconf.getBatchConf(key);
for(Map.Entry<String, String> conf : confs.entrySet())
{
System.out.println(conf.getKey() + " : " + conf.getValue());
}
}
catch(QconfException e)
{
e.printStackTrace();
}
// get Batch keys
try
{
ArrayList<String> keys = Qconf.getBatchKeys(key);
for(String one_key: keys)
{
System.out.println(one_key);
}
}
catch(QconfException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
for (int i = 1; i <= 100; i++)
{
TestQconfThread tqt = new TestQconfThread(i);
tqt.start();
}
}
}
| 1,412 |
643 | package com.hellokoding.datastructure.graph;
import java.util.ArrayList;
import java.util.List;
public class GraphWeightedByAdjacencyList {
private int V;
private List<List<WeightedVertex>> adjacencyList;
public GraphWeightedByAdjacencyList(int V) {
this.V = V;
adjacencyList = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adjacencyList.add(new ArrayList<>());
}
}
public Integer getV() {
return this.V;
}
public List<List<WeightedVertex>> getAdjacencyList() {
return this.adjacencyList;
}
public void addEdge(int source, int dest, int weight) {
adjacencyList.get(source).add(new WeightedVertex(dest, weight));
}
public void printAdjacencyList() {
for (int i = 0; i < V; i++) {
System.out.printf("Adjacency list of vertex %d is %s %s", i,
adjacencyList.get(i), System.lineSeparator());
}
}
static class WeightedVertex {
final Integer vertex, weight;
public WeightedVertex(int vertex, int weight) {
this.vertex = vertex;
this.weight = weight;
}
public int getWeight() {
return this.weight;
}
public String toString() {
return String.format("%d (weight %d)", vertex, weight);
}
}
public static void main(String[] args) {
GraphWeightedByAdjacencyList g = new GraphWeightedByAdjacencyList(4);
g.addEdge(0, 1, 19);
g.addEdge(2, 0, 15);
g.addEdge(2, 1, 17);
g.addEdge(3, 2, 12);
g.printAdjacencyList();
}
}
| 754 |
2,494 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* token.c
*
* This file implements the NSSCKFWToken type and methods.
*/
#ifndef CK_T
#include "ck.h"
#endif /* CK_T */
/*
* NSSCKFWToken
*
* -- create/destroy --
* nssCKFWToken_Create
* nssCKFWToken_Destroy
*
* -- public accessors --
* NSSCKFWToken_GetMDToken
* NSSCKFWToken_GetFWSlot
* NSSCKFWToken_GetMDSlot
* NSSCKFWToken_GetSessionState
*
* -- implement public accessors --
* nssCKFWToken_GetMDToken
* nssCKFWToken_GetFWSlot
* nssCKFWToken_GetMDSlot
* nssCKFWToken_GetSessionState
* nssCKFWToken_SetSessionState
*
* -- private accessors --
* nssCKFWToken_SetSessionState
* nssCKFWToken_RemoveSession
* nssCKFWToken_CloseAllSessions
* nssCKFWToken_GetSessionCount
* nssCKFWToken_GetRwSessionCount
* nssCKFWToken_GetRoSessionCount
* nssCKFWToken_GetSessionObjectHash
* nssCKFWToken_GetMDObjectHash
* nssCKFWToken_GetObjectHandleHash
*
* -- module fronts --
* nssCKFWToken_InitToken
* nssCKFWToken_GetLabel
* nssCKFWToken_GetManufacturerID
* nssCKFWToken_GetModel
* nssCKFWToken_GetSerialNumber
* nssCKFWToken_GetHasRNG
* nssCKFWToken_GetIsWriteProtected
* nssCKFWToken_GetLoginRequired
* nssCKFWToken_GetUserPinInitialized
* nssCKFWToken_GetRestoreKeyNotNeeded
* nssCKFWToken_GetHasClockOnToken
* nssCKFWToken_GetHasProtectedAuthenticationPath
* nssCKFWToken_GetSupportsDualCryptoOperations
* nssCKFWToken_GetMaxSessionCount
* nssCKFWToken_GetMaxRwSessionCount
* nssCKFWToken_GetMaxPinLen
* nssCKFWToken_GetMinPinLen
* nssCKFWToken_GetTotalPublicMemory
* nssCKFWToken_GetFreePublicMemory
* nssCKFWToken_GetTotalPrivateMemory
* nssCKFWToken_GetFreePrivateMemory
* nssCKFWToken_GetHardwareVersion
* nssCKFWToken_GetFirmwareVersion
* nssCKFWToken_GetUTCTime
* nssCKFWToken_OpenSession
* nssCKFWToken_GetMechanismCount
* nssCKFWToken_GetMechanismTypes
* nssCKFWToken_GetMechanism
*/
struct NSSCKFWTokenStr {
NSSCKFWMutex *mutex;
NSSArena *arena;
NSSCKMDToken *mdToken;
NSSCKFWSlot *fwSlot;
NSSCKMDSlot *mdSlot;
NSSCKFWInstance *fwInstance;
NSSCKMDInstance *mdInstance;
/*
* Everything above is set at creation time, and then not modified.
* The invariants the mutex protects are:
*
* 1) Each of the cached descriptions (versions, etc.) are in an
* internally consistant state.
*
* 2) The session counts and hashes are consistant.
*
* 3) The object hashes are consistant.
*
* Note that the calls accessing the cached descriptions will call
* the NSSCKMDToken methods with the mutex locked. Those methods
* may then call the public NSSCKFWToken routines. Those public
* routines only access the constant data above and the atomic
* CK_STATE session state variable below, so there's no problem.
* But be careful if you add to this object; mutexes are in
* general not reentrant, so don't create deadlock situations.
*/
NSSUTF8 *label;
NSSUTF8 *manufacturerID;
NSSUTF8 *model;
NSSUTF8 *serialNumber;
CK_VERSION hardwareVersion;
CK_VERSION firmwareVersion;
CK_ULONG sessionCount;
CK_ULONG rwSessionCount;
nssCKFWHash *sessions;
nssCKFWHash *sessionObjectHash;
nssCKFWHash *mdObjectHash;
nssCKFWHash *mdMechanismHash;
CK_STATE state;
};
#ifdef DEBUG
/*
* But first, the pointer-tracking stuff.
*
* NOTE: the pointer-tracking support in NSS/base currently relies
* upon NSPR's CallOnce support. That, however, relies upon NSPR's
* locking, which is tied into the runtime. We need a pointer-tracker
* implementation that uses the locks supplied through C_Initialize.
* That support, however, can be filled in later. So for now, I'll
* just do this routines as no-ops.
*/
static CK_RV
token_add_pointer
(
const NSSCKFWToken *fwToken
)
{
return CKR_OK;
}
static CK_RV
token_remove_pointer
(
const NSSCKFWToken *fwToken
)
{
return CKR_OK;
}
NSS_IMPLEMENT CK_RV
nssCKFWToken_verifyPointer
(
const NSSCKFWToken *fwToken
)
{
return CKR_OK;
}
#endif /* DEBUG */
/*
* nssCKFWToken_Create
*
*/
NSS_IMPLEMENT NSSCKFWToken *
nssCKFWToken_Create
(
NSSCKFWSlot *fwSlot,
NSSCKMDToken *mdToken,
CK_RV *pError
)
{
NSSArena *arena = (NSSArena *)NULL;
NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL;
CK_BBOOL called_setup = CK_FALSE;
/*
* We have already verified the arguments in nssCKFWSlot_GetToken.
*/
arena = NSSArena_Create();
if (!arena) {
*pError = CKR_HOST_MEMORY;
goto loser;
}
fwToken = nss_ZNEW(arena, NSSCKFWToken);
if (!fwToken) {
*pError = CKR_HOST_MEMORY;
goto loser;
}
fwToken->arena = arena;
fwToken->mdToken = mdToken;
fwToken->fwSlot = fwSlot;
fwToken->fwInstance = nssCKFWSlot_GetFWInstance(fwSlot);
fwToken->mdInstance = nssCKFWSlot_GetMDInstance(fwSlot);
fwToken->state = CKS_RO_PUBLIC_SESSION; /* some default */
fwToken->sessionCount = 0;
fwToken->rwSessionCount = 0;
fwToken->mutex = nssCKFWInstance_CreateMutex(fwToken->fwInstance, arena, pError);
if (!fwToken->mutex) {
if( CKR_OK == *pError ) {
*pError = CKR_GENERAL_ERROR;
}
goto loser;
}
fwToken->sessions = nssCKFWHash_Create(fwToken->fwInstance, arena, pError);
if (!fwToken->sessions) {
if( CKR_OK == *pError ) {
*pError = CKR_GENERAL_ERROR;
}
goto loser;
}
if( CK_TRUE != nssCKFWInstance_GetModuleHandlesSessionObjects(
fwToken->fwInstance) ) {
fwToken->sessionObjectHash = nssCKFWHash_Create(fwToken->fwInstance,
arena, pError);
if (!fwToken->sessionObjectHash) {
if( CKR_OK == *pError ) {
*pError = CKR_GENERAL_ERROR;
}
goto loser;
}
}
fwToken->mdObjectHash = nssCKFWHash_Create(fwToken->fwInstance,
arena, pError);
if (!fwToken->mdObjectHash) {
if( CKR_OK == *pError ) {
*pError = CKR_GENERAL_ERROR;
}
goto loser;
}
fwToken->mdMechanismHash = nssCKFWHash_Create(fwToken->fwInstance,
arena, pError);
if (!fwToken->mdMechanismHash) {
if( CKR_OK == *pError ) {
*pError = CKR_GENERAL_ERROR;
}
goto loser;
}
/* More here */
if (mdToken->Setup) {
*pError = mdToken->Setup(mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance);
if( CKR_OK != *pError ) {
goto loser;
}
}
called_setup = CK_TRUE;
#ifdef DEBUG
*pError = token_add_pointer(fwToken);
if( CKR_OK != *pError ) {
goto loser;
}
#endif /* DEBUG */
*pError = CKR_OK;
return fwToken;
loser:
if( CK_TRUE == called_setup ) {
if (mdToken->Invalidate) {
mdToken->Invalidate(mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance);
}
}
if (arena) {
(void)NSSArena_Destroy(arena);
}
return (NSSCKFWToken *)NULL;
}
static void
nss_ckfwtoken_session_iterator
(
const void *key,
void *value,
void *closure
)
{
/*
* Remember that the fwToken->mutex is locked
*/
NSSCKFWSession *fwSession = (NSSCKFWSession *)value;
(void)nssCKFWSession_Destroy(fwSession, CK_FALSE);
return;
}
static void
nss_ckfwtoken_object_iterator
(
const void *key,
void *value,
void *closure
)
{
/*
* Remember that the fwToken->mutex is locked
*/
NSSCKFWObject *fwObject = (NSSCKFWObject *)value;
(void)nssCKFWObject_Finalize(fwObject, CK_FALSE);
return;
}
/*
* nssCKFWToken_Destroy
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_Destroy
(
NSSCKFWToken *fwToken
)
{
CK_RV error = CKR_OK;
#ifdef NSSDEBUG
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return error;
}
#endif /* NSSDEBUG */
(void)nssCKFWMutex_Destroy(fwToken->mutex);
if (fwToken->mdToken->Invalidate) {
fwToken->mdToken->Invalidate(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/* we can destroy the list without locking now because no one else is
* referencing us (or _Destroy was invalidly called!)
*/
nssCKFWHash_Iterate(fwToken->sessions, nss_ckfwtoken_session_iterator,
(void *)NULL);
nssCKFWHash_Destroy(fwToken->sessions);
/* session objects go away when their sessions are removed */
if (fwToken->sessionObjectHash) {
nssCKFWHash_Destroy(fwToken->sessionObjectHash);
}
/* free up the token objects */
if (fwToken->mdObjectHash) {
nssCKFWHash_Iterate(fwToken->mdObjectHash, nss_ckfwtoken_object_iterator,
(void *)NULL);
nssCKFWHash_Destroy(fwToken->mdObjectHash);
}
if (fwToken->mdMechanismHash) {
nssCKFWHash_Destroy(fwToken->mdMechanismHash);
}
nssCKFWSlot_ClearToken(fwToken->fwSlot);
#ifdef DEBUG
error = token_remove_pointer(fwToken);
#endif /* DEBUG */
(void)NSSArena_Destroy(fwToken->arena);
return error;
}
/*
* nssCKFWToken_GetMDToken
*
*/
NSS_IMPLEMENT NSSCKMDToken *
nssCKFWToken_GetMDToken
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (NSSCKMDToken *)NULL;
}
#endif /* NSSDEBUG */
return fwToken->mdToken;
}
/*
* nssCKFWToken_GetArena
*
*/
NSS_IMPLEMENT NSSArena *
nssCKFWToken_GetArena
(
NSSCKFWToken *fwToken,
CK_RV *pError
)
{
#ifdef NSSDEBUG
if (!pError) {
return (NSSArena *)NULL;
}
*pError = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != *pError ) {
return (NSSArena *)NULL;
}
#endif /* NSSDEBUG */
return fwToken->arena;
}
/*
* nssCKFWToken_GetFWSlot
*
*/
NSS_IMPLEMENT NSSCKFWSlot *
nssCKFWToken_GetFWSlot
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (NSSCKFWSlot *)NULL;
}
#endif /* NSSDEBUG */
return fwToken->fwSlot;
}
/*
* nssCKFWToken_GetMDSlot
*
*/
NSS_IMPLEMENT NSSCKMDSlot *
nssCKFWToken_GetMDSlot
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (NSSCKMDSlot *)NULL;
}
#endif /* NSSDEBUG */
return fwToken->mdSlot;
}
/*
* nssCKFWToken_GetSessionState
*
*/
NSS_IMPLEMENT CK_STATE
nssCKFWToken_GetSessionState
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CKS_RO_PUBLIC_SESSION; /* whatever */
}
#endif /* NSSDEBUG */
/*
* BTW, do not lock the token in this method.
*/
/*
* Theoretically, there is no state if there aren't any
* sessions open. But then we'd need to worry about
* reporting an error, etc. What the heck-- let's just
* revert to CKR_RO_PUBLIC_SESSION as the "default."
*/
return fwToken->state;
}
/*
* nssCKFWToken_InitToken
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_InitToken
(
NSSCKFWToken *fwToken,
NSSItem *pin,
NSSUTF8 *label
)
{
CK_RV error;
#ifdef NSSDEBUG
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return CKR_ARGUMENTS_BAD;
}
#endif /* NSSDEBUG */
error = nssCKFWMutex_Lock(fwToken->mutex);
if( CKR_OK != error ) {
return error;
}
if( fwToken->sessionCount > 0 ) {
error = CKR_SESSION_EXISTS;
goto done;
}
if (!fwToken->mdToken->InitToken) {
error = CKR_DEVICE_ERROR;
goto done;
}
if (!pin) {
if( nssCKFWToken_GetHasProtectedAuthenticationPath(fwToken) ) {
; /* okay */
} else {
error = CKR_PIN_INCORRECT;
goto done;
}
}
if (!label) {
label = (NSSUTF8 *) "";
}
error = fwToken->mdToken->InitToken(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance, pin, label);
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return error;
}
/*
* nssCKFWToken_GetLabel
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_GetLabel
(
NSSCKFWToken *fwToken,
CK_CHAR label[32]
)
{
CK_RV error = CKR_OK;
#ifdef NSSDEBUG
if( (CK_CHAR_PTR)NULL == label ) {
return CKR_ARGUMENTS_BAD;
}
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return error;
}
#endif /* NSSDEBUG */
error = nssCKFWMutex_Lock(fwToken->mutex);
if( CKR_OK != error ) {
return error;
}
if (!fwToken->label) {
if (fwToken->mdToken->GetLabel) {
fwToken->label = fwToken->mdToken->GetLabel(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance, &error);
if ((!fwToken->label) && (CKR_OK != error)) {
goto done;
}
} else {
fwToken->label = (NSSUTF8 *) "";
}
}
(void)nssUTF8_CopyIntoFixedBuffer(fwToken->label, (char *)label, 32, ' ');
error = CKR_OK;
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return error;
}
/*
* nssCKFWToken_GetManufacturerID
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_GetManufacturerID
(
NSSCKFWToken *fwToken,
CK_CHAR manufacturerID[32]
)
{
CK_RV error = CKR_OK;
#ifdef NSSDEBUG
if( (CK_CHAR_PTR)NULL == manufacturerID ) {
return CKR_ARGUMENTS_BAD;
}
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return error;
}
#endif /* NSSDEBUG */
error = nssCKFWMutex_Lock(fwToken->mutex);
if( CKR_OK != error ) {
return error;
}
if (!fwToken->manufacturerID) {
if (fwToken->mdToken->GetManufacturerID) {
fwToken->manufacturerID = fwToken->mdToken->GetManufacturerID(fwToken->mdToken,
fwToken, fwToken->mdInstance, fwToken->fwInstance, &error);
if ((!fwToken->manufacturerID) && (CKR_OK != error)) {
goto done;
}
} else {
fwToken->manufacturerID = (NSSUTF8 *)"";
}
}
(void)nssUTF8_CopyIntoFixedBuffer(fwToken->manufacturerID, (char *)manufacturerID, 32, ' ');
error = CKR_OK;
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return error;
}
/*
* nssCKFWToken_GetModel
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_GetModel
(
NSSCKFWToken *fwToken,
CK_CHAR model[16]
)
{
CK_RV error = CKR_OK;
#ifdef NSSDEBUG
if( (CK_CHAR_PTR)NULL == model ) {
return CKR_ARGUMENTS_BAD;
}
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return error;
}
#endif /* NSSDEBUG */
error = nssCKFWMutex_Lock(fwToken->mutex);
if( CKR_OK != error ) {
return error;
}
if (!fwToken->model) {
if (fwToken->mdToken->GetModel) {
fwToken->model = fwToken->mdToken->GetModel(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance, &error);
if ((!fwToken->model) && (CKR_OK != error)) {
goto done;
}
} else {
fwToken->model = (NSSUTF8 *)"";
}
}
(void)nssUTF8_CopyIntoFixedBuffer(fwToken->model, (char *)model, 16, ' ');
error = CKR_OK;
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return error;
}
/*
* nssCKFWToken_GetSerialNumber
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_GetSerialNumber
(
NSSCKFWToken *fwToken,
CK_CHAR serialNumber[16]
)
{
CK_RV error = CKR_OK;
#ifdef NSSDEBUG
if( (CK_CHAR_PTR)NULL == serialNumber ) {
return CKR_ARGUMENTS_BAD;
}
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return error;
}
#endif /* NSSDEBUG */
error = nssCKFWMutex_Lock(fwToken->mutex);
if( CKR_OK != error ) {
return error;
}
if (!fwToken->serialNumber) {
if (fwToken->mdToken->GetSerialNumber) {
fwToken->serialNumber = fwToken->mdToken->GetSerialNumber(fwToken->mdToken,
fwToken, fwToken->mdInstance, fwToken->fwInstance, &error);
if ((!fwToken->serialNumber) && (CKR_OK != error)) {
goto done;
}
} else {
fwToken->serialNumber = (NSSUTF8 *)"";
}
}
(void)nssUTF8_CopyIntoFixedBuffer(fwToken->serialNumber, (char *)serialNumber, 16, ' ');
error = CKR_OK;
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return error;
}
/*
* nssCKFWToken_GetHasRNG
*
*/
NSS_IMPLEMENT CK_BBOOL
nssCKFWToken_GetHasRNG
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_FALSE;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetHasRNG) {
return CK_FALSE;
}
return fwToken->mdToken->GetHasRNG(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetIsWriteProtected
*
*/
NSS_IMPLEMENT CK_BBOOL
nssCKFWToken_GetIsWriteProtected
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_FALSE;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetIsWriteProtected) {
return CK_FALSE;
}
return fwToken->mdToken->GetIsWriteProtected(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetLoginRequired
*
*/
NSS_IMPLEMENT CK_BBOOL
nssCKFWToken_GetLoginRequired
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_FALSE;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetLoginRequired) {
return CK_FALSE;
}
return fwToken->mdToken->GetLoginRequired(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetUserPinInitialized
*
*/
NSS_IMPLEMENT CK_BBOOL
nssCKFWToken_GetUserPinInitialized
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_FALSE;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetUserPinInitialized) {
return CK_FALSE;
}
return fwToken->mdToken->GetUserPinInitialized(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetRestoreKeyNotNeeded
*
*/
NSS_IMPLEMENT CK_BBOOL
nssCKFWToken_GetRestoreKeyNotNeeded
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_FALSE;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetRestoreKeyNotNeeded) {
return CK_FALSE;
}
return fwToken->mdToken->GetRestoreKeyNotNeeded(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetHasClockOnToken
*
*/
NSS_IMPLEMENT CK_BBOOL
nssCKFWToken_GetHasClockOnToken
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_FALSE;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetHasClockOnToken) {
return CK_FALSE;
}
return fwToken->mdToken->GetHasClockOnToken(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetHasProtectedAuthenticationPath
*
*/
NSS_IMPLEMENT CK_BBOOL
nssCKFWToken_GetHasProtectedAuthenticationPath
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_FALSE;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetHasProtectedAuthenticationPath) {
return CK_FALSE;
}
return fwToken->mdToken->GetHasProtectedAuthenticationPath(fwToken->mdToken,
fwToken, fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetSupportsDualCryptoOperations
*
*/
NSS_IMPLEMENT CK_BBOOL
nssCKFWToken_GetSupportsDualCryptoOperations
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_FALSE;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetSupportsDualCryptoOperations) {
return CK_FALSE;
}
return fwToken->mdToken->GetSupportsDualCryptoOperations(fwToken->mdToken,
fwToken, fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetMaxSessionCount
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetMaxSessionCount
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_UNAVAILABLE_INFORMATION;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetMaxSessionCount) {
return CK_UNAVAILABLE_INFORMATION;
}
return fwToken->mdToken->GetMaxSessionCount(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetMaxRwSessionCount
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetMaxRwSessionCount
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_UNAVAILABLE_INFORMATION;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetMaxRwSessionCount) {
return CK_UNAVAILABLE_INFORMATION;
}
return fwToken->mdToken->GetMaxRwSessionCount(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetMaxPinLen
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetMaxPinLen
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_UNAVAILABLE_INFORMATION;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetMaxPinLen) {
return CK_UNAVAILABLE_INFORMATION;
}
return fwToken->mdToken->GetMaxPinLen(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetMinPinLen
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetMinPinLen
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_UNAVAILABLE_INFORMATION;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetMinPinLen) {
return CK_UNAVAILABLE_INFORMATION;
}
return fwToken->mdToken->GetMinPinLen(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetTotalPublicMemory
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetTotalPublicMemory
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_UNAVAILABLE_INFORMATION;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetTotalPublicMemory) {
return CK_UNAVAILABLE_INFORMATION;
}
return fwToken->mdToken->GetTotalPublicMemory(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetFreePublicMemory
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetFreePublicMemory
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_UNAVAILABLE_INFORMATION;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetFreePublicMemory) {
return CK_UNAVAILABLE_INFORMATION;
}
return fwToken->mdToken->GetFreePublicMemory(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetTotalPrivateMemory
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetTotalPrivateMemory
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_UNAVAILABLE_INFORMATION;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetTotalPrivateMemory) {
return CK_UNAVAILABLE_INFORMATION;
}
return fwToken->mdToken->GetTotalPrivateMemory(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetFreePrivateMemory
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetFreePrivateMemory
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CK_UNAVAILABLE_INFORMATION;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetFreePrivateMemory) {
return CK_UNAVAILABLE_INFORMATION;
}
return fwToken->mdToken->GetFreePrivateMemory(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetHardwareVersion
*
*/
NSS_IMPLEMENT CK_VERSION
nssCKFWToken_GetHardwareVersion
(
NSSCKFWToken *fwToken
)
{
CK_VERSION rv;
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
rv.major = rv.minor = 0;
return rv;
}
#endif /* NSSDEBUG */
if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) {
rv.major = rv.minor = 0;
return rv;
}
if( (0 != fwToken->hardwareVersion.major) ||
(0 != fwToken->hardwareVersion.minor) ) {
rv = fwToken->hardwareVersion;
goto done;
}
if (fwToken->mdToken->GetHardwareVersion) {
fwToken->hardwareVersion = fwToken->mdToken->GetHardwareVersion(
fwToken->mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance);
} else {
fwToken->hardwareVersion.major = 0;
fwToken->hardwareVersion.minor = 1;
}
rv = fwToken->hardwareVersion;
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return rv;
}
/*
* nssCKFWToken_GetFirmwareVersion
*
*/
NSS_IMPLEMENT CK_VERSION
nssCKFWToken_GetFirmwareVersion
(
NSSCKFWToken *fwToken
)
{
CK_VERSION rv;
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
rv.major = rv.minor = 0;
return rv;
}
#endif /* NSSDEBUG */
if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) {
rv.major = rv.minor = 0;
return rv;
}
if( (0 != fwToken->firmwareVersion.major) ||
(0 != fwToken->firmwareVersion.minor) ) {
rv = fwToken->firmwareVersion;
goto done;
}
if (fwToken->mdToken->GetFirmwareVersion) {
fwToken->firmwareVersion = fwToken->mdToken->GetFirmwareVersion(
fwToken->mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance);
} else {
fwToken->firmwareVersion.major = 0;
fwToken->firmwareVersion.minor = 1;
}
rv = fwToken->firmwareVersion;
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return rv;
}
/*
* nssCKFWToken_GetUTCTime
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_GetUTCTime
(
NSSCKFWToken *fwToken,
CK_CHAR utcTime[16]
)
{
CK_RV error = CKR_OK;
#ifdef NSSDEBUG
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return error;
}
if( (CK_CHAR_PTR)NULL == utcTime ) {
return CKR_ARGUMENTS_BAD;
}
#endif /* DEBUG */
if( CK_TRUE != nssCKFWToken_GetHasClockOnToken(fwToken) ) {
/* return CKR_DEVICE_ERROR; */
(void)nssUTF8_CopyIntoFixedBuffer((NSSUTF8 *)NULL, (char *)utcTime, 16, ' ');
return CKR_OK;
}
if (!fwToken->mdToken->GetUTCTime) {
/* It said it had one! */
return CKR_GENERAL_ERROR;
}
error = fwToken->mdToken->GetUTCTime(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance, utcTime);
if( CKR_OK != error ) {
return error;
}
/* Sanity-check the data */
{
/* Format is YYYYMMDDhhmmss00 */
int i;
int Y, M, D, h, m, s, z;
static int dims[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for( i = 0; i < 16; i++ ) {
if( (utcTime[i] < '0') || (utcTime[i] > '9') ) {
goto badtime;
}
}
Y = ((utcTime[ 0] - '0') * 1000) + ((utcTime[1] - '0') * 100) +
((utcTime[ 2] - '0') * 10) + (utcTime[ 3] - '0');
M = ((utcTime[ 4] - '0') * 10) + (utcTime[ 5] - '0');
D = ((utcTime[ 6] - '0') * 10) + (utcTime[ 7] - '0');
h = ((utcTime[ 8] - '0') * 10) + (utcTime[ 9] - '0');
m = ((utcTime[10] - '0') * 10) + (utcTime[11] - '0');
s = ((utcTime[12] - '0') * 10) + (utcTime[13] - '0');
z = ((utcTime[14] - '0') * 10) + (utcTime[15] - '0');
if( (Y < 1990) || (Y > 3000) ) goto badtime; /* Y3K problem. heh heh heh */
if( (M < 1) || (M > 12) ) goto badtime;
if( (D < 1) || (D > 31) ) goto badtime;
if( D > dims[M-1] ) goto badtime; /* per-month check */
if( (2 == M) && (((Y%4)||!(Y%100))&&(Y%400)) && (D > 28) ) goto badtime; /* leap years */
if( (h < 0) || (h > 23) ) goto badtime;
if( (m < 0) || (m > 60) ) goto badtime;
if( (s < 0) || (s > 61) ) goto badtime;
/* 60m and 60 or 61s is only allowed for leap seconds. */
if( (60 == m) || (s >= 60) ) {
if( (23 != h) || (60 != m) || (s < 60) ) goto badtime;
/* leap seconds can only happen on June 30 or Dec 31.. I think */
/* if( ((6 != M) || (30 != D)) && ((12 != M) || (31 != D)) ) goto badtime; */
}
}
return CKR_OK;
badtime:
return CKR_GENERAL_ERROR;
}
/*
* nssCKFWToken_OpenSession
*
*/
NSS_IMPLEMENT NSSCKFWSession *
nssCKFWToken_OpenSession
(
NSSCKFWToken *fwToken,
CK_BBOOL rw,
CK_VOID_PTR pApplication,
CK_NOTIFY Notify,
CK_RV *pError
)
{
NSSCKFWSession *fwSession = (NSSCKFWSession *)NULL;
NSSCKMDSession *mdSession;
#ifdef NSSDEBUG
if (!pError) {
return (NSSCKFWSession *)NULL;
}
*pError = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != *pError ) {
return (NSSCKFWSession *)NULL;
}
switch( rw ) {
case CK_TRUE:
case CK_FALSE:
break;
default:
*pError = CKR_ARGUMENTS_BAD;
return (NSSCKFWSession *)NULL;
}
#endif /* NSSDEBUG */
*pError = nssCKFWMutex_Lock(fwToken->mutex);
if( CKR_OK != *pError ) {
return (NSSCKFWSession *)NULL;
}
if( CK_TRUE == rw ) {
/* Read-write session desired */
if( CK_TRUE == nssCKFWToken_GetIsWriteProtected(fwToken) ) {
*pError = CKR_TOKEN_WRITE_PROTECTED;
goto done;
}
} else {
/* Read-only session desired */
if( CKS_RW_SO_FUNCTIONS == nssCKFWToken_GetSessionState(fwToken) ) {
*pError = CKR_SESSION_READ_WRITE_SO_EXISTS;
goto done;
}
}
/* We could compare sesion counts to any limits we know of, I guess.. */
if (!fwToken->mdToken->OpenSession) {
/*
* I'm not sure that the Module actually needs to implement
* mdSessions -- the Framework can keep track of everything
* needed, really. But I'll sort out that detail later..
*/
*pError = CKR_GENERAL_ERROR;
goto done;
}
fwSession = nssCKFWSession_Create(fwToken, rw, pApplication, Notify, pError);
if (!fwSession) {
if( CKR_OK == *pError ) {
*pError = CKR_GENERAL_ERROR;
}
goto done;
}
mdSession = fwToken->mdToken->OpenSession(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance, fwSession,
rw, pError);
if (!mdSession) {
(void)nssCKFWSession_Destroy(fwSession, CK_FALSE);
if( CKR_OK == *pError ) {
*pError = CKR_GENERAL_ERROR;
}
goto done;
}
*pError = nssCKFWSession_SetMDSession(fwSession, mdSession);
if( CKR_OK != *pError ) {
if (mdSession->Close) {
mdSession->Close(mdSession, fwSession, fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
(void)nssCKFWSession_Destroy(fwSession, CK_FALSE);
goto done;
}
*pError = nssCKFWHash_Add(fwToken->sessions, fwSession, fwSession);
if( CKR_OK != *pError ) {
(void)nssCKFWSession_Destroy(fwSession, CK_FALSE);
fwSession = (NSSCKFWSession *)NULL;
goto done;
}
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return fwSession;
}
/*
* nssCKFWToken_GetMechanismCount
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetMechanismCount
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return 0;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetMechanismCount) {
return 0;
}
return fwToken->mdToken->GetMechanismCount(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
/*
* nssCKFWToken_GetMechanismTypes
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_GetMechanismTypes
(
NSSCKFWToken *fwToken,
CK_MECHANISM_TYPE types[]
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CKR_ARGUMENTS_BAD;
}
if (!types) {
return CKR_ARGUMENTS_BAD;
}
#endif /* NSSDEBUG */
if (!fwToken->mdToken->GetMechanismTypes) {
/*
* This should only be called with a sufficiently-large
* "types" array, which can only be done if GetMechanismCount
* is implemented. If that's implemented (and returns nonzero),
* then this should be too. So return an error.
*/
return CKR_GENERAL_ERROR;
}
return fwToken->mdToken->GetMechanismTypes(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance, types);
}
/*
* nssCKFWToken_GetMechanism
*
*/
NSS_IMPLEMENT NSSCKFWMechanism *
nssCKFWToken_GetMechanism
(
NSSCKFWToken *fwToken,
CK_MECHANISM_TYPE which,
CK_RV *pError
)
{
NSSCKMDMechanism *mdMechanism;
if (!fwToken->mdMechanismHash) {
*pError = CKR_GENERAL_ERROR;
return (NSSCKFWMechanism *)NULL;
}
if (!fwToken->mdToken->GetMechanism) {
/*
* If we don't implement any GetMechanism function, then we must
* not support any.
*/
*pError = CKR_MECHANISM_INVALID;
return (NSSCKFWMechanism *)NULL;
}
/* lookup in hash table */
mdMechanism = fwToken->mdToken->GetMechanism(fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance, which, pError);
if (!mdMechanism) {
return (NSSCKFWMechanism *) NULL;
}
/* store in hash table */
return nssCKFWMechanism_Create(mdMechanism, fwToken->mdToken, fwToken,
fwToken->mdInstance, fwToken->fwInstance);
}
NSS_IMPLEMENT CK_RV
nssCKFWToken_SetSessionState
(
NSSCKFWToken *fwToken,
CK_STATE newState
)
{
CK_RV error = CKR_OK;
#ifdef NSSDEBUG
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return error;
}
switch( newState ) {
case CKS_RO_PUBLIC_SESSION:
case CKS_RO_USER_FUNCTIONS:
case CKS_RW_PUBLIC_SESSION:
case CKS_RW_USER_FUNCTIONS:
case CKS_RW_SO_FUNCTIONS:
break;
default:
return CKR_ARGUMENTS_BAD;
}
#endif /* NSSDEBUG */
error = nssCKFWMutex_Lock(fwToken->mutex);
if( CKR_OK != error ) {
return error;
}
fwToken->state = newState;
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return CKR_OK;
}
/*
* nssCKFWToken_RemoveSession
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_RemoveSession
(
NSSCKFWToken *fwToken,
NSSCKFWSession *fwSession
)
{
CK_RV error = CKR_OK;
#ifdef NSSDEBUG
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return error;
}
error = nssCKFWSession_verifyPointer(fwSession);
if( CKR_OK != error ) {
return error;
}
#endif /* NSSDEBUG */
error = nssCKFWMutex_Lock(fwToken->mutex);
if( CKR_OK != error ) {
return error;
}
if( CK_TRUE != nssCKFWHash_Exists(fwToken->sessions, fwSession) ) {
error = CKR_SESSION_HANDLE_INVALID;
goto done;
}
nssCKFWHash_Remove(fwToken->sessions, fwSession);
fwToken->sessionCount--;
if( nssCKFWSession_IsRWSession(fwSession) ) {
fwToken->rwSessionCount--;
}
if( 0 == fwToken->sessionCount ) {
fwToken->rwSessionCount = 0; /* sanity */
fwToken->state = CKS_RO_PUBLIC_SESSION; /* some default */
}
error = CKR_OK;
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return error;
}
/*
* nssCKFWToken_CloseAllSessions
*
*/
NSS_IMPLEMENT CK_RV
nssCKFWToken_CloseAllSessions
(
NSSCKFWToken *fwToken
)
{
CK_RV error = CKR_OK;
#ifdef NSSDEBUG
error = nssCKFWToken_verifyPointer(fwToken);
if( CKR_OK != error ) {
return error;
}
#endif /* NSSDEBUG */
error = nssCKFWMutex_Lock(fwToken->mutex);
if( CKR_OK != error ) {
return error;
}
nssCKFWHash_Iterate(fwToken->sessions, nss_ckfwtoken_session_iterator, (void *)NULL);
nssCKFWHash_Destroy(fwToken->sessions);
fwToken->sessions = nssCKFWHash_Create(fwToken->fwInstance, fwToken->arena, &error);
if (!fwToken->sessions) {
if( CKR_OK == error ) {
error = CKR_GENERAL_ERROR;
}
goto done;
}
fwToken->state = CKS_RO_PUBLIC_SESSION; /* some default */
fwToken->sessionCount = 0;
fwToken->rwSessionCount = 0;
error = CKR_OK;
done:
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return error;
}
/*
* nssCKFWToken_GetSessionCount
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetSessionCount
(
NSSCKFWToken *fwToken
)
{
CK_ULONG rv;
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (CK_ULONG)0;
}
#endif /* NSSDEBUG */
if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) {
return (CK_ULONG)0;
}
rv = fwToken->sessionCount;
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return rv;
}
/*
* nssCKFWToken_GetRwSessionCount
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetRwSessionCount
(
NSSCKFWToken *fwToken
)
{
CK_ULONG rv;
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (CK_ULONG)0;
}
#endif /* NSSDEBUG */
if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) {
return (CK_ULONG)0;
}
rv = fwToken->rwSessionCount;
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return rv;
}
/*
* nssCKFWToken_GetRoSessionCount
*
*/
NSS_IMPLEMENT CK_ULONG
nssCKFWToken_GetRoSessionCount
(
NSSCKFWToken *fwToken
)
{
CK_ULONG rv;
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (CK_ULONG)0;
}
#endif /* NSSDEBUG */
if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) {
return (CK_ULONG)0;
}
rv = fwToken->sessionCount - fwToken->rwSessionCount;
(void)nssCKFWMutex_Unlock(fwToken->mutex);
return rv;
}
/*
* nssCKFWToken_GetSessionObjectHash
*
*/
NSS_IMPLEMENT nssCKFWHash *
nssCKFWToken_GetSessionObjectHash
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (nssCKFWHash *)NULL;
}
#endif /* NSSDEBUG */
return fwToken->sessionObjectHash;
}
/*
* nssCKFWToken_GetMDObjectHash
*
*/
NSS_IMPLEMENT nssCKFWHash *
nssCKFWToken_GetMDObjectHash
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (nssCKFWHash *)NULL;
}
#endif /* NSSDEBUG */
return fwToken->mdObjectHash;
}
/*
* nssCKFWToken_GetObjectHandleHash
*
*/
NSS_IMPLEMENT nssCKFWHash *
nssCKFWToken_GetObjectHandleHash
(
NSSCKFWToken *fwToken
)
{
#ifdef NSSDEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (nssCKFWHash *)NULL;
}
#endif /* NSSDEBUG */
return fwToken->mdObjectHash;
}
/*
* NSSCKFWToken_GetMDToken
*
*/
NSS_IMPLEMENT NSSCKMDToken *
NSSCKFWToken_GetMDToken
(
NSSCKFWToken *fwToken
)
{
#ifdef DEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (NSSCKMDToken *)NULL;
}
#endif /* DEBUG */
return nssCKFWToken_GetMDToken(fwToken);
}
/*
* NSSCKFWToken_GetArena
*
*/
NSS_IMPLEMENT NSSArena *
NSSCKFWToken_GetArena
(
NSSCKFWToken *fwToken,
CK_RV *pError
)
{
#ifdef DEBUG
if (!pError) {
return (NSSArena *)NULL;
}
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
*pError = CKR_ARGUMENTS_BAD;
return (NSSArena *)NULL;
}
#endif /* DEBUG */
return nssCKFWToken_GetArena(fwToken, pError);
}
/*
* NSSCKFWToken_GetFWSlot
*
*/
NSS_IMPLEMENT NSSCKFWSlot *
NSSCKFWToken_GetFWSlot
(
NSSCKFWToken *fwToken
)
{
#ifdef DEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (NSSCKFWSlot *)NULL;
}
#endif /* DEBUG */
return nssCKFWToken_GetFWSlot(fwToken);
}
/*
* NSSCKFWToken_GetMDSlot
*
*/
NSS_IMPLEMENT NSSCKMDSlot *
NSSCKFWToken_GetMDSlot
(
NSSCKFWToken *fwToken
)
{
#ifdef DEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return (NSSCKMDSlot *)NULL;
}
#endif /* DEBUG */
return nssCKFWToken_GetMDSlot(fwToken);
}
/*
* NSSCKFWToken_GetSessionState
*
*/
NSS_IMPLEMENT CK_STATE
NSSCKFWSession_GetSessionState
(
NSSCKFWToken *fwToken
)
{
#ifdef DEBUG
if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) {
return CKS_RO_PUBLIC_SESSION;
}
#endif /* DEBUG */
return nssCKFWToken_GetSessionState(fwToken);
}
| 17,162 |
397 | <reponame>PaulSandoz/capsule<gh_stars>100-1000
/**
* Copyright (c) <NAME> <Centrum Wiskunde & Informatica> and Contributors.
* All rights reserved.
*
* This file is licensed under the BSD 2-Clause License, which accompanies this project
* and is available under https://opensource.org/licenses/BSD-2-Clause.
*/
package io.usethesource.capsule.core.trie;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import io.usethesource.capsule.util.EqualityComparator;
/**
* @param <C> is a (collection) representation of one or more values
*/
public interface MultimapNode<K, V, C, R extends MultimapNode<K, V, C, R>> extends Node {
boolean containsKey(K key, int keyHash, int shift, EqualityComparator<Object> cmp);
boolean containsTuple(K key, V value, int keyHash, int shift, EqualityComparator<Object> cmp);
Optional<C> findByKey(K key, int keyHash, int shift, EqualityComparator<Object> cmp);
boolean mustUnbox(C values);
V unbox(C values);
default R inserted(AtomicReference<Thread> mutator, K key, C values, int keyHash, int shift,
MultimapResult<K, V, C> details, EqualityComparator<Object> cmp) {
if (mustUnbox(values)) {
return insertedSingle(mutator, key, unbox(values), keyHash, shift, details, cmp);
} else {
return insertedMultiple(mutator, key, values, keyHash, shift, details, cmp);
}
}
R insertedSingle(AtomicReference<Thread> mutator, K key, V value, int keyHash, int shift,
MultimapResult<K, V, C> details, EqualityComparator<Object> cmp);
R insertedMultiple(AtomicReference<Thread> mutator, K key, C values, int keyHash, int shift,
MultimapResult<K, V, C> details, EqualityComparator<Object> cmp);
default R updated(AtomicReference<Thread> mutator, K key, C values, int keyHash, int shift,
MultimapResult<K, V, C> details, EqualityComparator<Object> cmp) {
if (mustUnbox(values)) {
return updatedSingle(mutator, key, unbox(values), keyHash, shift, details, cmp);
} else {
return updatedMultiple(mutator, key, values, keyHash, shift, details, cmp);
}
}
R updatedSingle(AtomicReference<Thread> mutator, K key, V value, int keyHash, int shift,
MultimapResult<K, V, C> details, EqualityComparator<Object> cmp);
R updatedMultiple(AtomicReference<Thread> mutator, K key, C values, int keyHash, int shift,
MultimapResult<K, V, C> details, EqualityComparator<Object> cmp);
/**
* Removes the {@code key} / {@code val} tuple.
*/
R removed(AtomicReference<Thread> mutator, K key, V value, int keyHash, int shift,
MultimapResult<K, V, C> details, EqualityComparator<Object> cmp);
/**
* Removes all values associated with {@code key}.
*/
R removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift,
MultimapResult<K, V, C> details, EqualityComparator<Object> cmp);
// TODO: remove from interface
@Deprecated
default int patternOfSingleton() {
throw new IllegalStateException();
}
// TODO: remove from interface
@Deprecated
default EitherSingletonOrCollection.Type typeOfSingleton() {
throw new IllegalStateException();
}
// TODO: remove from interface
@Deprecated
default R copyAndUpdateBitmaps(AtomicReference<Thread> mutator, final long bitmap) {
throw new IllegalStateException();
}
// // TODO: remove from interface
// @Deprecated
// default R copyAndUpdateBitmaps(AtomicReference<Thread> mutator, final int bitmap0,
// final int bitmap1) {
// throw new IllegalStateException();
// }
}
| 1,192 |
27,173 | import unittest
class TestProdThree(unittest.TestCase):
def test_prod_three(self):
solution = Solution()
self.assertRaises(TypeError, solution.max_prod_three, None)
self.assertRaises(ValueError, solution.max_prod_three, [1, 2])
self.assertEqual(solution.max_prod_three([5, -2, 3]), -30)
self.assertEqual(solution.max_prod_three([5, -2, 3, 1, -1, 4]), 60)
print('Success: test_prod_three')
def main():
test = TestProdThree()
test.test_prod_three()
if __name__ == '__main__':
main()
| 245 |
1,931 | import pytest
from wemake_python_styleguide.logic.complexity import annotations
@pytest.mark.parametrize(('annotation', 'complexity'), [
# simple annotations
('str', 1),
('int', 1),
('List', 1),
('List[str]', 2),
('List[int]', 2),
('Dict[str, int]', 2),
# empty values
('Literal[""]', 2),
('Tuple[()]', 2),
# invalid annotations
('"This is rainbow in the dark!"', 1),
# complex annotations
('Tuple[List[int], Optional[Dict[str, int]]]', 4),
])
def test_get_annotation_complexity(
parse_ast_tree, annotation: str, complexity: int,
) -> None:
"""Test get_annotation_complexity function."""
text = 'def f() -> {annotation}: pass\n'.format(annotation=annotation)
tree = parse_ast_tree(text)
node = tree.body[0].returns
assert annotations.get_annotation_complexity(node) == complexity
| 334 |
450 | #!/usr/bin/env python
# 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.
import sys, httplib, getopt, socket
def usage(exitarg):
print 'usage: %s [-q] host:port' % sys.argv[0]
print
print ' -q: quiet mode'
print
print 'e.g. %s localhost:8080' % sys.argv[0]
print
sys.exit(exitarg)
gpfdist = ''
quiet = 0
uri = ''
try:
(options, args) = getopt.getopt(sys.argv[1:], 'q')
except Exception, e:
usage('Error: ' + str(e))
for (switch, val) in options:
if (switch == '-q'): quiet = 1
if len(args) != 1:
usage('Error: please specify uri.')
host_port = args[0]
try:
conn = httplib.HTTPConnection(host_port)
conn.request('GET', '/')
r = conn.getresponse()
gpfdist = r.getheader('X-GPFDIST-VERSION', '')
except socket.error:
if not quiet:
print 'Error: gpfdist is not running (reason: socket error)'
print 'Exit: 1'
sys.exit(1)
if not gpfdist:
if not quiet:
print 'Error: gpfdist port is taken by some other programs'
print 'Exit: 2'
sys.exit(2)
if not quiet:
print 'Okay, gpfdist version "%s" is running on %s.' % (gpfdist, host_port)
sys.exit(0)
| 661 |
1,088 | <gh_stars>1000+
//
// CBLArray.h
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <Foundation/Foundation.h>
#import "CBLArrayFragment.h"
@class CBLBlob;
@class CBLDictionary;
@class CBLArray;
@class CBLMutableArray;
NS_ASSUME_NONNULL_BEGIN
/** CBLArray protocol defines a set of methods for reading array data. */
@protocol CBLArray <NSObject, CBLArrayFragment, NSFastEnumeration>
/** Gets a number of the items in the array. */
@property (readonly) NSUInteger count;
/*
Gets value at the given index. The object types are CBLBlob,
CBLArray, CBLDictionary, NSNumber, or NSString based on the underlying
data type; or nil if the value is nil.
@param index The index.
@return The object or nil.
*/
- (nullable id) valueAtIndex: (NSUInteger)index;
/**
Gets value at the given index as a string.
Returns nil if the value doesn't exist, or its value is not a string.
@param index The index.
@return The NSString object or nil.
*/
- (nullable NSString*) stringAtIndex: (NSUInteger)index;
/**
Gets value at the given index as a number.
Returns nil if the value doesn't exist, or its value is not a number.
@param index The index.
@return The NSNumber object or nil.
*/
- (nullable NSNumber*) numberAtIndex: (NSUInteger)index;
/**
Gets value at the given index as an integer value.
Floating point values will be rounded. The value `true` is returned as 1, `false` as 0.
Returns 0 if the value doesn't exist or does not have a numeric value.
@param index The index.
@return The integer value.
*/
- (NSInteger) integerAtIndex: (NSUInteger)index;
/**
Gets value at the given index as a long long value.
Floating point values will be rounded. The value `true` is returned as 1, `false` as 0.
Returns 0 if the value doesn't exist or does not have a numeric value.
@param index The index.
@return The long long value.
*/
- (long long) longLongAtIndex: (NSUInteger)index;
/**
Gets value at the given index as a float value.
Integers will be converted to float. The value `true` is returned as 1.0, `false` as 0.0.
Returns 0.0 if the value doesn't exist or does not have a numeric value.
@param index The index.
@return The float value.
*/
- (float) floatAtIndex: (NSUInteger)index;
/**
Gets value at the given index as a double value.
Integers will be converted to double. The value `true` is returned as 1.0, `false` as 0.0.
Returns 0.0 if the property doesn't exist or does not have a numeric value.
@param index The index.
@return The double value.
*/
- (double) doubleAtIndex: (NSUInteger)index;
/**
Gets value at the given index as a boolean.
Returns YES if the value exists, and is either `true` or a nonzero number.
@param index The index.
@return The boolean value.
*/
- (BOOL) booleanAtIndex: (NSUInteger)index;
/**
Gets value at the given index as an NSDate.
JSON does not directly support dates, so the actual property value must be a string, which is
then parsed according to the ISO-8601 date format (the default used in JSON.)
Returns nil if the value doesn't exist, is not a string, or is not parseable as a date.
NOTE: This is not a generic date parser! It only recognizes the ISO-8601 format, with or
without milliseconds.
@param index The index.
@return The NSDate object or nil.
*/
- (nullable NSDate*) dateAtIndex: (NSUInteger)index;
/**
Get value at the given index as a CBLBlob.
Returns nil if the value doesn't exist, or its value is not a CBLBlob.
@param index The index.
@return The CBLBlob object or nil.
*/
- (nullable CBLBlob*) blobAtIndex: (NSUInteger)index;
/**
Gets value as a CBLArray, which is a mapping object of an array value.
Returns nil if the value doesn't exists, or its value is not an array.
@param index The index.
@return The CBLArray object or nil.
*/
- (nullable CBLArray*) arrayAtIndex: (NSUInteger)index;
/**
Get value at the given index as a CBLDictionary, which is a mapping object of
a dictionary value.
Returns nil if the value doesn't exists, or its value is not a dictionary.
@param index The index.
@return The CBLDictionary object or nil.
*/
- (nullable CBLDictionary*) dictionaryAtIndex: (NSUInteger)index;
#pragma mark - Data
/**
Gets content of the current object as an NSArray. The value types of the values
contained in the returned NSArray object are CBLBlob, NSArray, NSDictionary,
NSNumber, NSNull, and NSString.
@return The NSArray object representing the content of the current object.
*/
- (NSArray*) toArray;
/** Return array data as JSON String */
- (NSString*) toJSON;
@end
/** CBLArray provides read access to array data. */
@interface CBLArray : NSObject <CBLArray, NSCopying, NSMutableCopying>
- (instancetype) init NS_UNAVAILABLE;
- (CBLMutableArray*) toMutable;
@end
NS_ASSUME_NONNULL_END
| 1,613 |
416 | /*
* Copyright (c) 2010 Apple Inc. All Rights Reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef _CC_PBKDF_H_
#define _CC_PBKDF_H_
#include <string.h>
#include <limits.h>
#include <stdlib.h>
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#ifdef __cplusplus
extern "C" {
#endif
enum {
kCCPBKDF2 = 2,
};
typedef uint32_t CCPBKDFAlgorithm;
enum {
kCCPRFHmacAlgSHA1 = 1,
kCCPRFHmacAlgSHA224 = 2,
kCCPRFHmacAlgSHA256 = 3,
kCCPRFHmacAlgSHA384 = 4,
kCCPRFHmacAlgSHA512 = 5,
};
typedef uint32_t CCPseudoRandomAlgorithm;
/*
@function CCKeyDerivationPBKDF
@abstract Derive a key from a text password/passphrase
@param algorithm Currently only PBKDF2 is available via kCCPBKDF2
@param password The text password used as input to the derivation
function. The actual octets present in this string
will be used with no additional processing. It's
extremely important that the same encoding and
normalization be used each time this routine is
called if the same key is expected to be derived.
@param passwordLen The length of the text password in bytes.
@param salt The salt byte values used as input to the derivation
function. The pointer can be NULL, only when saltLen is zero.
@param saltLen The length of the salt in bytes. It can be zero.
@param prf The Pseudo Random Algorithm to use for the derivation
iterations.
@param rounds The number of rounds of the Pseudo Random Algorithm
to use. It cannot be zero.
@param derivedKey The resulting derived key produced by the function.
The space for this must be provided by the caller.
@param derivedKeyLen The expected length of the derived key in bytes. It cannot be zero.
@discussion The following values are used to designate the PRF:
* kCCPRFHmacAlgSHA1
* kCCPRFHmacAlgSHA224
* kCCPRFHmacAlgSHA256
* kCCPRFHmacAlgSHA384
* kCCPRFHmacAlgSHA512
@result kCCParamError can result from bad values for the password, salt,
and unwrapped key pointers as well as a bad value for the prf
function.
*/
int
CCKeyDerivationPBKDF( CCPBKDFAlgorithm algorithm, const char *password, size_t passwordLen,
const uint8_t *salt, size_t saltLen,
CCPseudoRandomAlgorithm prf, unsigned rounds,
uint8_t *derivedKey, size_t derivedKeyLen)
API_AVAILABLE(macos(10.7), ios(5.0));
/*
* All lengths are in bytes - not bits.
*/
/*
@function CCCalibratePBKDF
@abstract Determine the number of PRF rounds to use for a specific delay on
the current platform.
@param algorithm Currently only PBKDF2 is available via kCCPBKDF2
@param passwordLen The length of the text password in bytes.
@param saltLen The length of the salt in bytes. saltlen must be smaller than 133.
@param prf The Pseudo Random Algorithm to use for the derivation
iterations.
@param derivedKeyLen The expected length of the derived key in bytes.
@param msec The targetted duration we want to achieve for a key
derivation with these parameters.
@result the number of iterations to use for the desired processing time.
Returns a minimum of 10000 iterations (safety net, not a particularly recommended value)
The number of iterations is a trade-off of usability and security. If there is an error
the function returns (unsigned)(-1). The minimum return value is set to 10000.
*/
unsigned
CCCalibratePBKDF(CCPBKDFAlgorithm algorithm, size_t passwordLen, size_t saltLen,
CCPseudoRandomAlgorithm prf, size_t derivedKeyLen, uint32_t msec)
API_AVAILABLE(macos(10.7), ios(5.0));
#ifdef __cplusplus
}
#endif
#endif /* _CC_PBKDF_H_ */
| 1,866 |
14,668 | <filename>components/gcm_driver/gcm_desktop_utils.h
// Copyright 2014 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_GCM_DRIVER_GCM_DESKTOP_UTILS_H_
#define COMPONENTS_GCM_DRIVER_GCM_DESKTOP_UTILS_H_
#include <memory>
#include "base/memory/ref_counted.h"
#include "base/task/sequenced_task_runner.h"
#include "components/version_info/version_info.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "services/network/public/mojom/proxy_resolving_socket.mojom-forward.h"
class PrefService;
namespace base {
class FilePath;
}
namespace network {
class NetworkConnectionTracker;
class SharedURLLoaderFactory;
}
namespace gcm {
class GCMDriver;
class GCMClientFactory;
std::unique_ptr<GCMDriver> CreateGCMDriverDesktop(
std::unique_ptr<GCMClientFactory> gcm_client_factory,
PrefService* prefs,
const base::FilePath& store_path,
bool remove_account_mappings_with_email_key,
base::RepeatingCallback<void(
mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>)>
get_socket_factory_callback,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
network::NetworkConnectionTracker* network_connection_tracker,
version_info::Channel channel,
const std::string& product_category_for_subtypes,
const scoped_refptr<base::SequencedTaskRunner>& ui_task_runner,
const scoped_refptr<base::SequencedTaskRunner>& io_task_runner,
const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner);
} // namespace gcm
#endif // COMPONENTS_GCM_DRIVER_GCM_DESKTOP_UTILS_H_
| 610 |
800 | <filename>app/src/main/java/com/sdwfqin/quickseed/ui/example/sortlist/SortListActivity.java
package com.sdwfqin.quickseed.ui.example.sortlist;
import android.view.View;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.LogUtils;
import com.sdwfqin.quicklib.base.BaseActivity;
import com.sdwfqin.quicklib.utils.rx.RxSchedulersUtils;
import com.sdwfqin.quickseed.R;
import com.sdwfqin.quickseed.databinding.ActivitySortListBinding;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
/**
* 仿京东分类列表
* <p>
*
* @author 张钦
* @date 2020/5/27
*/
public class SortListActivity extends BaseActivity<ActivitySortListBinding> {
private SortAdapter mSortAdapter;
private LinearLayoutManager mLayoutManager;
@Override
protected ActivitySortListBinding getViewBinding() {
return ActivitySortListBinding.inflate(getLayoutInflater());
}
@Override
protected void initEventAndData() {
mTopBar.setTitle("仿京东分类列表");
mTopBar.addLeftBackImageButton().setOnClickListener(v -> finish());
initSortList();
}
private void initSortList() {
mSortAdapter = new SortAdapter(getMockData());
mSortAdapter.setCheckedPosition(0);
initSortDetail((ArrayList<SortGroupBean>) mSortAdapter.getItem(0).getSortGroupBeans(), 0);
mLayoutManager = new LinearLayoutManager(mContext);
mBinding.rvSort.setLayoutManager(mLayoutManager);
mBinding.rvSort.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));
mBinding.rvSort.setAdapter(mSortAdapter);
mSortAdapter.setOnItemClickListener((adapter, view, position) -> {
mSortAdapter.setCheckedPosition(position);
});
mSortAdapter.setOnCallbackListener(position -> {
if (position >= mSortAdapter.getData().size()) {
return;
}
initSortDetail((ArrayList<SortGroupBean>) mSortAdapter.getItem(position).getSortGroupBeans(), position);
try {
View childAt = mBinding.rvSort.getChildAt(position - mLayoutManager.findFirstVisibleItemPosition());
int y = (childAt.getTop() - mBinding.rvSort.getHeight() / 2);
mBinding.rvSort.smoothScrollBy(0, y);
} catch (Exception e) {
e.printStackTrace();
}
});
}
private void initSortDetail(ArrayList<SortGroupBean> sortGroupBean, int positions) {
if (sortGroupBean == null) {
return;
}
// 在子线程加载Fragment
addSubscribe(Observable.create((ObservableOnSubscribe<Fragment>) emitter -> {
int witchType = SortListDetailFragment.ALL;
if (mSortAdapter.getData().size() == 1) {
witchType = SortListDetailFragment.NONE;
} else if (positions == 0) {
witchType = SortListDetailFragment.BACK;
} else if (mSortAdapter.getData().size() - 1 == positions) {
witchType = SortListDetailFragment.NEXT;
}
SortListDetailFragment sortListDetailFragment = SortListDetailFragment.newInstance(sortGroupBean, witchType);
emitter.onNext(sortListDetailFragment);
emitter.onComplete();
}).compose(RxSchedulersUtils.rxObservableSchedulerHelper())
.subscribe(fragment -> FragmentUtils.replace(getSupportFragmentManager(), fragment, R.id.fl_sort_detail),
LogUtils::e));
}
public void backSort() {
int checkedPosition = mSortAdapter.getCheckedPosition();
if (checkedPosition <= 0) {
return;
}
mSortAdapter.setCheckedPosition(--checkedPosition);
}
public void nextSort() {
int checkedPosition = mSortAdapter.getCheckedPosition();
if (checkedPosition >= mSortAdapter.getData().size() - 1) {
return;
}
mSortAdapter.setCheckedPosition(++checkedPosition);
}
private List<SortBean> getMockData() {
List<SortBean> beans = new ArrayList<>();
for (int i = 0; i < 15; i++) {
SortBean sortBean = new SortBean();
sortBean.setId(i);
sortBean.setTitle("分类:" + i);
List<SortGroupBean> groupBeans = new ArrayList<>();
for (int j = 0; j < 5; j++) {
SortGroupBean sortGroupBean = new SortGroupBean();
sortGroupBean.setId(i + j);
sortGroupBean.setTitle("分组:" + i + j);
List<SortDetailBean> detailBeans = new ArrayList<>();
for (int k = 0; k < 9; k++) {
SortDetailBean sortDetailBean = new SortDetailBean();
sortDetailBean.setId(i + j + k);
sortDetailBean.setImgUrl("test");
sortDetailBean.setTitle("数据:" + i + j + k);
detailBeans.add(sortDetailBean);
}
sortGroupBean.setSortDetailBeans(detailBeans);
groupBeans.add(sortGroupBean);
}
sortBean.setSortGroupBeans(groupBeans);
beans.add(sortBean);
}
return beans;
}
}
| 2,527 |
375 | <reponame>puraner/RED
/*
* Copyright 2015 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.rf.ide.core.testdata.text.read.separators;
import java.util.regex.Pattern;
import org.rf.ide.core.testdata.model.FileFormat;
import com.google.common.annotations.VisibleForTesting;
public class TokenSeparatorBuilder {
private static final Pattern PIPE_SEPARATOR_BEGIN = Pattern.compile("(^[|]\\s+)|(^[|]$)");
private final FileFormat format;
public TokenSeparatorBuilder(final FileFormat fileFormat) {
this.format = fileFormat;
}
public ALineSeparator createSeparator(final int lineNumber, final String line) {
if (format == FileFormat.TXT_OR_ROBOT) {
return isPipeSeparated(line) ? new PipeSeparator(lineNumber, line)
: new WhitespaceSeparator(lineNumber, line);
} else if (format == FileFormat.TSV) {
return new StrictTsvTabulatorSeparator(lineNumber, line);
} else {
return null;
}
}
@VisibleForTesting
boolean isPipeSeparated(final String line) {
return format == FileFormat.TXT_OR_ROBOT && PIPE_SEPARATOR_BEGIN.matcher(line).find();
}
}
| 494 |
1,016 | <filename>core/schema-discovery/schema-discovery-rdbms/src/main/java/com/thinkbiganalytics/schema/DefaultJdbcSchema.java<gh_stars>1000+
package com.thinkbiganalytics.schema;
/*-
* #%L
* kylo-schema-discovery-rdbms
* %%
* Copyright (C) 2017 - 2018 ThinkBig Analytics, a Teradata Company
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.thinkbiganalytics.discovery.schema.JdbcSchema;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* A table schema.
*/
public class DefaultJdbcSchema implements JdbcSchema {
/**
* Catalog name
*/
@Nullable
private String catalog;
/**
* Schema name
*/
@Nonnull
private final String schema;
/**
* Returns a function that converts the current result set item to a {@code DefaultJdbcSchema}.
*/
@Nonnull
public static <T extends JdbcSchema> JdbcFunction<ResultSet, T> fromResultSet() {
return new JdbcFunction<ResultSet, T>() {
@Override
@SuppressWarnings("unchecked")
public T apply(final ResultSet resultSet) throws SQLException {
return (T) DefaultJdbcSchema.fromResultSet(resultSet);
}
};
}
/**
* Creates a {@code DefaultJdbcSchema} from the current result set.
*/
@Nonnull
public static DefaultJdbcSchema fromResultSet(@Nonnull final ResultSet resultSet) throws SQLException {
final DefaultJdbcSchema schema = new DefaultJdbcSchema(resultSet.getString(JdbcConstants.TABLE_SCHEM));
schema.setCatalog(resultSet.getString(JdbcConstants.TABLE_CATALOG));
return schema;
}
/**
* Constructs a {@code DefaultJdbcSchema} with the specified schema name.
*/
public DefaultJdbcSchema(@Nonnull final String schema) {
this.schema = schema;
}
@Nullable
@Override
public String getCatalog() {
return catalog;
}
/**
* Sets the catalog name.
*/
public void setCatalog(@Nullable final String catalog) {
this.catalog = catalog;
}
@Nonnull
@Override
public String getSchema() {
return schema;
}
}
| 1,032 |
1,692 | /*
* Copyright 2018-2021 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.kafka.retrytopic;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.retry.backoff.BackOffPolicy;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.backoff.NoBackOffPolicy;
/**
* @author <NAME>
* @since 2.7
*/
class BackOffValuesGeneratorTests {
@Test
void shouldGenerateWithDefaultValues() {
// Default MAX_ATTEMPTS = 3
// Default Policy = FixedBackoffPolicy
// setup
BackOffValuesGenerator backOffValuesGenerator = new BackOffValuesGenerator(-1, null);
// when
List<Long> backOffValues = backOffValuesGenerator.generateValues();
// then
List<Long> expectedBackOffs = Arrays.asList(1000L, 1000L);
assertThat(backOffValues).isEqualTo(expectedBackOffs);
}
@Test
void shouldGenerateExponentialValues() {
// setup
ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setMultiplier(2);
backOffPolicy.setInitialInterval(1000);
BackOffValuesGenerator backOffValuesGenerator = new BackOffValuesGenerator(4, backOffPolicy);
// when
List<Long> backOffValues = backOffValuesGenerator.generateValues();
// then
List<Long> expectedBackoffs = Arrays.asList(1000L, 2000L, 4000L);
assertThat(backOffValues).isEqualTo(expectedBackoffs);
}
@Test
void shouldGenerateWithNoBackOff() {
// setup
BackOffPolicy backOffPolicy = new NoBackOffPolicy();
BackOffValuesGenerator backOffValuesGenerator = new BackOffValuesGenerator(4, backOffPolicy);
// when
List<Long> backOffValues = backOffValuesGenerator.generateValues();
// then
List<Long> expectedBackoffs = Arrays.asList(0L, 0L, 0L);
assertThat(backOffValues).isEqualTo(expectedBackoffs);
}
}
| 776 |
334 | <reponame>Cleython-Enginner/Desafios-java
// Uniformes de final de ano
/* O professor Girafales organizou a confecção de um uniforme para as turmas
da escola para comemorar o final do ano. Após algumas conversas, ficou
decidido com os alunos que eles poderiam escolher a cor do uniforme entre
branco ou vermelho. Assim sendo, Girafales precisa de sua ajuda para organizar
as listas de quem quer o uniforme em cada uma das turmas, relacionando estas
camisetas pela cor, tamanho (P, M ou G) e por último pelo nome.
- Entrada
Cada caso de teste inicia com um valor N, (1 ≤ N ≤ 60) inteiro e positivo, que
indica a quantidade de uniformes a serem feitas para aquela turma. As próximas
N*2 linhas contêm informações de cada um dos uniformes (serão duas linhas de
informação para cada uniforme). A primeira linha irá conter o nome do
estudante e a segunda linha irá conter a cor do uniforme ("branco" ou
"vermelho") seguido por um espaço e pelo tamanho do uniforme "P" "M" ou "G".
A entrada termina quando o valor de N for igual a zero (0) e está valor não
deverá ser processado.
- Saída
Para cada caso de entrada deverão ser impressas as informações ordenadas pela
cor em ordem ascendente, seguido pelos tamanhos em ordem descendente e por
último por ordem ascendente de nome, conforme o exemplo abaixo.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
public class UniformesFinalAno {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int linhas = Integer.parseInt(st.nextToken());
List<Uniforme> uniformes = new ArrayList<>();
for (int i = 0; i <= linhas; i++) {
var next = br.readLine();
if(next.equals("0")) {
break;
}
Uniforme uniforme = new Uniforme();
uniforme.setNomeEstudante(next);
var camiseta = br.readLine().split(" ");
uniforme.setCorUniforme(camiseta[0]);
uniforme.setTamUniforme(camiseta[1]);
uniformes.add(uniforme);
}
Comparator<Uniforme> comparator = Comparator
.comparing(Uniforme::getCorUniforme).reversed()
.thenComparing(Uniforme::getTamUniforme).reversed()
.thenComparing(Uniforme::getNomeEstudante);
uniformes.stream().sorted(comparator).forEach(System.out::println);
}
public static class Uniforme {
private String nomeEstudante;
private String corUniforme;
private String tamUniforme;
@Override
public String toString() {
return corUniforme + " " + tamUniforme + " "+ nomeEstudante;
}
public String getNomeEstudante() {
return nomeEstudante;
}
public void setNomeEstudante(String nomeEstudante) {
this.nomeEstudante = nomeEstudante;
}
public String getCorUniforme() {
return corUniforme;
}
public void setCorUniforme(String corUniforme) {
this.corUniforme = corUniforme;
}
public String getTamUniforme() {
return tamUniforme;
}
public void setTamUniforme(String tamUniforme) {
this.tamUniforme = tamUniforme;
}
}
} | 1,608 |
313 | #!/usr/bin/python
#-*- coding: utf-8 -*-
#Developer by Bafomet
import random
import string
import argparse
import os
import subprocess
# set color
WHSL = '\033[1;32m'
ENDL = '\033[0m'
REDL = '\033[0;31m'
GNSL = '\033[1;34m'
Filename="hook.js"
os.system('clear')
def ngrok():
return ("""
{1}__________________________________________________________________________________________________________________________________{2}
{1}Инструкции по запуску ngrok. {2}
{2}Тебе нужны 2 ссылки, которые перенаправляются на LocalHost:80 and LocalHost:3000 {2}
{1}__________________________________________________________________________________________________________________________________{2}
{1}Шаг первый :{2} Добавить эти строки в ngrok.yml [Location .ngrok2/ngrok.yml ] {2}
{0}
tunnels:
first-app:
addr: 80
proto: http
second-app:
addr: 3000
proto: http {0}
{1}Шаг второй.{1}{2} Запусти ngrok. ./ngrok start --all, без рута{2}
{1}__________________________________________________________________________________________________________________________________{2}
{1}Шаг третий.{1}{2} Beef listens on Port 3000 , поэтому эту ссылку следует перенаправить на LocalHost:3000{2}
{1}__________________________________________________________________________________________________________________________________{2}
{2}Шаг четвертый : Ты увидишь 2 разные ссылки, перенаправленные на{2}
{0}
Localhost:80 [ Ссылка для отправки жертве ]
Localhost:3000 [ Ваша ссылка будет подключаться к.. ] {0}
""").format(GNSL, REDL, WHSL)
def color(string, color=None):
attr = []
attr.append('1')
if color:
if color.lower() == "red":
attr.append('31')
elif color.lower() == "green":
attr.append('32')
elif color.lower() == "blue":
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
if string.strip().startswith("[!]"):
attr.append('31')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[+]"):
attr.append('32')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[?]"):
attr.append('33')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[*]"):
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
return string
def string_replace(filename, old_string, new_string):
# Safely read the input filename using 'with'
with open(filename) as f:
s = f.read()
if old_string not in s:
print '"{old_string}" not found in {filename}.'.format(**locals())
return
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
#print 'Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals())
s = s.replace(old_string, new_string)
f.write(s)
print color('[ ✔ ] File Changed...','green')
if __name__ == '__main__':
print("")
os.system("python3 dll.py")
print color(REDL + " [ + ] " + WHSL+ " Вводишь 1 он запустить beff с ngrok, введешь 0, запустит в локальной сети. \n")
ng_check=raw_input(color(REDL + " [ + ] " + WHSL+ " Введите варианты загрузки : "))
print ng_check
if (ng_check):
print color(ngrok(),"green")
con=raw_input(color(REDL + " [ + ] " + WHSL+ " Нажми Enter ..."))
print color(" Требуется проверка статуса услуг ","blue")
os.system("service apache2 start")
os.system("sudo beef-xss")
os.system("clear")
subprocess.call("sudo python3 dll.py", shell=True)
send_to=raw_input(color((' [ + ] Введите адрес ссылки [вы отправляете жертве]: ')))
print("")
send_to=send_to.rstrip()
print color((" [ + ] Send_To Link : "+ send_to))
print("")
connect_to=raw_input(color((' [ + ] Введите адрес ссылки [Ваша ссылка будет подключаться к.]: ')))
print("")
connect_to=connect_to.rstrip()
print color((" [ + ] Connect_To Link : "+ connect_to))
print("")
print color(' [ ✔ ] Проверка directories...','green')
print("")
if not os.path.isdir("./temp"):
os.makedirs("./temp")
print (color(" [ + ] Creating [./temp] directory for resulting code files","green"))
else:
os.system("rm -rf temp/*")
print color("Clean Succesful","green")
connect_to_full='http://'+connect_to+":80/hook.js"
connect_to_panel='http://'+connect_to+"/ui/panel"
send_to_full='http://'+send_to+'/beef.html'
#print connect_to_full
os.system("cp base.js ./temp/hook.js")
string_replace("./temp/hook.js","SKS_1",connect_to_full)
string_replace("./temp/hook.js","SKS_2",connect_to)
os.system("cp beef.html ./temp/beef.html")
string_replace("./temp/beef.html","SKS_3",send_to)
os.system("cp ./temp/* /var/www/html/")
os.system("chmod a+rw /var/www/html/hook.js")
print color("\n==================================== RESULT ====================================\n","blue")
print color(" [ + ] Доступ к панели управления BeeF с помощью : {}".format(connect_to_panel),"green")
print("")
print color("\t Username = beef\n\t Password = <PASSWORD>","blue")
print color(" [ + ] Отправь жертве ссылку. : "+send_to_full,"green")
| 2,759 |
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 MEDIA_BASE_MEDIA_LOG_TYPE_ENFORCEMENT_H_
#define MEDIA_BASE_MEDIA_LOG_TYPE_ENFORCEMENT_H_
#include "media/base/media_serializers.h"
namespace media {
namespace internal {
enum class UnmatchableType {};
} // namespace internal
// Forward declare the enums.
enum class MediaLogProperty;
enum class MediaLogEvent;
// Allow only specific types for an individual property.
template <MediaLogProperty PROP, typename T>
struct MediaLogPropertyTypeSupport {};
// Allow only specific types for an individual event.
// However unlike Property, T is not required, so we default it to some
// unmatchable type that will never be passed as an argument accidentally.
template <MediaLogEvent EVENT, typename T = internal::UnmatchableType>
struct MediaLogEventTypeSupport {};
// Lets us define the supported type in a single line in media_log_properties.h.
#define MEDIA_LOG_PROPERTY_SUPPORTS_TYPE(PROPERTY, TYPE) \
template <> \
struct MediaLogPropertyTypeSupport<MediaLogProperty::PROPERTY, TYPE> { \
static base::Value Convert(const TYPE& type) { \
return MediaSerialize<TYPE>(type); \
} \
}
#define MEDIA_LOG_EVENT_NAMED_DATA(EVENT, TYPE, DISPLAY) \
template <> \
struct MediaLogEventTypeSupport<MediaLogEvent::EVENT, TYPE> { \
static void AddExtraData(base::Value* params, const TYPE& t) { \
DCHECK(params); \
params->SetKey(DISPLAY, MediaSerialize<TYPE>(t)); \
} \
static std::string TypeName() { return #EVENT; } \
}
#define MEDIA_LOG_EVENT_NAMED_DATA_OP(EVENT, TYPE, DISPLAY, OP) \
template <> \
struct MediaLogEventTypeSupport<MediaLogEvent::EVENT, TYPE> { \
static void AddExtraData(base::Value* params, const TYPE& t) { \
DCHECK(params); \
params->SetKey(DISPLAY, MediaSerialize<TYPE>(OP(t))); \
} \
static std::string TypeName() { return #EVENT; } \
}
// Specifically do not create the Convert or DisplayName methods
#define MEDIA_LOG_EVENT_TYPELESS(EVENT) \
template <> \
struct MediaLogEventTypeSupport<MediaLogEvent::EVENT> { \
static std::string TypeName() { return #EVENT; } \
static void AddExtraData(base::Value* params) {} \
}
} // namespace media
#endif // MEDIA_BASE_MEDIA_LOG_TYPE_ENFORCEMENT_H_
| 1,445 |
805 | <gh_stars>100-1000
import unittest
import os
from tests.setup_scripts import ring_road_exp_setup, traffic_light_grid_mxn_exp_setup
from flow.core.params import VehicleParams
from flow.core.params import NetParams
from flow.core.params import SumoCarFollowingParams
from flow.core.params import TrafficLightParams
from flow.core.experiment import Experiment
from flow.controllers.routing_controllers import GridRouter
from flow.controllers.car_following_models import IDMController
os.environ["TEST_FLAG"] = "True"
class TestUpdateGetState(unittest.TestCase):
"""
Tests the update and get_state functions are working properly.
"""
def tearDown(self):
# terminate the traci instance
self.env.terminate()
# free data used by the class
self.env = None
def test_single_lane(self):
# add a traffic light to the top node
traffic_lights = TrafficLightParams()
traffic_lights.add("top")
# create a ring road with one lane
additional_net_params = {
"length": 230,
"lanes": 1,
"speed_limit": 30,
"resolution": 40
}
net_params = NetParams(additional_params=additional_net_params)
# create the environment and network classes for a ring road
self.env, _, _ = ring_road_exp_setup(
net_params=net_params, traffic_lights=traffic_lights)
self.env.reset()
self.env.step([])
state = self.env.k.traffic_light.get_state("top")
self.assertEqual(state, "G")
def test_multi_lane(self):
# add a traffic light to the top node
traffic_lights = TrafficLightParams()
traffic_lights.add("top")
# create a ring road with two lanes
additional_net_params = {
"length": 230,
"lanes": 2,
"speed_limit": 30,
"resolution": 40
}
net_params = NetParams(additional_params=additional_net_params)
# create the environment and network classes for a ring road
self.env, _, _ = ring_road_exp_setup(
net_params=net_params, traffic_lights=traffic_lights)
self.env.reset()
self.env.step([])
state = self.env.k.traffic_light.get_state("top")
self.assertEqual(state, "GG")
class TestSetState(unittest.TestCase):
"""
Tests the set_state function
"""
def setUp(self):
# add a traffic light to the top node
traffic_lights = TrafficLightParams()
traffic_lights.add("top")
# create a ring road with two lanes
additional_net_params = {
"length": 230,
"lanes": 2,
"speed_limit": 30,
"resolution": 40
}
net_params = NetParams(additional_params=additional_net_params)
# create the environment and network classes for a ring road
self.env, _, _ = ring_road_exp_setup(
net_params=net_params, traffic_lights=traffic_lights)
def tearDown(self):
# terminate the traci instance
self.env.terminate()
# free data used by the class
self.env = None
def test_all_lanes(self):
# reset the environment
self.env.reset()
# set all states to something
self.env.k.traffic_light.set_state(node_id="top", state="rY")
# run a new step
self.env.step([])
# check the new values
state = self.env.k.traffic_light.get_state("top")
self.assertEqual(state, "rY")
def test_single_lane(self):
# reset the environment
self.env.reset()
# set all state of lane 1 to something
self.env.k.traffic_light.set_state(
node_id="top", state="R", link_index=1)
# run a new step
self.env.step([])
# check the new values
state = self.env.k.traffic_light.get_state("top")
self.assertEqual(state[1], "R")
class TestPOEnv(unittest.TestCase):
"""
Tests the set_state function
"""
def setUp(self):
vehicles = VehicleParams()
vehicles.add(
veh_id="idm",
acceleration_controller=(IDMController, {}),
routing_controller=(GridRouter, {}),
car_following_params=SumoCarFollowingParams(
min_gap=2.5, tau=1.1),
num_vehicles=16)
self.env, _, _ = traffic_light_grid_mxn_exp_setup(
row_num=1, col_num=3, vehicles=vehicles)
def tearDown(self):
# terminate the traci instance
self.env.terminate()
# free data used by the class
self.env = None
@staticmethod
def compare_ordering(ordering):
# take in a list like [[bot0_0, right0_0, top0_1, left1_0], [bot....]
# print(ordering)
for x in ordering:
# print(x)
if not (x[0].startswith("bot") and x[1].startswith("right") and
x[2].startswith("top") and x[3].startswith("left")):
return False
return True
def test_node_mapping(self):
# reset the environment
self.env.reset()
node_mapping = self.env.network.node_mapping
nodes = [elem[0] for elem in node_mapping]
ordering = [elem[1] for elem in node_mapping]
self.assertEqual(nodes, sorted(nodes))
self.assertTrue(self.compare_ordering(ordering))
def test_k_closest(self):
self.env.step(None)
node_mapping = self.env.network.node_mapping
# get the node mapping for node center0
c0_edges = node_mapping[0][1]
k_closest = self.env.get_closest_to_intersection(c0_edges, 3)
# check bot, right, top, left in that order
self.assertEqual(
self.env.get_closest_to_intersection(c0_edges[0], 3),
k_closest[0:2])
self.assertEqual(
self.env.get_closest_to_intersection(c0_edges[1], 3),
k_closest[2:4])
self.assertEqual(
len(self.env.get_closest_to_intersection(c0_edges[2], 3)), 0)
self.assertEqual(
self.env.get_closest_to_intersection(c0_edges[3], 3),
k_closest[4:6])
for veh_id in k_closest:
self.assertTrue(self.env.k.vehicle.get_edge(veh_id) in c0_edges)
with self.assertRaises(ValueError):
self.env.get_closest_to_intersection(c0_edges, -1)
class TestItRuns(unittest.TestCase):
"""
Tests the set_state function
"""
def setUp(self):
vehicles = VehicleParams()
vehicles.add(
veh_id="idm",
acceleration_controller=(IDMController, {}),
routing_controller=(GridRouter, {}),
car_following_params=SumoCarFollowingParams(
min_gap=2.5, tau=1.1),
num_vehicles=16)
_, _, flow_params = traffic_light_grid_mxn_exp_setup(
row_num=1, col_num=3, vehicles=vehicles)
flow_params['env'].horizon = 50
self.exp = Experiment(flow_params)
def tearDown(self):
# free data used by the class
self.exp = None
def test_it_runs(self):
self.exp.run(5)
class TestIndividualLights(unittest.TestCase):
"""
Tests the functionality of the the TrafficLightParams class in allowing
for customization of specific nodes
"""
def setUp(self):
tl_logic = TrafficLightParams(baseline=False)
phases = [{
"duration": "31",
"minDur": "8",
"maxDur": "45",
"state": "GrGr"
}, {
"duration": "6",
"minDur": "3",
"maxDur": "6",
"state": "yryr"
}, {
"duration": "31",
"minDur": "8",
"maxDur": "45",
"state": "rGrG"
}, {
"duration": "6",
"minDur": "3",
"maxDur": "6",
"state": "ryry"
}]
tl_logic.add("center0", phases=phases, programID=1)
tl_logic.add("center1", phases=phases, programID=1, offset=1)
tl_logic.add(
"center2", tls_type="actuated", phases=phases, programID=1)
tl_logic.add(
"center3",
tls_type="actuated",
phases=phases,
programID=1,
maxGap=3.0,
detectorGap=0.8,
showDetectors=True,
file="testindividuallights.xml",
freq=100)
_, _, flow_params = traffic_light_grid_mxn_exp_setup(
row_num=1, col_num=4, tl_logic=tl_logic)
flow_params['env'].horizon = 50
self.exp = Experiment(flow_params)
def tearDown(self):
# free data used by the class
self.exp = None
def test_it_runs(self):
self.exp.run(5)
class TestCustomization(unittest.TestCase):
def setUp(self):
# add a traffic light to the top node
traffic_lights = TrafficLightParams()
# Phase durations in seconds
self.green = 4
self.yellow = 1
self.red = 4
phases = [{
"duration": repr(self.green),
"state": "G"
}, {
"duration": repr(self.yellow),
"state": "y"
}, {
"duration": repr(self.red),
"state": "r"
}]
traffic_lights.add("top", phases=phases)
# create a ring road with two lanes
additional_net_params = {
"length": 230,
"lanes": 1,
"speed_limit": 30,
"resolution": 40
}
net_params = NetParams(additional_params=additional_net_params)
# create the environment and network classes for a ring road
self.env, _, _ = ring_road_exp_setup(
net_params=net_params, traffic_lights=traffic_lights)
def tearDown(self):
# terminate the traci instance
self.env.terminate()
# free data used by the class
self.env = None
def test_static_phases(self):
# Reset the environment
self.env.reset()
# Calculate multiplier, because phases are in seconds
sim_multiplier = int(1 / self.env.sim_params.sim_step)
# Check that the phases occur for the correct amount of time
for i in range(self.green * sim_multiplier - 2):
# This is because env.reset() takes 1 step
self.assertEqual(self.env.k.traffic_light.get_state("top"), "G")
self.env.step([])
for i in range(self.yellow * sim_multiplier):
self.assertEqual(self.env.k.traffic_light.get_state("top"), "y")
self.env.step([])
for i in range(self.red * sim_multiplier):
self.assertEqual(self.env.k.traffic_light.get_state("top"), "r")
self.env.step([])
for i in range(3):
for _ in range(self.green * sim_multiplier):
self.assertEqual(
self.env.k.traffic_light.get_state("top"), "G")
self.env.step([])
for _ in range(self.yellow * sim_multiplier):
self.assertEqual(
self.env.k.traffic_light.get_state("top"), "y")
self.env.step([])
for _ in range(self.red * sim_multiplier):
self.assertEqual(
self.env.k.traffic_light.get_state("top"), "r")
self.env.step([])
if __name__ == '__main__':
unittest.main()
| 5,520 |
1,351 | <reponame>lailiaomm/SmoothRefreshLayout<gh_stars>1000+
package me.dkzwm.widget.srl.sample.ui;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.sample.R;
import me.dkzwm.widget.srl.sample.adapter.RecyclerViewAdapter;
import me.dkzwm.widget.srl.sample.utils.DataUtil;
import me.dkzwm.widget.srl.util.PixelUtl;
/**
* Created by dkzwm on 2017/6/1.
*
* @author dkzwm
*/
public class TestNestedActivity extends AppCompatActivity {
private MaterialSmoothRefreshLayout mRefreshLayout;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private Handler mHandler = new Handler();
private int mCount = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_nested);
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.arrow_back_white_72x72);
toolbar.setNavigationOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
mRecyclerView = findViewById(R.id.recyclerView_test_nested);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mAdapter = new RecyclerViewAdapter(this, getLayoutInflater());
mRecyclerView.setAdapter(mAdapter);
mRefreshLayout = findViewById(R.id.smoothRefreshLayout_test_nested);
mRefreshLayout.setDisableLoadMore(false);
mRefreshLayout.materialStyle();
mRefreshLayout.setOnRefreshListener(
new SmoothRefreshLayout.OnRefreshListener() {
@Override
public void onRefreshing() {
mHandler.postDelayed(
new Runnable() {
@Override
public void run() {
List<String> list = DataUtil.createList(mCount, 20);
mCount = list.size();
mAdapter.updateData(list);
mRefreshLayout.refreshComplete();
}
},
2000);
}
@Override
public void onLoadingMore() {
mHandler.postDelayed(
new Runnable() {
@Override
public void run() {
List<String> list = DataUtil.createList(mCount, 20);
mCount += list.size();
mAdapter.appendData(list);
mRefreshLayout.refreshComplete();
}
},
3000);
}
});
mRefreshLayout
.getHeaderView()
.getView()
.setPadding(0, PixelUtl.dp2px(this, 80), 0, PixelUtl.dp2px(this, 10));
mRefreshLayout.autoRefresh(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
startActivity(new Intent(TestNestedActivity.this, MainActivity.class));
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
}
| 2,391 |
629 | <filename>AA-Wide-ResNet/attention_augmented_wide_resnet.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from attention_augmented_conv import AugmentedConv
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def _weights_init(m):
if isinstance(m, nn.Conv2d):
torch.nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
torch.nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
n = m.weight.size(1)
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()
class wide_basic(nn.Module):
def __init__(self, in_planes, planes, dropout_rate, shape, stride=1, v=0.2, k=2, Nh=4):
super(wide_basic, self).__init__()
if stride == 2:
original_shape = shape * 2
else:
original_shape = shape
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = AugmentedConv(in_planes, planes, kernel_size=3, dk=k * planes, dv=int(v * planes), Nh=Nh, relative=True, shape=original_shape)
self.dropout = nn.Dropout(p=dropout_rate)
self.bn2 = nn.BatchNorm2d(planes)
self.conv2 = AugmentedConv(planes, planes, kernel_size=3, dk=k * planes, dv=int(v * planes), Nh=Nh, stride=stride, relative=True, shape=shape)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != planes:
self.shortcut = nn.Sequential(
AugmentedConv(in_planes, planes, kernel_size=3, dk=k * planes, dv=int(v * planes), Nh=Nh, relative=True, stride=stride, shape=shape),
)
def forward(self, x):
out = self.dropout(self.conv1(F.relu(self.bn1(x))))
out = self.conv2(F.relu(self.bn2(out)))
short = self.shortcut(x)
out += short
return out
class Wide_ResNet(nn.Module):
def __init__(self, depth, widen_factor, dropout_rate, num_classes, shape):
super(Wide_ResNet, self).__init__()
self.in_planes = 20
self.shape = shape
assert ((depth-4) % 6 == 0), 'Wide-resnet depth should be 6n+4'
n = int((depth - 4) / 6)
k = widen_factor
dv_v = 0.2
dk_k = 2
Nh = 4
print('| Wide-Resnet %dx%d' % (depth, k))
n_Stages = [20, 20 * k, 40 * k, 60 * k]
self.conv1 = AugmentedConv(in_channels=3, out_channels=n_Stages[0], kernel_size=3, dk=dk_k * n_Stages[0], dv=int(dv_v * n_Stages[0]), shape=shape, Nh=Nh, relative=True)
self.layer1 = nn.Sequential(
self._wide_layer(wide_basic, n_Stages[1], n, dropout_rate, stride=1, shape=shape),
)
self.layer2 = nn.Sequential(
self._wide_layer(wide_basic, n_Stages[2], n, dropout_rate, stride=2, shape=shape // 2),
)
self.layer3 = nn.Sequential(
self._wide_layer(wide_basic, n_Stages[3], n, dropout_rate, stride=2, shape=shape // 4),
)
self.bn1 = nn.BatchNorm2d(n_Stages[3], momentum=0.9)
self.linear = nn.Linear(n_Stages[3], num_classes)
self.apply(_weights_init)
def _wide_layer(self, block, planes, num_blocks, dropout_rate, stride, shape):
strides = [stride] + [1]*(num_blocks-1)
layers = []
for stride in strides:
layers.append(block(self.in_planes, planes, dropout_rate=dropout_rate, stride=stride, shape=shape))
self.in_planes = planes
return nn.Sequential(*layers)
def forward(self, x):
out = self.conv1(x)
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = F.relu(self.bn1(out))
out = F.avg_pool2d(out, 8)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
# tmp = torch.randn((4, 3, 32, 32))
# model = Wide_ResNet(28, 10, 0.3, num_classes=100, shape=32)
# print(model(tmp).shape)
#
# for name, param in model.named_parameters():
# print('parameter name: ', name)
| 1,951 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-5c86-xw43-gw75",
"modified": "2022-05-03T03:13:10Z",
"published": "2022-05-03T03:13:10Z",
"aliases": [
"CVE-2004-0790"
],
"details": "Multiple TCP/IP and ICMP implementations allow remote attackers to cause a denial of service (reset TCP connections) via spoofed ICMP error messages, aka the \"blind connection-reset attack.\" NOTE: CVE-2004-0790, CVE-2004-0791, and CVE-2004-1060 have been SPLIT based on different attacks; CVE-2005-0065, CVE-2005-0066, CVE-2005-0067, and CVE-2005-0068 are related identifiers that are SPLIT based on the underlying vulnerability. While CVE normally SPLITs based on vulnerability, the attack-based identifiers exist due to the variety and number of affected implementations and solutions that address the attacks instead of the underlying vulnerabilities.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2004-0790"
},
{
"type": "WEB",
"url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2005/ms05-019"
},
{
"type": "WEB",
"url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2006/ms06-064"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1177"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A176"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1910"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A211"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A3458"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A412"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A4804"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A514"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A53"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A622"
},
{
"type": "WEB",
"url": "http://marc.info/?l=bugtraq&m=112861397904255&w=2"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/18317"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/22341"
},
{
"type": "WEB",
"url": "http://securityreason.com/securityalert/19"
},
{
"type": "WEB",
"url": "http://securityreason.com/securityalert/57"
},
{
"type": "WEB",
"url": "http://sunsolve.sun.com/search/document.do?assetkey=1-26-101658-1"
},
{
"type": "WEB",
"url": "http://sunsolve.sun.com/search/document.do?assetkey=1-26-57746-1"
},
{
"type": "WEB",
"url": "http://www.gont.com.ar/drafts/icmp-attacks-against-tcp.html"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/418882/100/0/threaded"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/449179/100/0/threaded"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/13124"
},
{
"type": "WEB",
"url": "http://www.uniras.gov.uk/niscc/docs/al-20050412-00308.html?lang=en"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2006/3983"
},
{
"type": "WEB",
"url": "http://www.watersprings.org/pub/id/draft-gont-tcpm-icmp-attacks-03.txt"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 1,993 |
502 | package com.ywl5320.player.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ywl5320.player.R;
import com.ywl5320.player.bean.VideoListBean;
import java.util.List;
/**
* Created by ywl on 2017-7-25.
*/
public class VideoListAdapter extends RecyclerView.Adapter<VideoListAdapter.TypeHolder>{
private Context context;
private List<VideoListBean> datas;
private OnItemClickListener onItemClickListener;
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public VideoListAdapter(Context context, List<VideoListBean> datas) {
this.context = context;
this.datas = datas;
}
@Override
public TypeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item_videlist_layout, parent, false);
TypeHolder holder = new TypeHolder(v);
return holder;
}
@Override
public void onBindViewHolder(TypeHolder holder, final int position) {
holder.tvName.setText(datas.get(position).getName());
holder.tvName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(onItemClickListener != null)
{
onItemClickListener.onItemClick(datas.get(position));
}
}
});
}
@Override
public int getItemCount() {
return datas.size();
}
public class TypeHolder extends RecyclerView.ViewHolder
{
private TextView tvName;
public TypeHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tv_name);
}
}
public interface OnItemClickListener
{
void onItemClick(VideoListBean videoListBean);
}
}
| 840 |
1,647 | <reponame>davidbrochart/pythran
#ifndef PYTHONIC_INCLUDE_NUMPY_SETDIFF1D_HPP
#define PYTHONIC_INCLUDE_NUMPY_SETDIFF1D_HPP
#include "pythonic/include/utils/functor.hpp"
#include "pythonic/include/types/ndarray.hpp"
PYTHONIC_NS_BEGIN
namespace numpy
{
template <class T, class U>
types::ndarray<typename __combined<typename types::dtype_of<T>::type,
typename types::dtype_of<U>::type>::type,
types::pshape<long>>
setdiff1d(T const &ar1, U const &ar2, bool assume_unique = false);
DEFINE_FUNCTOR(pythonic::numpy, setdiff1d);
}
PYTHONIC_NS_END
#endif
| 303 |
5,671 | package com.reactnative.ivpusic.imagepicker;
import android.media.ExifInterface;
public class GeoDegree {
Float latitude;
Float longitude;
public GeoDegree(ExifInterface exif) {
String attrLATITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
String attrLATITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
String attrLONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
String attrLONGITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
if ((attrLATITUDE != null)
&& (attrLATITUDE_REF != null)
&& (attrLONGITUDE != null)
&& (attrLONGITUDE_REF != null)) {
if (attrLATITUDE_REF.equals("N")) {
latitude = convertToDegree(attrLATITUDE);
} else {
latitude = 0 - convertToDegree(attrLATITUDE);
}
if (attrLONGITUDE_REF.equals("E")) {
longitude = convertToDegree(attrLONGITUDE);
} else {
longitude = 0 - convertToDegree(attrLONGITUDE);
}
}
}
private Float convertToDegree(String stringDMS) {
Float result = null;
String[] DMS = stringDMS.split(",", 3);
String[] stringD = DMS[0].split("/", 2);
Double D0 = Double.valueOf(stringD[0]);
Double D1 = Double.valueOf(stringD[1]);
double FloatD = D0 / D1;
String[] stringM = DMS[1].split("/", 2);
Double M0 = Double.valueOf(stringM[0]);
Double M1 = Double.valueOf(stringM[1]);
double FloatM = M0 / M1;
String[] stringS = DMS[2].split("/", 2);
Double S0 = Double.valueOf(stringS[0]);
Double S1 = Double.valueOf(stringS[1]);
double FloatS = S0 / S1;
result = (float) (FloatD + (FloatM / 60) + (FloatS / 3600));
return result;
}
public Float getLatitude() {
return latitude;
}
public Float getLongitude() {
return longitude;
}
}
| 1,007 |
773 | <reponame>SakuyaIzayoi/esp-rfid
#ifndef OFFICIALBOARD
/**************************************************************************
@file PN532.cpp
@author Adafruit Industries, Elmü
@license BSD (see license.txt)
Driver for NXP's PN532 NFC/13.56MHz RFID Transceiver
This is a library for the Adafruit PN532 NFC/RFID breakout board.
This library works with the Adafruit NFC breakout
----> https://www.adafruit.com/products/364
Check out the links above for our tutorials and wiring diagrams
These chips use SPI or I2C to communicate.
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing products from Adafruit!
----------------------------------------------------------
April 2016, modifications by Elmü:
The code from Adafruit was a VERY SLOPPY code just for testing and playing around but not usable for production.
It has been rewritten completely by Elmü.
IRQ is not required anymore in I2C mode. Now the software handshake is used instead.
Removed all compiler warnings that appeared when compiling Adafruit code.
Bugfix: Adafruit used strncmp() to compare binary data which is completey wrong -> replaced with memcmp()
Bugfix: (Severe bug) Adafruit code does not check for valid return packets. The checksum is completely irgnored. Bytes received before the start code are not skipped!
Bugfix: (Severe bug) Adafruit code used a timeout = 0 (wait forever). This is completely wrong. If the chip does not respond, the code hangs forever!
Bugfix: Adafruit code does not allow to distinguish why readPassiveTargetID() returns false. (because there is no card or because of communication problem?)
Added support for Value blocks (in Mifare.cpp)
Added memory Dump (in Mifare.cpp)
AuthenticateDataBlock(), ReadDataBlock() and WriteDataBlock() rewritten (in Mifare.cpp)
Implemented the correct wake up procedure (sending PN532_WAKEUP) instead of sending getFirmwareVersion.
Debug output was buggy: The checksum bytes were displayed as 0xFFFFFFFC instead of 0xFC and removed useless "0x" before each byte.
Detailed debug output was missing. Added display of valid data bytes inside the packet.
SPI slow speed added (using Software SPI to get 10kHz clock)
getFirmwareVersion() was a very clumsy and cryptic command -> completely rewritten
writeGPIO() rewritten -> no warning about wrong usage anymore.
setPassiveActivationRetries() did not have any error checking at all.
Ugly code in writecommand() completely rewritten
Crappy code like this removed: int offset = mb_UsingSPI ? 5 : 6;
----------------------------------------------------------
Check for a new version on http://www.codeproject.com/Articles/1096861/DIY-electronic-RFID-Door-Lock-with-Battery-Backup
**************************************************************************/
#include "PN532.h"
/**************************************************************************
Constructor
**************************************************************************/
PN532::PN532()
{
mu8_ClkPin = 0;
mu8_MisoPin = 0;
mu8_MosiPin = 0;
mu8_SselPin = 0;
mu8_ResetPin = 0;
}
/**************************************************************************
Initializes for hardware I2C usage.
param reset The RSTPD_N pin
**************************************************************************/
#if USE_HARDWARE_I2C
void PN532::InitI2C(byte u8_Reset)
{
mu8_ResetPin = u8_Reset;
Utils::SetPinMode(mu8_ResetPin, OUTPUT);
}
#endif
/**************************************************************************
Initializes for software SPI usage.
param clk SPI clock pin (SCK)
param miso SPI MISO pin
param mosi SPI MOSI pin
param sel SPI chip select pin (CS/SSEL)
param reset Location of the RSTPD_N pin
**************************************************************************/
#if USE_SOFTWARE_SPI
void PN532::InitSoftwareSPI(byte u8_Clk, byte u8_Miso, byte u8_Mosi, byte u8_Sel, byte u8_Reset)
{
mu8_ClkPin = u8_Clk;
mu8_MisoPin = u8_Miso;
mu8_MosiPin = u8_Mosi;
mu8_SselPin = u8_Sel;
mu8_ResetPin = u8_Reset;
Utils::SetPinMode(mu8_ResetPin, OUTPUT);
Utils::SetPinMode(mu8_SselPin, OUTPUT);
Utils::SetPinMode(mu8_ClkPin, OUTPUT);
Utils::SetPinMode(mu8_MosiPin, OUTPUT);
Utils::SetPinMode(mu8_MisoPin, INPUT);
}
#endif
/**************************************************************************
Initializes for hardware SPI uage.
param sel SPI chip select pin (CS/SSEL)
param reset Location of the RSTPD_N pin
**************************************************************************/
#if USE_HARDWARE_SPI
void PN532::InitHardwareSPI(byte u8_Sel, byte u8_Reset)
{
mu8_SselPin = u8_Sel;
mu8_ResetPin = u8_Reset;
Utils::SetPinMode(mu8_ResetPin, OUTPUT);
Utils::SetPinMode(mu8_SselPin, OUTPUT);
}
#endif
/**************************************************************************
Reset the PN532, wake up and start communication
**************************************************************************/
void PN532::begin()
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** begin()\r\n");
Utils::WritePin(mu8_ResetPin, HIGH);
Utils::DelayMilli(10);
Utils::WritePin(mu8_ResetPin, LOW);
Utils::DelayMilli(400);
Utils::WritePin(mu8_ResetPin, HIGH);
Utils::DelayMilli(10); // Small delay required before taking other actions after reset. See datasheet section 12.23, page 209.
#if (USE_HARDWARE_SPI || USE_SOFTWARE_SPI)
{
#if USE_HARDWARE_SPI
SpiClass::Begin(PN532_HARD_SPI_CLOCK);
#endif
// Wake up the PN532 (chapter 7.2.11) -> send a sequence of 0x55 (dummy bytes)
byte u8_Buffer[20];
memset(u8_Buffer, PN532_WAKEUP, sizeof(u8_Buffer));
SendPacket(u8_Buffer, sizeof(u8_Buffer));
if (mu8_DebugLevel > 1)
{
Utils::Print("Send WakeUp packet: ");
Utils::PrintHexBuf(u8_Buffer, sizeof(u8_Buffer), LF);
}
}
#elif USE_HARDWARE_I2C
{
I2cClass::Begin();
}
#endif
}
/**************************************************************************
Enable / disable debug output to SerialClass
0 = Off, 1 = high level debug, 2 = low level debug (more details)
**************************************************************************/
void PN532::SetDebugLevel(byte level)
{
mu8_DebugLevel = level;
}
/**************************************************************************
Gets the firmware version of the PN5xx chip
returns:
pIcType = Version of the IC. For PN532, this byte is 0x32
pVersionHi, pVersionLo = Firmware version
pFlags, bit 0 = Support of ISO 14443A
pFlags, bit 1 = Support of ISO 14443B
pFlags, bit 2 = Support of ISO 18092
**************************************************************************/
bool PN532::GetFirmwareVersion(byte* pIcType, byte* pVersionHi, byte* pVersionLo, byte* pFlags)
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** GetFirmwareVersion()\r\n");
mu8_PacketBuffer[0] = PN532_COMMAND_GETFIRMWAREVERSION;
if (!SendCommandCheckAck(mu8_PacketBuffer, 1))
return 0;
byte len = ReadData(mu8_PacketBuffer, 13);
if (len != 6 || mu8_PacketBuffer[1] != PN532_COMMAND_GETFIRMWAREVERSION + 1)
{
Utils::Print("GetFirmwareVersion failed\r\n");
return false;
}
*pIcType = mu8_PacketBuffer[2];
*pVersionHi = mu8_PacketBuffer[3];
*pVersionLo = mu8_PacketBuffer[4];
*pFlags = mu8_PacketBuffer[5];
return true;
}
/**************************************************************************
Configures the SAM (Secure Access Module)
**************************************************************************/
bool PN532::SamConfig(void)
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** SamConfig()\r\n");
mu8_PacketBuffer[0] = PN532_COMMAND_SAMCONFIGURATION;
mu8_PacketBuffer[1] = 0x01; // normal mode;
mu8_PacketBuffer[2] = 0x14; // timeout 50ms * 20 = 1 second
mu8_PacketBuffer[3] = 0x01; // use IRQ pin!
if (!SendCommandCheckAck(mu8_PacketBuffer, 4))
return false;
byte len = ReadData(mu8_PacketBuffer, 9);
if (len != 2 || mu8_PacketBuffer[1] != PN532_COMMAND_SAMCONFIGURATION + 1)
{
Utils::Print("SamConfig failed\r\n");
return false;
}
return true;
}
/**************************************************************************
Sets the amount of reties that the PN532 tries to activate a target
**************************************************************************/
bool PN532::SetPassiveActivationRetries()
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** SetPassiveActivationRetries()\r\n");
mu8_PacketBuffer[0] = PN532_COMMAND_RFCONFIGURATION;
mu8_PacketBuffer[1] = 5; // Config item 5 (MaxRetries)
mu8_PacketBuffer[2] = 0xFF; // MxRtyATR (default = 0xFF)
mu8_PacketBuffer[3] = 0x01; // MxRtyPSL (default = 0x01)
mu8_PacketBuffer[4] = 3; // one retry is enough for Mifare Classic but Desfire is slower (if you modify this, you must also modify PN532_TIMEOUT!)
if (!SendCommandCheckAck(mu8_PacketBuffer, 5))
return false;
byte len = ReadData(mu8_PacketBuffer, 9);
if (len != 2 || mu8_PacketBuffer[1] != PN532_COMMAND_RFCONFIGURATION + 1)
{
Utils::Print("SetPassiveActivationRetries failed\r\n");
return false;
}
return true;
}
/**************************************************************************
Turns the RF field off.
When the field is on, the PN532 consumes approx 110 mA
When the field is off, the PN532 consumes approx 18 mA
The RF field is turned on again by ReadPassiveTargetID().
**************************************************************************/
bool PN532::SwitchOffRfField()
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** SwitchOffRfField()\r\n");
mu8_PacketBuffer[0] = PN532_COMMAND_RFCONFIGURATION;
mu8_PacketBuffer[1] = 1; // Config item 1 (RF Field)
mu8_PacketBuffer[2] = 0; // Field Off
if (!SendCommandCheckAck(mu8_PacketBuffer, 3))
return false;
byte len = ReadData(mu8_PacketBuffer, 9);
if (len != 2 || mu8_PacketBuffer[1] != PN532_COMMAND_RFCONFIGURATION + 1)
{
Utils::Print("SwitchOffRfField failed\r\n");
return false;
}
return true;
}
/**************************************************************************/
/*!
Writes an 8-bit value that sets the state of the PN532's GPIO pins
All pins that can not be used as GPIO should ALWAYS be left high
(value = 1) or the system will become unstable and a HW reset
will be required to recover the PN532.
pinState[0] (01) = P30 Can be used as GPIO
pinState[1] (02) = P31 Can be used as GPIO
pinState[2] (04) = P32 *** RESERVED (Must be set) ***
pinState[3] (08) = P33 Can be used as GPIO
pinState[4] (10) = P34 *** RESERVED (Must be set) ***
pinState[5] (20) = P35 Can be used as GPIO
This function is not used. The original intention was to drive a LED that
is connected to the PN532 board. But the pins deliver so few current
that a connected LED is very dark. (even if connected without resistor!)
Additionally the red LED cannot be connected to the PN532 because it should
flash if there is a communication error with the PN532. But if there is a
communication problem the command WRITEGPIO will never arrive at the PN532
and the red LED would never flash.
*/
/**************************************************************************/
bool PN532::WriteGPIO(bool P30, bool P31, bool P33, bool P35)
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** WriteGPIO()\r\n");
byte pinState = (P30 ? PN532_GPIO_P30 : 0) |
(P31 ? PN532_GPIO_P31 : 0) |
PN532_GPIO_P32 |
(P33 ? PN532_GPIO_P33 : 0) |
PN532_GPIO_P34 |
(P35 ? PN532_GPIO_P35 : 0);
mu8_PacketBuffer[0] = PN532_COMMAND_WRITEGPIO;
mu8_PacketBuffer[1] = PN532_GPIO_VALIDATIONBIT | pinState; // P3 Pins
mu8_PacketBuffer[2] = 0x00; // P7 GPIO Pins (not used ... taken by SPI)
if (!SendCommandCheckAck(mu8_PacketBuffer, 3))
return false;
byte len = ReadData(mu8_PacketBuffer, 9);
if (len != 2 || mu8_PacketBuffer[1] != PN532_COMMAND_WRITEGPIO + 1)
{
Utils::Print("WriteGPIO failed\r\n");
return false;
}
return true;
}
/**************************************************************************
Waits for an ISO14443A target to enter the field.
If the RF field has been turned off before, this command switches it on.
param u8_UidBuffer Pointer to an 8 byte buffer that will be populated with the card's UID (4 or 7 bytes)
param pu8_UidLength Pointer to the variable that will hold the length of the card's UID.
param pe_CardType Pointer to the variable that will hold if the card is a Desfire card
returns false only on error!
returns true and *UidLength = 0 if no card was found
returns true and *UidLength > 0 if a card has been read successfully
**************************************************************************/
bool PN532::ReadPassiveTargetID(byte* u8_UidBuffer, byte* pu8_UidLength, eCardType* pe_CardType)
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** ReadPassiveTargetID()\r\n");
*pu8_UidLength = 0;
*pe_CardType = CARD_Unknown;
memset(u8_UidBuffer, 0, 8);
mu8_PacketBuffer[0] = PN532_COMMAND_INLISTPASSIVETARGET;
mu8_PacketBuffer[1] = 1; // read data of 1 card (The PN532 can read max 2 targets at the same time)
mu8_PacketBuffer[2] = CARD_TYPE_106KB_ISO14443A; // This function currently does not support other card types.
if (!SendCommandCheckAck(mu8_PacketBuffer, 3))
return false; // Error (no valid ACK received or timeout)
/*
ISO14443A card response:
mu8_PacketBuffer Description
-------------------------------------------------------
b0 D5 (always) (PN532_PN532TOHOST)
b1 4B (always) (PN532_COMMAND_INLISTPASSIVETARGET + 1)
b2 Amount of cards found
b3 Tag number (always 1)
b4,5 SENS_RES (ATQA = Answer to Request Type A)
b6 SEL_RES (SAK = Select Acknowledge)
b7 UID Length
b8..Length UID (4 or 7 bytes)
nn ATS Length (Desfire only)
nn..Length-1 ATS data bytes (Desfire only)
*/
byte len = ReadData(mu8_PacketBuffer, 28);
if (len < 3 || mu8_PacketBuffer[1] != PN532_COMMAND_INLISTPASSIVETARGET + 1)
{
Utils::Print("ReadPassiveTargetID failed\r\n");
return false;
}
byte cardsFound = mu8_PacketBuffer[2];
if (mu8_DebugLevel > 0)
{
Utils::Print("Cards found: ");
Utils::PrintDec(cardsFound, LF);
}
if (cardsFound != 1)
return true; // no card found -> this is not an error!
byte u8_IdLength = mu8_PacketBuffer[7];
if (u8_IdLength != 4 && u8_IdLength != 7)
{
Utils::Print("Card has unsupported UID length: ");
Utils::PrintDec(u8_IdLength, LF);
return true; // unsupported card found -> this is not an error!
}
memcpy(u8_UidBuffer, mu8_PacketBuffer + 8, u8_IdLength);
*pu8_UidLength = u8_IdLength;
// See "Mifare Identification & Card Types.pdf" in the ZIP file
uint16_t u16_ATQA = ((uint16_t)mu8_PacketBuffer[4] << 8) | mu8_PacketBuffer[5];
byte u8_SAK = mu8_PacketBuffer[6];
if (u8_IdLength == 7 && u8_UidBuffer[0] != 0x80 && u16_ATQA == 0x0344 && u8_SAK == 0x20) *pe_CardType = CARD_Desfire;
if (u8_IdLength == 4 && u8_UidBuffer[0] == 0x80 && u16_ATQA == 0x0304 && u8_SAK == 0x20) *pe_CardType = CARD_DesRandom;
if (mu8_DebugLevel > 0)
{
Utils::Print("Card UID: ");
Utils::PrintHexBuf(u8_UidBuffer, u8_IdLength, LF);
// Examples: ATQA SAK UID length
// MIFARE Mini 00 04 09 4 bytes
// MIFARE Mini 00 44 09 7 bytes
// MIFARE Classic 1k 00 04 08 4 bytes
// MIFARE Classic 4k 00 02 18 4 bytes
// MIFARE Ultralight 00 44 00 7 bytes
// MIFARE DESFire Default 03 44 20 7 bytes
// MIFARE DESFire Random 03 04 20 4 bytes
// See "Mifare Identification & Card Types.pdf"
char s8_Buf[80];
sprintf(s8_Buf, "Card Type: ATQA= 0x%04X, SAK= 0x%02X", u16_ATQA, u8_SAK);
if (*pe_CardType == CARD_Desfire) strcat(s8_Buf, " (Desfire Default)");
if (*pe_CardType == CARD_DesRandom) strcat(s8_Buf, " (Desfire RandomID)");
Utils::Print(s8_Buf, LF);
}
return true;
}
/**************************************************************************
The goal of this command is to select the target. (Initialization, anti-collision loop and Selection)
If the target is already selected, no action is performed and Status OK is returned.
**************************************************************************/
bool PN532::SelectCard()
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** SelectCard()\r\n");
mu8_PacketBuffer[0] = PN532_COMMAND_INSELECT;
mu8_PacketBuffer[1] = 1; // Target 1
if (!SendCommandCheckAck(mu8_PacketBuffer, 2))
return false;
byte len = ReadData(mu8_PacketBuffer, 10);
if (len < 3 || mu8_PacketBuffer[1] != PN532_COMMAND_INSELECT + 1)
{
Utils::Print("Select failed\r\n");
return false;
}
return CheckPN532Status(mu8_PacketBuffer[2]);
}
/**************************************************************************
The goal of this command is to deselect the target.
The PN532 keeps all the information relative to this target (also certain error status).
This function is required due to a stupid behaviour with Mifare Classic:
When AuthenticateDataBlock() has failed for a sector, you also get an
authentication error for the next sector although you have passed the correct key.
So, after an authentication error you must first deselect the card before
authenticating a new sector!
**************************************************************************/
bool PN532::DeselectCard()
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** DeselectCard()\r\n");
mu8_PacketBuffer[0] = PN532_COMMAND_INDESELECT;
mu8_PacketBuffer[1] = 0; // Deselect all cards
if (!SendCommandCheckAck(mu8_PacketBuffer, 2))
return false;
byte len = ReadData(mu8_PacketBuffer, 10);
if (len < 3 || mu8_PacketBuffer[1] != PN532_COMMAND_INDESELECT + 1)
{
Utils::Print("Deselect failed\r\n");
return false;
}
return CheckPN532Status(mu8_PacketBuffer[2]);
}
/**************************************************************************
The goal of this command is to release the target.
Releasing a target means that the host controller has finished the communication with
the target, so the PN532 erases all the information relative to it.
**************************************************************************/
bool PN532::ReleaseCard()
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** ReleaseCard()\r\n");
mu8_PacketBuffer[0] = PN532_COMMAND_INRELEASE;
mu8_PacketBuffer[1] = 0; // Deselect all cards
if (!SendCommandCheckAck(mu8_PacketBuffer, 2))
return false;
byte len = ReadData(mu8_PacketBuffer, 10);
if (len < 3 || mu8_PacketBuffer[1] != PN532_COMMAND_INRELEASE + 1)
{
Utils::Print("Release failed\r\n");
return false;
}
return CheckPN532Status(mu8_PacketBuffer[2]);
}
/**************************************************************************
This function is private
It checks the status byte that is returned by some commands.
See chapter 7.1 in the manual.
u8_Status = the status byte
**************************************************************************/
bool PN532::CheckPN532Status(byte u8_Status)
{
// Bits 0...5 contain the error code.
u8_Status &= 0x3F;
if (u8_Status == 0)
return true;
char s8_Buf[50];
sprintf(s8_Buf, "PN532 Error 0x%02X: ", u8_Status);
Utils::Print(s8_Buf);
switch (u8_Status)
{
case 0x01:
Utils::Print("Timeout\r\n");
return false;
case 0x02:
Utils::Print("CRC error\r\n");
return false;
case 0x03:
Utils::Print("Parity error\r\n");
return false;
case 0x04:
Utils::Print("Wrong bit count during anti-collision\r\n");
return false;
case 0x05:
Utils::Print("Framing error\r\n");
return false;
case 0x06:
Utils::Print("Abnormal bit collision\r\n");
return false;
case 0x07:
Utils::Print("Insufficient communication buffer\r\n");
return false;
case 0x09:
Utils::Print("RF buffer overflow\r\n");
return false;
case 0x0A:
Utils::Print("RF field has not been switched on\r\n");
return false;
case 0x0B:
Utils::Print("RF protocol error\r\n");
return false;
case 0x0D:
Utils::Print("Overheating\r\n");
return false;
case 0x0E:
Utils::Print("Internal buffer overflow\r\n");
return false;
case 0x10:
Utils::Print("Invalid parameter\r\n");
return false;
case 0x12:
Utils::Print("Command not supported\r\n");
return false;
case 0x13:
Utils::Print("Wrong data format\r\n");
return false;
case 0x14:
Utils::Print("Authentication error\r\n");
return false;
case 0x23:
Utils::Print("Wrong UID check byte\r\n");
return false;
case 0x25:
Utils::Print("Invalid device state\r\n");
return false;
case 0x26:
Utils::Print("Operation not allowed\r\n");
return false;
case 0x27:
Utils::Print("Command not acceptable\r\n");
return false;
case 0x29:
Utils::Print("Target has been released\r\n");
return false;
case 0x2A:
Utils::Print("Card has been exchanged\r\n");
return false;
case 0x2B:
Utils::Print("Card has disappeared\r\n");
return false;
case 0x2C:
Utils::Print("NFCID3 initiator/target mismatch\r\n");
return false;
case 0x2D:
Utils::Print("Over-current\r\n");
return false;
case 0x2E:
Utils::Print("NAD msssing\r\n");
return false;
default:
Utils::Print("Undocumented error\r\n");
return false;
}
}
// ########################################################################
// #### LOW LEVEL FUNCTIONS #####
// ########################################################################
/**************************************************************************
Return true if the PN532 is ready with a response.
**************************************************************************/
bool PN532::IsReady()
{
#if (USE_HARDWARE_SPI || USE_SOFTWARE_SPI)
{
Utils::WritePin(mu8_SselPin, LOW);
Utils::DelayMilli(2); // INDISPENSABLE!! Otherwise reads bullshit
if (mu8_DebugLevel > 2) Utils::Print("IsReady(): write STATUSREAD\r\n");
SpiWrite(PN532_SPI_STATUSREAD);
byte u8_Ready = SpiRead();
if (mu8_DebugLevel > 2)
{
Utils::Print("IsReady(): read ");
Utils::PrintHex8(u8_Ready, LF);
}
Utils::WritePin(mu8_SselPin, HIGH);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
return u8_Ready == PN532_SPI_READY; // 0x01
}
#elif USE_HARDWARE_I2C
{
// After reading this byte, the bus must be released with a Stop condition
I2cClass::RequestFrom((byte)PN532_I2C_ADDRESS, (byte)1);
// PN532 Manual chapter 6.2.4: Before the data bytes the chip sends a Ready byte.
byte u8_Ready = I2cClass::Read();
if (mu8_DebugLevel > 2)
{
Utils::Print("IsReady(): read ");
Utils::PrintHex8(u8_Ready, LF);
}
return u8_Ready == PN532_I2C_READY; // 0x01
}
#endif
}
/**************************************************************************
Waits until the PN532 is ready.
**************************************************************************/
bool PN532::WaitReady()
{
uint16_t timer = 0;
while (!IsReady())
{
if (timer >= PN532_TIMEOUT)
{
if (mu8_DebugLevel > 0) Utils::Print("WaitReady() -> TIMEOUT\r\n");
return false;
}
Utils::DelayMilli(10);
timer += 10;
}
return true;
}
/**************************************************************************
Sends a command and waits a specified period for the ACK
param cmd Pointer to the command buffer
param cmdlen The size of the command in bytes
returns true if everything is OK,
false if timeout occured before an ACK was recieved
**************************************************************************/
bool PN532::SendCommandCheckAck(byte *cmd, byte cmdlen)
{
WriteCommand(cmd, cmdlen);
return ReadAck();
}
/**************************************************************************
Writes a command to the PN532, inserting the
preamble and required frame details (checksum, len, etc.)
param cmd Command buffer
param cmdlen Command length in bytes
**************************************************************************/
void PN532::WriteCommand(byte* cmd, byte cmdlen)
{
byte TxBuffer[PN532_PACKBUFFSIZE + 10];
int P=0;
TxBuffer[P++] = PN532_PREAMBLE; // 00
TxBuffer[P++] = PN532_STARTCODE1; // 00
TxBuffer[P++] = PN532_STARTCODE2; // FF
TxBuffer[P++] = cmdlen + 1;
TxBuffer[P++] = 0xFF - cmdlen;
TxBuffer[P++] = PN532_HOSTTOPN532; // D4
for (byte i=0; i<cmdlen; i++)
{
TxBuffer[P++] = cmd[i];
}
byte checksum = 0;
for (byte i=0; i<P; i++)
{
checksum += TxBuffer[i];
}
TxBuffer[P++] = ~checksum;
TxBuffer[P++] = PN532_POSTAMBLE; // 00
SendPacket(TxBuffer, P);
if (mu8_DebugLevel > 1)
{
Utils::Print("Sending: ");
Utils::PrintHexBuf(TxBuffer, P, LF, 5, cmdlen + 6);
}
}
/**************************************************************************
Send a data packet
**************************************************************************/
void PN532::SendPacket(byte* buff, byte len)
{
#if (USE_HARDWARE_SPI || USE_SOFTWARE_SPI)
{
Utils::WritePin(mu8_SselPin, LOW);
Utils::DelayMilli(2); // INDISPENSABLE!!
if (mu8_DebugLevel > 2) Utils::Print("WriteCommand(): write DATAWRITE\r\n");
SpiWrite(PN532_SPI_DATAWRITE);
for (byte i=0; i<len; i++)
{
SpiWrite(buff[i]);
}
Utils::WritePin(mu8_SselPin, HIGH);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
}
#elif USE_HARDWARE_I2C
{
Utils::DelayMilli(2); // delay is for waking up the board
I2cClass::BeginTransmission(PN532_I2C_ADDRESS);
for (byte i=0; i<len; i++)
{
I2cClass::Write(buff[i]);
}
I2cClass::EndTransmission();
}
#endif
}
/**************************************************************************
Read the ACK packet (acknowledge)
**************************************************************************/
bool PN532::ReadAck()
{
const byte Ack[] = {0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00};
byte ackbuff[sizeof(Ack)];
// ATTENTION: Never read more than 6 bytes here!
// The PN532 has a bug in SPI mode which results in the first byte of the response missing if more than 6 bytes are read here!
if (!ReadPacket(ackbuff, sizeof(ackbuff)))
return false; // Timeout
if (mu8_DebugLevel > 2)
{
Utils::Print("Read ACK: ");
Utils::PrintHexBuf(ackbuff, sizeof(ackbuff), LF);
}
if (memcmp(ackbuff, Ack, sizeof(Ack)) != 0)
{
Utils::Print("*** No ACK frame received\r\n");
return false;
}
return true;
}
/**************************************************************************
Reads n bytes of data from the PN532 via SPI or I2C and checks for valid data.
param buff Pointer to the buffer where data will be written
param len Number of bytes to read
returns the number of bytes that have been copied to buff (< len) or 0 on error
**************************************************************************/
byte PN532::ReadData(byte* buff, byte len)
{
byte RxBuffer[PN532_PACKBUFFSIZE];
const byte MIN_PACK_LEN = 2 /*start bytes*/ + 2 /*length + length checksum */ + 1 /*checksum*/;
if (len < MIN_PACK_LEN || len > PN532_PACKBUFFSIZE)
{
Utils::Print("ReadData(): len is invalid\r\n");
return 0;
}
if (!ReadPacket(RxBuffer, len))
return 0; // timeout
// The following important validity check was completely missing in Adafruit code (added by Elmü)
// PN532 documentation says (chapter 6.2.1.6):
// Before the start code (0x00 0xFF) there may be any number of additional bytes that must be ignored.
// After the checksum there may be any number of additional bytes that must be ignored.
// This function returns ONLY the pure data bytes:
// any leading bytes -> skipped (never seen, but documentation says to ignore them)
// preamble 0x00 -> skipped (optional, the PN532 does not send it always!!!!!)
// start code 0x00 -> skipped
// start code 0xFF -> skipped
// length -> skipped
// length checksum -> skipped
// data[0...n] -> returned to the caller (first byte is always 0xD5)
// checksum -> skipped
// postamble -> skipped (optional, the PN532 may not send it!)
// any bytes behind -> skipped (never seen, but documentation says to ignore them)
const char* Error = NULL;
int Brace1 = -1;
int Brace2 = -1;
int dataLength = 0;
do
{
int startCode = -1;
for (int i=0; i<=len-MIN_PACK_LEN; i++)
{
if (RxBuffer[i] == PN532_STARTCODE1 &&
RxBuffer[i+1] == PN532_STARTCODE2)
{
startCode = i;
break;
}
}
if (startCode < 0)
{
Error = "ReadData() -> No Start Code\r\n";
break;
}
int pos = startCode + 2;
dataLength = RxBuffer[pos++];
int lengthCheck = RxBuffer[pos++];
if ((dataLength + lengthCheck) != 0x100)
{
Error = "ReadData() -> Invalid length checksum\r\n";
break;
}
if (len < startCode + MIN_PACK_LEN + dataLength)
{
Error = "ReadData() -> Packet is longer than requested length\r\n";
break;
}
Brace1 = pos;
for (int i=0; i<dataLength; i++)
{
buff[i] = RxBuffer[pos++]; // copy the pure data bytes in the packet
}
Brace2 = pos;
// All returned data blocks must start with PN532TOHOST (0xD5)
if (dataLength < 1 || buff[0] != PN532_PN532TOHOST)
{
Error = "ReadData() -> Invalid data (no PN532TOHOST)\r\n";
break;
}
byte checkSum = 0;
for (int i=startCode; i<pos; i++)
{
checkSum += RxBuffer[i];
}
if (checkSum != (byte)(~RxBuffer[pos]))
{
Error = "ReadData() -> Invalid checksum\r\n";
break;
}
}
while(false); // This is not a loop. Avoids using goto by using break.
// Always print the package, even if it was invalid.
if (mu8_DebugLevel > 1)
{
Utils::Print("Response: ");
Utils::PrintHexBuf(RxBuffer, len, LF, Brace1, Brace2);
}
if (Error)
{
Utils::Print(Error);
return 0;
}
return dataLength;
}
/**************************************************************************
Reads n bytes of data from the PN532 via SPI or I2C and does NOT check for valid data.
param buff Pointer to the buffer where data will be written
param len Number of bytes to read
**************************************************************************/
bool PN532::ReadPacket(byte* buff, byte len)
{
if (!WaitReady())
return false;
#if (USE_HARDWARE_SPI || USE_SOFTWARE_SPI)
{
Utils::WritePin(mu8_SselPin, LOW);
Utils::DelayMilli(2); // INDISPENSABLE!! Otherwise reads bullshit
if (mu8_DebugLevel > 2) Utils::Print("ReadPacket(): write DATAREAD\r\n");
SpiWrite(PN532_SPI_DATAREAD);
for (byte i=0; i<len; i++)
{
Utils::DelayMilli(1);
buff[i] = SpiRead();
}
Utils::WritePin(mu8_SselPin, HIGH);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
return true;
}
#elif USE_HARDWARE_I2C
{
Utils::DelayMilli(2);
// read (n+1 to take into account leading Ready byte)
I2cClass::RequestFrom((byte)PN532_I2C_ADDRESS, (byte)(len+1));
// PN532 Manual chapter 6.2.4: Before the data bytes the chip sends a Ready byte.
// It is ignored here because it has been checked already in isready()
byte u8_Ready = I2cClass::Read();
if (mu8_DebugLevel > 2)
{
Utils::Print("ReadPacket(): read ");
Utils::PrintHex8(u8_Ready, LF);
}
for (byte i=0; i<len; i++)
{
Utils::DelayMilli(1);
buff[i] = I2cClass::Read();
}
return true;
}
#endif
}
/**************************************************************************
SPI write one byte
**************************************************************************/
void PN532::SpiWrite(byte c)
{
#if USE_HARDWARE_SPI
{
SpiClass::Transfer(c);
}
#elif USE_SOFTWARE_SPI
{
Utils::WritePin(mu8_ClkPin, HIGH);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
for (int i=1; i<=128; i<<=1)
{
Utils::WritePin(mu8_ClkPin, LOW);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
byte level = (c & i) ? HIGH : LOW;
Utils::WritePin(mu8_MosiPin, level);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
Utils::WritePin(mu8_ClkPin, HIGH);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
}
}
#endif
}
/**************************************************************************
SPI read one byte
**************************************************************************/
byte PN532::SpiRead(void)
{
#if USE_HARDWARE_SPI
{
return SpiClass::Transfer(0x00);
}
#elif USE_SOFTWARE_SPI
{
Utils::WritePin(mu8_ClkPin, HIGH);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
int x=0;
for (int i=1; i<=128; i<<=1)
{
if (Utils::ReadPin(mu8_MisoPin))
{
x |= i;
}
Utils::WritePin(mu8_ClkPin, LOW);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
Utils::WritePin(mu8_ClkPin, HIGH);
Utils::DelayMicro(PN532_SOFT_SPI_DELAY);
}
return x;
}
#else
{
return 0; // This code will never execute. Just for the compiler not to complain.
}
#endif
}
#endif
| 15,471 |
6,199 | <filename>pytext/common/utils.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from sys import stderr
def eprint(*args, **kwargs):
print(file=stderr, *args, **kwargs)
| 77 |
432 | /*
* Copyright (C) 2020 ActiveJ 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.
*/
package io.activej.codegen.expression;
import io.activej.codegen.Context;
import org.objectweb.asm.Label;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import java.util.List;
import static io.activej.codegen.expression.Expressions.throwException;
import static io.activej.codegen.util.Utils.isPrimitiveType;
import static org.objectweb.asm.Type.getType;
final class ExpressionSwitch implements Expression {
public static final Expression DEFAULT_EXPRESSION = throwException(IllegalArgumentException.class);
private final Expression value;
private final List<Expression> matchCases;
private final List<Expression> matchExpressions;
private final Expression defaultExpression;
ExpressionSwitch(Expression value, List<Expression> matchCases, List<Expression> matchExpressions, Expression defaultExpression) {
this.value = value;
this.matchCases = matchCases;
this.matchExpressions = matchExpressions;
this.defaultExpression = defaultExpression;
}
@Override
public Type load(Context ctx) {
GeneratorAdapter g = ctx.getGeneratorAdapter();
Type keyType = this.value.load(ctx);
VarLocal value = ctx.newLocal(keyType);
value.store(ctx);
Label labelExit = new Label();
Type resultType = getType(Object.class);
for (int i = 0; i < matchCases.size(); i++) {
Label labelNext = new Label();
if (isPrimitiveType(keyType) || keyType.equals(getType(Class.class))) {
matchCases.get(i).load(ctx);
value.load(ctx);
g.ifCmp(keyType, GeneratorAdapter.NE, labelNext);
} else {
ctx.invoke(matchCases.get(i), "equals", value);
g.push(true);
g.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.NE, labelNext);
}
resultType = matchExpressions.get(i).load(ctx);
g.goTo(labelExit);
g.mark(labelNext);
}
defaultExpression.load(ctx);
g.mark(labelExit);
return resultType;
}
}
| 801 |
3,102 | // RUN: %clang_cc1 -Wuninitialized -fsyntax-only %s 2>&1 | FileCheck %s
void pr14901(int a) {
int b, c;
a = b;
a = c;
}
// CHECK: 5:8: warning: variable 'b' is uninitialized when used here
// CHECK: 4:9: note: initialize the variable 'b' to silence this warning
// CHECK: 6:8: warning: variable 'c' is uninitialized when used here
// CHECK: 4:12: note: initialize the variable 'c' to silence this warning
| 151 |
488 | <reponame>maurizioabba/rose<filename>tests/CompileTests/Java_tests/cave3_for3.java
public class cave3_for3 {
public void loop() {
for(int i = 1, j = 10;
i < 10;
// Need to create list of expression
j--,
i=2) {
}
}
}
| 111 |
677 | /*
* Copyright (C) 2014 <NAME>, Koeln, Germany, robert-stupp.de
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.caffinitas.ohc.chunked;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.caffinitas.ohc.CacheSerializer;
import org.caffinitas.ohc.OHCache;
import org.caffinitas.ohc.OHCacheBuilder;
import org.caffinitas.ohc.OHCacheStats;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
public class EvictionTest
{
@AfterMethod(alwaysRun = true)
public void deinit()
{
Uns.clearUnsDebugForTest();
}
@Test
public void testEviction() throws IOException
{
try (OHCache<Integer, String> cache = OHCacheBuilder.<Integer, String>newBuilder()
.keySerializer(TestUtils.intSerializer)
.valueSerializer(TestUtils.stringSerializer)
.hashTableSize(64)
.segmentCount(4)
.capacity(8 * 1024 * 1024)
.chunkSize(65536)
.build())
{
for (int i = 0; i < 10000000; i++)
{
cache.put(i, Integer.toOctalString(i));
if (cache.stats().getEvictionCount() > 1000 * 150)
return;
}
fail();
}
}
@Test
public void testEvictionFixed() throws IOException
{
try (OHCache<Integer, String> cache = OHCacheBuilder.<Integer, String>newBuilder()
.keySerializer(TestUtils.intSerializer)
.valueSerializer(TestUtils.fixedValueSerializer)
.hashTableSize(64)
.segmentCount(4)
.capacity(8 * 1024 * 1024)
.chunkSize(65536)
.fixedEntrySize(TestUtils.INT_SERIALIZER_LEN, TestUtils.FIXED_VALUE_LEN)
.build())
{
for (int i = 0; i < 10000000; i++)
{
cache.put(i, Integer.toOctalString(i));
if (cache.stats().getEvictionCount() > 1000 * 150)
return;
}
fail();
}
}
@Test
public void testSize() throws Exception
{
ByteArrayCacheSerializer serializer = new ByteArrayCacheSerializer();
try (OHCache<byte[], byte[]> ohCache = OHCacheBuilder.<byte[], byte[]>newBuilder().capacity(1024 * 4)
.throwOOME(true)
.keySerializer(serializer)
.valueSerializer(serializer)
.segmentCount(1)
.chunkSize(1024)
.hashTableSize(256)
.build())
{
for (int i = 0; i < 12; ++i)
{
byte[] key = longToBytes(i);
byte[] value = new byte[256];
ohCache.put(key, value);
OHCacheStats pre = ohCache.stats();
ohCache.remove(key);
OHCacheStats post = ohCache.stats();
assertEquals(post.getSize(), 0);
assertEquals(post.getRemoveCount(), pre.getRemoveCount() + 1);
}
for (int i = 12; i < 16; ++i)
{
byte[] key = longToBytes(i);
byte[] value = new byte[256];
ohCache.put(key, value);
}
OHCacheStats stats = ohCache.stats();
assertEquals(stats.getSize(), 4);
assertTrue(stats.getEvictionCount() >= 0);
}
}
private byte[] longToBytes(long x)
{
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putLong(x);
return buffer.array();
}
static private class ByteArrayCacheSerializer implements CacheSerializer<byte[]>
{
@Override
public void serialize(byte[] value, ByteBuffer buf)
{
buf.put(value);
}
@Override
public byte[] deserialize(ByteBuffer buf)
{
byte[] bytes = new byte[buf.capacity()];
buf.get(bytes);
return bytes;
}
@Override
public int serializedSize(byte[] value)
{
return value.length;
}
}
}
| 3,519 |
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.
#include "chrome/browser/sharing/sms/sms_remote_fetcher.h"
#include "base/check.h"
#include "base/metrics/histogram_functions.h"
#include "build/build_config.h"
#include "chrome/browser/sharing/sharing_service_factory.h"
#include "chrome/browser/sharing/sms/sms_flags.h"
#include "chrome/browser/sharing/sms/sms_remote_fetcher_metrics.h"
#include "chrome/browser/sharing/sms/sms_remote_fetcher_ui_controller.h"
#include "content/public/browser/sms_fetcher.h"
#include "content/public/browser/web_contents.h"
#include "url/gurl.h"
#include "url/origin.h"
// TODO(crbug.com/1224878): Add browser tests for communication between this
// and the caller from content/.
base::OnceClosure FetchRemoteSms(
content::WebContents* web_contents,
const std::vector<url::Origin>& origin_list,
base::OnceCallback<void(absl::optional<std::vector<url::Origin>>,
absl::optional<std::string>,
absl::optional<content::SmsFetchFailureType>)>
callback) {
if (!base::FeatureList::IsEnabled(kWebOTPCrossDevice)) {
std::move(callback).Run(absl::nullopt, absl::nullopt,
content::SmsFetchFailureType::kCrossDeviceFailure);
RecordWebOTPCrossDeviceFailure(WebOTPCrossDeviceFailure::kFeatureDisabled);
return base::NullCallback();
}
if (!SharingServiceFactory::GetForBrowserContext(
web_contents->GetBrowserContext())) {
std::move(callback).Run(absl::nullopt, absl::nullopt,
content::SmsFetchFailureType::kCrossDeviceFailure);
RecordWebOTPCrossDeviceFailure(WebOTPCrossDeviceFailure::kNoSharingService);
return base::NullCallback();
}
// The current distinction of local fetcher being non-Android and remote fetcher
// being Android is a simplification we have made at this point and not a
// fundamental limitation. This may be relaxed in the future. e.g. allows
// tablets that run Android fetch a remote sms.
#if !defined(OS_ANDROID)
auto* ui_controller =
SmsRemoteFetcherUiController::GetOrCreateFromWebContents(web_contents);
return ui_controller->FetchRemoteSms(origin_list, std::move(callback));
#else
std::move(callback).Run(absl::nullopt, absl::nullopt,
content::SmsFetchFailureType::kCrossDeviceFailure);
RecordWebOTPCrossDeviceFailure(
WebOTPCrossDeviceFailure::kAndroidToAndroidNotSupported);
return base::NullCallback();
#endif
}
| 950 |
5,411 | // vendor/chromium/mojo/public/mojom/base/file_error.mojom-shared-internal.h is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef VENDOR_CHROMIUM_MOJO_PUBLIC_MOJOM_BASE_FILE_ERROR_MOJOM_SHARED_INTERNAL_H_
#define VENDOR_CHROMIUM_MOJO_PUBLIC_MOJOM_BASE_FILE_ERROR_MOJOM_SHARED_INTERNAL_H_
#include "mojo/public/cpp/bindings/lib/array_internal.h"
#include "mojo/public/cpp/bindings/lib/bindings_internal.h"
#include "mojo/public/cpp/bindings/lib/map_data_internal.h"
#include "mojo/public/cpp/bindings/lib/buffer.h"
#include "mojo/public/cpp/bindings/lib/native_enum_data.h"
#include "mojo/public/interfaces/bindings/native_struct.mojom-shared-internal.h"
namespace mojo {
namespace internal {
class ValidationContext;
}
}
namespace mojo_base {
namespace mojom {
namespace internal {
struct FileError_Data {
public:
static bool constexpr kIsExtensible = false;
static bool IsKnownValue(int32_t value) {
switch (value) {
case -16:
case -15:
case -14:
case -13:
case -12:
case -11:
case -10:
case -9:
case -8:
case -7:
case -6:
case -5:
case -4:
case -3:
case -2:
case -1:
case 0:
return true;
}
return false;
}
static bool Validate(int32_t value,
mojo::internal::ValidationContext* validation_context) {
if (kIsExtensible || IsKnownValue(value))
return true;
ReportValidationError(validation_context,
mojo::internal::VALIDATION_ERROR_UNKNOWN_ENUM_VALUE);
return false;
}
};
#pragma pack(push, 1)
#pragma pack(pop)
} // namespace internal
} // namespace mojom
} // namespace mojo_base
#endif // VENDOR_CHROMIUM_MOJO_PUBLIC_MOJOM_BASE_FILE_ERROR_MOJOM_SHARED_INTERNAL_H_ | 845 |
854 | <reponame>timxor/leetcode-journal
__________________________________________________________________________________________________
12ms
static const int _ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
class Solution {
public:
bool exist(std::vector<std::vector<char>>& Board, std::string Word) {
const int WordLen = Word.length();
if (WordLen < 1)
return true;
const int RowNum = Board.size();
if (RowNum < 1)
return false;
const int ColNum = Board[0].size();
if (ColNum < 1)
return false;
std::function<bool(int,int,int)> BackTrack;
BackTrack = [&](int Row, int Col, int CharIdx) {
if (CharIdx >= WordLen)
return true;
const char &WordCh = Word[CharIdx];
char &BoardCh = Board[Row][Col];
BoardCh = ~BoardCh;
bool IsMatch = false;
if (Row > 0 &&
Board[Row - 1][Col] == WordCh &&
BackTrack(Row - 1, Col, CharIdx + 1))
IsMatch = true;
else if (Col > 0 &&
Board[Row][Col - 1] == WordCh &&
BackTrack(Row, Col - 1, CharIdx + 1))
IsMatch = true;
else if (Row < RowNum - 1 &&
Board[Row + 1][Col] == WordCh &&
BackTrack(Row + 1, Col, CharIdx + 1))
IsMatch = true;
else if (Col < ColNum - 1 &&
Board[Row][Col + 1] == WordCh &&
BackTrack(Row, Col + 1, CharIdx + 1))
IsMatch = true;
BoardCh = ~BoardCh;
return IsMatch;
};
for (int Row = 0; Row < RowNum; ++Row) {
for (int Col = 0; Col < ColNum; ++Col) {
if (Board[Row][Col] == Word[0] && BackTrack(Row, Col, 1))
return true;
}
}
return false;
}
};
__________________________________________________________________________________________________
10004 kb
class Solution {
public:
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
bool exist(vector<vector<char>>& board, string word) {
for(int i = 0; i < board.size(); i++)
for(int j = 0; j < board[0].size(); j++)
if(board[i][j] == word[0] && helper(i, j, 0, board, word)) return 1;
// if(helper(i, j, 0, board, word)) return 1;
return 0;
}
bool helper(int i, int j, int w, vector<vector<char>> &board, string &word)
{
if(++w == word.size()) return 1;
// char c = board[i][j];
// board[i][j] = 0;
board[i][j] ^= -1;
for(auto &t : dir)
{
int a = i + t[0], b = j + t[1];
if(a >= 0 && b >= 0 && a < board.size() && b < board[0].size() && board[a][b] == word[w])
if(helper(a, b, w, board, word)) return 1;;
}
// board[i][j] = c;
board[i][j] ^= -1;
return 0;
}
};
static int x = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
return NULL;
}();
__________________________________________________________________________________________________
| 1,572 |
4,036 | <gh_stars>1000+
interface I {
boolean equals(Object o);
} | 22 |
776 | <gh_stars>100-1000
/*
* Copyright 2019-present HiveMQ GmbH
*
* 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.hivemq.diagnostic.data;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import java.net.NetworkInterface;
import static org.junit.Assert.assertNotNull;
/**
* @author <NAME>
* @since 4.1.0
*/
@SuppressWarnings("NullabilityAnnotations")
public class NetworkInterfaceInformationTest {
private NetworkInterfaceInformation networkInterfaceInformation;
private NetworkInterface networkInterface;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
networkInterface = NetworkInterface.getByName("Does_Not_Exist");
networkInterfaceInformation = new NetworkInterfaceInformation();
}
@Test
public void test_getIsLoopback_failed() {
assertNotNull(networkInterfaceInformation.getIsLoopback(networkInterface));
}
@Test
public void test_getIsP2P_failed() {
assertNotNull(networkInterfaceInformation.getIsP2P(networkInterface));
}
@Test
public void test_getIsUp_failed() {
assertNotNull(networkInterfaceInformation.getIsUp(networkInterface));
}
@Test
public void test_getIsVirtual_failed() {
assertNotNull(networkInterfaceInformation.getIsVirtual(networkInterface));
}
@Test
public void test_getSupportsMulticast_failed() {
assertNotNull(networkInterfaceInformation.getSupportsMulticast(networkInterface));
}
@Test
public void test_getMTU_failed() {
assertNotNull(networkInterfaceInformation.getMTU(networkInterface));
}
@Test
public void test_getMacaddress_failed() {
assertNotNull(networkInterfaceInformation.getMacaddress(networkInterface));
}
}
| 744 |
1,768 | // Copyright (c) 2003 Compaq Corporation. All rights reserved.
// Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved.
package tlc2.tool;
import util.UniqueString;
public class BuiltInOPs implements ToolGlobals {
private static int[] OpCodeTable;
static {
OpCodeTable = new int[200];
/* Operators */
put(OP_aa, OPCODE_aa);
put(OP_bc, OPCODE_bc);
put(OP_be, OPCODE_be);
put(OP_bf, OPCODE_bf);
put(OP_case, OPCODE_case);
put(OP_cp, OPCODE_cp);
put(OP_cl, OPCODE_cl);
put(OP_dl, OPCODE_dl);
put(OP_exc, OPCODE_exc);
put(OP_fa, OPCODE_fa);
put(OP_fc, OPCODE_fc);
put(OP_ite, OPCODE_ite);
put(OP_nrfs, OPCODE_nrfs);
put(OP_pair, OPCODE_pair);
put(OP_rc, OPCODE_rc);
put(OP_rs, OPCODE_rs);
put(OP_rfs, OPCODE_rfs);
put(OP_seq, OPCODE_seq);
put(OP_sa, OPCODE_sa);
put(OP_se, OPCODE_se);
put(OP_sf, OPCODE_sf);
put(OP_soa, OPCODE_soa);
put(OP_sor, OPCODE_sor);
put(OP_sof, OPCODE_sof);
put(OP_sso, OPCODE_sso);
put(OP_tup, OPCODE_tup);
put(OP_te, OPCODE_te);
put(OP_tf, OPCODE_tf);
put(OP_uc, OPCODE_uc);
put(OP_ue, OPCODE_ue);
put(OP_uf, OPCODE_uf);
put(OP_wf, OPCODE_wf);
/* Prefix operators */
put(OP_lnot, OPCODE_lnot);
put(OP_subset, OPCODE_subset);
put(OP_union, OPCODE_union);
put(OP_domain, OPCODE_domain);
put(OP_box, OPCODE_box);
put(OP_diamond, OPCODE_diamond);
put(OP_enabled, OPCODE_enabled);
put(OP_unchanged, OPCODE_unchanged);
/* Infix operators */
put(OP_eq, OPCODE_eq);
put(OP_land, OPCODE_land);
put(OP_lor, OPCODE_lor);
put(OP_implies, OPCODE_implies);
put(OP_cdot, OPCODE_cdot);
put(OP_equiv, OPCODE_equiv);
put(OP_leadto, OPCODE_leadto);
put(OP_arrow, OPCODE_arrow);
put(OP_noteq, OPCODE_noteq);
put(OP_subseteq, OPCODE_subseteq);
put(OP_in, OPCODE_in);
put(OP_notin, OPCODE_notin);
put(OP_setdiff, OPCODE_setdiff);
put(OP_cap, OPCODE_cap);
/***********************************************************************
* The following added by LL on 2 Aug 2007. *
***********************************************************************/
put(OP_nop, OPCODE_nop);
put(OP_cup, OPCODE_cup);
/* Postfix operators */
put(OP_prime, OPCODE_prime);
}
private static void put(UniqueString op, int opcode) {
int loc = op.getTok();
if (loc >= OpCodeTable.length) {
int len1 = loc + 20;
int[] OpCodeTable1 = new int[len1];
for (int i = 0; i < OpCodeTable.length; i++) {
OpCodeTable1[i] = OpCodeTable[i];
}
OpCodeTable = OpCodeTable1;
}
OpCodeTable[loc] = opcode;
}
/* Return the opcode for op. If it is not builtin, return 0. */
public static int getOpCode(UniqueString op) {
int loc = op.getTok();
return (loc < OpCodeTable.length) ? OpCodeTable[loc] : 0;
}
public static int getOpCode(int loc) {
return (loc < OpCodeTable.length) ? OpCodeTable[loc] : 0;
}
public static boolean isTemporal(int opcode) {
return OPCODE_sf <= opcode && opcode <= OPCODE_diamond;
}
public static boolean isAction(int opcode) {
return OPCODE_prime <= opcode && opcode <= OPCODE_cdot;
}
}
| 1,654 |
1,444 | package mage.cards.d;
import mage.MageInt;
import mage.abilities.common.BeginningOfEndStepTriggeredAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.condition.common.MorbidCondition;
import mage.abilities.costs.mana.GenericManaCost;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.DoIfCostPaid;
import mage.abilities.effects.common.continuous.BoostControlledEffect;
import mage.abilities.hint.common.MorbidHint;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.Predicates;
import mage.game.permanent.token.SkeletonToken;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class DeathPriestOfMyrkul extends CardImpl {
private static final FilterCreaturePermanent filter
= new FilterCreaturePermanent("Skeletons, Vampires, and Zombies");
static {
filter.add(Predicates.or(
SubType.SKELETON.getPredicate(),
SubType.VAMPIRE.getPredicate(),
SubType.ZOMBIE.getPredicate()
));
}
public DeathPriestOfMyrkul(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{B}{B}");
this.subtype.add(SubType.TIEFLING);
this.subtype.add(SubType.CLERIC);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Skeletons, Vampires, and Zombies you control get +1/+1.
this.addAbility(new SimpleStaticAbility(new BoostControlledEffect(
1, 1, Duration.WhileOnBattlefield, filter, false
)));
// At the beginning of your end step, if a creature died this turn, you may pay {1}. If you do, create a 1/1 black Skeleton creature token.
this.addAbility(new BeginningOfEndStepTriggeredAbility(
Zone.BATTLEFIELD,
new DoIfCostPaid(new CreateTokenEffect(new SkeletonToken()), new GenericManaCost(1)),
TargetController.YOU, MorbidCondition.instance, false
).addHint(MorbidHint.instance));
}
private DeathPriestOfMyrkul(final DeathPriestOfMyrkul card) {
super(card);
}
@Override
public DeathPriestOfMyrkul copy() {
return new DeathPriestOfMyrkul(this);
}
}
| 925 |
1,796 | <reponame>sameemj14/android-examples
package sample.github.nisrulz.usingretrofit2.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class People {
@SerializedName("name") @Expose private String name;
@SerializedName("height") @Expose private String height;
@SerializedName("mass") @Expose private String mass;
@SerializedName("hair_color") @Expose private String hairColor;
@SerializedName("skin_color") @Expose private String skinColor;
@SerializedName("eye_color") @Expose private String eyeColor;
@SerializedName("birth_year") @Expose private String birthYear;
@SerializedName("gender") @Expose private String gender;
public People(String birthYear, String eyeColor, String gender, String hairColor, String height,
String mass, String name, String skinColor, String url) {
this.birthYear = birthYear;
this.eyeColor = eyeColor;
this.gender = gender;
this.hairColor = hairColor;
this.height = height;
this.mass = mass;
this.name = name;
this.skinColor = skinColor;
}
/**
* @return The name
*/
public String getName() {
return name;
}
/**
* @param name The name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return The height
*/
public String getHeight() {
return height;
}
/**
* @param height The height
*/
public void setHeight(String height) {
this.height = height;
}
/**
* @return The mass
*/
public String getMass() {
return mass;
}
/**
* @param mass The mass
*/
public void setMass(String mass) {
this.mass = mass;
}
/**
* @return The hairColor
*/
public String getHairColor() {
return hairColor;
}
/**
* @param hairColor The hair_color
*/
public void setHairColor(String hairColor) {
this.hairColor = hairColor;
}
/**
* @return The skinColor
*/
public String getSkinColor() {
return skinColor;
}
/**
* @param skinColor The skin_color
*/
public void setSkinColor(String skinColor) {
this.skinColor = skinColor;
}
/**
* @return The eyeColor
*/
public String getEyeColor() {
return eyeColor;
}
/**
* @param eyeColor The eye_color
*/
public void setEyeColor(String eyeColor) {
this.eyeColor = eyeColor;
}
/**
* @return The birthYear
*/
public String getBirthYear() {
return birthYear;
}
/**
* @param birthYear The birth_year
*/
public void setBirthYear(String birthYear) {
this.birthYear = birthYear;
}
/**
* @return The gender
*/
public String getGender() {
return gender;
}
/**
* @param gender The gender
*/
public void setGender(String gender) {
this.gender = gender;
}
} | 972 |
5,422 | <gh_stars>1000+
//
// detail/gcc_arm_fenced_block.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2021 <NAME> (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_GCC_ARM_FENCED_BLOCK_HPP
#define ASIO_DETAIL_GCC_ARM_FENCED_BLOCK_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(__GNUC__) && defined(__arm__)
#include "asio/detail/noncopyable.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
class gcc_arm_fenced_block
: private noncopyable
{
public:
enum half_t { half };
enum full_t { full };
// Constructor for a half fenced block.
explicit gcc_arm_fenced_block(half_t)
{
}
// Constructor for a full fenced block.
explicit gcc_arm_fenced_block(full_t)
{
barrier();
}
// Destructor.
~gcc_arm_fenced_block()
{
barrier();
}
private:
static void barrier()
{
#if defined(__ARM_ARCH_4__) \
|| defined(__ARM_ARCH_4T__) \
|| defined(__ARM_ARCH_5__) \
|| defined(__ARM_ARCH_5E__) \
|| defined(__ARM_ARCH_5T__) \
|| defined(__ARM_ARCH_5TE__) \
|| defined(__ARM_ARCH_5TEJ__) \
|| defined(__ARM_ARCH_6__) \
|| defined(__ARM_ARCH_6J__) \
|| defined(__ARM_ARCH_6K__) \
|| defined(__ARM_ARCH_6Z__) \
|| defined(__ARM_ARCH_6ZK__) \
|| defined(__ARM_ARCH_6T2__)
# if defined(__thumb__)
// This is just a placeholder and almost certainly not sufficient.
__asm__ __volatile__ ("" : : : "memory");
# else // defined(__thumb__)
int a = 0, b = 0;
__asm__ __volatile__ ("swp %0, %1, [%2]"
: "=&r"(a) : "r"(1), "r"(&b) : "memory", "cc");
# endif // defined(__thumb__)
#else
// ARMv7 and later.
__asm__ __volatile__ ("dmb" : : : "memory");
#endif
}
};
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(__GNUC__) && defined(__arm__)
#endif // ASIO_DETAIL_GCC_ARM_FENCED_BLOCK_HPP
| 918 |
1,025 | <filename>src/main/java/com/myblog/lucene/ProductIterator.java
package com.myblog.lucene;
import org.apache.lucene.search.suggest.InputIterator;
import org.apache.lucene.util.BytesRef;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: Zephery
* Time: 2017/7/26 11:50
* Description:
*/
public class ProductIterator implements InputIterator {
private Iterator<Product> productIterator;
private Product currentProduct;
ProductIterator(Iterator<Product> productIterator) {
this.productIterator = productIterator;
}
@Override
public boolean hasContexts() {
return true;
}
/**
* 是否有设置payload信息
*/
@Override
public boolean hasPayloads() {
return true;
}
public Comparator<BytesRef> getComparator() {
return null;
}
@Override
public BytesRef next() {
if (productIterator.hasNext()) {
currentProduct = productIterator.next();
try {
//返回当前Project的name值,把product类的name属性值作为key
return new BytesRef(currentProduct.getName().getBytes("UTF8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Couldn't convert to UTF-8", e);
}
} else {
return null;
}
}
/**
* 将Product对象序列化存入payload
* [这里仅仅是个示例,其实这种做法不可取,一般不会把整个对象存入payload,这样索引体积会很大,浪费硬盘空间]
*/
@Override
public BytesRef payload() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(currentProduct);
out.close();
return new BytesRef(bos.toByteArray());
} catch (IOException e) {
throw new RuntimeException("Well that's unfortunate.");
}
}
/**
* 把产品的销售区域存入context,context里可以是任意的自定义数据,一般用于数据过滤
* Set集合里的每一个元素都会被创建一个TermQuery,你只是提供一个Set集合,至于new TermQuery
* Lucene底层API去做了,但你必须要了解底层干了些什么
*/
@Override
public Set<BytesRef> contexts() {
try {
Set<BytesRef> regions = new HashSet<BytesRef>();
for (String region : currentProduct.getRegions()) {
regions.add(new BytesRef(region.getBytes("UTF8")));
}
return regions;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Couldn't convert to UTF-8");
}
}
/**
* 返回权重值,这个值会影响排序
* 这里以产品的销售量作为权重值,weight值即最终返回的热词列表里每个热词的权重值
* 怎么设计返回这个权重值,发挥你们的想象力吧
*/
public long weight() {
return currentProduct.getNumberSold();
}
} | 1,629 |
14,668 | <gh_stars>1000+
// Copyright 2014 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 UI_GL_GPU_SWITCHING_OBSERVER_H_
#define UI_GL_GPU_SWITCHING_OBSERVER_H_
#include "ui/gl/gl_export.h"
#include "ui/gl/gpu_preference.h"
namespace ui {
class GL_EXPORT GpuSwitchingObserver {
public:
// Called for any observer when the system switches to a different GPU.
virtual void OnGpuSwitched(gl::GpuPreference active_gpu_heuristic) {}
// Called for any observer when a monitor is plugged in.
virtual void OnDisplayAdded() {}
// Called for any observer when a monitor is unplugged.
virtual void OnDisplayRemoved() {}
// Called for any observer when the display metrics changed.
virtual void OnDisplayMetricsChanged() {}
};
} // namespace ui
#endif // UI_GL_GPU_SWITCHING_OBSERVER_H_
| 290 |
631 | <filename>ThirdParty/nlopt/plis.cpp
#include <climits>
#include <cstdlib>
#include <cmath>
#include <string>
#include "luksan.h"
#include <vector>
#include "ThirdParty/rapidjson/document.h"
#include "ThirdParty/rapidjson/writer.h"
#include "ThirdParty/rapidjson/filereadstream.h"
#include "ThirdParty/rapidjson/filewritestream.h"
#include <iostream>
using namespace rapidjson;
#define MAX2(a,b) ((a) > (b) ? (a) : (b))
#define MIN2(a,b) ((a) < (b) ? (a) : (b))
std::vector<GenericStringRef<char>> lbfgsb_save_para_name = {
"nres", "ndec", "nin", "nit","nfg", "nfh" ,
"m","n","x", "f","work", "iters","inew","iold","nevals_p","niters_p" };
void restore_break(stat_common* state, double* x, double* f,
double* work, int* iters, int* inew, int* iold, int* nevals_p, int* niters_p,
std::string cache_file, int m = 20)
{
int64_t i, n, mf;
Document jsonDoc;
FILE* fpin = fopen(cache_file.c_str(), "rb"); // 非Windows平台使用"r"
char readBuffer[16000];
FileReadStream is(fpin, readBuffer, sizeof(readBuffer));
jsonDoc.ParseStream<kParseNanAndInfFlag>(is);
fclose(fpin);
//判断解析从流中读取的字符串是否有错误
if (jsonDoc.HasParseError()) {
std::cout << ("Json Parse error:%d", jsonDoc.GetParseError()) << std::endl; //打印错误编号
}
n = jsonDoc["nf"].GetDouble();
mf = jsonDoc["mf"].GetDouble();
// m = max number of lower-memory BFGS limit, 3 \le m \le 20
int64_t length[3] = { m, n, m * n };
int64_t offset_1 = MAX2(n, n * mf), offset_2 = MAX2(n, mf), offset = 0;
// xl, xu, gf, s
for (i = 0; i < length[1] * 4; i++)
{
work[i] = jsonDoc["work"][i].GetDouble();
}
// xo, go
offset += length[1] * 4;
for (i = 0; i < length[2]; i++)
{
work[i + n * 4] = jsonDoc["work"][i + offset].GetDouble();
work[i + n * 4 + offset_1] = jsonDoc["work"][i + offset + length[2]].GetDouble();
}
// uo, vo
offset += length[2] * 2;
for (i = 0; i < length[0]; i++)
{
work[i + n * 4 + offset_1 * 2] = jsonDoc["work"][i + offset].GetDouble();
work[i + n * 4 + offset_1 * 2 + offset_2] = jsonDoc["work"][i + offset
+ length[0]].GetDouble();
}
// x
for (i = 0; i < length[1]; i++)
{
x[i] = jsonDoc["x"][i].GetDouble();
}
*f = jsonDoc["f"].GetDouble();
*iters = jsonDoc["iters"].GetDouble();
*inew = jsonDoc["inew"].GetDouble();
*iold = jsonDoc["iold"].GetDouble();
*nevals_p = jsonDoc["nevals_p"].GetDouble();
*nevals_p = jsonDoc["niters_p"].GetDouble();
state->nres = jsonDoc["nres"].GetDouble();
state->ndec = jsonDoc["ndec"].GetDouble();
state->nin = jsonDoc["nin"].GetDouble();
state->nit = jsonDoc["nit"].GetDouble();
state->nfg = jsonDoc["nfg"].GetDouble();
state->nfh = jsonDoc["nfh"].GetDouble();
return;
}
void save_break(int64_t n, int64_t mf, stat_common* state, double* x, double f,
double* work, int iters, int inew, int iold, int nevals_p, int niters_p,
std::string cache_file, int m = 20)
{
int64_t i;
// state为19个,数组为3个,最后是可变参数:
// iter, iter_current_num, mode, prev_mode, fcur, fprev, want_grad
Document jsonDoc; //生成一个dom元素Document
Document::AllocatorType& allocator = jsonDoc.GetAllocator(); //获取分配器
jsonDoc.SetObject(); //将当前的Document设置为一个object,也就是说,整个Document是一个Object类型的dom元素
// m = max number of lower-memory BFGS limit, 3 \le m \le 20
int64_t length[3] = { m, n, m * n };
int64_t offset_1 = MAX2(n, n * mf), offset_2 = MAX2(n, mf), offset = 0;
jsonDoc.AddMember("nf", n, allocator);
jsonDoc.AddMember("mf", mf, allocator);
jsonDoc.AddMember("nevals_p", nevals_p, allocator);
jsonDoc.AddMember("niters_p", niters_p, allocator);
// 数组指针读取数据并写入work=xl+xu+gf+s +xo+go +uo+vo
Value work_array(kArrayType);
for (i = 0; i < length[1] * 4; i++)
{
work_array.PushBack(work[i], allocator);
}
for (i = 0; i < length[2]; i++)
{
work_array.PushBack(work[i + n * 4], allocator);
work_array.PushBack(work[i + n * 4 + offset_1], allocator);
}
for (i = 0; i < length[0]; i++)
{
work_array.PushBack(work[i + n * 4 + offset_1 * 2], allocator);
work_array.PushBack(work[i + n * 4 + offset_1 * 2 + offset_1], allocator);
}
jsonDoc.AddMember("work", work_array, allocator);
Value x_array(kArrayType);
for (i = 0; i < length[1]; i++)
{
x_array.PushBack(x[i], allocator);
}
jsonDoc.AddMember("x", x_array, allocator);
jsonDoc.AddMember("f", f, allocator);
jsonDoc.AddMember("iters", iters, allocator);
jsonDoc.AddMember("inew", inew, allocator);
jsonDoc.AddMember("iold", iold, allocator);
double temp_state[6] = { (double)state->nres,(double)state->ndec,(double)state->nin,
(double)state->nit,(double)state->nfg,(double)state->nfh };
for (i = 0; i < 6; i++)
{
jsonDoc.AddMember(lbfgsb_save_para_name[i], temp_state[i], allocator);
}
FILE* fpout = fopen(cache_file.c_str(), "wb"); // 非 Windows 平台使用 "w"
char writeBuffer[8192];
FileWriteStream os(fpout, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream, UTF8<>, UTF8<>,
CrtAllocator, kWriteNanAndInfFlag> writer(os);
jsonDoc.Accept(writer);
fclose(fpout);
}
/* *********************************************************************** */
/* SUBROUTINE PLIS ALL SYSTEMS 01/09/22 */
/* PURPOSE : */
/* GENERAL SUBROUTINE FOR LARGE-SCALE BOX CONSTRAINED MINIMIZATION THAT */
/* USE THE LIMITED MEMORY VARIABLE METRIC METHOD BASED ON THE STRANG */
/* RECURRENCES. */
/* PARAMETERS : */
/* II NF NUMBER OF VARIABLES. */
/* II NB CHOICE OF SIMPLE BOUNDS. NB=0-SIMPLE BOUNDS SUPPRESSED. */
/* NB>0-SIMPLE BOUNDS ACCEPTED. */
/* RI X(NF) VECTOR OF VARIABLES. */
/* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. IX(I)=0-VARIABLE */
/* X(I) IS UNBOUNDED. IX(I)=1-LOWER BOUND XL(I).LE.X(I). */
/* IX(I)=2-UPPER BOUND X(I).LE.XU(I). IX(I)=3-TWO SIDE BOUND */
/* XL(I).LE.X(I).LE.XU(I). IX(I)=5-VARIABLE X(I) IS FIXED. */
/* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. */
/* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. */
/* RO GF(NF) GRADIENT OF THE OBJECTIVE FUNCTION. */
/* RO S(NF) DIRECTION VECTOR. */
/* RU XO(NF) VECTORS OF VARIABLES DIFFERENCE. */
/* RI GO(NF) GRADIENTS DIFFERENCE. */
/* RA UO(NF) AUXILIARY VECTOR. */
/* RA VO(NF) AUXILIARY VECTOR. */
/* RI XMAX MAXIMUM STEPSIZE. */
/* RI TOLX TOLERANCE FOR CHANGE OF VARIABLES. */
/* RI TOLF TOLERANCE FOR CHANGE OF FUNCTION VALUES. */
/* RI TOLB TOLERANCE FOR THE FUNCTION VALUE. */
/* RI TOLG TOLERANCE FOR THE GRADIENT NORM. */
/* RI MINF_EST ESTIMATION OF THE MINIMUM FUNCTION VALUE. */
/* RO GMAX MAXIMUM PARTIAL DERIVATIVE. */
/* RO F VALUE OF THE OBJECTIVE FUNCTION. */
/* II MIT MAXIMUM NUMBER OF ITERATIONS. */
/* II MFV MAXIMUM NUMBER OF FUNCTION EVALUATIONS. */
/* II IEST ESTIMATION INDICATOR. IEST=0-MINIMUM IS NOT ESTIMATED. */
/* IEST=1-MINIMUM IS ESTIMATED BY THE VALUE MINF_EST. */
/* II MF NUMBER OF LIMITED MEMORY STEPS. */
/* IO ITERM VARIABLE THAT INDICATES THE CAUSE OF TERMINATION. */
/* ITERM=1-IF ABS(X-XO) WAS LESS THAN OR EQUAL TO TOLX IN */
/* MTESX (USUALLY TWO) SUBSEQUEBT ITERATIONS. */
/* ITERM=2-IF ABS(F-FO) WAS LESS THAN OR EQUAL TO TOLF IN */
/* MTESF (USUALLY TWO) SUBSEQUEBT ITERATIONS. */
/* ITERM=3-IF F IS LESS THAN OR EQUAL TO TOLB. */
/* ITERM=4-IF GMAX IS LESS THAN OR EQUAL TO TOLG. */
/* ITERM=6-IF THE TERMINATION CRITERION WAS NOT SATISFIED, */
/* BUT THE SOLUTION OBTAINED IS PROBABLY ACCEPTABLE. */
/* ITERM=11-IF NIT EXCEEDED MIT. ITERM=12-IF NFV EXCEEDED MFV. */
/* ITERM=13-IF NFG EXCEEDED MFG. ITERM<0-IF THE METHOD FAILED. */
/* VARIABLES IN COMMON /STAT/ (STATISTICS) : */
/* IO NRES NUMBER OF RESTARTS. */
/* IO NDEC NUMBER OF MATRIX DECOMPOSITION. */
/* IO NIN NUMBER OF INNER ITERATIONS. */
/* IO NIT NUMBER OF ITERATIONS. */
/* IO NFV NUMBER OF FUNCTION EVALUATIONS. */
/* IO NFG NUMBER OF GRADIENT EVALUATIONS. */
/* IO NFH NUMBER OF HESSIAN EVALUATIONS. */
/* SUBPROGRAMS USED : */
/* S PCBS04 ELIMINATION OF BOX CONSTRAINT VIOLATIONS. */
/* S PS1L01 STEPSIZE SELECTION USING LINE SEARCH. */
/* S PYADC0 ADDITION OF A BOX CONSTRAINT. */
/* S PYFUT1 TEST ON TERMINATION. */
/* S PYRMC0 DELETION OF A BOX CONSTRAINT. */
/* S PYTRCD COMPUTATION OF PROJECTED DIFFERENCES FOR THE VARIABLE METRIC */
/* UPDATE. */
/* S PYTRCG COMPUTATION OF THE PROJECTED GRADIENT. */
/* S PYTRCS COMPUTATION OF THE PROJECTED DIRECTION VECTOR. */
/* S MXDRCB BACKWARD PART OF THE STRANG FORMULA FOR PREMULTIPLICATION */
/* OF THE VECTOR X BY AN IMPLICIT BFGS UPDATE. */
/* S MXDRCF FORWARD PART OF THE STRANG FORMULA FOR PREMULTIPLICATION */
/* OF THE VECTOR X BY AN IMPLICIT BFGS UPDATE. */
/* S MXDRSU SHIFT OF COLUMNS OF THE RECTANGULAR MATRICES A AND B. */
/* SHIFT OF ELEMENTS OF THE VECTOR U. THESE SHIFTS ARE USED IN */
/* THE LIMITED MEMORY BFGS METHOD. */
/* S MXUDIR VECTOR AUGMENTED BY THE SCALED VECTOR. */
/* RF MXUDOT DOT PRODUCT OF TWO VECTORS. */
/* S MXUNEG COPYING OF A VECTOR WITH CHANGE OF THE SIGN. */
/* S MXVCOP COPYING OF A VECTOR. */
/* S MXVSCL SCALING OF A VECTOR. */
/* EXTERNAL SUBROUTINES : */
/* SE OBJ COMPUTATION OF THE VALUE OF THE OBJECTIVE FUNCTION. */
/* CALLING SEQUENCE: CALL OBJ(NF,X,FF) WHERE NF IS THE NUMBER */
/* OF VARIABLES, X(NF) IS THE VECTOR OF VARIABLES AND FF IS */
/* THE VALUE OF THE OBJECTIVE FUNCTION. */
/* SE DOBJ COMPUTATION OF THE GRADIENT OF THE OBJECTIVE FUNCTION. */
/* CALLING SEQUENCE: CALL DOBJ(NF,X,GF) WHERE NF IS THE NUMBER */
/* OF VARIABLES, X(NF) IS THE VECTOR OF VARIABLES AND GF(NF) */
/* IS THE GRADIENT OF THE OBJECTIVE FUNCTION. */
/* -- OBJ and DOBJ are replaced by a single function, objgrad, in NLopt */
/* METHOD : */
/* LIMITED MEMORY VARIABLE METRIC METHOD BASED ON THE STRANG */
/* RECURRENCES. */
static void plis_(int* nf, int* nb, double* x, int*
ix, double* xl, double* xu, double* gf, double* s,
double* xo, double* go, double* uo, double* vo,
double* xmax, double* tolx, double* tolf, double*
tolb, double* tolg, nlopt_stopping* stop,
double* minf_est, double* gmax,
double* f, int* mit, int* mfv, int* iest, int* mf,
int* iterm, stat_common* stat_1,
nlopt_func objgrad, void* objgrad_data,
bool restore_flag, std::string save_file_name)
{
/* System generated locals */
int i__1;
double d__1, d__2;
/* Builtin functions */
/* Local variables */
double a, b;
int i__, k, n;
double p = 0, r__;
int kd, ld;
double fo, fp, po, pp, ro, rp;
int kbf, mfg;
int mes, kit;
double alf1, alf2, eta9, par1, par2;
double eps8, eps9;
int mred, iold, nred;
double maxf, dmax__;
int xstop = 0;
int inew = 0;
double told;
int ites;
double rmin, rmax, umax, tolp, tols;
int isys;
int ires1, ires2;
int iterd, mtesf, ntesf;
double gnorm;
int iters, irest, inits, kters, maxst;
double snorm;
int mtesx, ntesx;
ps1l01_state state;
(void)tolb;
/* INITIATION */
/* Parameter adjustments */
--vo;
--uo;
--go;
--xo;
--s;
--gf;
--xu;
--xl;
--ix;
--x;
/* Function Body */
kbf = 0;
if (*nb > 0) {
kbf = 2;
}
stat_1->nres = 0;
stat_1->ndec = 0;
stat_1->nin = 0;
stat_1->nit = 0;
stat_1->nfg = 0;
stat_1->nfh = 0;
isys = 0;
ites = 1;
mtesx = 2;
mtesf = 2;
inits = 2;
*iterm = 0;
iterd = 0;
iters = 2;
kters = 3;
irest = 0;
ires1 = 999;
ires2 = 0;
mred = 10;
mes = 4;
eta9 = 1e120;
eps8 = 1.;
eps9 = 1e-8;
alf1 = 1e-10;
alf2 = 1e10;
rmax = eta9;
dmax__ = eta9;
maxf = 1e20;
if (*iest <= 0) {
*minf_est = -HUGE_VAL; /* changed from -1e60 by SGJ */
}
if (*iest > 0) {
*iest = 1;
}
if (*xmax <= 0.) {
*xmax = 1e16;
}
if (*tolx <= 0.) {
*tolx = 1e-16;
}
if (*tolf <= 0.) {
*tolf = 1e-14;
}
if (*tolg <= 0.) {
*tolg = 1e-8; /* SGJ: was 1e-6, but this sometimes stops too soon */
}
#if 0
/* removed by SGJ: this check prevented us from using minf_max <= 0,
which doesn't make sense. Instead, if you don't want to have a
lower limit, you should set minf_max = -HUGE_VAL */
if (*tolb <= 0.) {
*tolb = *minf_est + 1e-16;
}
#endif
told = 1e-4;
tols = 1e-4;
tolp = .8;
/* changed by SGJ: default is no limit (INT_MAX) on # iterations/fevals */
if (*mit <= 0) {
*mit = INT_MAX;
}
if (*mfv <= 0) {
*mfv = INT_MAX;
}
mfg = *mfv;
kd = 1;
ld = -1;
kit = -(ires1 * *nf + ires2);
fo = *minf_est;
iold = 0;
if (restore_flag)
{
if (fopen(save_file_name.c_str(), "rb") == NULL)
{
restore_break(stat_1, x + 1, f, xl + 1, &iters, &inew, &iold, stop->nevals_p, stop->niters_p, save_file_name);
}
else
{
std::cout << "Cannot find the restore file!" << std::endl;
}
goto restore_point;
}
/* INITIAL OPERATIONS WITH SIMPLE BOUNDS */
if (kbf > 0) {
i__1 = *nf;
for (i__ = 1; i__ <= i__1; ++i__) {
if ((ix[i__] == 3 || ix[i__] == 4) && xu[i__] <= xl[i__]) {
xu[i__] = xl[i__];
ix[i__] = 5;
}
else if (ix[i__] == 5 || ix[i__] == 6) {
xl[i__] = x[i__];
xu[i__] = x[i__];
ix[i__] = 5;
}
/* L2: */
}
luksan_pcbs04__(nf, &x[1], &ix[1], &xl[1], &xu[1], &eps9, &kbf);
luksan_pyadc0__(nf, &n, &x[1], &ix[1], &xl[1], &xu[1], &inew);
}
if (*iterm != 0) {
goto L11190;
}
*f = objgrad(*nf, &x[1], &gf[1], objgrad_data);
++* (stop->nevals_p);
++stat_1->nfg;
if (nlopt_stop_time(stop)) { *iterm = 100; goto L11190; }
L11120:
++* (stop->niters_p);
save_break(*nf, *mf, stat_1, x + 1, *f, xl + 1, iters, inew, iold, *stop->nevals_p, *stop->niters_p, save_file_name);
if (nlopt_stop_iters(stop)) { *iterm = 13; goto L11190; }
restore_point:
luksan_pytrcg__(nf, nf, &ix[1], &gf[1], &umax, gmax, &kbf, &iold);
luksan_pyfut1__(nf, f, &fo, &umax, gmax, xstop, stop, tolg,
&kd, &stat_1->nit, &kit, mit, &stat_1->nfg, &mfg,
&ntesx, &mtesx, &ntesf, &mtesf, &ites, &ires1, &ires2, &irest, &
iters, iterm);
if (*iterm != 0) {
goto L11190;
}
if (nlopt_stop_time(stop)) { *iterm = 100; goto L11190; }
if (kbf > 0 && rmax > 0.) {
luksan_pyrmc0__(nf, &n, &ix[1], &gf[1], &eps8, &umax, gmax, &rmax, &
iold, &irest);
}
L11130:
/* DIRECTION DETERMINATION */
gnorm = sqrt(luksan_mxudot__(nf, &gf[1], &gf[1], &ix[1], &kbf));
if (irest != 0) {
goto L12620;
}
/* Computing MIN */
i__1 = stat_1->nit - kit;
k = MIN2(i__1, *mf);
if (k <= 0) {
irest = MAX2(irest, 1);
goto L12620;
}
/* DETERMINATION OF THE PARAMETER B */
b = luksan_mxudot__(nf, &xo[1], &go[1], &ix[1], &kbf);
if (b <= 0.) {
irest = MAX2(irest, 1);
goto L12620;
}
uo[1] = 1. / b;
luksan_mxuneg__(nf, &gf[1], &s[1], &ix[1], &kbf);
luksan_mxdrcb__(nf, &k, &xo[1], &go[1], &uo[1], &vo[1], &s[1], &ix[1], &
kbf);
a = luksan_mxudot__(nf, &go[1], &go[1], &ix[1], &kbf);
if (a > 0.) {
d__1 = b / a;
luksan_mxvscl__(nf, &d__1, &s[1], &s[1]);
}
luksan_mxdrcf__(nf, &k, &xo[1], &go[1], &uo[1], &vo[1], &s[1], &ix[1], &
kbf);
snorm = sqrt(luksan_mxudot__(nf, &s[1], &s[1], &ix[1], &kbf));
/* Computing MIN */
i__1 = k + 1;
k = MIN2(i__1, *mf);
luksan_mxdrsu__(nf, &k, &xo[1], &go[1], &uo[1]);
L12620:
iterd = 0;
if (irest != 0) {
/* STEEPEST DESCENT DIRECTION */
luksan_mxuneg__(nf, &gf[1], &s[1], &ix[1], &kbf);
snorm = gnorm;
if (kit < stat_1->nit) {
++stat_1->nres;
kit = stat_1->nit;
}
else {
*iterm = -10;
if (iters < 0) {
*iterm = iters - 5;
}
}
}
/* TEST ON DESCENT DIRECTION AND PREPARATION OF LINE SEARCH */
if (kd > 0) {
p = luksan_mxudot__(nf, &gf[1], &s[1], &ix[1], &kbf);
}
if (iterd < 0) {
*iterm = iterd;
}
else {
/* TEST ON DESCENT DIRECTION */
if (snorm <= 0.) {
irest = MAX2(irest, 1);
}
else if (p + told * gnorm * snorm <= 0.) {
irest = 0;
}
else {
/* UNIFORM DESCENT CRITERION */
irest = MAX2(irest, 1);
}
if (irest == 0) {
/* PREPARATION OF LINE SEARCH */
nred = 0;
rmin = alf1 * gnorm / snorm;
/* Computing MIN */
d__1 = alf2 * gnorm / snorm, d__2 = *xmax / snorm;
rmax = MIN2(d__1, d__2);
}
}
if (*iterm != 0) {
goto L11190;
}
if (nlopt_stop_time(stop)) { *iterm = 100; goto L11190; }
if (irest != 0) {
goto L11130;
}
luksan_pytrcs__(nf, &x[1], &ix[1], &xo[1], &xl[1], &xu[1], &gf[1], &go[1],
&s[1], &ro, &fp, &fo, f, &po, &p, &rmax, &eta9, &kbf);
if (rmax == 0.) {
goto L11175;
}
L11170:
luksan_ps1l01__(&r__, &rp, f, &fo, &fp, &p, &po, &pp, minf_est, &maxf, &rmin,
&rmax, &tols, &tolp, &par1, &par2, &kd, &ld, &stat_1->nit, &kit, &
nred, &mred, &maxst, iest, &inits, &iters, &kters, &mes,
&isys, &state);
if (isys == 0) {
goto L11174;
}
luksan_mxudir__(nf, &r__, &s[1], &xo[1], &x[1], &ix[1], &kbf);
luksan_pcbs04__(nf, &x[1], &ix[1], &xl[1], &xu[1], &eps9, &kbf);
*f = objgrad(*nf, &x[1], &gf[1], objgrad_data);
++* (stop->nevals_p);
++stat_1->nfg;
p = luksan_mxudot__(nf, &gf[1], &s[1], &ix[1], &kbf);
goto L11170;
L11174:
if (iters <= 0) {
r__ = 0.;
*f = fo;
p = po;
luksan_mxvcop__(nf, &xo[1], &x[1]);
luksan_mxvcop__(nf, &go[1], &gf[1]);
irest = MAX2(irest, 1);
ld = kd;
goto L11130;
}
luksan_pytrcd__(nf, &x[1], &ix[1], &xo[1], &gf[1], &go[1], &r__, f, &fo, &
p, &po, &dmax__, &kbf, &kd, &ld, &iters);
xstop = nlopt_stop_dx(stop, &x[1], &xo[1]);
L11175:
if (kbf > 0) {
luksan_mxvine__(nf, &ix[1]);
luksan_pyadc0__(nf, &n, &x[1], &ix[1], &xl[1], &xu[1], &inew);
}
goto L11120;
L11190:
return;
} /* plis_ */
/* NLopt wrapper around plis_, handling dynamic allocation etc. */
nlopt_result luksan_plis(int n, nlopt_func f, void* f_data,
const double* lb, const double* ub, /* bounds */
double* x, /* in: initial guess, out: minimizer */
double* minf,
nlopt_stopping* stop,
int mf, bool restore_flag,
std::string save_file_name) /* subspace dimension, 0 for default */
{
int i, * ix, nb = 1;
double* work, * xl, * xu, * xo, * gf, * s, * go, * uo, * vo;
double gmax, minf_est;
double xmax = 0; /* no maximum */
double tolg = 0; /* default gradient tolerance */
int iest = 0; /* we have no estimate of min function value */
int mit = stop->maxiter; /* default no limit on #iterations */
int mfv = stop->maxeval;
stat_common stat;
int iterm;
ix = (int*)malloc(sizeof(int) * n);
if (!ix) return nlopt_result::NLOPT_OUT_OF_MEMORY;
if (mf <= 0) {
mf = MAX2(MEMAVAIL / n, 10);
if (stop->maxeval && stop->maxeval <= mf)
mf = MAX2(stop->maxeval, 1);
}
retry_alloc:
work = (double*)malloc(sizeof(double) * ((uint64_t)n * 4 + MAX2((uint64_t)n, (uint64_t)n * mf) * 2 +
MAX2((uint64_t)n, mf) * 2));
if (!work) {
if (mf > 0) {
mf = 0; /* allocate minimal memory */
goto retry_alloc;
}
free(ix);
return nlopt_result::NLOPT_OUT_OF_MEMORY;
}
xl = work; xu = xl + n; gf = xu + n; s = gf + n;
xo = s + n; go = xo + MAX2(n, n * mf);
uo = go + MAX2(n, n * mf); vo = uo + MAX2(n, mf);
for (i = 0; i < n; ++i) {
int lbu = lb[i] <= -0.99 * HUGE_VAL; /* lb unbounded */
int ubu = ub[i] >= 0.99 * HUGE_VAL; /* ub unbounded */
ix[i] = 3;
xl[i] = lb[i];
xu[i] = ub[i];
}
/* ? xo does not seem to be initialized in the
original Fortran code, but it is used upon
input to plis if mf > 0 ... perhaps ALLOCATE initializes
arrays to zero by default? */
memset(xo, 0, sizeof(double) * MAX2(n, n * mf));
plis_(&n, &nb, x, ix, xl, xu,
gf, s, xo, go, uo, vo,
&xmax,
/* fixme: pass tol_rel and tol_abs and use NLopt check */
&stop->xtol_rel,
&stop->ftol_rel,
&stop->minf_max,
&tolg,
stop,
&minf_est, &gmax,
minf,
&mit, &mfv,
&iest,
&mf,
&iterm, &stat,
f, f_data, restore_flag,
save_file_name);
free(work);
free(ix);
switch (iterm) {
case 1: return nlopt_result::NLOPT_XTOL_REACHED;
case 2: return nlopt_result::NLOPT_FTOL_REACHED;
case 3: return nlopt_result::NLOPT_MINF_MAX_REACHED;
case 4: return nlopt_result::NLOPT_SUCCESS; /* gradient tolerance reached */
case 6: return nlopt_result::NLOPT_SUCCESS;
case 12: return nlopt_result::NLOPT_MAXEVAL_REACHED;
case 13: return nlopt_result::NLOPT_MAXITER_REACHED;
case 100: return nlopt_result::NLOPT_MAXTIME_REACHED;
case -999: return nlopt_result::NLOPT_FORCED_STOP;
default: return nlopt_result::NLOPT_FAILURE;
}
}
| 11,553 |
839 | <reponame>kimjand/cxf
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.transport.http.spring;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
import org.apache.cxf.configuration.spring.AbstractBeanDefinitionParser;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
public class HttpDestinationBeanDefinitionParser
extends AbstractBeanDefinitionParser {
private static final String HTTP_NS =
"http://cxf.apache.org/transports/http/configuration";
@Override
public void doParse(Element element, ParserContext ctc, BeanDefinitionBuilder bean) {
bean.setAbstract(true);
mapElementToJaxbProperty(element, bean,
new QName(HTTP_NS, "server"), "server");
mapElementToJaxbProperty(element, bean,
new QName(HTTP_NS, "fixedParameterOrder"),
"fixedParameterOrder");
mapElementToJaxbProperty(element, bean,
new QName(HTTP_NS, "contextMatchStrategy"),
"contextMatchStrategy");
}
@Override
protected String getJaxbPackage() {
return "org.apache.cxf.transports.http.configuration";
}
@Override
protected Class<?> getBeanClass(Element arg0) {
return AbstractHTTPDestination.class;
}
}
| 766 |
1,025 | <filename>Core Data Editor/Core Data Editor/CDEOrderedRelationshipRequestDataCoordinator.h
#import "CDERequestDataCoordinator.h"
@interface CDEOrderedRelationshipRequestDataCoordinator : CDERequestDataCoordinator
@end
| 68 |
480 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.optimizer.view;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelInput;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rel.type.RelDataTypeFieldImpl;
import org.apache.calcite.sql.type.SqlTypeName;
import java.util.LinkedList;
import java.util.List;
public class InformationSchemaInnodbBufferPageLru extends VirtualView {
public InformationSchemaInnodbBufferPageLru(RelOptCluster cluster, RelTraitSet traitSet) {
super(cluster, traitSet, VirtualViewType.INNODB_BUFFER_PAGE_LRU);
}
public InformationSchemaInnodbBufferPageLru(RelInput relInput) {
super(relInput);
}
@Override
protected RelDataType deriveRowType() {
final RelDataTypeFactory typeFactory = getCluster().getTypeFactory();
List<RelDataTypeFieldImpl> columns = new LinkedList<>();
columns.add(new RelDataTypeFieldImpl("POOL_ID", 0, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("LRU_POSITION", 1, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("SPACE", 2, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("PAGE_NUMBER", 3, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("PAGE_TYPE", 4, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("FLUSH_TYPE", 5, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("FIX_COUNT", 6, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("IS_HASHED", 7, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("NEWEST_MODIFICATION", 8, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("OLDEST_MODIFICATION", 9, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("ACCESS_TIME", 10, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("TABLE_NAME", 11, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("INDEX_NAME", 12, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("NUMBER_RECORDS", 13, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("DATA_SIZE", 14, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("COMPRESSED_SIZE", 15, typeFactory.createSqlType(SqlTypeName.BIGINT)));
columns.add(new RelDataTypeFieldImpl("COMPRESSED", 16, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("IO_FIX", 17, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("IS_OLD", 18, typeFactory.createSqlType(SqlTypeName.VARCHAR)));
columns.add(new RelDataTypeFieldImpl("FREE_PAGE_CLOCK", 19, typeFactory.createSqlType(SqlTypeName.BIGINT)));
return typeFactory.createStructType(columns);
}
}
| 1,431 |
3,285 | <filename>python/oneflow/nn/modules/moving_average_min_max_observer.py
"""
Copyright 2020 The OneFlow 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.
"""
import numpy as np
import oneflow as flow
from oneflow.framework.tensor import register_tensor_op
from oneflow.nn.module import Module
class MovingAverageMinMaxObserver(Module):
"""
Compute the quantization parameters based on the moving average of the input tensor's min and max values.
First compute the moving\\_max and moving\\_min value of input tensor:
if quantization_scheme == "symmetric":
.. math::
& moving\\_max = moving\\_max * momentum + |max(input)| * (1 - momentum)
& moving\\_min = moving\\_max
elif quantization_scheme == "affine":
.. math::
& moving\\_max = moving\\_max * momentum + max(input) * (1 - momentum)
& moving\\_min = moving\\_min * momentum + min(input) * (1 - momentum)
The moving average of min and max values are initialized as the first batch of input `Blob`'s min and max.
Then compute the scale and zero_point with the following equations:
if quantization_scheme == "symmetric":
.. math::
& denom = 2^{quantization\\_to\\_bit - 1} - 1
& scale = moving\\_max / denom
& zero\\_point = 0
elif quantization_scheme == "affine":
.. math::
& denom = 2^{quantization\\_to\\_bit} - 1
& scale = (moving\\_max - moving\\_min) / denom
& zero\\_point = -moving\\_min / scale
Note:
``current_train_step`` can be directly assigned to an optimizer(eg.SGD) step.
Args:
training (bool): Is the model in training state. Defaults to False.
quantization_bit (int): Quantize input to uintX / intX, X can be in range [2, 8]. Defaults to 8.
quantization_scheme (str): "symmetric" or "affine", quantize to signed / unsigned integer. Defaults to "symmetric".
quantization_formula (str): Support "google" or "cambricon".
momentum (float): Smoothing parameter for exponential moving average operation. Defaults to 0.95.
Returns:
Tuple[oneflow.Tensor, oneflow.Tensor]: The scale and zero_point of input tensor.
For example:
.. code-block:: python
>>> import numpy as np
>>> import oneflow as flow
>>> weight = (np.random.random((2, 3, 4, 5)) - 0.5).astype(np.float32)
>>> input_tensor = flow.tensor(
... weight, dtype=flow.float32
... )
>>> current_train_step_tensor = flow.tensor(
... np.zeros((1,)).astype(np.float32),
... dtype=flow.int64,
... )
>>> momentum = 0.95
>>> quantization_bit = 8
>>> quantization_scheme = "symmetric"
>>> quantization_formula = "google"
>>> moving_average_min_max_observer = flow.nn.MovingAverageMinMaxObserver(training=True, quantization_formula=quantization_formula,
... stop_update_after_iters=1, quantization_bit=quantization_bit,
... quantization_scheme=quantization_scheme, momentum=momentum,
... )
>>> (scale, zero_point) = moving_average_min_max_observer(
... input_tensor,
... current_train_step_tensor,
... )
"""
def __init__(
self,
training: bool = False,
quantization_formula: str = "google",
stop_update_after_iters: int = 0,
quantization_bit: int = 8,
quantization_scheme: str = "symmetric",
momentum: float = 0,
) -> None:
super().__init__()
self.training = training
self.quantization_formula = quantization_formula
self.stop_update_after_iters = stop_update_after_iters
self.quantization_bit = quantization_bit
self.quantization_scheme = quantization_scheme
self.momentum = momentum
if training == True:
self.register_buffer("moving_max", flow.Tensor(1))
self.register_buffer("moving_min", flow.Tensor(1))
else:
self.register_parameter("moving_max", None)
self.register_parameter("moving_min", None)
self.reset_running_stats()
def reset_running_stats(self) -> None:
if self.training:
self.moving_max.fill_(0)
self.moving_min.fill_(0)
def forward(self, input, current_train_step):
return flow._C.moving_average_min_max_observer(
input,
current_train_step,
self.moving_max,
self.moving_min,
self.training,
self.quantization_formula,
self.stop_update_after_iters,
self.quantization_bit,
self.quantization_scheme,
self.momentum,
)
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
| 2,441 |
640 | /*
* CP/M GSX based graphics libraries
*
* putc_gsx()
* use with "-pragma-redirect=fputc_cons=_putc_gsx"
*
* <NAME> - 2021
*
* $Id: putc_gsx.c $
*/
#include <cpm.h>
#include <string.h>
//#include <graphics.h>
extern void __LIB__ putc_gsx(int chr);
extern void __LIB__ clg();
extern int gsx_maxx;
extern int gsx_maxy;
int putc_gsx_xc=0;
int putc_gsx_yc=8;
/* Clear Graphics */
void putc_gsx(int chr)
{
if (chr==12) {
putc_gsx_xc=0;
putc_gsx_yc=8;
clg();
return(0);
}
// CR
if ((chr==10)||(chr==13)) {
putc_gsx_xc=0;
putc_gsx_yc += 9;
return(0);
}
// Backspace
if (chr==8) {
if (putc_gsx_xc >= 0) putc_gsx_xc-=8;
gios_put_text(gsx_xscale(putc_gsx_xc),gsx_yscale(putc_gsx_yc)," ");
return(0);
}
gios_put_text(gsx_xscale(putc_gsx_xc),gsx_yscale(putc_gsx_yc),&chr);
putc_gsx_xc += 8;
if (putc_gsx_xc>gsx_maxx) {
putc_gsx_xc = 0;
putc_gsx_yc += 9;
}
}
| 515 |
2,062 | import strawberry
class SampleClass:
def __init__(self, schema):
self.schema = schema
@strawberry.type
class User:
name: str
age: int
@strawberry.type
class Query:
@strawberry.field
def user(self) -> User:
return User(name="Patrick", age=100)
schema = strawberry.Schema(query=Query)
sample_instance = SampleClass(schema)
not_a_schema = 42
| 149 |
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.
#include "chrome/browser/notifications/scheduler/test/fake_clock.h"
namespace notifications {
namespace test {
// static
base::Time FakeClock::GetTime(const char* time_str) {
base::Time time;
bool success = base::Time::FromString(time_str, &time);
DCHECK(success);
return time;
}
FakeClock::FakeClock() : time_mocked_(false) {}
FakeClock::~FakeClock() = default;
void FakeClock::SetNow(const char* time_str) {
base::Time now = GetTime(time_str);
SetNow(now);
}
void FakeClock::SetNow(const base::Time& time) {
time_ = time;
time_mocked_ = true;
}
void FakeClock::Reset() {
time_mocked_ = false;
}
base::Time FakeClock::Now() const {
return time_mocked_ ? time_ : base::Time::Now();
}
} // namespace test
} // namespace notifications
| 310 |
651 | #ifndef MLPCELL_F32
#define MLPCELL_F32
#include "mc_funcs.h"
#define PCL_ASSERT(cond, x...) do { if(!(cond)) { printf(x); fflush(stdout); exit(1); } } while(0)
#define DECL_VLA_PTR(type, name, dims, ptr) type (*name)dims = (type (*)dims)ptr
#define DECL_VLA_PTR_CHECK_VAR(var, type, name, dims, ptr) type (*name)dims = (var > 0) ? (type (*)dims)ptr : NULL
#define DECL_VLA_PTR_CHECK_COND(cond, type, name, dims, ptr) type (*name)dims = cond ? (type (*)dims)ptr : NULL
#define DECL_VLA_PTR_CHECK_COND_VAR(cond, var, type, name, dims, ptr) type (*name)dims = (cond && var > 0) ? (type (*)dims)ptr : NULL
#define DECL_VLA_PTR_PT(type, name, dims, t) type (*name)dims = (type (*)dims)(t.data_ptr<type>())
#define DECL_VLA_PTR_PT_CHECK_COND(cond, type, name, dims, t) type (*name)dims = cond ? (type (*)dims)(t.data_ptr<type>()) : NULL
#define DECL_VLA_PTR_NPT(newtype, type, name, dims, t) newtype (*name)dims = (newtype (*)dims)(t.data_ptr<type>())
#define DECL_VLA_PTR_NPT_CHECK_COND(cond, newtype, type, name, dims, t) newtype (*name)dims = cond ? (newtype (*)dims)(t.data_ptr<type>()) : NULL
#define LIBXSMM_ALIGNDOWN(N, A) ((N) & ~((A)-1))
//--------------------------------------norm_to_normT-----------------------------------------------------
//
void norm_to_normT_32b(float* in, float* out, int N, int M)
{
libxsmm_meltw_unary_param trans_param;
trans_param.in.primary = (void*)in;
trans_param.out.primary = (void*)out;
libxsmm_meltwfunction_unary trans_kernel = libxsmm_dispatch_meltw_unary(M, N, &M, &N, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_kernel == NULL ) {
fprintf( stderr, "JIT for NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
trans_kernel( &trans_param );
}
// ----------------------------------------------------------------------------------------------------------------
inline void colbcast_f32_copy(int N, int M, libxsmm_meltw_unary_param *params)
{
libxsmm_meltw_unary_flags unary_flags = LIBXSMM_MELTW_FLAG_UNARY_BCAST_COL;
libxsmm_meltw_unary_type unary_type = LIBXSMM_MELTW_TYPE_UNARY_IDENTITY;
libxsmm_meltwfunction_unary kernel = libxsmm_dispatch_meltw_unary(M, N, NULL, NULL, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, unary_flags, unary_type);
if ( kernel == NULL )
{
fprintf( stderr, "JIT for bf16 to b16 broadcast copy failed. Bailing...!\n");
exit(-1);
}
kernel(params);
}
inline void dropout_f32(long N, long M, libxsmm_meltw_unary_param *params, libxsmm_meltw_unary_flags flags)
{
libxsmm_meltwfunction_unary dropout_kernel = libxsmm_dispatch_meltw_unary(M, N, NULL, NULL, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, flags, LIBXSMM_MELTW_TYPE_UNARY_DROPOUT);
if ( dropout_kernel == NULL ) {
fprintf( stderr, "JIT for DROPOUT TPP. Bailing...!\n");
exit(-1);
}
dropout_kernel( params );
}
inline void dropout_bwd_f32(long N, long M, libxsmm_meltw_unary_param *params, libxsmm_meltw_unary_flags flags)
{
libxsmm_meltwfunction_unary dropout_kernel = libxsmm_dispatch_meltw_unary(M, N, NULL, NULL, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, flags, LIBXSMM_MELTW_TYPE_UNARY_DROPOUT_INV);
if ( dropout_kernel == NULL ) {
fprintf( stderr, "JIT for DROPOUT TPP. Bailing...!\n");
exit(-1);
}
dropout_kernel( params );
}
inline void brgemm_f32_f32(long n, long m, long k, long stride_b, long stride_a, float *B_, float *A_, float *C, long count, const float beta = 1.0, const char b_trans='n', const char a_trans='n')
{
const float alpha = 1.0;
float *A = A_;
float *B = B_;
unsigned long long l_br = count;
int flags = LIBXSMM_GEMM_FLAGS('n', b_trans);
// Query or JIT-generate reduction kernel; returns NULL if JIT is not supported (bf16 inputs, fp32-accumulate internally, bf16 outputs). *
libxsmm_smmfunction_reducebatch_strd kernel = libxsmm_smmdispatch_reducebatch_strd(m, n, k, stride_a*sizeof(float), stride_b*sizeof(float), NULL, NULL, NULL, &alpha, &beta, &flags, NULL);
PCL_ASSERT(kernel, "Null brgemm bf16 kernel\n");
kernel(A, B, C, &l_br);
}
inline void delbias_f32(int N, int M, int LD_N, int LD_M, libxsmm_meltw_unary_param *delbias_params)
{
libxsmm_meltw_unary_flags unary_flags = LIBXSMM_MELTW_FLAG_UNARY_REDUCE_COLS;
libxsmm_meltw_unary_type unary_type = LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X_OP_ADD_NCNC_FORMAT;
libxsmm_meltwfunction_unary delbias_kernel = libxsmm_dispatch_meltw_unary(M, N, (libxsmm_blasint*)&LD_M, (libxsmm_blasint*)&LD_N, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, unary_flags, unary_type);
if (delbias_kernel == NULL ) {
printf("Could not create f32 delbias kernel.. bailing\n");
exit(-1);
}
delbias_kernel(delbias_params);
}
inline void add_f32_f32(int N, int M, libxsmm_meltw_binary_param *binary_param)
{
libxsmm_meltw_binary_type binary_type = LIBXSMM_MELTW_TYPE_BINARY_ADD;
libxsmm_meltw_binary_flags binary_flags = LIBXSMM_MELTW_FLAG_BINARY_NONE;
libxsmm_meltwfunction_binary add_kernel = libxsmm_dispatch_meltw_binary(M, N, NULL, NULL, NULL, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, binary_flags, binary_type);
if ( add_kernel == NULL ){
fprintf( stderr, "JIT for BINARY TPP. Bailing...!\n");
exit(-1);
}
add_kernel(binary_param);
}
inline void relu_fwd_f32(long N, long M, libxsmm_meltw_unary_param *params)
{
libxsmm_meltw_unary_flags unary_flags = LIBXSMM_MELTW_FLAG_UNARY_BITMASK_2BYTEMULT;
libxsmm_meltwfunction_unary relu_kernel = libxsmm_dispatch_meltw_unary(M, N, NULL, NULL, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, unary_flags, LIBXSMM_MELTW_TYPE_UNARY_RELU);
if ( relu_kernel == NULL ) {
fprintf( stderr, "JIT for ReLU TPP. Bailing...!\n");
exit(-1);
}
relu_kernel( params );
}
inline void relu_bwd_f32(long N, long M, libxsmm_meltw_unary_param *params)
{
libxsmm_meltw_unary_flags unary_flags = LIBXSMM_MELTW_FLAG_UNARY_BITMASK_2BYTEMULT;
libxsmm_meltwfunction_unary relu_kernel = libxsmm_dispatch_meltw_unary(M, N, NULL, NULL, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, unary_flags, LIBXSMM_MELTW_TYPE_UNARY_RELU_INV);
if ( relu_kernel == NULL ) {
fprintf( stderr, "JIT for ReLU TPP. Bailing...!\n");
exit(-1);
}
relu_kernel( params );
}
class MLPCell_F32
{
public:
MLPCell_F32(int N, int C, int K, int bn, int bc, int bk, bool bias, bool skip, int act, bool norm, float p, bool train)
{
pN = N;
pC = C;
pK = K;
pbn = bn;
pbc = bc;
pbk = bk;
pbias = bias;
pskip = skip;
pact = act;
pnorm = norm;
pp = p;
ptrain = train;
//printf("MLPCell: N = %d, C = %d, K = %d, bf = %d, bias = %d, skip = %d, act = %d, norm = %d, dropout prob = %.2f train = %d\n", N, C, K, bias, skip, act, norm, p, train);
}
std::vector<at::Tensor> fwd(std::vector<at::Tensor> inputs)
{
long bn = pbn;
long bc = pbc;
long bk = pbk;
long nn = pN/bn;
long nc = pC;
long nk = pK;
long rn = pN % bn;
long in_off = nn*nc*bn*bc;
long out_off = nn*nk*bn*bk;
long C = nc*bc;
long K = nk*bk;
// std::cout << "F32--------------> " << std::endl;
libxsmm_meltw_unary_param copy_params;
libxsmm_meltw_unary_param cvt_params;
libxsmm_meltw_unary_param relu_params;
libxsmm_meltw_unary_param dropout_params;
libxsmm_meltw_unary_flags dropout_flags = LIBXSMM_MELTW_FLAG_UNARY_BITMASK_2BYTEMULT;
libxsmm_meltw_binary_param add_params;
libxsmm_meltw_binary_flags binary_flags = LIBXSMM_MELTW_FLAG_BINARY_NONE;
libxsmm_meltw_binary_type binary_type = LIBXSMM_MELTW_TYPE_BINARY_ADD;
int i=0;
at::Tensor t_input_l = inputs[i++];
at::Tensor t_input_r = inputs[i++];
at::Tensor t_weights_l = inputs[i++];
at::Tensor t_weights_r = inputs[i++];
at::Tensor t_bias_l = inputs[i++];
at::Tensor t_bias_r = inputs[i++];
at::Tensor t_output = t_input_l.new_empty({pN, K});
int dd = (bk % 32 == 0) ? bk/32 : bk/32 + 1;
at::Tensor t_dropout_mask_bN, t_dropout_mask_rN;
if(ptrain && pp > 0)
{
int size = nn*nk*bn*bk;
t_dropout_mask_bN = at::empty(size, torch::TensorOptions().dtype(torch::kByte));
if(rn > 0)
{
size = nk*rn*bk;
t_dropout_mask_rN = at::empty(size, torch::TensorOptions().dtype(torch::kByte));
}
}
__mmask32 (*dropout_mask_bN)[nk][bn][dd] = (ptrain && pp > 0) ? (__mmask32 (*)[nk][bn][dd])(t_dropout_mask_bN.data_ptr()) : NULL;
__mmask32 (*dropout_mask_rN)[nk][rn][dd] = (ptrain && pp > 0 && rn > 0) ? (__mmask32 (*)[nk][rn][dd])(t_dropout_mask_rN.data_ptr()) : NULL;
int rd = (bk % 32 == 0) ? bk/32 : bk/32 + 1;
at::Tensor t_relumask_bN, t_relumask_rN;
if(pact==1)
{
int size = nn*nk*bn*bk;
t_relumask_bN = at::empty(size, torch::TensorOptions().dtype(torch::kByte));
if(rn > 0)
{
size = nk*rn*bk;
t_relumask_rN = at::empty(size, torch::TensorOptions().dtype(torch::kByte));
}
}
__mmask32 (*relumask_bN)[nk][bn][rd] = pact==1 ? (__mmask32 (*)[nk][bn][rd])(t_relumask_bN.data_ptr()) : NULL;
__mmask32 (*relumask_rN)[nk][rn][rd] = (pact==1 && rn > 0) ? (__mmask32 (*)[nk][rn][rd])(t_relumask_rN.data_ptr()) : NULL;
int threads = 1;
#ifdef _OPENMP
threads = omp_get_max_threads();
#endif
long wts = nk*nc*bk*bc;
long in_bn = threads*nc*bn*bc;
long in_rn = nc*rn*bc;
long out_bn = threads*nk*bn*bk;
long out_rn = nk*rn*bk;
long scratch_size;
if(pskip)
scratch_size = (wts*4 + in_bn*2 + in_rn*2 + out_bn*3 + out_rn*3)*sizeof(float);
else
scratch_size = (wts*2 + in_bn + in_rn + out_bn + out_rn)*sizeof(float);
void *scratch = libxsmm_aligned_malloc(scratch_size, 2097152);
float *t_wt_l = (float*)scratch;
float *t_tr_wt_l = t_wt_l + wts;
float *t_input_bN_l = t_tr_wt_l + wts;
float *t_output_bN_l = t_input_bN_l + in_bn;
float *t_output_bN = t_output_bN_l + out_bn;
float *t_input_rN_l=NULL, *t_output_rN_l=NULL, *t_output_rN=NULL;
if(rn > 0)
{
t_input_rN_l = t_output_bN + out_bn;
t_output_rN_l = t_input_rN_l + in_rn;
t_output_rN = t_output_rN_l + out_rn;
}
float *t_wt_r=NULL, *t_tr_wt_r=NULL, *t_input_bN_r=NULL, *t_output_bN_r=NULL;
float *t_input_rN_r=NULL, *t_output_rN_r=NULL;
if(pskip)
{
if(rn > 0)
t_wt_r = t_output_rN + out_rn;
else
t_wt_r = t_output_bN + out_bn;
t_tr_wt_r = t_wt_r + wts;
t_input_bN_r = t_tr_wt_r + wts;
t_output_bN_r = t_input_bN_r + in_bn;
if(rn > 0)
{
t_input_rN_r = t_output_bN_r + out_bn;
t_output_rN_r = t_input_rN_r + in_rn;
}
}
DECL_VLA_PTR_PT(float, wt_f32_l, [C], t_weights_l);
float *bias_l = t_bias_l.data_ptr<float>();
float (*wt_f32_r)[C] = pskip ? (float (*)[C])t_weights_r.data_ptr<float>() : NULL;
float *bias_r = pskip ? t_bias_r.data_ptr<float>() : NULL;
DECL_VLA_PTR_PT(float, input_l, [C], t_input_l);
DECL_VLA_PTR_PT_CHECK_COND(pskip, float, input_r, [C], t_input_r);
DECL_VLA_PTR_PT(float, output, [K], t_output);
DECL_VLA_PTR(float, wt_l, [nc][bk][bc], t_wt_l);
DECL_VLA_PTR(float, tr_wt_l, [nc][bc][bk], t_tr_wt_l);
DECL_VLA_PTR(float, input_bN_l, [nc][bn][bc], t_input_bN_l);
DECL_VLA_PTR_CHECK_VAR(rn, float, input_rN_l, [nc][rn][bc], t_input_rN_l);
DECL_VLA_PTR(float, output_bN, [nk][bn][bk], t_output_bN);
DECL_VLA_PTR_CHECK_VAR(rn, float, output_rN, [nk][rn][bk], t_output_rN);
DECL_VLA_PTR_CHECK_COND(pskip, float, wt_r, [nc][bk][bc], t_wt_r);
DECL_VLA_PTR_CHECK_COND(pskip, float, tr_wt_r, [nc][bc][bk], t_tr_wt_r);
DECL_VLA_PTR_CHECK_COND(pskip, float, input_bN_r, [nc][bn][bc], t_input_bN_r);
DECL_VLA_PTR_CHECK_COND(pskip, float, input_rN_r, [nc][rn][bc], t_input_rN_r);
DECL_VLA_PTR_CHECK_COND(pskip, float, output_bN_l, [nk][bn][bk], t_output_bN_l);
DECL_VLA_PTR_CHECK_COND(pskip, float, output_bN_r, [nk][bn][bk], t_output_bN_r);
DECL_VLA_PTR_CHECK_COND_VAR(pskip, rn, float, output_rN_l, [nk][rn][bk], t_output_rN_l);
DECL_VLA_PTR_CHECK_COND_VAR(pskip, rn, float, output_rN_r, [nk][rn][bk], t_output_rN_r);
for(int k=0; k<nk; k++) {
for(int c=0; c<nc; c++) {
copy_params.in.primary = &wt_f32_l[k*bk][c*bc];
copy_params.out.primary = &wt_l[k][c];
f32_copy(bk, bc, bc, bc, ©_params);
}
}
// Wt: NORM to NORM_T
norm_to_normT_32b(wt_l[0][0][0], tr_wt_l[0][0][0], bk, bc);
if(pskip)
{
for(int k=0; k<nk; k++) {
for(int c=0; c<nc; c++) {
copy_params.in.primary = &wt_f32_r[k*bk][c*bc];
copy_params.out.primary = &wt_r[k][c];
f32_copy(bk, bc, bc, bc, ©_params);
}
}
norm_to_normT_32b(wt_r[0][0][0], tr_wt_r[0][0][0], bk, bc);
}
#ifdef _OPENMP
#pragma omp parallel
#endif
{
int tid = omp_get_thread_num();
int threads = omp_get_max_threads();
int jobs = (nn % threads == 0) ? nn/threads : nn/threads + 1;
int tb = (tid*jobs < nn) ? tid*jobs : nn;
int te = ((tid+1)*jobs < nn) ? (tid+1)*jobs : nn;
int count = nc;
libxsmm_meltw_unary_param copy_params;
libxsmm_meltw_binary_param add_params;
libxsmm_meltw_unary_param relu_params;
libxsmm_meltw_unary_param dropout_params;
libxsmm_meltw_unary_flags dropout_flags = LIBXSMM_MELTW_FLAG_UNARY_BITMASK_2BYTEMULT;
for(int m=tb; m<te; m++) {
for(int c=0; c<nc; c++) {
copy_params.in.primary = &input_l[m*bn][c*bc];
copy_params.out.primary = &input_bN_l[tid][c];
f32_copy(bn, bc, nc*bc, nc*bc, ©_params);
}
if(pskip)
{
for(int c=0; c<nc; c++) {
copy_params.in.primary = &input_r[m*bn][c*bc];
copy_params.out.primary = &input_bN_r[tid][c];
f32_copy(bn, bc, nc*bc, nc*bc, ©_params);
}
for(int k=0; k<nk; k++) {
copy_params.in.primary = bias_l;
copy_params.out.primary = &output_bN_l[tid][k];
colbcast_f32_copy(bn, bk, ©_params);
}
for(int k=0; k<nk; k++) {
copy_params.in.primary = bias_r;
copy_params.out.primary = &output_bN_r[tid][k];
colbcast_f32_copy(bn, bk, ©_params);
}
}
else
{
for(int k=0; k<nk; k++) {
copy_params.in.primary = bias_l;
copy_params.out.primary = &output_bN[tid][k];
colbcast_f32_copy(bn, bk, ©_params);
}
}
if(pskip)
{
brgemm_f32_f32(bn, bk, bc, bn*bk, 0, input_bN_l[tid][0][0], tr_wt_l[0][0][0], output_bN_l[tid][0][0], count);
brgemm_f32_f32(bn, bk, bc, bn*bk, 0, input_bN_r[tid][0][0], tr_wt_r[0][0][0], output_bN_r[tid][0][0], count);
add_params.in0.primary = (void*)&output_bN_l[tid][0];
add_params.in1.primary = (void*)&output_bN_r[tid][0];
add_params.out.primary = (void*)&output_bN[tid][0];
add_f32_f32(bn, bk, &add_params);
}
else
brgemm_f32_f32(bn, bk, bc, bn*bk, 0, input_bN_l[tid][0][0], tr_wt_l[0][0][0], output_bN[tid][0][0], count);
if(pact == 1)
{
for(int k=0; k<nk; k++) {
relu_params.in.primary = &output_bN[tid][k];
relu_params.out.primary = &output_bN[tid][k];
relu_params.out.secondary = &relumask_bN[m][k];
relu_fwd_f32(bn, bk, &relu_params);
}
}
if(ptrain && pp > 0)
{
for(int k=0; k<nk; k++)
{
dropout_params.in.primary = &output_bN[tid][k];
dropout_params.in.secondary = rnd_state;
dropout_params.in.tertiary = &pp;
dropout_params.out.primary = &output_bN[tid][k];
dropout_params.out.secondary = &dropout_mask_bN[m][k];
dropout_f32(bn, bk, &dropout_params, dropout_flags);
}
}
for(int k=0; k<nk; k++) {
copy_params.in.primary = &output_bN[tid][k];
copy_params.out.primary = &output[m*bn][k*bk];
f32_copy(bn, bk, nk*bk, nk*bk, ©_params);
}
}
}
if(rn > 0)
{
// Single-threaded part of compute
//
for(int c=0; c<nc; c++) {
copy_params.in.primary = &input_l[nn*bn][c*bc];
copy_params.out.primary = &input_rN_l[0][c];
f32_copy(rn, bc, nc*bc, nc*bc, ©_params);
}
if(pskip)
{
for(int c=0; c<nc; c++) {
copy_params.in.primary = &input_r[nn*bn][c*bc];
copy_params.out.primary = &input_rN_r[0][c];
f32_copy(rn, bc, nc*bc, nc*bc, ©_params);
}
for(int k=0; k<nk; k++) {
copy_params.in.primary = bias_l;
copy_params.out.primary = &output_rN_l[0][k];
colbcast_f32_copy(rn, bk, ©_params);
copy_params.in.primary = bias_r;
copy_params.out.primary = &output_rN_r[0][k];
colbcast_f32_copy(rn, bk, ©_params);
}
}
else
{
for(int k=0; k<nk; k++) {
copy_params.in.primary = bias_l;
copy_params.out.primary = &output_rN[0][k];
colbcast_f32_copy(rn, bk, ©_params);
}
}
int count = nc;
if(pskip)
{
brgemm_f32_f32(rn, bk, bc, rn*bk, 0, input_rN_l[0][0][0], tr_wt_l[0][0][0], output_rN_l[0][0][0], count);
brgemm_f32_f32(rn, bk, bc, rn*bk, 0, input_rN_r[0][0][0], tr_wt_r[0][0][0], output_rN_r[0][0][0], count);
add_params.in0.primary = (void*)&output_rN_l[0][0];
add_params.in1.primary = (void*)&output_rN_r[0][0];
add_params.out.primary = (void*)&output_rN[0][0];
add_f32_f32(rn, bk, &add_params);
}
else
brgemm_f32_f32(rn, bk, bc, rn*bk, 0, input_rN_l[0][0][0], tr_wt_l[0][0][0], output_rN[0][0][0], count);
if(pact == 1)
{
for(int k=0; k<nk; k++) {
relu_params.in.primary = &output_rN[0][k];
relu_params.out.primary = &output_rN[0][k];
relu_params.out.secondary = &relumask_rN[0][k];
relu_fwd_f32(rn, bk, &relu_params);
}
}
if(ptrain && pp > 0)
{
for(int k=0; k<nk; k++)
{
dropout_params.in.primary = &output_rN[0][k];
dropout_params.in.secondary = rnd_state;
dropout_params.in.tertiary = &pp;
dropout_params.out.primary = &output_rN[0][k];
dropout_params.out.secondary = &dropout_mask_rN[0][k];
dropout_f32(rn, bk, &dropout_params, dropout_flags);
}
}
for(int k=0; k<nk; k++) {
copy_params.in.primary = &output_rN[0][k];
copy_params.out.primary = &output[nn*bn][k*bk];
f32_copy(rn, bk, nk*bk, nk*bk, ©_params);
}
}
libxsmm_free((void*)scratch);
return {t_output, t_relumask_bN, t_relumask_rN, t_dropout_mask_bN, t_dropout_mask_rN};
}
////=======================================================
//// ====================== BWD ===========================
////=======================================================
std::vector<at::Tensor> bwd(std::vector<at::Tensor> inputs)
{
long bn = pbn;
long bc = pbc;
long bk = pbk;
long nn = pN/bn;
long nc = pC;
long nk = pK;
long rn = pN % bn;
long K = nk*bk;
long C = nc*bc;
libxsmm_meltw_unary_param copy_params;
libxsmm_meltw_unary_param relu_params;
libxsmm_meltw_unary_param dropout_params;
libxsmm_meltw_unary_param delbias_params;
libxsmm_meltw_unary_param cvt_params;
libxsmm_meltw_unary_flags dropout_flags = LIBXSMM_MELTW_FLAG_UNARY_BITMASK_2BYTEMULT;
int threads = 1;
#ifdef _OPENMP
threads = omp_get_max_threads();
#endif
int i=0;
at::Tensor t_grad_output = inputs[i++];
at::Tensor t_input_l = inputs[i++];
at::Tensor t_input_r = inputs[i++];
at::Tensor t_weights_l = inputs[i++];
at::Tensor t_weights_r = inputs[i++];
at::Tensor t_relumask_bN = inputs[i++];
at::Tensor t_relumask_rN = inputs[i++];
at::Tensor t_dropout_mask_bN = inputs[i++];
at::Tensor t_dropout_mask_rN = inputs[i++];
at::Tensor t_grad_weights_l = t_weights_l.new_empty({nk, nc, bk, bc});
at::Tensor t_grad_bias_l = t_weights_l.new_empty(K);
at::Tensor t_grad_input_l = t_input_l.new_empty({pN, C});
at::Tensor t_grad_weights_r, t_grad_bias_r, t_grad_input_r;
if(pskip)
{
t_grad_weights_r = t_weights_r.new_empty({nk, nc, bk, bc});
t_grad_bias_r = t_weights_r.new_empty(K);
t_grad_input_r = t_input_r.new_empty({pN, C});
}
long wts = nk*nc*bk*bc;
long go_bn = threads*nk*bn*bk;
long go_rn = nk*rn*bk;
long gi_bn = threads*nc*bn*bc;
long gi_rn = nc*rn*bc;
long in_bn = threads*nc*bn*bc;
long in_rn = nc*rn*bc;
long scratch_size;
if(pskip)
scratch_size = (wts*4 + go_bn + go_rn + gi_bn*2 + gi_rn*2 + in_bn*2 + in_rn*2)*sizeof(float);
else
scratch_size = (wts*2 + go_bn + go_rn + gi_bn + gi_rn + in_bn + in_rn)*sizeof(float);
void *scratch = libxsmm_aligned_malloc(scratch_size, 2097152);
float* t_grad_output_bN = (float*)scratch;
float* t_grad_input_bN_l = t_grad_output_bN + go_bn;
float* t_input_bN_l = t_grad_input_bN_l + gi_bn;
float* t_f32_grad_wt_l = t_input_bN_l + in_bn;
float* t_f32_wt_l = t_f32_grad_wt_l + wts;
float *t_grad_output_rN=NULL, *t_grad_input_rN_l=NULL, *t_input_rN_l=NULL;
if(rn > 0)
{
t_grad_output_rN = t_f32_wt_l + wts;
t_grad_input_rN_l = t_grad_output_rN + go_rn;
t_input_rN_l = t_grad_input_rN_l + gi_rn;
}
float *t_grad_input_bN_r=NULL, *t_input_bN_r=NULL;
float *t_grad_input_rN_r=NULL, *t_input_rN_r=NULL;
float *t_f32_grad_wt_r=NULL, *t_f32_wt_r=NULL;
if(pskip)
{
if(rn > 0)
t_grad_input_bN_r = t_input_rN_l + in_rn;
else
t_grad_input_bN_r = t_f32_wt_l + wts;
t_input_bN_r = t_grad_input_bN_r + gi_bn;
t_f32_grad_wt_r = t_input_bN_r + in_bn;
t_f32_wt_r = t_f32_grad_wt_r + wts;
if(rn > 0)
{
t_grad_input_rN_r = t_f32_wt_r + wts;
t_input_rN_r = t_grad_input_rN_r + gi_rn;
}
}
DECL_VLA_PTR_PT(float, wt_l, [C], t_weights_l);
DECL_VLA_PTR_PT(float, grad_wt_l, [C], t_grad_weights_l);
float (*wt_r)[C] = pskip ? (float (*)[C])t_weights_r.data_ptr<float>() : NULL;
float (*grad_wt_r)[C] = pskip ? (float (*)[C])t_grad_weights_r.data_ptr<float>() : NULL;
DECL_VLA_PTR_PT(float, grad_output, [K], t_grad_output);
DECL_VLA_PTR_PT(float, input_l, [C], t_input_l);
DECL_VLA_PTR_PT(float, grad_input_l, [C], t_grad_input_l);
DECL_VLA_PTR_PT_CHECK_COND(pskip, float, input_r, [C], t_input_r);
DECL_VLA_PTR_PT_CHECK_COND(pskip, float, grad_input_r, [C], t_grad_input_r);
DECL_VLA_PTR(float, grad_output_bN, [nk][bn][bk], t_grad_output_bN);
DECL_VLA_PTR(float, grad_input_bN_l, [nc][bn][bc], t_grad_input_bN_l);
DECL_VLA_PTR(float, input_bN_l, [nc][bn][bc], t_input_bN_l);
DECL_VLA_PTR(float, wt_f32_l, [nc][bk][bc], t_f32_wt_l);
DECL_VLA_PTR(float, grad_wt_f32_l, [nc][bk][bc], t_f32_grad_wt_l);
float *grad_bias_l = t_grad_bias_l.data_ptr<float>();
DECL_VLA_PTR_CHECK_COND(pskip, float, grad_input_bN_r, [nc][bn][bc], t_grad_input_bN_r);
DECL_VLA_PTR_CHECK_COND(pskip, float, input_bN_r, [nc][bn][bc], t_input_bN_r);
DECL_VLA_PTR_CHECK_COND(pskip, float, wt_f32_r, [nc][bk][bc], t_f32_wt_r);
DECL_VLA_PTR_CHECK_COND(pskip, float, grad_wt_f32_r, [nc][bk][bc], t_f32_grad_wt_r);
float *grad_bias_r = pskip ? t_grad_bias_r.data_ptr<float>() : NULL;
DECL_VLA_PTR_CHECK_VAR(rn, float, grad_output_rN, [nk][rn][bk], t_grad_output_rN);
DECL_VLA_PTR_CHECK_VAR(rn, float, grad_input_rN_l, [nc][rn][bc], t_grad_input_rN_l);
DECL_VLA_PTR_CHECK_VAR(rn, float, input_rN_l, [nc][rn][bc], t_input_rN_l);
DECL_VLA_PTR_CHECK_COND_VAR(pskip, rn, float, grad_input_rN_r, [nc][rn][bc], t_grad_input_rN_r);
DECL_VLA_PTR_CHECK_COND_VAR(pskip, rn, float, input_rN_r, [nc][rn][bc], t_input_rN_r);
int dd = (bk % 32 == 0) ? bk/32 : bk/32 + 1;
int rd = (bk % 32 == 0) ? bk/32 : bk/32 + 1;
__mmask32 (*dropout_mask_bN)[nk][bn][dd] = (ptrain && pp > 0) ? (__mmask32 (*)[nk][bn][dd])(t_dropout_mask_bN.data_ptr()) : NULL;
__mmask32 (*dropout_mask_rN)[nk][rn][dd] = (ptrain && pp > 0 && rn > 0) ? (__mmask32 (*)[nk][rn][dd])(t_dropout_mask_rN.data_ptr()) : NULL;
__mmask32 (*relumask_bN)[nk][bn][rd] = pact==1 ? (__mmask32 (*)[nk][bn][rd])(t_relumask_bN.data_ptr()) : NULL;
__mmask32 (*relumask_rN)[nk][rn][rd] = (pact==1 && rn > 0) ? (__mmask32 (*)[nk][rn][rd])(t_relumask_rN.data_ptr()) : NULL;
copy_params.out.primary = t_f32_grad_wt_l;
zero(K*C, ©_params);
copy_params.out.primary = t_grad_weights_l.data_ptr<float>();
zero(K*C, ©_params);
copy_params.out.primary = t_grad_bias_l.data_ptr<float>();
zero(K, ©_params);
if(pskip)
{
copy_params.out.primary = t_f32_grad_wt_r;
zero(K*C, ©_params);
}
if(pskip)
{
copy_params.out.primary = t_grad_weights_r.data_ptr<float>();
zero(K*C, ©_params);
copy_params.out.primary = t_grad_bias_r.data_ptr<float>();
zero(K, ©_params);
}
// Get F32 copy of weights
for(int k=0; k<nk; k++) {
for(int c=0; c<nc; c++) {
copy_params.in.primary = &wt_l[k*bk][c*bc];
copy_params.out.primary = &wt_f32_l[k][c];
f32_copy(bk, bc, bc, bc, ©_params);
}
}
if(pskip)
{
for(int k=0; k<nk; k++) {
for(int c=0; c<nc; c++) {
copy_params.in.primary = &wt_r[k*bk][c*bc];
copy_params.out.primary = &wt_f32_r[k][c];
f32_copy(bk, bc, bc, bc, ©_params);
}
}
}
if(pskip)
{
#ifdef _OPENMP
#pragma omp parallel reduction(+: grad_wt_f32_l[:nk][:nc][:bk][:bc], grad_bias_l[:K], grad_wt_f32_r[:nk][:nc][:bk][:bc], grad_bias_r[:K])
#endif
{
int tid = omp_get_thread_num();
int threads = omp_get_max_threads();
int jobs = (nn % threads == 0) ? nn/threads : nn/threads + 1;
int tb = (tid*jobs < nn) ? tid*jobs : nn;
int te = ((tid+1)*jobs < nn) ? (tid+1)*jobs : nn;
libxsmm_meltw_unary_param relu_params;
libxsmm_meltw_unary_param dropout_params;
libxsmm_meltw_unary_param copy_params;
libxsmm_meltw_unary_param delbias_params;
for(int m=tb; m<te; m++) {
for(int k=0; k<nk; k++) {
if(ptrain && pp > 0) {
dropout_params.in.primary = &grad_output[m*bn][k*bk];
dropout_params.in.secondary = &dropout_mask_bN[m][k][0][0];
dropout_params.in.tertiary = &pp;
dropout_params.out.primary = &grad_output[m*bn][k*bk];
dropout_bwd_f32(bn, bk, &dropout_params, dropout_flags);
}
if(pact == 1) {
relu_params.in.primary = &grad_output[m*bn][k*bk];
relu_params.in.secondary = &relumask_bN[m][k][0][0];
relu_params.out.primary = &grad_output[m*bn][k*bk];
relu_bwd_f32(bn, bk, &relu_params);
}
copy_params.in.primary = &grad_output[m*bn][k*bk];
copy_params.out.primary = &grad_output_bN[tid][k];
f32_copy(bn, bk, nk*bk, nk*bk, ©_params);
}
int count=1;
brgemm_f32_f32(bn, bc, bk, bn*bk, 0, grad_output_bN[tid][0][0], wt_f32_l[0][0][0], grad_input_bN_l[tid][0][0], count, 0.0);
for(int c=0; c<nc; c++) {
copy_params.in.primary = &grad_input_bN_l[tid][c];
copy_params.out.primary = &grad_input_l[m*bn][c*bc];
f32_copy(bn, bc, nc*bc, nc*bc, ©_params);
}
brgemm_f32_f32(bn, bc, bk, bn*bk, 0, grad_output_bN[tid][0][0], wt_f32_r[0][0][0], grad_input_bN_r[tid][0][0], count, 0.0);
for(int c=0; c<nc; c++) {
copy_params.in.primary = &grad_input_bN_r[tid][c];
copy_params.out.primary = &grad_input_r[m*bn][c*bc];
f32_copy(bn, bc, nc*bc, nc*bc, ©_params);
}
for(int c=0; c<nc; c++) {
copy_params.in.primary = &input_l[m*bn][c*bc];
copy_params.out.primary = &input_bN_l[tid][c];
f32_copy(bn, bc, nc*bc, nc*bc, ©_params);
}
for(int c=0; c<nc; c++) {
copy_params.in.primary = &input_r[m*bn][c*bc];
copy_params.out.primary = &input_bN_r[tid][c];
f32_copy(bn, bc, nc*bc, nc*bc, ©_params);
}
count = 1;
brgemm_f32_f32(bk, bc, bn, bn*bk, bn*bc, grad_output_bN[tid][0][0], input_bN_l[tid][0][0], grad_wt_f32_l[0][0][0], count, 1.0, 't');
brgemm_f32_f32(bk, bc, bn, bn*bk, bn*bc, grad_output_bN[tid][0][0], input_bN_r[tid][0][0], grad_wt_f32_r[0][0][0], count, 1.0, 't');
for(int k=0; k<nk; k++) {
delbias_params.in.primary = &grad_output_bN[tid][k];
delbias_params.out.primary = grad_bias_l;
delbias_f32(bn, bk, bn, bk, &delbias_params);
}
copy_params.in.primary = grad_bias_l;
copy_params.out.primary = grad_bias_r;
f32_copy(1, K, K, K, ©_params);
}
}
}
else
{
#ifdef _OPENMP
#pragma omp parallel reduction(+: grad_wt_f32_l[:nk][:nc][:bk][:bc], grad_bias_l[:K])
#endif
{
int tid = omp_get_thread_num();
int threads = omp_get_max_threads();
int jobs = (nn % threads == 0) ? nn/threads : nn/threads + 1;
int tb = (tid*jobs < nn) ? tid*jobs : nn;
int te = ((tid+1)*jobs < nn) ? (tid+1)*jobs : nn;
libxsmm_meltw_unary_param relu_params;
libxsmm_meltw_unary_param dropout_params;
libxsmm_meltw_unary_param copy_params;
libxsmm_meltw_unary_param delbias_params;
for(int m=tb; m<te; m++) {
for(int k=0; k<nk; k++) {
if(ptrain && pp > 0) {
dropout_params.in.primary = &grad_output[m*bn][k*bk];
dropout_params.in.secondary = &dropout_mask_bN[m][k][0][0];
dropout_params.in.tertiary = &pp;
dropout_params.out.primary = &grad_output[m*bn][k*bk];
dropout_bwd_f32(bn, bk, &dropout_params, dropout_flags);
}
if(pact == 1) {
relu_params.in.primary = &grad_output[m*bn][k*bk];
relu_params.in.secondary = &relumask_bN[m][k][0][0];
relu_params.out.primary = &grad_output[m*bn][k*bk];
relu_bwd_f32(bn, bk, &relu_params);
}
copy_params.in.primary = &grad_output[m*bn][k*bk];
copy_params.out.primary = &grad_output_bN[tid][k];
f32_copy(bn, bk, nk*bk, nk*bk, ©_params);
}
int count = 1;
brgemm_f32_f32(bn, bc, bk, bn*bk, 0, grad_output_bN[tid][0][0], wt_f32_l[0][0][0], grad_input_bN_l[tid][0][0], count, 0.0);
for(int c=0; c<nc; c++) {
copy_params.in.primary = &grad_input_bN_l[tid][c];
copy_params.out.primary = &grad_input_l[m*bn][c*bc];
f32_copy(bn, bc, nc*bc, nc*bc, ©_params);
}
for(int c=0; c<nc; c++) {
copy_params.in.primary = &input_l[m*bn][c*bc];
copy_params.out.primary = &input_bN_l[tid][c];
f32_copy(bn, bc, nc*bc, nc*bc, ©_params);
}
count = 1;
brgemm_f32_f32(bk, bc, bn, bn*bk, bn*bc, grad_output_bN[tid][0][0], input_bN_l[tid][0][0], grad_wt_f32_l[0][0][0], count, 1.0, 't');
for(int k=0; k<nk; k++) {
delbias_params.in.primary = &grad_output_bN[tid][k];
delbias_params.out.primary = grad_bias_l;
delbias_f32(bn, bk, bn, bk, &delbias_params);
}
}
}
}
if(rn > 0)
{
//Single-thread portion of code--------------------------
// Dropout
if(ptrain && pp > 0)
{
for(int k=0; k<nk; k++) {
dropout_params.in.primary = &grad_output[nn*bn][k*bk];
dropout_params.in.secondary = &dropout_mask_rN[0][k][0][0];
dropout_params.in.tertiary = &pp;
dropout_params.out.primary = &grad_output[nn*bn][k*bk];
dropout_bwd_f32(rn, bk, &dropout_params, dropout_flags);
}
}
// ReLU
if(pact == 1)
{
for(int k=0; k<nk; k++) {
relu_params.in.primary = &grad_output[nn*bn][k*bk];
relu_params.in.secondary = &relumask_rN[0][k][0][0];
relu_params.out.primary = &grad_output[nn*bn][k*bk];
relu_bwd_f32(rn, bk, &relu_params);
}
}
int count=1;
//grad-input
for(int k=0; k<nk; k++) {
copy_params.in.primary = &grad_output[nn*bn][k*bk];
copy_params.out.primary = &grad_output_rN[0][k];
f32_copy(rn, bk, nk*bk, nk*bk, ©_params);
}
brgemm_f32_f32(rn, bc, bk, rn*bk, 0, grad_output_rN[0][0][0], wt_f32_l[0][0][0], grad_input_rN_l[0][0][0], count, 0.0);
for(int c=0; c<nc; c++) {
copy_params.in.primary = &grad_input_rN_l[0][c];
copy_params.out.primary = &grad_input_l[nn*bn][c*bc];
f32_copy(rn, bc, nc*bc, nc*bc, ©_params);
}
if(pskip)
{
brgemm_f32_f32(rn, bc, bk, rn*bk, 0, grad_output_rN[0][0][0], wt_f32_r[0][0][0], grad_input_rN_r[0][0][0], count, 0.0);
for(int c=0; c<nc; c++) {
copy_params.in.primary = &grad_input_rN_r[0][c];
copy_params.out.primary = &grad_input_r[nn*bn][c*bc];
f32_copy(rn, bc, nc*bc, nc*bc, ©_params);
}
}
//grad-weights
count = 1;
brgemm_f32_f32(bk, bc, rn, rn*bk, rn*bc, grad_output_rN[0][0][0], input_rN_l[0][0][0], grad_wt_f32_l[0][0][0], count, 1.0, 't');
if(pskip)
{
for(int c=0; c<nc; c++) {
copy_params.in.primary = &input_r[nn*bn][c*bc];
copy_params.out.primary = &input_rN_r[0][c];
f32_copy(rn, bc, nc*bc, nc*bc, ©_params);
}
count = 1;
brgemm_f32_f32(bk, bc, rn, rn*bk, rn*bc, grad_output_rN[0][0][0], input_rN_r[0][0][0], grad_wt_f32_r[0][0][0], count, 1.0, 't');
}
for(int k=0; k<nk; k++) {
delbias_params.in.primary = &grad_output_rN[0][k];
delbias_params.out.primary = grad_bias_l;
delbias_f32(rn, bk, rn, bk, &delbias_params);
}
if(pskip)
{
for(int k=0; k<nk; k++) {
delbias_params.in.primary = &grad_output_rN[0][k];
delbias_params.out.primary = grad_bias_r;
delbias_f32(rn, bk, rn, bk, &delbias_params);
}
}
}
for(int k=0; k<nk; k++) {
for(int c=0; c<nc; c++) {
copy_params.in.primary = &grad_wt_f32_l[k][c];
copy_params.out.primary = &grad_wt_l[k*bk][c*bc];
f32_copy(bk, bc, nc*bc, nc*bc, ©_params);
}
}
if(pskip)
{
for(int k=0; k<nk; k++) {
for(int c=0; c<nc; c++) {
copy_params.in.primary = &grad_wt_f32_r[k][c];
copy_params.out.primary = &grad_wt_r[k*bk][c*bc];
f32_copy(bk, bc, nc*bc, nc*bc, ©_params);
}
}
}
libxsmm_free(scratch);
return {t_grad_input_l, t_grad_input_r, t_grad_weights_l, t_grad_weights_r, t_grad_bias_l, t_grad_bias_r};
}
bool has_bias() {return pbias;}
bool has_skip() {return pskip;}
bool has_norm() {return pnorm;}
private:
long pN;
long pC;
long pK;
long pbn;
long pbc;
long pbk;
bool pbias;
bool pskip;
int pact;
bool pnorm;
float pp;
bool ptrain;
};
#endif
| 19,738 |
314 | <reponame>tclfs/rocketmq-client-cpp<filename>test/src/protocol/LockBatchBodyTest.cpp
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "vector"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "LockBatchBody.h"
#include "MQMessageQueue.h"
#include "dataBlock.h"
using std::vector;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::LockBatchRequestBody;
using rocketmq::LockBatchResponseBody;
using rocketmq::MemoryBlock;
using rocketmq::MQMessageQueue;
using rocketmq::UnlockBatchRequestBody;
TEST(lockBatchBody, LockBatchRequestBody) {
LockBatchRequestBody lockBatchRequestBody;
lockBatchRequestBody.setClientId("testClientId");
EXPECT_EQ(lockBatchRequestBody.getClientId(), "testClientId");
lockBatchRequestBody.setConsumerGroup("testGroup");
EXPECT_EQ(lockBatchRequestBody.getConsumerGroup(), "testGroup");
vector<MQMessageQueue> vectorMessageQueue;
vectorMessageQueue.push_back(MQMessageQueue());
vectorMessageQueue.push_back(MQMessageQueue());
lockBatchRequestBody.setMqSet(vectorMessageQueue);
EXPECT_EQ(lockBatchRequestBody.getMqSet(), vectorMessageQueue);
Json::Value outJson = lockBatchRequestBody.toJson(MQMessageQueue("topicTest", "testBroker", 10));
EXPECT_EQ(outJson["topic"], "topicTest");
EXPECT_EQ(outJson["brokerName"], "testBroker");
EXPECT_EQ(outJson["queueId"], 10);
string outData;
lockBatchRequestBody.Encode(outData);
Json::Value root;
Json::Reader reader;
reader.parse(outData, root);
EXPECT_EQ(root["clientId"], "testClientId");
EXPECT_EQ(root["consumerGroup"], "testGroup");
}
TEST(lockBatchBody, UnlockBatchRequestBody) {
UnlockBatchRequestBody uRB;
uRB.setClientId("testClient");
EXPECT_EQ(uRB.getClientId(), "testClient");
uRB.setConsumerGroup("testGroup");
EXPECT_EQ(uRB.getConsumerGroup(), "testGroup");
// message queue
EXPECT_TRUE(uRB.getMqSet().empty());
vector<MQMessageQueue> mqs;
MQMessageQueue mqA("testTopic", "testBrokerA", 1);
mqs.push_back(mqA);
MQMessageQueue mqB("testTopic", "testBrokerB", 2);
mqs.push_back(mqB);
uRB.setMqSet(mqs);
EXPECT_EQ(uRB.getMqSet().size(), 2);
string outData;
uRB.Encode(outData);
EXPECT_GT(outData.length(), 1);
EXPECT_NE(outData.find("testTopic"), string::npos);
}
TEST(lockBatchBody, LockBatchResponseBody) {
Json::Value root;
Json::Value mqs;
Json::Value mq;
mq["topic"] = "testTopic";
mq["brokerName"] = "testBroker";
mq["queueId"] = 1;
mqs[0] = mq;
root["lockOKMQSet"] = mqs;
Json::FastWriter fastwrite;
string outData = fastwrite.write(root);
MemoryBlock* mem = new MemoryBlock(outData.c_str(), outData.size());
LockBatchResponseBody lockBatchResponseBody;
vector<MQMessageQueue> messageQueues;
LockBatchResponseBody::Decode(mem, messageQueues);
MQMessageQueue messageQueue("testTopic", "testBroker", 1);
EXPECT_EQ(messageQueue, messageQueues[0]);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "lockBatchBody.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}
| 1,338 |
5,169 | <reponame>Gantios/Specs<gh_stars>1000+
{
"name": "DJComponentHotfix",
"version": "0.1.1",
"summary": "A short description of DJHotfixManager.",
"description": "only for private use",
"homepage": "http://douzhongxu.com",
"license": "MIT (Dokay)",
"authors": {
"Doaky": "<EMAIL>"
},
"platforms": {
"ios": "7.0"
},
"source": {
"git": "https://github.com/Dokay/DJHotfixManager.git",
"tag": "0.1.1"
},
"subspecs": [
{
"name": "RSA",
"source_files": "DJComponentHotfix/DJHotfixManager/RSA/*.{h,m}",
"requires_arc": true,
"frameworks": "Security"
},
{
"name": "Core",
"source_files": "DJComponentHotfix/DJHotfixManager/Core/*.{h,m}",
"exclude_files": [
"DJComponentHotfix/DJHotfixManager/Core/AppDelegate+DJLaunchProtect.h",
"DJComponentHotfix/DJHotfixManager/Core/AppDelegate+DJLaunchProtect.m"
],
"requires_arc": true,
"dependencies": {
"JSPatch": [
],
"DJComponentHotfix/RSA": [
]
}
}
]
}
| 501 |
305 | <gh_stars>100-1000
//*****************************************************************************
// Copyright 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <cstring>
#include <iostream>
#include <shared_mutex>
#include "../../custom_node_interface.h"
#include "../common/custom_node_library_internal_manager.hpp"
#include "../common/utils.hpp"
#include "add_one_internal_manager.hpp"
using InternalManager = ovms::custom_nodes_common::AddOneInternalManager;
static constexpr const char* INPUT_TENSOR_NAME = "input_numbers";
static constexpr const char* INPUT_INFO_NAME = "input_info";
static constexpr const char* INPUT_INFO_DIMS_NAME = "input_info_dims";
static constexpr const char* OUTPUT_NAME = "output";
static constexpr const char* OUTPUT_TENSOR_NAME = "output_numbers";
static constexpr const char* OUTPUT_TENSOR_DIMS_NAME = "output_dims";
static constexpr const char* OUTPUT_INFO_NAME = "output_info";
static constexpr const char* OUTPUT_INFO_DIMS_NAME = "output_info_dims";
int initializeInternalManager(void** customNodeLibraryInternalManager, const struct CustomNodeParam* params, int paramsCount) {
std::unique_ptr<InternalManager> internalManager = std::make_unique<InternalManager>();
NODE_ASSERT(internalManager != nullptr, "internalManager allocation failed");
int output_queue_size = get_int_parameter("output_queue_size", params, paramsCount, internalManager->getCurrentOutputQueueSize());
NODE_ASSERT(output_queue_size > 0, "output_queue_size should be greater than 0");
internalManager->setCurrentOutputQueueSize(output_queue_size);
int info_queue_size = get_int_parameter("info_queue_size", params, paramsCount, internalManager->getCurrentInfoQueueSize());
NODE_ASSERT(info_queue_size > 0, "info_queue_size should be greater than 0");
internalManager->setCurrentInfoQueueSize(info_queue_size);
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_NAME, 1 * sizeof(CustomNodeTensor), output_queue_size), "output buffer creation failed");
uint64_t byteSize = sizeof(float) * internalManager->getOutputSize();
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_TENSOR_NAME, byteSize, output_queue_size), "output tensor buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_TENSOR_DIMS_NAME, 2 * sizeof(uint64_t), output_queue_size), "output tensor dims buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(INPUT_INFO_NAME, 1 * sizeof(CustomNodeTensorInfo), info_queue_size), "input info buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_INFO_NAME, 1 * sizeof(CustomNodeTensorInfo), info_queue_size), "output info buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(INPUT_INFO_DIMS_NAME, 2 * sizeof(uint64_t), info_queue_size), "input info dims buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_INFO_DIMS_NAME, 2 * sizeof(uint64_t), info_queue_size), "output info dims buffer creation failed");
*customNodeLibraryInternalManager = internalManager.release();
return 0;
}
int reinitializeInternalManagerIfNeccessary(void** customNodeLibraryInternalManager, const struct CustomNodeParam* params, int paramsCount) {
InternalManager* internalManager = static_cast<InternalManager*>(*customNodeLibraryInternalManager);
NODE_ASSERT(internalManager != nullptr, "internalManager is not initialized");
std::unique_lock<std::shared_timed_mutex> lock(internalManager->getInternalManagerLock());
int output_queue_size = get_int_parameter("output_queue_size", params, paramsCount, internalManager->getCurrentOutputQueueSize());
NODE_ASSERT(output_queue_size > 0, "output_queue_size should be greater than 0");
int info_queue_size = get_int_parameter("info_queue_size", params, paramsCount, internalManager->getCurrentInfoQueueSize());
NODE_ASSERT(info_queue_size > 0, "info_queue_size should be greater than 0");
if (internalManager->getCurrentOutputQueueSize() != output_queue_size) {
NODE_ASSERT(internalManager->recreateBuffersQueue(OUTPUT_NAME, 1 * sizeof(CustomNodeTensor), output_queue_size), "output buffer recreation failed");
uint64_t byteSize = sizeof(float) * internalManager->getOutputSize();
NODE_ASSERT(internalManager->recreateBuffersQueue(OUTPUT_TENSOR_NAME, byteSize, output_queue_size), "output tensor buffer recreation failed");
NODE_ASSERT(internalManager->recreateBuffersQueue(OUTPUT_TENSOR_DIMS_NAME, 2 * sizeof(uint64_t), output_queue_size), "output tensor dims buffer recreation failed");
internalManager->setCurrentOutputQueueSize(output_queue_size);
}
if (internalManager->getCurrentInfoQueueSize() != info_queue_size) {
NODE_ASSERT(internalManager->recreateBuffersQueue(INPUT_INFO_NAME, 1 * sizeof(CustomNodeTensorInfo), info_queue_size), "input info buffer recreation failed");
NODE_ASSERT(internalManager->recreateBuffersQueue(OUTPUT_INFO_NAME, 1 * sizeof(CustomNodeTensorInfo), info_queue_size), "output info buffer recreation failed");
NODE_ASSERT(internalManager->recreateBuffersQueue(INPUT_INFO_DIMS_NAME, 2 * sizeof(uint64_t), info_queue_size), "input info dims buffer recreation failed");
NODE_ASSERT(internalManager->recreateBuffersQueue(OUTPUT_INFO_DIMS_NAME, 2 * sizeof(uint64_t), info_queue_size), "output info dims buffer recreation failed");
internalManager->setCurrentInfoQueueSize(info_queue_size);
}
return 0;
}
int initialize(void** customNodeLibraryInternalManager, const struct CustomNodeParam* params, int paramsCount) {
auto status = 0;
if (*customNodeLibraryInternalManager == nullptr) {
status = initializeInternalManager(customNodeLibraryInternalManager, params, paramsCount);
} else {
status = reinitializeInternalManagerIfNeccessary(customNodeLibraryInternalManager, params, paramsCount);
}
NODE_ASSERT(status == 0, "initialize failed");
return 0;
}
int deinitialize(void* customNodeLibraryInternalManager) {
if (customNodeLibraryInternalManager != nullptr) {
InternalManager* internalManager = static_cast<InternalManager*>(customNodeLibraryInternalManager);
delete internalManager;
}
return 0;
}
int execute(const struct CustomNodeTensor* inputs, int inputsCount, struct CustomNodeTensor** outputs, int* outputsCount, const struct CustomNodeParam* params, int paramsCount, void* customNodeLibraryInternalManager) {
InternalManager* internalManager = static_cast<InternalManager*>(customNodeLibraryInternalManager);
NODE_ASSERT(internalManager != nullptr, "internalManager is not initialized");
std::shared_lock<std::shared_timed_mutex> lock(internalManager->getInternalManagerLock());
NODE_ASSERT(inputsCount == 1, "too many inputs provided");
NODE_ASSERT(std::strcmp(inputs[0].name, INPUT_TENSOR_NAME) == 0, "invalid input name");
const CustomNodeTensor* inputTensor = &(inputs[0]);
NODE_ASSERT(inputTensor->precision == FP32, "input precision is not FP32");
NODE_ASSERT(inputTensor->dimsCount == 2, "input shape must have 2 dimensions");
NODE_ASSERT(inputTensor->dims[0] == 1, "input batch size must be 1");
NODE_ASSERT(inputTensor->dims[1] == 10, "input dim[1] must be 10");
int add_number = get_int_parameter("add_number", params, paramsCount, 1);
NODE_ASSERT(add_number >= 0, "add_number should be equal or greater than 0");
int sub_number = get_int_parameter("sub_number", params, paramsCount, 0);
NODE_ASSERT(sub_number >= 0, "sub_number should be equal or greater than 0");
*outputsCount = 1;
if (!get_buffer<struct CustomNodeTensor>(internalManager, outputs, OUTPUT_NAME, 1 * sizeof(CustomNodeTensor))) {
return 1;
}
struct CustomNodeTensor* outputTensor = (&(*outputs))[0];
outputTensor->name = OUTPUT_TENSOR_NAME;
float* buffer = nullptr;
if (!get_buffer<float>(internalManager, &buffer, OUTPUT_TENSOR_NAME, inputTensor->dataBytes * sizeof(uint8_t))) {
release(*outputs, internalManager);
return 1;
}
memcpy(buffer, inputTensor->data, inputTensor->dataBytes);
outputTensor->data = reinterpret_cast<uint8_t*>(buffer);
outputTensor->dataBytes = inputTensor->dataBytes;
if (!get_buffer<uint64_t>(internalManager, &(outputTensor->dims), OUTPUT_TENSOR_DIMS_NAME, 2 * sizeof(uint64_t))) {
release(buffer, internalManager);
release(*outputs, internalManager);
return 1;
}
outputTensor->dimsCount = inputTensor->dimsCount;
outputTensor->dims[0] = 1;
outputTensor->dims[1] = 10;
outputTensor->precision = inputTensor->precision;
for (uint64_t i = 0; i < outputTensor->dataBytes; i += sizeof(float)) {
*(float*)(outputTensor->data + i) = *(float*)(inputTensor->data + i) + add_number - sub_number;
}
return 0;
}
int getInputsInfo(struct CustomNodeTensorInfo** info, int* infoCount, const struct CustomNodeParam* params, int paramsCount, void* customNodeLibraryInternalManager) {
InternalManager* internalManager = static_cast<InternalManager*>(customNodeLibraryInternalManager);
NODE_ASSERT(internalManager != nullptr, "internalManager is not initialized");
std::shared_lock<std::shared_timed_mutex> lock(internalManager->getInternalManagerLock());
*infoCount = 1;
if (!get_buffer<struct CustomNodeTensorInfo>(internalManager, info, INPUT_INFO_NAME, 1 * sizeof(CustomNodeTensorInfo))) {
return 1;
}
(*info)->name = INPUT_TENSOR_NAME;
(*info)->dimsCount = 2;
if (!get_buffer<uint64_t>(internalManager, &((*info)->dims), INPUT_INFO_DIMS_NAME, 2 * sizeof(uint64_t))) {
release(*info, internalManager);
return 1;
}
(*info)->dims[0] = 1;
(*info)->dims[1] = internalManager->getInputSize();
(*info)->precision = FP32;
return 0;
}
int getOutputsInfo(struct CustomNodeTensorInfo** info, int* infoCount, const struct CustomNodeParam* params, int paramsCount, void* customNodeLibraryInternalManager) {
InternalManager* internalManager = static_cast<InternalManager*>(customNodeLibraryInternalManager);
NODE_ASSERT(internalManager != nullptr, "internalManager is not initialized");
std::shared_lock<std::shared_timed_mutex> lock(internalManager->getInternalManagerLock());
*infoCount = 1;
if (!get_buffer<struct CustomNodeTensorInfo>(internalManager, info, OUTPUT_INFO_NAME, 1 * sizeof(CustomNodeTensorInfo))) {
return 1;
}
(*info)->name = "output_numbers";
(*info)->dimsCount = 2;
if (!get_buffer<uint64_t>(internalManager, &((*info)->dims), OUTPUT_INFO_DIMS_NAME, 2 * sizeof(uint64_t))) {
release(*info, internalManager);
return 1;
}
(*info)->dims[0] = 1;
(*info)->dims[1] = internalManager->getOutputSize();
(*info)->precision = FP32;
return 0;
}
int release(void* ptr, void* customNodeLibraryInternalManager) {
InternalManager* internalManager = static_cast<InternalManager*>(customNodeLibraryInternalManager);
if (!internalManager->releaseBuffer(ptr)) {
free(ptr);
return 0;
}
return 0;
}
| 3,862 |
5,169 | <reponame>Ray0218/Specs
{
"name": "MWIDCardValidate",
"version": "1.0.0",
"summary": "居民身份证验证",
"description": "This is ID card validate for chinese.\n中华人民共和国居民身份证验证",
"homepage": "https://github.com/wuchuwuyou/MWVerifyID",
"license": "MIT",
"authors": {
"Murphy": "<EMAIL>"
},
"platforms": {
"ios": "7.0"
},
"source": {
"git": "https://github.com/wuchuwuyou/MWVerifyID.git",
"tag": "1.0.0"
},
"source_files": "MWIDCardValidate/*"
}
| 254 |
910 | <reponame>ThePreviousOne/SVG-Android<gh_stars>100-1000
package com.github.megatronking.svg.sample.animation;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.LinearInterpolator;
import com.github.megatronking.svg.sample.R;
import com.github.megatronking.svg.support.extend.SVGImageView;
public class AnimationSVGImageViewSampleActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animation_svg_imageview_sample);
setTitle(getIntent().getStringExtra("title"));
final SVGImageView imageView1 = (SVGImageView) findViewById(R.id.animation_svgimageview_image1);
ObjectAnimator animatorRotation = ObjectAnimator.ofFloat(imageView1, "svgRotation", 0, 360);
animatorRotation.setDuration(2000);
animatorRotation.setRepeatCount(ValueAnimator.INFINITE);
animatorRotation.setInterpolator(new LinearInterpolator());
animatorRotation.start();
SVGImageView imageView2 = (SVGImageView) findViewById(R.id.animation_svgimageview_image2);
ObjectAnimator animatorAlpha = ObjectAnimator.ofFloat(imageView2, "svgAlpha", 0, 1);
animatorAlpha.setDuration(4000);
animatorAlpha.setRepeatCount(ValueAnimator.INFINITE);
animatorAlpha.setRepeatMode(ValueAnimator.REVERSE);
animatorAlpha.setInterpolator(new LinearInterpolator());
animatorAlpha.start();
final SVGImageView imageView3 = (SVGImageView) findViewById(R.id.animation_svgimageview_image3);
ObjectAnimator animatorWidth = ObjectAnimator.ofInt(imageView3, "svgWidth", 50, 150);
animatorWidth.setDuration(2000);
animatorWidth.setInterpolator(new LinearInterpolator());
animatorWidth.setRepeatCount(ValueAnimator.INFINITE);
animatorWidth.setRepeatMode(ValueAnimator.REVERSE);
animatorWidth.start();
animatorWidth.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// There is a bug in ImageView(ImageButton), in this case, we must call requestLayout() here.
imageView3.requestLayout();
}
});
SVGImageView imageView4 = (SVGImageView) findViewById(R.id.animation_svgimageview_image4);
ObjectAnimator animatorColor = ObjectAnimator.ofInt(imageView4, "svgColor", Color.BLACK, Color.BLUE);
animatorColor.setDuration(2000);
animatorColor.setRepeatCount(ValueAnimator.INFINITE);
animatorColor.setRepeatMode(ValueAnimator.REVERSE);
animatorColor.setInterpolator(new LinearInterpolator());
animatorColor.start();
}
}
| 1,182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.