repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
guilhermejccavalcanti/orientdb
|
object/src/main/java/com/orientechnologies/orient/object/entity/OObjectEntityClassHandler.java
|
/*
*
* Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.object.entity;
import com.orientechnologies.orient.core.entity.OEntityManagerClassHandler;
import com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author <NAME> (<EMAIL>ino.luca--at--<EMAIL>)
*/
public class OObjectEntityClassHandler extends OEntityManagerClassHandler {
private static final ConcurrentMap<String, OObjectEntityClassHandler> instances = new ConcurrentHashMap<String, OObjectEntityClassHandler>();
@Override
public void registerEntityClass(Class<?> iClass) {
registerEntityClass(iClass, true);
}
@Override
public synchronized void registerEntityClass(Class<?> iClass, boolean forceSchemaReload) {
if (!OObjectEntitySerializer.isToSerialize(iClass) && !iClass.isEnum())
registerEntityClass(iClass.getSimpleName(), iClass, forceSchemaReload);
}
@Override
public synchronized void registerEntityClass(String iClassName, Class<?> iClass) {
registerEntityClass(iClassName, iClass, true);
}
@Override
public synchronized void registerEntityClass(String iClassName, Class<?> iClass, boolean forceSchemaReload) {
if (!OObjectEntitySerializer.isToSerialize(iClass) && !iClass.isEnum()) {
OObjectEntitySerializer.registerClass(iClass, forceSchemaReload);
super.registerEntityClass(iClassName, iClass, forceSchemaReload);
}
}
@Override
public synchronized void deregisterEntityClass(Class<?> iClass) {
if (!OObjectEntitySerializer.isToSerialize(iClass) && !iClass.isEnum()) {
OObjectEntitySerializer.deregisterClass(iClass);
super.deregisterEntityClass(iClass);
}
}
public static OObjectEntityClassHandler getInstance(String url) {
OObjectEntityClassHandler classHandler = instances.get(url);
if (classHandler != null)
return classHandler;
classHandler = new OObjectEntityClassHandler();
OObjectEntityClassHandler oldClassHandler = instances.putIfAbsent(url, classHandler);
if (oldClassHandler != null)
classHandler = oldClassHandler;
return classHandler;
}
}
|
davidmoser/Activiti
|
modules/activiti-camel/src/main/java/org/activiti/camel/ActivitiEndpoint.java
|
<gh_stars>1-10
/* 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.activiti.camel;
import org.activiti.engine.RuntimeService;
import org.apache.camel.*;
import org.apache.camel.impl.DefaultEndpoint;
public class ActivitiEndpoint extends DefaultEndpoint {
private RuntimeService runtimeService;
private ActivitiConsumer activitiConsumer;
private boolean copyVariablesToProperties = true;
private boolean copyVariablesToBody = false;
private boolean copyVariablesFromProperties = false;
public ActivitiEndpoint(String uri, CamelContext camelContext, RuntimeService runtimeService) {
super(uri, camelContext);
this.runtimeService = runtimeService;
}
void addConsumer(ActivitiConsumer consumer) {
if (activitiConsumer != null) {
throw new RuntimeException("Activit consumer already defined for " + getEndpointUri() + "!");
}
activitiConsumer = consumer;
}
public void process(Exchange ex) throws Exception {
if (activitiConsumer == null) {
throw new RuntimeException("Activiti consumer not defined for " + getEndpointUri());
}
activitiConsumer.getProcessor().process(ex);
}
public Producer createProducer() throws Exception {
return new ActivitiProducer(this, runtimeService);
}
public Consumer createConsumer(Processor processor) throws Exception {
return new ActivitiConsumer(this, processor);
}
public boolean isSingleton() {
return true;
}
public boolean isCopyVariablesToProperties() {
return copyVariablesToProperties;
}
public void setCopyVariablesToProperties(boolean copyVariablesToProperties) {
this.copyVariablesToProperties = copyVariablesToProperties;
}
public boolean isCopyVariablesToBody() {
return copyVariablesToBody;
}
public void setCopyVariablesToBody(boolean copyVariablesToBody) {
this.copyVariablesToBody = copyVariablesToBody;
}
public boolean isCopyVariablesFromProperties() {
return copyVariablesFromProperties;
}
public void setCopyVariablesFromProperties(boolean copyVariablesFromProperties) {
this.copyVariablesFromProperties = copyVariablesFromProperties;
}
@Override
public boolean isLenientProperties() {
return true;
}
}
|
npocmaka/Windows-Server-2003
|
base/cluster/mgmt/cluscfg/basecluster/cbaseclusteraddnode.h
|
<reponame>npocmaka/Windows-Server-2003
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000 Microsoft Corporation
//
// Module Name:
// CBaseClusterAddNode.h
//
// Description:
// Header file for CBaseClusterAddNode class.
//
// The CBaseClusterAddNode class is a class that captures the commonality
// between forming and joining a cluster.
//
// Implementation Files:
// CBaseClusterAddNode.cpp
//
// Maintained By:
// <NAME> (Vvasu) 03-MAR-2000
//
//////////////////////////////////////////////////////////////////////////////
// Make sure that this file is included only once per compile path.
#pragma once
//////////////////////////////////////////////////////////////////////////
// Include Files
//////////////////////////////////////////////////////////////////////////
// For the base class of this class.
#include "CBaseClusterAction.h"
// For LsaClose, LSA_HANDLE, etc.
#include <ntsecapi.h>
// For the CStr class.
#include "CStr.h"
//////////////////////////////////////////////////////////////////////////////
//++
//
// class CBaseClusterAddNode
//
// Description:
// The CBaseClusterAddNode class is a class that captures the commonality
// between forming and joining a cluster.
//
//--
//////////////////////////////////////////////////////////////////////////////
class CBaseClusterAddNode : public CBaseClusterAction
{
public:
//////////////////////////////////////////////////////////////////////////
// Public accessors
//////////////////////////////////////////////////////////////////////////
// Get the name of the cluster being formed or joined.
const CStr &
RStrGetClusterName( void ) const throw() { return m_strClusterName; }
// Get the NetBIOS name of the cluster being formed or joined.
const CStr &
RStrGetClusterNetBIOSName( void ) const throw() { return m_strClusterNetBIOSName; }
// Get the name of this node.
const WCHAR *
PszGetNodeName( void ) const throw() { return m_szComputerName; }
// Get the length of the name of this node..
DWORD
DwGetNodeNameLength( void ) const throw() { return m_dwComputerNameLen; }
// Get the node highest version.
DWORD
DwGetNodeHighestVersion( void ) const throw() { return m_dwNodeHighestVersion; }
// Get the node lowest version.
DWORD
DwGetNodeLowestVersion( void ) const throw() { return m_dwNodeLowestVersion; }
// Get the cluster IP Address.
DWORD
DwGetClusterIPAddress( void ) const throw() { return m_dwClusterIPAddress; }
// Get the cluster service account credentials.
IClusCfgCredentials &
GetServiceAccountCredentials( void ) const throw() { return *m_pcccServiceAccount; }
// Get the cluster service account UPN
CStr
StrGetServiceAccountUPN( void );
// Get the cluster binding string.
const CStr &
RStrGetClusterBindingString( void ) const throw() { return m_strClusterBindingString; }
// Get the SID of the cluster service account.
SID *
PSidGetServiceAccountSID( void ) const throw() { return m_sspClusterAccountSid.PMem(); }
// Get the LSA policy handle.
LSA_HANDLE
HGetLSAPolicyHandle( void ) const throw() { return m_slsahPolicyHandle.HHandle(); }
// Get the NodeId of this node.
virtual const WCHAR *
PszGetNodeIdString( void ) const throw() = 0;
// Indicates if version checking is disabled or not.
bool
FIsVersionCheckingDisabled( void ) const throw() { return m_fIsVersionCheckingDisabled; }
protected:
//////////////////////////////////////////////////////////////////////////
// Constructors and destructors
//////////////////////////////////////////////////////////////////////////
// Constructor.
CBaseClusterAddNode(
CBCAInterface * pbcaiInterfaceIn
, const WCHAR * pcszClusterNameIn
, const WCHAR * pszClusterBindingStringIn
, IClusCfgCredentials * pcccServiceAccountIn
, DWORD dwClusterIPAddressIn
);
// Default destructor.
~CBaseClusterAddNode( void ) throw();
//////////////////////////////////////////////////////////////////////////
// Protected accessors
//////////////////////////////////////////////////////////////////////////
// Set the name of the cluster being formed.
void
SetClusterName( const WCHAR * pszClusterNameIn );
// Set the cluster IP Address
void
SetClusterIPAddress( DWORD dwClusterIPAddressIn )
{
m_dwClusterIPAddress = dwClusterIPAddressIn;
}
void
SetVersionCheckingDisabled( bool fDisabledIn = true )
{
m_fIsVersionCheckingDisabled = fDisabledIn;
}
private:
//////////////////////////////////////////////////////////////////////////
// Private types
//////////////////////////////////////////////////////////////////////////
typedef CBaseClusterAction BaseClass;
typedef CSmartGenericPtr< CPtrTrait< SID > > SmartSIDPtr;
typedef CSmartResource<
CHandleTrait<
LSA_HANDLE
, NTSTATUS
, LsaClose
>
>
SmartLSAHandle;
//////////////////////////////////////////////////////////////////////////
// Private data
//////////////////////////////////////////////////////////////////////////
// Name of the cluster
CStr m_strClusterName;
CStr m_strClusterNetBIOSName;
// Name and version information of this computer
WCHAR m_szComputerName[ MAX_COMPUTERNAME_LENGTH + 1 ];
DWORD m_dwComputerNameLen;
DWORD m_dwNodeHighestVersion;
DWORD m_dwNodeLowestVersion;
DWORD m_dwClusterIPAddress;
bool m_fIsVersionCheckingDisabled;
// Cluster service account information.
IClusCfgCredentials * m_pcccServiceAccount;
CStr m_strClusterDomainAccount;
CStr m_strClusterBindingString;
SmartSIDPtr m_sspClusterAccountSid;
// Smart handle to the LSA policy.
SmartLSAHandle m_slsahPolicyHandle;
}; //*** class CBaseClusterAddNode
|
ematusov/mBaas-service
|
node_modules/fh-mbaas-api/node_modules/fh-security/node_modules/node-rsa/.tmp/speed.js
|
var NodeRSA = require('../src/NodeRSA');
var key = new NodeRSA({b:1024}, {environment: 'browser'});
var text = 'Hello RSA!';
var encrypted = key.encrypt(text, 'base64');
var decrypted = key.decrypt(encrypted, 'utf8');
console.log(decrypted);
console.time('browser encrypt');
for(var i = 0; i < 100; i++) {
var encrypted = key.encrypt(text, 'base64');
var decrypted = key.decrypt(encrypted, 'utf8');
}
console.timeEnd('browser encrypt');
console.time('browser encrypt (another key)');
for(var i = 0; i < 100; i++) {
var encrypted = key.encryptPrivate(text, 'base64');
var decrypted = key.decryptPublic(encrypted, 'utf8');
}
console.timeEnd('browser encrypt (another key)');
var key = new NodeRSA({b:1024}, {encryptionScheme: 'pkcs1'});
var text = 'Hello RSA!';
var encrypted = key.encrypt(text, 'base64');
var decrypted = key.decrypt(encrypted, 'utf8');
console.log(decrypted);
console.time('node encrypt');
for(var i = 0; i < 100; i++) {
var encrypted = key.encrypt(text, 'base64');
var decrypted = key.decrypt(encrypted, 'utf8');
}
console.timeEnd('node encrypt');
console.time('node encrypt (another key)');
for(var i = 0; i < 100; i++) {
var encrypted = key.encryptPrivate(text, 'base64');
var decrypted = key.decryptPublic(encrypted, 'utf8');
}
console.timeEnd('node encrypt (another key)');
|
jaamal/overclocking
|
sources/Algorithms/src/patternMatching/fcpm/table/builder/APTableBuilderFactory.java
|
<reponame>jaamal/overclocking<filename>sources/Algorithms/src/patternMatching/fcpm/table/builder/APTableBuilderFactory.java
package patternMatching.fcpm.table.builder;
import patternMatching.fcpm.MultiThreadPatternMatchingContextFactory;
import patternMatching.fcpm.MultiThreadWithSharedTablePatternMatchingContextFactory;
import patternMatching.fcpm.SingleThreadPatternMatchingContextFactory;
import patternMatching.fcpm.localsearch.*;
import patternMatching.fcpm.table.APTableCellCalculator;
public final class APTableBuilderFactory implements IAPTableBuilderFactory {
public APTableBuilderFactory() {
}
@Override
public IAPTableBuilder create(IPatternMatchingConfig config) {
ILocalSearchExecutor localSearchExecutor = createLocalSearch(config.getLocalSearchStrategy());
switch (config.getExecutionStrategy()) {
case SingleThread:
return new SimpleAPTableBuilder(new SingleThreadPatternMatchingContextFactory(config), new APTableCellCalculator(localSearchExecutor));
case MultiThreadWithAggregation: {
ITextIteratorFactory textIteratorFactory = config.getTextsIterationStrategy() == TextsIterationStrategy.Interval ? new IntervalTextIteratorFactory() : new OrderedTextIteratorFactory();
IConcurrentBuildingStatisticsFactory buildingStatisticsFactory = config.withStatistics() ? new ConcurrentBuildingStatisticsFactory() : IConcurrentBuildingStatisticsFactory.DummyFactory;
APTableCellCalculator tableCellCalculator = new APTableCellCalculator(localSearchExecutor);
return new ConcurrentAPTableBuilder(config.getThreadCount(), textIteratorFactory, new MultiThreadPatternMatchingContextFactory(config), tableCellCalculator, new ArithmeticProgressionListFactory(), buildingStatisticsFactory);
}
case MultiThreadWithSharedTable: {
ITextIteratorFactory textIteratorFactory = config.getTextsIterationStrategy() == TextsIterationStrategy.Interval ? new IntervalTextIteratorFactory() : new OrderedTextIteratorFactory();
IConcurrentBuildingStatisticsFactory buildingStatisticsFactory = config.withStatistics() ? new ConcurrentBuildingStatisticsFactory() : IConcurrentBuildingStatisticsFactory.DummyFactory;
APTableCellCalculator tableCellCalculator = new APTableCellCalculator(localSearchExecutor);
return new ConcurrentAPTableBuilderWithSharedTable(config.getThreadCount(), textIteratorFactory, new MultiThreadWithSharedTablePatternMatchingContextFactory(config), tableCellCalculator, new ArithmeticProgressionListFactory(), buildingStatisticsFactory);
}
}
throw new IllegalStateException();
}
private ILocalSearchExecutor createLocalSearch(LocalSearchStrategy strategy) {
switch (strategy) {
case Classic:
return new ClassicLocalSearchExecutor(new LocalSearchResultFactory());
case Iterative:
return new IterativeLocalSearchExecutor(new LocalSearchResultFactory());
case Recursive:
return new RecursiveLocalSearchExecutor(new LocalSearchResultFactory());
case RecursiveWithContains:
return new RecursiveLocalSearchExecutorWithContains(new LocalSearchResultFactory());
}
throw new IllegalStateException();
}
}
|
jeozey/XmppServerTester
|
xmpp-core-client/src/main/java/rocks/xmpp/core/session/ReconnectionStrategy.java
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package rocks.xmpp.core.session;
import rocks.xmpp.core.stream.StreamErrorException;
import rocks.xmpp.core.stream.model.errors.Condition;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* A strategy for reconnection logic, i.e. when and in which interval reconnection attempts will happen. You can provide your own strategy by implementing this interface.
* <p>
* Alternatively you can use some of the predefined strategies which you can retrieve by one of the static methods.
* </p>
* E.g. {@link #alwaysAfter(Duration)} always tries to reconnect after a fix amount of time.
*
* @author <NAME>
* @see rocks.xmpp.core.session.XmppSessionConfiguration.Builder#reconnectionStrategy(ReconnectionStrategy)
*/
@FunctionalInterface
public interface ReconnectionStrategy {
default boolean mayReconnect(int attempt, Throwable e) {
// By default allow reconnection only if it's not caused by a <conflict/> stream error.
return !(e instanceof StreamErrorException) || ((StreamErrorException) e).getCondition() != Condition.CONFLICT;
}
/**
* Gets the duration after which the next reconnection is attempted.
*
* @param attempt The current reconnection attempt. The first attempt is 0, the second attempt is 1, etc...
* @param cause The cause for the disconnection.
* @return The the duration after which the next reconnection is attempted.
*/
Duration getNextReconnectionAttempt(int attempt, Throwable cause);
/**
* This is the default reconnection strategy.
* <p>
* It exponentially increases the time span from which a random value for the next reconnection attempt is chosen.
* The formula for doing this, is: <code>(2<sup>n</sup> - 1) * s</code>, where <code>n</code> is the number of reconnection attempt and <code>s</code> is the slot time, which is 60 seconds by default.
* </p>
* <p>
* In practice this means, the first reconnection attempt occurs after a random period of time between 0 and 60 seconds.<br>
* The second attempt chooses a random number >= 0 and < 180 seconds.<br>
* The third attempt chooses a random number >= 0 and < 420 seconds.<br>
* The fourth attempt chooses a random number >= 0 and < 900 seconds.<br>
* The fifth attempt chooses a random number >= 0 and < 1860 seconds (= 31 minutes)<br>
* </p>
* <p>
* The strategy is called "truncated", because it won't increase the time span after the nth iteration, which means in the example above, the sixth and any further attempt
* behaves equally to the fifth attempt.
* </p>
* This "truncated binary exponential backoff" is the <a href="http://xmpp.org/rfcs/rfc6120.html#tcp-reconnect">recommended reconnection strategy by the XMPP specification</a>.
*
* @param slotTime The slot time (in seconds), usually 60.
* @param ceiling The ceiling, i.e. when the time is truncated. E.g. if the ceiling is 4, the back off is truncated at the 5th reconnection attempt (it starts at zero).
* @return The truncated binary exponential backoff strategy.
*/
static ReconnectionStrategy truncatedBinaryExponentialBackoffStrategy(int slotTime, int ceiling) {
return new TruncatedBinaryExponentialBackoffStrategy(slotTime, ceiling);
}
/**
* Reconnects always after a fix duration, e.g. after 10 seconds. When a disconnection is detected the first reconnection attempt is started after the given duration.
* If the attempt fails, the second one is started again after the same duration and so on.
*
* @param duration The fix duration after which a reconnection is attempted.
* @return The reconnection strategy.
*/
static ReconnectionStrategy alwaysAfter(Duration duration) {
return (attempt, cause) -> duration;
}
/**
* Reconnects always after a random duration which lies between the given min and max duration, e.g. after 10-20 seconds.
*
* @param min The min duration after which a reconnection is attempted.
* @param max The max duration.
* @return The reconnection strategy.
*/
static ReconnectionStrategy alwaysRandomlyAfter(Duration min, Duration max) {
return (attempt, cause) -> Duration.ofSeconds(ThreadLocalRandom.current().nextLong(min.getSeconds(), max.getSeconds()));
}
/**
* Uses a hybrid reconnection strategy, which uses the first one on system shutdown and the second one on every other disconnection cause.
*
* @param first The first strategy.
* @param second The second strategy.
* @return The reconnection strategy.
*/
static ReconnectionStrategy onSystemShutdownFirstOrElseSecond(ReconnectionStrategy first, ReconnectionStrategy second) {
return new HybridReconnectionStrategy(first, second, new ReconnectionManager.SystemShutdownPredicate());
}
/**
* Reconnection won't happen automatically, i.e. it's disabled.
*
* @return The reconnection strategy.
*/
static ReconnectionStrategy none() {
return new ReconnectionStrategy() {
@Override
public boolean mayReconnect(int attempt, Throwable cause) {
return false;
}
@Override
public Duration getNextReconnectionAttempt(int attempt, Throwable cause) {
return Duration.ZERO;
}
};
}
}
|
jdleesmiller/twenty48
|
ext/twenty48/policy_writer.cxx
|
#include <string.h>
#include <sstream>
#include "policy_writer.hpp"
namespace twenty48 {
policy_writer_t::policy_writer_t(const char *pathname)
: os(pathname, std::ios::out | std::ios::binary), data(0), offset(0)
{ }
policy_writer_t::~policy_writer_t() {
flush();
}
void policy_writer_t::write(direction_t direction) {
int shift = 2 * (3 - offset);
data |= (direction & 0x3) << shift;
offset += 1;
if (offset % 4 == 0) flush();
}
void policy_writer_t::flush() {
if (offset == 0) return;
os.write(reinterpret_cast<const char *>(&data), sizeof(data));
if (!os) {
std::ostringstream oss;
oss << "policy_writer_t: write failed: " << errno << " " << strerror(errno);
throw std::runtime_error(oss.str());
}
data = 0;
offset = 0;
}
void policy_writer_t::close() {
os.close();
}
}
|
kaz-yamam0t0/php2javascript
|
test/strlen.test.js
|
<gh_stars>1-10
const {strlen} = require("../function/strlen.js");
test("test strlen()", ()=>{
expect(strlen("abcdef")).toStrictEqual(6)
expect(strlen(" ab cd ")).toStrictEqual(7)
expect(strlen("")).toStrictEqual(0)
})
|
tbirdso/ITKUltrasound
|
include/itkBlockMatchingCosineInterpolationDisplacementCalculator.h
|
<gh_stars>10-100
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkBlockMatchingCosineInterpolationDisplacementCalculator_h
#define itkBlockMatchingCosineInterpolationDisplacementCalculator_h
#include "itkBlockMatchingMetricImageToDisplacementCalculator.h"
namespace itk
{
namespace BlockMatching
{
/** \class CosineInterpolationDisplacementCalculator
*
* \brief The displacement around the maximum pixel is interpolated by a cosine
* in each direction and the peak of the cosine is used.
*
* Cespedes et. al. Methods for estimation of subsample time delays of digitized
* echo signals. Ultrasonic Imaging 17. 142-171. 1995.
*
* \ingroup Ultrasound
*/
template <typename TMetricImage, typename TDisplacementImage, typename TCoordRep = double>
class ITK_TEMPLATE_EXPORT CosineInterpolationDisplacementCalculator
: public MetricImageToDisplacementCalculator<TMetricImage, TDisplacementImage>
{
public:
/** Standard class type alias. */
using Self = CosineInterpolationDisplacementCalculator;
using Superclass = MetricImageToDisplacementCalculator<TMetricImage, TDisplacementImage>;
using Pointer = SmartPointer<Self>;
using ConstPointer = SmartPointer<const Self>;
/** ImageDimension enumeration. */
itkStaticConstMacro(ImageDimension, unsigned int, Superclass::ImageDimension);
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(CosineInterpolationDisplacementCalculator, MetricImageToDisplacementCalculator);
using MetricImageType = typename Superclass::MetricImageType;
using MetricImagePointerType = typename Superclass::MetricImagePointerType;
using PixelType = typename MetricImageType::PixelType;
using SpacingType = typename MetricImageType::SpacingType;
using PointType = typename Superclass::PointType;
using IndexType = typename Superclass::IndexType;
virtual void
SetMetricImagePixel(const PointType & point, const IndexType & index, MetricImageType * image);
virtual void
Compute()
{
// We do this here instead of SetMetricImagePixel so it only has to be done
// once.
this->m_DisplacementImage->Modified();
};
protected:
CosineInterpolationDisplacementCalculator();
private:
CosineInterpolationDisplacementCalculator(const Self &);
void
operator=(const Self &);
};
} // namespace BlockMatching
} // namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
# include "itkBlockMatchingCosineInterpolationDisplacementCalculator.hxx"
#endif
#endif
|
peakforest/peakforest-webapp
|
src/main/webapp/resources/js/JSmol/j2s/java/lang/NoSuchMethodError.js
|
<gh_stars>100-1000
Clazz.load(["java.lang.IncompatibleClassChangeError"],"java.lang.NoSuchMethodError",null,function(){
c$=Clazz.declareType(java.lang,"NoSuchMethodError",IncompatibleClassChangeError);
});
|
coderzzz/Shuangyin
|
iwen/iwen/Controllers/Login/Controller/RegistViewController.h
|
<reponame>coderzzz/Shuangyin<filename>iwen/iwen/Controllers/Login/Controller/RegistViewController.h
//
// RegistViewController.h
// iwen
//
// Created by Interest on 15/10/9.
// Copyright (c) 2015年 Interest. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface RegistViewController : BaseViewController
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UITextField *wordField;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (weak, nonatomic) IBOutlet UIButton *checkBtn;
@property (weak, nonatomic) IBOutlet UIButton *txtBtn;
@property (copy, nonatomic) NSString *type;
@property (nonatomic, strong) NSString *isTourist;
@property (weak, nonatomic) IBOutlet UIView *bumView;
- (IBAction)getWordAction:(id)sender;
- (IBAction)nextAction:(id)sender;
- (IBAction)checkAction:(id)sender;
- (IBAction)txtAction:(id)sender;
@end
|
MXPOL/velo-external-db
|
packages/velo-external-db-core/test/drivers/date_time_provider_test_support.js
|
const current = new Date()
const dateTime = {
currentDateTime: () => current,
}
module.exports = dateTime
|
linuxlsx/Algo
|
src/main/java/org/linuxlsx/algo/leetcode/PartitionList.java
|
package org.linuxlsx.algo.leetcode;
public class PartitionList {
/**
* 时间复杂度 O(n)
* @param head
* @param x
* @return
*/
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null) {
return null;
}
ListNode swap = null;
ListNode first = new ListNode(-1, head);
//找到列表中的插入点
while (first.next != null){
if(first.next.val >= x){
break;
}
first = first.next;
}
ListNode node = first.next;
while (node != null){
if(node.next != null){
if(node.next.val < x){
//将node.next 和 first.next 交换
swap = node.next;
node.next = node.next.next;
swap.next = first.next;
//这里判断下如果交换的是head
if(first.next == head){
head = swap;
}
first.next = swap;
first = swap;
}else {
node = node.next;
}
}else {
break;
}
}
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(2);
head.next = new ListNode(1);
// head.next.next = new ListNode(3);
// head.next.next.next = new ListNode(2);
// head.next.next.next.next = new ListNode(5);
// head.next.next.next.next.next = new ListNode(2);
// head.next.next.next.next.next.next = new ListNode(1);
//
PartitionList partitionList = new PartitionList();
ListNode newHead = partitionList.partition(head, 2);
if (newHead != null) {
do {
System.out.println(newHead);
}while ((newHead = newHead.next) != null);
}else {
System.out.println("null");
}
}
}
|
wangxs123/copy
|
hsweb-message/hsweb-message-api/src/main/java/org/hswebframework/web/message/support/simple/SimpleServiceInvokerMessage.java
|
<reponame>wangxs123/copy
package org.hswebframework.web.message.support.simple;
import org.hswebframework.web.message.support.ServiceInvokerMessage;
import java.io.Serializable;
/**
* TODO 完成注释
*
* @author zhouhao
*/
public class SimpleServiceInvokerMessage implements ServiceInvokerMessage {
private String serviceName;
private String method;
private Serializable[] args;
@Override
public String getServiceName() {
return serviceName;
}
@Override
public String getMethod() {
return method;
}
@Override
public Serializable[] getArgs() {
return args;
}
public void setArgs(Serializable[] args) {
this.args = args;
}
public void setMethod(String method) {
this.method = method;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public SimpleServiceInvokerMessage(String serviceName, String method, Serializable... args) {
this.serviceName = serviceName;
this.method = method;
this.args = args;
}
public SimpleServiceInvokerMessage() {
}
}
|
TextC0de/pasapalabra
|
server/helpers/dates.js
|
export const getDiffInSeconds = (finalDate, initialDate) => (finalDate - initialDate) / 1000;
|
hackingbear/deeplearning4j
|
deeplearning4j-scaleout/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/sentenceiterator/LuceneSentenceIterator.java
|
package org.deeplearning4j.text.sentenceiterator;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
import org.deeplearning4j.berkeley.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Lucene sentence iterator.
* Read a sentence index
* and produce sentences.
*
* @author <NAME>
*/
public class LuceneSentenceIterator implements SentenceIterator {
private Directory dir;
private transient IndexReader reader;
public final static String WORD_FIELD = "word";
private int index = 0;
private SentencePreProcessor preProcessor;
private List<Integer> docs;
public LuceneSentenceIterator(Directory dir) {
try {
this.dir = dir;
reader = DirectoryReader.open(dir);
docs = allDocs();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String nextSentence() {
Document doc = null;
try {
doc = reader.document(docs.get(index));
index++;
} catch (IOException e) {
e.printStackTrace();
}
String[] values = doc.getValues(WORD_FIELD);
return StringUtils.join(values," ");
}
@Override
public boolean hasNext() {
return index < docs.size();
}
@Override
public void reset() {
index = 0;
}
@Override
public void finish() {
IOUtils.closeQuietly(reader);
}
@Override
public SentencePreProcessor getPreProcessor() {
return preProcessor;
}
@Override
public void setPreProcessor(SentencePreProcessor preProcessor) {
this.preProcessor = preProcessor;
}
private List<Integer> allDocs() {
List<Integer> docIds = new ArrayList<>();
Bits liveDocs = MultiFields.getLiveDocs(reader);
for(int i = 0; i < reader.maxDoc() + 1; i++) {
if (liveDocs != null && !liveDocs.get(i))
continue;
docIds.add(i);
}
return docIds;
}
}
|
hiaux0/Coding-2
|
client/ListMapper/list-mapper/db.js
|
export default {
"shortcuts": [
{
"content": "C-a :",
"position": 0
},
{
"content": "C-b :",
"position": 1
},
{
"content": "C-c :",
"position": 2
},
{
"content": "C-d :",
"position": 3
},
{
"content": "C-e :",
"position": 4
},
{
"content": "C-f :",
"position": 5
},
{
"content": "C-g :",
"position": 6
},
// {
// "content": "C-h :",
// "position": 7
// },
// {
// "content": "C-i :",
// "position": 8
// },
// {
// "content": "C-j :",
// "position": 9
// },
// {
// "content": "C-k :",
// "position": 10
// },
// {
// "content": "C-l :",
// "position": 11
// },
// {
// "content": "C-m :",
// "position": 12
// },
// {
// "content": "C-n :",
// "position": 13
// },
// {
// "content": "C-o :",
// "position": 14
// },
// {
// "content": "C-p :",
// "position": 15
// },
// {
// "content": "C-q :",
// "position": 16
// },
// {
// "content": "C-r :",
// "position": 17
// },
// {
// "content": "C-s :",
// "position": 18
// },
// {
// "content": "C-t :",
// "position": 19
// },
// {
// "content": "C-u :",
// "position": 20
// },
// {
// "content": "C-v :",
// "position": 21
// },
// {
// "content": "C-w :",
// "position": 22
// },
// {
// "content": "C-x :",
// "position": 23
// },
// {
// "content": "C-y :",
// "position": 24
// },
// {
// "content": "C-z :",
// "position": 25
// }
],
"commands": [
{
"content": "Command-a :",
"position": 0
},
{
"content": "Command-b :",
"position": 1
},
{
"content": "Command-c :",
"position": 2
},
{
"content": "Command-d :",
"position": 3
},
{
"content": "Command-e :",
"position": 4
},
{
"content": "Command-f :",
"position": 5
},
{
"content": "Command-g :",
"position": 6
},
{
"content": "Command-h :",
"position": 7
},
{
"content": "Command-i :",
"position": 8
},
{
"content": "Command-j :",
"position": 9
},
{
"content": "Command-k :",
"position": 10
},
{
"content": "Command-l :",
"position": 11
},
{
"content": "Command-m :",
"position": 12
},
{
"content": "Command-n :",
"position": 13
},
{
"content": "Command-o :",
"position": 14
},
{
"content": "Command-p :",
"position": 15
},
{
"content": "Command-q :",
"position": 16
},
{
"content": "Command-r :",
"position": 17
},
{
"content": "Command-s :",
"position": 18
},
{
"content": "Command-t :",
"position": 19
},
{
"content": "Command-u :",
"position": 20
},
{
"content": "Command-v :",
"position": 21
},
{
"content": "Command-w :",
"position": 22
},
{
"content": "Command-x :",
"position": 23
},
{
"content": "Command-y :",
"position": 24
},
{
"content": "Command-z :",
"position": 25
}
],
"breadcrumbs": [
{
"content": "breadcrumbs.focus",
"position": 0
},
{
"content": "breadcrumbs.focusAndSelect",
"position": 1
},
{
"content": "breadcrumbs.focusNext",
"position": 2
},
{
"content": "breadcrumbs.focusNext",
"position": 3
},
{
"content": "breadcrumbs.focusPrevious",
"position": 4
},
{
"content": "breadcrumbs.focusPrevious",
"position": 5
},
{
"content": "breadcrumbs.revealFocused",
"position": 6
},
{
"content": "breadcrumbs.revealFocused",
"position": 7
},
{
"content": "breadcrumbs.revealFocusedFromTreeAside",
"position": 8
},
{
"content": "breadcrumbs.selectEditor",
"position": 9
},
{
"content": "breadcrumbs.selectFocused",
"position": 10
},
{
"content": "breadcrumbs.selectFocused",
"position": 11
},
]
}
|
pageinsec/security_content
|
bin/automated_detection_testing/ci/labeled_data/labeled_data.py
|
import sys
import argparse
import shutil
import os
from modules.github_service import GithubService
from modules import aws_service, testing_service
DT_ATTACK_RANGE_STATE_STORE = "dt-attack-range-tf-state-store"
DT_ATTACK_RANGE_STATE = "dt-attack-range-state"
REGION = "eu-central-1"
NAME = "detection-testing-attack-range"
def main(args):
github_service = GithubService('develop')
test_files = github_service.get_test_files()
for test_file in test_files:
print(test_file)
dt_ar = aws_service.get_ar_information_from_dynamo_db(REGION, DT_ATTACK_RANGE_STATE)
splunk_instance = aws_service.get_splunk_instance(REGION, dt_ar['ssh_key_name'])
splunk_ip = splunk_instance['NetworkInterfaces'][0]['Association']['PublicIp']
splunk_password = dt_ar['password']
ssh_key_name = dt_ar['ssh_key_name']
private_key = dt_ar['private_key']
testing_service.prepare_detection_testing(ssh_key_name, private_key, splunk_ip, splunk_password)
testing_service.test_detections(ssh_key_name, private_key, splunk_ip, splunk_password, test_files)
# Get Password, private_key and key_name from DynamoDB
# For loop
# Detection Test
if __name__ == "__main__":
main(sys.argv[1:])
|
embrosyn/ja2-stracciatella-mpslsm
|
Build/Tactical/Merc_Hiring.cc
|
#include "Font_Control.h"
#include "Debug.h"
#include "math.h"
#include "MapScreen.h"
#include "MessageBoxScreen.h"
#include "WorldDef.h"
#include "Assignments.h"
#include "Soldier_Control.h"
#include "Animation_Data.h"
#include "Render_Fun.h"
#include "Render_Dirty.h"
#include "MouseSystem.h"
#include "SysUtil.h"
#include "Points.h"
#include "Random.h"
#include "AI.h"
#include "Soldier_Ani.h"
#include "Overhead.h"
#include "Soldier_Profile.h"
#include "Game_Clock.h"
#include "Soldier_Create.h"
#include "Merc_Hiring.h"
#include "Game_Event_Hook.h"
#include "Message.h"
#include "StrategicMap.h"
#include "Strategic.h"
#include "Items.h"
#include "Soldier_Add.h"
#include "History.h"
#include "Squads.h"
#include "Strategic_Merc_Handler.h"
#include "Dialogue_Control.h"
#include "Map_Screen_Interface.h"
#include "Map_Screen_Interface_Map.h"
#include "ScreenIDs.h"
#include "JAScreens.h"
#include "Text.h"
#include "Merc_Contract.h"
#include "LaptopSave.h"
#include "Personnel.h"
#include "Auto_Resolve.h"
#include "Map_Screen_Interface_Bottom.h"
#include "Quests.h"
#define MIN_FLIGHT_PREP_TIME 6
#ifdef JA2TESTVERSION
BOOLEAN gForceHireMerc=FALSE;
void SetFlagToForceHireMerc( BOOLEAN fForceHire );
#endif
extern BOOLEAN gfTacticalDoHeliRun;
extern BOOLEAN gfFirstHeliRun;
// ATE: Globals that dictate where the mercs will land once being hired
// Default to start sector
// Saved in general saved game structure
INT16 g_merc_arrive_sector = START_SECTOR;
INT8 HireMerc(MERC_HIRE_STRUCT& h)
{
ProfileID const pid = h.ubProfileID;
MERCPROFILESTRUCT& p = GetProfile(pid);
// If we are to disregard the status of the merc
#ifdef JA2TESTVERSION
if (!gForceHireMerc)
#endif
{
switch (p.bMercStatus)
{
case 0:
case MERC_ANNOYED_BUT_CAN_STILL_CONTACT:
case MERC_HIRED_BUT_NOT_ARRIVED_YET:
break;
default:
return MERC_HIRE_FAILED;
}
}
if (NumberOfMercsOnPlayerTeam() >= 18) return MERC_HIRE_OVER_20_MERCS_HIRED;
// ATE: if we are to use landing zone, update to latest value
// they will be updated again just before arrival...
if (h.fUseLandingZoneForArrival)
{
h.sSectorX = SECTORX(g_merc_arrive_sector);
h.sSectorY = SECTORY(g_merc_arrive_sector);
h.bSectorZ = 0;
}
SOLDIERCREATE_STRUCT MercCreateStruct;
memset(&MercCreateStruct, 0, sizeof(MercCreateStruct));
MercCreateStruct.ubProfile = pid;
MercCreateStruct.sSectorX = h.sSectorX;
MercCreateStruct.sSectorY = h.sSectorY;
MercCreateStruct.bSectorZ = h.bSectorZ;
MercCreateStruct.bTeam = OUR_TEAM;
MercCreateStruct.fCopyProfileItemsOver = h.fCopyProfileItemsOver;
SOLDIERTYPE* const s = TacticalCreateSoldier(MercCreateStruct);
if (s == NULL)
{
DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "TacticalCreateSoldier in HireMerc(): Failed to Add Merc");
return MERC_HIRE_FAILED;
}
if (DidGameJustStart())
{
// OK, CHECK FOR FIRST GUY, GIVE HIM SPECIAL ITEM!
if (s->ubID == 0)
{
// OK, give this item to our merc!
OBJECTTYPE o;
memset(&o, 0, sizeof(o));
o.usItem = LETTER;
o.ubNumberOfObjects = 1;
o.bStatus[0] = 100;
const BOOLEAN fReturn = AutoPlaceObject(s, &o, FALSE);
(void)fReturn;
Assert(fReturn);
}
// Set insertion for first time in chopper
h.ubInsertionCode = INSERTION_CODE_CHOPPER;
}
// Record how long the merc will be gone for
p.bMercStatus = (UINT8)h.iTotalContractLength;
// Copy over insertion data
s->ubStrategicInsertionCode = h.ubInsertionCode;
s->usStrategicInsertionData = h.usInsertionData;
// ATE: Copy over value for using landing zone to soldier type
s->fUseLandingZoneForArrival = h.fUseLandingZoneForArrival;
// Set assignment
if (s->bAssignment != IN_TRANSIT) SetTimeOfAssignmentChangeForMerc(s);
ChangeSoldiersAssignment(s, IN_TRANSIT);
// Set the contract length
s->iTotalContractLength = h.iTotalContractLength;
// Reset the insurance values
s->iStartOfInsuranceContract = 0;
s->iTotalLengthOfInsuranceContract = 0;
// Store arrival time in soldier structure so map screen can display it
s->uiTimeSoldierWillArrive = h.uiTimeTillMercArrives;
if (DidGameJustStart())
{
// Set time of initial merc arrival in minutes
h.uiTimeTillMercArrives = (STARTING_TIME + FIRST_ARRIVAL_DELAY) / NUM_SEC_IN_MIN;
//set when the merc's contract is finished
s->iEndofContractTime = GetMidnightOfFutureDayInMinutes(s->iTotalContractLength) + GetHourWhenContractDone(s) * 60;
}
else
{
//set when the merc's contract is finished (+1 cause it takes a day for the merc to arrive)
s->iEndofContractTime = GetMidnightOfFutureDayInMinutes(1 + s->iTotalContractLength) + GetHourWhenContractDone(s) * 60;
}
// Set the time and ID of the last hired merc will arrive
LaptopSaveInfo.sLastHiredMerc.iIdOfMerc = pid;
LaptopSaveInfo.sLastHiredMerc.uiArrivalTime = h.uiTimeTillMercArrives;
// If we are trying to hire a merc that should arrive later, put the merc in the queue
if (h.uiTimeTillMercArrives != 0)
{
AddStrategicEvent(EVENT_DELAYED_HIRING_OF_MERC, h.uiTimeTillMercArrives, s->ubID);
// Specify that the merc is hired but has not arrived yet
p.bMercStatus = MERC_HIRED_BUT_NOT_ARRIVED_YET;
}
// Set the type of merc
if (pid < BIFF)
{
s->ubWhatKindOfMercAmI = MERC_TYPE__AIM_MERC;
// Determine how much the contract is, and remember what type of contract he got
switch (h.iTotalContractLength)
{
case 1:
s->bTypeOfLastContract = CONTRACT_EXTEND_1_DAY;
s->iTimeCanSignElsewhere = GetWorldTotalMin();
break;
case 7:
s->bTypeOfLastContract = CONTRACT_EXTEND_1_WEEK;
s->iTimeCanSignElsewhere = GetWorldTotalMin();
break;
case 14:
s->bTypeOfLastContract = CONTRACT_EXTEND_2_WEEK;
// This fellow needs to stay the whole duration!
s->iTimeCanSignElsewhere = s->iEndofContractTime;
break;
}
// remember the medical deposit we PAID. The one in his profile can increase when he levels!
s->usMedicalDeposit = p.sMedicalDepositAmount;
}
else if (pid <= BUBBA)
{
s->ubWhatKindOfMercAmI = MERC_TYPE__MERC;
p.iMercMercContractLength = 1;
// Set starting conditions for the merc
s->iStartContractTime = GetWorldDay();
AddHistoryToPlayersLog(HISTORY_HIRED_MERC_FROM_MERC, pid, GetWorldTotalMin(), -1, -1);
}
else if (pid < MIGUEL)
{
s->ubWhatKindOfMercAmI = MERC_TYPE__PLAYER_CHARACTER;
}
else
{
s->ubWhatKindOfMercAmI = MERC_TYPE__NPC;
}
// remove the merc from the Personnel screens departed list (if they have never been hired before, its ok to call it)
RemoveNewlyHiredMercFromPersonnelDepartedList(s->ubProfile);
gfAtLeastOneMercWasHired = TRUE;
return MERC_HIRE_OK;
}
static void CheckForValidArrivalSector(void);
void MercArrivesCallback(SOLDIERTYPE& s)
{
UINT32 uiTimeOfPost;
if (!DidGameJustStart() && g_merc_arrive_sector == START_SECTOR)
{ /* Mercs arriving in start sector. This sector has been deemed as the always
* safe sector. Seeing we don't support entry into a hostile sector (except
* for the beginning), we will nuke any enemies in this sector first. */
if (gWorldSectorX != SECTORX(START_SECTOR) ||
gWorldSectorY != SECTORY(START_SECTOR) ||
gbWorldSectorZ != 0)
{
EliminateAllEnemies(SECTORX(g_merc_arrive_sector), SECTORY(g_merc_arrive_sector));
}
}
// This will update ANY soldiers currently schedules to arrive too
CheckForValidArrivalSector( );
// stop time compression until player restarts it
StopTimeCompression();
MERCPROFILESTRUCT& p = GetProfile(s.ubProfile);
// add the guy to a squad
AddCharacterToAnySquad(&s);
// ATE: Make sure we use global.....
if (s.fUseLandingZoneForArrival)
{
s.sSectorX = SECTORX(g_merc_arrive_sector);
s.sSectorY = SECTORY(g_merc_arrive_sector);
s.bSectorZ = 0;
}
// Add merc to sector ( if it's the current one )
if (gWorldSectorX == s.sSectorX && gWorldSectorY == s.sSectorY && s.bSectorZ == gbWorldSectorZ)
{
// OK, If this sector is currently loaded, and guy does not have CHOPPER insertion code....
// ( which means we are at beginning of game if so )
// Setup chopper....
if (s.ubStrategicInsertionCode != INSERTION_CODE_CHOPPER &&
SECTOR(s.sSectorX, s.sSectorY) == START_SECTOR)
{
gfTacticalDoHeliRun = TRUE;
// OK, If we are in mapscreen, get out...
if ( guiCurrentScreen == MAP_SCREEN )
{
// ATE: Make sure the current one is selected!
ChangeSelectedMapSector( gWorldSectorX, gWorldSectorY, 0 );
RequestTriggerExitFromMapscreen( MAP_EXIT_TO_TACTICAL );
}
s.ubStrategicInsertionCode = INSERTION_CODE_CHOPPER;
}
UpdateMercInSector(s, s.sSectorX, s.sSectorY, s.bSectorZ);
}
else
{
// OK, otherwise, set them in north area, so once we load again, they are here.
s.ubStrategicInsertionCode = INSERTION_CODE_NORTH;
}
if (s.ubStrategicInsertionCode != INSERTION_CODE_CHOPPER)
{
ScreenMsg(FONT_MCOLOR_WHITE, MSG_INTERFACE, TacticalStr[MERC_HAS_ARRIVED_STR], s.name);
// ATE: He's going to say something, now that they've arrived...
if (!gTacticalStatus.bMercArrivingQuoteBeingUsed && !gfFirstHeliRun)
{
gTacticalStatus.bMercArrivingQuoteBeingUsed = TRUE;
TacticalCharacterDialogue(&s, QUOTE_MERC_REACHED_DESTINATION);
class DialogueEventUnsetArrivesFlag : public DialogueEvent
{
public:
bool Execute()
{
gTacticalStatus.bMercArrivingQuoteBeingUsed = FALSE;
return false;
}
};
DialogueEvent::Add(new DialogueEventUnsetArrivesFlag());
}
}
//record how long the merc will be gone for
p.bMercStatus = (UINT8)s.iTotalContractLength;
// remember when excatly he ARRIVED in Arulco, in case he gets fired early
s.uiTimeOfLastContractUpdate = GetWorldTotalMin();
//set when the merc's contract is finished
s.iEndofContractTime = GetMidnightOfFutureDayInMinutes(s.iTotalContractLength) + GetHourWhenContractDone(&s) * 60;
// Do initial check for bad items
if (s.bTeam == OUR_TEAM)
{
//ATE: Try to see if our equipment sucks!
if (SoldierHasWorseEquipmentThanUsedTo(&s))
{
// Randomly anytime between 9:00, and 10:00
uiTimeOfPost = 540 + Random( 660 );
if ( GetWorldMinutesInDay() < uiTimeOfPost )
{
AddSameDayStrategicEvent(EVENT_MERC_COMPLAIN_EQUIPMENT, uiTimeOfPost, s.ubProfile);
}
}
}
HandleMercArrivesQuotes(s);
fTeamPanelDirty = TRUE;
// if the currently selected sector has no one in it, select this one instead
if ( !CanGoToTacticalInSector( sSelMapX, sSelMapY, ( UINT8 )iCurrentMapSectorZ ) )
{
ChangeSelectedMapSector(s.sSectorX, s.sSectorY, 0);
}
}
bool IsMercHireable(MERCPROFILESTRUCT const& p)
{
/* If the merc has an .edt file, is not away on assignment, and isn't already
* hired (but not arrived yet), he is not dead and he isn't returning home */
return
p.bMercStatus <= 0 &&
p.bMercStatus != MERC_HAS_NO_TEXT_FILE &&
p.bMercStatus != MERC_HIRED_BUT_NOT_ARRIVED_YET &&
p.bMercStatus != MERC_IS_DEAD &&
p.bMercStatus != MERC_RETURNING_HOME &&
p.bMercStatus != MERC_WORKING_ELSEWHERE &&
p.bMercStatus != MERC_FIRED_AS_A_POW &&
p.uiDayBecomesAvailable == 0;
}
bool IsMercDead(MERCPROFILESTRUCT const& p)
{
return p.bMercStatus == MERC_IS_DEAD;
}
void HandleMercArrivesQuotes(SOLDIERTYPE& s)
{
// If we are approaching with helicopter, don't say any ( yet )
if (s.ubStrategicInsertionCode == INSERTION_CODE_CHOPPER) return;
// Player-generated characters issue a comment about arriving in Omerta.
if (s.ubWhatKindOfMercAmI == MERC_TYPE__PLAYER_CHARACTER &&
gubQuest[QUEST_DELIVER_LETTER] == QUESTINPROGRESS)
{
TacticalCharacterDialogue(&s, QUOTE_PC_DROPPED_OMERTA);
}
// Check to see if anyone hates this merc and will now complain
FOR_EACH_IN_TEAM(other, OUR_TEAM)
{
if (other->ubWhatKindOfMercAmI != MERC_TYPE__AIM_MERC) continue;
// hates the merc who has arrived and is going to gripe about it!
switch (WhichHated(other->ubProfile, s.ubProfile))
{
case 0: TacticalCharacterDialogue(other, QUOTE_HATED_1_ARRIVES); break;
case 1: TacticalCharacterDialogue(other, QUOTE_HATED_2_ARRIVES); break;
default: break;
}
}
}
#ifdef JA2TESTVERSION
void SetFlagToForceHireMerc( BOOLEAN fForceHire )
{
gForceHireMerc = fForceHire;
}
#endif
UINT32 GetMercArrivalTimeOfDay( )
{
UINT32 uiCurrHour;
UINT32 uiMinHour;
// Pick a time...
// First get the current time of day.....
uiCurrHour = GetWorldHour( );
// Subtract the min time for any arrival....
uiMinHour = uiCurrHour + MIN_FLIGHT_PREP_TIME;
// OK, first check if we need to advance a whole day's time...
// See if we have missed the last flight for the day...
if ( ( uiCurrHour ) > 13 ) // ( > 1:00 pm - too bad )
{
// 7:30 flight....
return( GetMidnightOfFutureDayInMinutes( 1 ) + MERC_ARRIVE_TIME_SLOT_1 );
}
// Well, now we can handle flights all in one day....
// Find next possible flight
if ( uiMinHour <= 7 )
{
return( GetWorldDayInMinutes() + MERC_ARRIVE_TIME_SLOT_1 ); // 7:30 am
}
else if ( uiMinHour <= 13 )
{
return( GetWorldDayInMinutes() + MERC_ARRIVE_TIME_SLOT_2 ); // 1:30 pm
}
else
{
return( GetWorldDayInMinutes() + MERC_ARRIVE_TIME_SLOT_3 ); // 7:30 pm
}
}
void UpdateAnyInTransitMercsWithGlobalArrivalSector( )
{
FOR_EACH_IN_TEAM(s, OUR_TEAM)
{
if (s->bAssignment == IN_TRANSIT && s->fUseLandingZoneForArrival)
{
s->sSectorX = SECTORX(g_merc_arrive_sector);
s->sSectorY = SECTORY(g_merc_arrive_sector);
s->bSectorZ = 0;
}
}
}
static INT16 StrategicPythSpacesAway(INT16 sOrigin, INT16 sDest)
{
INT16 sRows,sCols,sResult;
sRows = abs((sOrigin / MAP_WORLD_X) - (sDest / MAP_WORLD_X));
sCols = abs((sOrigin % MAP_WORLD_X) - (sDest % MAP_WORLD_X));
// apply Pythagoras's theorem for right-handed triangle:
// dist^2 = rows^2 + cols^2, so use the square root to get the distance
sResult = (INT16)sqrt((double)((sRows * sRows) + (sCols * sCols)));
return(sResult);
}
// ATE: This function will check if the current arrival sector
// is valid
// if there are enemies present, it's invalid
// if so, search around for nearest non-occupied sector.
static void CheckForValidArrivalSector(void)
{
INT16 sTop, sBottom;
INT16 sLeft, sRight;
INT16 cnt1, cnt2;
UINT8 ubRadius = 4;
INT32 leftmost;
INT16 sSectorGridNo, sSectorGridNo2;
INT32 uiRange, uiLowestRange = 999999;
BOOLEAN fFound = FALSE;
wchar_t sString[ 1024 ];
wchar_t zShortTownIDString1[ 50 ];
wchar_t zShortTownIDString2[ 50 ];
sSectorGridNo = SECTOR_INFO_TO_STRATEGIC_INDEX(g_merc_arrive_sector);
// Check if valid...
if ( !StrategicMap[ sSectorGridNo ].fEnemyControlled )
{
return;
}
GetShortSectorString(SECTORX(g_merc_arrive_sector), SECTORY(g_merc_arrive_sector), zShortTownIDString1, lengthof(zShortTownIDString1));
// If here - we need to do a search!
sTop = ubRadius;
sBottom = -ubRadius;
sLeft = - ubRadius;
sRight = ubRadius;
INT16 sGoodX = 0; // XXX HACK000E
INT16 sGoodY = 0; // XXX HACK000E
for( cnt1 = sBottom; cnt1 <= sTop; cnt1++ )
{
leftmost = ( ( sSectorGridNo + ( MAP_WORLD_X * cnt1 ) )/ MAP_WORLD_X ) * MAP_WORLD_X;
for( cnt2 = sLeft; cnt2 <= sRight; cnt2++ )
{
sSectorGridNo2 = sSectorGridNo + ( MAP_WORLD_X * cnt1 ) + cnt2;
if( sSectorGridNo2 >=1 && sSectorGridNo2 < ( ( MAP_WORLD_X - 1 ) * ( MAP_WORLD_X - 1 ) ) && sSectorGridNo2 >= leftmost && sSectorGridNo2 < ( leftmost + MAP_WORLD_X ) )
{
if ( !StrategicMap[ sSectorGridNo2 ].fEnemyControlled && !StrategicMap[ sSectorGridNo2 ].fEnemyAirControlled )
{
uiRange = StrategicPythSpacesAway( sSectorGridNo2, sSectorGridNo );
if ( uiRange < uiLowestRange )
{
sGoodY = cnt1;
sGoodX = cnt2;
uiLowestRange = uiRange;
fFound = TRUE;
}
}
}
}
}
if ( fFound )
{
g_merc_arrive_sector = SECTOR(SECTORX(g_merc_arrive_sector) + sGoodX, SECTORY(g_merc_arrive_sector) + sGoodY);
UpdateAnyInTransitMercsWithGlobalArrivalSector( );
GetShortSectorString(SECTORX(g_merc_arrive_sector), SECTORY(g_merc_arrive_sector), zShortTownIDString2, lengthof(zShortTownIDString2));
swprintf(sString, lengthof(sString), str_arrival_rerouted, zShortTownIDString2, zShortTownIDString1);
DoScreenIndependantMessageBox( sString, MSG_BOX_FLAG_OK, NULL );
}
}
|
Lucioric2000/jsorolla
|
src/core/webcomponents/individual/opencga-individual-inferred-sex-view.js
|
/**
* Copyright 2015-2019 OpenCB
*
* 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 {LitElement, html} from "/web_modules/lit-element.js";
import UtilsNew from "../../utilsNew.js";
import "../commons/view/data-form.js";
export default class OpencgaIndividualInferredSexView extends LitElement {
constructor() {
super();
this._init();
}
createRenderRoot() {
return this;
}
static get properties() {
return {
opencgaSession: {
type: Object
},
individualId: {
type: String
},
individual: {
type: Object
},
individuals: {
type: Array
},
config: {
type: Object
}
};
}
_init() {
this._config = this.getDefaultConfig();
}
connectedCallback() {
super.connectedCallback();
this._config = {...this.getDefaultConfig(), ...this.config};
}
updated(changedProperties) {
if (changedProperties.has("individual")) {
this.individuals = [this.individual];
}
if (changedProperties.has("individualId")) {
this.individualIdObserver();
}
if (changedProperties.has("individuals")) {
this.requestUpdate();
}
if (changedProperties.has("config")) {
this._config = {...this.getDefaultConfig(), ...this.config};
}
}
individualIdObserver() {
if (this.opencgaSession && this.individualId) {
this.opencgaSession.opencgaClient.individuals().info(this.individualId, {study: this.opencgaSession.study.fqn})
.then( response => {
this.individuals = response.responses[0].results;
// this.requestUpdate();
})
.catch(function(reason) {
console.error(reason);
});
}
}
onDownload(e) {
let dataString = [];
let mimeType = "";
let extension = "";
// Check if user clicked in Tab or JSON format
if (e.currentTarget.dataset.downloadOption.toLowerCase() === "tab") {
const data = this.individuals.map(individual => {
let inferredSex = individual?.qualityControl?.inferredSexReports[0];
return [
individual.id,
individual?.qualityControl?.sampleId ?? "N/A",
individual.karyotypicSex,
...(inferredSex ?
[
inferredSex.values.ratioX.toFixed(4),
inferredSex.values.ratioY.toFixed(4),
inferredSex.inferredKaryotypicSex ?? "-",
inferredSex.method
] : ["-", "-", "-", "-"])
].join("\t")
});
dataString = [
[
"Individual ID",
"Sample ID", "Sex",
"Reported Phenotypic Sex",
"Reported Karyotypic Sex",
"Ratio (avg. chrX/auto)",
"Ratio (avg. chrY/auto)",
"Inferred Karyotypic Sex",
"Method"
].join("\t"),
data.join("\n")
];
//console.log(dataString);
mimeType = "text/plain";
extension = ".txt";
} else {
const data = this.individuals.map(individual => {
return {
id: individual.id,
sampleId: individual?.qualityControl?.sampleId ?? "N/A",
karyotypicSex: individual.karyotypicSex,
...individual?.qualityControl?.inferredSexReports[0]
};
});
dataString = [JSON.stringify(data, null, "\t")];
mimeType = "application/json";
extension = ".json";
}
// Build file and anchor link
const data = new Blob([dataString.join("\n")], {type: mimeType});
const file = window.URL.createObjectURL(data);
const a = document.createElement("a");
a.href = file;
a.download = this.opencgaSession.study.alias + extension;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
}, 0);
}
renderTable() {
if (this.individuals && Array.isArray(this.individuals)) {
// let _cellPadding = "padding: 0px 15px";
return html`
<table class="table table-hover table-no-bordered text-center">
<thead>
<tr>
<th>Individual ID</th>
<th>Sample ID</th>
<th>Reported Phenotypic Sex</th>
<th>Reported Karyotypic Sex</th>
<th>Ratio (avg. chrX/auto)</th>
<th>Ratio (avg. chrY/auto)</th>
<th>Inferred Karyotypic Sex</th>
<th>Method</th>
<!-- <th>Status</th> -->
</tr>
</thead>
<tbody>
${this.individuals.map(individual => {
let inferredSex = individual?.qualityControl?.inferredSexReports[0];
return html`
<tr>
<td>
<label>${individual.id}</label>
</td>
<td>${individual?.qualityControl?.sampleId ?? "N/A"}</td>
<td>${individual.sex}</td>
<td>
<span style="color: ${!inferredSex || individual.karyotypicSex === inferredSex?.inferredKaryotypicSex ? "black" : "red"}">
${individual.karyotypicSex}
</span>
</td>
${inferredSex ? html`
<td>${inferredSex.values.ratioX.toFixed(4)}</td>
<td>${inferredSex.values.ratioY.toFixed(4)}</td>
<td>
<span style="color: ${individual.karyotypicSex === inferredSex.inferredKaryotypicSex ? "black" : "red"}">
${inferredSex.inferredKaryotypicSex || "-"}
</span>
</td>
<td>${inferredSex.method}</td>
<!--
<td>
<span>${individual.karyotypicSex === inferredSex.inferredKaryotypicSex
? html`<i class='fa fa-check' style='color: green'></i>`
: html`<i class='fa fa-times' style='color: red'></i>`
}
</span>
</td>
-->
` : html`
<td colspan="4"><div class="alert-warning text-center"><i class="fas fa-info-circle align-middle"></i> Inferred Sex data not available.</div></td>
`}
</tr>
`})
}
</tbody>
</table>`;
}
}
getDefaultConfig() {
return {
download: ["Tab", "JSON"]
}
}
render() {
if (!this.individual?.qualityControl && !this.individuals?.length) {
return html`<div class="alert alert-info"><i class="fas fa-3x fa-info-circle align-middle"></i> No QC data are available yet.</div>`;
}
return html`
<div>
<div class="btn-group pull-right">
<button type="button" class="btn btn-default ripple btn-xs dropdown-toggle" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-download pad5" aria-hidden="true"></i> Download <span class="caret"></span>
</button>
<ul class="dropdown-menu btn-sm">
${this._config?.download && this._config?.download?.length ? this._config.download.map(item => html`
<li><a href="javascript:;" data-download-option="${item}" @click="${this.onDownload}">${item}</a></li>
`) : null}
</ul>
</div>
<div>
${this.renderTable()}
</div>
</div>
`;
}
}
customElements.define("opencga-individual-inferred-sex-view", OpencgaIndividualInferredSexView);
|
cjang/chai
|
jitast/TransMatmul.cpp
|
<gh_stars>10-100
// Copyright 2011 <NAME> (<EMAIL>) under The Artistic License 2.0
#include "AstMatmulVV.hpp"
#include "AstMatmulVM.hpp"
#include "AstMatmulMV.hpp"
#include "AstMatmulMM.hpp"
#include "TransMatmul.hpp"
namespace chai_internal {
////////////////////////////////////////
// dispatched operation
BaseAst* TransMatmul::sub_eval(void) const
{
const size_t leftH = _argStack[0]->H();
const size_t rightH = _argStack[1]->H();
if ( (1 == leftH) && (1 == rightH) )
{
// vector * vector
return
new AstMatmulVV(_argStack[0],
_argStack[1]);
}
else if (1 == leftH)
{
// vector * matrix
return
new AstMatmulVM(_argStack[0],
_argStack[1]);
}
else if (1 == rightH)
{
// matrix * vector
return
new AstMatmulMV(_argStack[0],
_argStack[1]);
}
else
{
// matrix * matrix
return
new AstMatmulMM(_argStack[0],
_argStack[1]);
}
}
TransMatmul::TransMatmul(void)
: BaseTrans(0, 2) { }
}; // namespace chai_internal
|
ajayns/zulip-mobile
|
src/nav/StreamTabs.js
|
/* @TODO flow */
import React from 'react';
import { Text } from 'react-native';
import { TabNavigator, TabBarTop } from 'react-navigation';
import { FormattedMessage } from 'react-intl';
import tabsOptions from '../styles/tabs';
import UnreadStreamsContainer from '../unread/UnreadStreamsContainer';
import SubscriptionsContainer from '../streams/SubscriptionsContainer';
import StreamListContainer from '../subscriptions/StreamListContainer';
export default TabNavigator(
{
unread: {
screen: props => <UnreadStreamsContainer {...props.screenProps} />,
navigationOptions: {
tabBarLabel: props => (
<Text style={{ color: props.tintColor }}>
<FormattedMessage id="Unread" defaultMessage="Unread" />
</Text>
),
},
},
subscribed: {
screen: props => <SubscriptionsContainer {...props.screenProps} />,
navigationOptions: {
tabBarLabel: props => (
<Text style={{ color: props.tintColor }}>
<FormattedMessage id="Subscribed" defaultMessage="Subscribed" />
</Text>
),
},
},
streams: {
screen: props => <StreamListContainer {...props.screenProps} />,
navigationOptions: {
tabBarLabel: props => (
<Text style={{ color: props.tintColor }}>
<FormattedMessage id="All streams" defaultMessage="All streams" />
</Text>
),
},
},
},
tabsOptions(TabBarTop, 'top', true, 100),
);
|
lemkova/Yorozuya
|
YorozuyaGSLib/source/_talk_crystal_matrial_combine_nodeDetail.cpp
|
#include <_talk_crystal_matrial_combine_nodeDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Detail
{
Info::_talk_crystal_matrial_combine_nodeConsume2_ptr _talk_crystal_matrial_combine_nodeConsume2_next(nullptr);
Info::_talk_crystal_matrial_combine_nodeConsume2_clbk _talk_crystal_matrial_combine_nodeConsume2_user(nullptr);
Info::_talk_crystal_matrial_combine_nodeGetMixNeedNum4_ptr _talk_crystal_matrial_combine_nodeGetMixNeedNum4_next(nullptr);
Info::_talk_crystal_matrial_combine_nodeGetMixNeedNum4_clbk _talk_crystal_matrial_combine_nodeGetMixNeedNum4_user(nullptr);
Info::_talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_ptr _talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_next(nullptr);
Info::_talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_clbk _talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_user(nullptr);
Info::_talk_crystal_matrial_combine_nodeInit8_ptr _talk_crystal_matrial_combine_nodeInit8_next(nullptr);
Info::_talk_crystal_matrial_combine_nodeInit8_clbk _talk_crystal_matrial_combine_nodeInit8_user(nullptr);
Info::_talk_crystal_matrial_combine_nodeMake10_ptr _talk_crystal_matrial_combine_nodeMake10_next(nullptr);
Info::_talk_crystal_matrial_combine_nodeMake10_clbk _talk_crystal_matrial_combine_nodeMake10_user(nullptr);
Info::_talk_crystal_matrial_combine_nodePush12_ptr _talk_crystal_matrial_combine_nodePush12_next(nullptr);
Info::_talk_crystal_matrial_combine_nodePush12_clbk _talk_crystal_matrial_combine_nodePush12_user(nullptr);
Info::_talk_crystal_matrial_combine_nodeSet14_ptr _talk_crystal_matrial_combine_nodeSet14_next(nullptr);
Info::_talk_crystal_matrial_combine_nodeSet14_clbk _talk_crystal_matrial_combine_nodeSet14_user(nullptr);
Info::_talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_ptr _talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_next(nullptr);
Info::_talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_clbk _talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_user(nullptr);
void _talk_crystal_matrial_combine_nodeConsume2_wrapper(struct _talk_crystal_matrial_combine_node* _this, int nConsumeCount)
{
_talk_crystal_matrial_combine_nodeConsume2_user(_this, nConsumeCount, _talk_crystal_matrial_combine_nodeConsume2_next);
};
int _talk_crystal_matrial_combine_nodeGetMixNeedNum4_wrapper(struct _talk_crystal_matrial_combine_node* _this)
{
return _talk_crystal_matrial_combine_nodeGetMixNeedNum4_user(_this, _talk_crystal_matrial_combine_nodeGetMixNeedNum4_next);
};
int _talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_wrapper(struct _talk_crystal_matrial_combine_node* _this)
{
return _talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_user(_this, _talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_next);
};
void _talk_crystal_matrial_combine_nodeInit8_wrapper(struct _talk_crystal_matrial_combine_node* _this)
{
_talk_crystal_matrial_combine_nodeInit8_user(_this, _talk_crystal_matrial_combine_nodeInit8_next);
};
void _talk_crystal_matrial_combine_nodeMake10_wrapper(struct _talk_crystal_matrial_combine_node* _this, int nMakeCount)
{
_talk_crystal_matrial_combine_nodeMake10_user(_this, nMakeCount, _talk_crystal_matrial_combine_nodeMake10_next);
};
bool _talk_crystal_matrial_combine_nodePush12_wrapper(struct _talk_crystal_matrial_combine_node* _this, _STORAGE_LIST::_db_con* pItem, char byUseCount, char byClientIndex)
{
return _talk_crystal_matrial_combine_nodePush12_user(_this, pItem, byUseCount, byClientIndex, _talk_crystal_matrial_combine_nodePush12_next);
};
bool _talk_crystal_matrial_combine_nodeSet14_wrapper(struct _talk_crystal_matrial_combine_node* _this, int nMixIndex, int nNeedItemNum, char byTableCode, uint16_t wItemIndex)
{
return _talk_crystal_matrial_combine_nodeSet14_user(_this, nMixIndex, nNeedItemNum, byTableCode, wItemIndex, _talk_crystal_matrial_combine_nodeSet14_next);
};
void _talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_wrapper(struct _talk_crystal_matrial_combine_node* _this)
{
_talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_user(_this, _talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_next);
};
::std::array<hook_record, 8> _talk_crystal_matrial_combine_node_functions =
{
_hook_record {
(LPVOID)0x140430a90L,
(LPVOID *)&_talk_crystal_matrial_combine_nodeConsume2_user,
(LPVOID *)&_talk_crystal_matrial_combine_nodeConsume2_next,
(LPVOID)cast_pointer_function(_talk_crystal_matrial_combine_nodeConsume2_wrapper),
(LPVOID)cast_pointer_function((void(_talk_crystal_matrial_combine_node::*)(int))&_talk_crystal_matrial_combine_node::Consume)
},
_hook_record {
(LPVOID)0x1404321f0L,
(LPVOID *)&_talk_crystal_matrial_combine_nodeGetMixNeedNum4_user,
(LPVOID *)&_talk_crystal_matrial_combine_nodeGetMixNeedNum4_next,
(LPVOID)cast_pointer_function(_talk_crystal_matrial_combine_nodeGetMixNeedNum4_wrapper),
(LPVOID)cast_pointer_function((int(_talk_crystal_matrial_combine_node::*)())&_talk_crystal_matrial_combine_node::GetMixNeedNum)
},
_hook_record {
(LPVOID)0x140432210L,
(LPVOID *)&_talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_user,
(LPVOID *)&_talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_next,
(LPVOID)cast_pointer_function(_talk_crystal_matrial_combine_nodeGetRequiredSlotCount6_wrapper),
(LPVOID)cast_pointer_function((int(_talk_crystal_matrial_combine_node::*)())&_talk_crystal_matrial_combine_node::GetRequiredSlotCount)
},
_hook_record {
(LPVOID)0x1404307f0L,
(LPVOID *)&_talk_crystal_matrial_combine_nodeInit8_user,
(LPVOID *)&_talk_crystal_matrial_combine_nodeInit8_next,
(LPVOID)cast_pointer_function(_talk_crystal_matrial_combine_nodeInit8_wrapper),
(LPVOID)cast_pointer_function((void(_talk_crystal_matrial_combine_node::*)())&_talk_crystal_matrial_combine_node::Init)
},
_hook_record {
(LPVOID)0x140430b70L,
(LPVOID *)&_talk_crystal_matrial_combine_nodeMake10_user,
(LPVOID *)&_talk_crystal_matrial_combine_nodeMake10_next,
(LPVOID)cast_pointer_function(_talk_crystal_matrial_combine_nodeMake10_wrapper),
(LPVOID)cast_pointer_function((void(_talk_crystal_matrial_combine_node::*)(int))&_talk_crystal_matrial_combine_node::Make)
},
_hook_record {
(LPVOID)0x1404309c0L,
(LPVOID *)&_talk_crystal_matrial_combine_nodePush12_user,
(LPVOID *)&_talk_crystal_matrial_combine_nodePush12_next,
(LPVOID)cast_pointer_function(_talk_crystal_matrial_combine_nodePush12_wrapper),
(LPVOID)cast_pointer_function((bool(_talk_crystal_matrial_combine_node::*)(_STORAGE_LIST::_db_con*, char, char))&_talk_crystal_matrial_combine_node::Push)
},
_hook_record {
(LPVOID)0x1404308f0L,
(LPVOID *)&_talk_crystal_matrial_combine_nodeSet14_user,
(LPVOID *)&_talk_crystal_matrial_combine_nodeSet14_next,
(LPVOID)cast_pointer_function(_talk_crystal_matrial_combine_nodeSet14_wrapper),
(LPVOID)cast_pointer_function((bool(_talk_crystal_matrial_combine_node::*)(int, int, char, uint16_t))&_talk_crystal_matrial_combine_node::Set)
},
_hook_record {
(LPVOID)0x140432110L,
(LPVOID *)&_talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_user,
(LPVOID *)&_talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_next,
(LPVOID)cast_pointer_function(_talk_crystal_matrial_combine_nodector__talk_crystal_matrial_combine_node16_wrapper),
(LPVOID)cast_pointer_function((void(_talk_crystal_matrial_combine_node::*)())&_talk_crystal_matrial_combine_node::ctor__talk_crystal_matrial_combine_node)
},
};
}; // end namespace Detail
END_ATF_NAMESPACE
|
bitbrain/v0id
|
core/src/de/bitbrain/v0id/core/WeaponTemplate.java
|
<reponame>bitbrain/v0id<gh_stars>0
package de.bitbrain.v0id.core;
public class WeaponTemplate {
public final BulletType type;
public final String assetId;
public final String soundId;
public final String hitParticleEffectId;
public final float frequency;
public final float velocityX;
public final float velocityY;
public final float size;
public final int[] pattern;
public WeaponTemplate(//
BulletType type,//
String assetId,//
String soundId,
String hitParticleEffectId,
float frequency,//
float velocityX,//
float velocityY,//
float size,
int[] pattern) {
this.type = type;
this.assetId = assetId;
this.soundId = soundId;
this.hitParticleEffectId = hitParticleEffectId;
this.frequency = frequency;
this.velocityX = velocityX;
this.velocityY = velocityY;
this.size = size;
this.pattern = pattern;
}
}
|
claytonv/xbox-live-api
|
Source/Services/Presence/device_presence_change_event_args.cpp
|
// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "xsapi/presence.h"
NAMESPACE_MICROSOFT_XBOX_SERVICES_PRESENCE_CPP_BEGIN
device_presence_change_event_args::device_presence_change_event_args() :
m_deviceType(presence_device_type::unknown),
m_isUserLoggedOnDevice(false)
{
}
device_presence_change_event_args::device_presence_change_event_args(
_In_ string_t xboxUserId,
_In_ presence_device_type deviceType,
_In_ bool isUserLoggedOnDevice
) :
m_xboxUserId(std::move(xboxUserId)),
m_deviceType(deviceType),
m_isUserLoggedOnDevice(isUserLoggedOnDevice)
{
}
const string_t&
device_presence_change_event_args::xbox_user_id() const
{
return m_xboxUserId;
}
presence_device_type
device_presence_change_event_args::device_type() const
{
return m_deviceType;
}
bool
device_presence_change_event_args::is_user_logged_on_device() const
{
return m_isUserLoggedOnDevice;
}
NAMESPACE_MICROSOFT_XBOX_SERVICES_PRESENCE_CPP_END
|
huahang/incubator-nuttx
|
include/nuttx/symtab.h
|
/****************************************************************************
* include/nuttx/symtab.h
*
* Copyright (C) 2009, 2015 <NAME>. All rights reserved.
* Author: <NAME> <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#ifndef __INCLUDE_NUTTX_SYMTAB_H
#define __INCLUDE_NUTTX_SYMTAB_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/****************************************************************************
* Public Types
****************************************************************************/
/* struct symbtab_s describes one entry in the symbol table. A symbol table
* is a fixed size array of struct symtab_s. The information is intentionally
* minimal and supports only:
*
* 1. Function pointers as sym_values. Of other kinds of values need to be
* supported, then typing information would also need to be included in
* the structure.
*
* 2. Fixed size arrays. There is no explicit provisional for dyanamically
* adding or removing entries from the symbol table (realloc might be
* used for that purpose if needed). The intention is to support only
* fixed size arrays completely defined at compilation or link time.
*/
struct symtab_s
{
FAR const char *sym_name; /* A pointer to the symbol name string */
FAR const void *sym_value; /* The value associated witht the string */
};
/****************************************************************************
* Public Functions
****************************************************************************/
#undef EXTERN
#if defined(__cplusplus)
#define EXTERN extern "C"
extern "C"
{
#else
#define EXTERN extern
#endif
/****************************************************************************
* Name: symtab_findbyname
*
* Description:
* Find the symbol in the symbol table with the matching name.
* This version assumes that table is not ordered with respect to symbol
* name and, hence, access time will be linear with respect to nsyms.
*
* Returned Value:
* A reference to the symbol table entry if an entry with the matching
* name is found; NULL is returned if the entry is not found.
*
****************************************************************************/
FAR const struct symtab_s *
symtab_findbyname(FAR const struct symtab_s *symtab,
FAR const char *name, int nsyms);
/****************************************************************************
* Name: symtab_findorderedbyname
*
* Description:
* Find the symbol in the symbol table with the matching name.
* This version assumes that table ordered with respect to symbol name.
*
* Returned Value:
* A reference to the symbol table entry if an entry with the matching
* name is found; NULL is returned if the entry is not found.
*
****************************************************************************/
FAR const struct symtab_s *
symtab_findorderedbyname(FAR const struct symtab_s *symtab,
FAR const char *name, int nsyms);
/****************************************************************************
* Name: symtab_findbyvalue
*
* Description:
* Find the symbol in the symbol table whose value closest (but not greater
* than), the provided value. This version assumes that table is not ordered
* with respect to symbol name and, hence, access time will be linear with
* respect to nsyms.
*
* Returned Value:
* A reference to the symbol table entry if an entry with the matching
* name is found; NULL is returned if the entry is not found.
*
****************************************************************************/
FAR const struct symtab_s *
symtab_findbyvalue(FAR const struct symtab_s *symtab,
FAR void *value, int nsyms);
/****************************************************************************
* Name: symtab_sortbyname
*
* Description:
* Sort the symbol table by name.
*
* Returned Value:
* None.
*
****************************************************************************/
void symtab_sortbyname(FAR struct symtab_s *symtab, int nsyms);
#undef EXTERN
#if defined(__cplusplus)
}
#endif
#endif /* __INCLUDE_NUTTX_SYMTAB_H */
|
Hans-JakobHoltzTT/ecutest-plugin
|
src/main/java/de/tracetronic/jenkins/plugins/ecutest/wrapper/com/ETComException.java
|
<reponame>Hans-JakobHoltzTT/ecutest-plugin
/*
* Copyright (c) 2015-2019 TraceTronic GmbH
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package de.tracetronic.jenkins.plugins.ecutest.wrapper.com;
/**
* Exception thrown if an error occurs while communicating with a COM instance.
*/
public class ETComException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Instantiates a new {@link ETComException}.
*
* @param cause the cause of the {@link Exception}
*/
public ETComException(final Throwable cause) {
super(cause);
}
/**
* Instantiates a new {@link ETComException}.
*
* @param message the message to attach to the {@link Exception}
* @param cause the cause of the {@link Exception}
*/
public ETComException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Instantiates a new {@link ETComException}.
*
* @param message the message to attach to the {@link Exception}
*/
public ETComException(final String message) {
super(message);
}
/**
* Instantiates a new {@link ETComException}.
*/
public ETComException() {
super();
}
}
|
pulewicz/scala-commons
|
commons-core/src/test/scala/com/avsystem/commons/testutil/CompilationErrorAssertions.scala
|
<filename>commons-core/src/test/scala/com/avsystem/commons/testutil/CompilationErrorAssertions.scala
package com.avsystem.commons
package testutil
import com.avsystem.commons.macros.TestMacros
import org.scalatest.Assertions
trait CompilationErrorAssertions extends Assertions {
def typeErrorFor(code: String): String = macro TestMacros.typeErrorImpl
}
|
royalfx/ae_snippets
|
src/ae/app/as_getAeReleaseVersion.js
|
<reponame>royalfx/ae_snippets<filename>src/ae/app/as_getAeReleaseVersion.js
// Copyright (c) 2021 <NAME>
// This code is licensed under MIT license
// See also http://www.opensource.org/licenses/mit-license.php
/**
* @version 1.0.1
* @date Oct 12 2019
*
* @description Get AE release version
* @param version {string} AEVersion
*/
function as_getAeReleaseVersion(version) {
// Declare vars
var verMatch = null;
var versionsList = AEVersion.getList();
// Loop AE versions
for (var v = 0, ver; v < versionsList.length; v++) {
ver = versionsList[v];
// Compare
var compare = as_compareVersions(version, ver);
if (compare == 0) {
// Found
verMatch = ver;
break;
} else if (compare > 0) {
// Return prev
break;
} else {
// Continue
verMatch = ver;
}
}
return verMatch;
}
|
beyondkqw/react-kqw
|
src/Component/GoodsDetails/GoodsPopup.js
|
import React, { Component } from 'react';
import '../../Stylesheets/App/goodsDetails.css';
import $ from 'jquery';
export default class GoodsPopup extends Component {
// 构造
constructor(props) {
super(props);
// 初始状态
this.attrIds = []
this.risePrice=[];
this.state = {
value:1,
total:this.props.price
};
this.kind={}
}
//数量减
minusNum(){
if(this.state.value === 1){
}else {
this.setState({value:--this.state.value});
}
}
//数量加
addNum(){
this.setState({value:++this.state.value});
}
handleChange() {
this.setState({value:this.state.value});
}
ensure(type,typeParam,inx,rise){
if(type==2){
this.kind[inx]=rise;
let priceTotal = this.props.price
for(var j in this.kind){
priceTotal += this.kind[j];
this.setState({
total:priceTotal
})
}
}
this.attrIds = [];
const {ensurePress} = this.props
let radios = document.getElementsByClassName('chooseColor')
for(let i =0;i<radios.length;i++){
if(radios[i].checked){
this.attrIds.push(radios[i].value)
}
}
if(type==1){
ensurePress&&ensurePress(this.attrIds,this.state.value,typeParam)
}
}
render() {
const {closePopUp,attr,onClick,isOnly,typeParam,price,image} = this.props
return (
<div className="modalNav pa width_100 height_all font14" style={{zIndex:100}}>
<div className="popupContainer pf bottom0 z_index bkg_color wrap border_top pr" style={{zIndex:1050}}>
<div className="pa close" onClick={closePopUp}><img src={require('../../Images/common/delModal.png')} alt=""/></div>
<div className="pm_img plAll">
<span className="di productImg"><img src={image} alt=""/></span>
<span className="colorff f12 margin15">¥</span><span className="colorff font18">{this.state.total}</span>
</div>
{
attr&&attr.map((el,inx)=>{
return(
<div className="plAll border_top">
<span className="font14 color6">{el.NAME}</span>
<div>
{
el.DETAILS&&el.DETAILS.map((detail,index)=>{
return(
<span
onClick = {()=>this.ensure(2,'',inx,detail.RISE_PRICE)}
className="di mr10"
>
<input
//ref = {`${inx}`+'ATTR_ID'+`${index}`}
type="radio"
value = {detail.ID}
name = {el.DESC}
className="chooseColor"
id={`${inx}`+'ATTR_ID'+`${index}`}
/>
<label htmlFor={`${inx}`+'ATTR_ID'+`${index}`}>{detail.VALUE}</label>
</span>
)
})
}
</div>
</div>
)
})
}
<div className="popupContainer bottom0 z_index bkg_color width_100 pr">
<div className="plAll border_top">
<span className="font14 color6">选择数量</span>
<div className="border_ra mt5 changeCount tc">
<span className="di width333 height_all bkg_e5 f25 lh13 fl" onClick={()=>this.minusNum()}>-</span>
<input className="di width333 height_all f17 borderno tc" value={this.state.value} onChange={this.handleChange}/>
<span className="di width333 height_all bkg_e5 f25 lh13 fr" onClick={()=>this.addNum()}>+</span>
</div>
</div>
</div>
{
isOnly?
<div className="width_100 commit bkg_ff color_white">
<button
className="width_100 height_all"
onClick = {()=>{this.ensure(1)}}
>
确定
</button>
</div>
:
<div className="width_100 commit">
<button
className="width50 height_all color_pink color_yellow"
onClick = {()=>this.ensure(1,1)}
>
加入购物车
</button>
<button
className="width50 height_all bkg_ff color_white"
onClick = {()=>this.ensure(1,2)}
>
立即购买
</button>
</div>
}
</div>
</div>
)
}
}
|
chinmobi/gin-mvc
|
model/x/validator/userid.go
|
<reponame>chinmobi/gin-mvc<gh_stars>10-100
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package validator
import (
"strconv"
"unicode"
)
func ParseUserID(s string) (uint32, bool) {
for _, c := range s {
if !unicode.IsDigit(c) {
return 0, false
}
}
id, _ := strconv.ParseUint(s, 10, 64)
return uint32(id), true
}
|
frisciliasultan/tp
|
src/main/java/seedu/iscam/logic/commands/AddMeetingCommand.java
|
<filename>src/main/java/seedu/iscam/logic/commands/AddMeetingCommand.java<gh_stars>0
package seedu.iscam.logic.commands;
import static java.util.Objects.requireNonNull;
import static seedu.iscam.logic.parser.CliSyntax.PREFIX_CLIENT;
import static seedu.iscam.logic.parser.CliSyntax.PREFIX_DESCRIPTION;
import static seedu.iscam.logic.parser.CliSyntax.PREFIX_LOCATION;
import static seedu.iscam.logic.parser.CliSyntax.PREFIX_ON;
import static seedu.iscam.logic.parser.CliSyntax.PREFIX_TAG;
import seedu.iscam.logic.commands.exceptions.CommandException;
import seedu.iscam.model.Model;
import seedu.iscam.model.meeting.Meeting;
/**
* Adds a meeting to the iscam book.
*/
public class AddMeetingCommand extends Command {
public static final String COMMAND_WORD = "addmeet";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Add a meeting with a client to the iScam Book. \n"
+ "Parameters: "
+ PREFIX_CLIENT + "CLIENT_NAME "
+ PREFIX_ON + "DATE_TIME "
+ PREFIX_LOCATION + "LOCATION "
+ PREFIX_DESCRIPTION + "DESCRIPTION "
+ "[" + PREFIX_TAG + "TAG(s)] \n"
+ "Example: " + COMMAND_WORD + " "
+ PREFIX_CLIENT + "<NAME> "
+ PREFIX_ON + "25-10-2021 10:00 "
+ PREFIX_LOCATION + "Starbucks, Tampines Hub "
+ PREFIX_DESCRIPTION + "Discuss insurance policy "
+ PREFIX_TAG + "Urgent "
+ PREFIX_TAG + "Premium";
public static final String MESSAGE_SUCCESS = "New meeting added: %1$s";
public static final String MESSAGE_MEETING_CONFLICT = "A meeting with this date and time already exists in the "
+ "iScam book ";
private final Meeting toAdd;
/**
* Creates an AddMeetingCommand to add the specified {@code Meeting}
*/
public AddMeetingCommand(Meeting meeting) {
requireNonNull(meeting);
toAdd = meeting;
}
@Override
public CommandResult execute(Model model) throws CommandException {
requireNonNull(model);
if (model.hasMeeting(toAdd)) {
throw new CommandException(MESSAGE_MEETING_CONFLICT);
}
model.addMeeting(toAdd);
return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd));
}
@Override
public boolean equals(Object other) {
return other == this || (other instanceof AddMeetingCommand && toAdd.equals(((AddMeetingCommand) other).toAdd));
}
}
|
atultherajput/evpoco
|
evnet/src/EVTCPServer.cpp
|
<reponame>atultherajput/evpoco<gh_stars>1-10
//
// Library: evnet
// Package: EVTCPServer
// Module: EVTCPServer
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include <sys/time.h>
#include <sys/socket.h>
#include <ev.h>
#include <ef_io.h>
#include "Poco/evnet/evnet.h"
#include "Poco/Util/AbstractConfiguration.h"
#include "Poco/Util/Application.h"
#include "Poco/evnet/EVTCPServer.h"
#include "Poco/evnet/EVTCPServerDispatcher.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/evnet/EVTCPServerConnectionFactory.h"
#include "Poco/Timespan.h"
#include "Poco/Exception.h"
#include "Poco/ErrorHandler.h"
#include "Poco/evnet/EVTCPServerNotification.h"
using Poco::ErrorHandler;
extern "C" {
void debug_io_watcher(const char * file, const int lineno, const ev_io * w);
void debug_io_watchers(const char * file, const int lineno, EV_P);
}
namespace Poco {
namespace evnet {
const std::string EVTCPServer::SERVER_PREFIX_CFG_NAME("EVTCPServer.");
const std::string EVTCPServer::NUM_THREADS_CFG_NAME("numThreads");
const std::string EVTCPServer::RECV_TIME_OUT_NAME("receiveTimeOut");
const std::string EVTCPServer::NUM_CONNECTIONS_CFG_NAME("numConnections");
const std::string EVTCPServer::USE_IPV6_FOR_CONN("useIpv6ForConn");
// this callback is called when a submitted generic task is complete
static void file_evt_occured (EV_P_ ev_async *w, int revents)
{
strms_pc_cb_ptr_type cb_ptr = (strms_pc_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_pc_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleFileEvtOccured(const bool)
*/
((cb_ptr->objPtr)->*(cb_ptr->method))(true);
return;
}
static void file_operation_completion(int fd, int completed_oper, void * cb_data)
{
EVTCPServer * tcpserver = (EVTCPServer*) cb_data;
if (tcpserver == NULL) {
DEBUGPOINT("THIS MUST NOT HAPPEN\n");
std::abort();
}
tcpserver->pushFileEvent(fd, completed_oper);
return ;
}
static void periodic_call_for_housekeeping(EV_P_ ev_timer *w, int revents)
{
bool ev_occurred = true;
strms_pc_cb_ptr_type cb_ptr = (strms_pc_cb_ptr_type)0;
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_pc_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handlePeriodicWakeup(const bool&)
*/
if (cb_ptr) ((cb_ptr->objPtr)->*(cb_ptr->method))(ev_occurred);
return;
}
// this callback is called when data is readable on a socket
static void data_available_on_primary_inp_fd(EV_P_ ev_io *w, int revents)
{
bool ev_occurred = true;
srvrs_io_cb_ptr_type cb_ptr = (srvrs_io_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
debug_io_watcher(__FILE__,__LINE__,w);
return ;
}
cb_ptr = (srvrs_io_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleDataAvlblOnPrimaryInp(const bool)
*/
((cb_ptr->objPtr)->*(cb_ptr->connArrived))(ev_occurred);
return;
}
// this callback is called when a new connection request is available
static void new_connection(EV_P_ ev_io *w, int revents)
{
bool ev_occurred = true;
srvrs_io_cb_ptr_type cb_ptr = (srvrs_io_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
debug_io_watcher(__FILE__,__LINE__,w);
return ;
}
cb_ptr = (srvrs_io_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleConnReq(const bool)
*/
((cb_ptr->objPtr)->*(cb_ptr->connArrived))(ev_occurred);
return;
}
static void async_stream_socket_cb_1(EV_P_ ev_io *w, int revents);
// this callback is called when socket is writable
static void async_stream_socket_cb_2 (EV_P_ ev_io *w, int revents)
{
strms_io_cb_ptr_type cb_ptr = (strms_io_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_io_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleAccSocketWritable(const bool)
*/
ssize_t ret = 0;
ret = ((cb_ptr->objPtr)->*(cb_ptr->socketWritable))(*(cb_ptr->ssPtr) , true);
return;
}
// this callback is called when data is readable on a socket
static void async_stream_socket_cb_1(EV_P_ ev_io *w, int revents)
{
if (revents & EV_WRITE) async_stream_socket_cb_2(loop, w, revents);
if (revents & EV_READ) {
strms_io_cb_ptr_type cb_ptr = (strms_io_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_io_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleAccSocketReadable(const bool) or
* EVTCPServer::handleCLFdReadable(const bool)
*/
//DEBUGPOINT("INVOKING handleAccSocketReadable\n");
((cb_ptr->objPtr)->*(cb_ptr->dataAvailable))(*(cb_ptr->ssPtr) , true);
// Suspending interest in events of this fd until one request is processed
//ev_io_stop(loop, w);
//ev_clear_pending(loop, w);
}
return;
}
// this callback is called when a submitted generic task is complete
static void generic_task_complete (EV_P_ ev_async *w, int revents)
{
strms_pc_cb_ptr_type cb_ptr = (strms_pc_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_pc_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleGenericTaskComplete(const bool)
*/
((cb_ptr->objPtr)->*(cb_ptr->method))(true);
return;
}
// this callback is called when a passed domain name is resolved
static void host_addr_resolved (EV_P_ ev_async *w, int revents)
{
strms_pc_cb_ptr_type cb_ptr = (strms_pc_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_pc_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleHostResolved(const bool)
*/
((cb_ptr->objPtr)->*(cb_ptr->method))(true);
return;
}
// this callback is called when connected socket is writable
static void async_stream_socket_cb_5 (EV_P_ ev_io *w, int revents)
{
strms_io_cb_ptr_type cb_ptr = (strms_io_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_io_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleConnSocketWriteable(const bool) or
* EVTCPServer::handleConnSocketWriteReady(const bool)
*/
ssize_t ret = 0;
ret = ((cb_ptr->objPtr)->*(cb_ptr->connSocketWritable))(cb_ptr , true);
return;
}
// this callback is called when connected socket is writable
static void async_stream_socket_cb_4 (EV_P_ ev_io *w, int revents)
{
strms_io_cb_ptr_type cb_ptr = (strms_io_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_io_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleConnSocketWriteable(const bool) or
* EVTCPServer::handleConnSocketWriteReady(const bool)
*/
ssize_t ret = 0;
ret = ((cb_ptr->objPtr)->*(cb_ptr->connSocketWritable))(cb_ptr , true);
return;
}
// this callback is called when data is readable on a connected socket
static void async_stream_socket_cb_3(EV_P_ ev_io *w, int revents)
{
if ((revents & EV_READ) && (revents & EV_WRITE)) {
async_stream_socket_cb_5(loop, w, revents);
}
else if (revents & EV_WRITE) {
//DEBUGPOINT("HERE\n");
async_stream_socket_cb_4(loop, w, revents);
}
else if (revents & EV_READ) {
strms_io_cb_ptr_type cb_ptr = (strms_io_cb_ptr_type)0;
/* for one-shot events, one must manually stop the watcher
* with its corresponding stop function.
* ev_io_stop (loop, w);
*/
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_io_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleConnSocketReadable(const bool)
* EVTCPServer::handleConnSocketReadReady(const bool) or
*/
((cb_ptr->objPtr)->*(cb_ptr->connSocketReadable))(cb_ptr , true);
// Suspending interest in events of this fd until one request is processed
//ev_io_stop(loop, w);
//ev_clear_pending(loop, w);
}
return;
}
/* This callback is to break all watchers and stop the loop. */
static void stop_the_loop(struct ev_loop *loop, ev_async *w, int revents)
{
ev_break (loop, EVBREAK_ALL);
return;
}
/* This callback is for completion of processing of one socket. */
/* SOMETHING HAPPENED HOUTSIDE EVENT LOOP IN ANOTHER THREAD */
static void event_notification_on_downstream_socket(struct ev_loop *loop, ev_async *w, int revents)
{
bool ev_occurred = true;
strms_pc_cb_ptr_type cb_ptr = (strms_pc_cb_ptr_type)0;
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_pc_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::somethingHappenedInAnotherThread(const bool)
*/
if (cb_ptr) ((cb_ptr->objPtr)->*(cb_ptr->method))(ev_occurred);
return;
}
/* This callback is for processing of service requests submitted by other threads.
* The service requests are for connecting a socket to a server,
* sending request data to server or receiving request data from server */
/* HANDLESERVICEREQUEST submitted by abother thread. */
static void process_service_request (struct ev_loop *loop, ev_async *w, int revents)
{
bool ev_occurred = true;
strms_pc_cb_ptr_type cb_ptr = (strms_pc_cb_ptr_type)0;
if (!ev_is_active(w)) {
return ;
}
cb_ptr = (strms_pc_cb_ptr_type)w->data;
/* The below line of code essentially calls
* EVTCPServer::handleServiceRequest(const bool)
*/
if (cb_ptr) ((cb_ptr->objPtr)->*(cb_ptr->method))(ev_occurred);
return;
}
//
// EVTCPServer
//
void EVTCPServer::init()
{
Poco::Util::AbstractConfiguration& config = appConfig();
_numThreads = config.getInt(SERVER_PREFIX_CFG_NAME + NUM_THREADS_CFG_NAME , 2);
_receiveTimeOut = config.getInt(SERVER_PREFIX_CFG_NAME+RECV_TIME_OUT_NAME, 5);
_numConnections = config.getInt(SERVER_PREFIX_CFG_NAME + NUM_CONNECTIONS_CFG_NAME , 500);
_use_ipv6_for_conn = config.getBool(SERVER_PREFIX_CFG_NAME + USE_IPV6_FOR_CONN, false);
_loop_active_spin_lock = create_spin_lock();
_loop_active = false;
atomic_thread_fence(std::memory_order_release);
}
EVTCPServer::EVTCPServer(EVTCPServerConnectionFactory::Ptr pFactory, Poco::UInt16 portNumber, TCPServerParams::Ptr pParams):
_mode(EVTCPServer::SERVER_MODE),
_socket(ServerSocket(portNumber)),
_thread(threadName(_socket)),
_stopped(true),
_loop(0),
_ssLRUList(0,0),
_numThreads(2),
_numConnections(500),
//_blocking(pParams->getBlocking()),
_blocking(false),
_pConnectionFactory(pFactory),
_receiveTimeOut(5),
_sr_srl_num(0),
_thread_pool(0),
_stop_watcher_ptr1(0),
_stop_watcher_ptr2(0),
_stop_watcher_ptr3(0),
_dns_watcher_ptr(0),
_gen_task_compl_watcher_ptr(0),
_file_evt_watcher_ptr(0),
_aux_tc_queue(create_ev_queue()),
_file_evt_queue(create_ev_queue()),
_host_resolve_queue(create_ev_queue()),
_use_ipv6_for_conn(false)
{
init();
Poco::ThreadPool& pool = Poco::ThreadPool::defaultPool(_numThreads,_numThreads);
if (pParams) {
int toAdd = pParams->getMaxThreads() - pool.capacity();
if (toAdd > 0) pool.addCapacity(toAdd);
}
_pDispatcher = new EVTCPServerDispatcher(pFactory, pool, pParams, this);
}
EVTCPServer::EVTCPServer(EVTCPServerConnectionFactory::Ptr pFactory, const ServerSocket& socket, TCPServerParams::Ptr pParams):
_mode(EVTCPServer::SERVER_MODE),
_pipe_rd_fd(-1),
_pipe_wr_fd(-1),
_socket(socket),
_thread(threadName(socket)),
_stopped(true),
_loop(0),
_ssLRUList(0,0),
_numThreads(2),
_numConnections(500),
//_blocking(pParams->getBlocking()),
_blocking(false),
_pConnectionFactory(pFactory),
_receiveTimeOut(5),
_sr_srl_num(0),
_thread_pool(0),
_stop_watcher_ptr1(0),
_stop_watcher_ptr2(0),
_stop_watcher_ptr3(0),
_dns_watcher_ptr(0),
_gen_task_compl_watcher_ptr(0),
_file_evt_watcher_ptr(0),
_aux_tc_queue(create_ev_queue()),
_file_evt_queue(create_ev_queue()),
_host_resolve_queue(create_ev_queue()),
_use_ipv6_for_conn(false)
{
init();
Poco::ThreadPool& pool = Poco::ThreadPool::defaultPool(_numThreads,_numThreads);
if (pParams) {
int toAdd = pParams->getMaxThreads() - pool.capacity();
if (toAdd > 0) pool.addCapacity(toAdd);
}
_pDispatcher = new EVTCPServerDispatcher(pFactory, pool, pParams, this);
}
EVTCPServer::EVTCPServer(EVTCPServerConnectionFactory::Ptr pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, TCPServerParams::Ptr pParams):
_mode(EVTCPServer::SERVER_MODE),
_pipe_rd_fd(-1),
_pipe_wr_fd(-1),
_socket(socket),
_thread(threadName(socket)),
_stopped(true),
_loop(0),
_ssLRUList(0,0),
_numThreads(2),
_numConnections(500),
//_blocking(pParams->getBlocking()),
_blocking(false),
_pConnectionFactory(pFactory),
_receiveTimeOut(5),
_sr_srl_num(0),
_thread_pool(0),
_stop_watcher_ptr1(0),
_stop_watcher_ptr2(0),
_stop_watcher_ptr3(0),
_dns_watcher_ptr(0),
_gen_task_compl_watcher_ptr(0),
_file_evt_watcher_ptr(0),
_aux_tc_queue(create_ev_queue()),
_file_evt_queue(create_ev_queue()),
_host_resolve_queue(create_ev_queue()),
_use_ipv6_for_conn(false)
{
init();
_pDispatcher = new EVTCPServerDispatcher(pFactory, threadPool, pParams, this);
}
EVTCPServer::EVTCPServer(EVTCPServerConnectionFactory::Ptr pFactory, int pipe_rd_fd, int pipe_wr_fd, TCPServerParams::Ptr pParams):
_mode(EVTCPServer::COMMAND_LINE_MODE),
_pipe_rd_fd(pipe_rd_fd),
_pipe_wr_fd(pipe_wr_fd),
_thread(threadName(_pipe_rd_fd)),
_stopped(true),
_loop(0),
_ssLRUList(0,0),
_numThreads(2),
_numConnections(500),
//_blocking(pParams->getBlocking()),
_blocking(false),
_pConnectionFactory(pFactory),
_receiveTimeOut(5),
_sr_srl_num(0),
_thread_pool(0),
_stop_watcher_ptr1(0),
_stop_watcher_ptr2(0),
_stop_watcher_ptr3(0),
_dns_watcher_ptr(0),
_gen_task_compl_watcher_ptr(0),
_file_evt_watcher_ptr(0),
_aux_tc_queue(create_ev_queue()),
_file_evt_queue(create_ev_queue()),
_host_resolve_queue(create_ev_queue()),
_use_ipv6_for_conn(false)
{
init();
Poco::ThreadPool& pool = Poco::ThreadPool::defaultPool(_numThreads,_numThreads);
if (pParams) {
int toAdd = pParams->getMaxThreads() - pool.capacity();
if (toAdd > 0) pool.addCapacity(toAdd);
}
_pDispatcher = new EVTCPServerDispatcher(pFactory, pool, pParams, this);
}
EVTCPServer::~EVTCPServer()
{
try {
stop();
_pDispatcher->release();
freeClear();
}
catch (...) {
poco_unexpected();
}
}
void EVTCPServer::freeClear()
{
for ( ASColMapType::iterator it = _accssColl.begin(); it != _accssColl.end(); ++it ) {
delete it->second;
}
_accssColl.clear();
ef_unset_cb_func();
for (FileEvtSubscrMap::iterator it = _file_evt_subscriptions.begin(); it != _file_evt_subscriptions.end(); ++it) {
delete it->second._usN;
}
destroy_spin_lock(_loop_active_spin_lock);
}
void EVTCPServer::clearAcceptedSocket(poco_socket_t fd)
{
EVAcceptedStreamSocket *tn = getTn(fd);
_accssColl.erase(fd);
_ssLRUList.remove(tn);
{
ev_io * socket_watcher_ptr = 0;
socket_watcher_ptr = tn->getSocketWatcher();
if (socket_watcher_ptr && ev_is_active(socket_watcher_ptr)) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
}
}
delete tn;
}
const TCPServerParams& EVTCPServer::params() const
{
return _pDispatcher->params();
}
void EVTCPServer::start()
{
poco_assert (_stopped);
_stopped = false;
_thread.start(*this);
}
void EVTCPServer::stop()
{
if (!_stopped)
{
_stopped = true;
{
ev_spin_lock(this->_loop_active_spin_lock);
/* Calls stop_the_loop */
ev_async_send(this->_loop, this->_stop_watcher_ptr1);
_loop_active = false;
atomic_thread_fence(std::memory_order_release);
ev_spin_unlock(this->_loop_active_spin_lock);
}
_thread.join();
_pDispatcher->stop();
destroy_thread_pool(this->_thread_pool);
}
}
ssize_t EVTCPServer::sendData(StreamSocket& ss, void * chptr, size_t size, int *wait_mode_ptr)
{
ssize_t ret = 0;
errno = 0;
try {
//ret = ss.sendBytes(chptr, size , 0);
ret = ss.sendBytes(chptr, size );
if (ret < 0 && wait_mode_ptr) *wait_mode_ptr = ret;
else if (wait_mode_ptr) *wait_mode_ptr = 0;
}
catch (...) {
if (ret < 0 && wait_mode_ptr) *wait_mode_ptr = ret;
else if (wait_mode_ptr) *wait_mode_ptr = 0;
ret = -1;
}
if ((ret <= 0) || errno) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
}
else {
const char * error_string = NULL;
if (!errno) {
error_string = "Peer closed connection";
}
else {
error_string = strerror(errno);
}
return -1;
}
}
return ret;
}
ssize_t EVTCPServer::sendData(int fd, void * chptr, size_t size, int * wait_mode_ptr)
{
ssize_t ret = 0;
errno = 0;
ret = send(fd, chptr, size , 0);
if (ret < 0 && wait_mode_ptr) *wait_mode_ptr = ret;
else if (wait_mode_ptr) *wait_mode_ptr = 0;
if ((ret <= 0) || errno) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
}
else {
const char * error_string = NULL;
if (!errno) {
error_string = "Peer closed connection";
}
else {
error_string = strerror(errno);
}
return -1;
}
}
return ret;
}
ssize_t EVTCPServer::handleConnSocketConnected(strms_io_cb_ptr_type cb_ptr, const bool& ev_occured)
{
int optval = 0;
unsigned int optlen = sizeof(optval);
EVConnectedStreamSocket * cn = cb_ptr->cn;
cn->setState(EVConnectedStreamSocket::NOT_WAITING);
ev_io_stop(this->_loop, cn->getSocketWatcher());
ev_clear_pending(this->_loop, cn->getSocketWatcher());
EVAcceptedStreamSocket *tn = getTn(cn->getAccSockfd());
tn->decrNumCSEvents();
//DEBUGPOINT("CONNECTED [%d]\n", cn->getStreamSocket().impl()->sockfd());
getsockopt(cn->getStreamSocket().impl()->sockfd(), SOL_SOCKET, SO_ERROR, (void*)&optval, &optlen);
/* Enqueue the notification only if the accepted socket is still being processed.
* */
if ((tn->getProcState()) && tn->srInSession(cb_ptr->sr_num)) {
if (!optval) {
cn->getStreamSocket().impl()->setBlocking(_blocking);
fcntl(cn->getStreamSocket().impl()->sockfd(), F_SETFL, O_NONBLOCK);
}
EVUpstreamEventNotification * usN = 0;
usN = new EVUpstreamEventNotification(cb_ptr->sr_num, (cn->getStreamSocket().impl()->sockfd()),
cb_ptr->cb_evid_num,
(!optval)?1:-1,
optval);
usN->setRecvStream(cn->getRcvMemStream());
usN->setSendStream(cn->getSendMemStream());
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
return 1;
}
ssize_t EVTCPServer::handleConnSocketWriteable(strms_io_cb_ptr_type cb_ptr, const bool& ev_occured)
{
ssize_t ret = 0;
EVConnectedStreamSocket * cn = cb_ptr->cn;
cn->setTimeOfLastUse();
if (cn->getState() == EVConnectedStreamSocket::BEFORE_CONNECT) {
//DEBUGPOINT("HERE BC\n");
cn->setState(EVConnectedStreamSocket::NOT_WAITING);
return handleConnSocketConnected(cb_ptr, ev_occured);
}
//EVAcceptedStreamSocket *tn = _accssColl[cn->getAccSockfd()];
if (!cn->sendDataAvlbl()) {
goto handleConnSocketWritable_finally;
}
{
chunked_memory_stream * cms = 0;
ssize_t ret1 = 0;
int count = 0;
cms = cn->getSendMemStream();
void * nodeptr = 0;
void * buffer = 0;
size_t bytes = 0;
nodeptr = cms->get_next(0);
while (nodeptr) {
count ++;
buffer = cms->get_buffer(nodeptr);
bytes = cms->get_buffer_len(nodeptr);
//ret1 = sendData(streamSocket.impl()->sockfd(), buffer, bytes);
//DEBUGPOINT("SENDING_DATA ON CONN SOCK %d\n", cn->getStreamSocket().impl()->sockfd());
ret1 = sendData(cn->getStreamSocket(), buffer, bytes);
if (ret1 > 0) {
cms->erase(ret1);
nodeptr = cms->get_next(0);
buffer = 0;
bytes = 0;
ret += ret1;
ret1 = 0;
}
else if (ret1 == 0) {
// Add to waiting for being write ready.
ret = 0;
break;
}
else {
ret = -1;
break;
}
}
}
handleConnSocketWritable_finally:
if (ret >=0) {
/* If there is more data to be sent, wait for
* the socket to become writable again.
* */
if (!cn->sendDataAvlbl()) ret = 1;
else ret = 0;
}
if (ret > 0) {
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
socket_watcher_ptr = cn->getSocketWatcher();
if (cn->getState() == EVConnectedStreamSocket::WAITING_FOR_WRITE) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
cn->setState(EVConnectedStreamSocket::NOT_WAITING);
}
else if (cn->getState() == EVConnectedStreamSocket::WAITING_FOR_READWRITE) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_3, cn->getStreamSocket().impl()->sockfd(), EV_READ);
ev_io_start (this->_loop, socket_watcher_ptr);
cn->setState(EVConnectedStreamSocket::WAITING_FOR_READ);
}
else {
/* It should not come here otherwise. */
DEBUGPOINT("It should not come here otherwise.[%d]\n", cn->getState());
std::abort();
}
// TBD Handle dispatching of EVENT here. TBD
/* For the case of sending data, calling the upstream event back is not done
* A send simply tries to transfer data to the socket
*
* If there is any failure the caller is expected to find from the
* receive side.
* */
}
else if (ret <0) {
/* At this point we know that the socket has become unusable,
* it is possible to dispose it off and complete housekeeping.
* However there is a likelihood that another thread is still
* processing this socket, hence the disposing off must not be
* done over here.
*
* When the processing gets complete, and the socket is returned,
* At that time the socket will get disposed.
* */
cn->setSockInError();
// TBD Handle dispatching of EVENT here. TBD
/* For the case of sending data, calling the upstream event back is not done
* A send simply tries to transfer data to the socket
*
* If there is any failure the caller is expected to find from the
* receive side.
* */
}
if (ret != 0) {
//srComplete(tn);
//tn->decrNumCSEvents();
}
return ret;
}
ssize_t EVTCPServer::handleCLWrFdWritable(StreamSocket & streamSocket, const bool& ev_occured)
{
ssize_t ret = 0;
EVAcceptedStreamSocket *tn = getTn(streamSocket.impl()->sockfd());
if (!tn) return -1;
tn->setTimeOfLastUse();
_ssLRUList.move(tn);
if (!tn->resDataAvlbl()) {
goto handleCLWrFdWritable_finally;
}
{
chunked_memory_stream * cms = 0;
ssize_t ret1 = 0;
int count = 0;
cms = tn->getResMemStream();
void * nodeptr = 0;
void * buffer = 0;
size_t bytes = 0;
nodeptr = cms->get_next(0);
//DEBUGPOINT("Here np = %p for %d\n", nodeptr, tn->getSockfd());
while (nodeptr) {
count ++;
buffer = cms->get_buffer(nodeptr);
bytes = cms->get_buffer_len(nodeptr);
//ret1 = sendData(streamSocket.impl()->sockfd(), buffer, bytes);
//DEBUGPOINT("SENDING_DATA ON ACCP SOCK %d\n", streamSocket.impl()->sockfd());
ret1 = writeData(tn->getOutStreamSocket().impl()->sockfd(), buffer, bytes);
if (ret1 > 0) {
cms->erase(ret1);
nodeptr = cms->get_next(0);
buffer = 0;
bytes = 0;
ret += ret1;
ret1 = 0;
//DEBUGPOINT("Here for [%zd] %d [%s]\n", ret, tn->getSockfd(), strerror(errno));
}
else if (ret1 == 0) {
// Add to waiting for being write ready.
//DEBUGPOINT("Here for [%zd] %d [%s]\n", ret, tn->getSockfd(), strerror(errno));
ret = 0;
break;
}
else {
//DEBUGPOINT("Here for [%zd] %d [%s]\n", ret, tn->getSockfd(), strerror(errno));
ret = -1;
break;
}
}
}
handleCLWrFdWritable_finally:
if (ret >=0) {
/* If there is more data to be sent, wait for
* the socket to become writable again.
* */
if (!tn->resDataAvlbl()) ret = 1;
else ret = 0;
}
//DEBUGPOINT("Here ret = %zd state = %d for %d\n", ret, tn->getState(), tn->getSockfd());
if (ret > 0) {
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
socket_watcher_ptr = tn->getSocketWatcher();
if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_WRITE) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
tn->setState(EVAcceptedStreamSocket::NOT_WAITING);
}
else if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READWRITE) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_1, streamSocket.impl()->sockfd(), EV_READ);
ev_io_start (this->_loop, socket_watcher_ptr);
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_READ);
}
else {
/* It should not come here otherwise. */
std::abort();
}
}
else if (ret <0) {
/* At this point we know that the socket has become unusable,
* it is possible to dispose it off and complete housekeeping.
* However there is a likelihood that another thread is still
* processing this socket, hence the disposing off must not be
* done over here.
*
* When the processing gets complete, and the socket is returned,
* At that time the socket will get disposed.
* */
//DEBUGPOINT("Here for %d\n", tn->getSockfd());
tn->setSockInError();
}
return ret;
}
ssize_t EVTCPServer::handleAccSocketWritable(StreamSocket & streamSocket, const bool& ev_occured)
{
ssize_t ret = 0;
EVAcceptedStreamSocket *tn = getTn(streamSocket.impl()->sockfd());
if (!tn) return -1;
tn->setTimeOfLastUse();
_ssLRUList.move(tn);
if (!tn->resDataAvlbl()) {
goto handleAccSocketWritable_finally;
}
{
chunked_memory_stream * cms = 0;
ssize_t ret1 = 0;
int count = 0;
cms = tn->getResMemStream();
void * nodeptr = 0;
void * buffer = 0;
size_t bytes = 0;
nodeptr = cms->get_next(0);
//DEBUGPOINT("Here np = %p for %d\n", nodeptr, tn->getSockfd());
while (nodeptr) {
count ++;
buffer = cms->get_buffer(nodeptr);
bytes = cms->get_buffer_len(nodeptr);
//ret1 = sendData(streamSocket.impl()->sockfd(), buffer, bytes);
//DEBUGPOINT("SENDING_DATA ON ACCP SOCK %d\n", streamSocket.impl()->sockfd());
ret1 = sendData(streamSocket, buffer, bytes);
if (ret1 > 0) {
cms->erase(ret1);
nodeptr = cms->get_next(0);
buffer = 0;
bytes = 0;
ret += ret1;
ret1 = 0;
//DEBUGPOINT("Here for [%zd] %d [%s]\n", ret, tn->getSockfd(), strerror(errno));
}
else if (ret1 == 0) {
// Add to waiting for being write ready.
//DEBUGPOINT("Here for [%zd] %d [%s]\n", ret, tn->getSockfd(), strerror(errno));
ret = 0;
break;
}
else {
//DEBUGPOINT("Here for [%zd] %d [%s]\n", ret, tn->getSockfd(), strerror(errno));
ret = -1;
break;
}
}
}
handleAccSocketWritable_finally:
if (ret >=0) {
/* If there is more data to be sent, wait for
* the socket to become writable again.
* */
if (!tn->resDataAvlbl()) ret = 1;
else ret = 0;
}
//DEBUGPOINT("Here ret = %zd state = %d for %d\n", ret, tn->getState(), tn->getSockfd());
if (ret > 0) {
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
socket_watcher_ptr = tn->getSocketWatcher();
if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_WRITE) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
tn->setState(EVAcceptedStreamSocket::NOT_WAITING);
}
else if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READWRITE) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_1, streamSocket.impl()->sockfd(), EV_READ);
ev_io_start (this->_loop, socket_watcher_ptr);
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_READ);
}
else {
/* It should not come here otherwise. */
std::abort();
}
}
else if (ret <0) {
/* At this point we know that the socket has become unusable,
* it is possible to dispose it off and complete housekeeping.
* However there is a likelihood that another thread is still
* processing this socket, hence the disposing off must not be
* done over here.
*
* When the processing gets complete, and the socket is returned,
* At that time the socket will get disposed.
* */
//DEBUGPOINT("Here for %d\n", tn->getSockfd());
tn->setSockInError();
}
return ret;
}
ssize_t EVTCPServer::receiveData(StreamSocket & ss, void * chptr, size_t size, int * wait_mode_ptr)
{
ssize_t ret = 0;
errno = 0;
try {
ret = ss.receiveBytes(chptr, size );
}
catch (std::exception & e) {
}
if (ret < 0 && wait_mode_ptr) *wait_mode_ptr = ret;
else if (wait_mode_ptr) *wait_mode_ptr = 0;
if ((ret <= 0) || errno) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
}
else {
const char * error_string = NULL;
if (!errno) {
error_string = "Peer closed connection";
}
else {
error_string = strerror(errno);
}
return -1;
}
}
return ret;
}
ssize_t EVTCPServer::writeData(int fd, void * chptr, size_t size, int * wait_mode_ptr)
{
ssize_t ret = 0;
errno = 0;
//DEBUGPOINT("fd = [%d]\n", fd);
ret = write(fd, chptr, size);
if (ret < 0 && wait_mode_ptr) *wait_mode_ptr = ret;
else if (wait_mode_ptr) *wait_mode_ptr = 0;
if ((ret <= 0) || errno) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
}
else {
const char * error_string = NULL;
if (!errno) {
error_string = "Peer closed connection";
}
else {
error_string = strerror(errno);
}
return -1;
}
}
return ret;
}
ssize_t EVTCPServer::readData(int fd, void * chptr, size_t size, int * wait_mode_ptr)
{
ssize_t ret = 0;
errno = 0;
ret = read(fd, chptr, size);
if (ret < 0 && wait_mode_ptr) *wait_mode_ptr = ret;
else if (wait_mode_ptr) *wait_mode_ptr = 0;
if ((ret <= 0) || errno) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
}
else {
const char * error_string = NULL;
if (!errno) {
error_string = "Peer closed connection";
}
else {
error_string = strerror(errno);
}
DEBUGPOINT("%d:%d-%s\n", errno, fd, error_string);
return -1;
}
}
return ret;
}
ssize_t EVTCPServer::receiveData(int fd, void * chptr, size_t size, int * wait_mode_ptr)
{
ssize_t ret = 0;
errno = 0;
ret = recv(fd, chptr, size , 0);
if (ret < 0 && wait_mode_ptr) *wait_mode_ptr = ret;
else if (wait_mode_ptr) *wait_mode_ptr = 0;
if ((ret <= 0) || errno) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
}
else {
const char * error_string = NULL;
if (!errno) {
error_string = "Peer closed connection";
}
else {
error_string = strerror(errno);
}
DEBUGPOINT("%d:%d-%s\n", errno, fd, error_string);
return -1;
}
}
return ret;
}
ssize_t EVTCPServer::handleConnSocketReadAndWriteReady(strms_io_cb_ptr_type cb_ptr, const bool& ev_occured)
{
//DEBUGPOINT("EVTCPServer::handleConnSocketReadAndWriteReady\n");
ssize_t ret = 0;
size_t received_bytes = 0;
EVConnectedStreamSocket *cn = cb_ptr->cn;
cn->setTimeOfLastUse();
errno = 0;
EVAcceptedStreamSocket *tn = getTn(cn->getAccSockfd());
if (!tn) {
DEBUGPOINT("THIS CONDITION MUST NEVER HAPPEN\n");
std::abort();
return -1;
}
EVConnectedStreamSocket *ref_cn = tn->getProcState()->getEVConnSock(cn->getSockfd());
if ((!ref_cn) || (ref_cn->getSockfd() != cn->getSockfd())) {
DEBUGPOINT("THIS CONDITION MUST NEVER HAPPEN\n");
std::abort();
return -1;
}
//DEBUGPOINT("EVTCPServer::handleConnSocketReadAndWriteReady\n");
EVUpstreamEventNotification * usN = 0;
if ((tn->getProcState()) && tn->srInSession(cb_ptr->sr_num)) {
usN = new EVUpstreamEventNotification(cb_ptr->sr_num, (cn->getStreamSocket().impl()->sockfd()),
cb_ptr->cb_evid_num,
(ret)?ret:1, 0);
usN->setConnSockState(EVUpstreamEventNotification::READY_FOR_READWRITE);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
ev_io * socket_watcher_ptr = cn->getSocketWatcher();
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
cn->setState(EVConnectedStreamSocket::NOT_WAITING);
DEBUGPOINT("EVTCPServer::handleConnSocketReadAndWriteReady %d\n", cb_ptr->connSocketManaged);
if (cb_ptr->connSocketManaged) {
ref_cn->invalidateSocket();
tn->getProcState()->eraseEVConnSock(cn->getSockfd());
}
return ret;
}
ssize_t EVTCPServer::handleConnSocketWriteReady(strms_io_cb_ptr_type cb_ptr, const bool& ev_occured)
{
//DEBUGPOINT("EVTCPServer::handleConnSocketWriteReady\n");
ssize_t ret = 0;
size_t received_bytes = 0;
EVConnectedStreamSocket *cn = cb_ptr->cn;
cn->setTimeOfLastUse();
errno = 0;
EVAcceptedStreamSocket *tn = getTn(cn->getAccSockfd());
if (!tn) {
DEBUGPOINT("THIS CONDITION MUST NEVER HAPPEN\n");
std::abort();
return -1;
}
EVConnectedStreamSocket *ref_cn = tn->getProcState()->getEVConnSock(cn->getSockfd());
if ((!ref_cn) || (ref_cn->getSockfd() != cn->getSockfd())) {
DEBUGPOINT("THIS CONDITION MUST NEVER HAPPEN\n");
std::abort();
return -1;
}
//DEBUGPOINT("EVTCPServer::handleConnSocketWriteReady\n");
EVUpstreamEventNotification * usN = 0;
if ((tn->getProcState()) && tn->srInSession(cb_ptr->sr_num)) {
usN = new EVUpstreamEventNotification(cb_ptr->sr_num, (cn->getStreamSocket().impl()->sockfd()),
cb_ptr->cb_evid_num,
(ret)?ret:1, 0);
usN->setConnSockState(EVUpstreamEventNotification::READY_FOR_WRITE);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
ev_io * socket_watcher_ptr = cn->getSocketWatcher();
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
cn->setState(EVConnectedStreamSocket::NOT_WAITING);
//DEBUGPOINT("EVTCPServer::handleConnSocketWriteReady\n");
//DEBUGPOINT("EVTCPServer::handleConnSocketWriteReady %d\n", cb_ptr->connSocketManaged);
if (cb_ptr->connSocketManaged) {
ref_cn->invalidateSocket();
tn->getProcState()->eraseEVConnSock(cn->getSockfd());
}
return ret;
}
ssize_t EVTCPServer::handleConnSocketReadReady(strms_io_cb_ptr_type cb_ptr, const bool& ev_occured)
{
//DEBUGPOINT("EVTCPServer::handleConnSocketReadReady\n");
ssize_t ret = 0;
size_t received_bytes = 0;
EVConnectedStreamSocket *cn = cb_ptr->cn;
cn->setTimeOfLastUse();
errno = 0;
//DEBUGPOINT("EVTCPServer::handleConnSocketReadReady\n");
EVAcceptedStreamSocket *tn = getTn(cn->getAccSockfd());
if (!tn) {
DEBUGPOINT("THIS CONDITION MUST NEVER HAPPEN\n");
std::abort();
return -1;
}
EVConnectedStreamSocket *ref_cn = tn->getProcState()->getEVConnSock(cn->getSockfd());
if ((!ref_cn) || (ref_cn->getSockfd() != cn->getSockfd())) {
DEBUGPOINT("THIS CONDITION MUST NEVER HAPPEN\n");
std::abort();
return -1;
}
EVUpstreamEventNotification * usN = 0;
if ((tn->getProcState()) && tn->srInSession(cb_ptr->sr_num)) {
usN = new EVUpstreamEventNotification(cb_ptr->sr_num, (cn->getStreamSocket().impl()->sockfd()),
cb_ptr->cb_evid_num,
(ret)?ret:1, 0);
usN->setConnSockState(EVUpstreamEventNotification::READY_FOR_READ);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
ev_io * socket_watcher_ptr = cn->getSocketWatcher();
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
cn->setState(EVConnectedStreamSocket::NOT_WAITING);
//DEBUGPOINT("EVTCPServer::handleConnSocketReadReady\n");
if (cb_ptr->connSocketManaged) {
ref_cn->invalidateSocket();
tn->getProcState()->eraseEVConnSock(cn->getSockfd());
}
return ret;
}
ssize_t EVTCPServer::handleConnSocketReadable(strms_io_cb_ptr_type cb_ptr, const bool& ev_occured)
{
ssize_t ret = 0;
size_t received_bytes = 0;
EVConnectedStreamSocket *cn = cb_ptr->cn;
cn->setTimeOfLastUse();
if (cn->getState() == EVConnectedStreamSocket::BEFORE_CONNECT) {
DEBUGPOINT("HERE BC\n");
cn->setState(EVConnectedStreamSocket::NOT_WAITING);
return handleConnSocketConnected(cb_ptr, ev_occured);
}
errno = 0;
EVAcceptedStreamSocket *tn = getTn(cn->getAccSockfd());
if (!tn) {
DEBUGPOINT("THIS CONDITION MUST NEVER HAPPEN\n");
std::abort();
return -1;
}
EVConnectedStreamSocket *ref_cn = tn->getProcState()->getEVConnSock(cn->getSockfd());
if ((!ref_cn) || (ref_cn->getSockfd() != cn->getSockfd())) {
DEBUGPOINT("THIS CONDITION MUST NEVER HAPPEN\n");
std::abort();
return -1;
}
{
ssize_t ret1 = 0;
int count = 0;
do {
count ++;
void * buffer = malloc(TCP_BUFFER_SIZE);
memset(buffer,0,TCP_BUFFER_SIZE);
//ret1 = receiveData(streamSocket.impl()->sockfd(), buffer, TCP_BUFFER_SIZE);
ret1 = receiveData(cn->getStreamSocket(), buffer, TCP_BUFFER_SIZE);
if (ret1 >0) {
//printf("%zd\n", ret1);
cn->pushRcvData(buffer, (size_t)ret1);
ret += ret1;
received_bytes += ret1;
}
else {
free(buffer);
if (ret1 < 0) {
ret = -1;
}
}
} while(!_blocking && ret1>0);
}
handleConnSocketReadable_finally:
/* ret will be 0 after recv even on a tickled socket
* in case of SSL handshake.
* */
//DEBUGPOINT("Return value of read = %zd\n", ret);
if (ret != 0) {
ev_io * socket_watcher_ptr = 0;
socket_watcher_ptr = cn->getSocketWatcher();
if (cn->getState() == EVConnectedStreamSocket::WAITING_FOR_READ) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
cn->setState(EVConnectedStreamSocket::NOT_WAITING);
}
else if (cn->getState() == EVConnectedStreamSocket::WAITING_FOR_READWRITE) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_3, cn->getSockfd(), EV_WRITE);
ev_io_start (this->_loop, socket_watcher_ptr);
cn->setState(EVConnectedStreamSocket::WAITING_FOR_WRITE);
}
else {
/* It should not come here otherwise. */
DEBUGPOINT("SHOULD NOT HAVE REACHED HERE %d\n", cn->getState());
std::abort();
}
tn->decrNumCSEvents();
}
if ((ret >=0) && cn->rcvDataAvlbl()) {
EVUpstreamEventNotification * usN = 0;
if ((tn->getProcState()) && tn->srInSession(cb_ptr->sr_num)) {
usN = new EVUpstreamEventNotification(cb_ptr->sr_num, (cn->getStreamSocket().impl()->sockfd()),
cb_ptr->cb_evid_num,
(ret)?ret:1, 0);
usN->setRecvStream(cn->getRcvMemStream());
usN->setSendStream(cn->getSendMemStream());
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
}
else if (ret<0) {
cn->setSockInError();
EVUpstreamEventNotification * usN = 0;
if ((tn->getProcState()) && tn->srInSession(cb_ptr->sr_num)) {
usN = new EVUpstreamEventNotification(cb_ptr->sr_num, (cn->getStreamSocket().impl()->sockfd()),
cb_ptr->cb_evid_num,
-1, errno);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
cn->setSockInError();
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
}
else {
}
return ret;
}
ssize_t EVTCPServer::handleAccSocketReadable(StreamSocket & ss, const bool& ev_occured)
{
ssize_t ret = 0;
size_t received_bytes = 0;
EVAcceptedStreamSocket *tn = getTn(ss.impl()->sockfd());
tn->setTimeOfLastUse();
_ssLRUList.move(tn);
{
ssize_t ret1 = 0;
int count = 0;
do {
count ++;
void * buffer = malloc(TCP_BUFFER_SIZE);
memset(buffer,0,TCP_BUFFER_SIZE);
//ret1 = receiveData(ss.impl()->sockfd(), buffer, TCP_BUFFER_SIZE);
ret1 = receiveData(ss, buffer, TCP_BUFFER_SIZE);
if (ret1 >0) {
//printf("%zd\n", ret1);
tn->pushReqData(buffer, (size_t)ret1);
ret += ret1;
received_bytes += ret1;
}
else {
free(buffer);
if (ret1 < 0) {
ret = -1;
}
}
} while(!_blocking && ret1>0);
}
handleAccSocketReadable_finally:
if ((ret >=0) && tn->reqDataAvlbl()) {
if (!(tn->getProcState()) ||
( tn->getProcState()->needMoreData() &&
( (tn->getProcState()->newDataProcessed()) ||
(!(tn->getProcState()->newDataProcessed()) && (received_bytes > 0))
)
)
) {
if (!(tn->getProcState())) {
tn->setProcState(_pConnectionFactory->createReqProcState(this));
//DEBUGPOINT("Created processing state %p for %d\n", tn->getProcState(), tn->getSockfd());
tn->getProcState()->setClientAddress(tn->clientAddress());
tn->getProcState()->setServerAddress(tn->serverAddress());
/* Session starts when a new processing state is created. */
unsigned long sr_num = std::atomic_load(&(this->_sr_srl_num));
tn->setBaseSRSrlNum(sr_num);
}
tn->setSockBusy();
_pDispatcher->enqueue(tn);
/* If data is available, and a task has been enqueued.
* It is not OK to cleanup the socket.
* It is proper to process whatever data is still there
* and then close the socket at a later time.
* */
ret = 1;
}
else {
/* This is a case of receiving data that is not asked by the
* server.
* */
}
}
/* ret will be 0 after recv even on a tickled socket
* in case of SSL handshake.
* */
if (ret > 0) {
ev_io * socket_watcher_ptr = 0;
socket_watcher_ptr = tn->getSocketWatcher();
if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READ) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
tn->setState(EVAcceptedStreamSocket::NOT_WAITING);
}
else if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READWRITE) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_1, ss.impl()->sockfd(), EV_WRITE);
ev_io_start (this->_loop, socket_watcher_ptr);
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_WRITE);
}
else {
/* It should not come here otherwise. */
DEBUGPOINT("SHOULD NOT HAVE REACHED HERE %d\n", tn->getState());
std::abort();
}
}
else if (ret < 0) {
//DEBUGPOINT("Here for %d\n", tn->getSockfd());
tn->setSockInError();
// If handleAccSocketReadable is called not from event loop (ev_occured = true)
// Cleaning up of socket will lead to context being lost completely.
// It sould be marked as being in error and the housekeeping to be done at
// an approporiate time.
{
ev_io * socket_watcher_ptr = 0;
socket_watcher_ptr = tn->getSocketWatcher();
if (socket_watcher_ptr && ev_is_active(socket_watcher_ptr)) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
}
}
errorWhileReceiving(ss.impl()->sockfd(), true);
}
return ret;
}
void EVTCPServer::dataReadyForSend(int fd)
{
/* Enque the socket */
_queue.enqueueNotification(new EVTCPServerNotification(fd,
EVTCPServerNotification::DATA_FOR_SEND_READY));
/* And then wake up the loop calls event_notification_on_downstream_socket */
//DEBUGPOINT("FROM HERE\n");
ev_async_send(this->_loop, this->_stop_watcher_ptr3);
return;
}
void EVTCPServer::receivedDataConsumed(int fd)
{
/* Enque the socket */
//STACK_TRACE();
_queue.enqueueNotification(new EVTCPServerNotification(fd,
EVTCPServerNotification::REQDATA_CONSUMED));
/* And then wake up the loop calls event_notification_on_downstream_socket */
//DEBUGPOINT("FROM HERE\n");
ev_async_send(this->_loop, this->_stop_watcher_ptr3);
return;
}
void EVTCPServer::errorWhileSending(poco_socket_t fd, bool connInErr)
{
/* Enque the socket */
//_queue.enqueueNotification(new EVTCPServerNotification(streamSocket,fd,true));
/* The StreamSocket Received in this function may not contain the desirable value.
* It could have become -1.
* */
_queue.enqueueNotification(new EVTCPServerNotification(fd,
EVTCPServerNotification::ERROR_WHILE_SENDING));
/* And then wake up the loop calls event_notification_on_downstream_socket */
//DEBUGPOINT("FROM HERE\n");
ev_async_send(this->_loop, this->_stop_watcher_ptr3);
return;
}
void EVTCPServer::errorWhileReceiving(poco_socket_t fd, bool connInErr)
{
/* Enque the socket */
//_queue.enqueueNotification(new EVTCPServerNotification(streamSocket,fd,true));
/* The StreamSocket Received in this function may not contain the desirable value.
* It could have become -1.
* */
_queue.enqueueNotification(new EVTCPServerNotification(fd,
EVTCPServerNotification::ERROR_WHILE_RECEIVING));
/* And then wake up the loop calls event_notification_on_downstream_socket */
//DEBUGPOINT("FROM HERE\n");
ev_async_send(this->_loop, this->_stop_watcher_ptr3);
return;
}
void EVTCPServer::errorInAuxProcesing(poco_socket_t fd, bool connInErr)
{
/* Enque the socket */
//_queue.enqueueNotification(new EVTCPServerNotification(streamSocket,fd,true));
/* The StreamSocket Received in this function may not contain the desirable value.
* It could have become -1.
* */
//DEBUGPOINT("Here for %d\n", fd);
//STACK_TRACE();
_queue.enqueueNotification(new EVTCPServerNotification(fd,
EVTCPServerNotification::ERROR_IN_AUX_PROCESSING));
/* And then wake up the loop calls event_notification_on_downstream_socket */
//DEBUGPOINT("FROM HERE\n");
ev_async_send(this->_loop, this->_stop_watcher_ptr3);
return;
}
void EVTCPServer::errorInReceivedData(poco_socket_t fd, bool connInErr)
{
/* Enque the socket */
//_queue.enqueueNotification(new EVTCPServerNotification(streamSocket,fd,true));
/* The StreamSocket Received in this function may not contain the desirable value.
* It could have become -1.
* */
_queue.enqueueNotification(new EVTCPServerNotification(fd,
EVTCPServerNotification::ERROR_IN_PROCESSING));
/* And then wake up the loop calls event_notification_on_downstream_socket */
//DEBUGPOINT("FROM HERE\n");
ev_async_send(this->_loop, this->_stop_watcher_ptr3);
return;
}
void EVTCPServer::monitorDataOnCLFd(EVAcceptedStreamSocket *tn)
{
ev_io * socket_watcher_ptr = 0;
if (tn->sockInError()) {
DEBUGPOINT("SOCK IN ERROR RETURNING for %d\n", tn->getSockfd());
return;
}
socket_watcher_ptr = tn->getSocketWatcher();
StreamSocket ss = tn->getStreamSocket();
{
/* If socket is not readable make it readable*/
if ((tn->getState() == EVAcceptedStreamSocket::NOT_WAITING) ||
tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_WRITE) {
int events = 0;
if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_WRITE) {
events = EVAcceptedStreamSocket::WAITING_FOR_READWRITE;
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_READWRITE);
}
else {
events = EVAcceptedStreamSocket::WAITING_FOR_READ;
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_READ);
}
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
//ev_io_set (socket_watcher_ptr, ss.impl()->sockfd(), EV_READ);
ev_io_init(socket_watcher_ptr, async_stream_socket_cb_1, ss.impl()->sockfd(), events);
ev_io_start (this->_loop, socket_watcher_ptr);
}
}
if (tn->reqDataAvlbl()) {
/* There is residual data on socket.
* This can be a cause for unnecessary thread context switching
* opportunity for optimization.
* */
handleCLFdReadable(ss, false);
}
else {
// TBD TO ADD SOCKET TO TIME OUT MONITORING LIST
}
return;
}
void EVTCPServer::monitorDataOnAccSocket(EVAcceptedStreamSocket *tn)
{
ev_io * socket_watcher_ptr = 0;
if (tn->sockInError()) {
DEBUGPOINT("SOCK IN ERROR RETURNING for %d\n", tn->getSockfd());
return;
}
socket_watcher_ptr = tn->getSocketWatcher();
StreamSocket ss = tn->getStreamSocket();
{
/* If socket is not readable make it readable*/
if ((tn->getState() == EVAcceptedStreamSocket::NOT_WAITING) ||
tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_WRITE) {
int events = 0;
if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_WRITE) {
events = EVAcceptedStreamSocket::WAITING_FOR_READWRITE;
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_READWRITE);
}
else {
events = EVAcceptedStreamSocket::WAITING_FOR_READ;
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_READ);
}
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
//ev_io_set (socket_watcher_ptr, ss.impl()->sockfd(), EV_READ);
ev_io_init(socket_watcher_ptr, async_stream_socket_cb_1, ss.impl()->sockfd(), events);
ev_io_start (this->_loop, socket_watcher_ptr);
}
}
if (tn->reqDataAvlbl()) {
/* There is residual data on socket.
* This can be a cause for unnecessary thread context switching
* opportunity for optimization.
* */
handleAccSocketReadable(ss, false);
}
else {
// TBD TO ADD SOCKET TO TIME OUT MONITORING LIST
}
return;
}
void EVTCPServer::sendDataOnReturnPipe(EVAcceptedStreamSocket *tn, int OnEvent)
{
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
socket_watcher_ptr = tn->getSocketWatcher();
if (!socket_watcher_ptr) std::abort();
cb_ptr = (strms_io_cb_ptr_type)socket_watcher_ptr->data;
/* If socket is not writable make it so. */
//DEBUGPOINT("Here state %d for %d\n", tn->getState(), tn->getSockfd());
if ((tn->getState() == EVAcceptedStreamSocket::NOT_WAITING) ||
tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READ) {
int events = 0;
if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READ) {
//STACK_TRACE();
//DEBUGPOINT("Here for socket %d\n", tn->getSockfd());
events = EVAcceptedStreamSocket::WAITING_FOR_READWRITE;
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_READWRITE);
}
else {
//STACK_TRACE();
//DEBUGPOINT("Here for socket %d\n", tn->getSockfd());
events = EVAcceptedStreamSocket::WAITING_FOR_WRITE;
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_WRITE);
}
cb_ptr->socketWritable = &EVTCPServer::handleCLWrFdWritable;
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_1, tn->getSockfd(), events);
ev_io_start (this->_loop, socket_watcher_ptr);
}
StreamSocket ss = tn->getStreamSocket();
handleCLWrFdWritable(ss, false);
return;
}
void EVTCPServer::sendDataOnAccSocket(EVAcceptedStreamSocket *tn, int OnEvent)
{
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
socket_watcher_ptr = tn->getSocketWatcher();
if (!socket_watcher_ptr) std::abort();
cb_ptr = (strms_io_cb_ptr_type)socket_watcher_ptr->data;
/* If socket is not writable make it so. */
//DEBUGPOINT("Here state %d for %d\n", tn->getState(), tn->getSockfd());
if ((tn->getState() == EVAcceptedStreamSocket::NOT_WAITING) ||
tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READ) {
int events = 0;
if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READ) {
//STACK_TRACE();
//DEBUGPOINT("Here for socket %d\n", tn->getSockfd());
events = EVAcceptedStreamSocket::WAITING_FOR_READWRITE;
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_READWRITE);
}
else {
//STACK_TRACE();
//DEBUGPOINT("Here for socket %d\n", tn->getSockfd());
events = EVAcceptedStreamSocket::WAITING_FOR_WRITE;
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_WRITE);
}
cb_ptr->socketWritable = &EVTCPServer::handleAccSocketWritable;
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_1, tn->getSockfd(), events);
ev_io_start (this->_loop, socket_watcher_ptr);
}
StreamSocket ss = tn->getStreamSocket();
handleAccSocketWritable(ss, false);
return;
}
void EVTCPServer::somethingHappenedInAnotherThread(const bool& ev_occured)
{
ev_io * socket_watcher_ptr = 0;
AutoPtr<Notification> pNf = 0;
for (pNf = _queue.dequeueNotification(); pNf ; pNf = _queue.dequeueNotification()) {
EVTCPServerNotification * pcNf = dynamic_cast<EVTCPServerNotification*>(pNf.get());
EVTCPServerNotification::what event = pcNf->getEvent();
EVAcceptedStreamSocket *tn = getTn(pcNf->sockfd());
if (!tn) {
/* This should never happen. */
DEBUGPOINT("Did not find entry in _accssColl for [%d] for event = [%d]\n", pcNf->sockfd(), event);
/* Multiple events can get queued for a socket from another thread.
* In the meanwhile, it is possible that the socket gets into an error state
* due to various conditions, one such is wrong data format and the protocol
* handler fails. This condition will lead to socket getting closed.
* Subsequent events after closing of the socket must be ignored.
* */
continue;
}
socket_watcher_ptr = getTn(pcNf->sockfd())->getSocketWatcher();
StreamSocket ss = tn->getStreamSocket();
/* If some error has been noticed on this socket, dispose it off cleanly
* over here
* */
if ((event == EVTCPServerNotification::REQDATA_CONSUMED) && (tn->sockInError())) {
//DEBUGPOINT("Here for %d\n", tn->getSockfd());
event = EVTCPServerNotification::ERROR_IN_PROCESSING;
}
switch (event) {
case EVTCPServerNotification::REQDATA_CONSUMED:
//DEBUGPOINT("REQDATA_CONSUMED on socket %d\n", ss.impl()->sockfd());
tn->setSockFree();
if (PROCESS_COMPLETE <= (tn->getProcState()->getState())) {
//DEBUGPOINT("REMOVING STATE of %d\n", ss.impl()->sockfd());
std::map<int,int>& subscriptions = tn->getProcState()->getFileEvtSubscriptions();
for (auto it = subscriptions.begin(); it != subscriptions.end(); ++it) {
//DEBUGPOINT("Here %d\n", it->first);
_file_evt_subscriptions.erase(it->first);
}
subscriptions.clear();
if (this->_mode == SERVER_MODE)
DEBUGPOINT("Deleted processing state %p for %d\n", tn->getProcState(), tn->getSockfd());
tn->deleteState();
/* Should reset of number of CS events be done at all
* tn->newresetNumCSEvents();
* */
tn->setWaitingTobeEnqueued(false);
//DEBUGPOINT("COMPLETED PROCESSING # CS EVENTS %d\n",tn->pendingCSEvents());
}
//else DEBUGPOINT("RETAINING STATE\n");
if (tn->getSockMode() == EVAcceptedStreamSocket::COMMAND_LINE_MODE)
sendDataOnReturnPipe(tn, event);
else
sendDataOnAccSocket(tn, event);
/* SOCK IS FREE HERE */
if (tn->getProcState() && tn->waitingTobeEnqueued()) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
/* SOCK HAS BECOME BUSY HERE */
srCompleteEnqueue(tn);
}
if (!tn->getProcState() && tn->sockInError()) {
/* If processing state is present, another thread can still be processing
* the request, hence cannot complete housekeeping.
* */
//DEBUGPOINT("clearing for %d\n", tn->getSockfd());
clearAcceptedSocket(pcNf->sockfd());
}
else {
//DEBUGPOINT("Here for %d\n", tn->getSockfd());
/* SHOULD MONITOR FOR MORE DATA ONLY IF SOCKET IS FREE */
if (this->_mode == SERVER_MODE) {
if (!(tn->sockBusy())) monitorDataOnAccSocket(tn);
}
else {
if (!(tn->sockBusy())) monitorDataOnCLFd(tn);
}
}
break;
case EVTCPServerNotification::DATA_FOR_SEND_READY:
//DEBUGPOINT("DATA_FOR_SEND_READY on socket %d\n", ss.impl()->sockfd());
if (tn->getSockMode() == EVAcceptedStreamSocket::COMMAND_LINE_MODE)
sendDataOnReturnPipe(tn, event);
else
sendDataOnAccSocket(tn, event);
break;
case EVTCPServerNotification::ERROR_IN_PROCESSING:
//DEBUGPOINT("ERROR_IN_PROCESSING on socket %d\n", pcNf->sockfd());
tn->setSockFree();
if (tn->newpendingCSEvents()) {
//DEBUGPOINT("RETAINING ACC SOCK\n");
//DEBUGPOINT("Here for %d\n", tn->getSockfd());
tn->setSockInError();
}
else {
//DEBUGPOINT("CLEARING ACC SOCK %d\n", pcNf->sockfd());
if (tn->getProcState()) {
std::map<int,int>& subscriptions = tn->getProcState()->getFileEvtSubscriptions();
for (auto it = subscriptions.begin(); it != subscriptions.end(); ++it) {
//DEBUGPOINT("Here %d\n", it->first);
_file_evt_subscriptions.erase(it->first);
}
subscriptions.clear();
}
//DEBUGPOINT("clearing for %d\n", tn->getSockfd());
clearAcceptedSocket(pcNf->sockfd());
}
break;
case EVTCPServerNotification::ERROR_IN_AUX_PROCESSING:
//DEBUGPOINT("ERROR_IN_AUX_PROCESSING on socket %d\n", pcNf->sockfd());
if (tn->newpendingCSEvents() || tn->sockBusy()) {
//DEBUGPOINT("RETAINING ACC SOCK\n");
//DEBUGPOINT("Here for %d\n", tn->getSockfd());
tn->setSockInError();
}
else {
//DEBUGPOINT("CLEARING ACC SOCK %d\n", pcNf->sockfd());
if (tn->getProcState()) {
std::map<int,int>& subscriptions = tn->getProcState()->getFileEvtSubscriptions();
for (auto it = subscriptions.begin(); it != subscriptions.end(); ++it) {
//DEBUGPOINT("Here %d\n", it->first);
_file_evt_subscriptions.erase(it->first);
}
subscriptions.clear();
}
//DEBUGPOINT("clearing for %d\n", tn->getSockfd());
clearAcceptedSocket(pcNf->sockfd());
}
break;
/* The following 2 cases are generated within the thread of
* EVTCPServer. Whereas the above ones are resultant of some
* event in the worker thread.
* */
case EVTCPServerNotification::ERROR_WHILE_SENDING:
//DEBUGPOINT("ERROR_WHILE_SENDING on socket %d\n", pcNf->sockfd());
case EVTCPServerNotification::ERROR_WHILE_RECEIVING:
//DEBUGPOINT("ERROR_WHILE_RECEIVING on socket %d\n", pcNf->sockfd());
//DEBUGPOINT("SOCK [%d] BUSY = %d\n", pcNf->sockfd(), tn->sockBusy());
//DEBUGPOINT("SOCK [%d] peinding CS events = %d\n", pcNf->sockfd(), tn->newpendingCSEvents());
if (!(tn->sockBusy()) && !(tn->newpendingCSEvents())) {
//DEBUGPOINT("CLEARING ACC SOCK tn sock = %d, pcNf sock = %d\n", tn->getSockfd(), pcNf->sockfd());
if (tn->getProcState()) {
std::map<int,int>& subscriptions = tn->getProcState()->getFileEvtSubscriptions();
for (auto it = subscriptions.begin(); it != subscriptions.end(); ++it) {
//DEBUGPOINT("Here %d\n", it->first);
_file_evt_subscriptions.erase(it->first);
}
subscriptions.clear();
}
//DEBUGPOINT("clearing for %d\n", tn->getSockfd());
clearAcceptedSocket(pcNf->sockfd());
}
else {
//DEBUGPOINT("RETAINING ACC SOCK\n");
//DEBUGPOINT("Here for %d\n", tn->getSockfd());
tn->setSockInError();
}
break;
default:
break;
}
pcNf = NULL;
}
return;
}
void EVTCPServer::handleConnReq(const bool& ev_occured)
{
EVAcceptedStreamSocket * ptr = _ssLRUList.getLast();
while (ptr && (_accssColl.size() >= _numConnections)) {
if (ptr->getProcState()) {
ptr = ptr->getPrevPtr();
continue;
}
ev_io_stop(this->_loop, ptr->getSocketWatcher());
ev_clear_pending(this->_loop, ptr->getSocketWatcher());
DEBUGPOINT("Here\n");
errorInReceivedData(ptr->getSockfd(),true);
ptr = ptr->getPrevPtr();
}
int fd = 0;
try {
/* If the number of connections exceeds the limit this server can handle.
* Dont continue handling the connection.
* TBD: This strategy needs to be examined properly. TBD
* */
StreamSocket ss = _socket.acceptConnection();
if (_accssColl.size() >= _numConnections) {
return;
}
if (!_pConnectionFilter || _pConnectionFilter->accept(ss)) {
// enable nodelay per default: OSX really needs that
#if defined(POCO_OS_FAMILY_UNIX)
if (ss.address().family() != AddressFamily::UNIX_LOCAL)
#endif
{
ss.setNoDelay(true);
}
EVAcceptedStreamSocket * acceptedSock = new EVAcceptedStreamSocket(ss);
acceptedSock->setClientAddress(ss.peerAddress());
acceptedSock->setServerAddress(ss.address());
acceptedSock->setEventLoop(this->_loop);
{
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
socket_watcher_ptr = (ev_io*)malloc(sizeof(ev_io));
memset(socket_watcher_ptr,0,sizeof(ev_io));
cb_ptr = (strms_io_cb_ptr_type) malloc(sizeof(strms_io_cb_struct_type));
memset(cb_ptr,0,sizeof(strms_io_cb_struct_type));
acceptedSock->setSocketWatcher(socket_watcher_ptr);
fd = ss.impl()->sockfd();
_accssColl[ss.impl()->sockfd()] = acceptedSock;
acceptedSock->setTimeOfLastUse();
_ssLRUList.add(acceptedSock);
cb_ptr->objPtr = this;
cb_ptr->dataAvailable = &EVTCPServer::handleAccSocketReadable;
cb_ptr->ssPtr =acceptedSock->getStreamSocketPtr();
socket_watcher_ptr->data = (void*)cb_ptr;
acceptedSock->setState(EVAcceptedStreamSocket::WAITING_FOR_READ);
// Make the socket non blocking.
if (!_blocking) {
ss.impl()->setBlocking(_blocking);
fcntl(fd, F_SETFL, O_NONBLOCK);
}
/*
{
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval));
}
*/
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_1, ss.impl()->sockfd(), EV_READ);
ev_io_start (this->_loop, socket_watcher_ptr);
}
}
else {
DEBUGPOINT("CONN REQUEST REJECTED\n");
}
}
catch (Poco::Exception& exc) {
ErrorHandler::handle(exc);
}
catch (std::exception& exc) {
ErrorHandler::handle(exc);
}
catch (...) {
ErrorHandler::handle();
}
errno=0;
}
void EVTCPServer::handlePeriodicWakeup(const bool& ev_occured)
{
EVAcceptedStreamSocket *tn = 0;
tn = _ssLRUList.getFirst();
while (tn) {
/* Handle all those sockets which are waiting for read while
* processing of input data is in progress.
* */
/* This O(n) parsing can be a problem, if there are hundreds
* of thousands of connections.
* */
if ((EVAcceptedStreamSocket::WAITING_FOR_READWRITE == tn->getState() ||
EVAcceptedStreamSocket::WAITING_FOR_READ == tn->getState()) &&
(tn->getProcState() && (tn->getProcState()->needMoreData()))) {
struct timeval tv;
gettimeofday(&tv,0);
if ((tv.tv_sec - tn->getTimeOfLastUse()) > _receiveTimeOut) {
DEBUGPOINT("TIMER EVENT OCCURED for socket %d\n", tn->getSockfd());
ev_io_stop(this->_loop, tn->getSocketWatcher());
ev_clear_pending(this->_loop, tn->getSocketWatcher());
errorInReceivedData(tn->getSockfd(),true);
}
}
tn= tn->getNextPtr();
}
return;
}
ssize_t EVTCPServer::handleCLFdReadable(StreamSocket & ss, const bool& ev_occured)
{
ssize_t ret = 0;
size_t received_bytes = 0;
EVAcceptedStreamSocket *tn = getTn(ss.impl()->sockfd());
tn->setTimeOfLastUse();
_ssLRUList.move(tn);
{
ssize_t ret1 = 0;
int count = 0;
do {
count ++;
void * buffer = malloc(TCP_BUFFER_SIZE);
memset(buffer,0,TCP_BUFFER_SIZE);
ret1 = readData(ss.impl()->sockfd(), buffer, TCP_BUFFER_SIZE);
if (ret1 >0) {
tn->pushReqData(buffer, (size_t)ret1);
ret += ret1;
received_bytes += ret1;
if (received_bytes > TCP_BUFFER_SIZE) {
DEBUGPOINT("Commands of lentgth greater than [%d] not supported\n", TCP_BUFFER_SIZE);
std::abort();
}
}
else {
free(buffer);
if (ret1 < 0) {
ret = -1;
}
}
} while(!_blocking && ret1>0);
}
//std::abort();
handleCLFdReadable_finally:
if ((ret >=0) && tn->reqDataAvlbl()) {
if (!(tn->getProcState()) ||
( tn->getProcState()->needMoreData() &&
( (tn->getProcState()->newDataProcessed()) ||
(!(tn->getProcState()->newDataProcessed()) && (received_bytes > 0))
)
)
) {
if (!(tn->getProcState())) {
tn->setProcState(_pConnectionFactory->createCLProcState(this));
tn->getProcState()->setMode(EVTCPServer::COMMAND_LINE_MODE);
//DEBUGPOINT("Created processing state %p for %d\n", tn->getProcState(), tn->getSockfd());
tn->getProcState()->setClientAddress(tn->clientAddress());
tn->getProcState()->setServerAddress(tn->serverAddress());
/* Session starts when a new processing state is created. */
unsigned long sr_num = std::atomic_load(&(this->_sr_srl_num));
tn->setBaseSRSrlNum(sr_num);
}
tn->setSockBusy();
_pDispatcher->enqueue(tn);
/* If data is available, and a task has been enqueued.
* It is not OK to cleanup the socket.
* It is proper to process whatever data is still there
* and then close the socket at a later time.
* */
ret = 1;
}
else {
/* This is a case of receiving data that is not asked by the
* server.
* */
}
}
/* ret will be 0 after recv even on a tickled socket
* in case of SSL handshake.
* */
if (ret > 0) {
ev_io * socket_watcher_ptr = 0;
socket_watcher_ptr = tn->getSocketWatcher();
if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READ) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
tn->setState(EVAcceptedStreamSocket::NOT_WAITING);
}
else if (tn->getState() == EVAcceptedStreamSocket::WAITING_FOR_READWRITE) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_1, ss.impl()->sockfd(), EV_WRITE);
ev_io_start (this->_loop, socket_watcher_ptr);
tn->setState(EVAcceptedStreamSocket::WAITING_FOR_WRITE);
}
else {
/* It should not come here otherwise. */
DEBUGPOINT("SHOULD NOT HAVE REACHED HERE %d\n", tn->getState());
std::abort();
}
}
else if (ret < 0) {
//DEBUGPOINT("Here for %d\n", tn->getSockfd());
tn->setSockInError();
// If handleAccSocketReadable is called not from event loop (ev_occured = true)
// Cleaning up of socket will lead to context being lost completely.
// It sould be marked as being in error and the housekeeping to be done at
// an approporiate time.
{
ev_io * socket_watcher_ptr = 0;
socket_watcher_ptr = tn->getSocketWatcher();
if (socket_watcher_ptr && ev_is_active(socket_watcher_ptr)) {
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_clear_pending(this->_loop, socket_watcher_ptr);
}
}
errorWhileReceiving(ss.impl()->sockfd(), true);
}
return ret;
}
#include <poll.h>
void EVTCPServer::addCLPrimaryFdToAcceptedList(int fd, int wr_fd)
{
try {
EVAcceptedStreamSocket * acceptedSock = new EVAcceptedStreamSocket(fd, wr_fd);
acceptedSock->setEventLoop(this->_loop);
{
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
socket_watcher_ptr = (ev_io*)malloc(sizeof(ev_io));
memset(socket_watcher_ptr,0,sizeof(ev_io));
cb_ptr = (strms_io_cb_ptr_type) malloc(sizeof(strms_io_cb_struct_type));
memset(cb_ptr,0,sizeof(strms_io_cb_struct_type));
acceptedSock->setSocketWatcher(socket_watcher_ptr);
acceptedSock->getStreamSocketPtr()->setFd(fd);
_accssColl[fd] = acceptedSock;
acceptedSock->setTimeOfLastUse();
_ssLRUList.add(acceptedSock);
cb_ptr->objPtr = this;
cb_ptr->dataAvailable = &EVTCPServer::handleCLFdReadable;
/* The below line is a dummy and a hack to avoid SIGSEGV */
cb_ptr->ssPtr = acceptedSock->getStreamSocketPtr();
/* The above line is a dummy and a hack to avoid SIGSEGV */
socket_watcher_ptr->data = (void*)cb_ptr;
acceptedSock->setState(EVAcceptedStreamSocket::WAITING_FOR_READ);
// Make the socket non blocking.
if (!_blocking) {
fcntl(fd, F_SETFL, O_NONBLOCK);
}
ev_io_init (socket_watcher_ptr, async_stream_socket_cb_1, fd, EV_READ);
ev_io_start (this->_loop, socket_watcher_ptr);
errno=0;
}
}
catch (Poco::Exception& exc) {
ErrorHandler::handle(exc);
}
catch (std::exception& exc) {
ErrorHandler::handle(exc);
}
catch (...) {
ErrorHandler::handle();
}
}
static void fatal_error (const char *msg) noexcept
{
DEBUGPOINT("IN FATAL_ERROR\n");
perror (msg);
std::abort ();
}
void EVTCPServer::run()
{
ev_io socket_watcher;
ev_async stop_watcher_1;
ev_async stop_watcher_2;
ev_async stop_watcher_3;
ev_async dns_watcher;
ev_async gen_task_compl_watcher;
ev_async file_evt_watcher;
ev_timer timeout_watcher;
double timeout = 0.00001;
this->_thread_pool = create_thread_pool(DEFAULT_NUM_AUXJOB_THREADS);
//this->_thread_pool = create_thread_pool(1);
ef_set_thrpool(this->_thread_pool);
ef_init();
ef_set_cb_func(file_operation_completion, (void *)this);
this->_loop = EV_DEFAULT;
memset(&(socket_watcher), 0, sizeof(ev_io)); // Sinvle channel to monitor incoming
// connection requests and
// events on accepted sockets
memset(&(stop_watcher_1), 0, sizeof(ev_async)); // Channel to end the loop
memset(&(stop_watcher_2), 0, sizeof(ev_async)); // Channel for children threads
// to request services from main loop
memset(&(stop_watcher_3), 0, sizeof(ev_async)); // Channel for the asigned worker thread
// to coordinate with main thread
// for various request processing events
memset(&(dns_watcher),0,sizeof(ev_async)); // Channel to indicate resolution of a name
// via DNS service
memset(&(gen_task_compl_watcher),0,sizeof(ev_async));
// Channel to handle event of completion
// of generic tasks void* (*task)(void*)
memset(&(file_evt_watcher),0,sizeof(ev_async)); // Channel to monitor comletion of
// FILE IO events
memset(&(timeout_watcher), 0, sizeof(ev_timer));// Channel to monitor periodic timer
// for GC, etc...
this->_stop_watcher_ptr1 = &(stop_watcher_1);
this->_stop_watcher_ptr2 = &(stop_watcher_2);
this->_stop_watcher_ptr3 = &(stop_watcher_3);
this->_dns_watcher_ptr = &(dns_watcher);
this->_gen_task_compl_watcher_ptr = &(gen_task_compl_watcher);
this->_file_evt_watcher_ptr = &(file_evt_watcher);
if (this->_mode == SERVER_MODE) {
this->_cbStruct.objPtr = this;
this->_cbStruct.connArrived = &EVTCPServer::handleConnReq;
socket_watcher.data = (void*)&this->_cbStruct;
/* Making the server socket non-blocking. */
if (!_blocking) this->socket().impl()->setBlocking(_blocking);
/* Making the server socket non-blocking. */
/* Async handler to wait for the command to stop the server. */
{
ev_io_init (&(socket_watcher), new_connection, this->sockfd(), EV_READ);
ev_io_start (this->_loop, &(socket_watcher));
}
}
else {
this->addCLPrimaryFdToAcceptedList(_pipe_rd_fd, _pipe_wr_fd);
}
{
ev_async_init (&(stop_watcher_1), stop_the_loop);
ev_async_start (this->_loop, &(stop_watcher_1));
}
/* Async handler to wait for a service request from worker threads
* to deal with upstream connections */
{
/* When servicing of connected sockets is required, either to make new connection
* or to send data or to receive data.
* */
strms_pc_cb_ptr_type pc_cb_ptr = (strms_pc_cb_ptr_type)0;;
pc_cb_ptr = (strms_pc_cb_ptr_type)malloc(sizeof(strms_pc_cb_struct_type));
pc_cb_ptr->objPtr = this;
pc_cb_ptr->method = &EVTCPServer::handleServiceRequest;
stop_watcher_2.data = (void*)pc_cb_ptr;
ev_async_init (&(stop_watcher_2), process_service_request);
ev_async_start (this->_loop, &(stop_watcher_2));
}
/* Async request to handle events occeuring from worker thread on the
* accepted socket.
* */
{
/* When request processing either completes or more data is required
* for processing. */
strms_pc_cb_ptr_type pc_cb_ptr = (strms_pc_cb_ptr_type)0;;
pc_cb_ptr = (strms_pc_cb_ptr_type)malloc(sizeof(strms_pc_cb_struct_type));
pc_cb_ptr->objPtr = this;
pc_cb_ptr->method = &EVTCPServer::somethingHappenedInAnotherThread;
stop_watcher_3.data = (void*)pc_cb_ptr;
ev_async_init (&(stop_watcher_3), event_notification_on_downstream_socket);
ev_async_start (this->_loop, &(stop_watcher_3));
}
{
/* When host resolution service request completes in an auxillary thread
* the main event loop needs to be woken up for continuing the task.
* */
strms_pc_cb_ptr_type cb_ptr = 0;
cb_ptr = (strms_pc_cb_ptr_type) malloc(sizeof(strms_pc_cb_struct_type));
memset(cb_ptr,0,sizeof(strms_pc_cb_struct_type));
cb_ptr->objPtr = this;
cb_ptr->method = &EVTCPServer::handleHostResolved;
dns_watcher.data = (void*)cb_ptr;
ev_async_init(&dns_watcher, host_addr_resolved);
ev_async_start (this->_loop, &dns_watcher);
}
{
/* When execution of generic task completes in an auxillary thread
* the main event loop needs to be woken up for continuing the task.
* */
strms_pc_cb_ptr_type cb_ptr = 0;
cb_ptr = (strms_pc_cb_ptr_type) malloc(sizeof(strms_pc_cb_struct_type));
memset(cb_ptr,0,sizeof(strms_pc_cb_struct_type));
cb_ptr->objPtr = this;
cb_ptr->method = &EVTCPServer::handleGenericTaskComplete;
gen_task_compl_watcher.data = (void*)cb_ptr;
ev_async_init(&gen_task_compl_watcher, generic_task_complete);
ev_async_start (this->_loop, &gen_task_compl_watcher);
}
{
/* When read/close of a file completes in an auxillary thread
* the main event loop needs to be woken up for continuing the task.
* */
strms_pc_cb_ptr_type cb_ptr = 0;
cb_ptr = (strms_pc_cb_ptr_type) malloc(sizeof(strms_pc_cb_struct_type));
memset(cb_ptr,0,sizeof(strms_pc_cb_struct_type));
cb_ptr->objPtr = this;
cb_ptr->method = &EVTCPServer::handleFileEvtOccured;
file_evt_watcher.data = (void*)cb_ptr;
ev_async_init(&file_evt_watcher, file_evt_occured);
ev_async_start (this->_loop, &file_evt_watcher);
}
{
/* When a time interval of normal operation completes, housekeeping
* tasks have to be initiated to carryout cleanups wherever necessary.
* */
strms_pc_cb_ptr_type pc_cb_ptr = (strms_pc_cb_ptr_type)0;;
pc_cb_ptr = (strms_pc_cb_ptr_type)malloc(sizeof(strms_pc_cb_struct_type));
pc_cb_ptr->objPtr = this;
pc_cb_ptr->method = &EVTCPServer::handlePeriodicWakeup;
timeout_watcher.data = (void*)pc_cb_ptr;
timeout = 5.0;
ev_timer_init(&timeout_watcher, periodic_call_for_housekeeping, timeout, timeout);
ev_timer_start(this->_loop, &timeout_watcher);
}
// now wait for events to arrive
errno = 0;
ev_set_syserr_cb(fatal_error);
_loop_active = true;
atomic_thread_fence(std::memory_order_release);
ev_run (this->_loop, 0);
free(stop_watcher_2.data);
free(stop_watcher_3.data);
free(dns_watcher.data);
free(gen_task_compl_watcher.data);
free(file_evt_watcher.data);
free(timeout_watcher.data);
return;
}
int EVTCPServer::currentThreads() const
{
return _pDispatcher->currentThreads();
}
int EVTCPServer::maxThreads() const
{
return _pDispatcher->maxThreads();
}
int EVTCPServer::totalConnections() const
{
return _pDispatcher->totalConnections();
}
int EVTCPServer::currentConnections() const
{
return _pDispatcher->currentConnections();
}
int EVTCPServer::maxConcurrentConnections() const
{
return _pDispatcher->maxConcurrentConnections();
}
int EVTCPServer::queuedConnections() const
{
return _pDispatcher->queuedConnections();
}
int EVTCPServer::refusedConnections() const
{
return _pDispatcher->refusedConnections();
}
void EVTCPServer::setConnectionFilter(const TCPServerConnectionFilter::Ptr& pConnectionFilter)
{
poco_assert (_stopped);
_pConnectionFilter = pConnectionFilter;
}
std::string EVTCPServer::threadName(int pipe_rd_fd)
{
char str[128];
sprintf(str, "%d", pipe_rd_fd);
std::string name("EVTCPServer: ");
name = name + "Listening on:" + str;
return name;
}
std::string EVTCPServer::threadName(const ServerSocket& socket)
{
#if _WIN32_WCE == 0x0800
// Workaround for WEC2013: only the first call to getsockname()
// succeeds. To mitigate the impact of this bug, do not call
// socket.address(), which calls getsockname(), here.
std::string name("EVTCPServer");
#pragma message("Using WEC2013 getsockname() workaround in EVTCPServer::threadName(). Remove when no longer needed.")
#else
std::string name("EVTCPServer: ");
name.append(socket.address().toString());
#endif
return name;
}
AbstractConfiguration& EVTCPServer::appConfig()
{
try
{
return Poco::Util::Application::instance().config();
}
catch (Poco::NullPointerException&)
{
throw Poco::IllegalStateException(
"An application configuration is required to initialize the Poco::Net::SSLManager, "
"but no Poco::Util::Application instance is available."
);
}
}
int EVTCPServer::recvDataOnConnSocket(EVTCPServiceRequest * sr)
{
int ret = 0;
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
int optval = 0;
unsigned int optlen = sizeof(optval);
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
errno = 0;
if (tn->getProcState()) {
EVConnectedStreamSocket * cn = tn->getProcState()->getEVConnSock(sr->sockfd());
if (cn) {
socket_watcher_ptr = cn->getSocketWatcher();
cb_ptr = (strms_io_cb_ptr_type)socket_watcher_ptr->data;
ev_io_stop (this->_loop, socket_watcher_ptr);
}
else {
/*
* ERROR CONDITION:
* DID NOT FIND CONNECTED SOCKET FOR THE GIVEN NUMBER.
*/
EVUpstreamEventNotification * usN = 0;
if ((tn->getProcState()) && tn->srInSession(cb_ptr->sr_num)) {
usN = new EVUpstreamEventNotification(sr->getSRNum(), (sr->getStreamSocket().impl()->sockfd()),
sr->getCBEVIDNum(), -1, EBADF);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
return -1;
}
socket_watcher_ptr = cn->getSocketWatcher();
cn->setTimeOfLastUse();
if ((cn->getState() == EVConnectedStreamSocket::NOT_WAITING) ||
cn->getState() == EVConnectedStreamSocket::WAITING_FOR_WRITE) {
int events = 0;
if (cn->getState() == EVConnectedStreamSocket::WAITING_FOR_WRITE) {
events = EVConnectedStreamSocket::WAITING_FOR_READWRITE;
cn->setState(EVConnectedStreamSocket::WAITING_FOR_READWRITE);
}
else {
events = EVConnectedStreamSocket::WAITING_FOR_READ;
cn->setState(EVConnectedStreamSocket::WAITING_FOR_READ);
}
cb_ptr->sr_num = sr->getSRNum();
cb_ptr->cb_evid_num = sr->getCBEVIDNum();
/* This will invoke the call back EVTCPServer::handleConnSocketReadable. */
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_io_init(socket_watcher_ptr, async_stream_socket_cb_3, cn->getSockfd(), events);
ev_io_start (this->_loop, socket_watcher_ptr);
tn->incrNumCSEvents();
}
}
// TBD TO ADD SOCKET TO TIME OUT MONITORING LIST
return ret;
}
int EVTCPServer::pollSocketForReadOrWrite(EVTCPServiceRequest * sr)
{
//DEBUGPOINT("EVTCPServer::pollSocketForReadOrWrite\n");
int ret = -1;
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
int optval = 0;
unsigned int optlen = sizeof(optval);
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
if ((tn->getProcState()) && tn->srInSession(sr->getSRNum())) {
socket_watcher_ptr = (ev_io*)malloc(sizeof(ev_io));
memset(socket_watcher_ptr,0,sizeof(ev_io));
EVConnectedStreamSocket * connectedSock = new EVConnectedStreamSocket(sr->accSockfd(), sr->getStreamSocket());
// Since this method is for making connection to a given socket address
// There is no need for the address resolution step.
connectedSock->setState(EVConnectedStreamSocket::BEFORE_CONNECT);
connectedSock->setSocketWatcher(socket_watcher_ptr);
connectedSock->setEventLoop(this->_loop);
tn->getProcState()->setEVConnSock(connectedSock);
connectedSock->setTimeOfLastUse();
cb_ptr = (strms_io_cb_ptr_type) malloc(sizeof(strms_io_cb_struct_type));
memset(cb_ptr,0,sizeof(strms_io_cb_struct_type));
cb_ptr->objPtr = this;
cb_ptr->sr_num = sr->getSRNum();
cb_ptr->cb_evid_num = sr->getCBEVIDNum();
cb_ptr->connSocketReadable = &EVTCPServer::handleConnSocketReadReady;
cb_ptr->connSocketWritable = &EVTCPServer::handleConnSocketWriteReady;
cb_ptr->connSocketReadAndWritable = &EVTCPServer::handleConnSocketReadAndWriteReady;
cb_ptr->cn = connectedSock;
cb_ptr->connSocketManaged = sr->getConnSocketManaged();
socket_watcher_ptr->data = (void*)cb_ptr;
int waitfor = 0;
switch (sr->getPollFor()) {
case EVTCPServiceRequest::READ:
waitfor = EV_READ;
break;
case EVTCPServiceRequest::WRITE:
waitfor = EV_WRITE;
break;
case EVTCPServiceRequest::READWRITE:
default:
waitfor = EV_WRITE|EV_READ;
}
ev_io_init(socket_watcher_ptr, async_stream_socket_cb_3, sr->getStreamSocket().impl()->sockfd(), waitfor);
ev_io_start (this->_loop, socket_watcher_ptr);
tn->incrNumCSEvents();
ret = 0;
}
return ret;
}
int EVTCPServer::sendDataOnConnSocket(EVTCPServiceRequest * sr)
{
int ret = 0;
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
int optval = 0;
unsigned int optlen = sizeof(optval);
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
errno = 0;
if (tn->getProcState()) {
EVConnectedStreamSocket * cn = tn->getProcState()->getEVConnSock(sr->sockfd());
if (cn) {
socket_watcher_ptr = cn->getSocketWatcher();
cb_ptr = (strms_io_cb_ptr_type)socket_watcher_ptr->data;
ev_io_stop (this->_loop, socket_watcher_ptr);
}
else {
DEBUGPOINT("THIS CONDITION MUST NEVER HAPPEN SOCK = [%d]\n", tn->getSockfd());
std::abort();
return -1;
}
socket_watcher_ptr = cn->getSocketWatcher();
cn->setTimeOfLastUse();
srComplete(tn);
if ((cn->getState() == EVConnectedStreamSocket::NOT_WAITING) ||
cn->getState() == EVConnectedStreamSocket::WAITING_FOR_READ) {
int events = 0;
if (cn->getState() == EVConnectedStreamSocket::WAITING_FOR_READ) {
events = EVConnectedStreamSocket::WAITING_FOR_READWRITE;
cn->setState(EVConnectedStreamSocket::WAITING_FOR_READWRITE);
}
else {
events = EVConnectedStreamSocket::WAITING_FOR_WRITE;
cn->setState(EVConnectedStreamSocket::WAITING_FOR_WRITE);
}
/* Connected socket writable does not invoke any call back.
* Hence there is no service request number or event number relevant for this
* */
/* This will invoke the call back EVTCPServer::handleConnSocketWriteable. */
ev_io_stop(this->_loop, socket_watcher_ptr);
ev_io_init(socket_watcher_ptr, async_stream_socket_cb_3, cn->getSockfd(), events);
ev_io_start (this->_loop, socket_watcher_ptr);
tn->incrNumCSEvents();
}
}
return ret;
}
void host_resolution(void * ptr)
{
cb_ref_data_ptr_type ref_data = 0;
dns_io_ptr_type dio_ptr = (dns_io_ptr_type)ptr;
errno = 0;
dio_ptr->_out._return_value = getaddrinfo(dio_ptr->_in._host_name,
dio_ptr->_in._serv_name, &dio_ptr->_in._hints, &dio_ptr->_out._result);
/*
DEBUGPOINT("ret = [%d]\n", dio_ptr->_out._return_value);
DEBUGPOINT("hn = [%s]\n", dio_ptr->_in._host_name);
DEBUGPOINT("sn = [%p]\n", dio_ptr->_in._serv_name);
DEBUGPOINT("errno = [%d]\n", errno);
DEBUGPOINT("error = [%s]\n", strerror(errno));
*/
dio_ptr->_out._errno = errno;
ref_data = (cb_ref_data_ptr_type)dio_ptr->_in._ref_data;
ref_data->_instance->postHostResolution(dio_ptr);
return;
}
/* This method will execute in one of the aux worker threads. */
void EVTCPServer::postHostResolution(dns_io_ptr_type dio_ptr)
{
/* This is to make sure that multiple parallel resolution objects
* queue, so that the single event loop thread can handle them one by one.
* */
enqueue(_host_resolve_queue, dio_ptr);
/* Wake the event loop. */
/* This will invoke host_addr_resolved and therefore EVTCPServer::handleHostResolved */
ev_async_send(this->_loop, this->_dns_watcher_ptr);
}
/* Fill in code for this method to pickup the usN object and push a callback event in. */
/* This method will execute in the event loop thread. */
void EVTCPServer::handleHostResolved(const bool& ev_occured)
{
void* pNf = 0;
for (pNf = dequeue(_host_resolve_queue); pNf ; pNf = dequeue(_host_resolve_queue)) {
dns_io_ptr_type dio_ptr = ((dns_io_ptr_type)(pNf));
cb_ref_data_ptr_type ref_data = 0;
ref_data = (cb_ref_data_ptr_type)dio_ptr->_in._ref_data;
EVAcceptedStreamSocket *tn = getTn(ref_data->_acc_fd);
EVUpstreamEventNotification * usN = ref_data->_usN;;
dio_ptr->_in._ref_data = NULL;
usN->setHRRet(dio_ptr->_out._return_value);
usN->setRet(dio_ptr->_out._return_value);
usN->setErrNo(dio_ptr->_out._errno);
usN->setAddrInfo(dio_ptr->_out._result);
tn->decrNumCSEvents();
if ((tn->getProcState()) && tn->srInSession(usN->getSRNum())) {
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
delete usN;
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
delete ref_data;
delete dio_ptr;
}
}
/* Fill in code for this method to trigger a getaddrinfo asynchronously */
int EVTCPServer::resolveHost(EVTCPServiceRequest * sr)
{
dns_io_ptr_type dio_ptr = new dns_io_struct_type();
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
dio_ptr->_in._host_name = sr->getDomainName();
dio_ptr->_in._serv_name = sr->getServName();
//DEBUGPOINT("Here ipv6 = %d\n", _use_ipv6_for_conn);
if (_use_ipv6_for_conn)
dio_ptr->_in._hints.ai_family = PF_UNSPEC;
else
dio_ptr->_in._hints.ai_family = PF_INET;
dio_ptr->_in._hints.ai_socktype = SOCK_STREAM;
dio_ptr->_in._hints.ai_protocol = IPPROTO_TCP;
dio_ptr->_in._hints.ai_flags = AI_DEFAULT;
//dio_ptr->_in._hints.ai_flags = AI_ALL|AI_V4MAPPED;
//dio_ptr->_in._hints.ai_flags = AI_ALL;
cb_ref_data_ptr_type ref_data = new cb_ref_data_type();
ref_data->_usN = new EVUpstreamEventNotification(sr->getSRNum(), sr->getCBEVIDNum());
ref_data->_instance = this;
ref_data->_acc_fd = sr->accSockfd();
dio_ptr->_in._ref_data = ref_data;
enqueue_task(_thread_pool, &(host_resolution), dio_ptr);
tn->incrNumCSEvents();
return 0;
}
/* Fill in code for this method to trigger a getaddrinfo asynchronously */
int EVTCPServer::resolveHost(EVAcceptedStreamSocket* tn, EVTCPServiceRequest* sr)
{
dns_io_ptr_type dio_ptr = new dns_io_struct_type();
dio_ptr->_in._host_name = sr->getDomainName();
dio_ptr->_in._serv_name = sr->getServName();
//DEBUGPOINT("Here ipv6 = %d\n", _use_ipv6_for_conn);
if (_use_ipv6_for_conn)
dio_ptr->_in._hints.ai_family = PF_UNSPEC;
else
dio_ptr->_in._hints.ai_family = PF_INET;
dio_ptr->_in._hints.ai_socktype = SOCK_STREAM;
dio_ptr->_in._hints.ai_protocol = IPPROTO_TCP;
dio_ptr->_in._hints.ai_flags = AI_DEFAULT;
//dio_ptr->_in._hints.ai_flags = AI_ALL|AI_V4MAPPED;
//dio_ptr->_in._hints.ai_flags = AI_ALL;
cb_ref_data_ptr_type ref_data = new cb_ref_data_type();
ref_data->_usN = new EVUpstreamEventNotification(sr->getSRNum(), sr->getCBEVIDNum());
ref_data->_instance = this;
ref_data->_acc_fd = sr->accSockfd();
dio_ptr->_in._ref_data = ref_data;
enqueue_task(_thread_pool, &(host_resolution), dio_ptr);
tn->incrNumCSEvents();
return 0;
}
typedef struct {
int _fd;
int _completed_oper;
} file_evt_s, * file_evt_p;
void EVTCPServer::handleFileEvtOccured(const bool& ev_occured)
{
void* pNf = 0;
for (pNf = dequeue(_file_evt_queue); pNf ; pNf = dequeue(_file_evt_queue)) {
file_evt_p fe_ptr = ((file_evt_p)(pNf));
try {
file_event_status_s& fes = _file_evt_subscriptions.at(fe_ptr->_fd);
EVAcceptedStreamSocket *tn = getTn(fes._acc_fd);
if (!tn) {
DEBUGPOINT("Here tn has become null while task was being processed\n");
return;
}
EVUpstreamEventNotification * usN = fes._usN;;
if (fe_ptr->_completed_oper == FILE_OPER_OPEN) {
errno = 0;
int status = ef_open_status(fe_ptr->_fd);
usN->setErrNo(errno);
usN->setRet(status);
}
else if (fe_ptr->_completed_oper == FILE_OPER_READ) {
int status = ef_file_ready_for_read(fe_ptr->_fd);
//DEBUGPOINT("Here ret = %d errno = %d\n", status, errno);
usN->setErrNo(errno);
usN->setRet(status);
}
else {
DEBUGPOINT("THIS MUST NOT HAPPEN\n");
std::abort();
}
//DEBUGPOINT("Here fd = %d oper = %d\n", fe_ptr->_fd, fe_ptr->_completed_oper);
usN->setFileFd(fe_ptr->_fd);
usN->setFileOper(fe_ptr->_completed_oper);
if ((tn->getProcState()) && tn->srInSession(usN->getSRNum())) {
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
delete usN;
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
tn->decrNumCSEvents();
_file_evt_subscriptions.erase(fe_ptr->_fd);
(tn->getProcState()->getFileEvtSubscriptions()).erase(fe_ptr->_fd);
}
catch (...) {
/* No subcriptions for events of this file. */
}
delete fe_ptr;
}
}
void EVTCPServer::pushFileEvent(int fd, int completed_oper)
{
//DEBUGPOINT("Here\n");
file_evt_p fe_ptr = (file_evt_p)malloc(sizeof(file_evt_s));
/* This is to make sure that multiple parallel file event completions
* queue up, so that the single event loop thread can handle them one by one.
* */
fe_ptr->_fd = fd;
fe_ptr->_completed_oper = completed_oper;
enqueue(_file_evt_queue, fe_ptr);
/* Wake the event loop. */
/* This will invoke file_evt_occured and therefore EVTCPServer::handleFileEvtOccured */
ev_spin_lock(this->_loop_active_spin_lock);
atomic_thread_fence(std::memory_order_acquire);
if (_loop_active) ev_async_send(this->_loop, this->_file_evt_watcher_ptr);
ev_spin_unlock(this->_loop_active_spin_lock);
}
typedef struct {
poco_socket_t _acc_fd;
EVUpstreamEventNotification* _usN;
} tc_enqueued_struct, * tc_enqueued_struct_ptr;
/* This is handling of task completion within the event loop.
* So that the event of task completion can be sent to the
* correct worker thread handling the request.
* */
void EVTCPServer::handleGenericTaskComplete(const bool& ev_occured)
{
//DEBUGPOINT("Here\n");
void* pNf = 0;
for (pNf = dequeue(_aux_tc_queue); pNf ; pNf = dequeue(_aux_tc_queue)) {
tc_enqueued_struct_ptr tc_ptr = ((tc_enqueued_struct_ptr)(pNf));
EVAcceptedStreamSocket *tn = getTn(tc_ptr->_acc_fd);
if (!tn) {
DEBUGPOINT("Here tn has become null while task was being processed\n");
delete tc_ptr;
return;
}
EVUpstreamEventNotification * usN = tc_ptr->_usN;;
if ((tn->getProcState()) && tn->srInSession(usN->getSRNum())) {
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
delete usN;
if (usN->getTaskReturnValue()) { free(usN->getTaskReturnValue()); usN->setTaskReturnValue(NULL); }
DEBUGPOINT("REACHED HERE, WHICH MUST NEVER HAVE HAPPENED\n");
std::abort();
}
tn->decrNumCSEvents();
delete tc_ptr;
}
//DEBUGPOINT("Here\n");
}
void EVTCPServer::postGenericTaskComplete(poco_socket_t acc_fd, EVUpstreamEventNotification *usN)
{
//DEBUGPOINT("Here\n");
tc_enqueued_struct_ptr tc_ptr = (tc_enqueued_struct_ptr)malloc(sizeof(tc_enqueued_struct));
/* This is to make sure that multiple parallel task completion objects
* queue up, so that the single event loop thread can handle them one by one.
* */
tc_ptr->_acc_fd = acc_fd;
tc_ptr->_usN = usN;
//DEBUGPOINT("Here %p\n", tc_ptr->_usN);
//tc_ptr->_usN->debug(__FILE__, __LINE__);
enqueue(_aux_tc_queue, tc_ptr);
/* Wake the event loop. */
/* This will invoke generic_task_complete and therefore EVTCPServer::handleGenericTaskComplete */
ev_async_send(this->_loop, this->_gen_task_compl_watcher_ptr);
//DEBUGPOINT("Here\n");
}
static void post_task_completion(void* return_data, void* ref_data)
{
cb_ref_data_ptr_type ref = (cb_ref_data_ptr_type)ref_data;
if (ref) {
ref->_usN->setTaskReturnValue(return_data);
ref->_usN->setRet(0);
ref->_instance->postGenericTaskComplete(ref->_acc_fd, ref->_usN);
}
else {
/*
* If the task completion is not waited for
* the return data from the task should be NULL.
* */
poco_assert (return_data == NULL);
}
delete ref;
return;
}
/* Fill in code for this method to trigger a getaddrinfo asynchronously */
int EVTCPServer::initiateGenericTask(EVTCPServiceRequest * sr)
{
void* task_input_data = sr->getTaskInputData();
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
cb_ref_data_ptr_type ref_data = new cb_ref_data_type();
ref_data->_usN = new EVUpstreamEventNotification(sr->getSRNum(), sr->getCBEVIDNum());
ref_data->_instance = this;
ref_data->_acc_fd = sr->accSockfd();
enqueue_task_function(_thread_pool, (sr->getTaskFunc()), task_input_data, ref_data, &post_task_completion);
tn->incrNumCSEvents();
//DEBUGPOINT("Here func = %p, notification_func = %p, inp = %p %s\n", sr->getTaskFunc(), &post_task_completion, task_input_data, (char*)task_input_data);
//DEBUGPOINT("Here\n");
return 0;
}
int EVTCPServer::initiateGenericTask(EVAcceptedStreamSocket * tn, EVTCPServiceRequest * sr)
{
void* task_input_data = sr->getTaskInputData();
cb_ref_data_ptr_type ref_data = new cb_ref_data_type();
ref_data->_usN = new EVUpstreamEventNotification(sr->getSRNum(), sr->getCBEVIDNum());
ref_data->_instance = this;
ref_data->_acc_fd = sr->accSockfd();
enqueue_task_function(_thread_pool, (sr->getTaskFunc()), task_input_data, ref_data, &post_task_completion);
tn->incrNumCSEvents();
//DEBUGPOINT("Here func = %p, notification_func = %p, inp = %p %s\n", sr->getTaskFunc(), &post_task_completion, task_input_data, (char*)task_input_data);
//DEBUGPOINT("Here\n");
return 0;
}
int EVTCPServer::initiateGenericTaskNR(EVTCPServiceRequest * sr)
{
void* task_input_data = sr->getTaskInputData();
enqueue_task_function(_thread_pool, (sr->getTaskFunc()), task_input_data, NULL, &post_task_completion);
return 0;
}
int EVTCPServer::makeTCPConnection(EVTCPServiceRequest * sr)
{
int ret = 0;
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
int optval = 0;
unsigned int optlen = sizeof(optval);
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
errno = 0;
try {
sr->getStreamSocket().connectNB(sr->getAddr());
} catch (Exception &e) {
DEBUGPOINT("Exception = %s\n", e.what());
optval = errno;
ret = -1;
}
if (ret < 0) {
DEBUGPOINT("Here from %d\n", tn->getSockfd());
// SO_ERROR probably works only in case of select system call.
// It is not returning the correct errno over here.
//getsockopt(sr->getStreamSocket().impl()->sockfd(), SOL_SOCKET, SO_ERROR, (void*)&optval, &optlen);
/* Enqueue the notification only if the accepted socket is still being processed.
*
* For consideration
* TBD: We may have to further make sure that the service request for which this notification
* is being passed is in the same session as the current state.
* */
if ((tn->getProcState()) && tn->srInSession(sr->getSRNum())) {
EVUpstreamEventNotification * usN = 0;
usN = new EVUpstreamEventNotification(sr->getSRNum(), (sr->getStreamSocket().impl()->sockfd()),
sr->getCBEVIDNum(), ret, optval);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
DEBUGPOINT("IS THIS AN IMPOSSIBLE CONDITION for %d\n", tn->getSockfd());
std::abort();
}
return ret;
}
socket_watcher_ptr = (ev_io*)malloc(sizeof(ev_io));
memset(socket_watcher_ptr,0,sizeof(ev_io));
EVConnectedStreamSocket * connectedSock = new EVConnectedStreamSocket(sr->accSockfd(), sr->getStreamSocket());
// Since this method is for making connection to a given socket address
// There is no need for the address resolution step.
connectedSock->setState(EVConnectedStreamSocket::BEFORE_CONNECT);
connectedSock->setSocketWatcher(socket_watcher_ptr);
connectedSock->setEventLoop(this->_loop);
tn->getProcState()->setEVConnSock(connectedSock);
connectedSock->setTimeOfLastUse();
cb_ptr = (strms_io_cb_ptr_type) malloc(sizeof(strms_io_cb_struct_type));
memset(cb_ptr,0,sizeof(strms_io_cb_struct_type));
cb_ptr->objPtr = this;
cb_ptr->sr_num = sr->getSRNum();
cb_ptr->cb_evid_num = sr->getCBEVIDNum();
cb_ptr->connSocketReadable = &EVTCPServer::handleConnSocketReadable;
cb_ptr->connSocketWritable = &EVTCPServer::handleConnSocketWriteable;
cb_ptr->cn = connectedSock;
socket_watcher_ptr->data = (void*)cb_ptr;
ev_io_init(socket_watcher_ptr, async_stream_socket_cb_3, sr->getStreamSocket().impl()->sockfd(), EV_WRITE);
ev_io_start (this->_loop, socket_watcher_ptr);
tn->incrNumCSEvents();
return ret;
}
int EVTCPServer::closeTCPConnection(EVTCPServiceRequest * sr)
{
int ret = 0;
ev_io * socket_watcher_ptr = 0;
strms_io_cb_ptr_type cb_ptr = 0;
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
if (tn->getProcState()) {
EVConnectedStreamSocket * cn = tn->getProcState()->getEVConnSock(sr->sockfd());
if (cn) {
socket_watcher_ptr = cn->getSocketWatcher();
ev_io_stop (this->_loop, socket_watcher_ptr); }
errno = 0;
ret = 0;
try {
sr->getStreamSocket().close();
} catch (Exception &e) {
ret = -1;
}
tn->getProcState()->eraseEVConnSock(sr->accSockfd());
}
/* We do not enqueue upstream notification for socket closure.
* Neither do we check for accepted socket being busy etc.
*
* The assumption is that the caller is not really interested in
* result of the closure operation.
* */
int fd = sr->getStreamSocket().impl()->sockfd();
return ret;
}
int EVTCPServer::pollFileOpenEvent(EVTCPServiceRequest * sr)
{
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
errno = 0;
if ((tn->getProcState()) && tn->srInSession(sr->getSRNum())) {
//DEBUGPOINT("Here\n");
EVUpstreamEventNotification * usN = 0;
usN = new EVUpstreamEventNotification(sr->getSRNum(), sr->getCBEVIDNum());
usN->setFileFd(sr->getFileFd());
usN->setFileOper(FILE_OPER_OPEN);
FileEvtSubscrMap::iterator it = _file_evt_subscriptions.find(sr->getFileFd());
if (_file_evt_subscriptions.end() != it) {
//DEBUGPOINT("Here\n");
usN->setErrNo(EBUSY);
usN->setRet(-1);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
int ret = ef_open_status(sr->getFileFd());
if (ret == -1) {
//DEBUGPOINT("Here\n");
if (errno == EAGAIN) {
//DEBUGPOINT("Here %d\n", ret);
file_event_status_s fes;
fes._usN = usN;
fes._acc_fd = sr->accSockfd();
_file_evt_subscriptions[sr->getFileFd()] = fes;
(tn->getProcState()->getFileEvtSubscriptions())[sr->getFileFd()] = sr->getFileFd();
tn->incrNumCSEvents();
}
else {
//DEBUGPOINT("Here %d\n", ret);
usN->setErrNo(errno);
usN->setRet(ret);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
}
else {
//DEBUGPOINT("Here %d errno %d\n", ret, errno);
usN->setErrNo(0);
usN->setRet(ret);
usN->setFileFd(sr->getFileFd());
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
}
}
return 0;
}
int EVTCPServer::pollFileReadEvent(EVTCPServiceRequest * sr)
{
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
if ((tn->getProcState()) && tn->srInSession(sr->getSRNum())) {
//DEBUGPOINT("Here\n");
EVUpstreamEventNotification * usN = 0;
usN = new EVUpstreamEventNotification(sr->getSRNum(), sr->getCBEVIDNum());
usN->setFileFd(sr->getFileFd());
usN->setFileOper(FILE_OPER_READ);
FileEvtSubscrMap::iterator it = _file_evt_subscriptions.find(sr->getFileFd());
if (_file_evt_subscriptions.end() != it) {
//DEBUGPOINT("Here\n");
usN->setErrNo(EBUSY);
usN->setRet(-1);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
errno = 0;
int ret = ef_file_ready_for_read(sr->getFileFd());
if (ret < 0) {
//DEBUGPOINT("Here ret = %d errno = %d\n", ret, errno);
if (errno == EAGAIN) {
//DEBUGPOINT("Here ret = %d errno = %d\n", ret, errno);
file_event_status_s fes;
fes._usN = usN;
fes._acc_fd = sr->accSockfd();
_file_evt_subscriptions[sr->getFileFd()] = fes;
(tn->getProcState()->getFileEvtSubscriptions())[sr->getFileFd()] = sr->getFileFd();
tn->incrNumCSEvents();
}
else {
//DEBUGPOINT("Here ret = %d errno = %d\n", ret, errno);
usN->setErrNo(errno);
usN->setRet(ret);
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
}
else {
//DEBUGPOINT("Here ret = %d errno = %d\n", ret, errno);
usN->setErrNo(0);
usN->setRet(ret); /* >0 means data available, 0 means EOF */
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
}
}
return 0;
}
void EVTCPServer::handleServiceRequest(const bool& ev_occured)
{
AutoPtr<Notification> pNf = 0;
for (pNf = _service_request_queue.dequeueNotification(); pNf ; pNf = _service_request_queue.dequeueNotification()) {
EVTCPServiceRequest * srNF = dynamic_cast<EVTCPServiceRequest*>(pNf.get());
EVTCPServiceRequest::what event = srNF->getEvent();
EVAcceptedStreamSocket *tn = getTn(srNF->accSockfd());
if (!tn) {
/* This should never happen. */
DEBUGPOINT("Did not find entry in _accssColl for [%d][%d] for event = [%d]\n",
srNF->sockfd(), srNF->accSockfd(), event);
/* Multiple events can get queued for a socket from another thread.
* In the meanwhile, it is possible that the socket gets into an error state
* due to various conditions, one such is wrong data format and the protocol
* handler fails. This condition will lead to socket getting closed.
* Subsequent events after closing of the socket must be ignored.
* */
// TBD Handle sending of error event here. TBD
continue;
}
if (!(tn->getProcState()) || !(tn->srInSession(srNF->getSRNum()))) {
DEBUGPOINT("Here DEAD REQUEST %d\n", srNF->getEvent());
continue;
}
switch (event) {
case EVTCPServiceRequest::HOST_RESOLUTION:
//DEBUGPOINT("HOST_RESOLUTION from %d\n", tn->getSockfd());
resolveHost(srNF);
break;
case EVTCPServiceRequest::POLL_REQUEST:
//DEBUGPOINT("POLL_REQUEST from %d\n", tn->getSockfd());
pollSocketForReadOrWrite(srNF);
break;
case EVTCPServiceRequest::CONNECTION_REQUEST:
//DEBUGPOINT("CONNECTION_REQUEST from %d\n", tn->getSockfd());
makeTCPConnection(srNF);
break;
case EVTCPServiceRequest::CLEANUP_REQUEST:
//DEBUGPOINT("CLEANUP_REQUEST from %d\n", tn->getSockfd());
closeTCPConnection(srNF);
break;
case EVTCPServiceRequest::SENDDATA_REQUEST:
//DEBUGPOINT("SENDDATA_REQUEST from %d\n", tn->getSockfd());
sendDataOnConnSocket(srNF);
break;
case EVTCPServiceRequest::RECVDATA_REQUEST:
//DEBUGPOINT("RECVDATA_REQUEST from %d\n", tn->getSockfd());
recvDataOnConnSocket(srNF);
break;
case EVTCPServiceRequest::GENERIC_TASK:
//DEBUGPOINT("GENERIC_TASK from %d\n", tn->getSockfd());
initiateGenericTask(srNF);
break;
case EVTCPServiceRequest::GENERIC_TASK_NR:
//DEBUGPOINT("GENERIC_TASK_NR from %d\n", tn->getSockfd());
initiateGenericTaskNR(srNF);
break;
case EVTCPServiceRequest::FILEOPEN_NOTIFICATION:
//DEBUGPOINT("FILEOPEN_NOTIFICATION from %d\n", tn->getSockfd());
pollFileOpenEvent(srNF);
break;
case EVTCPServiceRequest::FILEREAD_NOTIFICATION:
//DEBUGPOINT("FILEREAD_NOTIFICATION from %d\n", tn->getSockfd());
pollFileReadEvent(srNF);
break;
case EVTCPServiceRequest::INITIATE_REDIS_CONNECTION:
//DEBUGPOINT("INITIATE_REDIS_CONNECTION from %d\n", tn->getSockfd());
break;
case EVTCPServiceRequest::TRANSCEIVE_REDIS_COMMAND:
//DEBUGPOINT("TRANSCEIVE_REDIS_COMMAND from %d\n", tn->getSockfd());
addRedisSocketToPoll(srNF);
break;
case EVTCPServiceRequest::CLOSE_REDIS_CONNECTION:
//DEBUGPOINT("CLOSE_REDIS_CONNECTION from %d\n", tn->getSockfd());
closeRedisConnection(srNF);
break;
default:
//DEBUGPOINT("INVALID EVENT %d from %d\n", event, tn->getSockfd());
std::abort();
break;
}
srNF = NULL;
}
return;
}
void EVTCPServer::justEnqueue(EVAcceptedStreamSocket* tn)
{
tn->setSockBusy();
_pDispatcher->enqueue(tn);
}
void EVTCPServer::srCompleteEnqueue(EVAcceptedStreamSocket* tn)
{
//DEBUGPOINT("DECREMENTING FOR [%d]\n", tn->getSockfd());
//tn->newdecrNumCSEvents();
if (!tn->sockInError()) {
tn->setSockBusy();
_pDispatcher->enqueue(tn);
}
else {
errorInAuxProcesing(tn->getSockfd(), true);
}
}
void EVTCPServer::srComplete(EVAcceptedStreamSocket* tn)
{
//DEBUGPOINT("DECREMENTING FOR [%d]\n", tn->getSockfd());
tn->newdecrNumCSEvents();
}
void EVTCPServer::enqueueSR(EVAcceptedSocket * en, EVTCPServiceRequest * sr)
{
//DEBUGPOINT("ENQUEUEING FOR %d\n", en->getSockfd());
en->newincrNumCSEvents();
_service_request_queue.enqueueNotification(sr);
return ;
}
long EVTCPServer::submitRequestForRecvData(int cb_evid_num, EVAcceptedSocket *en, Net::StreamSocket& css)
{
long sr_num = getNextSRSrlNum();
/* Enque the socket */
enqueueSR(en, new EVTCPServiceRequest(sr_num, cb_evid_num,
EVTCPServiceRequest::RECVDATA_REQUEST, en->getSockfd(), css));
/* And then wake up the loop calls process_service_request */
ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest */
return sr_num;
}
long EVTCPServer::submitRequestForSendData(EVAcceptedSocket *en, Net::StreamSocket& css)
{
long sr_num = getNextSRSrlNum();
/* Enque the socket */
enqueueSR(en, new EVTCPServiceRequest(sr_num, EVTCPServiceRequest::SENDDATA_REQUEST, en->getSockfd(), css));
/* And then wake up the loop calls process_service_request */
ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest */
return sr_num;
}
long EVTCPServer::submitRequestForHostResolution(int cb_evid_num, EVAcceptedSocket *en, const char* domain_name, const char* serv_name)
{
long sr_num = getNextSRSrlNum();
EVTCPServiceRequest sr(sr_num, cb_evid_num,
EVTCPServiceRequest::HOST_RESOLUTION, en->getSockfd(), domain_name, serv_name);
en->newincrNumCSEvents();
resolveHost((EVAcceptedStreamSocket*)en, &sr);
return sr_num;
}
//long EVTCPServer::submitRequestForHostResolution(int cb_evid_num, EVAcceptedSocket *en, const char* domain_name, const char* serv_name)
//{
//long sr_num = getNextSRSrlNum();
/* Enque the socket */
//enqueueSR(en, new EVTCPServiceRequest(sr_num, cb_evid_num,
//EVTCPServiceRequest::HOST_RESOLUTION, en->getSockfd(), domain_name, serv_name));
/* And then wake up the loop calls process_service_request */
//ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest */
//return sr_num;
//}
long EVTCPServer::submitRequestForConnection(int cb_evid_num, EVAcceptedSocket *en, Net::SocketAddress& addr, Net::StreamSocket& css)
{
long sr_num = getNextSRSrlNum();
/* Enque the socket */
enqueueSR(en, new EVTCPServiceRequest(sr_num, cb_evid_num,
EVTCPServiceRequest::CONNECTION_REQUEST, en->getSockfd(), css, addr));
/* And then wake up the loop calls process_service_request */
ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest */
return sr_num;
}
long EVTCPServer::submitRequestForPoll(int cb_evid_num, EVAcceptedSocket *en, Net::StreamSocket& css, int poll_for, int managed)
{
long sr_num = getNextSRSrlNum();
/* Enque the socket */
//DEBUGPOINT("sr_num = [%d]:[%ld][%d][%d]\n", css.impl()->sockfd(), sr_num, poll_for, managed);
EVTCPServiceRequest *sr = new EVTCPServiceRequest(sr_num, cb_evid_num,
EVTCPServiceRequest::POLL_REQUEST, en->getSockfd(), css);
sr->setPollFor(poll_for);
sr->setConnSocketManaged(managed);
enqueueSR(en, sr);
/* And then wake up the loop calls process_service_request */
ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest */
return sr_num;
}
long EVTCPServer::submitRequestForClose(EVAcceptedSocket *en, Net::StreamSocket& css)
{
long sr_num = getNextSRSrlNum();
/* Enque the socket */
enqueueSR(en, new EVTCPServiceRequest(sr_num, EVTCPServiceRequest::CLEANUP_REQUEST, en->getSockfd(), css));
/* And then wake up the loop calls process_service_request */
ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest */
return sr_num;
}
/* TBD
* Consider implementing execution of generic task without waking up the event listener thread 2 times.
* The task can be initiated in the worker thread itself and upon completion, the completion handler can
* wake up the event listener to submit the event back to the worker thread.
* This however can violate certain safety conditions.
* It requires to be thoughroughly checked and designed before implementation.
* */
long EVTCPServer::submitRequestForTaskExecution(int cb_evid_num,
EVAcceptedSocket *en, generic_task_handler_t tf, void* input_data)
{
long sr_num = getNextSRSrlNum();
EVTCPServiceRequest sr(sr_num, cb_evid_num,
EVTCPServiceRequest::GENERIC_TASK, en->getSockfd(), tf, input_data);
en->newincrNumCSEvents();
initiateGenericTask((EVAcceptedStreamSocket*)en, &sr);
return sr_num;
}
//long EVTCPServer::submitRequestForTaskExecution(int cb_evid_num,
//EVAcceptedSocket *en, generic_task_handler_t tf, void* input_data)
//{
//long sr_num = getNextSRSrlNum();
/* Enque the socket */
//DEBUGPOINT("Here loop = %p, sw = %p on socket %d\n", this->_loop, this->_stop_watcher_ptr2, en->getSockfd());
//enqueueSR(en, new EVTCPServiceRequest(sr_num, cb_evid_num,
//EVTCPServiceRequest::GENERIC_TASK, en->getSockfd(), tf, input_data));
/* And then wake up the loop calls process_service_request */
//ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest */
//return sr_num;
//}
long EVTCPServer::submitRequestForTaskExecutionNR(generic_task_handler_nr_t tf, void* input_data)
{
long sr_num = getNextSRSrlNum();
//DEBUGPOINT("Here %p\n", tf);
//DEBUGPOINT("Here %p\n", input_data);
enqueue_task(_thread_pool, tf, input_data);
return sr_num;
}
long EVTCPServer::notifyOnFileOpen(int cb_evid_num, EVAcceptedSocket *en, int fd)
{
long sr_num = getNextSRSrlNum();
/* Enque the socket */
enqueueSR(en, new EVTCPServiceRequest(sr_num, cb_evid_num,
EVTCPServiceRequest::FILEOPEN_NOTIFICATION, en->getSockfd(), fd));
/* And then wake up the loop calls process_service_request */
ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest */
return sr_num;
}
long EVTCPServer::notifyOnFileRead(int cb_evid_num, EVAcceptedSocket *en, int fd)
{
long sr_num = getNextSRSrlNum();
/* Enque the socket */
enqueueSR(en, new EVTCPServiceRequest(sr_num, cb_evid_num,
EVTCPServiceRequest::FILEREAD_NOTIFICATION, en->getSockfd(), fd));
/* And then wake up the loop calls process_service_request */
ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest */
return sr_num;
}
/*
* REDIS INTERFACE RELATED FUNCTIONS
*/
typedef void (EVTCPServer::*transceive_complete_handler)(struct redis_call_related_data *);
struct redis_call_related_data {
redisAsyncContext *ac;
const char * message;
EVTCPServer * server_ptr;
redisReply * reply;
long sr_num;
int cb_evid_num;
int acc_fd;
transceive_complete_handler handle_redis_transceive_complete;
};
void EVTCPServer::handle_redis_transceive_complete(struct redis_call_related_data * redis_data_ptr)
{
EVAcceptedStreamSocket *tn = getTn(redis_data_ptr->acc_fd);
if (!tn) {
DEBUGPOINT("REACHED HERE, WHICH MUST NEVER HAVE HAPPENED\n");
free(redis_data_ptr);
std::abort();
return;
}
EVUpstreamEventNotification * usN =
new EVUpstreamEventNotification(redis_data_ptr->sr_num, redis_data_ptr->cb_evid_num);
usN->setTaskReturnValue(redis_data_ptr->reply);
if ((tn->getProcState()) && tn->srInSession(usN->getSRNum())) {
enqueue(tn->getUpstreamIoEventQueue(), (void*)usN);
tn->newdecrNumCSEvents();
if (!(tn->sockBusy())) {
//tn->setSockBusy();
//_pDispatcher->enqueue(tn);
srCompleteEnqueue(tn);
}
else {
tn->setWaitingTobeEnqueued(true);
}
}
else {
delete usN;
free(redis_data_ptr);
DEBUGPOINT("REACHED HERE, WHICH MUST NEVER HAVE HAPPENED\n");
std::abort();
return;
}
tn->decrNumCSEvents();
free(redis_data_ptr);
return;
}
static void redis_callback(redisAsyncContext *ac, void * r, void * private_data)
{
struct redis_call_related_data * redis_data_ptr = (struct redis_call_related_data *)private_data;
redis_data_ptr->reply = (redisReply *)r;
((redis_data_ptr->server_ptr)->*(redis_data_ptr->handle_redis_transceive_complete))(redis_data_ptr);
return;
}
int EVTCPServer::addRedisSocketToPoll(EVTCPServiceRequest * sr)
{
struct redis_call_related_data * redis_data_ptr ;
redis_data_ptr = (struct redis_call_related_data *)sr->getTaskInputData();
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
redis_data_ptr->server_ptr = this;
redis_data_ptr->handle_redis_transceive_complete = &EVTCPServer::handle_redis_transceive_complete;
redis_data_ptr->sr_num = sr->getSRNum();
redis_data_ptr->cb_evid_num = sr->getCBEVIDNum();
redis_data_ptr->acc_fd = sr->accSockfd();
redisAsyncCommand(redis_data_ptr->ac, redis_callback, (void*)redis_data_ptr, redis_data_ptr->message);
tn->incrNumCSEvents();
return 0;
}
long EVTCPServer::redistransceive(int cb_evid_num, EVAcceptedSocket *en, redisAsyncContext *ac, const char * message)
{
long sr_num = getNextSRSrlNum();
struct redis_call_related_data *redis_data_ptr = (struct redis_call_related_data*)malloc(sizeof(struct redis_call_related_data));
redis_data_ptr->ac = ac;
redis_data_ptr->message = message;
redis_data_ptr->server_ptr = NULL;
/* Enque the socket */
enqueueSR(en, new EVTCPServiceRequest(sr_num, cb_evid_num,
EVTCPServiceRequest::TRANSCEIVE_REDIS_COMMAND, en->getSockfd(), (void*)redis_data_ptr));
/* And then wake up the loop calls process_service_request */
ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest
* and addRedisSocketToPoll */
return sr_num;
}
int EVTCPServer::closeRedisConnection(EVTCPServiceRequest * sr)
{
struct redis_call_related_data * redis_data_ptr ;
redis_data_ptr = (struct redis_call_related_data *)sr->getTaskInputData();
EVAcceptedStreamSocket *tn = getTn(sr->accSockfd());
redisAsyncDisconnect(redis_data_ptr->ac);
free(redis_data_ptr);
tn->newdecrNumCSEvents();
return 0;
}
long EVTCPServer::redisDisconnect(int cb_evid_num, EVAcceptedSocket *en, redisAsyncContext *ac)
{
long sr_num = getNextSRSrlNum();
struct redis_call_related_data *redis_data_ptr = (struct redis_call_related_data*)malloc(sizeof(struct redis_call_related_data));
redis_data_ptr->ac = ac;
redis_data_ptr->message = NULL;
redis_data_ptr->server_ptr = NULL;
/* Enque the socket */
enqueueSR(en, new EVTCPServiceRequest(sr_num, cb_evid_num,
EVTCPServiceRequest::CLOSE_REDIS_CONNECTION, en->getSockfd(), (void*)redis_data_ptr));
/* And then wake up the loop calls process_service_request */
ev_async_send(this->_loop, this->_stop_watcher_ptr2);
/* This will result in invocation of handleServiceRequest
* and closeRedisConnection */
return 0;
}
void EVTCPServer::redisLibevAttach(redisAsyncContext *ac)
{
//DEBUGPOINT("BEGIN OF THE ENTIRE SAGA\n");
::redisLibevAttach(this->_loop, ac);
return;
}
} } // namespace Poco::evnet
|
YoufuLi/radlog
|
datalog/src/main/java/edu/ucla/cs/wis/bigdatalog/database/store/bplustree/BPlusTree.java
|
<filename>datalog/src/main/java/edu/ucla/cs/wis/bigdatalog/database/store/bplustree/BPlusTree.java
package edu.ucla.cs.wis.bigdatalog.database.store.bplustree;
import edu.ucla.cs.wis.bigdatalog.measurement.MemoryMeasurement;
public interface BPlusTree {
public int getNumberOfEntries();
public MemoryMeasurement getSizeOf();
public String toString();
public String toStringShort();
public void deleteAll();
public BPlusTreeLeaf<?> getFirstChild();
}
|
silver-snoopy/material-ui
|
packages/material-ui-icons/src/WbShade.js
|
<reponame>silver-snoopy/material-ui
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M14 12v2.5l5.5 5.5H22zm0 8h3l-3-3zM8 4l-6 6h2v10h8V10h2L8 4zm1 10H7v-4h2v4z" />
, 'WbShade');
|
leapframework/framework
|
web/core/src/main/java/leap/web/format/HtmlFormat.java
|
<filename>web/core/src/main/java/leap/web/format/HtmlFormat.java
/*
* Copyright 2014 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
*
* 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 leap.web.format;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import leap.lang.Strings;
import leap.lang.convert.Converts;
import leap.lang.http.MimeTypes;
import leap.web.Content;
import leap.web.Contents;
import leap.web.action.ActionContext;
public class HtmlFormat extends AbstractResponseFormat {
public HtmlFormat() {
super(MimeTypes.TEXT_HTML_TYPE);
}
@Override
public Content getContent(ActionContext context, Object value) throws Exception {
String html;
if(null == value){
html = Strings.EMPTY;
}else{
html = Converts.toString(value);
}
return Contents.html(html);
}
}
|
EricCharnesky/CIS2001-Winter2021
|
Project2/TransportMethod.py
|
class TransportMethod:
def __init__(self, number, number_of_items_until_full, load_time_multiple=1):
self.number = number
self.number_of_items_until_full = number_of_items_until_full
self.time_until_full = 0
self.current_number_of_items = 0
self.load_time_multiple = load_time_multiple
def load_item(self, current_time_elapsed):
self.current_number_of_items += 1
current_time_elapsed += self.number * self.load_time_multiple
if self.current_number_of_items == self.number_of_items_until_full:
self.time_until_full = current_time_elapsed
return current_time_elapsed + self.number * self.load_time_multiple
|
ferhatelmas/algo
|
leetCode/algorithms/medium/random_pick_index.py
|
<reponame>ferhatelmas/algo
import random
class Solution(object):
def __init__(self, nums):
self.nums = nums
def pick(self, target):
r, c = -1, 0
for i, e in enumerate(self.nums):
if e == target:
if random.randint(0, c) == 0:
r = i
c += 1
return r
|
Martin-Seysen/mmgroup
|
src/mmgroup/generate_c/testcode.py
|
<filename>src/mmgroup/generate_c/testcode.py
from generate_functions import UserDirective
from make_c_tables import TableGenerator
class TestGen:
def add_to(x, expr):
return "{x} = {x} + {expr};\n".format(x = x, expr = str(expr))
functions = {
"AddTo": UserDirective(add_to, "si"),
}
tables = {
"y" : [1,2,3],
"TABLE_SIZE": 32,
"mult": 17,
"pair_list": list(zip(range(3), [7,4,9])),
}
def generate():
T = TestGen
tg = TableGenerator(T.tables, T.functions, verbose = 1)
tg.generate("testcode.ske", "test.c", "test.h")
print("Table in test code:")
print( tg.names )
if __name__ == "__main__":
generate()
|
RIPBackdoored/Backdoored-1.7-Deobf-Source-Leak
|
backdoored/client/i/j/c/q.java
|
package l.c.i.j.c;
import l.c.i.d.a;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderManager;
public class q extends a {
public static final int qtj;
public static final boolean qtc;
public q() {
super("Player Preview Element");
}
public void k(int var1, int var2, float var3) {
this.g().fqs = 25;
this.g().fqm = 25;
super.k(var1, var2, var3);
if (this.ey()) {
EntityPlayerSP var4 = mc.player;
GlStateManager.pushMatrix();
GlStateManager.color(1.0F, 1.0F, 1.0F);
RenderHelper.enableStandardItemLighting();
GlStateManager.enableAlpha();
GlStateManager.shadeModel(7424);
GlStateManager.enableAlpha();
GlStateManager.enableDepth();
GlStateManager.rotate(0.0F, 0.0F, 5.0F, 0.0F);
GlStateManager.enableColorMaterial();
GlStateManager.pushMatrix();
GlStateManager.translate((float)this.a().fqs + (float)this.g().fqs, (float)this.a().fqm + (float)this.g().fqm, 50.0F);
GlStateManager.scale(-50.0F, 50.0F, 50.0F);
GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F);
GlStateManager.rotate(135.0F, 0.0F, 1.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GlStateManager.rotate(-135.0F, 0.0F, 1.0F, 0.0F);
GlStateManager.rotate(-((float)Math.atan((double)((float)this.a().fqm / 40.0F))) * 20.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.translate(0.0F, 0.0F, 0.0F);
RenderManager var5 = Minecraft.getMinecraft().getRenderManager();
var5.setPlayerViewY(180.0F);
var5.setRenderShadow(false);
var5.renderEntity(var4, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F, false);
var5.setRenderShadow(true);
GlStateManager.popMatrix();
GlStateManager.disableRescaleNormal();
GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GlStateManager.disableTexture2D();
GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit);
GlStateManager.depthFunc(515);
GlStateManager.resetColor();
GlStateManager.disableDepth();
GlStateManager.popMatrix();
}
}
}
|
itfuyun/learning-examples
|
common-example/src/main/java/org/example/common/handler/GlobalExceptionHandler.java
|
<gh_stars>1-10
package org.example.common.handler;
import org.example.common.exception.BusinessException;
import org.example.common.response.ResultEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @author <a href="mailto:<EMAIL>">Tanxh</a>
* @since 1.0
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 校验参数异常统一处理
*
* @param e
* @return 没有@RequestBody时候抛出此异常 后端接收为表单提交形式的参数时
* https://github.com/spring-projects/spring-framework/issues/14790
*/
@ExceptionHandler(BindException.class)
public Object handleException(BindException e) {
//获取校验结果
BindingResult bindingResult = e.getBindingResult();
StringBuilder stringBuilder = new StringBuilder();
for (FieldError error : bindingResult.getFieldErrors()) {
String field = error.getField();
Object value = error.getRejectedValue();
String msg = error.getDefaultMessage();
String message = String.format("错误字段:%s,错误值:%s,原因:%s;", field, value, msg);
stringBuilder.append(message).append("\r\n");
}
return ResultEntity.failed(stringBuilder.toString());
}
/**
* 校验参数异常统一处理
*
* @param e
* @return
* @RequestBody 时候抛出此异常 后端接收为json形式的参数时
* https://github.com/spring-projects/spring-framework/issues/14790
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleException(MethodArgumentNotValidException e) {
//获取校验结果
BindingResult bindingResult = e.getBindingResult();
StringBuilder stringBuilder = new StringBuilder();
for (FieldError error : bindingResult.getFieldErrors()) {
String field = error.getField();
Object value = error.getRejectedValue();
String msg = error.getDefaultMessage();
String message = String.format("错误字段:%s,错误值:%s,原因:%s;", field, value, msg);
stringBuilder.append(message).append("\r\n");
}
return ResultEntity.failed(stringBuilder.toString());
}
/**
* 业务处理
*
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
public Object handleException(BusinessException e) {
//返回错误信息
return ResultEntity.failed(e.getCode(), e.getMsg());
}
/**
* 其他异常处理
*
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public Object handleException(Exception e) {
//返回错误信息
return ResultEntity.failed(e.getMessage());
}
}
|
siaomingjeng/konga-test
|
assets/js/app/core/layout/03_layout-services.js
|
/**
* This file contains all necessary Angular service definitions for 'frontend.core.layout' module.
*
* Note that this file should only contain services and nothing else.
*/
(function() {
'use strict';
// Generic service to return all available menu items for main level navigation.
angular.module('frontend.core.layout')
.factory('HeaderNavigationItems', [
'AccessLevels','AuthService','$rootScope','UserService',
function factory(AccessLevels,AuthService,$rootScope,UserService) {
return [
{
state: 'dashboard',
icon : 'mdi-view-dashboard',
show : function() {
return AuthService.isAuthenticated()
},
title: 'Dashboard',
access: AccessLevels.user
},
{
state: 'apis',
show : function() {
return AuthService.isAuthenticated() && $rootScope.Gateway
},
title: 'APIs',
icon : 'mdi-cloud-outline',
access: AccessLevels.user
},
{
state: 'consumers',
show : function() {
return AuthService.isAuthenticated() && $rootScope.Gateway
},
title: 'Consumers',
icon : 'mdi-account-outline',
access: AccessLevels.user
},
{
state: 'plugins',
icon : 'mdi-power-plug',
show : function() {
return AuthService.isAuthenticated() && $rootScope.Gateway
},
title: 'Plugins',
access: AccessLevels.anon
},
{
state: 'upstreams',
icon : 'mdi-shuffle-variant',
show : function() {
return AuthService.isAuthenticated() && UserService.user().node && $rootScope.Gateway && $rootScope.Gateway.version.indexOf("0.10.") > -1
},
title: 'Upstreams',
access: AccessLevels.anon
},
{
state: 'certificates',
icon : 'mdi-certificate',
show : function() {
return AuthService.isAuthenticated() && UserService.user().node && $rootScope.Gateway && $rootScope.Gateway.version.indexOf("0.10.") > -1
},
title: 'Certificates',
access: AccessLevels.anon
}
];
}
])
;
}());
|
MrDDaye/cna_cp1855
|
final/final_part2/operations.py
|
"""Operations team manager program."""
from cli import display_lineup_header, display_player, display_player_position, display_player_stats, display_farewell, display_player_updated
from inputs import get_lineup_number, get_string, get_position, get_int
from baseball_stats import batting_average
from files import read_from_file, save_to_file
def display_lineup(players: list[list[str]]) -> None:
"""Displays the lineup of the baseball team."""
display_lineup_header()
for index, player in enumerate(players):
display_player(index + 1, player)
def add_player(players: list[list[str]], players_file: str) -> None:
"""Prompts user for new player information and adds it to team lineup."""
name: str = get_string('Name: ')
position: str = get_position('Position: ')
at_bats: int = get_int('At bats: ')
hits: int = get_int('Hits: ')
average: float = batting_average(at_bats, hits)
players.append([name, position, at_bats, hits, average])
save_players_to_file(players_file, players)
print(f'{name} was added.')
def remove_player(players: list[list[str]], players_file: str) -> None:
"""Prompts user for lineup number and remove player from team lineup."""
lineup_index: int = get_lineup_number('Lineup number: ', players) - 1
removed_player: list[str] = players.pop(lineup_index)
save_players_to_file(players_file, players)
print(f'{removed_player[0]} was removed.')
def move_player(players: list[list[str]], players_file: str) -> None:
"""Prompts user for lineup number and desired new lineup number. Moves player to new lineup position."""
lineup_index: int = get_lineup_number('Current lineup number: ', players) - 1
moved_player: list[str] = players.pop(lineup_index)
print(f'{moved_player[0]} was selected.')
lineup_index: int = get_lineup_number('New lineup number: ', players) - 1
players.insert(lineup_index, moved_player)
save_players_to_file(players_file, players)
print(f'{moved_player[0]} was moved.')
def edit_player_position(players: list[list[str]], players_file: str) -> None:
"""Prompts user for lineup number and allows user to edit selected players position."""
lineup_index: int = get_lineup_number('Lineup number: ', players) - 1
selected_player: list[str] = players[lineup_index]
display_player_position(selected_player)
selected_player[1] = get_position('New position: ')
save_players_to_file(players_file, players)
display_player_updated(selected_player)
def edit_player_stats(players: list[list[str]], players_file: str) -> None:
"""Prompts user for lineup number and allows user to edit selected players statistics."""
lineup_index: int = get_lineup_number('Lineup number: ', players) - 1
selected_player: list[str] = players[lineup_index]
display_player_stats(selected_player)
selected_player[2] = get_int('At bats: ')
selected_player[3] = get_int('Hits: ')
selected_player[4] = batting_average(selected_player[2], selected_player[3])
save_players_to_file(players_file, players)
display_player_updated(selected_player)
def finish(players: list[list[str]], players_file: str) -> None:
"""Close the program."""
save_players_to_file(players_file, players)
display_farewell()
quit()
def read_players_from_file(file: str) -> None:
players = read_from_file(file)
for player in players:
player[2] = int(player[2])
player[3] = int(player[3])
player[4] = float(player[4])
return players
def save_players_to_file(file: str, players: list[list[str]]) -> None:
save_to_file(file, players)
def run_option(option: int, players: list[list[str]], players_file: str) -> None:
"""Run the function specified by option."""
if option == 1:
display_lineup(players)
elif option == 2:
add_player(players, players_file)
elif option == 3:
remove_player(players, players_file)
elif option == 4:
move_player(players, players_file)
elif option == 5:
edit_player_position(players, players_file)
elif option == 6:
edit_player_stats(players, players_file)
else:
finish(players, players_file)
|
zhanghqgit/joyrpc
|
joyrpc-core/src/main/java/io/joyrpc/cluster/event/ConfigEvent.java
|
package io.joyrpc.cluster.event;
/*-
* #%L
* joyrpc
* %%
* Copyright (C) 2019 joyrpc.io
* %%
* 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 io.joyrpc.event.UpdateEvent;
import java.util.Map;
/**
* 配置变更事件,只支持全量
*/
public class ConfigEvent extends UpdateEvent<Map<String, String>> {
/**
* 构造函数
*
* @param source
* @param target
* @param version
* @param datum
*/
public ConfigEvent(final Object source, final Object target, final long version, final Map<String, String> datum) {
super(source, target, UpdateType.FULL, version, datum);
}
/**
* 数据是否为空
*
* @return
*/
public boolean isEmpty() {
return datum == null || datum.isEmpty();
}
}
|
areese/jni_cleanup
|
src/main/java/yjava/jni/cleaner/DeallocatingClosedBase.java
|
<filename>src/main/java/yjava/jni/cleaner/DeallocatingClosedBase.java<gh_stars>0
/* Copyright 2015 Yahoo Inc. */
/* Licensed under the terms of the 3-Clause BSD license. See LICENSE file in the project root for details. */
package yjava.jni.cleaner;
/**
* This class takes advantage of the Cleaner API inside the GC to do native memory collection without a finalizer. The
* Cleaner is a special type of PhatomReference and when the GC see's it during reference processing, it will call the
* runnable method. This allows us to call a special JNI Free function that is implemented in Destructor, which only
* takes a long which is actually a C pointer.
*
* This also deals with ensuring that we don't double free if the resource has been closed.
*
* @author areese
*
*/
public abstract class DeallocatingClosedBase extends ClosedBaseChecked implements PointerAccess {
protected volatile Pointer pointer;
protected volatile AbstractDeallocator destructor;
protected volatile RunnableDestructor runnableDestructor;
@SuppressWarnings("restriction")
protected volatile sun.misc.Cleaner cleaner;
@SuppressWarnings("restriction")
protected DeallocatingClosedBase(Pointer pointer, AbstractDeallocator destructor) {
this.pointer = pointer;
this.destructor = destructor;
this.runnableDestructor = new RunnableDestructor(destructor, this.pointer);
if (null != this.runnableDestructor) {
this.cleaner = sun.misc.Cleaner.create(this, this.runnableDestructor);
} else {
this.cleaner = null;
}
}
/**
* This is only ever called from close(), so it's not leaked.
*/
@Override
protected final boolean release() {
if (null != pointer) {
int leakIndex = release(pointer);
// pointer is free set it to 0.
erasePointer(leakIndex);
}
return true;
}
/**
* Throw if the pointer has been released.
*
* @throws IllegalStateException if the pointer has already been released.
*/
public void validate() throws IllegalStateException {
if (null == pointer || 0 == pointer.pointer) {
throw new IllegalStateException("Context has been released");
}
}
protected synchronized int release(final Pointer pointer) {
// call validate here because this should never be called with a pointer
// that is 0.
validate();
int leakIndex = destructor.free(pointer);
erasePointer(leakIndex);
return leakIndex;
}
@Override
public abstract int getLeakIndex();
@Override
public Pointer getPointer() {
return pointer;
}
@Override
public void erasePointer(int leakIndex) {
if (null == this.pointer) {
this.closed = true;
return;
}
this.pointer.pointer = 0;
this.pointer = null;
if (null != this.destructor) {
// note this wasn't leaked.
if (null != this.destructor.counter) {
this.destructor.counter.close(leakIndex);
}
// ensure the deallocator doesn't think it owns the pointer.
this.runnableDestructor.pointer.pointer = 0L;
this.runnableDestructor.pointer = null;
this.runnableDestructor.destructor = null;
// releases the deallocator
this.destructor = null;
}
// release the cleaner
this.cleaner = null;
this.closed = true;
}
}
|
Tencao/ExNihiloCreatio
|
src/main/java/exnihilocreatio/compatibility/tconstruct/CompatTConstruct.java
|
package exnihilocreatio.compatibility.tconstruct;
import exnihilocreatio.ModItems;
import exnihilocreatio.config.ModConfig;
import exnihilocreatio.items.ore.EnumOreSubtype;
import exnihilocreatio.items.ore.ItemOre;
import exnihilocreatio.registries.manager.ExNihiloRegistryManager;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.library.materials.Material;
import slimeknights.tconstruct.library.modifiers.Modifier;
public class CompatTConstruct {
public static void postInit() {
if (ModConfig.compatibility.tinkers_construct_compat.addModifer) {
Modifier smashingModifier = new ModifierSmashing();
smashingModifier.addItem(ModItems.hammerDiamond);
}
if (ModConfig.compatibility.tinkers_construct_compat.addMeltingOfChunks) {
registerMeltingChunks();
}
if (ModConfig.compatibility.tinkers_construct_compat.addMeltingOfDust) {
registerMeltingDust();
}
}
private static void registerMeltingChunks() {
for (ItemOre ore : ExNihiloRegistryManager.ORE_REGISTRY.getItemOreRegistry()) {
if (FluidRegistry.isFluidRegistered(ore.getOre().getName())) {
Fluid fluid = FluidRegistry.getFluid(ore.getOre().getName());
TinkerRegistry.registerMelting(new ItemStack(ore, 1, EnumOreSubtype.CHUNK.getMeta()), fluid,
(int) (ModConfig.compatibility.tinkers_construct_compat.ingotsPerChunkWhenMelting * Material.VALUE_Ingot));
} else if (ore.getOre().getName().equals("aluminium") && FluidRegistry.isFluidRegistered("aluminum")) {
Fluid fluid = FluidRegistry.getFluid("aluminum");
TinkerRegistry.registerMelting(new ItemStack(ore, 1, EnumOreSubtype.CHUNK.getMeta()), fluid,
(int) (ModConfig.compatibility.tinkers_construct_compat.ingotsPerChunkWhenMelting * Material.VALUE_Ingot));
}
}
}
private static void registerMeltingDust() {
for (ItemOre ore : ExNihiloRegistryManager.ORE_REGISTRY.getItemOreRegistry()) {
if (FluidRegistry.isFluidRegistered(ore.getOre().getName())) {
Fluid fluid = FluidRegistry.getFluid(ore.getOre().getName());
TinkerRegistry.registerMelting(new ItemStack(ore, 1, EnumOreSubtype.DUST.getMeta()), fluid,
(int) (ModConfig.compatibility.tinkers_construct_compat.ingotsPerDustWhenMelting * Material.VALUE_Ingot));
} else if (ore.getOre().getName().equals("aluminium") && FluidRegistry.isFluidRegistered("aluminum")) {
Fluid fluid = FluidRegistry.getFluid("aluminum");
TinkerRegistry.registerMelting(new ItemStack(ore, 1, EnumOreSubtype.DUST.getMeta()), fluid,
(int) (ModConfig.compatibility.tinkers_construct_compat.ingotsPerDustWhenMelting * Material.VALUE_Ingot));
}
}
}
}
|
demidenko05/beige-acc
|
src/main/java/org/beigesoft/acc/prc/InvLnSv.java
|
/*
BSD 2-Clause License
Copyright (c) 2019, Beigesoft™
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.beigesoft.acc.prc;
import java.util.Map;
import org.beigesoft.mdl.IReqDt;
import org.beigesoft.prc.IPrcEnt;
import org.beigesoft.acc.mdlb.AInv;
import org.beigesoft.acc.mdlb.AInvLn;
import org.beigesoft.acc.mdlb.AInTxLn;
import org.beigesoft.acc.mdlb.ALnTxLn;
import org.beigesoft.acc.srv.SrInLnSv;
import org.beigesoft.acc.srv.ISrInItLn;
import org.beigesoft.acc.srv.UtInLnTxTo;
/**
* <p>Processor that saves invoice line into DB.</p>
*
* @param <RS> platform dependent record set type
* @param <T> invoice type
* @param <L> invoice line type
* @param <TL> tax line type
* @param <LTL> item tax line type
* @author <NAME>
*/
public class InvLnSv<RS, T extends AInv, L extends AInvLn<T, ?>,
TL extends AInTxLn<T>, LTL extends ALnTxLn<T, L>>
implements IPrcEnt<L, Long> {
/**
* <p>Saving service.</p>
**/
private SrInLnSv srInLnSv;
/**
* <p>Service that makes taxes and totals for line and invoice.</p>
**/
private UtInLnTxTo<RS, T, L, TL, LTL> utInTxTo;
/**
* <p>Item line oriented service.</p>
**/
private ISrInItLn<T, L> srInItLn;
/**
* <p>Process that saves entity.</p>
* @param pRvs request scoped vars
* @param pRqDt Request Data
* @param pEnt Entity to process
* @return Entity processed for farther process or null
* @throws Exception - an exception
**/
@Override
public final L process(final Map<String, Object> pRvs, final L pEnt,
final IReqDt pRqDt) throws Exception {
return this.srInLnSv.save(pRvs, pEnt, pRqDt, this.utInTxTo, this.srInItLn);
}
//Simple getters and setters:
/**
* <p>Getter for srInLnSv.</p>
* @return SrInLnSv
**/
public final SrInLnSv getSrInLnSv() {
return this.srInLnSv;
}
/**
* <p>Setter for srInLnSv.</p>
* @param pSrInLnSv reference
**/
public final void setSrInLnSv(final SrInLnSv pSrInLnSv) {
this.srInLnSv = pSrInLnSv;
}
/**
* <p>Getter for utInTxTo.</p>
* @return UtInLnTxTo<RS, T, L, TL, LTL>
**/
public final UtInLnTxTo<RS, T, L, TL, LTL> getUtInTxTo() {
return this.utInTxTo;
}
/**
* <p>Setter for utInTxTo.</p>
* @param pUtInTxTo reference
**/
public final void setUtInTxTo(final UtInLnTxTo<RS, T, L, TL, LTL> pUtInTxTo) {
this.utInTxTo = pUtInTxTo;
}
/**
* <p>Getter for srInItLn.</p>
* @return ISrInItLn<T, L>
**/
public final ISrInItLn<T, L> getSrInItLn() {
return this.srInItLn;
}
/**
* <p>Setter for srInItLn.</p>
* @param pSrInItLn reference
**/
public final void setSrInItLn(final ISrInItLn<T, L> pSrInItLn) {
this.srInItLn = pSrInItLn;
}
}
|
bhutchinson/rice
|
rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/container/PageGroup.java
|
/**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.uif.container;
import java.util.List;
import org.kuali.rice.krad.uif.element.BreadcrumbItem;
import org.kuali.rice.krad.uif.element.BreadcrumbOptions;
import org.kuali.rice.krad.uif.element.PageBreadcrumbOptions;
/**
* Interface for top-level page components, to be used as items in a multi-page view.
*
* @author Kuali Rice Team (<EMAIL>)
*/
public interface PageGroup extends Group {
/**
* When this is true, the first field of the kualiForm will be focused by
* default, unless the parameter focusId is set on the form (by an
* actionField), then that field will be focused instead. When this setting
* if false, no field will be focused.
*
* @return the autoFocus
*/
boolean isAutoFocus();
/**
* @param autoFocus the autoFocus to set
*/
void setAutoFocus(boolean autoFocus);
/**
* The breadcrumbOptions specific to this page.
*
* <p>
* Important note: breadcrumbOptions for preViewBreadcrumbs, prePageBreadcrumbs, and
* breadcrumbOverrides are inherited from the View if not explicitly set from the PageGroup level's
* breadcrumbOptions
* (if they contain a value at the view level and the property is null at the page level - default behavior).
* Explicitly providing an empty list or setting these properties at the PageGroup level will
* override this inheritance.
* </p>
*
* @return the {@link BreadcrumbOptions}
*/
PageBreadcrumbOptions getBreadcrumbOptions();
/**
* Set the breadcrumbOptions
*
* @param breadcrumbOptions
*/
void setBreadcrumbOptions(PageBreadcrumbOptions breadcrumbOptions);
/**
* Gets the breadcrumb items indicating a homeward path.
*
* @return breadcrumb items
*/
List<BreadcrumbItem> getHomewardPathBreadcrumbs();
/**
* Gets the breadcrumb items leading to the current view.
*
* @return breadcrumb items
*/
List<BreadcrumbItem> getPreViewBreadcrumbs();
/**
* Gets the breadcrumb items leading to the current page.
*
* @return breadcrumb items
*/
List<BreadcrumbItem> getPrePageBreadcrumbs();
/**
* Gets the breadcrumb items overrides.
*
* @return breadcrumb items
*/
List<BreadcrumbItem> getBreadcrumbOverrides();
/**
* The breadcrumbItem for this page. This is the item that (generally) appears last in the breadcrumb list.
*
* <p>
* If a label is not explicitly defined, the label is retrieved from the headerText of the PageGroup's header.
* If this is also not defined, the breadcrumbItem is NOT rendered. The url properties do not need to be provided
* for this breadcrumbItem because it is automatically determined based on the this PageGroup's pageId, viewId,
* and controllerMapping retrieved from the initial controller request.
* </p>
*
* @return the breadcrumbItem for this page
*/
BreadcrumbItem getBreadcrumbItem();
/**
* Set the breadcrumbItem for this PageGroup
*
* @param breadcrumbItem
*/
void setBreadcrumbItem(BreadcrumbItem breadcrumbItem);
/**
* When true, this page's footer will become sticky (fixed) at the bottom of the window
*
* @return true if the page footer is sticky, false otherwise
*/
boolean isStickyFooter();
/**
* Set to true to make this page's footer sticky
*
* @param stickyFooter
*/
void setStickyFooter(boolean stickyFooter);
/**
* Specifies the URL the view's form should post to
*
* <p>
* Any valid form post URL (full or relative) can be specified. If left
* empty, the form will be posted to the same URL of the preceding request
* URL.
* </p>
*
* @return post URL
*/
String getFormPostUrl();
/**
* Setter for the form post URL
*
* @param formPostUrl
*/
void setFormPostUrl(String formPostUrl);
}
|
joetache4/project-euler
|
data/p079.py
|
def get_data():
return [
319,
680,
180,
690,
129,
620,
762,
689,
762,
318,
368,
710,
720,
710,
629,
168,
160,
689,
716,
731,
736,
729,
316,
729,
729,
710,
769,
290,
719,
680,
318,
389,
162,
289,
162,
718,
729,
319,
790,
680,
890,
362,
319,
760,
316,
729,
380,
319,
728,
716]
|
kkcookies99/UAST
|
Dataset/Leetcode/train/121/656.java
|
<filename>Dataset/Leetcode/train/121/656.java
class Solution {
public int XXX(int[] prices) {
if (prices.length <= 1) {
return 0;
}
int res = Integer.MIN_VALUE;
int min = prices[0];
/*
本质上的意思是f(i) = max(当前价格 - 之前价格最小值,之前最大利润)
*/
for (int i = 1; i < prices.length; i++) {
if (prices[i] < min) {
min = prices[i];
} else {
res = prices[i] - min > res ? prices[i] - min : res;
}
}
return res == Integer.MIN_VALUE ? 0 : res;
}
}
undefined
for (i = 0; i < document.getElementsByTagName("code").length; i++) { console.log(document.getElementsByTagName("code")[i].innerText); }
|
ZRock-Application/ZROCK_APPLICATION_SCRIPTME
|
ZROCK_SCRIPTME/app/src/main/java/zrock/application/scriptme/ScriptMeActivity.java
|
<reponame>ZRock-Application/ZROCK_APPLICATION_SCRIPTME<gh_stars>0
package zrock.application.scriptme;
import zrock.application.scriptme.R;
import zrock.application.scriptme.activities.*;
import zrock.application.scriptme.fragments.*;
import zrock.application.scriptme.utils.Root;
import zrock.application.engine.Engine;
import zrock.application.engine.view.ResideMenu;
import zrock.application.engine.view.ResideMenuItem;
import zrock.application.engine.view.TouchDisableView;
import zrock.application.engine.view.menu.v1.*;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.graphics.Color;
import android.content.Intent;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
public class ScriptMeActivity extends FragmentActivity implements View.OnClickListener
{
/*This ZROCK APPLICATION SCRIPTME*/
private ResideMenu resideMenu;
private ScriptMeActivity mContext;
private ResideMenuItem itemHome;
private ResideMenuItem itemScriptMe;
private ResideMenuItem itemEditor;
private ResideMenuItem itemRunner;
private RadialMenuWidget pieMenu;
public RadialMenuItem menuItem, menuCloseItem, menuExpandItem;
public RadialMenuItem Home, Right, Left;
private List<RadialMenuItem> children = new ArrayList<RadialMenuItem>();
/**
* Called when the activity is first created.
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_application_scriptme);
Root.requestRoot();
mContext = this;
setUpMenu();
if (savedInstanceState == null)
changeFragment(new ScriptMeFragment());
}
private void setUpMenu()
{
// attach to current activity;
resideMenu = new ResideMenu(this);
resideMenu.setBackground(R.drawable.activity_background);
resideMenu.attachToActivity(this);
resideMenu.setMenuListener(menuListener);
//valid scale factor is between 0.0f and 1.0f. leftmenu'width is 150dip.
resideMenu.setScaleValue(0.6f);
// create menu items;
itemHome = new ResideMenuItem(this, android.R.drawable.ic_input_add, "Home");
itemScriptMe = new ResideMenuItem(this, android.R.drawable.ic_input_add, "Tweaks");
itemEditor = new ResideMenuItem(this, android.R.drawable.ic_input_add, "Editor");
itemRunner = new ResideMenuItem(this, android.R.drawable.ic_input_add, "Run Script");
itemHome.setOnClickListener(this);
itemScriptMe.setOnClickListener(this);
itemEditor.setOnClickListener(this);
itemRunner.setOnClickListener(this);
resideMenu.addMenuItem(itemHome, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemScriptMe, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemEditor, ResideMenu.DIRECTION_RIGHT);
resideMenu.addMenuItem(itemRunner, ResideMenu.DIRECTION_RIGHT);
// You can disable a direction by setting ->
// resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_RIGHT);
pieMenu = new RadialMenuWidget(this);
menuCloseItem = new RadialMenuItem(getString(R.string.close), null);
menuCloseItem.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem = new RadialMenuItem(getString(R.string.zrock_radial_create), null);
menuItem.setDisplayIcon(R.drawable.ic_edit_script);
menuItem.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
@Override
public void execute()
{
CreateActivity.start(ScriptMeActivity.this);
pieMenu.dismiss();
}
});
Home = new RadialMenuItem(getString(R.string.zrock_radial_home), null);
Home.setDisplayIcon(R.drawable.ic_action_github);
Home.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
@Override
public void execute()
{
// Can edit based on preference. Also can add animations
// here.
//pieMenu.dismiss();
}
});
Right = new RadialMenuItem(getString(R.string.zrock_radial_right), null);
Right.setDisplayIcon(android.R.drawable.ic_media_next);
Right.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
@Override
public void execute()
{
// Can edit based on preference. Also can add animations
// here.
resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
pieMenu.dismiss();
}
});
Left = new RadialMenuItem(getString(R.string.zrock_radial_left), null);
Left.setDisplayIcon(android.R.drawable.ic_media_previous);
Left.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
@Override
public void execute()
{
// Can edit based on preference. Also can add animations
// here.
resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
pieMenu.dismiss();
}
});
menuExpandItem = new RadialMenuItem(getString(R.string.zrock_radial_expandable), getString(R.string.zrock_radial_expandable));
children.add(Home);
children.add(Right);
children.add(Left);
menuExpandItem.setMenuChildren(children);
menuCloseItem.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
@Override
public void execute()
{
// menuLayout.removeAllViews();
pieMenu.dismiss();
}
});
// pieMenu.setDismissOnOutsideClick(true, menuLayout);
pieMenu.setAnimationSpeed(0L);
pieMenu.setSourceLocation(200, 200);
pieMenu.setIconSize(15, 30);
pieMenu.setTextSize(13);
pieMenu.setOutlineColor(Color.BLACK, 225);
pieMenu.setInnerRingColor(Color.GRAY, 180);
pieMenu.setOuterRingColor(Color.DKGRAY, 180);
pieMenu.setSelectedColor(Color.GREEN,180);
//pieMenu.setHeader("Test Menu", 20);
pieMenu.setCenterCircle(menuCloseItem);
pieMenu.addMenuEntry(new ArrayList<RadialMenuItem>() {
{
add(menuItem);
add(menuExpandItem);
}
});
findViewById(R.id.main_fragment).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view)
{
pieMenu.show(view);
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev)
{
return resideMenu.dispatchTouchEvent(ev);
}
@Override
public void onClick(View view)
{
if (view == itemHome)
{
new android.os.Handler().postDelayed(new Runnable(){
@Override
public void run(){
android.os.Process.killProcess(android.os.Process.myPid());
}
},1200);
}
else if (view == itemScriptMe)
{
TweaksActivity.start(ScriptMeActivity.this);
}
else if (view == itemEditor)
{
EditorActivity.start(ScriptMeActivity.this);
}
else if (view == itemRunner)
{
RunnerActivity.start(ScriptMeActivity.this);
}
resideMenu.closeMenu();
}
private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
@Override
public void openMenu()
{
Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();
}
@Override
public void closeMenu()
{
Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
}
};
private void changeFragment(Fragment targetFragment)
{
resideMenu.clearIgnoredViewList();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
// What good method is to access resideMenu?
public ResideMenu getResideMenu()
{
return resideMenu;
}
public RadialMenuWidget getRadialMenu()
{
return pieMenu;
}
@Override
protected void onResume()
{
// TODO: Implement this method
super.onResume();
//findViewById(R.id.main_fragment).post(new Runnable() {
//public void run()
//{
//pieMenu.show(findViewById(R.id.main_fragment));
//}
//});
}
@Override
protected void onDestroy()
{
Log.v("MainActivity", "onDestroy");
super.onDestroy();
}
}
|
scbedd/azure-sdk-for-node
|
lib/services/logicManagement/lib/models/integrationAccountMapPropertiesParametersSchema.js
|
<filename>lib/services/logicManagement/lib/models/integrationAccountMapPropertiesParametersSchema.js
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* The parameters schema of integration account map.
*
*/
class IntegrationAccountMapPropertiesParametersSchema {
/**
* Create a IntegrationAccountMapPropertiesParametersSchema.
* @property {string} [ref] The reference name.
*/
constructor() {
}
/**
* Defines the metadata of IntegrationAccountMapPropertiesParametersSchema
*
* @returns {object} metadata of IntegrationAccountMapPropertiesParametersSchema
*
*/
mapper() {
return {
required: false,
serializedName: 'IntegrationAccountMapProperties_parametersSchema',
type: {
name: 'Composite',
className: 'IntegrationAccountMapPropertiesParametersSchema',
modelProperties: {
ref: {
required: false,
serializedName: 'ref',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = IntegrationAccountMapPropertiesParametersSchema;
|
lpezo/marca2
|
public/modules/clientes/controllers/clientes.client.controller.js
|
'use strict';
// Clientes controller
angular.module('clientes').controller('ClientesController', ['$scope', '$stateParams', '$location',
'Authentication', 'Clientes', 'TableSettings', 'ClientesForm',
function($scope, $stateParams, $location, Authentication, Clientes, TableSettings, ClientesForm ) {
$scope.authentication = Authentication;
$scope.tableParams = TableSettings.getParams(Clientes);
$scope.cliente = {};
$scope.setFormFields = function(disabled) {
$scope.formFields = ClientesForm.getFormFields(disabled);
//console.log($scope.formFields);
};
// Create new Cliente
$scope.create = function() {
var cliente = new Clientes($scope.cliente);
// Redirect after save
cliente.$save(function(response) {
$location.path('clientes/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Cliente
$scope.remove = function(cliente) {
if ( cliente ) {
cliente = Clientes.get({clienteId:cliente._id}, function() {
cliente.$remove(function(){
$scope.tableParams.reload();
});
});
} else {
$scope.cliente.$remove(function() {
$location.path('clientes');
});
}
};
// Update existing Cliente
$scope.update = function() {
var cliente = $scope.cliente;
cliente.$update(function() {
$location.path('clientes/' + cliente._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.toViewCliente = function() {
$scope.cliente = Clientes.get( {clienteId: $stateParams.clienteId} );
$scope.setFormFields(true);
};
$scope.toEditCliente = function() {
$scope.cliente = Clientes.get( {clienteId: $stateParams.clienteId} );
$scope.setFormFields(false);
};
$scope.iniList = function() {
$scope.tableParams.parameters({filter:{}});
};
// $scope.$on('reload_cli', function(event, data){
// var codcli = data[0];
// $scope.tableParams.parameters({filter:{codigo:codcli}});
// $scope.tableParams.reload();
// });
}
]);
|
HendryKaak/u8g2
|
tools/font/build/single_font_files/u8g2_font_crox2hb_tf.c
|
/*
Fontname: -Cronyx-Helvetica-Bold-R-Normal--10-100-75-75-P-56-RAWIN-R
Copyright: Copyright (C) 1990, 1991 EWT Consulting, Portions Copyright (C) 1994 Cronyx Ltd.
Glyphs: 191/224
BBX Build Mode: 0
*/
const uint8_t u8g2_font_crox2hb_tf[2616] U8G2_FONT_SECTION("u8g2_font_crox2hb_tf") =
"\277\0\3\3\4\4\2\5\5\16\20\0\375\12\375\12\375\1\204\3T\12\37 \5\0v\12!\10\242C"
"\212\7\221\0\42\7D[\213\7\1#\15\250B<\42\323\211H:\21\331\0$\17\266?,\31\345p"
"\220\61\35&\64\21\0%\32\253\303\236\71@\42\223(\311Fr\210\34\42\207\210f\42\211\232D\16\230"
"\0&\21\250C\255\241D&\221I\204C\232H\311&:'\7B[\212C\0(\15\324\267*\211H"
"\42\322\67\221L\0)\15\324\266\212\240H&\322\27\221$\6*\11FZ+Q\204\305\0+\12VK"
",\241\310$\24\1,\7#>\232\21\0-\6\25\322\212\2.\6\22C\12\1/\15\305\272:M\62"
"%\231R\60\21\0\60\13\246C\34\212\210?I(\0\61\10\244C,\223\376\0\62\14\246C\34\212\210"
"$\224\351(\64\63\17\246C\34\212H\250\64\25\12I\22\12\0\64\14\246CL\331\210EB:\4\65"
"\65\17\246C\214CP\261\42\22\12I\22\12\0\66\17\246C\34\212\210(\254LHL\22\12\0\67\15"
"\246C\14\243\232P&\224\11\325\0\70\16\246C\34\212\210IB\21q\222P\0\71\16\246C\34\212\210"
"\313\244($I(\0:\10rC\12\71L\0;\11\203>\32\71\322\10\0<\10vG\274\321\306\15"
"=\7\66O\14\263\1>\11vG\214\341\246m\0?\16\246C\34\212\210$\224)\252\303D\0@\35"
"\315\277\317\362l&\7\210\344\0\211\254BR!\251\220$\42\211\350$\207\16\247\66\0A\26\252BM"
"\71D\16 SEB\221\354\20\22J\342\200\71@\0B\16\250C\215\213\220\361 \21r<H\0C"
"\24\251C\255\232\212\224\16\220\3\344\0\71@*\221\311J\0D\15\251\303\215\223P\42\345G\311\11\0"
"E\14\250C\215\303X\371\42\326|\10F\14\250\303\214\303X\371\42\326\31\0G\21\251\303\255\232\212\224"
"\16\220\3dV\252D\66:H\13\251\303\15)\327\203\225W\1I\7\242C\212\7\3J\13\246CL"
"}$\221$\24\0K\22\250\303\14\231D\244\42#N\211\22\231HM\42\24L\10\247C\14\251\376z"
"M\20\252C\16\61\271h<\35B\26\236D$\5N\20\251\303\15i\321f\243\210H\22\232cU\0"
"O\15\251\303\255\232\212\224\257\22\231\254\4P\22\251C\215\223P\42e\224\234\344\0\71@\16\220\3Q"
"\15\251\303\255\232\212\224o\24\231\354\0R\26\252\303\215\233P$\225H%B\321!$\225H%R\211"
"X\0S\20\250C\35\213\220\35@\7\314\1D\242\304\2T\26\252B\215\303P\16\221C\344\20\71D"
"\16\221C\344\20\71D\10U\14\251\303\15)\225\310d%\0V\26\252B\215\70`\16\220\10EB"
"\231H(\222\222\351\0\71D\10W\31\256B\217\250p*\234\12%\42\222\22IF\42\222\210$\252P"
",\224\1X\21\251\302\214\360X\42S\221\216\247\22\231Jx,Y\27\252B\215\70`\16\220\10e\42"
")\35 \207\310!r\210\34\42\4Z\14\247\303\214\253P*\324*\224\36[\11\324\267\12\223\376\23\1"
"\134\14\305\272\212`\252LQ\246(S]\11\324\266\12\222\376\223\1^\10\66c,\31E$_\7\30"
":\214C\0`\7#\343\12\221\0a\17x\303\234\222Ld\221Id\22\231\350\0b\16\247\303\14\251"
"\252eDc+\35\42\0c\13wC\234\212\214\252MR\1d\14\247\303\134-\207P\215\323\304\0e"
"\15w\303\234\212\214v\240\312$\25\0f\14\244B*\211HB\21\351\5\0g\15\247\267\234C\250\306"
"ibU\251\0h\14\246C\14\241beB\342I\0i\10\242C\12\341\341\0j\13\323\66\32\71@"
"\242_F\0k\17\247C\14\251&\211\22\215&\21\251\310\4l\7\242C\212\7\3m\20zC\216\312"
"\26\222\210$\42\211H\42\222\2n\12vC\214\312\204\304\223\0o\13w\303\234\212\214\67I\5\0p"
"\16\247\267\14\313\210\306V:D\244\252\0q\14\247\267\234C\250\306ib\325\0r\11t\303\212\213H"
"'\0s\13vC\34\212\210\312$\241\0t\13\224B\32\221\204\42\322M\0u\11vC\14\21_&"
"\5v\15xB\214\350T\42\322F\244\312\0w\23zB\215\230h&\222\34B\207\320!&\22\212D"
"\0x\15w\302\213\240Dm\270&\221\4\5y\20\250\66\214\350T\42\322F\244\212\245\302)\0z\12"
"u\303\213\232HM$+{\14\326\66\273\221P\247\251P\327\1|\7\322\67\212\17\5}\15\326\66\213"
"\251P\327\221P\247\31\0~\12\70_\235\21EB\232\0\240\5\0v\12\241\10\242\67\12\321\341 \242"
"\17\226?L\11ER\221\220H\23\11E\10\270\16\246C\234\221DQ*+\11eB\3\244\12VW"
"\14\221\204\304\42\22\245\21\250B\214\350T\42\222\221\16\61\331!&V\3\246\10\322\67\212C\351P\247"
"\22\246C\34\212H\42\34ID\22\321P\42\222P\0\250\7\25\346\212\220\0\251\20\211\312\254\232J\350"
"\42\233\310F\26\231\254\4\252\11tO\33\231\344\62$\253\10VG,\12\33\3\254\7&S\14\243\0"
"\255\6\25\322\212\2\256\22\211\312\254\232J\204\62\221T(\23\11E&+\1\257\7\30n\214C\0\260"
"\10\64\337\32\11E\2\261\13vC,\241\310$\224C\14\262\11U\326\232IHS\1\250\13U\326\232"
"IH%$\231\0\264\7#\343\32\12\0\265\25\267\67\14\221D$\21ID\22\221D$\21I\16R"
"U\0\266\12\246C\234\303\207H\211\7\267\6\22W\12\1\270\10\64\267\32Y\5\0\271\7S\327\232\212"
"\6\272\11tO\33\311\241\42%\273\11VG\14\32\13\23\0\274\27\252B\35\231h\246$\24\11%r"
"\210H&\232IH\222\222P\0\275\26\252B\35\231h\246$\24\11%rH\221\42\23\311DBI\1"
"\276\27\252B\235\221($\21Jd!b\35\42\222\211f\22\222\244$\24\277\16\246\67,\71L\250\246"
"(\42I(\0\300\26\252BM\71D\16 SEB\221\354\20\22J\342\200\71@\0\301\15\250C\215"
"\213X\371\42\344x\220\0\302\16\250C\215\213\220\361 \21r<H\0\303\11\247\303\214\203T\5\304"
"\27\311\273-\233H&\222\211d\42\231H&\222\211\324$\7*U\0\305\14\250C\215\303X\371\42\326"
"|\10\306\27\256B\37\231&U\211:\300\16\242\203\354\0\211\252HMKT(\307\20\250C\35\213P"
"\254F\7\210\305D\211\5\0\310\17\251\303\15)\307\232IB\21\331\212T\1\311\21\311\303-\211t&"
"\345X\63I(\42[\221*\312\22\250\303\14\231D\244\42#N\211\22\231HM\42\24\313\26\253\303\256"
"\203H*\222\212\244\42\251H*\222\212\244\42iY\0\314\20\252C\16\61\271h<\35B\26\236D$"
"\5\315\13\251\303\15)\327\203\225W\1\316\15\251\303\255\232\212\224\257\22\231\254\4\317\11\251\303\215\3\225"
"\25\320\22\251C\215\223P\42e\224\234\344\0\71@\16\220\3\321\24\251C\255\232\212\224\16\220\3\344"
"\0\71@*\221\311J\0\322\26\252B\215\303P\16\221C\344\20\71D\16\221C\344\20\71D\10\323\26"
"\252B\215\70`\16\220\10e\42)\35 \207\310\1r\200x\16\324\24\252\303-\233D\223\210$\42\211"
"H\42\222\212\66\263\20\0\325\21\251\302\214\360X\42S\221\216\247\22\231Jx,\326\32\312\273\15\251D"
"*\221J\244\22\251D*\221J\244\22\251\344\60\207\310!\2\327\22\251\303\15)W\311!\16\220\3\344"
"\0\71@\16\20\330\26\254C\17\231\214&\243\311h\62\232\214&\243\311h\62\232\354p\331\33\315;\17"
"\231\212LE\246\42S\221\251\310Td*\62\25\231\312\301\16\224\3\5\332\27\253B\16:H\16\222\203"
"\344\240CL*\222\212\244\42\251\350\20\1\333\22\253\303\16\71\200\16\240\3\350\200\303\204\352\365P\21\334"
"\22\251\303\15\71@\16\220\3\344\200CD\312\365\60\1\335\23\251\303\255\232\212T\16\220\331\1r\0U"
"\42\223\225\0\336\21\252C\16\21I\42\222\20\375H\21ID$\0\337\20\251\303\235\303\224\253\344\20\23"
"\251I\204T\1\340\17x\303\234\222Ld\221Id\22\231\350\0\341\15\247\303\134IEj\221\361&\251"
"\0\342\15w\303\14\213\214v\240\321\16\21\0\343\11vC\214CP\217\0\344\21\231\273-\233H&\222"
"\211d\42\65\311\201J\25\345\15w\303\234\212\214v\240\312$\25\0\346\21|B\36\221\232D\325l\225"
"\250\211T\202\62\1\347\15w\303\234\212L*\42\323$\25\0\350\14w\303\14\31S\345\20)\321\4\351"
"\16\227\303\34\265\221\214\251r\210\224h\2\352\16wC\14\221D\211F\223\210Td\2\353\17w\303\34"
"\213H\42\222\210$\42\211\210&\354\14xC\15a\351`\221\20\31\5\355\12vC\14\21\323a\304$"
"\356\13w\303\234\212\214\67I\5\0\357\11vC\214C\210O\2\360\16\247\267\14\313\210\306V:D\244"
"\252\0\361\13wC\234\212\214\252MR\1\362\12xC\215CL\254\67\0\363\20\250\66\214\350T\42\322"
"F\244\212\245\302)\0\364\22\270\67=\241E\205\42\241H(\22\212\212Q\254\6\365\15w\302\213\240D"
"m\270&\221\4\5\366\21\227;\14\221D$\21ID\22\221D$\271*\367\12vC\14\21\223\244\250"
"\1\370\21zC\16\221\210$\42\211H\42\222\210$:\24\371\25\233;\16\221\212HE\244\42R\21\251"
"\210T\16t\220\34$\372\20yB\15:@\16\260)\311D\62\221\5\0\373\15y\303\15)\365\20\241"
"\271\35&\2\374\14w\303\14\251\324\42c;D\0\375\15w\303\234\212L*\252\322$\25\0\376\13x"
"C\15\11\223O\24\12\0\377\14w\303\234C\214Mb\21\321\4\0\0\0";
|
komamj/Audient
|
storemusic/src/main/java/com/xinshang/store/playlist/ReasonDialogFragment.java
|
package com.xinshang.store.playlist;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.xinshang.store.R;
import com.xinshang.store.StoreMusicApplication;
import com.xinshang.store.base.BaseDialogFragment;
import com.xinshang.store.data.entities.MessageEvent;
import com.xinshang.store.utils.Constants;
import org.greenrobot.eventbus.EventBus;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ReasonDialogFragment extends BaseDialogFragment implements ReasonContract.View {
private static final String TAG = "ReasonDialogFragment";
@BindView(R.id.radio_group)
RadioGroup mRadioGroup;
@BindView(R.id.progress_bar)
ProgressBar mProgressBar;
@Inject
ReasonPresenter mPresenter;
private String mId;
@OnClick(R.id.tv_ok)
void doConfirm() {
RadioButton radioButton = mRadioGroup.findViewById(mRadioGroup.getCheckedRadioButtonId());
String reason = radioButton.getText().toString();
if (mPresenter != null) {
mPresenter.deleteStoreSong(mId, reason);
}
}
@OnClick(R.id.tv_cancel)
void doCancel() {
this.dismiss();
}
public static void showReasonDialog(FragmentManager fragmentManager, String id) {
ReasonDialogFragment reasonDialogFragment = new ReasonDialogFragment();
Bundle bundle = new Bundle();
bundle.putString(Constants.KEY_STORE_SONG_ID, id);
reasonDialogFragment.setArguments(bundle);
reasonDialogFragment.show(fragmentManager, TAG);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, R.style.AuditionDilogTheme);
if (getArguments() != null) {
mId = getArguments().getString(Constants.KEY_STORE_SONG_ID);
}
// inject presenter
DaggerReasonComponent.builder()
.audientRepositoryComponent(((StoreMusicApplication) getActivity().getApplication()).getRepositoryComponent())
.reasonPresenterModule(new ReasonPresenterModule(this))
.build()
.inject(this);
}
@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.reason_dialog_fragment, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mPresenter != null) {
mPresenter.unSubscribe();
}
}
@Override
public void setPresenter(ReasonContract.Presenter presenter) {
}
@Override
public boolean isActive() {
return this.isAdded();
}
@Override
public void setLoadingIndicator(boolean isActive) {
if (isActive) {
mProgressBar.setVisibility(View.VISIBLE);
} else {
mProgressBar.setVisibility(View.GONE);
}
}
@Override
public void dismissReasonDialogFragment() {
EventBus.getDefault().post(new MessageEvent(Constants.MESSAGE_PLAYLIST_CHANGED));
this.dismiss();
}
}
|
rlgod/gallery
|
node_modules/babel-plugin-transform-cjs-system-require/test/fixtures/require-calls-only/options.js
|
module.exports = {
mappedRequireName : '$__require'
};
|
fajarutamaa/display-device
|
src/components/mixins/common.js
|
import { DateRangeTypes } from '../../constants/date'
export function update() {
const chart = this.$refs.chart.$refs.chart
chart.clear()
chart.showLoading()
Promise.all([this.fetchData(), this.updateAnnotations()]).finally(() => {
chart.hideLoading()
chart.mergeOptions(this.chartOptions)
})
}
export function onPeriodChange(period, { startTime, endTime }) {
if (period.type === DateRangeTypes.CUSTOM) {
this.setPeriod(period)
this.setStartTime(startTime)
this.setEndTime(endTime)
this.update()
} else {
this.setPeriod(period)
this.update()
}
}
export function updateChart({ withLoading = true, clear = true } = {}) {
const chart = this.$refs.chart.$refs.chart
if (clear) {
chart.clear()
}
if (withLoading) {
chart.showLoading()
}
chart.mergeOptions(this.chartOptions)
}
export function handleUpdateAnnotations(options) {
const chart = this.$refs.chart.$refs.chart
chart.clear()
chart.showLoading()
this.setAnnotationOptions(options)
this.updateAnnotations().finally(() => {
chart.hideLoading()
chart.mergeOptions(this.chartOptions)
})
}
|
thiagoyoussef/registry
|
db/migrate/20150109081914_create_api_log_tables.rb
|
<filename>db/migrate/20150109081914_create_api_log_tables.rb
class CreateApiLogTables < ActiveRecord::Migration[6.0]
def connection
ApiLog::Db.connection
end
def up
# create_table :epp_logs do |t|
# t.text :request
# t.text :response
# t.string :request_command
# t.string :request_object
# t.boolean :request_successful
# t.string :api_user_name
# t.string :api_user_registrar
# t.string :ip
# t.timestamps
# end
# create_table :repp_logs do |t|
# t.string :request_path
# t.string :request_method
# t.text :request_params
# t.text :response
# t.string :response_code
# t.string :api_user_name
# t.string :api_user_registrar
# t.string :ip
# t.timestamps
# end
end
def down
drop_table :epp_logs
drop_table :repp_logs
end
end
|
MatrixTunnel/1.13-Command-API
|
1.13CommandAPI/src/io/github/jorelali/commandapi/api/arguments/SuggestedStringArgument.java
|
<reponame>MatrixTunnel/1.13-Command-API
package io.github.jorelali.commandapi.api.arguments;
import java.util.List;
import com.mojang.brigadier.arguments.StringArgumentType;
import io.github.jorelali.commandapi.api.CommandPermission;
/**
* Deprecated as of 1.9, due to implementation of OverrideableSuggestions. Use <br>
* <code>new StringArgument().overrideSuggestions(String...)</code><br>
* instead
*/
@SuppressWarnings("unchecked")
@Deprecated
public class SuggestedStringArgument implements Argument {
com.mojang.brigadier.arguments.ArgumentType<?> rawType;
String[] suggestions;
/**
* A string argument for one word, which has suggested values
*/
public SuggestedStringArgument(String... suggestions) {
rawType = StringArgumentType.word();
this.suggestions = suggestions;
}
public SuggestedStringArgument(List<String> suggestions) {
this(suggestions.toArray(new String[suggestions.size()]));
}
@Override
public <T> com.mojang.brigadier.arguments.ArgumentType<T> getRawType() {
return (com.mojang.brigadier.arguments.ArgumentType<T>) rawType;
}
@Override
public <V> Class<V> getPrimitiveType() {
return (Class<V>) String.class;
}
@Override
public boolean isSimple() {
return true;
}
public String[] getSuggestions() {
return suggestions;
}
private CommandPermission permission = CommandPermission.NONE;
@Override
public SuggestedStringArgument withPermission(CommandPermission permission) {
this.permission = permission;
return this;
}
@Override
public CommandPermission getArgumentPermission() {
return permission;
}
}
|
scibian/fmgui
|
src/com/intel/stl/ui/logger/config/LoggingInputValidator.java
|
/**
* Copyright (c) 2015, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.intel.stl.ui.logger.config;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import com.intel.stl.api.configuration.AppenderConfig;
import com.intel.stl.api.configuration.LoggingConfiguration;
import com.intel.stl.api.configuration.LoggingThreshold;
import com.intel.stl.api.configuration.RollingFileAppender;
import com.intel.stl.ui.common.STLConstants;
import com.intel.stl.ui.common.Validator;
import com.intel.stl.ui.model.LoggingThresholdViz;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.core.status.Status;
/**
* Custom input validator to check the validity of the inputs on the Logging
* Wizard view
*/
public class LoggingInputValidator {
private final int OK = LoggingValidatorError.OK.getId();
private final int MAX_BACKUP_FILES = 20;
private final int kiloBytes = 1024;
private final String byteStr = "B";
private static LoggingInputValidator instance;
ArrayList<String> validCodes =
new ArrayList<String>(
Arrays.asList(STLConstants.K0649_SC.getValue().trim(),
STLConstants.K0650_C.getValue().trim(),
STLConstants.K0651_D.getValue().trim(),
STLConstants.K0652_F.getValue().trim(),
STLConstants.K0653_SL.getValue().trim(),
STLConstants.K0654_L.getValue().trim(),
STLConstants.K0655_SM.getValue().trim(),
STLConstants.K0656_M.getValue().trim(),
STLConstants.K0657_SN.getValue().trim(),
STLConstants.K0658_SP.getValue().trim(),
STLConstants.K0659_SR.getValue()
.trim(),
STLConstants.K0660_ST.getValue().trim(),
STLConstants.K0661_SX.getValue().trim(),
STLConstants.K0662_DOUBLE_PERCENT.getValue().trim()));
public static LoggingInputValidator getInstance() {
if (instance == null) {
instance = new LoggingInputValidator();
}
return instance;
}
public int validate(LoggingConfiguration loggingConfig) {
int errorCode = OK;
LoggingThreshold rootLoggingLevel =
loggingConfig.getRootLogger().getLevel();
List<AppenderConfig> appenders = loggingConfig.getAppenders();
// Find Rolling File Appender
boolean found = false;
RollingFileAppender fileAppender = null;
Iterator<AppenderConfig> it = appenders.iterator();
while (it.hasNext() && !found) {
AppenderConfig appender = it.next();
if (appender instanceof RollingFileAppender) {
fileAppender = (RollingFileAppender) appender;
found = true;
}
}
// Currently supporting File Appender type only
if (fileAppender != null) {
// Validate information level (threshold)
errorCode =
validateInformationLevel(fileAppender, rootLoggingLevel);
if (errorCode == OK) {
// Validate output format
errorCode = validateOutputFormat(fileAppender);
if (errorCode == OK) {
// Validate maximum file size
errorCode = validateMaxFileSize(fileAppender);
if (errorCode == OK) {
// Validate maximum number of files
errorCode = validateMaxNumFiles(fileAppender);
if (errorCode == OK) {
// Validate file location
errorCode = validateFileLocation(fileAppender);
}
}
}
}
} else {
errorCode = LoggingValidatorError.UNSUPPORTED_APPENDER_TYPE.getId();
}
return errorCode;
}
protected int validateInformationLevel(RollingFileAppender fileAppender,
LoggingThreshold threshold) {
int errorCode = OK;
String thresholdName = threshold.name().toLowerCase();
String thresholdNameVizUpper =
LoggingThresholdViz.getLoggingThresholdName(threshold);
String thresholdNameViz = null;
if (thresholdNameVizUpper != null) {
thresholdNameViz = thresholdNameVizUpper.toLowerCase();
}
if (!thresholdName.equals(thresholdNameViz)) {
errorCode = LoggingValidatorError.INVALID_THRESHOLD_TYPE.getId();
}
// int i = 0;
// boolean found = false;
// while ((!found) && (i < LoggingThresholdViz.values().length)) {
// found = threshold.equals(LoggingThresholdViz.values()[i]);
// i++;
// }
//
// if (!found) {
// errorCode = LoggingValidatorError.INVALID_THRESHOLD_TYPE.getId();
// }
return errorCode;
}
protected int validateOutputFormat(RollingFileAppender fileAppender) {
int errorCode = OK;
// Check if conversion pattern is blank or null
String conversionPattern = fileAppender.getConversionPattern();
if ((conversionPattern == null) || (conversionPattern.equals(""))) {
errorCode = LoggingValidatorError.FORMAT_STRING_EMPTY.getId();
} else {
// I think this validation implementation should go in the back end
// to hide the logging tool in use
LoggerContext loggerContext = new LoggerContext();
loggerContext.reset();
PatternLayout encoder = new PatternLayout();
encoder.setContext(loggerContext);
encoder.setPattern(conversionPattern);
encoder.start();
List<Status> errors =
loggerContext.getStatusManager().getCopyOfStatusList();
if (errors.size() == 0) {
errorCode = OK;
} else {
String emsg = errors.get(errors.size() - 1).getMessage();
// This message should be shown to the user
System.out.println(emsg);
errorCode = LoggingValidatorError.FORMAT_STRING_INVALID.getId();
}
// Evaluate the validity of the pattern
/*-
String[] conversionArray = conversionPattern.split(" ");
for (int i = 0; i < conversionArray.length; i++) {
boolean validStartToken =
((conversionArray[i].startsWith("%")) || (conversionArray[i]
.startsWith("[%")));
if (validStartToken) {
String token = conversionArray[i].replace("[", "");
token = token.replace("]", "");
if (!validCodes.contains(token)) {
errorCode =
LoggingValidatorError.FORMAT_STRING_INVALID
.getId();
}
} else {
System.out.println("Token in error: " + conversionArray[i]);
errorCode =
LoggingValidatorError.FORMAT_STRING_INVALID.getId();
}
}
*/
}
return errorCode;
}
protected int validateMaxFileSize(RollingFileAppender fileAppender) {
int errorCode = OK;
String maxFileSizeStr = fileAppender.getMaxFileSize();
// Check if conversion pattern is blank or null
if (Validator.isBlankOrNull(maxFileSizeStr)) {
errorCode = LoggingValidatorError.MAX_FILE_SIZE_MISSING.getId();
} else {
String maxFileSizeNumOnly = null;
String unit = null;
// Separate the number from the units
if (!maxFileSizeStr.endsWith(byteStr)) {
maxFileSizeNumOnly = maxFileSizeStr;
} else {
unit = maxFileSizeStr.substring(maxFileSizeStr.length() - 2,
maxFileSizeStr.length());
maxFileSizeNumOnly = maxFileSizeStr.substring(0,
maxFileSizeStr.length() - 2);
}
// Check the validity of the number
try {
Long maxFileSize = new Long(maxFileSizeNumOnly);
Long max = null;
if (unit == null) {
max = Long.MAX_VALUE;
} else if (unit.equals(STLConstants.K0695_KB.getValue())) {
max = Long.MAX_VALUE / kiloBytes;
} else if (unit.equals(STLConstants.K0722_MB.getValue())) {
max = Long.MAX_VALUE / (kiloBytes * kiloBytes);
} else if (unit.equals(STLConstants.K0696_GB.getValue())) {
max = Long.MAX_VALUE / (kiloBytes * kiloBytes * kiloBytes);
} else {
// shouldn't happen
throw new IllegalArgumentException(
"Unknow unit '" + unit + "'");
}
if ((maxFileSize <= 0) || (max < maxFileSize)) {
LoggingValidatorError.data = max;
errorCode = LoggingValidatorError.MAX_FILE_SIZE_OUT_OF_RANGE
.getId();
}
} catch (NumberFormatException e) {
errorCode = LoggingValidatorError.MAX_FILE_SIZE_FORMAT_EXCEPTION
.getId();
}
}
return errorCode;
}
protected int validateMaxNumFiles(RollingFileAppender fileAppender) {
int errorCode = OK;
String maxNumFilesStr = fileAppender.getMaxNumOfBackUp();
try {
if (Validator.isBlankOrNull(maxNumFilesStr)) {
errorCode = LoggingValidatorError.MAX_NUM_FILES_MISSING.getId();
} else {
int maxNumFiles = Integer.parseInt(maxNumFilesStr);
// Check that the number is an integer
if ((Integer
.valueOf(maxNumFiles) instanceof Integer) == false) {
errorCode = LoggingValidatorError.MAX_NUM_FILES_INVALID_TYPE
.getId();
}
// Range check the max number of files
if ((maxNumFiles <= 0) || (MAX_BACKUP_FILES < maxNumFiles)) {
LoggingValidatorError.data = MAX_BACKUP_FILES;
errorCode = LoggingValidatorError.MAX_NUM_FILES_OUT_OF_RANGE
.getId();
}
}
} catch (NumberFormatException e) {
errorCode = LoggingValidatorError.MAX_NUM_FILES_FORMAT_EXCEPTION
.getId();
}
return errorCode;
}
protected int validateFileLocation(RollingFileAppender fileAppender) {
int errorCode = OK;
File file = new File(fileAppender.getFileLocation());
// Make sure the file location isn't null or blank
String fileLocationStr = fileAppender.getFileLocation();
if (fileLocationStr == null || fileLocationStr.equals("")) {
errorCode = LoggingValidatorError.FILE_LOCATION_MISSING.getId();
} else {
// Make sure this file location isn't a directory
if (file.isDirectory()) {
errorCode = LoggingValidatorError.FILE_LOCATION_DIRECTORY_ERROR
.getId();
} else {
// See if the file exists
if (!file.exists()) {
try {
if (!file.createNewFile()) {
errorCode =
LoggingValidatorError.FILE_LOCATION_CREATION_ERROR
.getId();
}
} catch (HeadlessException e) {
errorCode =
LoggingValidatorError.FILE_LOCATION_HEADLESS_ERROR
.getId();
} catch (IOException e) {
errorCode = LoggingValidatorError.FILE_LOCATION_IO_ERROR
.getId();
}
}
}
}
return errorCode;
}
}
|
karolciba/playground
|
probol/student.py
|
<gh_stars>0
#!/usr/bin/env python
from prob import P
from enum import Enum
from decimal import Decimal
class Difficulty(Enum):
d0 = 0
d1 = 1
class Intelligence(Enum):
i0 = 0
i1 = 1
class Grade(Enum):
g1 = 1
g2 = 2
g3 = 3
class Sat(Enum):
s0 = 0
s1 = 1
class Letter(Enum):
l0 = 0
l1 = 1
p_Intelligence = P(Intelligence)
p_Intelligence.table([[Intelligence.i0, 0.7],
[Intelligence.i1, 0.3]])
p_Difficulty = P(Difficulty)
p_Difficulty.table([[Difficulty.d0, 0.6],
[Difficulty.d1, 0.4]])
p_Sat_Intelligence = P(Sat).given(Intelligence)
p_Sat_Intelligence.table([[Intelligence.i0, Sat.s0, 0.95],
[Intelligence.i0, Sat.s1, 0.05],
[Intelligence.i1, Sat.s0, 0.2],
[Intelligence.i1, Sat.s1, 0.8]])
p_Grade_DifficultyIntelligence = P(Grade).given(Difficulty, Intelligence)
p_Grade_DifficultyIntelligence.table([[Intelligence.i0, Difficulty.d0, Grade.g1, 0.3],
[Intelligence.i0, Difficulty.d0, Grade.g2, 0.4],
[Intelligence.i0, Difficulty.d0, Grade.g3, 0.3],
[Intelligence.i0, Difficulty.d1, Grade.g1, 0.05],
[Intelligence.i0, Difficulty.d1, Grade.g2, 0.25],
[Intelligence.i0, Difficulty.d1, Grade.g3, 0.7],
[Intelligence.i1, Difficulty.d0, Grade.g1, 0.9],
[Intelligence.i1, Difficulty.d0, Grade.g2, 0.08],
[Intelligence.i1, Difficulty.d0, Grade.g3, 0.02],
[Intelligence.i1, Difficulty.d1, Grade.g1, 0.5],
[Intelligence.i1, Difficulty.d1, Grade.g2, 0.3],
[Intelligence.i1, Difficulty.d1, Grade.g3, 0.2]])
p_Letter_Grade = P(Letter).given(Grade)
p_Letter_Grade.table([[Grade.g1, Letter.l0, 0.1],
[Grade.g1, Letter.l1, 0.9],
[Grade.g2, Letter.l0, 0.4],
[Grade.g2, Letter.l1, 0.6],
[Grade.g3, Letter.l0, 0.99],
[Grade.g3, Letter.l1, 0.01]])
p_Joint = p_Letter_Grade * p_Grade_DifficultyIntelligence * p_Difficulty * p_Intelligence * p_Sat_Intelligence
p_Joint_no_Sat = p_Letter_Grade * p_Grade_DifficultyIntelligence * p_Difficulty * p_Intelligence
# d0 , g2 , i1 , l0 , s1 = 0.004608
assert p_Joint.query(Difficulty.d0, Grade.g2, Intelligence.i1, Letter.l0, Sat.s1) == Decimal('0.004608')
w_s1 = p_Joint.query(Difficulty.d0, Grade.g2, Intelligence.i1, Letter.l0, Sat.s1)
w_s0 = p_Joint.query(Difficulty.d0, Grade.g2, Intelligence.i1, Letter.l0, Sat.s0)
w = p_Joint_no_Sat.query(Difficulty.d0, Grade.g2, Intelligence.i1, Letter.l0) # == 0.00576
assert w == w_s1+w_s0, (w, w_s1 + w_s0)
print "Test"
# import pdb; pdb.set_trace()
assert p_Joint.query(Difficulty.d0, Grade.g2, Intelligence.i1, Letter.l0) == Decimal('0.00576')
|
Michelean/pandorajob
|
powerjob-server/powerjob-server-common/src/main/java/tech/powerjob/server/common/utils/ListUtils.java
|
package tech.powerjob.server.common.utils;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
/**
* User: zmx
*/
public class ListUtils {
public static <R, T> List<R> toList(List<T> list, Supplier<List<R>> supplier, Function<T, R> function) {
return stream(list).map(function).collect(Collectors.toCollection(supplier));
}
public static <T, R> List<R> toList(List<T> list, Function<T, R> function) {
return stream(list).map(function).collect(Collectors.toList());
}
public static <T, R> List<R> toUniqueList(List<T> list, Function<T, R> function) {
return stream(list).map(function).distinct().collect(Collectors.toList());
}
public static <T> boolean anyMatch(List<T> list, Predicate<T> predicate) {
return stream(list).anyMatch(predicate);
}
public static <T> boolean allMatch(List<T> list, Predicate<T> predicate) {
return stream(list).allMatch(predicate);
}
public static <R> List<R> filter(List<R> list, Predicate<R> predicate) {
return stream(list).filter(predicate).collect(Collectors.toList());
}
public static <T, R> List<R> filter(List<T> list, Predicate<T> predicate, Function<T, R> function) {
return stream(list).filter(predicate).map(function).collect(Collectors.toList());
}
public static <R> Set<R> filterSet(List<R> list, Predicate<R> predicate) {
return stream(list).filter(predicate).collect(Collectors.toSet());
}
public static <T, R> Set<R> filterSet(List<T> list, Predicate<T> predicate, Function<T, R> function) {
return stream(list).filter(predicate).map(function).collect(Collectors.toSet());
}
public static <T, R> List<T> distinctByProperty(List<T> list, Function<T, R> propertyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return stream(list).filter(t -> seen.add(propertyExtractor.apply(t))).collect(Collectors.toList());
}
public static <T, R> Set<R> toSet(List<T> list, Function<T, R> function) {
return stream(list).map(function).collect(Collectors.toSet());
}
public static <T, K> Map<K, T> toMap(List<T> list, Function<T, K> keyMapper) {
return toMap(list, keyMapper, t -> t);
}
public static <T, K, V> Map<K, V> toMap(List<T> list, Function<T, K> keyMapper, Function<T, V> valueMapper) {
return toMap(list, keyMapper, valueMapper, (v, v2) -> v);
}
public static <T, K> Map<K, T> toMap(List<T> list, Function<T, K> keyMapper, BinaryOperator<T> mergeFunction) {
return toMap(list, keyMapper, t -> t, mergeFunction);
}
public static <T, K, V> Map<K, V> toMap(List<T> list, Function<T, K> keyMapper, Function<T, V> valueMapper, BinaryOperator<V> mergeFunction) {
return stream(list).collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction));
}
public static <K, T> Map<K, List<T>> group(List<T> list, Function<T, K> function) {
return stream(list).collect(groupingBy(function));
}
public static <K, T, R> Map<K, List<R>> group(List<T> list, Function<T, K> function, Function<T, R> convert) {
return stream(list).collect(groupingBy(function, mapping(convert, Collectors.toList())));
}
public static <K, T> Map<K, Set<T>> groupSet(List<T> list, Function<T, K> function) {
return stream(list).collect(groupingBy(function, Collectors.toSet()));
}
public static <K, T, R> Map<K, Set<R>> groupSet(List<T> list, Function<T, K> function, Function<T, R> convert) {
return stream(list).collect(groupingBy(function, mapping(convert, Collectors.toSet())));
}
public static List<String> toList(String str, String separatorChars) {
if (StringUtils.isBlank(str)) {
return Collections.emptyList();
}
return Arrays.asList(StringUtils.split(str, separatorChars));
}
private static <T> Stream<T> stream(List<T> list) {
return list.parallelStream();
}
}
|
Jwomers/trinity
|
eth2/beacon/state_machines/forks/serenity/epoch_processing.py
|
from typing import (
Iterable,
Sequence,
Tuple,
)
from eth_utils import to_tuple
from eth2.beacon import helpers
from eth2._utils.numeric import (
is_power_of_two,
)
from eth2._utils.tuple import (
update_tuple_item,
)
from eth2.beacon.exceptions import (
NoWinningRootError,
)
from eth2.beacon.committee_helpers import (
get_crosslink_committees_at_slot,
get_current_epoch_committee_count,
)
from eth2.beacon.epoch_processing_helpers import (
get_current_epoch_attestations,
get_previous_epoch_attestations,
get_winning_root,
)
from eth2.beacon.helpers import (
get_active_validator_indices,
get_effective_balance,
get_epoch_start_slot,
get_randao_mix,
slot_to_epoch,
)
from eth2.beacon.typing import ShardNumber
from eth2.beacon._utils.hash import (
hash_eth2,
)
from eth2.beacon.types.attestations import Attestation
from eth2.beacon.types.crosslink_records import CrosslinkRecord
from eth2.beacon.types.states import BeaconState
from eth2.beacon.state_machines.configs import BeaconConfig
#
# Crosslinks
#
@to_tuple
def _filter_attestations_by_shard(
attestations: Sequence[Attestation],
shard: ShardNumber) -> Iterable[Attestation]:
for attestation in attestations:
if attestation.data.shard == shard:
yield attestation
def process_crosslinks(state: BeaconState, config: BeaconConfig) -> BeaconState:
"""
Implement 'per-epoch-processing.crosslinks' portion of Phase 0 spec:
https://github.com/ethereum/eth2.0-specs/blob/master/specs/core/0_beacon-chain.md#crosslinks
For each shard from the past two epochs, find the shard block
root that has been attested to by the most stake.
If enough(>= 2/3 total stake) attesting stake, update the crosslink record of that shard.
Return resulting ``state``
"""
latest_crosslinks = state.latest_crosslinks
previous_epoch_attestations = get_previous_epoch_attestations(
state,
config.EPOCH_LENGTH,
config.GENESIS_EPOCH,
)
current_epoch_attestations = get_current_epoch_attestations(state, config.EPOCH_LENGTH)
prev_epoch_start_slot = get_epoch_start_slot(
state.previous_epoch(config.EPOCH_LENGTH, config.GENESIS_EPOCH),
config.EPOCH_LENGTH,
)
next_epoch_start_slot = get_epoch_start_slot(
state.next_epoch(config.EPOCH_LENGTH),
config.EPOCH_LENGTH,
)
for slot in range(prev_epoch_start_slot, next_epoch_start_slot):
crosslink_committees_at_slot = get_crosslink_committees_at_slot(
state,
slot,
config.GENESIS_EPOCH,
config.EPOCH_LENGTH,
config.TARGET_COMMITTEE_SIZE,
config.SHARD_COUNT,
)
for crosslink_committee, shard in crosslink_committees_at_slot:
try:
winning_root, total_attesting_balance = get_winning_root(
state=state,
shard=shard,
# Use `_filter_attestations_by_shard` to filter out attestations
# not attesting to this shard so we don't need to going over
# irrelevent attestations over and over again.
attestations=_filter_attestations_by_shard(
previous_epoch_attestations + current_epoch_attestations,
shard,
),
genesis_epoch=config.GENESIS_EPOCH,
epoch_length=config.EPOCH_LENGTH,
max_deposit_amount=config.MAX_DEPOSIT_AMOUNT,
target_committee_size=config.TARGET_COMMITTEE_SIZE,
shard_count=config.SHARD_COUNT,
)
except NoWinningRootError:
# No winning shard block root found for this shard.
pass
else:
total_balance = sum(
get_effective_balance(state.validator_balances, i, config.MAX_DEPOSIT_AMOUNT)
for i in crosslink_committee
)
if 3 * total_attesting_balance >= 2 * total_balance:
latest_crosslinks = update_tuple_item(
latest_crosslinks,
shard,
CrosslinkRecord(
epoch=state.current_epoch(config.EPOCH_LENGTH),
shard_block_root=winning_root,
),
)
else:
# Don't update the crosslink of this shard
pass
state = state.copy(
latest_crosslinks=latest_crosslinks,
)
return state
#
# Validator registry and shuffling seed data
#
def _check_if_update_validator_registry(state: BeaconState,
config: BeaconConfig) -> Tuple[bool, int]:
if state.finalized_epoch <= state.validator_registry_update_epoch:
return False, 0
num_shards_in_committees = get_current_epoch_committee_count(
state,
shard_count=config.SHARD_COUNT,
epoch_length=config.EPOCH_LENGTH,
target_committee_size=config.TARGET_COMMITTEE_SIZE,
)
# Get every shard in the current committees
shards = set(
(state.current_epoch_start_shard + i) % config.SHARD_COUNT
for i in range(num_shards_in_committees)
)
for shard in shards:
if state.latest_crosslinks[shard].epoch <= state.validator_registry_update_epoch:
return False, 0
return True, num_shards_in_committees
def update_validator_registry(state: BeaconState) -> BeaconState:
# TODO
return state
def _update_latest_index_roots(state: BeaconState,
config: BeaconConfig) -> BeaconState:
"""
Return the BeaconState with updated `latest_index_roots`.
"""
next_epoch = state.next_epoch(config.EPOCH_LENGTH)
# TODO: chanege to hash_tree_root
active_validator_indices = get_active_validator_indices(
state.validator_registry,
next_epoch,
)
index_root = hash_eth2(
b''.join(
[
index.to_bytes(32, 'big')
for index in active_validator_indices
]
)
)
latest_index_roots = update_tuple_item(
state.latest_index_roots,
next_epoch % config.LATEST_INDEX_ROOTS_LENGTH,
index_root,
)
return state.copy(
latest_index_roots=latest_index_roots,
)
def process_validator_registry(state: BeaconState,
config: BeaconConfig) -> BeaconState:
state = state.copy(
previous_calculation_epoch=state.current_calculation_epoch,
previous_epoch_start_shard=state.current_epoch_start_shard,
previous_epoch_seed=state.current_epoch_seed,
)
state = _update_latest_index_roots(state, config)
need_to_update, num_shards_in_committees = _check_if_update_validator_registry(state, config)
if need_to_update:
state = update_validator_registry(state)
# Update step-by-step since updated `state.current_calculation_epoch`
# is used to calculate other value). Follow the spec tightly now.
state = state.copy(
current_calculation_epoch=state.next_epoch(config.EPOCH_LENGTH),
)
state = state.copy(
current_epoch_start_shard=(
state.current_epoch_start_shard + num_shards_in_committees
) % config.SHARD_COUNT,
)
# The `helpers.generate_seed` function is only present to provide an entry point
# for mocking this out in tests.
current_epoch_seed = helpers.generate_seed(
state=state,
epoch=state.current_calculation_epoch,
epoch_length=config.EPOCH_LENGTH,
seed_lookahead=config.SEED_LOOKAHEAD,
entry_exit_delay=config.ENTRY_EXIT_DELAY,
latest_index_roots_length=config.LATEST_INDEX_ROOTS_LENGTH,
latest_randao_mixes_length=config.LATEST_RANDAO_MIXES_LENGTH,
)
state = state.copy(
current_epoch_seed=current_epoch_seed,
)
else:
epochs_since_last_registry_change = (
state.current_epoch(config.EPOCH_LENGTH) - state.validator_registry_update_epoch
)
if is_power_of_two(epochs_since_last_registry_change):
# Update step-by-step since updated `state.current_calculation_epoch`
# is used to calculate other value). Follow the spec tightly now.
state = state.copy(
current_calculation_epoch=state.next_epoch(config.EPOCH_LENGTH),
)
# The `helpers.generate_seed` function is only present to provide an entry point
# for mocking this out in tests.
current_epoch_seed = helpers.generate_seed(
state=state,
epoch=state.current_calculation_epoch,
epoch_length=config.EPOCH_LENGTH,
seed_lookahead=config.SEED_LOOKAHEAD,
entry_exit_delay=config.ENTRY_EXIT_DELAY,
latest_index_roots_length=config.LATEST_INDEX_ROOTS_LENGTH,
latest_randao_mixes_length=config.LATEST_RANDAO_MIXES_LENGTH,
)
state = state.copy(
current_epoch_seed=current_epoch_seed,
)
else:
pass
return state
#
# Final updates
#
def process_final_updates(state: BeaconState,
config: BeaconConfig) -> BeaconState:
current_epoch = state.current_epoch(config.EPOCH_LENGTH)
next_epoch = state.next_epoch(config.EPOCH_LENGTH)
state = state.copy(
latest_penalized_balances=update_tuple_item(
state.latest_penalized_balances,
next_epoch % config.LATEST_PENALIZED_EXIT_LENGTH,
state.latest_penalized_balances[current_epoch % config.LATEST_PENALIZED_EXIT_LENGTH],
),
latest_randao_mixes=update_tuple_item(
state.latest_randao_mixes,
next_epoch % config.LATEST_PENALIZED_EXIT_LENGTH,
get_randao_mix(
state=state,
epoch=current_epoch,
epoch_length=config.EPOCH_LENGTH,
latest_randao_mixes_length=config.LATEST_RANDAO_MIXES_LENGTH,
),
),
)
latest_attestations = tuple(
filter(
lambda attestation: (
slot_to_epoch(attestation.data.slot, config.EPOCH_LENGTH) >= current_epoch
),
state.latest_attestations
)
)
state = state.copy(
latest_attestations=latest_attestations,
)
return state
|
przemek83/data-explorer-go
|
internal/column_numeric.go
|
<filename>internal/column_numeric.go
package internal
// ColumnNumeric - numeric column struct.
type ColumnNumeric struct {
data []int
}
// GetType - get type of column.
func (column *ColumnNumeric) GetType() ColumnType {
return NumericColumn
}
// GetSize - Get number of elements in column.
func (column *ColumnNumeric) GetSize() int {
return len(column.data)
}
// Append - append value to column end.
func (column *ColumnNumeric) Append(value int) {
column.data = append(column.data, value)
}
// Get - get value for given index.
func (column *ColumnNumeric) Get(index int) int {
return column.data[index]
}
|
ExpandiumSAS/cxxutils
|
sources/libraries/cxxu/cxxu/daemon.cpp
|
<reponame>ExpandiumSAS/cxxutils
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#include <stdlib.h>
#include <unistd.h>
#include <cxxu/daemon.hpp>
#include <cxxu/logging.hpp>
#include <cxxu/signaler.hpp>
namespace cxxu {
daemon::daemon(const std::string& name)
: name_(name)
{}
daemon::~daemon()
{}
void
daemon::operator()(bool daemonize)
{
if (daemonize) {
if (::daemon(0, 0) == -1) {
CXXU_SYSDIE("failed to daemonize");
}
cxxu::logger::get().daemon(true, name_);
}
auto &s = cxxu::signaler::get();
s.register_signal(
cxxu::signal::reconfig,
[this](cxxu::signal sig) { reconfig(); }
);
s.register_signal(
cxxu::signal::quit,
[this](cxxu::signal sig) { quit(); }
);
s.register_signal(
cxxu::signal::user1,
[this](cxxu::signal sig) { user1(); }
);
s.register_signal(
cxxu::signal::user2,
[this](cxxu::signal sig) { user2(); }
);
init();
run();
}
void
daemon::init()
{}
void
daemon::reconfig()
{}
void
daemon::user1()
{}
void
daemon::user2()
{}
} // namespace cxxu
|
KartikChugh/Jeras
|
src/kc/ml/jeras/_testing/InitializerTests.java
|
package kc.ml.jeras._testing;
import kc.ml.jeras.architecture.Dense;
import kc.ml.jeras.architecture.Input;
import kc.ml.jeras.architecture.Sequential;
import static kc.ml.jeras.initializers.Initializers.*;
public class InitializerTests {
public static void main(String[] args) {
final long init = System.currentTimeMillis();
Sequential s = new Sequential();
s.add(new Input(2).withWeightInitializer(RANDOM_NORMAL).withBiasInitializer(ZEROS));
s.add(new Dense(16).withWeightInitializer(GLOROT_UNIFORM));
s.add(new Dense(16).withWeightInitializer(GLOROT_UNIFORM));
s.add(new Dense(8).withWeightInitializer(RANDOM_NORMAL.withStdDev(0.001)));
s.add(new Dense(2).withWeightInitializer(CONSTANT.withValue(0.5)));
s.add(new Dense(1));
s.compile();
System.out.println(System.currentTimeMillis() - init);
/* for (int i = 0; i < 10; i++) {
double w = ru.nextWeight();
System.out.println(w);
if (Math.abs(w) >= Math.sqrt(3.0/2)) {
throw new AssertionError(w);
}
}*/
}
}
|
xiang12835/mall-platform
|
mall-api/src/main/java/ltd/newbee/mall/service/impl/NewBeeMallUserAddressServiceImpl.java
|
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2020 十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.newbee.mall.service.impl;
import ltd.newbee.mall.api.vo.NewBeeMallUserAddressVO;
import ltd.newbee.mall.common.NewBeeMallException;
import ltd.newbee.mall.common.ServiceResultEnum;
import ltd.newbee.mall.dao.MallUserAddressMapper;
import ltd.newbee.mall.entity.MallUserAddress;
import ltd.newbee.mall.service.NewBeeMallUserAddressService;
import ltd.newbee.mall.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@Service
public class NewBeeMallUserAddressServiceImpl implements NewBeeMallUserAddressService {
@Autowired
private MallUserAddressMapper userAddressMapper;
@Override
public List<NewBeeMallUserAddressVO> getMyAddresses(Long userId) {
List<MallUserAddress> myAddressList = userAddressMapper.findMyAddressList(userId);
List<NewBeeMallUserAddressVO> newBeeMallUserAddressVOS = BeanUtil.copyList(myAddressList, NewBeeMallUserAddressVO.class);
return newBeeMallUserAddressVOS;
}
@Override
@Transactional
public Boolean saveUserAddress(MallUserAddress mallUserAddress) {
Date now = new Date();
if (mallUserAddress.getDefaultFlag().intValue() == 1) {
//添加默认地址,需要将原有的默认地址修改掉
MallUserAddress defaultAddress = userAddressMapper.getMyDefaultAddress(mallUserAddress.getUserId());
if (defaultAddress != null) {
defaultAddress.setDefaultFlag((byte) 0);
defaultAddress.setUpdateTime(now);
int updateResult = userAddressMapper.updateByPrimaryKeySelective(defaultAddress);
if (updateResult < 1) {
//未更新成功
NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
}
}
}
return userAddressMapper.insertSelective(mallUserAddress) > 0;
}
@Override
public Boolean updateMallUserAddress(MallUserAddress mallUserAddress) {
MallUserAddress tempAddress = getMallUserAddressById(mallUserAddress.getAddressId());
Date now = new Date();
if (mallUserAddress.getDefaultFlag().intValue() == 1) {
//修改为默认地址,需要将原有的默认地址修改掉
MallUserAddress defaultAddress = userAddressMapper.getMyDefaultAddress(mallUserAddress.getUserId());
if (defaultAddress != null && !defaultAddress.getAddressId().equals(tempAddress)) {
//存在默认地址且默认地址并不是当前修改的地址
defaultAddress.setDefaultFlag((byte) 0);
defaultAddress.setUpdateTime(now);
int updateResult = userAddressMapper.updateByPrimaryKeySelective(defaultAddress);
if (updateResult < 1) {
//未更新成功
NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
}
}
}
mallUserAddress.setUpdateTime(now);
return userAddressMapper.updateByPrimaryKeySelective(mallUserAddress) > 0;
}
@Override
public MallUserAddress getMallUserAddressById(Long addressId) {
MallUserAddress mallUserAddress = userAddressMapper.selectByPrimaryKey(addressId);
if (mallUserAddress == null) {
NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
return mallUserAddress;
}
@Override
public MallUserAddress getMyDefaultAddressByUserId(Long userId) {
return userAddressMapper.getMyDefaultAddress(userId);
}
@Override
public Boolean deleteById(Long addressId) {
return userAddressMapper.deleteByPrimaryKey(addressId) > 0;
}
}
|
ghuntley/COVIDSafe_1.0.11.apk
|
src/sources/rx/internal/operators/BlockingOperatorLatest.java
|
package rx.internal.operators;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import rx.Notification;
import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
public final class BlockingOperatorLatest {
private BlockingOperatorLatest() {
throw new IllegalStateException("No instances!");
}
public static <T> Iterable<T> latest(final Observable<? extends T> observable) {
return new Iterable<T>() {
public Iterator<T> iterator() {
LatestObserverIterator latestObserverIterator = new LatestObserverIterator();
observable.materialize().subscribe(latestObserverIterator);
return latestObserverIterator;
}
};
}
static final class LatestObserverIterator<T> extends Subscriber<Notification<? extends T>> implements Iterator<T> {
Notification<? extends T> iteratorNotification;
final Semaphore notify = new Semaphore(0);
final AtomicReference<Notification<? extends T>> value = new AtomicReference<>();
public void onCompleted() {
}
public void onError(Throwable th) {
}
LatestObserverIterator() {
}
public void onNext(Notification<? extends T> notification) {
if (this.value.getAndSet(notification) == null) {
this.notify.release();
}
}
public boolean hasNext() {
Notification<? extends T> notification = this.iteratorNotification;
if (notification == null || !notification.isOnError()) {
Notification<? extends T> notification2 = this.iteratorNotification;
if ((notification2 == null || !notification2.isOnCompleted()) && this.iteratorNotification == null) {
try {
this.notify.acquire();
Notification<? extends T> andSet = this.value.getAndSet((Object) null);
this.iteratorNotification = andSet;
if (andSet.isOnError()) {
throw Exceptions.propagate(this.iteratorNotification.getThrowable());
}
} catch (InterruptedException e) {
unsubscribe();
Thread.currentThread().interrupt();
this.iteratorNotification = Notification.createOnError(e);
throw Exceptions.propagate(e);
}
}
return !this.iteratorNotification.isOnCompleted();
}
throw Exceptions.propagate(this.iteratorNotification.getThrowable());
}
public T next() {
if (!hasNext() || !this.iteratorNotification.isOnNext()) {
throw new NoSuchElementException();
}
T value2 = this.iteratorNotification.getValue();
this.iteratorNotification = null;
return value2;
}
public void remove() {
throw new UnsupportedOperationException("Read-only iterator.");
}
}
}
|
AlCash07/ACTL
|
include/actl/operation/scalar/arithmetic/all.hpp
|
// Copyright 2021 <NAME>.
//
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#pragma once
#include <actl/operation/scalar/arithmetic/add.hpp>
#include <actl/operation/scalar/arithmetic/div.hpp>
#include <actl/operation/scalar/arithmetic/mul.hpp>
#include <actl/operation/scalar/arithmetic/neg.hpp>
#include <actl/operation/scalar/arithmetic/sub.hpp>
|
lemkova/Yorozuya
|
YorozuyaGSLib/source/CNationSettingFactoryGroupDetail.cpp
|
#include <CNationSettingFactoryGroupDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Detail
{
Info::CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_ptr CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_next(nullptr);
Info::CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_clbk CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_user(nullptr);
Info::CNationSettingFactoryGroupCreate4_ptr CNationSettingFactoryGroupCreate4_next(nullptr);
Info::CNationSettingFactoryGroupCreate4_clbk CNationSettingFactoryGroupCreate4_user(nullptr);
Info::CNationSettingFactoryGroupInit6_ptr CNationSettingFactoryGroupInit6_next(nullptr);
Info::CNationSettingFactoryGroupInit6_clbk CNationSettingFactoryGroupInit6_user(nullptr);
Info::CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_ptr CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_next(nullptr);
Info::CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_clbk CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_user(nullptr);
void CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_wrapper(struct CNationSettingFactoryGroup* _this)
{
CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_user(_this, CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_next);
};
struct CNationSettingData* CNationSettingFactoryGroupCreate4_wrapper(struct CNationSettingFactoryGroup* _this, int iNationCode, char* szNationCodeStr, bool bServiceMode)
{
return CNationSettingFactoryGroupCreate4_user(_this, iNationCode, szNationCodeStr, bServiceMode, CNationSettingFactoryGroupCreate4_next);
};
int CNationSettingFactoryGroupInit6_wrapper(struct CNationSettingFactoryGroup* _this)
{
return CNationSettingFactoryGroupInit6_user(_this, CNationSettingFactoryGroupInit6_next);
};
void CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_wrapper(struct CNationSettingFactoryGroup* _this)
{
CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_user(_this, CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_next);
};
::std::array<hook_record, 4> CNationSettingFactoryGroup_functions =
{
_hook_record {
(LPVOID)0x140229810L,
(LPVOID *)&CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_user,
(LPVOID *)&CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_next,
(LPVOID)cast_pointer_function(CNationSettingFactoryGroupctor_CNationSettingFactoryGroup2_wrapper),
(LPVOID)cast_pointer_function((void(CNationSettingFactoryGroup::*)())&CNationSettingFactoryGroup::ctor_CNationSettingFactoryGroup)
},
_hook_record {
(LPVOID)0x140229750L,
(LPVOID *)&CNationSettingFactoryGroupCreate4_user,
(LPVOID *)&CNationSettingFactoryGroupCreate4_next,
(LPVOID)cast_pointer_function(CNationSettingFactoryGroupCreate4_wrapper),
(LPVOID)cast_pointer_function((struct CNationSettingData*(CNationSettingFactoryGroup::*)(int, char*, bool))&CNationSettingFactoryGroup::Create)
},
_hook_record {
(LPVOID)0x1402178a0L,
(LPVOID *)&CNationSettingFactoryGroupInit6_user,
(LPVOID *)&CNationSettingFactoryGroupInit6_next,
(LPVOID)cast_pointer_function(CNationSettingFactoryGroupInit6_wrapper),
(LPVOID)cast_pointer_function((int(CNationSettingFactoryGroup::*)())&CNationSettingFactoryGroup::Init)
},
_hook_record {
(LPVOID)0x140229860L,
(LPVOID *)&CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_user,
(LPVOID *)&CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_next,
(LPVOID)cast_pointer_function(CNationSettingFactoryGroupdtor_CNationSettingFactoryGroup8_wrapper),
(LPVOID)cast_pointer_function((void(CNationSettingFactoryGroup::*)())&CNationSettingFactoryGroup::dtor_CNationSettingFactoryGroup)
},
};
}; // end namespace Detail
END_ATF_NAMESPACE
|
npocmaka/Windows-Server-2003
|
inetcore/mshtml/src/other/moniker/abtprot.cxx
|
<filename>inetcore/mshtml/src/other/moniker/abtprot.cxx
//+---------------------------------------------------------------------------
//
// Microsoft Forms
// Copyright (C) Microsoft Corporation, 1996
//
// File: abtprot.cxx
//
// Contents: Implementation of the about protocol
//
// History: 07-23-97 krisma Created
//
//----------------------------------------------------------------------------
#include "headers.hxx"
#ifndef X_ABTPROT_HXX_
#define X_ABTPROT_HXX_
#include "abtprot.hxx"
#endif
#ifndef X_OTHRGUID_H_
#define X_OTHRGUID_H_
#include "othrguid.h"
#endif
#ifndef X_ROSTM_HXX_
#define X_ROSTM_HXX_
#include "rostm.hxx"
#endif
#ifndef X_UWININET_H_
#define X_UWININET_H_
#include "uwininet.h"
#endif
#ifndef X_SHELLAPI_H_
#define X_SHELLAPI_H_
#include <shellapi.h> // for the definition of ShellExecuteA (for AXP)
#endif
MtDefine(Protocols, Mem, "Protocols")
MtDefine(CAboutProtocol, Protocols, "CAboutProtocol")
// Some Static strings that we use to read from the registry
static TCHAR szAboutKey[] =
_T("SOFTWARE\\Microsoft\\Internet Explorer\\AboutURLs");
extern BOOL g_fInIexplorer;
extern BOOL g_fInExplorer;
//+---------------------------------------------------------------------------
//
// Function: CreateAboutProtocol
//
// Synopsis: Creates an about Async Pluggable protocol
//
// Arguments: pUnkOuter Controlling IUnknown
//
//----------------------------------------------------------------------------
CBase *
CreateAboutProtocol(IUnknown *pUnkOuter)
{
return new CAboutProtocol(pUnkOuter);
}
CAboutProtocolCF g_cfAboutProtocol(CreateAboutProtocol);
#define GetStdLocationORD 150
typedef HRESULT (APIENTRY* PFNGETSTDLOCATION)(LPTSTR pszPath, DWORD cchPath, UINT id);
HRESULT GetShellStdLocation(LPTSTR lpszBuffer, DWORD cchBuffer, DWORD dwID)
{
HRESULT hres = E_FAIL;
HINSTANCE hinst;
if (0 < cchBuffer)
*lpszBuffer = 0;
hinst = LoadLibrary(TEXT("shdocvw.dll"));
if (hinst)
{
PFNGETSTDLOCATION pfn = (PFNGETSTDLOCATION)GetProcAddress(hinst, MAKEINTRESOURCEA(GetStdLocationORD));
if (pfn)
{
hres = pfn(lpszBuffer, cchBuffer, dwID);
}
FreeLibrary(hinst);
}
return hres;
}
HRESULT
CAboutProtocolCF::QueryInfo(
LPCWSTR pwzUrl,
QUERYOPTION QueryOption,
DWORD dwQueryFlags,
LPVOID pvBuffer,
DWORD cbBuffer,
DWORD * pcbBuffer,
DWORD dwReserved)
{
HRESULT hr;
HKEY hkey = NULL;
TCHAR * szRegValue;
LONG lRegErrorValue;
TCHAR szBuffer[pdlUrlLen];
DWORD dwType;
DWORD cbData = sizeof(szBuffer);
DWORD dwRetval;
//
// Before resolving through registry, see if the \1 part forces the URL to be unsecure
//
if (QueryOption == QUERY_IS_SECURE && !HasSecureContext(pwzUrl))
{
dwRetval = FALSE;
goto ReturnDword;
}
szRegValue = _tcschr(pwzUrl, ':');
szRegValue += 1;
lRegErrorValue = RegOpenKeyEx(
HKEY_LOCAL_MACHINE, szAboutKey, NULL, KEY_READ,
&hkey);
if (lRegErrorValue != ERROR_SUCCESS)
{
hr = INET_E_DEFAULT_ACTION;
goto Cleanup;
}
lRegErrorValue = SHQueryValueEx(hkey, szRegValue, NULL, &dwType, (LPBYTE)szBuffer, &cbData);
if (lRegErrorValue == ERROR_SUCCESS)
{
// If the value is in the registry as a DWORD then it must be a special Shell location. Map the ID to the URL
// by passing it to GetStdLocation.
if (dwType == REG_DWORD)
{
if (FAILED(GetShellStdLocation(szBuffer, ARRAY_SIZE(szBuffer), *((LPDWORD)szBuffer))))
{
hr = INET_E_DEFAULT_ACTION;
goto Cleanup;
}
}
hr = THR(CoInternetQueryInfo(szBuffer, QueryOption, dwQueryFlags, pvBuffer, cbBuffer, pcbBuffer, dwReserved));
}
else
{
switch (QueryOption)
{
case QUERY_USES_NETWORK:
case QUERY_IS_CACHED:
dwRetval = FALSE;
goto ReturnDword;
case QUERY_IS_SECURE:
dwRetval = TRUE;
goto ReturnDword;
default:
hr = INET_E_DEFAULT_ACTION;
break;
}
}
Cleanup:
if (hkey)
RegCloseKey(hkey);
RRETURN1(hr, INET_E_DEFAULT_ACTION);
ReturnDword:
if (!pvBuffer || cbBuffer < sizeof(DWORD))
{
hr = E_FAIL;
goto Cleanup;
}
if (pcbBuffer)
{
*pcbBuffer = sizeof(DWORD);
}
*(DWORD *)pvBuffer = dwRetval;
hr = S_OK;
goto Cleanup;
}
//+---------------------------------------------------------------------------
//
// Method: CAboutProtocolCF::ParseUrl
//
// Synopsis: per IInternetProtocolInfo. Reads new URL from
// registry and replaces the about: URL.
//
//----------------------------------------------------------------------------
HRESULT
CAboutProtocolCF::ParseUrl(
LPCWSTR pwzUrl,
PARSEACTION ParseAction,
DWORD dwFlags,
LPWSTR pwzResult,
DWORD cchResult,
DWORD * pcchResult,
DWORD dwReserved)
{
CStr cstr;
HRESULT hr = INET_E_DEFAULT_ACTION;
HKEY hkey = NULL;
TCHAR *szRegValue;
TCHAR *pchSourceUrl = NULL;
LONG lRegErrorValue;
DWORD dwType;
if (!pcchResult || !pwzResult)
{
hr = E_POINTER;
goto Cleanup;
}
if (ParseAction == PARSE_CANONICALIZE)
{
static TCHAR szBuffer[pdlUrlLen];
DWORD cbData = sizeof(szBuffer);
//
// Search for an embedded \1. If it's found, then strip it
// out because that's the source url of this protocol.
//
pchSourceUrl = _tcschr(pwzUrl, _T('\1'));
hr = pchSourceUrl ?
THR(cstr.Set(pwzUrl, pchSourceUrl - pwzUrl)) :
THR(cstr.Set(pwzUrl));
szRegValue = _tcschr(cstr, ':');
szRegValue += 1;
//
// Special case for about:blank so
// we don't lose security info
//
if (!_tcsicmp(_T("blank"), szRegValue))
{
hr = THR(super::ParseUrl(
pwzUrl,
ParseAction,
dwFlags,
pwzResult,
cchResult,
pcchResult,
dwReserved));
goto Cleanup;
}
lRegErrorValue = RegOpenKeyEx(
HKEY_LOCAL_MACHINE, szAboutKey, NULL, KEY_READ,
&hkey);
if (lRegErrorValue != ERROR_SUCCESS)
{
hr=INET_E_DEFAULT_ACTION;
goto Cleanup;
}
lRegErrorValue = SHQueryValueEx(
hkey, szRegValue, NULL, &dwType, (LPBYTE)szBuffer, &cbData);
if (lRegErrorValue == ERROR_SUCCESS)
{
// If the value is in the registry as a DWORD then it must be a special Shell location. Map the ID to the URL
// by passing it to GetStdLocation.
if (dwType == REG_DWORD)
{
if (FAILED(GetShellStdLocation(szBuffer, ARRAY_SIZE(szBuffer), *((LPDWORD)szBuffer))))
{
hr = INET_E_DEFAULT_ACTION;
goto Cleanup;
}
}
}
else
{
//
// If the registry value does not exist, procede as
// normal (write the string to the document).
//
// [kusumav] 03/07/2002 - Disabled about protocol except for ones we register
// We now navigate to about:NavigationCanceled for any about URL except
// the ones in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\AboutURLs
// This is the first place where we block non-blessed about urls.
// If we don't find the NavigationCanceled key, then our protocol handler will
// be called and we return E_ACCESSDENIED in the Start method which will
// effectively block whatever slips through this check
//
//
lRegErrorValue = SHQueryValueEx(
hkey, L"NavigationCanceled", NULL, &dwType, (LPBYTE)szBuffer, &cbData);
if ((!g_fInExplorer && !g_fInIexplorer) || (lRegErrorValue != ERROR_SUCCESS && (dwType != REG_SZ)))
{
hr = THR(super::ParseUrl(
pwzUrl,
ParseAction,
dwFlags,
pwzResult,
cchResult,
pcchResult,
dwReserved));
goto Cleanup;
}
}
*pcchResult = cchResult;
hr = UrlCanonicalize(szBuffer, pwzResult, pcchResult, dwFlags);
}
else if (ParseAction == PARSE_SECURITY_URL)
{
hr = THR(UnwrapSpecialUrl(pwzUrl, cstr));
if (hr)
goto Cleanup;
*pcchResult = cstr.Length() + 1;
if (cstr.Length() + 1 > cchResult)
{
// Not enough room, so fill in *pcchResult with size we need
hr = S_FALSE;
goto Cleanup;
}
_tcscpy(pwzResult, cstr);
}
else
{
hr = THR_NOTRACE(super::ParseUrl(
pwzUrl,
ParseAction,
dwFlags,
pwzResult,
cchResult,
pcchResult,
dwReserved));
}
Cleanup:
if (hkey)
RegCloseKey(hkey);
RRETURN2(hr, INET_E_DEFAULT_ACTION, S_FALSE);
}
const CBase::CLASSDESC CAboutProtocol::s_classdesc =
{
&CLSID_AboutProtocol, // _pclsid
};
//+---------------------------------------------------------------------------
//
// Method: CAboutProtocol::CAboutProtocol
//
// Synopsis: ctor
//
//----------------------------------------------------------------------------
CAboutProtocol::CAboutProtocol(IUnknown *pUnkOuter) : super(pUnkOuter)
{
}
//+---------------------------------------------------------------------------
//
// Method: CAboutProtocol::~CAboutProtocol
//
// Synopsis: dtor
//
//----------------------------------------------------------------------------
CAboutProtocol::~CAboutProtocol()
{
}
//+---------------------------------------------------------------------------
//
// Method: CAboutProtocol::Start
//
// Synopsis: per IInternetProtocol
//
//----------------------------------------------------------------------------
HRESULT
CAboutProtocol::Start(
LPCWSTR pchUrl,
IInternetProtocolSink *pTrans,
IInternetBindInfo *pOIBindInfo,
DWORD grfSTI,
HANDLE_PTR dwReserved)
{
HRESULT hr = NOERROR;
TCHAR ach[pdlUrlLen];
DWORD dwSize;
Assert(!_pProtSink && pOIBindInfo && pTrans && !_cstrURL);
if ( !(grfSTI & PI_PARSE_URL))
{
if ((g_fInExplorer || g_fInIexplorer) && _tcsicmp(_T("about:blank"), pchUrl))
{
// Block all about urls. Return E_ACCESSDENIED instead of E_FAIL
// since Trident doesn't handle all errors, it will handle this one correctly
// We will never come to this codepath for the blessed about urls
// since we map them to res:// urls in our ParseAndBind method above
hr = E_ACCESSDENIED;
goto Cleanup;
}
ReplaceInterface(&_pProtSink, pTrans);
ReplaceInterface(&_pOIBindInfo, pOIBindInfo);
}
_bindinfo.cbSize = sizeof(BINDINFO);
hr = THR(pOIBindInfo->GetBindInfo(&_grfBindF, &_bindinfo));
//
// First get the basic url. Unescape it first.
//
hr = THR(CoInternetParseUrl(pchUrl, PARSE_ENCODE, 0, ach, ARRAY_SIZE(ach), &dwSize, 0));
if (hr)
goto Cleanup;
hr = THR(_cstrURL.Set(ach));
if (hr)
goto Cleanup;
//
// Now append any extra data if needed.
//
if (_bindinfo.szExtraInfo)
{
hr = THR(_cstrURL.Append(_bindinfo.szExtraInfo));
if (hr)
goto Cleanup;
}
_grfSTI = grfSTI;
//
// If forced to go async, return E_PENDING now, and
// perform binding when we get the Continue.
//
if (grfSTI & PI_FORCE_ASYNC)
{
PROTOCOLDATA protdata;
hr = E_PENDING;
protdata.grfFlags = PI_FORCE_ASYNC;
protdata.dwState = BIND_ASYNC;
protdata.pData = NULL;
protdata.cbData = 0;
_pProtSink->Switch(&protdata);
}
else
{
hr = THR(ParseAndBind());
}
Cleanup:
RRETURN(hr);
}
//+---------------------------------------------------------------------------
//
// Method: CAboutProtocol::ParseAndBind
//
// Synopsis: Actually perform the binding & execution of script.
//
//----------------------------------------------------------------------------
void
CAboutProtocol::_ReportData(ULONG cb)
{
_bscf |= BSCF_LASTDATANOTIFICATION | BSCF_DATAFULLYAVAILABLE;
_pProtSink->ReportData(_bscf, cb, cb);
}
HRESULT
CAboutProtocol::ParseAndBind()
{
HRESULT hr = S_OK;
TCHAR * pch = NULL;
TCHAR * pchBuf = NULL;
CStr cstrBuf;
ULONG cb = NULL;
CROStmOnBuffer *prostm = NULL;
HINSTANCE hInst = NULL;
//
// The url is of the following syntax:
// about:<name>
//
Assert(_tcsnipre(_T("about:"), 6, _cstrURL, -1));
//
// Do the binding.
//
pch = _tcschr(_cstrURL, ':');
if (!pch)
{
hr = MK_E_SYNTAX;
goto Cleanup;
}
pch++;
{
TCHAR szBuf[] = _T(" <HTML>");
szBuf[0] = NATIVE_UNICODE_SIGNATURE;
hr = THR(cstrBuf.Set(szBuf));
}
if (hr)
goto Cleanup;
//
// Special case for about:blank. Just show a blank page.
//
if (_tcsicmp(_T("blank"), pch))
{
hr = THR(cstrBuf.Append(pch));
if (hr)
goto Cleanup;
}
hr = THR(cstrBuf.Append(_T("</HTML>")));
if (hr)
goto Cleanup;
pchBuf = cstrBuf;
cb = (cstrBuf.Length() + 1) * sizeof(TCHAR);
hr = THR(_pProtSink->ReportProgress(
BINDSTATUS_MIMETYPEAVAILABLE,
_T("text/html")));
if (hr)
goto Cleanup;
Assert(pchBuf);
// cb includes the null terminator
prostm = new CROStmOnBuffer;
if (!prostm)
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
hr = THR(prostm->Init((BYTE *)pchBuf, cb));
if (hr)
goto Cleanup;
_pStm = (IStream *)prostm;
_pStm->AddRef();
Cleanup:
if (!_fAborted)
{
if (!hr)
{
_ReportData(cb);
}
if (_pProtSink)
{
_pProtSink->ReportResult(hr, 0, 0);
}
}
if (hInst)
{
FreeLibrary(hInst);
}
if (prostm)
{
prostm->Release();
}
RRETURN(hr);
}
|
weiss/original-bsd
|
sys/vax/if/ACC/driver/if_dda.c
|
<filename>sys/vax/if/ACC/driver/if_dda.c
/*************************************************************************/
/* */
/* */
/* ________________________________________________________ */
/* / \ */
/* | AAA CCCCCCCCCCCCCC CCCCCCCCCCCCCC | */
/* | AAAAA CCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCC | */
/* | AAAAAAA CCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCC | */
/* | AAAA AAAA CCCC CCCC | */
/* | AAAA AAAA CCCC CCCC | */
/* | AAAA AAAA CCCC CCCC | */
/* | AAAA AAAA CCCC CCCC | */
/* | AAAA AAAAAAAAAAA CCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCC | */
/* | AAAA AAAAAAAAAAA CCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCC | */
/* | AAAA AAAAAAAAA CCCCCCCCCCCCCC CCCCCCCCCCCCCC | */
/* \________________________________________________________/ */
/* */
/* Copyright (c) 1986 by Advanced Computer Communications */
/* 720 Santa Barbara Street, Santa Barbara, California 93101 */
/* (805) 963-9431 */
/* */
/* */
/* File: if_dda.c */
/* */
/* Project: DDN-X.25 Network Interface Driver for ACP 5250 */
/* and ACP 6250 */
/* */
/* Function: This is a network interface driver supporting */
/* the ACP5250/6250 under UNIX versions 4.2, 4.3, */
/* 4.3-tahoe, Ultrix versions 1.2 and 2.0, and */
/* under VMS, TWG WIN/VX and TGV Multinet. */
/* */
/* Components: required: if_dda.c, if_ddareg.h, if_ddavar.h, */
/* and one of: if_dda_uqbus.c if_dda_bibus.c */
/* optional: if_pi.c, if_pivar.h, if_x29.c, */
/* if_vmsx29.c */
/* */
/*************************************************************************/
#include "dda.h"
#if NDDA > 0
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% %%*/
/*%% SYSTEM CONFIGURATION %%*/
/*%% %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#if !defined(ACC_ULTRIX) && !defined(ACC_BSD) && !defined(ACC_VMS)
ERROR
an ACC OS specific option must be defined in your config file
ERROR
#endif
/*
* now define the un-set options to zero
*/
#if !defined(ACC_ULTRIX)
#define ACC_ULTRIX 00
#endif
#if !defined(ACC_BSD)
#define ACC_BSD 00
#endif
#if !defined(ACC_VMS)
#define ACC_VMS 00
#endif
/*
* the define DDA_MSGQ enables the message queue. this adds 2k to the
* data size of the driver. It should only be used during driver development
*/
/*#define DDA_MSGQ /* uncomment this to enable message queue */
/*
* The following line disables the use of the histogram facilities. This
* value (DDA_HISTOGRAM) is automatically undefined for all 4.2 and ULTRIX
* 1.2 systems which do not support the histogram facilities.
*/
#define DDA_HISTOGRAM /* comment this out to disable histogram */
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% %%*/
/*%% INCLUDE FILES %%*/
/*%% %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifndef SIMULATION /* real unix system */
#include "../machine/pte.h" /* page table entries */
#include "../h/param.h"
#include "../h/systm.h"
#include "../h/mbuf.h"
#include "../h/buf.h"
#include "../h/protosw.h"
#include "../h/socket.h"
#include "../h/vmmac.h"
#include "../h/errno.h"
#include "../h/dir.h"
#include "../h/user.h"
#include "../h/kernel.h"
#include "../h/ioctl.h"
#include "../vax/cpu.h"
#include "../vax/mtpr.h"
#include "../net/if.h"
#include "../net/netisr.h"
#include "../net/route.h"
#include "../netinet/in.h"
#include "../netinet/in_systm.h"
# if ACC_BSD > 42 || ACC_ULTRIX > 12
# include "../netinet/in_var.h"
# endif
#include "../netinet/ip.h"
#include "../netinet/ip_var.h"
#include "../vaxif/if_ddareg.h"
#include "../vaxif/if_ddavar.h"
#else SIMULATION
#include "machine/pte.h" /* page table entries */
#include "h/param.h"
#include "h/systm.h"
#include "h/mbuf.h"
#include "h/buf.h"
#include "h/protosw.h"
#include "h/socket.h"
#include "h/vmmac.h"
#include "h/errno.h"
#include "h/dir.h"
#include "h/user.h"
#include "h/kernel.h"
#include "h/ioctl.h"
#include "vax/cpu.h"
#include "vax/mtpr.h"
#include "net/if.h"
#include "net/netisr.h"
#include "net/route.h"
#include "netinet/in.h"
#include "netinet/in_systm.h"
# if ACC_BSD > 42 || ACC_ULTRIX > 12
# include "netinet/in_var.h"
# endif
#include "netinet/ip.h"
#include "netinet/ip_var.h"
#include "if_ddareg.h"
#include "if_ddavar.h"
# ifndef SIOCACPCONFIG
# define SIOCACPCONFIG _IOWR(i,40,struct ifreq)
# endif
# ifndef INET
# define INET 1
# endif
extern struct ifqueue ipintrq; /* IP input queue */
#endif SIMULATION
#if ACC_VMS > 00
# ifdef eunice
# define WINS
# else
# define MULTINET
# endif
#endif
#if ACC_VMS > 00
# ifdef WINS
# include <vms/adpdef.h> /* Define Adapters */
# include <vms/dcdef.h> /* Define AT$_UBA, adapter type */
# else MULTINET
# include "../vaxif/if_ddaioctl.h" /* not in ioctl.h */
# endif
#endif
/* disable histogram functions for BSD 4.2 and ULTRIX 1.2 */
#if ACC_BSD == 42 || ACC_ULTRIX == 12
# undef DDA_HISTOGRAM
#endif
/* Ultrix doesn't have syslog, so use printf instead. Since the two
* functions take different arg list formats, embed the open paren in
* the defined symbol; provide DDAELOG to close the call while keeping
* parentheses matched. The argument to DDALOG is ignored for printf;
* for log(), debugging messages use LOG_DEBUG, all others use LOG_ERR.
*/
#if (ACC_BSD > 42 || ACC_VMS > 00) && !defined(SIMULATION)
# include "syslog.h"
# define DDALOG(s) log( s,
#else
# define DDALOG(s) printf(
#endif
#define DDAELOG )
#ifndef DDADEBUG
#define PRIVATE static /* hide our internal functions */
#else
#define PRIVATE /* let the world see them */
#endif
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% %%*/
/*%% GLOBAL FUNCTIONS %%*/
/*%% %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
int ddaprobe();
int ddaattach();
int ddareset();
int ddainit();
int ddaoutput();
int ddatimer();
int ddaioctl();
int ddainta(); /* service interrupt "a" from front end */
int ddaintb(); /* service interrupt "b" from front end */
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% %%*/
/*%% LOCAL FUNCTIONS %%*/
/*%% %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void send_config();
PRIVATE struct dda_cb *locate_x25_lcn();
PRIVATE struct dda_cb *find_free_lcn();
PRIVATE boolean convert_ip_addr();
PRIVATE u_long convert_x25_addr();
PRIVATE boolean make_x25_call();
PRIVATE void dda_start();
PRIVATE void dda_rrq();
PRIVATE void dda_wrq();
PRIVATE int start_chn();
PRIVATE void dda_data();
PRIVATE void dda_supr();
PRIVATE void supr_msg();
PRIVATE boolean decode_ring();
PRIVATE void decode_answer();
PRIVATE void clear_lcn();
PRIVATE void send_restart();
PRIVATE void send_supr();
PRIVATE void start_supr();
PRIVATE void abort_io();
PRIVATE void prt_addr();
#ifdef DDA_PAD_OR_RAW
PRIVATE int dda_decode_type();
#endif
#ifdef DDA_PADOPT
PRIVATE void x29_data();
PRIVATE void x29_supr();
PRIVATE void x29_init();
#endif DDA_PADOPT
#ifdef DDA_RAWOPT
PRIVATE void pi_data();
PRIVATE void pi_supr();
PRIVATE void pi_init();
PRIVATE int pi_circuit_to_handle_protocol();
#endif DDA_RAWOPT
#ifdef DDADEBUG
PRIVATE void prt_bytes();
#endif
PRIVATE char *fmt_x25();
#ifdef DDA_HISTOGRAM
PRIVATE void hist_init(); /* histogram functions */
PRIVATE void hist_lcn_state();
PRIVATE void hist_all_lcns();
PRIVATE void hist_link_state();
PRIVATE void hist_read();
PRIVATE int hist_copyout();
#else DDA_HISTOGRAM /* make all histogram functions no-op's */
#define hist_init(a,b)
#define hist_lcn_state(a,b,c)
#define hist_all_lcns(a,b)
#define hist_link_state(a,b,c)
#define hist_read(a)
#define hist_copyout(a,b)
#endif DDA_HISTOGRAM
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% %%*/
/*%% LOCAL VARIABLES %%*/
/*%% %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE int tmo_data_idle = TMO_DATA_IDLE; /* idle circuit timeout for
* all boards */
PRIVATE int nddach[4] = { /* number of channels currently in use */
NDDACH_DEFAULT, NDDACH_DEFAULT,
NDDACH_DEFAULT, NDDACH_DEFAULT };
PRIVATE char *dda_product; /* name of product, like "ACP5250" */
PRIVATE int dda_hasmaint; /* do we have a maintenance board? */
/* the message bits are used in the DMESG macros defined in if_ddavar.h */
/* word 1 and 2 (msgs 0 - 63) are reserved for the IP interface */
/* word 3 (msgs 64 - 95) are reserved for the PI interface */
/* word 4 (msgs 96 - 127) are reserved for the X.29 interface */
/* word 5 and 6 (msgs 128 - 191) are reserved for debugging main module*/
/* word 7 (msgs 192 - 223) are reserved for debugging the PI */
/* word 8 (msgs 224 - 255) are reserved for debugging X29 */
/* word 9 (msgs 256 - 287) are reserved for call logging */
#define NDMESGWORDS 9
#define MAXDMSGS (NDMESGWORDS * 32)
PRIVATE long ddamsgs[NDDA][NDMESGWORDS];
/* | | | | | | | | |
* default: all informational messages on, /--/--/--/ | | | | |
* all debug messages off, --------------------/---/---/---/ |
* log busys, but not calls or I/O aborts ---------------------/
*/
/* Must be as large as the larger of (trtab, ddactl, dnload): */
char dda_iobuf[sizeof(struct ddactl)];
struct dda_softc dda_softc[NDDA]; /* per device infomation */
/* header for building command to be sent to the front end in */
/* response to ACPCONFIG user command */
PRIVATE u_char acpconfig_msg[] = {
LINE_CNTL, /* set command code */
0x00, /* not used */
0x00, /* not used */
0x00, /* extension length (set at runtime) */
0x00, /* cmd space */
0x00,
0x00,
0x00,
0x00
};
PRIVATE u_char bfr_size_msg[] =
{
SET_BFR_SIZE, /* set command code */
0x00, /* not used */
0x00, /* not used */
0x01, /* extension length */
0x00, /* cmd space */
0x00,
0x00,
0x00,
0x00
};
PRIVATE u_char ddacb_cmnd[4] = { CALL, 0, 0, 0 };
PRIVATE u_char ddacb_called_addr[16] = {0};
PRIVATE u_char ddacb_calling_addr[16] = {0};
PRIVATE u_char ddacb_facilities[64] = {0};
PRIVATE u_char ddacb_protocol[5] = {0};
PRIVATE u_char ddacb_user_data[64] = {0};
#ifdef DDADEBUG
u_char dda_silo_counter;
u_char dda_debug_silo[256];
#endif
/* Table of baud rate values and the associated parameter for the Set */
/* System Parameters message, ddainit_msg. The 'parameter1' is nonzero */
/* for valid baud rate divisors. These are nominal baud rates. */
PRIVATE struct baud {
char b_value;
u_char parameter1; /* first byte of baud rate setting */
u_char parameter2; /* second byte of baud rate setting */
} ddabaud_rate[] = {
{ 1, 0x02, 0x00 }, /* 2.00M */
{ 2, 0x03, 0x00 }, /* 1.33M */
{ 3, 0x04, 0x00 }, /* 1.00M */
{ 4, 0x08, 0x00 }, /* 500K */
{ 5, 0x10, 0x00 }, /* 250K */
{ 6, 0x28, 0x00 }, /* 100K */
{ 7, 0x3e, 0x00 }, /* 64K */
{ 8, 0x47, 0x00 }, /* 56K */
{ 9, 0x85, 0x00 }, /* 30K */
{ 10, 0xd0, 0x00 }, /* 19.2K */
{ 11, 0xa1, 0x01 }, /* 9600 */
{ 12, 0x41, 0x03 }, /* 4800 */
{ 13, 0x83, 0x06 }, /* 2400 */
{ 14, 0x05, 0x0d }, /* 1200 */
{ 0, 0, 0 }
};
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% %%*/
/*%% Address Translation Table for Internet <-> X.25 addresses %%*/
/*%% %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#define DDANATT 32 /* number of addr translation table entries */
PRIVATE int dda_num_addr_tr[NDDA] = {0}; /* number of address
* translations */
/* currently stored */
PRIVATE struct dda_addr_tr { /* X.25 PDN address translation table */
u_long ip_addr; /* internet address */
u_char x25_addr[MAXADDRLEN]; /* X.25 address */
} dda_addr_tr[NDDA][DDANATT] = {{ 0L, ""}}; /* null */
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% %%*/
/*%% Aliasing of IP address for 4.2 ==> 4.3 compatibility %%*/
/*%% Note: this union is not required in 4.2, since the s_net %%*/
/*%% field and its friends are in an include file. We use it to %%*/
/*%% minimize the number of #ifdef dependencies in the code. %%*/
/*%% %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifdef s_net /* 4.2 */
# undef s_net
# undef s_host
# undef s_lh
# undef s_impno
#endif
union imp_addr {
struct in_addr ip;
struct imp {
u_char s_net;
u_char s_host;
u_char s_lh;
u_char s_impno;
} imp;
};
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% %%*/
/*%% GLOBAL ROUTINES %%*/
/*%% %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifdef ACP_BI
#include "if_dda_bibus.c"
#else
#include "if_dda_uqbus.c"
#endif
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% DDAIOCTL() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine processes device dependent ioctl's. Supported */
/* ioctls set the host's internet address for this network */
/* interface, or send Set System Parameters Message to the ACP. */
/* The logic for setting the interface address must remain */
/* compatible with both ifconfig and acpconfig programs. */
/* If the ioctl comes from the acpconfig program, the front end */
/* is not initialized because the user will specify explicitly */
/* what parameters are desired. If the ioctl comes from the */
/* ifconfig program, the fron end is initialized with default */
/* parameters in the ddainit_msg array. */
/* */
/* Call: ddaioctl(ifp, cmd, data) */
/* Argument: ifp: pointer to the network interface data */
/* structure, ifnet */
/* cmd: identifies the type of ioctl */
/* data: information for the ioctl */
/* Returns: 0 for success, or the nonzero error value: */
/* EINVAL invalid ioctl request */
/* Called by: network software, address of this routine is */
/* defined in af_inet network interface struct */
/* Calls to: splimp() */
/* if_rtinit() */
/* in_netof() */
/* in_lnaof() */
/* ddainit() */
/* send_config() */
/* DDALOG() */
/* splx() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifdef MULTINET
volatile int StatQuery_Completed; /* Polled for board stat ioctl */
#endif
ddaioctl(ifp, cmd, data)
register struct ifnet *ifp;
int cmd;
caddr_t data;
{
register struct dda_softc *ds = &dda_softc[ifp->if_unit];
struct ifreq *ifr = (struct ifreq *) data;
#if defined(DDA_PADOPT) && defined(WINS)
int prealloc_x29(); /* Preallocate UCBs for X29 */
#endif
#if ACC_BSD == 42 || ACC_ULTRIX == 12
struct sockaddr_in *sin = (struct sockaddr_in *) & ifr->ifr_addr;
#else
struct ifaddr *ifa = ds->dda_if.if_addrlist;
#endif
int s;
int error = 0;
int i;
register struct dda_addr_tr *atp, *btp;
struct trtab *tr;
struct ddactl *da;
char arg2[MAXADDRLEN], code;
#ifdef DDADEBUG
if (DDADBCH(4, ifp->if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: ioctl()\n", ifp->if_unit DDAELOG;
}
#endif DDADEBUG
/*
* This may not be necessary here, but under some flavors of BSDish
* systems (2.0ULTRIX) this routine is apparently called at splimp(). In
* the case that we are currently processing ioctls issued from acpconfig
* in /etc/rc, the board may not have come on line yet - so we need to be
* able to process the B interrupt while in the delay loop below.
*/
#ifndef MULTINET
s = spl0();
#endif
switch (cmd) {
case SIOCSIFADDR:
if (!suser())
return EACCES;
#if ACC_BSD == 42 || ACC_ULTRIX == 12
if (ifp->if_flags & IFF_RUNNING)
if_rtinit(ifp, -1); /* delete previous route */
ifp->if_addr = *(struct sockaddr *) sin;
ifp->if_net = in_netof(sin->sin_addr);
ifp->if_host[0] = in_lnaof(sin->sin_addr);
if (ifp->if_flags & IFF_RUNNING)
if_rtinit(ifp, RTF_UP);
else
ddainit(ifp->if_unit);
ds->dda_ipaddr.s_addr = ((struct sockaddr_in *) & ifp->if_addr)->sin_addr.s_addr;
#else /* 4.3 networking */
if (ifa->ifa_addr.sa_family != AF_INET)
return (EINVAL);
if ((ifp->if_flags & IFF_RUNNING) == 0)
ddainit(ifp->if_unit);
ds->dda_ipaddr = IA_SIN(ifa)->sin_addr;
#endif /* 4.3 networking */
break;
case SIOCACPCONFIG:
/* process ioctl from acpconfig program */
code = *(ifr->ifr_data);
/*********************************************************
* *
* Commands n, h, q, and r are non-privileged *
* *
*********************************************************/
if (!suser() && code != 'n' && code != 'h' && code != 'q' && code != 'r')
return EACCES;
#if ACC_BSD == 42 || ACC_ULTRIX == 12
sin = (struct sockaddr_in *) & ds->dda_if.if_addr;
if (in_netof(sin->sin_addr) == 0)
#else
if (ds->dda_if.if_addrlist == 0)
#endif
{
error = EDESTADDRREQ; /* error, no internet address */
goto exit;
}
/* for command to set baud rate, look up the value for the */
/* baud rate divisor in the ddabaud_rate table, put value */
/* in the Set System Parameters message, ddainit_msg */
if (code >= 1 && code <= 14) {
register struct baud *p;
if (error = diags_completed(ds))
goto exit;
for (p = ddabaud_rate; p->b_value; p++) {
if ((*(ifr->ifr_data) - p->b_value) == 0)
break;
}
/* if internal clock not set, do so */
if ((ds->dda_init & DDA_INTCLOCK) == 0) {
ds->dda_init |= DDA_INTCLOCK;
acpconfig_msg[MSG_OFFSET] = CLOCK_CNTL;
acpconfig_msg[MSG_OFFSET + 1] = INTERNAL_CLOCK;
acpconfig_msg[MSG_OFFSET + 2] = BAUD_CNTL;
acpconfig_msg[MSG_OFFSET + 3] = p->parameter1;
acpconfig_msg[MSG_OFFSET + 4] = p->parameter2;
acpconfig_msg[MSG_LENGTH] = 5;
} else {
acpconfig_msg[MSG_OFFSET] = BAUD_CNTL;
acpconfig_msg[MSG_OFFSET + 1] = p->parameter1;
acpconfig_msg[MSG_OFFSET + 2] = p->parameter2;
acpconfig_msg[MSG_LENGTH] = 3;
}
if ((p->b_value == 0) || (p->parameter1 == 0))
error = EINVAL; /* baud rate value invalid */
else
send_config(ds, acpconfig_msg); /* send message to front end */
goto exit;
}
switch (code) {
case 'a': /* Add address translation table entry */
if (error = diags_completed(ds))
goto exit;
if (dda_num_addr_tr[ifp->if_unit] >= DDANATT) { /* table already full */
error = ENOMEM;
goto exit;
}
/*
* Copy in user arguments and point "tr" at them. Then scan the
* translation table and either find location to insert or flag
* error
*/
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct trtab))) {
error = EFAULT;
goto exit;
}
tr = (struct trtab *) dda_iobuf;
for (i = 0, atp = &dda_addr_tr[ifp->if_unit][0];
i < dda_num_addr_tr[ifp->if_unit]; i++, atp++) {
if (atp->ip_addr == tr->ipaddr) {
if (bcmp((char *) atp->x25_addr,
(char *) tr->x25addr, MAXADDRLEN)) {
error = EADDRINUSE;
goto exit;
} else /* addresses are the same, just ignore ioctl */
goto exit;
}
if (atp->ip_addr > tr->ipaddr) /* insert entry here */
break;
}
for (btp = &dda_addr_tr[ifp->if_unit][dda_num_addr_tr[ifp->if_unit]];
btp > atp; btp--) { /* open up space for a new entry */
btp->ip_addr = (btp - 1)->ip_addr;
bcopy((btp - 1)->x25_addr, btp->x25_addr, MAXADDRLEN);
}
atp->ip_addr = tr->ipaddr;
bcopy(tr->x25addr, atp->x25_addr, MAXADDRLEN);
dda_num_addr_tr[ifp->if_unit]++; /* one more table entry */
goto exit;
case 'D':
if (error = diags_completed(ds))
goto exit;
/* clear table for use by 'r' flag of acpconfig */
for (i = 0, atp = &dda_addr_tr[ifp->if_unit][0];
i < dda_num_addr_tr[ifp->if_unit]; i++, atp++) {
atp->ip_addr = 0L;
atp->x25_addr[0] = 0;
}
dda_num_addr_tr[ifp->if_unit] = 0;
goto exit;
case 'd': /* Delete address translation table entry */
if (error = diags_completed(ds))
goto exit;
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct trtab))) {
error = EFAULT;
goto exit;
}
tr = (struct trtab *) dda_iobuf;
error = EFAULT; /* in case inet address not in table */
for (i = 0, atp = &dda_addr_tr[ifp->if_unit][0];
i < dda_num_addr_tr[ifp->if_unit]; i++, atp++) {
if (atp->ip_addr == tr->ipaddr) {
error = 0; /* found it: cancel error */
for (; i < dda_num_addr_tr[ifp->if_unit] - 1; i++, atp++) {
atp->ip_addr = (atp + 1)->ip_addr;
bcopy((atp + 1)->x25_addr, atp->x25_addr, MAXADDRLEN);
}
atp->ip_addr = 0L; /* clear last vacated entry */
atp->x25_addr[0] = 0;
dda_num_addr_tr[ifp->if_unit]--; /* one fewer table
* entries */
break;
}
}
goto exit;
case 'f': /* -f facility status */
/*
* The first byte of the "msg" selects the flow control parameter
* and the "drval" field holds the status (on or off).
*/
if (error = diags_completed(ds))
goto exit;
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct ddactl))) {
error = EFAULT;
goto exit;
}
if (ds->dda_firmrev < 0x21) { /* need 2.0 or above ROMs */
error = ENOPROTOOPT;
goto exit;
}
da = (struct ddactl *) dda_iobuf;
switch (da->msg[0]) {
case 0: /* packet */
if (da->drval)
ds->dda_init |= DDA_PKTNEG;
else
ds->dda_init &= ~DDA_PKTNEG;
break;
case 1: /* window */
if (da->drval)
ds->dda_init |= DDA_WNDNEG;
else
ds->dda_init &= ~DDA_WNDNEG;
break;
}
goto exit;
case 'o': /* Set options */
if (error = diags_completed(ds))
goto exit;
if (ds->dda_firmrev < 0x21) { /* need 2.1 or above ROMs */
error = ENOPROTOOPT;
goto exit;
}
if (ds->dda_state != S_DISABLED) { /* must bring link down */
error = EINPROGRESS;
goto exit;
}
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct ddactl))) {
error = EFAULT;
goto exit;
}
da = (struct ddactl *) dda_iobuf;
acpconfig_msg[MSG_OFFSET] = PKT_OPTIONS;
acpconfig_msg[MSG_OFFSET + 1] = da->msg[0];
acpconfig_msg[MSG_LENGTH] = 2;
#ifdef DDADEBUG
if (DDADBCH(4, ifp->if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: acpconfig_msg is %x %x %x\n",
ifp->if_unit, acpconfig_msg[MSG_LENGTH],
acpconfig_msg[MSG_OFFSET], acpconfig_msg[MSG_OFFSET + 1] DDAELOG;
}
#endif DDADEBUG
send_config(ds, acpconfig_msg);
goto exit;
case 'N': /* read network id */
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct ddactl))) {
error = EFAULT;
goto exit;
}
da = (struct ddactl *) dda_iobuf;
ds->dda_net_id = da->drval;
goto exit;
case 'r': /* Read address translation table entry */
/*
* The value stored in "ipaddr" is not an address, but an index
* of a translation table entry to read out. The x25_addr field
* in the input structure is not used.
*/
if (error = diags_completed(ds))
goto exit;
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct trtab))) {
error = EFAULT;
goto exit;
}
tr = (struct trtab *) dda_iobuf;
i = tr->ipaddr;
if (i >= DDANATT) { /* scanned the whole table */
error = EFAULT;
goto exit;
}
tr->ipaddr = dda_addr_tr[ifp->if_unit][i].ip_addr;
bcopy(dda_addr_tr[ifp->if_unit][i].x25_addr, tr->x25addr, MAXADDRLEN);
if (copyout(tr, ifr->ifr_data, sizeof(struct trtab)))
error = EFAULT;
goto exit;
#ifdef DDA_HISTOGRAM
case 'h': /* read histogram */
if (error = diags_completed(ds))
goto exit;
hist_read(ifp->if_unit);
if (hist_copyout(ifp->if_unit, ifr->ifr_data))
error = EFAULT;
goto exit;
case 'H': /* read and reset histogram */
if (error = diags_completed(ds))
goto exit;
hist_read(ifp->if_unit);
if (hist_copyout(ifp->if_unit, ifr->ifr_data))
error = EFAULT;
else
hist_init(ifp->if_unit, 1);
goto exit;
#endif DDA_HISTOGRAM
case 'v': /* -v variable value */
/*
* There are two "variables" in the driver which can be set via
* ioctl: packet size, and window size. The "drval" field holds
* the value and the first byte of the "msg" selects the variable.
* Note that the selector is another little undocumented piece of
* the interface between here and the acpconfig program. It is
* coupled to the ordering of a little string table inside that
* program; new parameters should be added at the end, not the
* middle!
*/
/* No check to see if powerup diags are completed */
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct ddactl))) {
error = EFAULT;
goto exit;
}
da = (struct ddactl *) dda_iobuf;
switch (da->msg[0]) {
case 0: /* set logging (obsolete) */
case 1: /* set debug (obsolete) */
case 2: /* set debug unit (obsolete) */
error = EINVAL;
break;
/*
* For both packet and window sizes, we check that the link
* is currently down. The new parameters will be sent to the
* FEP when the link is next brought up. See processing for
* -u flag.
*/
case 3: /* set packetsize */
if (error = diags_completed(ds))
goto exit;
if (ds->dda_firmrev < 0x21) { /* need 2.1 or above ROMs */
error = ENOPROTOOPT;
goto exit;
}
if (ds->dda_state != S_DISABLED) { /* must bring link down */
error = EINPROGRESS;
goto exit;
}
/*
* X.25 (1984) section 7.2.2.1.1 says 12 (4096 byte packets)
* BBN report 5760 (September 1984) 14.2.1.2 says 10. We just
* check for 12.
*/
if (da->drval < 4 || da->drval > 12)
error = EINVAL;
else {
int packetsize = 1 << da->drval;
acpconfig_msg[MSG_LENGTH] = 3;
acpconfig_msg[MSG_OFFSET] = MAX_PKT_SZ; /* Max negotiable */
/* pkt size */
acpconfig_msg[MSG_OFFSET + 1] = packetsize & 0xFF;
acpconfig_msg[MSG_OFFSET + 2] = (packetsize >> 8) & 0xFF;
send_config(ds, acpconfig_msg);
}
break;
case 4: /* set windowsize */
if (error = diags_completed(ds))
goto exit;
if (ds->dda_firmrev < 0x21) { /* need 2.0 or above ROMs */
error = ENOPROTOOPT;
goto exit;
}
if (ds->dda_state != S_DISABLED) { /* must bring link down */
error = EINPROGRESS;
goto exit;
}
if (da->drval < 1 || da->drval > 127)
error = EINVAL;
else {
acpconfig_msg[MSG_LENGTH] = 2;
acpconfig_msg[MSG_OFFSET] = MAX_PKT_WN; /* Max negotiable */
/* pkt window */
acpconfig_msg[MSG_OFFSET + 1] = da->drval;
send_config(ds, acpconfig_msg);
}
break;
}
goto exit;
case 'm': /* -m message */
if (error = diags_completed(ds))
goto exit;
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct ddactl))) {
error = EFAULT;
goto exit;
}
da = (struct ddactl *) dda_iobuf;
send_config(ds, da->msg);
goto exit;
case 'n': /* -n svc_count */
if (error = diags_completed(ds))
goto exit;
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct ddactl))) {
error = EFAULT;
goto exit;
}
if (ds->dda_firmrev < 0x21) { /* need 2.1 or above ROMs */
error = ENOPROTOOPT;
goto exit;
}
da = (struct ddactl *) dda_iobuf;
i = 0; /* i holds the return value */
if (da->drval == 0)
i = nddach[ifp->if_unit];
else if (ds->dda_state != S_DISABLED) { /* must bring link down */
error = EINPROGRESS;
goto exit;
} else {
if (!suser()) {
error = EACCES;
goto exit;
}
if (da->drval < 1 || da->drval > NDDACH)
error = EINVAL;
else {
acpconfig_msg[MSG_LENGTH] = 2;
acpconfig_msg[MSG_OFFSET] = SVC_LIMIT;
acpconfig_msg[MSG_OFFSET + 1] = da->drval;
nddach[ifp->if_unit] = da->drval;
send_config(ds, acpconfig_msg);
}
}
if (copyout(&i, ifr->ifr_data, sizeof(int)))
error = EFAULT;
goto exit;
case 'c': /* -c msgnum -- dis/enable driver mesg */
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct ddactl))) {
error = EFAULT;
goto exit;
}
da = (struct ddactl *) dda_iobuf;
if (da->drval < 0 || da->drval >= MAXDMSGS)
error = EINVAL;
else {
u_char new_val;
DMESGTOG(ifp->if_unit, da->drval);
new_val = DMESGVAL(ifp->if_unit, da->drval) ? 1 : 0;
/* 1 means disabled, 0 means enabled */
if (copyout(&new_val, ifr->ifr_data, sizeof(u_char)))
error = EFAULT;
}
goto exit;
case 't': /* -t sec -- set data idle timeout */
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct ddactl))) {
error = EFAULT;
goto exit;
}
da = (struct ddactl *) dda_iobuf;
if (da->drval < 1)
error = EINVAL;
else
tmo_data_idle = da->drval / DDA_TIMEOUT;
goto exit;
case 'q': /* driver/FE/shm/silo state queries */
if (copyin(ifr->ifr_data, dda_iobuf, sizeof(struct ddactl))) {
error = EFAULT;
goto exit;
}
da = (struct ddactl *) dda_iobuf;
switch (da->msg[0]) {
case 0: /* front end state query */
if ((error = diags_completed(ds)) == 0) {
int s2 = splimp();
/* need 2.0 or above ROMs */
if (ds->dda_firmrev < 0x21) {
error = ENOPROTOOPT;
splx(s2); /* We got it and woke up */
break;
}
#ifdef MULTINET
StatQuery_Completed = 0;
send_supr(ds, STATQUERY, 0, 0);
splx(s2); /* drop ioctl so we can be scheduled */
while (!StatQuery_Completed);
#else MULTINET
send_supr(ds, STATQUERY, 0, 0);
sleep(dda_iobuf, PSLEP); /* Interruptible with ^C */
splx(s2); /* We got it and woke up */
#endif MULTINET
if (copyout(dda_iobuf, ifr->ifr_data,
sizeof(struct ddactl)))
error = EFAULT;
}
break;
case 1: /* driver state query */
da->msg[0] = ds->dda_state;
da->msg[1] = ds->dda_init;
da->msg[2] = ds->dda_flags;
da->msg[3] = ds->dda_firmrev;
if (copyout(dda_iobuf, ifr->ifr_data,
sizeof(struct ddactl)))
error = EFAULT;
break;
#ifdef DDADEBUG
case 2: /* debug query */
if (copyout(dda_debug_silo, ifr->ifr_data, 256))
error = EFAULT;
break;
#endif
#if defined(DDADEBUG) && defined(ACP_BI)
case 3: /* shm/biic query (temporary) */
{
register struct uba_device *ui = ddainfo[ifp->if_unit];
dda_dump_shm((SYSGEN_BLOCK *) ds->dda_mapreg);
dda_dump_biic_regs((struct biic_regs *) ui->ui_addr);
}
break;
#endif
default:
error = EINVAL;
}
goto exit;
case '0': /* -u 0 */
if (error = diags_completed(ds))
goto exit;
acpconfig_msg[MSG_OFFSET] = LINK_DISABLE;
acpconfig_msg[MSG_LENGTH] = 1;
hist_link_state(ifp->if_unit, ds->dda_state, S_GOING_DOWN);
ds->dda_state = S_GOING_DOWN;
break;
case '1': /* -u 1 */
if (error = diags_completed(ds))
goto exit;
acpconfig_msg[MSG_OFFSET] = LINK_LOOPBACK;
acpconfig_msg[MSG_OFFSET + 1] = LOOP_NONE;
acpconfig_msg[MSG_OFFSET + 2] = DTE_DCE_MODE;
acpconfig_msg[MSG_OFFSET + 3] = DTE;
acpconfig_msg[MSG_OFFSET + 4] = LINK_ENABLE;
acpconfig_msg[MSG_LENGTH] = 5;
ds->dda_state = S_COMING_UP;
hist_init(ifp->if_unit, 0);
break;
case '2': /* -u 2 */
if (error = diags_completed(ds))
goto exit;
acpconfig_msg[MSG_OFFSET] = LINK_LOOPBACK;
acpconfig_msg[MSG_OFFSET + 1] = LOOP_NONE;
acpconfig_msg[MSG_OFFSET + 2] = DTE_DCE_MODE;
acpconfig_msg[MSG_OFFSET + 3] = DCE;
acpconfig_msg[MSG_OFFSET + 4] = LINK_ENABLE;
acpconfig_msg[MSG_LENGTH] = 5;
ds->dda_state = S_COMING_UP;
hist_init(ifp->if_unit, 0);
break;
case '3': /* -u 3 */
if (error = diags_completed(ds))
goto exit;
acpconfig_msg[MSG_OFFSET] = LINK_LOOPBACK;
acpconfig_msg[MSG_OFFSET + 1] = LOOP_EXTERNAL;
acpconfig_msg[MSG_OFFSET + 2] = LINK_ENABLE;
acpconfig_msg[MSG_LENGTH] = 3;
ds->dda_state = S_COMING_UP;
hist_init(ifp->if_unit, 0);
break;
case '4': /* -u 4 */
if (error = diags_completed(ds))
goto exit;
acpconfig_msg[MSG_OFFSET] = LINK_LOOPBACK;
acpconfig_msg[MSG_OFFSET + 1] = LOOP_INTERNAL;
acpconfig_msg[MSG_OFFSET + 2] = LINK_ENABLE;
acpconfig_msg[MSG_LENGTH] = 3;
ds->dda_state = S_COMING_UP;
hist_init(ifp->if_unit, 0);
break;
case 'b': /* -b 0 */
if (error = diags_completed(ds))
goto exit;
acpconfig_msg[MSG_OFFSET] = CLOCK_CNTL;
acpconfig_msg[MSG_OFFSET + 1] = EXTERNAL_CLOCK;
acpconfig_msg[MSG_LENGTH] = 2;
ds->dda_init &= ~DDA_INTCLOCK;
break;
case 'S': /* select DDN standard X.25 service */
/* -s 0 or -s standard */
if (error = diags_completed(ds))
goto exit;
if (ds->dda_if.if_flags & IFF_UP && ds->dda_init & DDA_PDN) {
error = EALREADY;
goto exit; /* no PDN->DDN mode change if running */
}
ds->dda_init &= ~(DDA_BASIC | DDA_PDN);
ds->dda_init |= DDA_STANDARD;
goto exit;
case 'T': /* select DDN basic X.25 service */
/* -s 1 or -s basic */
if (error = diags_completed(ds))
goto exit;
if (ds->dda_if.if_flags & IFF_UP && ds->dda_init & DDA_PDN) {
error = EALREADY;
goto exit; /* no PDN->DDN mode change if running */
}
ds->dda_init &= ~(DDA_PDN | DDA_STANDARD);
ds->dda_init |= DDA_BASIC;
goto exit;
case 'U': /* select X.25 Public Data Network service */
/* -s 2 or -s pdn */
if (error = diags_completed(ds))
goto exit;
if (ds->dda_if.if_flags & IFF_UP && (ds->dda_init &
(DDA_BASIC | DDA_STANDARD))) {
error = EALREADY;
goto exit; /* no DDN->PDN mode change if running */
}
ds->dda_init &= ~(DDA_BASIC | DDA_STANDARD);
ds->dda_init |= DDA_PDN;
goto exit;
case 'e': /* set buffer size */
/* -e size size is encoded in second byte */
if (error = diags_completed(ds))
goto exit;
/*
* check to see if we have newer at least version 2.2 roms.
*/
if (ds->dda_firmrev < 0x22) {
error = ENOPROTOOPT;
goto exit;
}
if (ds->dda_if.if_flags & IFF_UP) {
error = EALREADY;
goto exit; /* no PDN->DDN mode change if running */
}
bfr_size_msg[MSG_OFFSET] = ifr->ifr_data[1];
send_config(ds, bfr_size_msg);
bufreset(ifp->if_unit);
goto exit;
#ifdef ACP_BI
case 'L':
{ struct dda_dnload dl;
if (copyin(ifr->ifr_data, &dl, sizeof(struct dda_dnload))) {
error = EFAULT;
goto exit;
}
error = dda_dload(ifp->if_unit, &dl);
goto exit;
}
#endif
#if defined(DDA_PADOPT) && defined(WINS)
case 'x': /* Preallocate UCBs for X29 -- VMS only */
printf("Preallocated %d PTYs for X29\n", prealloc_x29());
goto exit;
#endif
case 'z': /* reset specified front-end device, -z */
/* second parm is supposed to be uban, but ddareset doesn't care about it */
ddareset(ifp->if_unit, 0);
goto exit;
default:
error = EINVAL;
goto exit;
}
if ((*(ifr->ifr_data) != '0') && (ds->dda_init & DDA_PDN) &&
#if ACC_BSD == 42 || ACC_ULTRIX == 12
(convert_ip_addr(sin->sin_addr, (u_char *) arg2, ds) == 0)
#else
(convert_ip_addr(ds->dda_ipaddr, (u_char *) arg2, ds) == 0)
#endif
) {
error = EADDRNOTAVAIL;
goto exit;
}
send_config(ds, acpconfig_msg);
break;
default:
error = EINVAL;
}
exit:
#ifndef MULTINET
splx(s);
#endif
return (error);
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% DDAOUTPUT() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine is called by the network software when it has an */
/* IP datagram to send out this interface. An attempt is made */
/* to find a LCN which has a virtual circuit open to the */
/* indicated host. If an LCN is found the packet is queued for */
/* output on that LCN. */
/* */
/* Call: ddaoutput(ifp, m0, dst) */
/* Arguments: ifp: locates the network interface, ifnet */
/* m0: locates an mbuf buffer */
/* dst: is the socket destination address */
/* Returns: 0 for success, or one of following nonzero */
/* error indications: */
/* ENETDOWN */
/* EAFNOSUPPORT */
/* ENOBUFS */
/* Called by: network software, address of this routine is */
/* defined in the dda_if network interface struct */
/* Calls to: DDALOG() */
/* m_freem() */
/* splimp() */
/* locate_x25_lcn() */
/* IF_QFULL() */
/* IF_DROP() */
/* splx() */
/* IF_ENQUEUE() */
/* dda_start() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
ddaoutput(ifp, m0, dst)
struct ifnet *ifp;
struct mbuf *m0;
struct sockaddr_in *dst;
{
register struct mbuf *m = m0;
register struct dda_softc *ds = &dda_softc[ifp->if_unit];
register struct dda_cb *dc;
register struct ifqueue *oq;
struct mbuf *prev;
int s;
union imp_addr imp_addr;
#ifdef DDADEBUG
if (DDADBCH(1, ifp->if_unit)) {
imp_addr.ip = dst->sin_addr;
DDALOG(LOG_DEBUG) "dda%d: ddaoutput: dst = %d.%d.%d.%d\n",
ifp->if_unit, imp_addr.imp.s_net, imp_addr.imp.s_host,
imp_addr.imp.s_lh, imp_addr.imp.s_impno DDAELOG;
}
#endif DDADEBUG
if ((ds->dda_if.if_flags & IFF_UP) == 0)
return (ENETDOWN);
switch (dst->sin_family) {
#ifdef INET
case AF_INET:
break;
#endif INET
default:
DMESG(ifp->if_unit, 2,
(DDALOG(LOG_ERR) "dda%d: can't handle af%d\n", ifp->if_unit,
dst->sin_family DDAELOG));
m_freem(m0);
return (EAFNOSUPPORT);
}
#ifdef DDADEBUG
if (DDADBCH(2, ifp->if_unit)) {
imp_addr.ip = dst->sin_addr;
DDALOG(LOG_DEBUG) "dda%d: ddaoutput: dst = %d.%d.%d.%d\n",
ifp->if_unit, imp_addr.imp.s_net, imp_addr.imp.s_host,
imp_addr.imp.s_lh, imp_addr.imp.s_impno DDAELOG;
}
#endif DDADEBUG
/* Mod to V1.5b ==> V1.5b1 */
/* In 4.3, the IP code may pass mbuf chains with 0-length mbufs */
/* This causes "transfer count = 0" messages and might even */
/* cause actual garbage data transmission if the mbuf is at the */
/* end of the chain (we don't think it ever will be, but one */
/* can't be too sure...so we scan the chain first). */
/* WE DO ASSUME that there is at least one nonempty mbuf! */
/* (ULTRIX: we don't know, but the code is at worst harmless) */
while (m0->m_len == 0) {
m = m0;
m0 = m0->m_next;
m->m_next = 0;
m_freem(m);
}
/* Now we know the first mbuf (at m0) is not zero length */
prev = m0;
m = m0->m_next;
while (m) {
if (m->m_len == 0) {
prev->m_next = m->m_next;
m->m_next = 0;
m_freem(m);
m = prev->m_next;
} else {
prev = m;
m = m->m_next;
}
}
m = m0; /* reset m to beginning of modified chain */
s = splimp(); /* disable interrrupts */
/* try to find an LCN */
if (dc = locate_x25_lcn(ds, dst->sin_addr)) { /* if found */
#ifdef DDADEBUG
if (DDADBCH(2, ifp->if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: ddaoutput: lcn found = %d\n", ifp->if_unit,
dc->dc_lcn DDAELOG;
}
#endif DDADEBUG
oq = &(dc->dc_oq); /* point to output queue */
if (IF_QFULL(oq)) { /* if q full */
IF_DROP(oq); /* drop the data */
m_freem(m);
ds->dda_if.if_collisions++; /* for netstat display */
splx(s);
return (ENOBUFS);
}
IF_ENQUEUE(oq, m); /* otherwise queue it */
dda_start(ds, dc); /* and try to output */
splx(s);
return (0);
} else { /* if no circuit available */
IF_DROP(&ifp->if_snd); /* drop the data */
m_freem(m);
splx(s);
return (EHOSTUNREACH);
}
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% DDATIMER() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine is entered to perform timer management. The */
/* LCN table is scanned for active timers (nonzero) which are */
/* decremented. If a timer expires (becomes zero), the proper */
/* action is taken. */
/* */
/* */
/* Call: ddatimer(unit) */
/* Arguments: unit: ACP device unit number */
/* Returns: nothing */
/* Called by: ddainit() */
/* Calls to: splimp() */
/* send_restart() */
/* clear_lcn() */
/* splx() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
int
ddatimer(unit)
int unit;
{
register struct dda_softc *ds = &dda_softc[unit];
register struct dda_cb *dc;
register int s, lcn;
#ifdef DDADEBUG
if (DDADBCH(3, unit)) {
DDALOG(LOG_DEBUG) "dda%d: ddatimer()\n", unit DDAELOG;
}
#endif DDADEBUG
ds->dda_if.if_timer = DDA_TIMEOUT; /* restart timer */
dc = ds->dda_cb;
s = splimp();
/* LCNLINK */
for (lcn = 0; lcn <= nddach[unit]; lcn++) { /* scan all LCN's */
#ifdef DDADEBUG
if (dc->dc_out_t && lcn > 0 && (--(dc->dc_out_t) == 0)) {
DDALOG(LOG_DEBUG) "dda%d: write completion timeout lcn %d\n",
unit, lcn DDAELOG;
}
#endif
if (dc->dc_timer && (--(dc->dc_timer) == 0)) { /* if a timer expired */
if (dc->dc_state == LC_RESTART) { /* if a restart was out */
send_restart(ds); /* send another one */
break;
} else { /* otherwise */
#ifdef DDA_PAD_OR_RAW
/* if it is not an X.29 connection */
if ((dc->dc_flags & (DC_X29W | DC_X29 | DC_RAW)) == 0)
#endif
clear_lcn(ds, dc); /* clear the LCN */
}
}
dc++;
}
splx(s);
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% DIAGS_COMPLETED() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine checks to see that power up diagnostics have completed*/
/* It waits for a while if necessary. */
/* Call: diags_completed(ds) */
/* Argument: ds - pointer to softc structure; */
/* Returns: 0 if board is up, EINTR if it never came on line. */
/* Called by: ddaioctl() */
/* Calls to: */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
diags_completed(ds)
struct dda_softc *ds;
{
int nretries = 10;
/*
* It's overkill to check this on EVERY ioctl, because it only matters if
* we are going to touch the board. But the driver has had repeated
* problems with not checking it when it should have - overkill is
* preferred. The delays are here rather then in the acpconfig program
* due to a bug in acpconfig. They will only be executed during
* /etc/rc.local when the board has not had a chance to do the "B"
* interrupt yet. At that time the machine will be running essentially
* single thread so it won't really matter where the delays are. (ie, if
* we put the delay into acpconfig and kept calling here 10 times, the
* machine would not do anything else useful in the meantime - might as
* well loop here).
*/
while (((ds->dda_flags & DDAF_OK) == 0) && nretries-- > 0)
DELAY(3000000);
if ((ds->dda_flags & DDAF_OK) == 0) /* never came on line... */
return (EINTR);
else
return (0);
}
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% %%*/
/*%% LOCAL FUNCTIONS %%*/
/*%% %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% SEND_CONFIG() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* Send a Set System Parameters Message to the front end in */
/* response to an ACPCONFIG command from the user. */
/* */
/* Call: send_config(ds, p) */
/* Argument: ds: pointer to ACP device control structure */
/* p: pointer to the message */
/* Returns: nothing */
/* Called by: ddaioctl() */
/* Calls to: MGET() */
/* DDALOG() */
/* mtod() */
/* bcopy() */
/* sizeof() */
/* start_supr() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
send_config(ds, p)
struct dda_softc *ds;
u_char *p;
{
struct mbuf *m;
register u_char *bp;
int length;
#ifdef DDADEBUG
if (DDADBCH(7, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: send_config()\n", ds->dda_if.if_unit DDAELOG;
}
#endif DDADEBUG
MGET(m, M_DONTWAIT, MT_DATA);
if (m == 0) {
DMESG(ds->dda_if.if_unit, 18,
(DDALOG(LOG_ERR) "dda%d: can't get bfr for acpconfig msg\n",
ds->dda_if.if_unit DDAELOG));
return;
}
bp = mtod(m, u_char *); /* point to data section of mbuf */
length = p[MSG_LENGTH] + MSG_OFFSET; /* msg length */
if (length > MLEN - 1) {
/*
* Supervisory messages have to fit in a small mbuf. The driver
* itself is careful never to get in trouble this way, but now that
* we have "-m" the user could. Dropping such a message is not
* likely to cause any big problems, and the user can rephrase the
* request.
*/
DMESG(ds->dda_if.if_unit, 19,
(DDALOG(LOG_ERR) "dda%d: supervisor message too long\n",
ds->dda_if.if_unit DDAELOG));
m->m_next = 0;
m_freem(m);
return;
}
bcopy(p, bp, length);
m->m_len = length; /* set msg length */
#ifdef DDADEBUG
if (DDADBCH(8, ds->dda_if.if_unit)) {
prt_bytes(ds->dda_if.if_unit, "send_config", bp, length);
}
#endif DDADEBUG
start_supr(ds, m);
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% LOCATE_X25_LCN() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine tries to locate an X25 LCN associated with a */
/* remote internet address. A linear search of the LCN table */
/* is made for a matching address. If the search succeeds, the */
/* LCN is returned. If the search fails, the LCN table is */
/* searched for an unused table entry. If an unused table */
/* entry is found, an X25 call is generated to the host */
/* specified in the destination internet address. If no LCN is */
/* available, zero is returned. */
/* */
/* Call: locate_x25_lcn(ds, ip_addr) */
/* Argument: ds: pointer to dev control block struct */
/* ip_addr: IP address */
/* Returns: pointer to the dda control block which */
/* contains LCN, else zero for failure */
/* Called by: ddaoutput() */
/* Calls to: convert_ip_addr() */
/* make_x25_call() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE struct dda_cb *
locate_x25_lcn(ds, ip_addr)
struct dda_softc *ds;
struct in_addr ip_addr;
{
register int lcn, maxlcn;
register struct dda_cb *dc;
union imp_addr imp_addr;
#ifdef DDADEBUG
if (DDADBCH(9, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: locate_x25_lcn()\n",
ds->dda_if.if_unit DDAELOG;
}
#endif DDADEBUG
imp_addr.ip = ip_addr; /* DDN X.25 doesn't know net number */
if (!(ds->dda_init & DDA_PDN)) {
if ((imp_addr.imp.s_net & 0x80) == 0x00) { /* class A */
imp_addr.imp.s_net = 0;
imp_addr.imp.s_lh = 0;
} else if ((imp_addr.imp.s_net & 0xc0) == 0x80) { /* class B */
imp_addr.imp.s_net = 0;
imp_addr.imp.s_host = 0;
} else { /* class C, should check for class C */
imp_addr.imp.s_net = 0;
imp_addr.imp.s_host = 0;
imp_addr.imp.s_lh = 0;
}
}
/* LCNLINK */
maxlcn = nddach[ds->dda_if.if_unit];
dc = &(ds->dda_cb[1]); /* scan LCN table for addr match */
for (lcn = 1; lcn <= maxlcn; lcn++) {
if ((dc->dc_key.key_addr.s_addr == imp_addr.ip.s_addr)
&& (dc->dc_state == LC_CALL_PENDING || dc->dc_state == LC_DATA_IDLE))
return (dc); /* return LCN */
dc++;
}
if ((dc = find_free_lcn(ds)) == 0)
return (0);
ddacb_user_data[0] = (u_char) 0; /* we have no user data */
if (convert_ip_addr(ip_addr, ddacb_called_addr, ds)
&& make_x25_call(ds, dc, ip_addr, X25_PROTO_IP)) {
/* addr can be converted */
dc->dc_inaddr = ip_addr; /* store dest ip addr */
dc->dc_key.key_addr.s_addr = imp_addr.ip.s_addr;
/* store match key */
#ifdef DDADEBUG
if (DDADBCH(9, ds->dda_if.if_unit)) {
imp_addr.ip = ip_addr;
DDALOG(LOG_DEBUG)
"dda%d: locate_x25_lcn: made call to %d.%d.%d.%d\n",
ds->dda_if.if_unit, imp_addr.imp.s_net, imp_addr.imp.s_host,
imp_addr.imp.s_lh, imp_addr.imp.s_impno DDAELOG;
}
#endif DDADEBUG
return (dc); /* and return the LCN */
} else {
return (0); /* give up */
}
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% FIND_FREE_LCN() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine tries to locate a free X25 LCN. */
/* The LCN table is searched for an unused entry. */
/* If no LCN is available, zero is returned. */
/* */
/* Call: find_free_lcn(ds) */
/* Argument: ds: pointer to dev control block struct */
/* Returns: pointer to the dda control block which */
/* contains LCN, else zero for failure */
/* Called by: locate_x25_lcn() */
/* supr_msg() */
/* xxcntl() */
/* Calls to: DDALOG() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE struct dda_cb *
find_free_lcn(ds)
struct dda_softc *ds;
{
struct dda_cb *dc;
register int lcn, maxlcn, dwnflg = 0;
/* LCNLINK */
dc = &(ds->dda_cb[1]); /* scan LCN table for free entry */
maxlcn = nddach[ds->dda_if.if_unit];
for (lcn = 1; lcn <= maxlcn; lcn++) {
#ifdef DDA_PAD_OR_RAW
if (dc->dc_state == LC_IDLE && (dc->dc_flags & (DC_X29W | DC_X29 | DC_RAW)) == 0)
#else
if (dc->dc_state == LC_IDLE)
#endif DDA_PAD_OR_RAW
break;
else if (dc->dc_state == LC_RESTART || dc->dc_state == LC_DOWN)
dwnflg = 1;
dc++;
}
/* LCNLINK */
if (lcn > maxlcn) { /* if we didn't find a free entry */
if (LOG_BUSY) {
if (dwnflg)
DDALOG(LOG_ERR) "dda%d: no circuits available (link not up)\n",
ds->dda_if.if_unit DDAELOG;
else
DDALOG(LOG_ERR) "dda%d: all circuits in use\n",
ds->dda_if.if_unit DDAELOG;
}
return (0); /* return empty handed */
}
return (dc);
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% CONVERT_IP_ADDR() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* Based on the type of X.25 service, this routine performs */
/* one of two functions. For PDN X.25 service, the address */
/* translation table is searched for presence of local X.25 */
/* address (which was entered by the user via acpconfig). */
/* */
/* For DDN X.25 service, this routine accepts an internet */
/* address and attempts to translate to an equivalent X25 */
/* address. This follows the guidelines in the DDN X25 */
/* interface spec. The resultant X25 address is stored in the */
/* X25 called addr buffer. */
/* */
/* NOTE: Although front end was designed to accept ASCII coded */
/* digits for the address fields, we only supply the binary */
/* values. The front end only uses low four bits to extract */
/* the binary value from the ASCII digits, so this works out. */
/* */
/* */
/* */
/* */
/* */
/* */
/* Call: convert_ip_addr(ip_addr, x25addr, ds) */
/* Argument: ip_addr: IP address */
/* x25addr: X.25 address */
/* ds: &dda_softc[unit] */
/* Returns: 1 for success */
/* Called by: locate_x25_lcn() */
/* make_x25_call() */
/* ddaioctl() */
/* Calls to: bcopy() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE boolean
convert_ip_addr(ip_addr, x25addr, ds)
struct in_addr ip_addr;
u_char x25addr[];
struct dda_softc *ds;
{
register struct dda_addr_tr *atp, *hip, *lop;
register int temp;
union imp_addr imp_addr;
/****************************************************************/
/* processing for Public Data Network (PDN) X.25 service */
/* search address translation table for local address */
/****************************************************************/
if (ds->dda_init & DDA_PDN) {
x25addr[0] = 0; /* clear result X.25 address length */
lop = &dda_addr_tr[ds->dda_if.if_unit][0]; /* set up for binary
* search */
hip = &dda_addr_tr[ds->dda_if.if_unit][dda_num_addr_tr[ds->dda_if.if_unit]];
while (lop < hip - 1) { /* binary search loop */
atp = lop + (hip - lop) / 2;
if (atp->ip_addr > ip_addr.s_addr)
hip = atp;
else
lop = atp;
}
if (lop->ip_addr == ip_addr.s_addr)
bcopy(lop->x25_addr, x25addr, MAXADDRLEN);
}
/****************************************************************/
/* processing for DDN Standard or Basic X.25 service */
/* convert IP address to X.25 address */
/****************************************************************/
else {
int imp_no, imp_port;
imp_addr.ip = ip_addr;
if ((imp_addr.imp.s_net & 0x80) == 0x00) { /* class A */
imp_no = imp_addr.imp.s_impno;
imp_port = imp_addr.imp.s_host;
} else if ((imp_addr.imp.s_net & 0xc0) == 0x80) { /* class B */
imp_no = imp_addr.imp.s_impno;
imp_port = imp_addr.imp.s_lh;
} else { /* class C */
imp_no = imp_addr.imp.s_impno / 32;
imp_port = imp_addr.imp.s_impno % 32;
}
x25addr[0] = 12; /* set addr length */
x25addr[1] = 0; /* clear DNIC */
x25addr[2] = 0;
x25addr[3] = 0;
x25addr[4] = 0;
if (imp_port < 64) { /* Physical: 0000 0 IIIHH00 [SS] *//* s_impno
* -> III, s_host -> HH */
x25addr[5] = 0; /* set flag bit */
x25addr[6] = imp_no / 100;
x25addr[7] = (imp_no % 100) / 10;
x25addr[8] = imp_no % 10;
x25addr[9] = imp_port / 10;
x25addr[10] = imp_port % 10;
} else { /* Logical: 0000 1 RRRRR00 [SS] *//* s
* _host * 256 + s_impno -> RRRRR */
temp = (imp_port << 8) + imp_no;
x25addr[5] = 1;
x25addr[6] = temp / 10000;
x25addr[7] = (temp % 10000) / 1000;
x25addr[8] = (temp % 1000) / 100;
x25addr[9] = (temp % 100) / 10;
x25addr[10] = temp % 10;
}
x25addr[11] = 0; /* clear rest of addr */
x25addr[12] = 0;
}
#ifdef DDADEBUG
if (DDADBCH(11, ds->dda_if.if_unit)) {
imp_addr.ip = ip_addr;
DDALOG(LOG_DEBUG) "dda%d: convert_ip_addr: %d.%d.%d.%d ==> %s\n",
ds->dda_if.if_unit, imp_addr.imp.s_net, imp_addr.imp.s_host,
imp_addr.imp.s_lh, imp_addr.imp.s_impno,
fmt_x25(&x25addr[1], (int) x25addr[0]) DDAELOG;
}
#endif DDADEBUG
return (x25addr[0] ? 1 : 0);
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% CONVERT_X25_ADDR() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine accepts an X25 address and attempts to */
/* translate to an equivalent internet address. For DDA this */
/* follows the guidelines in the DDA X25 interface spec. The */
/* resultant internet address is returned to the caller. */
/* */
/* Call: convert_x25_addr(x25addr, ds) */
/* Argument: x25addr: X.25 address */
/* ds: &dda_softc[unit] */
/* dc: pointer to allocated dda_cb structure */
/* Returns: IP address for success, else zero for fail */
/* Called by: supr_msg() */
/* Calls to: DDALOG() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE u_long
convert_x25_addr(x25addr, ds, dc)
u_char x25addr[];
struct dda_softc *ds;
struct dda_cb *dc;
{
register int cnt, temp;
union imp_addr imp_addr;
register struct dda_addr_tr *atp;
dc->dc_inaddr.s_addr = imp_addr.ip.s_addr = 0L;
if (ds->dda_init & DDA_PDN) {
for (atp = &dda_addr_tr[ds->dda_if.if_unit][0];
atp < &dda_addr_tr[ds->dda_if.if_unit][dda_num_addr_tr[ds->dda_if.if_unit]]; atp++) {
if (bcmp((char *) atp->x25_addr, (char *) x25addr, x25addr[0] + 1) == 0) {
/* set key address and print address up */
dc->dc_inaddr.s_addr = imp_addr.ip.s_addr = atp->ip_addr;
break;
}
}
} else {
int imp_no, imp_port;
struct in_addr my_addr;
my_addr = ds->dda_ipaddr;
if (((cnt = x25addr[0]) < MINADDRLEN - 1) || (cnt > MAXADDRLEN - 1)) {
DMESG(ds->dda_if.if_unit, 20,
(DDALOG(LOG_ERR) "dda%d: illegal X25 address length!\n",
ds->dda_if.if_unit DDAELOG));
return (0L);
}
switch (x25addr[5] & 0x0f) {
case 0: /* Physical: 0000 0 IIIHH00 [SS] */
imp_no =
((int) (x25addr[6] & 0x0f) * 100) +
((int) (x25addr[7] & 0x0f) * 10) +
((int) (x25addr[8] & 0x0f));
imp_port =
((int) (x25addr[9] & 0x0f) * 10) +
((int) (x25addr[10] & 0x0f));
break;
case 1: /* Logical: 0000 1 RRRRR00 [SS] */
temp = ((int) (x25addr[6] & 0x0f) * 10000)
+ ((int) (x25addr[7] & 0x0f) * 1000)
+ ((int) (x25addr[8] & 0x0f) * 100)
+ ((int) (x25addr[9] & 0x0f) * 10)
+ ((int) (x25addr[10] & 0x0f));
imp_port = temp >> 8;
imp_no = temp & 0xff;
break;
default:
DMESG(ds->dda_if.if_unit, 21,
(DDALOG(LOG_ERR) "dda%d: illegal X25 address format!\n",
ds->dda_if.if_unit DDAELOG));
return (0L);
}
dc->dc_inaddr = imp_addr.ip = my_addr; /* use local net number */
if ((imp_addr.imp.s_net & 0x80) == 0x00) { /* class A */
imp_addr.imp.s_net = 0; /* mask net number */
imp_addr.imp.s_lh = 0; /* mask logical host */
imp_addr.imp.s_host = imp_port;
((union imp_addr *) & dc->dc_inaddr.s_addr)->imp.s_host = imp_port;
imp_addr.imp.s_impno = imp_no;
((union imp_addr *) & dc->dc_inaddr.s_addr)->imp.s_impno = imp_no;
} else if ((imp_addr.imp.s_net & 0xc0) == 0x80) { /* class B */
imp_addr.imp.s_net = 0;
imp_addr.imp.s_lh = imp_port;
((union imp_addr *) & dc->dc_inaddr.s_addr)->imp.s_lh = imp_port;
imp_addr.imp.s_host = 0;
imp_addr.imp.s_impno = imp_no;
((union imp_addr *) & dc->dc_inaddr.s_addr)->imp.s_impno = imp_no;
} else { /* class C */
imp_addr.imp.s_impno = (imp_no << 5) + imp_port;
((union imp_addr *) & dc->dc_inaddr.s_addr)->imp.s_impno = imp_addr.imp.s_impno;
imp_addr.imp.s_lh = 0;
imp_addr.imp.s_host = 0;
imp_addr.imp.s_net = 0;
}
}
#ifdef DDADEBUG
if (DDADBCH(12, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: convert_x25_addr: %s ==> %d.%d.%d.%d\n",
ds->dda_if.if_unit, fmt_x25(&x25addr[1], (int) x25addr[0]),
imp_addr.imp.s_net, imp_addr.imp.s_host, imp_addr.imp.s_lh,
imp_addr.imp.s_impno DDAELOG;
}
#endif DDADEBUG
return (imp_addr.ip.s_addr);
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% MAKE_X25_CALL() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine places an X25 call using the X25 Call Msg */
/* buffer. The calling LCN is placed in the appropriate state */
/* and a timer is started. Based on dda_init flag, implement */
/* DDN standard or basic service. (If PDN mode is set, then */
/* the logic for basic service is followed.) */
/* */
/* Call: make_x25_call(ds, dc, ip_addr, proto */
/* udlen, ud) */
/* Arguments: ds: pointer to device control structure */
/* dc: pointer to the Logical Channel control */
/* block structure */
/* ip_addr: callee's ip address */
/* proto: protocol identifier byte */
/* udlen: user data length */
/* ud: user data */
/* Returns: one for success, zero for failure */
/* Called by: locate_x25_lcn() */
/* Calls to: MGET() */
/* mtod() */
/* convert_ip_addr() */
/* bcopy() */
/* IF_ENQUEUE() */
/* start_supr() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE boolean
make_x25_call(ds, dc, ip_addr, proto, udlen, ud)
register struct dda_softc *ds;
register struct dda_cb *dc;
struct in_addr ip_addr;
u_char proto;
u_char udlen;
u_char *ud;
{
register struct mbuf *m_callbfr;
register u_char *cb;
union imp_addr imp_addr;
#if ACC_BSD == 42 || ACC_ULTRIX == 12
struct sockaddr_in *our_addr;
#endif
#ifdef DDADEBUG
if (DDADBCH(13, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: make_x25_call: lcn used = %d\n",
ds->dda_if.if_unit, dc->dc_lcn DDAELOG;
}
#endif DDADEBUG
MGET(m_callbfr, M_DONTWAIT, MT_DATA); /* try to get call cmnd
* buffer */
if (m_callbfr == 0) {
DMESG(ds->dda_if.if_unit, 22,
(DDALOG(LOG_ERR) "dda%d: couldn't get mbuf for call command\n",
ds->dda_if.if_unit DDAELOG));
return (0);
}
cb = mtod(m_callbfr, u_char *);
if (ds->dda_net_id == TRANSPAC) {
ddacb_calling_addr[0] = 0; /* send a 0 length calling address */
} else {
#if ACC_BSD == 42 || ACC_ULTRIX == 12
our_addr = (struct sockaddr_in *) & (ds->dda_if.if_addr);
(void) convert_ip_addr(our_addr->sin_addr, ddacb_calling_addr, ds);
#else
(void) convert_ip_addr(ds->dda_ipaddr, ddacb_calling_addr, ds);
#endif
}
ddacb_protocol[0] = 4;
ddacb_protocol[1] = proto; /* protocol type */
ddacb_protocol[2] = 0;
ddacb_protocol[3] = 0;
ddacb_protocol[4] = 0;
/*
* CCITT standard facilities must precede DDN specific facilities See BBN
* report 5476 section 2.1.2. Firmware preceding rev 0x20 does not
* support packet size / window negotiation.
*/
ddacb_facilities[0] = 0; /* initialize facilities length */
if (ds->dda_firmrev >= 0x21) {
ddacb_facilities[0] = 0;
if (ds->dda_init & DDA_PKTNEG) {
int n = ddacb_facilities[0]; /* length so far */
ddacb_facilities[n + 1] = X25_FACIL_PKTSIZE;
ddacb_facilities[n + 2] = PKTSIZE_LARGE;
ddacb_facilities[n + 3] = PKTSIZE_LARGE;
ddacb_facilities[0] += 3;
}
if (ds->dda_init & DDA_WNDNEG) {
int n = ddacb_facilities[0]; /* length so far */
ddacb_facilities[n + 1] = X25_FACIL_WINSIZE;
ddacb_facilities[n + 2] = WINSIZE_LARGE;
ddacb_facilities[n + 3] = WINSIZE_LARGE;
ddacb_facilities[0] += 3;
}
}
if ((ds->dda_init & (DDA_BASIC | DDA_PDN)) == 0) { /* DDN standard mode,
* tell callee */
int n = ddacb_facilities[0]; /* length so far */
ddacb_facilities[0] += 4; /* additional facility bytes */
ddacb_facilities[n + 1] = DDN_FACIL_MARKER; /* end of CCITT stuff, */
ddacb_facilities[n + 2] = DDN_FACIL_MARKER; /* and start DDN local */
ddacb_facilities[n + 3] = X25_FACIL_DDA; /* DDA standard mode */
ddacb_facilities[n + 4] = FAC_DDASTD;
}
ddacb_cmnd[0] = CALL; /* set command code */
ddacb_cmnd[1] = dc->dc_lcn << 1; /* set channel id */
ddacb_cmnd[2] = 0;
ddacb_cmnd[3] = (ddacb_called_addr[0] + 1) + /* tally cmnd ext len */
(ddacb_calling_addr[0] + 1) +
(ddacb_protocol[0] + 1) +
(ddacb_facilities[0] + 1) +
(ddacb_user_data[0] + 1);
if ((unsigned) ddacb_cmnd[3] + 4 > MLEN) {
DMESG(ds->dda_if.if_unit, 38, (DDALOG(LOG_ERR)
"dda%d: make_x25_call message too large for mbuf (%d bytes)\n",
ds->dda_if.if_unit, (unsigned) ddacb_cmnd[3] + 4 DDAELOG));
return 0; /* failure */
}
m_callbfr->m_len = ddacb_cmnd[3] + 4;
/* copy command header */
bcopy(ddacb_cmnd, cb, 4);
cb += 4;
/* copy called address */
bcopy(ddacb_called_addr, cb, ddacb_called_addr[0] + 1);
cb += (ddacb_called_addr[0] + 1);
/* copy calling address */
bcopy(ddacb_calling_addr, cb, ddacb_calling_addr[0] + 1);
cb += (ddacb_calling_addr[0] + 1);
/* copy protocol */
bcopy(ddacb_protocol, cb, ddacb_protocol[0] + 1);
cb += (ddacb_protocol[0] + 1);
/* copy facilities */
bcopy(ddacb_facilities, cb, ddacb_facilities[0] + 1);
cb += (ddacb_facilities[0] + 1);
/* copy user data */
bcopy(ddacb_user_data, cb, ddacb_user_data[0] + 1);
cb += (ddacb_user_data[0] + 1);
hist_lcn_state(ds->dda_if.if_unit, dc->dc_state, LC_CALL_PENDING);
dc->dc_state = LC_CALL_PENDING; /* set state */
dc->dc_timer = TMO_CALL_PENDING; /* start call timeout */
#ifdef DDADEBUG
if (DDADBCH(13, ds->dda_if.if_unit)) {
prt_bytes(ds->dda_if.if_unit, "make_x25_call: call_bfr",
mtod(m_callbfr, u_char *), m_callbfr->m_len);
}
#endif DDADEBUG
if (LOG_CALLS) {
imp_addr.ip = ip_addr;
DDALOG(LOG_ERR) "dda%d: Calling %d.%d.%d.%d (%s) on lcn %d\n",
ds->dda_if.if_unit, imp_addr.imp.s_net, imp_addr.imp.s_host,
imp_addr.imp.s_lh, imp_addr.imp.s_impno,
fmt_x25(&ddacb_called_addr[1], (int) ddacb_called_addr[0]),
dc->dc_lcn
DDAELOG;
}
start_supr(ds, m_callbfr);
return (1);
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% DDA_START() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine attempts to start output of data queued on a */
/* specific LCN. If the LCN was not already busy and data is */
/* available for output, the data is copied into the LCN's I/O */
/* buffer and a write request queued to the ACP device. Data */
/* is passed in mbuf(s) from IP to ddaoutput(), ddaoutput() */
/* queues the data, and the data is dequeued here. */
/* */
/* Call: dda_start(ds, dc) */
/* Arguments: ds: pointer to device control structure */
/* dc: pointer to the Logical Channel control */
/* block structure */
/* Returns: nothing */
/* Called by: ddaoutput() */
/* x25_init() */
/* make_x25_call() */
/* supr_msg() */
/* send_supr() */
/* dda_data() */
/* dda_supr() */
/* Calls to: IF_DEQUEUE() */
/* dda_wrq() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
dda_start(ds, dc)
register struct dda_softc *ds;
register struct dda_cb *dc;
{
register struct mbuf *m;
register struct hdx_chan *hc = &dc->dc_wchan;
register int s;
#ifdef DDADEBUG
if (DDADBCH(14, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: dda_start()\n", ds->dda_if.if_unit DDAELOG;
}
#endif DDADEBUG
/*
* If output isn't active, attempt to start sending a new packet.
*/
if ((dc->dc_flags & DC_OBUSY) || (dc->dc_oq.ifq_len == 0) ||
((dc->dc_lcn != 0) && (dc->dc_state != LC_DATA_IDLE))) {
return;
}
if (dc->dc_lcn != 0)
dc->dc_timer = tmo_data_idle;
/*
* Raise priority whenever touching dc_oq because
* the mbufs on this queue may be asynchronously
* freed upon receipt of a line status msg, restart,
* clear, or reset.
*/
s = splimp();
IF_DEQUEUE(&dc->dc_oq, m);
splx(s);
if (m == 0) { /* XXX this is a bug catcher XXX */
DMESG(ds->dda_if.if_unit, 24,
(DDALOG(LOG_ERR) "dda%d: dequeued NULL mbuf in IP output chain!\n",
ds->dda_if.if_unit DDAELOG));
DMESG(ds->dda_if.if_unit, 24,
(DDALOG(LOG_ERR) "RESET dda%d MANUALLY: use /etc/acpconfig dda%d -z\n",
ds->dda_if.if_unit, ds->dda_if.if_unit DDAELOG));
ds->dda_if.if_flags &= ~(IFF_RUNNING | IFF_UP);
hist_link_state(ds->dda_if.if_unit, ds->dda_state, S_DISABLED);
ds->dda_state = S_DISABLED;
dda_disable(ds->dda_if.if_unit);
return;
}
s = splimp();
hc->hc_mbuf = m;
hc->hc_curr = m;
#ifdef DDA_PAD_OR_RAW /* crufty kludge to get the Qbit */
if (dc->dc_flags & (DC_X29 | DC_X29W | DC_RAW)) { /* raw or x29? */
if (m->m_len < (MLEN - 1)) /* small mbuf? */
hc->hc_sbfc = m->m_dat[MLEN - 1]; /* ok, get the subfunc byte */
else
hc->hc_sbfc = 0; /* subfunc must be zero for large buffers */
} else
hc->hc_sbfc = 0; /* subfunc must be zero for ip buffers */
#else
hc->hc_sbfc = 0;
#endif
splx(s);
dc->dc_flags |= DC_OBUSY;
dda_wrq(ds, hc, 0); /* write request to ACP */
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% DDA_DATA() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine is called when a data channel I/O completes. */
/* If the completion was for a write, an attempt is made to */
/* start output on the next packet waiting for output on that */
/* LCN. If the completion was for a read, the received packet */
/* is sent to the IP input queue (if no error) and another read */
/* is started on the LCN. */
/* */
/* Call: dda_data(ds, hc, cc, cnt) */
/* Argument: ds: device control block */
/* hc: half duplex channel control block */
/* cc: Mailbox I/O completion status */
/* cnt: byte count */
/* Returns: nothing */
/* Called by: ddainta() */
/* Calls to: m_freem() */
/* dda_start() */
/* IF_QFULL() */
/* IF_DROP() */
/* IF_ENQUEUE() */
/* schednetisr() */
/* dda_rrq() */
/* dda_wrq() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
dda_data(ds, hc, cc, cnt)
register struct dda_softc *ds;
register struct hdx_chan *hc;
int cc, cnt;
{
register struct dda_cb *dc = &(ds->dda_cb[hc->hc_chan / 2]);
struct ifqueue *inq = &ipintrq; /* IP input queue */
/* note that this routine is a weird case in which Ultrix 2.0 behaves like
* a 4.2 system rather than a 4.3 system. This is reflected in the structure
* of conditional compilation segments.
*/
#if ACC_BSD > 42 /* 4.3bsd or newer */
register struct mbuf *m, *mb;
struct ifnet *ifp;
#else /* 4.2, or all flavors of Ultrix */
register struct mbuf *m;
#endif
#ifdef DDADEBUG
if (DDADBCH(18, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: dda_data: chan=%d cc=%x cnt=%x\n",
ds->dda_if.if_unit, hc->hc_chan, cc, cnt DDAELOG;
}
#endif DDADEBUG
#if ACC_BSD > 42
ifp = &ds->dda_if;
#endif
if (hc->hc_chan & 0x01) { /* was it read or write? *//* write, fire up
* next output */
#ifdef DDADEBUG
dc->dc_out_t = TMO_OFF; /* turn off output completion timer */
#endif
hc = &dc->dc_wchan;
if ((hc->hc_func != DDAABT) && (hc->hc_curr = hc->hc_curr->m_next))
dda_wrq(ds, hc, 0);
else {
m_freem(hc->hc_mbuf);
hc->hc_mbuf = hc->hc_curr = (struct mbuf *) 0;
if (hc->hc_func == DDAABT) {
hc->hc_func &= ~DDAABT;
hc->hc_inv &= ~INVALID_MBUF;
} else
ds->dda_if.if_opackets++;
dc->dc_flags &= ~DC_OBUSY;
dda_start(ds, dc);
}
} else { /* read, process rcvd packet */
hc = &dc->dc_rchan;
#ifdef DDADEBUG
if (DDADBCH(19, ds->dda_if.if_unit)) {
u_char *p;
p = mtod(hc->hc_curr, u_char *);
prt_bytes(ds->dda_if.if_unit, "received data", p, (cnt < 64 ? cnt : 64));
}
#endif DDADEBUG
if (cc == DDAIOCOK) { /* Queue good packet for input */
#ifdef DDADEBUG
if (DDADBCH(19, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: dda_data: chan=%d DDAIOCOK\n",
ds->dda_if.if_unit, hc->hc_chan DDAELOG;
}
#endif DDADEBUG
ds->dda_if.if_ipackets++;
hist_lcn_state(ds->dda_if.if_unit, dc->dc_state, LC_DATA_IDLE);
if (dc->dc_state == LC_DATA_IDLE)
dc->dc_timer = tmo_data_idle;
hc->hc_curr->m_len += cnt; /* update byte count */
m = hc->hc_mbuf; /* que mbuf chain */
#if ACC_BSD > 42
/* Prepend ifp pointer for 4.3 */
MGET(mb, M_DONTWAIT, MT_DATA);
if (mb == 0) {
DMESG(ds->dda_if.if_unit, 26,
(DDALOG(LOG_ERR) "dda%d: couldn't get mbuf for ifp header\n",
ds->dda_if.if_unit DDAELOG));
m_freem(m);
return;
}
*(mtod(mb, struct ifnet **)) = ifp;
mb->m_len = sizeof(ifp);
mb->m_next = m;
if (IF_QFULL(inq)) {
IF_DROP(inq);
m_freem(mb);
} else {
IF_ENQUEUE(inq, mb);
schednetisr(NETISR_IP);
}
#else
if (IF_QFULL(inq)) {
IF_DROP(inq);
m_freem(m);
} else {
IF_ENQUEUE(inq, m);
schednetisr(NETISR_IP);
}
#endif
hc->hc_mbuf = hc->hc_curr = (struct mbuf *) 0;
} else if (cc == DDAIOCOKP) { /* good completion, more data pending */
hc->hc_curr->m_len += cnt;
} else {
m_freem(hc->hc_mbuf);
hc->hc_mbuf = hc->hc_curr = (struct mbuf *) 0;
}
/* hang a new data read */
dda_rrq(ds, hc);
}
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% DDA_SUPR() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine is called when a supervisor I/O completes. */
/* If the completion was for a write, an attempt is made to */
/* start output on the next supervisor command waiting for */
/* output. If the completion was for a read, the received */
/* supervisor message is processed and another read is started. */
/* */
/* Call: dda_supr(ds, hc, cc) */
/* Argument: ds: device control block */
/* hc: half duplex channel control block */
/* cc: Mailbox I/O completion status */
/* Returns: nothing */
/* Called by: ddainta() */
/* Calls to: dda_start() */
/* mtod() */
/* supr_msg() */
/* m_free() */
/* dda_rrq() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
dda_supr(ds, hc, cc, cnt)
register struct dda_softc *ds;
struct hdx_chan *hc;
int cc;
int cnt;
{
register struct dda_cb *dc = &(ds->dda_cb[hc->hc_chan / 2]);
u_char *p;
#ifdef DDADEBUG
if (DDADBCH(20, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: dda_supr: chan=%d cc=%x\n",
ds->dda_if.if_unit, hc->hc_chan, cc DDAELOG;
}
#endif DDADEBUG
/* an odd-numbered channel indicates a write */
/* the supr msg is assumed to be in 1 mbuf */
if (hc->hc_chan & 0x01) {
m_freem(hc->hc_mbuf);
hc->hc_mbuf = hc->hc_curr = (struct mbuf *) 0;
dc->dc_flags &= ~DC_OBUSY;
dda_start(ds, dc);
}
/* otherwise, process the read */
else {
if (cc == DDAIOCOK) {
p = mtod(hc->hc_curr, u_char *); /* point to data in mbuf */
#ifdef DDA_PAD_OR_RAW
switch (dda_decode_type(ds, p)) {
# ifdef DDA_PADOPT
case 1:
# ifdef DDADEBUG
if (DDADBCH(20, ds->dda_if.if_unit)) {
printf("dda%d: dda_supr(): case 1: chan = %x, p = %x\n",
ds->dda_if.if_unit, hc->hc_chan, *p);
}
# endif DDADEBUG
x29_supr(ds, p);
break;
# endif
# ifdef DDA_RAWOPT
case 2:
# ifdef DDADEBUG
if (DDADBCH(20, ds->dda_if.if_unit)) {
printf("dda%d: dda_supr(): case 2: chan = %x, p = %x\n",
ds->dda_if.if_unit, hc->hc_chan, *p);
}
# endif DDADEBUG
hc->hc_curr->m_len += cnt;
pi_supr(ds, hc->hc_curr);
/* don't free mbuf here */
hc->hc_mbuf = hc->hc_curr = (struct mbuf *) 0;
dda_rrq(ds, hc);/* hang a new supr read */
return;
# endif
default:
supr_msg(ds, p);/* process supervisor message */
break;
}
#else DDA_PAD_OR_RAW
supr_msg(ds, p); /* process supervisor message */
#endif DDA_PAD_OR_RAW
} else if (cc == DDAIOCOKP) {
DMESG(ds->dda_if.if_unit, 28,
(DDALOG(LOG_ERR) "dda%d: truncated supervisor message\n",
ds->dda_if.if_unit DDAELOG));
}
m_freem(hc->hc_mbuf);
hc->hc_mbuf = hc->hc_curr = (struct mbuf *) 0;
dda_rrq(ds, hc); /* hang a new supr read */
}
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% SUPR_MSG() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine processes received supervisor messages. */
/* Depending on the message type, the appropriate action is */
/* taken. */
/* */
/* Call: supr_msg(ds, p) */
/* Arguments: ds: pointer to dev control block struct */
/* p: pointer to a character array */
/* containing the supervisor message */
/* Returns: nothing */
/* Called by: dda_supr() */
/* Calls to: DDALOG() */
/* IF_DEQUEUE() */
/* m_freem() */
/* send_restart() */
/* send_supr() */
/* dda_start() */
/* decode_ring() */
/* decode_answer() */
/* convert_x25_addr() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
supr_msg(ds, p)
struct dda_softc *ds;
u_char p[];
{
register struct dda_cb *dc;
register int lcn;
register int maxlcn;
union imp_addr imp_addr;
#ifdef DDADEBUG
if (DDADBCH(21, ds->dda_if.if_unit)) {
prt_bytes(ds->dda_if.if_unit, "supr_msg", p, (int) (4 + p[3]));
}
#endif DDADEBUG
maxlcn = nddach[ds->dda_if.if_unit]; /* obtain SVC limit */
switch (p[0]) {
case LINE_STATUS: /* link status msg */
if (p[2] == LINK_UP) { /* if link came up */
#ifdef DDADEBUG
if (DDADBCH(21, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: supr_msg: HDLC link up\n",
ds->dda_if.if_unit DDAELOG;
}
#endif DDADEBUG
send_restart(ds); /* send restart msg */
ds->dda_state = S_COMING_UP;
} else { /* if link went down */
ds->dda_if.if_flags &= ~IFF_UP; /* ? should call if_down() ? */
hist_link_state(ds->dda_if.if_unit, ds->dda_state, S_DISABLED);
ds->dda_state = S_DISABLED;
dc = ds->dda_cb;
/* LCNLINK */
for (lcn = 0; lcn <= maxlcn; lcn++) { /* for all LCN's */
dc->dc_inaddr.s_addr = 0; /* forget dest address */
dc->dc_key.key_addr.s_addr = 0;
dc->dc_wsizein = dc->dc_wsizeout = 0;
dc->dc_pktsizein = dc->dc_pktsizeout = 0;
dc->dc_state = LC_DOWN; /* set state */
dc->dc_timer = TMO_OFF; /* stop timer */
dc++;
}
hist_all_lcns(ds->dda_if.if_unit, LC_DOWN);
abort_io(ds->dda_if.if_unit, ALL_CHANS);
#ifdef DDA_PADOPT
x29_init(ds->dda_if.if_unit, 1);
#endif
if (p[2] == LINK_DISABLED) /* link disabled */
DMESG(ds->dda_if.if_unit, 29,
(DDALOG(LOG_ERR) "dda%d: link disabled\n",
ds->dda_if.if_unit DDAELOG));
else
DMESG(ds->dda_if.if_unit, 30,
(DDALOG(LOG_ERR) "dda%d: link down\n", ds->dda_if.if_unit DDAELOG));
}
break;
case RESTART: /* restart received */
if (ds->dda_cb[0].dc_state != LC_RESTART) { /* if not restarting */
#ifdef DDADEBUG
if (DDADBCH(21, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG)
"dda%d: supr_msg: RESTART rcvd, no RESTART pending\n",
ds->dda_if.if_unit DDAELOG;
}
#endif DDADEBUG
send_supr(ds, RSTRT_ACK, 0, 0); /* send restart ack */
}
/* fall thru */
case RSTRT_ACK: /* restart ack */
if ((ds->dda_state == S_COMING_UP) || (ds->dda_state == S_LINK_UP)) {
if (p[0] == RSTRT_ACK) {
DMESG(ds->dda_if.if_unit, 31,
(DDALOG(LOG_ERR) "dda%d: Restart Ack received\n",
ds->dda_if.if_unit DDAELOG));
} else { /* restart. print cause and diagnostic. */
DMESG(ds->dda_if.if_unit, 31,
(DDALOG(LOG_ERR) "dda%d: Restart (%x %x) received\n",
ds->dda_if.if_unit, p[2], p[3] ? p[4] : 0 DDAELOG));
}
ds->dda_if.if_flags |= IFF_UP;
hist_link_state(ds->dda_if.if_unit, ds->dda_state, S_LINK_UP);
ds->dda_state = S_LINK_UP;
dc = ds->dda_cb;
/* LCNLINK */
for (lcn = 0; lcn <= maxlcn; lcn++) { /* for all LCN's */
dc->dc_state = LC_IDLE; /* set state */
dc->dc_timer = TMO_OFF; /* stop timer */
dc->dc_inaddr.s_addr = 0; /* forget address */
dc->dc_key.key_addr.s_addr = 0;
dc->dc_wsizein = dc->dc_wsizeout = 0;
dc->dc_pktsizein = dc->dc_pktsizeout = 0;
dc++;
}
hist_all_lcns(ds->dda_if.if_unit, LC_IDLE);
abort_io(ds->dda_if.if_unit, ALL_CHANS);
DMESG(ds->dda_if.if_unit, 32,
(DDALOG(LOG_ERR) "dda%d: (%s rev %d.%d) link up\n",
ds->dda_if.if_unit, dda_product,
(ds->dda_firmrev >> 4) & 0xF, ds->dda_firmrev & 0xF DDAELOG));
#ifdef DDA_PAD_OR_RAW
x29_init(ds->dda_if.if_unit, 1);
/*
* wake up all processes that tried to open a x29 device but
* slept because the board was not up
*/
wakeup(&ds->dda_state);
#endif DDA_PAD_OR_RAW
} else
#ifdef DDADEBUG
if (DDADBCH(21, ds->dda_if.if_unit)) {
DDALOG(LOG_ERR) "dda%d: Unexpected RESTART in state %x\n",
ds->dda_if.if_unit, ds->dda_state DDAELOG;
}
#endif DDADEBUG
break;
case ANSWER: /* call answered */
lcn = p[1] / 2;
dc = &(ds->dda_cb[lcn]);
if (dc->dc_state == LC_CALL_PENDING) { /* if a call pending */
hist_lcn_state(ds->dda_if.if_unit, dc->dc_state, LC_DATA_IDLE);
decode_answer(p, dc);
dc->dc_state = LC_DATA_IDLE; /* set state */
dc->dc_timer = tmo_data_idle; /* start timer */
dda_start(ds, dc); /* try to send data */
}
if (LOG_CALLS) {
DDALOG(LOG_ERR) "dda%d: lcn %d connected\n",
ds->dda_if.if_unit, lcn DDAELOG;
}
break;
case RING: /* incoming call */
/* if ring looks ok, and we find a free LCN to assign */
if (decode_ring(p) && (dc = find_free_lcn(ds))) {
dc->dc_key.key_addr.s_addr =
convert_x25_addr(ddacb_calling_addr, ds, dc);
#ifdef DDADEBUG
if (DDADBCH(21, ds->dda_if.if_unit)) {
imp_addr.ip = dc->dc_inaddr;
DDALOG(LOG_DEBUG)
"dda%d: supr_msg: got call from %d.%d.%d.%d\n",
ds->dda_if.if_unit, imp_addr.imp.s_net, imp_addr.imp.s_host,
imp_addr.imp.s_lh, imp_addr.imp.s_impno DDAELOG;
}
#endif DDADEBUG
hist_lcn_state(ds->dda_if.if_unit, dc->dc_state, LC_DATA_IDLE);
dc->dc_state = LC_DATA_IDLE; /* set state */
dc->dc_timer = tmo_data_idle; /* start timer */
dc->dc_pktsizein = 0;
dc->dc_pktsizeout = 0;
dc->dc_wsizein = 0;
dc->dc_wsizeout = 0;
send_supr(ds, ANSWER, (int) dc->dc_lcn * 2,
(int) p[2]); /* send answer */
if (LOG_CALLS) {
imp_addr.ip = dc->dc_inaddr;
DDALOG(LOG_ERR)
"dda%d: Accepting call from %d.%d.%d.%d (%s) on lcn %d\n",
ds->dda_if.if_unit, imp_addr.imp.s_net, imp_addr.imp.s_host,
imp_addr.imp.s_lh, imp_addr.imp.s_impno,
fmt_x25(&ddacb_calling_addr[1],
(int) ddacb_calling_addr[0]), dc->dc_lcn DDAELOG;
}
} else { /* if no free LCN's */
send_supr(ds, CLEARVC, p[2], 0); /* clear call */
if (LOG_CALLS) {
DDALOG(LOG_ERR) "dda%d: Rejecting call from %s on VC 0x%x\n",
ds->dda_if.if_unit,
fmt_x25(&ddacb_calling_addr[1], ddacb_calling_addr[0]),
p[1] DDAELOG;
}
}
break;
case CLEARLC: /* clear by LCN */
/*
* This could mean one of three things: If we have a call request
* outstanding, this message means the call has failed. If we have a
* clear request outstanding, this message completes the cleanup; the
* channel is now available for reuse. If we have a call active, this
* message means the other side is closing the circuit.
*/
lcn = p[1] / 2; /* get LCN */
dc = &(ds->dda_cb[lcn]);
if (dc->dc_state != LC_CLR_PENDING) { /* if no clear pending */
send_supr(ds, CLEARLC, p[1], 0); /* ack the clear */
}
if (dc->dc_state == LC_CALL_PENDING /* if call is cleared */
&& (LOG_CALLS || DMESGVAL(ds->dda_if.if_unit, 33) == 0)) {
imp_addr.ip = dc->dc_inaddr;
DDALOG(LOG_ERR)
"dda%d: Call to %d.%d.%d.%d on lcn %d failed (%x %x)\n",
ds->dda_if.if_unit, imp_addr.imp.s_net, imp_addr.imp.s_host,
imp_addr.imp.s_lh, imp_addr.imp.s_impno, dc->dc_lcn, p[2], p[4]
DDAELOG;
} else if (LOG_CALLS) {
if (dc->dc_state == LC_CLR_PENDING) { /* did we clear it? *//* y
* es, IP address is
* already gone. Say
* channel is free. */
DDALOG(LOG_ERR) "dda%d: Cleared lcn %d\n",
ds->dda_if.if_unit, dc->dc_lcn DDAELOG;
} else { /* cleared by net, print more info */
imp_addr.ip = dc->dc_inaddr;
DDALOG(LOG_ERR)
"dda%d: Cleared lcn %d to %d.%d.%d.%d (%x %x)\n",
ds->dda_if.if_unit, dc->dc_lcn, imp_addr.imp.s_net,
imp_addr.imp.s_host, imp_addr.imp.s_lh, imp_addr.imp.s_impno,
p[2], p[4] DDAELOG;
}
}
hist_lcn_state(ds->dda_if.if_unit, dc->dc_state, LC_IDLE);
/* LCNLINK delete */
dc->dc_state = LC_IDLE; /* set state */
dc->dc_timer = TMO_OFF; /* stop timer */
dc->dc_inaddr.s_addr = 0; /* forget address */
dc->dc_key.key_addr.s_addr = 0;
dc->dc_wsizein = dc->dc_wsizeout = 0;
dc->dc_pktsizein = dc->dc_pktsizeout = 0;
abort_io(ds->dda_if.if_unit, lcn);
if (LOG_CALLS) {
printf("dda%d: Cleared LCN %d cause code %x diag code %x\n",
ds->dda_if.if_unit, dc->dc_lcn, p[2], p[4]);
}
break;
case CLEARVC: /* clear by VCN */
send_supr(ds, CLEARVC, p[1], 0); /* send clear ack */
if (LOG_CALLS) {
DDALOG(LOG_ERR) "dda%d: Network cleared VC %x (%x %x)\n",
ds->dda_if.if_unit, p[1], p[2], p[4] DDAELOG;
}
#ifdef DDADEBUG
else if (DDADBCH(21, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: supr_msg: CLEARVC VCN=%x\n",
ds->dda_if.if_unit, p[1] DDAELOG;
}
#endif DDADEBUG
break;
case RESET: /* X25 reset */
lcn = p[1] / 2; /* get LCN */
dc = &(ds->dda_cb[lcn]);
send_supr(ds, RESET_ACK, p[1], 0); /* send reset ack */
abort_io(ds->dda_if.if_unit, lcn);
imp_addr.ip = dc->dc_inaddr;
DMESG(ds->dda_if.if_unit, 34,
(DDALOG(LOG_ERR)
"dda%d: X25 RESET (%x %x) on lcn %d: %d.%d.%d.%d\n",
ds->dda_if.if_unit, p[2], p[4], lcn, imp_addr.imp.s_net,
imp_addr.imp.s_host, imp_addr.imp.s_lh, imp_addr.imp.s_impno
DDAELOG));
break;
case INTERRUPT: /* X25 interrupt */
lcn = p[1] / 2; /* get LCN */
dc = &(ds->dda_cb[lcn]);
imp_addr.ip = dc->dc_inaddr;
DMESG(ds->dda_if.if_unit, 35,
(DDALOG(LOG_ERR)
"dda%d: X25 INTERRUPT (%x) on lcn %d: %d.%d.%d.%d\n",
ds->dda_if.if_unit, p[2], lcn, imp_addr.imp.s_net,
imp_addr.imp.s_host, imp_addr.imp.s_lh, imp_addr.imp.s_impno
DDAELOG));
break;
case STATRESP: /* Statistics Response from FEP */
/*
* Copy the whole message into a static buffer, dda_iobuf. The buffer
* is viewed as a (struct ddactl). Wake up the ioctl thread which
* will copy the message out for acpconfig.
*/
{
struct ddactl *da = (struct ddactl *) dda_iobuf;
bcopy(p, da->msg, max(4 + p[3], sizeof(da->msg)));
#ifdef MULTINET
StatQuery_Completed = 1;
#else
wakeup(dda_iobuf);
#endif
break;
}
default:
DMESG(ds->dda_if.if_unit, 36,
(DDALOG(LOG_ERR) "dda%d: supervisor error (%x %x %x %x)\n",
ds->dda_if.if_unit, p[0], p[1], p[2], p[3] DDAELOG));
}
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% DECODE_ANSWER() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* This routine looks at the answer message from the FE */
/* and decodes it to find the negtiated packet and window sizes */
/* if they are present. */
/* */
/* Call: decode_answer(p, dc) */
/* Argument: p: pointer to mbuf data for ANSWER message */
/* dc: pointer to relavant lcn structure */
/* Returns: nothing */
/* Called by: supr_msg() */
/* Calls to: */
/* DDALOG() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
decode_answer(p, dc)
u_char *p;
struct dda_cb *dc;
{
register u_char *cp;
int i, faclen;
dc->dc_pktsizein = 0;
dc->dc_pktsizeout = 0;
dc->dc_wsizein = 0;
dc->dc_wsizeout = 0;
cp = p + 4; /* skip over code, lcn, vcn and count in
* answer message */
/* cp now points to length of called address */
cp += *cp + 1; /* skip over called address and length byte */
/* cp now points to length of calling address */
cp += *cp + 1; /* skip over calling address and length byte */
/* cp now points to length of protocol */
cp += *cp + 1; /* skip over protocol and protocol length
* byte */
/* cp now points to the facilities length */
faclen = *cp++;
/* cp now points to start of facilities */
for (i = 0; i < faclen;) {
switch (*cp & 0xc0) {
case 0x00: /* single octet parameter field */
i += 2;
cp += 2;
break;
case 0x40: /* double octet parameter field */
switch (*cp) {
case X25_FACIL_PKTSIZE: /* 0x42, packet size */
dc->dc_pktsizein = *(cp + 1);
dc->dc_pktsizeout = *(cp + 2);
break;
case X25_FACIL_WINSIZE: /* 0x43, window size */
dc->dc_wsizein = *(cp + 1);
dc->dc_wsizeout = *(cp + 2);
break;
}
i += 3;
cp += 3;
break;
case 0x80: /* triple octet parameter field */
i += 4;
cp += 4;
break;
case 0xc0: /* variable-length parameter field */
cp++;
i += 2 + *cp;
cp += 1 + *cp;
break;
/* Note: No other cases (i.e., default) possible */
}
}
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% DECODE_RING() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine parses and validates the incoming call message. */
/* */
/* Call: decode_ring(p) */
/* Argument: p: pointer to the message */
/* Returns: 1 for success, else 0 for failure */
/* Called by: supr_msg() */
/* Calls to: bcopy() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE boolean
decode_ring(p)
register u_char *p;
{
register int cnt;
#ifdef DDADEBUG
if (DDADBCH(22, 0)) { /* no easy access to unit, assume unit 0 */
DDALOG(LOG_DEBUG) "dda: decode_ring()\n" DDAELOG;
}
#endif DDADEBUG
p += 3; /* skip to cmnd ext length */
if (*p++ < 5) /* is count appropriate */
return (0); /* return false if not */
/* called address */
if ((cnt = *p + 1) > 16) /* is called addr len legal? */
return (0); /* return false if not */
bcopy(p, ddacb_called_addr, cnt); /* copy field */
p += cnt;
/* calling address */
if ((cnt = *p + 1) > 16) /* is calling addr len legal? */
return (0); /* return false if not */
bcopy(p, ddacb_calling_addr, cnt); /* copy field */
p += cnt;
/* protocol part of user data */
if ((cnt = *p + 1) > 5) /* is protocol len legal? */
return (0); /* return false if not */
bcopy(p, ddacb_protocol, cnt); /* copy field */
p += cnt;
/* facilities */
if ((cnt = *p + 1) > 64) /* is facilities len legal? */
return (0); /* return false if not */
bcopy(p, ddacb_facilities, cnt); /* copy field */
p += cnt;
/* ignore rest of user data for now */
#ifdef DDA_PAD_OR_RAW
if (ddacb_protocol[0] == 0)
return (0);
#else DDA_PAD_OR_RAW
if ((ddacb_protocol[0] == 0) || (ddacb_protocol[1] != X25_PROTO_IP))
return (0); /* bad if not IP */
#endif DDA_PAD_OR_RAW
#ifndef DDA_PAD_OR_RAW
return (1); /* looks ok */
#else
# ifdef DDA_RAWOPT
return (1); /* anything is ok if we're PI interface */
# else
if (ddacb_protocol[1] == X25_PROTO_IP || ddacb_protocol[1] == X25_PROTO_X29)
return (1); /* looks ok */
else
return (0); /* bad if not IP or X29 */
# endif
#endif DDA_PAD_OR_RAW
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% CLEAR_LCN() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine clears an X25 circuit and releases any buffers */
/* queued for transmission. */
/* */
/* Call: clear_lcn(ds, dc) */
/* Argument: ds: pointer to dev control block struct */
/* dc: pointer to the Logical Channel control */
/* block structure */
/* Returns: nothing */
/* Called by: ddatimer() */
/* Calls to: IF_DEQUEUE() */
/* m_freem() */
/* send_supr() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
clear_lcn(ds, dc)
struct dda_softc *ds;
struct dda_cb *dc;
{
register struct mbuf *m;
register int s;
#ifdef DDADEBUG
if (DDADBCH(23, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: clear_lcn(%d)\n", ds->dda_if.if_unit,
dc->dc_lcn DDAELOG;
}
#endif DDADEBUG
if (dc->dc_state == LC_CLR_PENDING) { /* Unfortunately, we can't
* display the destination's
* IP address, as we cleared
* it when we entered
* clear-pending state (to
* prevent new data from
* being queued to this
* channel). */
DMESG(ds->dda_if.if_unit, 37,
(DDALOG(LOG_ERR) "dda%d: Clear request lost -- lcn %d\n",
ds->dda_if.if_unit, dc->dc_lcn DDAELOG));
return;
}
hist_lcn_state(ds->dda_if.if_unit, dc->dc_state, LC_CLR_PENDING);
dc->dc_state = LC_CLR_PENDING; /* set state */
dc->dc_timer = TMO_CLR_PENDING; /* start clear timer */
dc->dc_inaddr.s_addr = 0; /* clear associated address */
dc->dc_key.key_addr.s_addr = 0;
dc->dc_wsizein = dc->dc_wsizeout = 0;
dc->dc_pktsizein = dc->dc_pktsizeout = 0;
/*
* Raise priority whenever dc_oq is touched.
*/
s = splimp();
while (dc->dc_oq.ifq_len) { /* drop any pending data */
IF_DEQUEUE(&dc->dc_oq, m);
m_freem(m);
}
splx(s);
send_supr(ds, CLEARLC, (int) dc->dc_lcn * 2, 0); /* send clear msg */
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% SEND_RESTART() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine marks all LCNs as being in a restarting state */
/* and sends a restart command to X25. */
/* */
/* Call: send_restart(ds) */
/* Argument: ds: pointer to dev control block struct */
/* Returns: nothing */
/* Called by: ddatimer() */
/* supr_msg() */
/* Calls to: IF_DEQUEUE() */
/* m_freem() */
/* send_supr() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
send_restart(ds)
struct dda_softc *ds;
{
register struct dda_cb *dc;
register int lcn;
register int maxlcn;
#ifdef DDADEBUG
if (DDADBCH(24, ds->dda_if.if_unit)) {
DDALOG(LOG_DEBUG) "dda%d: send_restart()\n", ds->dda_if.if_unit DDAELOG;
}
#endif DDADEBUG
dc = ds->dda_cb;
/* LCNLINK */
maxlcn = nddach[ds->dda_if.if_unit];
for (lcn = 0; lcn <= maxlcn; lcn++) { /* for all LCN's */
dc->dc_state = LC_RESTART; /* set state */
dc->dc_timer = TMO_RESTART; /* start restart timeout */
dc->dc_inaddr.s_addr = 0; /* forget address */
dc->dc_key.key_addr.s_addr = 0;
dc->dc_wsizein = dc->dc_wsizeout = 0;
dc->dc_pktsizein = dc->dc_pktsizeout = 0;
dc++;
}
hist_all_lcns(ds->dda_if.if_unit, LC_RESTART);
abort_io(ds->dda_if.if_unit, ALL_CHANS);
send_supr(ds, RESTART, 0, 0); /* send restart msg */
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% SEND_SUPR() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine is used to send short (4 bytes only) supervisor */
/* commands, except that longer ANSWER messages may be sent. */
/* */
/* Call: send_supr(ds, cmd, p1, p2) */
/* Argument: ds: pointer to dev control block struct */
/* cmd: type of command */
/* p1: 2nd byte of supervisor message */
/* p2: 3rd byte of supervisor message */
/* Returns: nothing */
/* Called by: supr_msg() */
/* clear_lcn() */
/* send_restart() */
/* Calls to: MGET() */
/* DDALOG() */
/* mtod() */
/* IF_ENQUEUE() */
/* dda_start() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
send_supr(ds, cmd, p1, p2)
struct dda_softc *ds;
int cmd, p1, p2;
{
struct mbuf *m;
register u_char *cp;
u_char *savcp, *fp, *svcp;
int i, faclen;
MGET(m, M_DONTWAIT, MT_DATA);
if (m == 0) {
DMESG(ds->dda_if.if_unit, 23,
(DDALOG(LOG_ERR) "dda%d: failed to get supr msg bfr!\n",
ds->dda_if.if_unit DDAELOG));
return;
}
cp = savcp = mtod(m, u_char *);
/* build supervisor message */
*cp++ = (u_char) cmd;
*cp++ = (u_char) p1;
*cp++ = (u_char) p2;
*cp++ = 0;
m->m_len = 4;
if (cmd == ANSWER) {
register struct dda_cb *dc;
/* for answer messages p1 is (lcn * 2) */
dc = &(ds->dda_cb[p1 / 2]);
*cp++ = 0; /* zero length called address */
*cp++ = 0; /* zero length calling address */
*cp++ = 0; /* zero length protocol */
/* check and copy facilities */
faclen = 0;
svcp = cp++;
for (i = 0, fp = &ddacb_facilities[1]; i < ddacb_facilities[0];) {
switch (*fp & 0xc0) {
case 0x00: /* single octet parameter field */
i += 2;
fp += 2;
break;
case 0x40: /* double octet parameter field */
/*
* Note that this code can in some cases attempt to negotiate
* the packet size or window away from the default, which
* appears to violate the X.25 spec. In fact, the FEP
* examines these values and bounds them between the
* requested value and the default value thus satisfying X.25
*/
switch (*fp) {
case X25_FACIL_PKTSIZE: /* 0x42, packet size */
*cp++ = X25_FACIL_PKTSIZE;
if (ds->dda_firmrev < 0x21) {
*cp++ = PKTSIZE_DEF; /* Set incoming and outgoing */
*cp++ = PKTSIZE_DEF; /* packet size to default */
dc->dc_pktsizein = dc->dc_pktsizeout = PKTSIZE_DEF;
} else {
*cp++ = *(fp + 1); /* Answer with requested */
*cp++ = *(fp + 2); /* facilities */
dc->dc_pktsizeout = *(fp + 1);
dc->dc_pktsizein = *(fp + 2);
}
faclen += 3;
break;
case X25_FACIL_WINSIZE: /* 0x43, window size */
*cp++ = X25_FACIL_WINSIZE;
if (ds->dda_firmrev < 0x21) {
*cp++ = WINSIZE_DEF; /* Set incoming and outgoing */
*cp++ = WINSIZE_DEF; /* window size to default */
dc->dc_wsizein = dc->dc_wsizeout = WINSIZE_DEF;
} else {
*cp++ = *(fp + 1); /* Answer with requested */
*cp++ = *(fp + 2); /* facilities */
dc->dc_wsizeout = *(fp + 1);
dc->dc_wsizein = *(fp + 2);
}
faclen += 3;
break;
}
i += 3;
fp += 3;
break;
case 0x80: /* triple octet parameter field */
i += 4;
fp += 4;
break;
case 0xc0: /* variable-length parameter field */
fp++;
i += 2 + *fp;
fp += 1 + *fp;
break;
/* Note: No other cases (i.e., default) possible */
}
}
if (faclen) { /* Found facilities to negotiate! */
*svcp = faclen; /* facility length <- faclen */
*cp++ = 0; /* user data length <- 0 */
*(savcp + 3) = cp - savcp - 4; /* set supv message length */
m->m_len = cp - savcp; /* set mbuf message length */
}
} /* (end of answer message case) */
# ifdef DDADEBUG
if (DDADBCH(25, ds->dda_if.if_unit)) {
prt_bytes(ds->dda_if.if_unit, "send_supr", savcp, m->m_len);
}
#endif DDADEBUG
start_supr(ds, m);
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% START_SUPR() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* Start i/o on the supervisor channel, checking for queue full. */
/* Added to revision 2.0 so that "queue full" checking would be */
/* applied uniformly to all supervisory channel output. */
/* */
/* Call: start_supr(ds, m) */
/* Argument: ds: softc structure for board */
/* m: mbuf holding message */
/* Returns: nothing */
/* Called by: send_supr(), send_config(), make_x25_call() */
/* Calls to: DDALOG(), dda_start(), IF_ENQUEUE() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
start_supr(ds, m)
struct dda_softc *ds;
struct mbuf *m;
{
register int s;
#ifdef DDADEBUG
if (DDADBCH(27, ds->dda_if.if_unit))
DDALOG(LOG_DEBUG) "dda%d: start_supr\n", ds->dda_if.if_unit DDAELOG;
#endif DDADEBUG
if (IF_QFULL(&(ds->dda_cb[0].dc_oq))) {
DMESG(ds->dda_if.if_unit, 27,
(DDALOG(LOG_ERR) "dda%d: supervisory channel overflow (maxlen=%d)\n",
ds->dda_if.if_unit, ds->dda_cb[0].dc_oq.ifq_maxlen DDAELOG));
ds->dda_cb[0].dc_oq.ifq_maxlen += ds->dda_cb[0].dc_oq.ifq_maxlen;
}
/*
* Raise priority whenever you touch dc_oq.
* We do not want to be interrupted in the middle of adding
* an mbuf to the output queue because the interrupt may indicate
* a condition that will cause the mbuf to be freed.
* (The mbufs are freed on receipt of a line status msg, restart,
* clear, or reset.)
*/
s = splimp();
#ifdef DDA_PAD_OR_RAW
m->m_dat[MLEN - 1] = 0;
#endif
IF_ENQUEUE(&(ds->dda_cb[0].dc_oq), m);
splx(s);
dda_start(ds, &(ds->dda_cb[0]));
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% ABORT_IO() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* Abort outstanding I/O upon receipt of a line status message, */
/* restart, clear, or reset. */
/* The contents of the output queue (dc_oq) is cleared for each */
/* lcn; all I/O queued on either the read or write queue */
/* (dc_rchan and dc_wchan) is marked invalid; all I/O queued on */
/* the sioq is marked invalid; */
/* */
/* Call: abort_io() */
/* Argument: none */
/* Returns: nothing */
/* Called by: */
/* Calls to: IF_DEQUEUE() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
abort_io(unit, lcn)
int unit, lcn;
{
register struct dda_cb *dc;
register struct dda_softc *ds = &dda_softc[unit];
register struct hdx_chan *hc;
register struct mbuf *m;
register int lchan;
register int s;
register struct hdx_chan *ptr;
int start, end;
/* set up range of lcns affected */
if (lcn == ALL_CHANS) {
start = 1;
end = nddach[unit];
} else
start = end = lcn;
#ifdef DDADEBUG
if (DDADBCH(28, unit))
DDALOG(LOG_DEBUG) "dda%d: abort_io on lcn's %d - %d\n",
unit, start, end DDAELOG;
#endif DDADEBUG
s = splimp();
/*
* Invalidate writes on the sioq for specified channel(s)
*/
if (ptr = ds->dda_sioq.sq_head)
for (; ptr; ptr = ptr->hc_next) /* scan sioq */
if ((ptr->hc_chan & 0x01) &&
((lcn == ALL_CHANS) || (lcn == ptr->hc_chan >> 1))
&& (ptr->hc_chan != 1)) {
#ifdef DDADEBUG
if (DDADBCH(28, unit))
DDALOG(LOG_DEBUG)
"dda%d: abort_io--invalidating sioq lcn %d\n",
unit, ptr->hc_chan >> 1 DDAELOG;
#endif DDADEBUG
ptr->hc_inv |= INVALID_MBUF;
}
/*
* For each selected lcn, clear the output queue and
* add an hdx struct to the sioq that will generate an
* abort.
*/
for (lchan = start; lchan <= end; lchan++) { /* for selected LCNs */
dc = &dda_softc[unit].dda_cb[lchan];
hc = &dc->dc_wchan;
while (dc->dc_oq.ifq_len) {
IF_DEQUEUE(&dc->dc_oq, m);
m_freem(m);
}
if (hc->hc_mbuf && !(hc->hc_inv & INVALID_MBUF)) {
if (dc->dc_flags & DC_OBUSY) { /* output pending */
#ifdef DDADEBUG
if (DDADBCH(28, unit))
DDALOG(LOG_DEBUG)
"dda%d: abort_io--queueing abort: lcn %d\n",
unit, lchan DDAELOG;
#endif DDADEBUG
hc->hc_inv |= INVALID_MBUF;
hc->hc_func = DDAABT;
/*
* Add to the sioq
*/
dda_wrq(ds, hc, DDAABT);
}
}
}
splx(s);
}
#ifdef DDADEBUG
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% PRT_BYTES() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine is used to print a label, followed by the contents of */
/* a buffer in hex, 16 bytes per line. Each line is preceded by */
/* the device name and unit number. */
/* */
/* Call: prt_bytes(unit, label, bp, cnt) */
/* Argument: unit: dda unit number to be displayed */
/* label: pointer to string to be displayed */
/* bp: pointer to the buffer to be dumped */
/* cnt: number of bytes in buffer */
/* Returns: nothing */
/* Called by: dda_data() */
/* dda_supr() */
/* supr_msg() */
/* Calls to: DDALOG() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
prt_bytes(unit, label, bp, cnt)
int unit;
char *label;
u_char *bp;
int cnt;
{
char hexbuf[50]; /* (worst case: 3 * 16 + 1 = 49 bytes) */
char *p;
int i;
static char hex[] = "0123456789abcdef";
DDALOG(LOG_DEBUG) "dda%d: %s\n", unit, label DDAELOG;
while (cnt > 0) {
i = (cnt > 16) ? 16 : cnt;
cnt -= i;
p = hexbuf;
while (--i >= 0) {
*p++ = ' ';
*p++ = hex[*bp >> 4];
*p++ = hex[*bp++ & 0x0f];
}
*p++ = '\0';
DDALOG(LOG_DEBUG) "dda%d: %s\n", unit, hexbuf DDAELOG;
}
}
#endif
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% FMT_X25() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine is used to format an X.25 address for inclusion in */
/* an error message. The previous return value is invalidated each */
/* time the function is called, as it is stored in a static buffer */
/* Note: The X.25 address is apparently sometimes stored in */
/* BCD, and other times (PDN mode) in ASCII. So we mask */
/* off the high order bits to make ourselves immune. */
/* Call: fmt_x25(bp, cnt) */
/* Argument: bp: pointer to the string */
/* cnt: number of bytes (usually from address[0]) */
/* Returns: pointer to an internal buffer containing the string; */
/* string is 1 to 15 digits, null-terminated. */
/* Called by: make_x25_call() */
/* supr_msg() */
/* convert_x25_addr() */
/* Calls to: none */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE char *
fmt_x25(bp, cnt)
register u_char *bp;
register int cnt;
{
char *p;
static char x25buf[20]; /* worst case is 15 digits plus trailing null */
/* (Don't put this on the stack!) */
p = x25buf;
if (cnt >= sizeof(x25buf))
cnt = sizeof(x25buf) - 1; /* (oops!) */
while (cnt--)
*p++ = (*bp++ & 0x0f) + '0';
*p++ = '\0';
return (x25buf);
}
#ifdef DDA_HISTOGRAM
/*----------------------- HISTOGRAM SUPPORT ---------------------------------*/
/* the histogram array */
struct timeval histogram[NDDA][HISTSIZE];
/* these two structures save the time of the last change in the state of the
* lcn table or the board status.
*/
struct timeval last_lcn_time[NDDA] = {0L, 0L};
struct timeval last_brd_time[NDDA] = {0L, 0L};
/* h_lcn_level: the current number of active lcns */
int h_lcn_level[NDDA] = {0};
/*#define DDA_HIST_DEBUG 1 /* set this to debug history features */
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% HIST_INIT() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine initializes the histogram facility when coming up or */
/* after a reset. */
/* Call: hist_init(unit,reset) */
/* Argument: unit - board number to initialize. */
/* reset - set to 1 to force an init. */
/* Returns: nothing. */
/* Called by: ddaioctl() */
/* Calls to: microtime() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
hist_init(unit, reset)
int unit;
int reset;
{
int s;
register int i;
struct dda_cb *dc;
if (last_lcn_time[unit].tv_sec != 0L && !reset)
return; /* histogram for this unit already enabled */
bzero(histogram[unit], sizeof(struct timeval) * HISTSIZE);
h_lcn_level[unit] = 0;
dc = dda_softc[unit].dda_cb;
s = splimp();
for (i = 0; i < NDDACH + 1; i++) {
if (dc++->dc_state == LC_DATA_IDLE)
h_lcn_level[unit]++;
}
splx(s);
microtime(&histogram[unit][H_START]);
#ifdef DDA_HIST_DEBUG
DDALOG(LOG_DEBUG) "hist_init: starting at level %d\n",
h_lcn_level[unit] DDAELOG;
#endif
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% HIST_LCN_STATE() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine changes the histogram depending on how the state of */
/* a channel has changed. */
/* Call: hist_lcn_state(unit, old_state, new_state) */
/* Argument: old_state: the old state of the lcn. */
/* new_state: the state the lcn is changing to. */
/* unit: unit this applies to */
/* Returns: nothing. */
/* Called by: */
/* Calls to: timevalsub(), timevaladd(), microtime() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
hist_lcn_state(unit, old_state, new_state)
int unit;
u_char old_state;
u_char new_state;
{
struct timeval tv, tmpv;
/*
* this structure for determining state transitions is much more general
* than is necessary right now. However it allows easy changes to the
* state transition table for the histogram so I will leave it in until
* it settles down
*/
switch (old_state) {
case LC_DATA_IDLE:
switch (new_state) {
case LC_DATA_IDLE:
break;
default: /* all other states */
microtime(&tv);
tmpv = tv;
timevalsub(&tv, &last_lcn_time[unit]);
#ifdef DDA_HIST_DEBUG
DDALOG(LOG_DEBUG) "hist_lcn_state: adding %ld.%ld to level %d--\n",
tv.tv_sec, tv.tv_usec, h_lcn_level[unit] DDAELOG;
#endif
timevaladd(&histogram[unit][h_lcn_level[unit]], &tv);
last_lcn_time[unit] = tmpv;
if (--h_lcn_level[unit] < 0) /* safety net for driver
* errors */
h_lcn_level[unit] = 0;
break;
}
break;
default:
switch (new_state) {
case LC_DATA_IDLE:
microtime(&tv);
tmpv = tv;
timevalsub(&tv, &last_lcn_time[unit]);
#ifdef DDA_HIST_DEBUG
DDALOG(LOG_DEBUG) "hist_lcn_state: adding %ld.%ld to level %d++\n",
tv.tv_sec, tv.tv_usec, h_lcn_level[unit] DDAELOG;
#endif
timevaladd(&histogram[unit][h_lcn_level[unit]], &tv);
last_lcn_time[unit] = tmpv;
if (++h_lcn_level[unit] > NDDACH) /* safety net for driver
* errors */
h_lcn_level[unit] = NDDACH;
break;
default: /* all other states */
break;
}
break;
}
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% HIST_ALL_LCNS() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine changes the histogram when the state of all the lcns */
/* are changed as a group. */
/* Call: hist_lcn_state(unit, state) */
/* Argument: state: state that all lcn are going to. Currently not*/
/* used. */
/* unit: unit this applies to */
/* Returns: nothing. */
/* Called by: */
/* Calls to: timevalsub(), timevaladd(), microtime() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
hist_all_lcns(unit, state)
int unit, state;
{
struct timeval tmpv, tv;
#ifdef lint
state = state;
#endif
if (last_brd_time[unit].tv_sec == 0L
|| last_lcn_time[unit].tv_sec == 0L)
return; /* see if we have initialized yet */
microtime(&tv);
tmpv = tv;
timevalsub(&tv, &last_lcn_time[unit]);
#ifdef DDA_HIST_DEBUG
DDALOG(LOG_DEBUG) "hist_all_lcns: adding %ld.%ld to level %d\n",
tv.tv_sec, tv.tv_usec, h_lcn_level[unit] DDAELOG;
#endif
timevaladd(&histogram[unit][h_lcn_level[unit]], &tv);
last_lcn_time[unit] = tmpv;
h_lcn_level[unit] = 0;
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% HIST_LINK_STATE() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine changes the histogram depending on how the state of */
/* the link has changed. */
/* Call: hist_link_state(old_state, new_state) */
/* Argument: old_state: the old state of the link. */
/* new_state: the state the link is changing to. */
/* unit: unit this applies to */
/* Returns: nothing. */
/* Called by: */
/* Calls to: timevalsub(), timevaladd(), microtime() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
hist_link_state(unit, old_state, new_state)
int unit;
u_char old_state;
u_char new_state;
{
struct timeval tv, tmpv;
/*
* this structure for determining state transitions is much more general
* than is necessary right now. However it allows easy changes to the
* state transition table for the histogram so I will leave it in until
* it settles down
*/
switch (old_state) {
case S_LINK_UP:
switch (new_state) {
case S_LINK_UP:
break;
default: /* all other states */
#ifdef DDA_HIST_DEBUG
DDALOG(LOG_DEBUG) "hist_link_state: link down\n" DDAELOG;
#endif
microtime(&tv);
tmpv = tv;
timevalsub(&tv, &last_lcn_time[unit]);
timevaladd(&histogram[unit][h_lcn_level[unit]], &tv);
tv = tmpv;
timevalsub(&tv, &last_brd_time[unit]);
timevaladd(&histogram[unit][H_LINK_UP], &tv);
last_brd_time[unit].tv_sec = 0L;
break;
}
break;
default: /* all other states */
switch (new_state) {
case S_LINK_UP:
#ifdef DDA_HIST_DEBUG
DDALOG(LOG_DEBUG) "hist_link_state: link up\n" DDAELOG;
#endif
microtime(&last_brd_time[unit]);
/*
* reset last_lcn_time so 0 entry will not accumulate the time
* that we were down
*/
last_lcn_time[unit] = last_brd_time[unit];
break;
default:
break;
}
break;
}
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% HIST_READ() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine prepares the histogram table for reading by making */
/* all entries current. */
/* Call: hist_read(unit) */
/* Argument: unit : board to use. */
/* Returns: nothing */
/* Called by: ddaioctl() */
/* Calls to: timevalsub(), timevaladd(), microtime() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE void
hist_read(unit)
int unit;
{
struct timeval tmpv, tv;
microtime(&tv);
tmpv = tv;
histogram[unit][H_END] = tmpv;
histogram[unit][H_TMO].tv_sec = tmo_data_idle * DDA_TIMEOUT;
histogram[unit][H_TMO].tv_usec = 0L;
if (last_brd_time[unit].tv_sec) {
timevalsub(&tv, &last_lcn_time[unit]);
#ifdef DDA_HIST_DEBUG
DDALOG(LOG_DEBUG) "hist_read: adding %ld.%ld to level %d\n",
tv.tv_sec, tv.tv_usec, h_lcn_level[unit] DDAELOG;
#endif
timevaladd(&histogram[unit][h_lcn_level[unit]], &tv);
last_lcn_time[unit] = tmpv;
tv = tmpv;
timevalsub(&tv, &last_brd_time[unit]);
timevaladd(&histogram[unit][H_LINK_UP], &tv);
last_brd_time[unit] = tmpv;
}
}
/*@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*%% HIST_COPYOUT() %%*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/* */
/* Purpose: */
/* */
/* This routine prepares the histogram table for reading by making */
/* all entries current. */
/* Call: hist_copyout(unit, to) */
/* Argument: unit : board to use. */
/* to : address in user space to copy to. */
/* Returns: return value from copyout */
/* Called by: ddaioctl() */
/* Calls to: copyout() */
/* */
/*##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
PRIVATE int
hist_copyout(unit, to)
int unit;
caddr_t to;
{
return ((copyout(histogram[unit], to, sizeof(struct timeval) * HISTSIZE)));
}
#endif DDA_HISTOGRAM
#ifdef DDA_PAD_OR_RAW
#if ACC_BSD > 42
# include "uba.h"
# include "bk.h"
# include "conf.h"
# include "proc.h"
# include "tty.h"
# include "map.h"
# include "vm.h"
# include "bkmac.h"
# include "clist.h"
# include "file.h"
# include "uio.h"
#endif
#if ACC_BSD == 42 || ACC_ULTRIX > 00
# include "bk.h"
# include "../h/conf.h"
# include "../h/proc.h"
# include "../h/tty.h"
# include "../h/map.h"
# include "../h/vm.h"
# if ACC_ULTRIX > 12
# include "uba.h"
# endif
# include "../h/bk.h"
# ifdef SIMULATION
# include "Clist.h"
# else
# include "../h/clist.h"
# endif
# include "../h/file.h"
# include "../h/uio.h"
#endif
PRIVATE int
dda_decode_type(ds, p)
struct dda_softc *ds;
u_char *p;
{
register u_char *cp;
int i, usrlen;
#ifdef DDADEBUG
if (DDADBCH(20, ds->dda_if.if_unit)) {
printf(" dda_decode_type(): p[0]= %x ", *p);
}
#endif DDADEBUG
switch (p[0]) {
case LINE_STATUS: /* link status msg */
case RESTART: /* restart received */
case RSTRT_ACK: /* restart ack */
case STATRESP: /* Statistics Response from FEP */
case CLEARVC: /* clear by VCN */
return (0);
case RESET: /* X25 reset */
return (1);
case ANSWER:
case CLEARLC:
case INTERRUPT:
case INTR_ACK:
i = p[1] / 2; /* get lcn */
if (ds->dda_cb[i].dc_flags & (DC_X29 | DC_X29W))
return (1);
else if (ds->dda_cb[i].dc_flags & (DC_RAW))
return (2);
else
return (0);
}
if (p[0] != RING) { /* let standard dda handle it */
return (0);
}
cp = p + 4; /* skip over code, lcn, vcn and count in
* (ring?) answer message */
/* cp now points to length of called address */
cp += *cp + 1; /* skip over called address and length byte */
/* cp now points to length of calling address */
cp += *cp + 1; /* skip over calling address and length byte */
/* cp now points to length of protocol */
if (*cp == 0)
return (0);
usrlen = *cp++;
if (usrlen) {
#ifdef DDA_RAWOPT
if (pi_circuit_to_handle_protocol(*cp))
return (2);
#endif
#ifdef DDADEBUG
if (DDADBCH(20, ds->dda_if.if_unit)) {
printf(" dda_decode_type(): return value = %x ", *cp);
}
#endif DDADEBUG
switch (*cp) {
case X25_PROTO_IP:
return (0);
case X25_PROTO_X29:
return (1);
default:
return (2);
}
} else
return (0);
}
#endif DDA_PAD_OR_RAW
#ifdef SIMULATION
# ifdef DDA_PADOPT
# include "if_x29.c"
# endif
# ifdef DDA_RAWOPT
# include "if_pi.c"
# endif
#else
# ifdef DDA_PADOPT
# if ACC_VMS > 00
# include "../vaxif/if_vmsx29.c"
# else
# include "../vaxif/if_x29.c"
# endif
# endif
# ifdef DDA_RAWOPT
# include "../vaxif/if_pi.c"
# endif
#endif
#ifdef DDA_MSGQ
u_char ddamsgq[MSGQSIZE];
PRIVATE u_char *mqptr = 0;
#define MSGQEND (ddamsgq+MSGQSIZE)
dda_mqstr(s)
char *s;
{
if (mqptr == 0)
mqptr = ddamsgq;
while (*s) {
*mqptr++ = *s++;
if (mqptr >= MSGQEND)
mqptr = ddamsgq;
}
*mqptr = '\0';
}
dda_mqnum(num, type)
int num, type;
{
if (mqptr == 0)
mqptr = ddamsgq;
if ((mqptr + sizeof(int) + 2) >= MSGQEND)
mqptr = ddamsgq;
*mqptr++ = type;
*((int *) mqptr) = num;
mqptr += sizeof(int);
*mqptr = '\0';
}
#endif DDA_MSGQ
/* link in support for steve's test-jig */
#ifdef SIMULATION
#include "if_dda_sim.c"
#endif
/*
Revision History:
18-Dec-87: V3.0 - <NAME>
Added the -t flag to acpconfig and the 't' case in ddaioctl to allow
setting of the idle circuit timeout.
The constant TMO_DATA_IDLE was changed to a variable called
tmo_data_idle.
11-Mar-88: V3.0 - <NAME>
Modified the history routine to return the current value of the
timeout. Also fixed bug so that level 0 records amount of time 0
circuits were in use only when link is up.
11-Mar-88: V3.0 - <NAME>
Changed handling of supervisor channel overflows to double the max q
length each time it overflows. This Will prevent a flood of console
messages while still notifying the user that there has been an
overflow.
21-Mar-88: V3.0 - <NAME>
Fixed bug in writing the facilities field for packet and window size
negotiation. This was in the routine make X.25 call. Previously
constants were used to index into the facilities buffer now offsets
from the current facilities length are used.
12-Apr-88: V3.0 - Brad Engstrom
Added ability to handle class b and class c addressing. The changes
affect locate_x25_lcn, convert_x25_addr, and convert_ip_addr. The
modifications came from fixes sent to Wollongong by <NAME>.
12-Apr-88: V3.0 - <NAME>
Made modifications so the driver will work under Ultrix or BSD. In
cases where there are differences between 4.3 and 4.2 bsd (shown by
#ifdef BSD4_3) Ultrix 1.2 is exactly like a 4.2 system. Ultrix 2.0 is
like 4.3 in most cases. New macros were added to distinquish between
systems. These are BSD4_2 and BSD43_OR_ULTRIX20.
13-Apr-88: V3.0 - <NAME>
ddareset() was called from ddaintb without arguments. This could
cause ddareset to return without doing anything. Proper arguments were
inserted. In ddaioctl the priority level s may be used without being
set. This was fixed.
18-Apr-88: V3.0 - <NAME>
Added the use of a key field in the dda_cb structure. Previously the
dc_inaddr field was used both for printing the ip address (-l command)
and for searching for circuits that were open to a destination. Using
this for a cicuit matching address means that the network and local
host fields needed to be masked off, thus making this field less
usefull for printing. Now two fields are used dc_inaddr is used for
printing. dc_key is used for circuit matching. In PDN mode the
full ip address is used as the key. In DDN mode just the imp number
and host(port) number are used.
18-Apr-88: V3.0 - <NAME>
Made histogram facilities a compile time option. The histogram is
enabled if DDA_HISTOGRAM is defined. The facilities are always
disabled when using 4.2 or ULTRIX 1.2 as the kernel does not have the
proper support routines available.
22-Apr-88: V3.0 - <NAME>
Added new option to -v command to set the dda_db_unit variable.
22-Apr-88: V3.0 - <NAME>
Added the DMESG macro and the msgbits array to allow selective
disabling of driver error messages. To enable or disable an error
message the -c command of acpconfig is used. The msgbits array holds
info about whether each message is enabled or disabled. Setting a bit
to 1 disables a message. Clearing a bit to 0 enables a message.
All messages start as enabled.
22-Apr-88: V3.0 - <NAME>
Added check for DDAMAINT_BRD in probe routine. If DDAMAINT_BRD is
defined then assume we are using a maintenence board so don't try to
find the firmware id because it won't be there. Fake info that was
supposed to be contained in the firmware id.
25-Apr-88: V3.0 - <NAME>
Added check in locate_x25_lcn to see if state of lc is LC_CALL_PENDING
or LC_DATA_IDLE in the loop that looks for an already open lc. This
will prevent an address of 0.0.0.0 from matching a circuit that is not
in use. If the address is invalid then the imp will kick it out.
26-Apr-88: V3.0 - <NAME>
Changed the -n command case so that a command of the form "-n 0" will
return the number of channels currently available. This will be used
by the -l command and possible by the -h command to determine the
number of available circuits.
10-May-88: V3.0 - <NAME>
Made all occurences of the length of and X.25 address refer to the
constants MAXADDRLEN and MINADDRLEN defined in if_ddavar.h. These
constants include the 1 byte for encoding the length.
02-Jun-88: V3.0 - <NAME>
Change the check for the firmware revision level to 2.2 for the -e
command. This command will crash [56]250s that don't have at least
v2.2 firmware.
12-Jul-88: V3.0 - <NAME>
Deleted case for class_b_c addressing.
20-Jul-88: V3.0 - <NAME>
Fixed bug in parsing facilities that would cause the kernel to hang.
The bug was not incrmenting pointers when an urecognized 2 octet
facility was seen. Fixes were applied to send_supr() and
decode_answer()
30-Aug-88: V4.0 - <NAME>rom
Modified driver to support X.29 and a programmers interface. Includes
files if_x29.c, if_pi.c, and if_pivar.h
30-Aug-88: V4.0 - <NAME>
Added support for debug logging under the control of the DDA_MSGQ
define. Information is extracted using the new -p command of
acpconfig.
30-Aug-88: V4.0 - <NAME>
Modified start_chan to check the ready bit before touching the
comregs. Also modified dda_rrq and dda_wrq to raise ipl before
touching the sioq. These changes fixed a bug where the FE was losing
I/O requests.
20-Oct-88: V4.0 - <NAME>
Added SIMULATION #ifdef for simulation support
08-Jan-89: V4.1 - <NAME>
MERGE 4.0 and 3.1
10-Oct-88: V3.1 - <NAME>
Replace prt_x25 with fmt_x25, which returns a pointer to a formatted
message instead of printing its data; this allows error messages to be
output with a single call to DDALOG (or syslog). Move prt_addr
inline, for same reason. Add IP address to some error messages;
trim excess text from some error messages. Allocate channels
for incoming calls from lowest channel up; we do linear searches of
the lcn table, so it's to our advantage to use the lowest numbers for
all active circuits. (The lcn is not related to the virtual circuit
number, so there is no need to allocate incoming channels from the
top down.) Modify prt_bytes to take unit number and descriptive
string to be printed along with the buffer and byte count; it now
formats up to 16 bytes at a time and prints a full line with each call
to DDALOG rather than calling DDALOG for each byte.
17-Oct-88: V3.1 - <NAME>
Add definitions for DDALOG and DDAELOG, which translate into a call to
DDALOG() or log().
26-Oct-88: V3.1 - <NAME>
Change index for 'v' ioctl to preserve compatibility with previous
versions. Restrict maximum window size to 127, not 128.
7-Nov-88: V3.2 - <NAME>
Fix check for no free circuits when processing RING
17-Feb-89: V4.3.0 - <NAME>
Added TGV changes for Multinet.
8-Mar-89: V4.3.1 - <NAME>
Installed 'Q' ioctl to support obtaining an internal trace log used
for debugging only -- not documented for general user. acpconfig
dda0 -q 2 dumps 256 bytes from the dda_debug_silo[] array
13-Mar-89: V4.3.2 - <NAME>
Updated Multinet support.
17-Apr-89: V4.3.3 - <NAME>
Split bus and simulation related code out to included files for first
shot at 7000 and tahoe design. Don't reset timeout counter in
dda_data() unless link really is in idle state.
28-Apr-89: V4.3.4 - <NAME>
Modified changes of 17-Apr-89, added minimal tahoe support until
driver modified to use 4.3uba transfers.
Fixed timeout fix of 17-Apr-89 to do what was intended.
Fixed code dealing with maintenance board, reformatted with indent
to repair readablility.
09-May-89: V4.3.5 - <NAME>
Minimal tahoe support completed, based on BSD4_3TAHOE define which
must be uncommented manually. Finalizing for ECO.
24-May-89: V4.3.6 - <NAME>
Ultrix 3.0 support added. Revised 4.3 tahoe support for automatic
invocation.
*** NOTE: one of the three OS defines (ACC_BSD, ACC_ULTRIX, ACC_VMS)
in if_dda.c must be set to a non-zero value for the driver to
compile.
Attempting multiple-os support based upon weird variables from include
files is not acceptable with the latest proliferation of OS versions.
20-Jun-89: V4.3.7 - <NAME>
Removed crufty old debug stuff and integrated it with the log-message
code. Now X29 and PI modules can be debuged properly (no #if 0's!).
22-Jun-89: - <NAME>
Diddled ring-decode logic to check for proper ring packet decoding
before attempting to find a free lcn. This will make it easier to deal
with the race condition with find_free_lcn().
Modified ACC os specific equates to be set as options in the config
file. This way, most users won't ever edit if_dda.c.
18-Jul-89: - <NAME>
Driver will no longer return errors if duplicate address-translation
entries are made. Errors will only happen if a redefiniton is
attempted.
Moved dc_key.ttyline out of union, creating dc_line.
26-Jul-89: - <NAME> f/<NAME>
Added support for called user-data field (two new params to
make_x25_call) to support extended pad mode in the X.29 module.
01-Aug-89: - <NAME>
Made ddamsgs uninitialized -- it gets inited in ddaattach now.
03-Aug-89: - <NAME>
Changed hist_copyout definition to PRIVATE.
15-Aug-89: - <NAME>
Made dda_softc and dda_iobuf non-private.
18-Aug-89: - <NAME>
Somehow, ddareset was removed from the 'z' ioctl.
28-Aug-89: - <NAME>
Changed make_x25_call so that it checks length of data to be stuffed
into the mbuf before actually copying data in. Removed udlen and
ud parameters to the routine, as the public areas will be plugged
with data before being called. (May need to splimp()).
22-Sep-89: - <NAME>
The order of the 'v' ioctl parameters was screwed up. This caused
window and packet size setting to fail.
23-Oct-89: - <NAME>
Added further support for Steve's yetchy simulation. Updated main
module to work with BI version of dda board.
29-Oct-89: - <NAME>
Acpconfig inconsistancy (again): removed the 'p', and 'Q' ioctls.
Since all of these are queries, I placed them under the 'q' ioctl
with a new switch. Some day we should just scrap the whole mess
and design a proper ioctl interface.
11-Nov-89: - <NAME>
Moved rrq/wrq routines into bus modules because we can do several
queue reads and writes when working with the BI.
*/
#endif NDDA > 0
|
PrzemyslawMalinowski-epm/sample-repo-git-flow
|
test/transform/resource/after-ecj/EqualsAndHashCodeOfAndExclude.java
|
<filename>test/transform/resource/after-ecj/EqualsAndHashCodeOfAndExclude.java
final @lombok.EqualsAndHashCode(of = {"x"}) class EqualsAndHashCodeOf {
int x;
int y;
EqualsAndHashCodeOf() {
super();
}
public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) {
if ((o == this))
return true;
if ((! (o instanceof EqualsAndHashCodeOf)))
return false;
final EqualsAndHashCodeOf other = (EqualsAndHashCodeOf) o;
if ((this.x != other.x))
return false;
return true;
}
public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() {
final int PRIME = 59;
int result = 1;
result = ((result * PRIME) + this.x);
return result;
}
}
final @lombok.EqualsAndHashCode(exclude = {"y"}) class EqualsAndHashCodeExclude {
int x;
int y;
EqualsAndHashCodeExclude() {
super();
}
public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) {
if ((o == this))
return true;
if ((! (o instanceof EqualsAndHashCodeExclude)))
return false;
final EqualsAndHashCodeExclude other = (EqualsAndHashCodeExclude) o;
if ((this.x != other.x))
return false;
return true;
}
public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() {
final int PRIME = 59;
int result = 1;
result = ((result * PRIME) + this.x);
return result;
}
}
|
mitchellolsthoorn/ASE-Technical-2021-api-linkage-replication
|
EvoMaster/client-java/instrumentation/src/test/java/org/evomaster/client/java/instrumentation/example/methodreplacement/strings/BranchCovSCTest.java
|
package org.evomaster.client.java.instrumentation.example.methodreplacement.strings;
import com.foo.somedifferentpackage.examples.methodreplacement.strings.StringCallsImp;
import org.evomaster.client.java.instrumentation.InstrumentingClassLoader;
import org.evomaster.client.java.instrumentation.staticstate.ExecutionTracer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.function.Consumer;
import static org.evomaster.client.java.instrumentation.example.ExampleUtils.checkIncreasingTillCoveredForSingleMethodReplacement;
public class BranchCovSCTest {
private StringCalls sc;
@BeforeAll
@AfterAll
public static void reset() {
ExecutionTracer.reset();
}
@BeforeEach
public void initTest() throws Exception {
InstrumentingClassLoader cl = new InstrumentingClassLoader("com.foo");
sc = (StringCalls)
cl.loadClass(StringCallsImp.class.getName())
.newInstance();
}
private class Pair {
public final String first;
public final String second;
public Pair(String first, String second) {
this.first = first;
this.second = second;
}
@Override
public String toString() {
return "['" + first + '\'' + ", '" + second + "']";
}
}
@Test
public void testEquals() throws Exception {
Consumer<Pair> lambda = p -> sc.callEquals(p.first, p.second);
String target = "target";
checkIncreasingTillCoveredForSingleMethodReplacement(Arrays.asList(
new Pair("", target),
new Pair("a", target),
new Pair("t", target),
new Pair("targ", target),
new Pair("t1234", target),
new Pair("tar3456", target),
new Pair("ta2345", target),
new Pair("ta234t", target)
),
new Pair(target, target), lambda);
}
@Test
public void testEqualsIgnoreCase() throws Exception {
Consumer<Pair> lambda = p -> sc.callEqualsIgnoreCase(p.first, p.second);
String target = "target";
checkIncreasingTillCoveredForSingleMethodReplacement(Arrays.asList(
new Pair("", target),
new Pair("a", target),
new Pair("ta", target),
new Pair("taZ", target),
new Pair("tap", target),
new Pair("taS", target)
),
new Pair(target, target), lambda);
}
@Test
public void testStartsWith() throws Exception {
Consumer<Pair> lambda = p -> sc.callStartsWith(p.first, p.second);
String target = "abc";
checkIncreasingTillCoveredForSingleMethodReplacement(Arrays.asList(
new Pair("", target),
new Pair("1", target),
new Pair("12", target),
new Pair("12345", target),
new Pair("1b345", target),
new Pair("ab345", target)
),
new Pair(target + "12345", target), lambda);
}
private class Triple {
public final String first;
public final String second;
public final int number;
public Triple(String first, String second, int number) {
this.first = first;
this.second = second;
this.number = number;
}
@Override
public String toString() {
return "['" + first + '\'' + ", '" + second + ", " + number + "]";
}
}
@Test
public void testStartsWithOffset() throws Exception {
Consumer<Triple> lambda = t -> sc.callStartsWith(t.first, t.second, t.number);
String target = "abc";
checkIncreasingTillCoveredForSingleMethodReplacement(Arrays.asList(
new Triple("", target, -100),
new Triple("1", target, -100),
new Triple("123abc456", target, -100),
new Triple("123abc456", target, -90),
new Triple("123abc456", target, 50),
new Triple("123abc456", target, 8),
new Triple("123abc456", target, 7),
new Triple("123abc456", target, 0),
new Triple("123abc456", target, 2)
),
new Triple("123" + target + "456", target, 3), lambda);
}
@Test
public void testEndsWith() throws Exception {
Consumer<Pair> lambda = p -> sc.callEndsWith(p.first, p.second);
String target = "123";
checkIncreasingTillCoveredForSingleMethodReplacement(Arrays.asList(
new Pair("", target),
new Pair("a", target),
new Pair("abced", target),
new Pair("abce1", target),
new Pair("abce2", target),
new Pair("abc12", target),
new Pair("abc121", target)
),
new Pair("foobar" + target, target), lambda);
}
@Test
public void testIsEmpty() throws Exception {
Consumer<String> lambda = s -> sc.callIsEmpty(s);
checkIncreasingTillCoveredForSingleMethodReplacement(Arrays.asList("a b", "a ", "a ", "a"), "", lambda);
}
@Test
public void testContentEquals() throws Exception {
Consumer<Pair> lambda = p -> sc.callContentEquals(p.first, p.second);
String target = "foo";
checkIncreasingTillCoveredForSingleMethodReplacement(Arrays.asList(
new Pair("", target),
new Pair("a", target),
new Pair("f", target),
new Pair("fo", target),
new Pair("f12", target)
),
new Pair(target, target), lambda);
}
@Test
public void testContains() throws Exception {
Consumer<Pair> lambda = p -> sc.callContains(p.first, p.second);
String target = "abc";
checkIncreasingTillCoveredForSingleMethodReplacement(Arrays.asList(
new Pair("", target),
new Pair("a", target),
new Pair("z ", target),
new Pair("z zbcd", target),
new Pair("z zbcd bbd", target),
new Pair("z zbcd abbd", target)
),
new Pair(target, target), lambda);
}
}
|
dolphinridercrypto/bxcommon
|
test/unit/models/test_node_model.py
|
<reponame>dolphinridercrypto/bxcommon<gh_stars>10-100
import unittest
from bxcommon import constants
from bxcommon.models.node_model import NodeModel
from bxcommon.models.node_type import NodeType
from bxcommon.utils import model_loader
from bxutils.logging import log_config
class TestNodeModel(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
log_config.create_logger(None)
def test_from_json(self):
node_json = {
"external_ip": "foo",
"external_port": 123,
"network": "bad_net_name",
"node_type": "RELAY"
}
node = model_loader.load_model(NodeModel, node_json)
self.assertEqual(node_json.get("external_ip"), node.external_ip)
self.assertEqual(node_json.get("external_port"), node.external_port)
self.assertEqual(node_json.get("network"), node.network)
self.assertEqual(NodeType.RELAY, node.node_type)
def test_invalid_json(self):
node_json = {
"a": "foo",
"b": "bazz",
"node_type": "garbage"
}
# Should throw error, none of the keys are right, node_type is wrong
with self.assertRaises(TypeError):
model_loader.load_model(NodeModel, node_json)
def test_add_new_gateway_continent(self):
node_json = {
"external_ip": "foo",
"external_port": 123,
"network": constants.DEFAULT_NETWORK_NAME,
"node_type": "RELAY",
"continent": "AT"
}
node = model_loader.load_model(NodeModel, node_json)
self.assertEqual(node.continent, None, "Continent AT should changed to None")
node_json = {
"external_ip": "foo",
"external_port": 123,
"network": constants.DEFAULT_NETWORK_NAME,
"node_type": "RELAY",
"continent": "EU"
}
node = model_loader.load_model(NodeModel, node_json)
self.assertEqual(node.continent, "EU", "Continent EU should remains")
def test_add_new_gateway_country(self):
node_json = {
"external_ip": "foo",
"external_port": 123,
"network": constants.DEFAULT_NETWORK_NAME,
"country": "United States",
"node_type": "RELAY"
}
node = model_loader.load_model(NodeModel, node_json)
self.assertEqual(node.country, "United States", "country United States should remains")
node_json = {
"external_ip": "foo",
"external_port": 123,
"network": constants.DEFAULT_NETWORK_NAME,
"node_type": "RELAY",
"country": "Country name after truncation. Very long country that has more than 30 characters"
}
node = model_loader.load_model(NodeModel, node_json)
self.assertEqual(node.country, "Country name after truncation.", "country name should be truncated")
|
wvffle/Ystring
|
src/Ystring/Encodings/Iso8859_15.cpp
|
<reponame>wvffle/Ystring<gh_stars>0
//****************************************************************************
// Copyright © 2015 <NAME>. All rights reserved.
// Created by <NAME> on 2015-09-19.
//
// This file is distributed under the Simplified BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "Iso8859_15.hpp"
#include "CodePageFactory.hpp"
namespace Ystring { namespace Encodings
{
namespace
{
typedef std::pair<uint8_t, char32_t> P;
const P SpecialChars[] = {
P(0xA4, 0x20AC), P(0xA6, 0x0160), P(0xA8, 0x0161),
P(0xB4, 0x017D), P(0xB8, 0x017E), P(0xBC, 0x0152),
P(0xBD, 0x0153), P(0xBE, 0x0178)
};
CodePageFactory factory(std::begin(SpecialChars),
std::end(SpecialChars),
Encoding::ISO_8859_15);
}
CodePage makeIso8859_15()
{
return factory.makeCodePage();
}
}}
|
mcvine/mcvine
|
packages/mccomponents/tests/mccomponentsbpmodule/phonon/NdArray_TestCase.py
|
<reponame>mcvine/mcvine
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# <NAME>
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
import unittestX as unittest
import journal
debug = journal.debug( "NdArray_TestCase" )
warning = journal.warning( "NdArray_TestCase" )
import mcni
from mccomposite import mccompositebp
from mccomponents import mccomponentsbp
import numpy
try:
from danse.ins import numpyext
except ImportError:
import numpyext
import warnings
warnings.warn("Using old numpyext. Should use danse.ins.numpyext")
try:
from danse.ins import bpext
except ImportError:
import bpext
import warnings
warnings.warn("Using old bpext. Should use danse.ins.bpext")
class TestCase(unittest.TestCase):
def test(self):
a = numpy.arange(12, dtype = numpy.double)
a.shape = 3,4
ptr = numpyext.getdataptr( a )
wp = bpext.wrap_native_ptr( ptr )
shape = mccomponentsbp.vector_uint( 0 )
for i in a.shape: shape.append( i )
a1 = mccomponentsbp.new_NdArray_dblarr_2( wp, shape )
a1.origin = a
indexes = mccomponentsbp.vector_uint( 0 )
indexes.append( 2 ); indexes.append( 1 )
self.assertEqual( a1[ indexes ], 9 )
return
pass # end of TestCase
def pysuite():
suite1 = unittest.makeSuite(TestCase)
return unittest.TestSuite( (suite1,) )
def main():
#debug.activate()
pytests = pysuite()
alltests = unittest.TestSuite( (pytests, ) )
res = unittest.TextTestRunner(verbosity=2).run(alltests)
import sys; sys.exit(not res.wasSuccessful())
if __name__ == "__main__":
main()
# version
__id__ = "$Id$"
# End of file
|
sinzlab/nntransfer
|
nntransfer/trainer/utils/loss.py
|
<reponame>sinzlab/nntransfer
import math
import torch
from torch.nn import Module
class CircularDistanceLoss(Module):
def __init__(self, reduction: str = "mean") -> None:
super(CircularDistanceLoss, self).__init__()
self.reduction = reduction
def forward(self, input, target):
distances = 0.5 * (
torch.ones_like(input) - torch.cos(math.pi * (input - target) / 180)
)
if self.reduction == "mean":
return distances.mean()
else:
return distances.sum()
|
ivayloivanof/CarWashSoftware
|
src/main/java/bg/car_wash/areas/role/entity/Role.java
|
package bg.car_wash.areas.role.entity;
import org.springframework.security.core.GrantedAuthority;
import javax.persistence.*;
import javax.validation.constraints.Size;
@Entity
@Table(name = "roles")
public class Role implements GrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Size(min = 5, max = 25)
@Column(name = "authority", nullable = false)
private String authority;
public Role() {
}
@Override
public String getAuthority() {
return this.authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public long getId() {
return id;
}
private void setId(long id) {
this.id = id;
}
}
|
jpetto/olympia
|
src/olympia/amo/signals.py
|
<reponame>jpetto/olympia
import contextlib
from django.db import models
def flush_front_end_cache(sender, instance, **kwargs):
from . import tasks
furls = getattr(instance, 'flush_urls', None)
urls = furls() if hasattr(furls, '__call__') else furls
if urls:
tasks.flush_front_end_cache_urls.apply_async(args=[urls])
def _connect():
models.signals.post_save.connect(flush_front_end_cache)
models.signals.post_delete.connect(flush_front_end_cache)
def _disconnect():
models.signals.post_save.disconnect(flush_front_end_cache)
models.signals.post_delete.disconnect(flush_front_end_cache)
@contextlib.contextmanager
def hera_disabled():
_disconnect()
try:
yield
finally:
_connect()
|
itsthejoker/filamentcolors.xyz
|
filamentcolors/migrations/0015_auto_20200327_0106.py
|
<reponame>itsthejoker/filamentcolors.xyz
# Generated by Django 3.0.4 on 2020-03-27 01:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("filamentcolors", "0014_auto_20191219_0633"),
]
operations = [
migrations.AddField(
model_name="swatch",
name="rebuild_long_way",
field=models.BooleanField(
default=False,
verbose_name="Regenerate the color information using the long way for increased accuracy.",
),
),
migrations.AlterField(
model_name="swatch",
name="regenerate_info",
field=models.BooleanField(
default=False,
verbose_name="Rebuild all the information related to this swatch.",
),
),
]
|
universekavish/Learning-Java
|
src/Polymorphism.java
|
// used classses are named like VehiclePm
public class Polymorphism {
public static void main(String[] args) {
CarPm car = new CarPm();
BicyclePm bicycle = new BicyclePm();
BoatPm boat = new BoatPm();
VehiclePm[] racers = {car,bicycle,boat};// using polymorphism to create an array of diffeerent objects of classes.
for(VehiclePm x : racers) {
x.go();
}
}
}
|
MaximilianLincks/LectureFeed
|
src/main/java/com/lecturefeed/repository/service/SessionDBService.java
|
<reponame>MaximilianLincks/LectureFeed
package com.lecturefeed.repository.service;
import com.lecturefeed.entity.model.Session;
import com.lecturefeed.repository.SessionRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SessionDBService extends AbstractService<Session, SessionRepository> {
public SessionDBService(SessionRepository sessionRepository) {
super(sessionRepository);
}
public List<Session> findByClosed(long closed){
return repo.findByClosed(closed);
}
public List<Session> findAllOpen(){
return repo.findByClosed(0);
}
public List<Session> findAllClosed(){
return repo.findAllClosed();
}
}
|
flashboss/rubia-forums
|
rubia-forums-jsf/src/test/java/it/vige/rubia/selenium/forum/model/Links.java
|
<reponame>flashboss/rubia-forums
package it.vige.rubia.selenium.forum.model;
import org.openqa.selenium.By;
import static org.openqa.selenium.By.*;
public enum Links {
CATEGORY_TEMPLATE_LINK(xpath("//li[@class='first']/ul/li/a")), FORUM_TEMPLATE_LINK(
xpath("//li[@class='first']/ul/li/ul/li/a")), TOPIC_TEMPLATE_LINK(
xpath("//li[@class='first']/ul/li/ul/li/ul/li/a")), POST_TEMPLATE_LINK(
xpath("//li[@class='first']/ul/li/ul/li/ul/li/a"));
private By value;
private Links(By value) {
this.setValue(value);
}
public By getValue() {
return value;
}
public void setValue(By value) {
this.value = value;
}
}
|
jurieo/tgo-cli
|
template/core/_tgo.js
|
<reponame>jurieo/tgo-cli
/*
* @Author: Jurieo
* @Date: 2019-08-23 09:58:22
* @LastEditTime: 2019-08-23 09:59:01
* @Description: _tgo请求封装
*/
const _tgo = {};
const md5 = require("md5");
_tgo.cardId = "template_ssr_frontend_lwox97wk2dqx";
_tgo.appKey = "99999999";
_tgo.SALIT = "COaFpf69BverHMdhVIBIOPMmwwnRwuxM";
_tgo.md5 = md5;
_tgo.newSign = function() {
let sign = "";
sign = _tgo.md5(_tgo.appKey + _tgo.newDate());
sign = _tgo.md5(sign + _tgo.SALIT);
sign = _tgo.md5(sign + _tgo.SALIT + _tgo.cardId);
return sign;
};
_tgo.newDate = function() {
let day = new Date();
day = day.getTime();
day = day.toString();
day = day.substring(0, 10);
return day;
};
export default _tgo;
|
filepicker/filestack-java
|
src/main/java/com/filestack/transforms/tasks/TornEdgesTask.java
|
package com.filestack.transforms.tasks;
import com.filestack.transforms.ImageTransformTask;
public class TornEdgesTask extends ImageTransformTask {
// Constructor left public because this task can be used with default options
public TornEdgesTask() {
super("torn_edges");
}
public static class Builder {
private TornEdgesTask tornEdgesTask;
public Builder() {
this.tornEdgesTask = new TornEdgesTask();
}
public Builder spread(int first, int second) {
tornEdgesTask.addOption("spread", new Integer[] {first, second});
return this;
}
public Builder background(String background) {
tornEdgesTask.addOption("background", background);
return this;
}
public TornEdgesTask build() {
return tornEdgesTask;
}
}
}
|
dHannasch/beluga
|
beluga/ivpsol/tests/test_ivpsol.py
|
<reponame>dHannasch/beluga<filename>beluga/ivpsol/tests/test_ivpsol.py<gh_stars>0
from beluga.ivpsol import Propagator, Trajectory, integrate_quads
import numpy as np
from math import *
tol = 1e-3
def test_propagator_1():
k = [-0.5, -0.2]
def odefn(x, p, const):
return np.array([k[0]*x[0], k[1]*x[1]])
y0 = np.array([10, -50])
q0 = np.array([])
tspan = np.array([0, 1.0])
prop = Propagator()
solout = prop(odefn, None, tspan, y0, q0, [], {})
t1 = solout.t
x1 = solout.y.T
x1_expected = np.array([y*np.exp(k_*t1) for (y, k_) in zip(y0, k)])
assert (x1 - x1_expected < 1e-5).all()
def test_propagator_2():
def odefun(x, p, const):
return -x[1], x[0]
def quadfun(x, p, const):
return x[0]
y0 = np.array([1, 0])
q0 = np.array([0])
tspan = np.array([0, pi / 2])
prop = Propagator()
solout = prop(odefun, quadfun, tspan, y0, q0, [], [])
assert solout.y.T[0, -1] < tol
assert solout.y.T[1, -1] - 1 < tol
assert ((solout.y[:, 1] - solout.q[:, 0]) < tol).all()
def test_Trajectory():
t = np.array([0, 1, 2, 3])
y1 = t ** 2
gam = Trajectory(t, y1)
y, q, u = gam(0.5)
assert y == 0.5
assert len(q) == 0
assert len(u) == 0
y, q, u = gam(0.25)
assert y == 0.25
assert len(q) == 0
assert len(u) == 0
gam.set_interpolate_function('cubic')
y, q, u = gam(0.25)
assert y - 0.0625 < 1e-4
assert len(q) == 0
assert len(u) == 0
t, y, q, u = gam[0]
assert t == 0
assert y == 0
assert len(q) == 0
assert len(u) == 0
def test_integrate_quads():
# Test a 1-dim x and 1-dim q
t = np.linspace(0, 10, 100)
y1 = np.sin(t)
def quadfun(t, y):
return y[0]
gam = Trajectory(t, y1)
assert integrate_quads(quadfun, np.array([0, 1 * np.pi]) + 0, gam) - 2 < 1e-3
assert integrate_quads(quadfun, np.array([0, 2 * np.pi]) + 0, gam) < 1e-3
assert integrate_quads(quadfun, np.array([0, 2 * np.pi]) + 1, gam) < 1e-3
assert integrate_quads(quadfun, np.array([0, 2 * np.pi]) + 2, gam) < 1e-3
assert integrate_quads(quadfun, np.array([0, 2 * np.pi]) + 3, gam) < 1e-3
# Test a 2-dim x and 1-dim q
t = np.linspace(0, 10, 100)
y1 = np.sin(t)
y2 = np.cos(t)
def quadfun(t, y):
return y[0]*y[1]
gam = Trajectory(t, np.vstack((y1, y2)).T)
assert integrate_quads(quadfun, np.array([0, 1 * np.pi]) + 0, gam) - np.pi/2 < 1e-3
assert integrate_quads(quadfun, np.array([0, 2 * np.pi]) + 0, gam) - np.pi < 1e-3
# Test a 1-dim x and 2-dim q
t = np.linspace(0, 10, 100)
y1 = np.sin(t)
def quadfun(t, y):
return y[0], y[0]**2
gam = Trajectory(t, y1)
assert integrate_quads(quadfun, np.array([0, 1 * np.pi]) + 0, gam)[0] - 2 < 1e-3
assert integrate_quads(quadfun, np.array([0, 1 * np.pi]) + 0, gam)[1] - np.pi/2 < 1e-3
# Test a 2-dim x and 2-dim q
t = np.linspace(0, 10, 100)
y1 = np.sin(t)
y2 = np.cos(t)
def quadfun(t, y):
return y[0], y[1]
gam = Trajectory(t, np.vstack((y1, y2)).T)
assert len(integrate_quads(quadfun, np.array([0, 2 * np.pi]) + 2, gam)) == 2
assert integrate_quads(quadfun, np.array([0, 2 * np.pi]) + 2, gam)[0] < 1e-3
assert integrate_quads(quadfun, np.array([0, 2 * np.pi]) + 2, gam)[1] < 1e-3
assert integrate_quads(quadfun, np.array([0, 1 * np.pi]) + 0, gam)[0] - 2 < 1e-3
assert integrate_quads(quadfun, np.array([0, 1 * np.pi]) + 0, gam)[1] < 1e-3
|
kdcsoftware/abu
|
packages/api-admin-access/tests/integration/access.spec.js
|
import { start, makeFakeEvent } from "helper";
import { handler as create } from "../../src/create";
import { handler as read } from "../../src/read";
import { handler as list } from "../../src/list";
import { handler as update } from "../../src/update";
import { handler as remove } from "../../src/delete";
import apiAccesses from "../fixtures/api-access.json";
let ddb;
let tableName;
const accesses = [];
describe("Access", () => {
beforeAll(async () => {
({ DocumentClient: ddb, TableName: tableName } = await start());
});
apiAccesses.forEach((access) => {
it(`should create access ${access.name}`, async () => {
const event = makeFakeEvent({
path: "/",
headers: { "Content-Type": "application/json" },
httpMethod: "POST",
body: JSON.stringify(access),
});
const response = await create(event);
expect(response.statusCode).toEqual(201);
expect(response.isBase64Encoded).toBe(false);
const json = JSON.parse(response.body);
expect(json).toHaveProperty("id");
const params = {
TableName: tableName,
Key: {
pk: `API#${json.id}`,
sk: "META",
},
};
const { Item } = await ddb.get(params).promise();
expect(Item.sk2).toBe(access.name);
expect(Item.read).toEqual(access.read);
expect(Item.write).toEqual(access.write);
expect(Item).toHaveProperty("pk3");
accesses.push({ ...access, id: json.id });
});
});
it("should list access with pagination", async () => {
let event = makeFakeEvent({
path: "/",
headers: { "Content-Type": "application/json" },
queryStringParameters: { limit: 3 },
httpMethod: "GET",
});
let response = await list(event);
expect(response.statusCode).toEqual(200);
expect(response.isBase64Encoded).toBe(false);
let json = JSON.parse(response.body);
expect(json).toHaveProperty("cursor");
expect(json.Items).toHaveLength(3);
// second page
event = makeFakeEvent({
path: "/",
pathParameters: { modelId: "blog" },
queryStringParameters: { limit: 3, cursor: json.cursor },
headers: { "Content-Type": "application/json" },
httpMethod: "GET",
});
response = await list(event);
expect(response.statusCode).toEqual(200);
expect(response.isBase64Encoded).toBe(false);
json = JSON.parse(response.body);
expect(json).toHaveProperty("cursor");
expect(json.Items).toHaveLength(2);
});
it("should list access with default limit of 10", async () => {
const event = makeFakeEvent({
path: "/",
headers: { "Content-Type": "application/json" },
httpMethod: "GET",
});
const response = await list(event);
expect(response.statusCode).toEqual(200);
expect(response.isBase64Encoded).toBe(false);
const json = JSON.parse(response.body);
expect(json).toHaveProperty("cursor");
expect(json.Items).toHaveLength(5);
});
it("should read aaccess", async () => {
const access = accesses[4];
const event = makeFakeEvent({
path: "/",
pathParameters: { id: access.id },
queryStringParameters: { all: "true" },
headers: { "Content-Type": "application/json" },
httpMethod: "GET",
});
const response = await read(event);
expect(response.statusCode).toEqual(200);
expect(response.isBase64Encoded).toBe(false);
const json = JSON.parse(response.body);
expect(json.id).toBe(access.id);
expect(json.name).toBe(access.name);
expect(json.read).toEqual(access.read);
expect(json.write).toEqual(access.write);
expect(json).toHaveProperty("key");
expect(json).toHaveProperty("created");
expect(json).toHaveProperty("modified");
expect(json).not.toHaveProperty("pk");
expect(json).not.toHaveProperty("pk2");
expect(json).not.toHaveProperty("pk3");
expect(json).not.toHaveProperty("sk");
expect(json).not.toHaveProperty("sk2");
expect(json).not.toHaveProperty("entity");
accesses[4].key = json.key;
});
it("should be able to use key", async () => {
const access = accesses[4];
const params = {
TableName: tableName,
IndexName: "GSI2",
KeyConditionExpression: "pk3 = :key",
ExpressionAttributeValues: {
":key": `KEY#${access.key}`,
},
};
const { Items, Count } = await ddb.query(params).promise();
const [data] = Items;
expect(Count).toBe(1);
expect(data.sk2).toBe(access.name);
expect(data.read).toEqual(access.read);
expect(data.write).toEqual(access.write);
});
it("should throw content not found", async () => {
const event = makeFakeEvent({
path: "/",
pathParameters: { id: "fake-id" },
headers: { "Content-Type": "application/json" },
httpMethod: "GET",
});
const response = await read(event);
expect(response.statusCode).toEqual(404);
expect(response.isBase64Encoded).toBe(false);
const json = JSON.parse(response.body);
expect(json.message).toBe("API not found");
});
it("should delete access", async () => {
const access = accesses[1];
const event = makeFakeEvent({
path: "/",
pathParameters: { id: access.id },
headers: { "Content-Type": "application/json" },
httpMethod: "DELETE",
});
const response = await remove(event);
expect(response.statusCode).toEqual(204);
expect(response.isBase64Encoded).toBe(false);
const params = {
TableName: tableName,
Key: {
pk: `API#${access.id}`,
sk: "META",
},
};
const res = await ddb.get(params).promise();
expect(res).not.toHaveProperty("Item");
});
it("should update access", async () => {
const access = accesses[0];
const { id } = access;
const event = makeFakeEvent({
path: "/",
pathParameters: { id },
headers: { "Content-Type": "application/json" },
httpMethod: "PUT",
body: JSON.stringify({ name: "Edited access" }),
});
const response = await update(event);
expect(response.statusCode).toEqual(204);
expect(response.isBase64Encoded).toBe(false);
const params = {
TableName: tableName,
Key: {
pk: `API#${id}`,
sk: "META",
},
};
const res = await ddb.get(params).promise();
expect(res.Item.sk2).toEqual("Edited access");
});
});
|
lifeich1/play-cf
|
src/1070d/_io.cc
|
#include "type.h"
#include <cstdio>
using namespace std;
_2018ICPC_NEERC_D_gardis_in_t in_;
_2018ICPC_NEERC_D_gardis_out_t out_;
void _get_input()
{
int n, k;
scanf("%d%d", &n, &k);
in_.n = n;
in_.k = k;
for (int i = 0; i < n; ++i)
{
scanf("%d", in_.a + i);
}
}
void _print_output()
{
printf("%lld\n", out_.res);
}
int main(int argc, char *argv[])
{
_get_input();
gardis_2018ICPC_NEERC_D(in_, out_);
_print_output();
return 0;
}
|
cuntoushifu/EWN
|
src/main/java/me/aichina/strategy/evaluation/RandomEvaluate.java
|
package me.aichina.strategy.evaluation;
import java.util.Random;
import me.aichina.board.ChessBoard;
import me.aichina.board.PieceType;
/**
* 随机估值,返回随机数
*
* @author 陆梦轩
*
*/
public class RandomEvaluate extends EvaluationFunction {
/**
* 构造函数,创建一个随机估值函数
*/
public RandomEvaluate() {
setLabel("RandomEvaluate");
}
@Override
public double getValue(ChessBoard board, PieceType type) {
// TODO 自动生成的方法存根
return new Random().nextDouble()*2 - 1;
}
}
|
MC-JY/inception
|
inception/inception-api-annotation/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/annotation/paging/TokenWrappingPagingStrategy.java
|
/*
* Licensed to the Technische Universität Darmstadt under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The Technische Universität Darmstadt
* 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.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.tudarmstadt.ukp.clarin.webanno.api.annotation.paging;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.wicket.Component;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.model.AnnotatorState;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.page.AnnotationPageBase;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.util.WebAnnoCasUtil;
public class TokenWrappingPagingStrategy
implements PagingStrategy
{
private static final long serialVersionUID = -3983123604003839467L;
private int maxLineLength;
public TokenWrappingPagingStrategy(int aMaxLineLength)
{
maxLineLength = aMaxLineLength;
}
@Override
public List<Unit> units(CAS aCas, int aFirstIndex, int aLastIndex)
{
Iterator<AnnotationFS> tokenIterator = WebAnnoCasUtil.selectTokens(aCas).iterator();
List<Unit> units = new ArrayList<>();
int currentUnitStart = 0;
int currentUnitEnd = 0;
while (tokenIterator.hasNext()) {
AnnotationFS currentToken = tokenIterator.next();
String gap = aCas.getDocumentText().substring(currentUnitEnd, currentToken.getBegin());
int gapStart = currentUnitEnd;
int lineBreakIndex = gap.indexOf("\n");
while (lineBreakIndex > -1) {
currentUnitEnd = gapStart + lineBreakIndex;
units.add(new Unit(units.size() + 1, currentUnitStart, currentUnitEnd));
currentUnitStart = currentUnitEnd + 1; // +1 because of the line break character
lineBreakIndex = gap.indexOf("\n", lineBreakIndex + 1);
}
boolean unitNonEmpty = (currentUnitEnd - currentUnitStart) > 0;
boolean unitFull = unitNonEmpty
&& ((currentToken.getEnd() - currentUnitStart) > maxLineLength);
// If the unit is full, finish the unit and start a new one
if (unitFull) {
units.add(new Unit(units.size() + 1, currentUnitStart, currentUnitEnd));
currentUnitStart = -1;
}
if (currentUnitStart == -1) {
currentUnitStart = currentToken.getBegin();
}
currentUnitEnd = currentToken.getEnd();
}
if (currentUnitEnd - currentUnitStart > 0) {
units.add(new Unit(units.size() + 1, currentUnitStart, currentUnitEnd));
}
return units;
}
@Override
public Component createPositionLabel(String aId, IModel<AnnotatorState> aModel)
{
Label label = new Label(aId, () -> {
AnnotatorState state = aModel.getObject();
return String.format("%d-%d / %d blocks [doc %d / %d]",
state.getFirstVisibleUnitIndex(), state.getLastVisibleUnitIndex(),
state.getUnitCount(), state.getDocumentIndex() + 1,
state.getNumberOfDocuments());
});
label.setOutputMarkupPlaceholderTag(true);
return label;
}
@Override
public DefaultPagingNavigator createPageNavigator(String aId, AnnotationPageBase aPage)
{
return new DefaultPagingNavigator(aId, aPage);
}
}
|
antonmedv/year
|
packages/2018/08/20/index.js
|
module.exports = new Date(2018, 7, 20)
|
cg31/cule
|
cule/atari/games/timepilot.hpp
|
<gh_stars>100-1000
#pragma once
#include <cule/config.hpp>
#include <cule/atari/controller.hpp>
#include <cule/atari/state.hpp>
namespace cule
{
namespace atari
{
namespace games
{
namespace timepilot
{
template<typename State>
CULE_ANNOTATION
void reset(State& s)
{
s.m_reward = 0;
s.m_score = 0;
s.tiaFlags.clear(FLAG_ALE_TERMINAL);
s.m_lives = 5;
}
template<typename State>
CULE_ANNOTATION
void step(State& s)
{
using cule::atari::games::getDecimalScore;
using cule::atari::ram::read;
// update the reward
int score = getDecimalScore(s, 0x8D, 0x8F);
score *= 100;
int reward = score - s.m_score;
s.m_reward = reward;
s.m_score = score;
int lives_byte = ram::read(s, 0x8B) & 0x7;
int screen_byte = ram::read(s, 0x80) & 0xF;
// update terminal status
s.tiaFlags.template change<FLAG_ALE_TERMINAL>(ram::read(s, 0xA0));
// Only update lives when actually flying; otherwise funny stuff happens
s.m_lives = (screen_byte == 2) ? (lives_byte + 1) : s.m_lives;
}
CULE_ANNOTATION
bool isMinimal(const Action &a)
{
switch (a)
{
case ACTION_NOOP:
case ACTION_FIRE:
case ACTION_UP:
case ACTION_RIGHT:
case ACTION_LEFT:
case ACTION_DOWN:
case ACTION_UPFIRE:
case ACTION_RIGHTFIRE:
case ACTION_LEFTFIRE:
case ACTION_DOWNFIRE:
return true;
default:
return false;
}
}
template<typename State>
CULE_ANNOTATION
int32_t lives(State& s)
{
int lives_byte = cule::atari::ram::read(s.ram, 0x8B) & 0x7;
return lives_byte + 1;
}
template<typename State>
CULE_ANNOTATION
void setTerminal(State& s)
{
// update terminal status
s.tiaFlags.template change<FLAG_ALE_TERMINAL>(cule::atari::ram::read(s.ram, 0xA0));
}
template<typename State>
CULE_ANNOTATION
int32_t score(State& s)
{
return 100 * cule::atari::games::getDecimalScore(s, 0x8D, 0x8F);
}
template<typename State>
CULE_ANNOTATION
int32_t reward(State& s)
{
return score(s) - s.score;
}
} // end namespace timepilot
} // end namespace games
} // end namespace atari
} // end namespace cule
|
pivotal-cf-experimental/gocd
|
tools/jruby/lib/ruby/gems/1.8/specifications/Antwrap-0.7.0-java.gemspec
|
<reponame>pivotal-cf-experimental/gocd
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{Antwrap}
s.version = "0.7.0"
s.platform = %q{java}
s.required_rubygems_version = nil if s.respond_to? :required_rubygems_version=
s.authors = ["<NAME>"]
s.cert_chain = nil
s.date = %q{2008-02-16}
s.description = %q{A Ruby module that wraps the Apache Ant build tool. Antwrap can be used to invoke Ant Tasks from a Ruby or a JRuby script. == FEATURES/PROBLEMS: Antwrap runs on the native Ruby interpreter via the RJB (Ruby Java Bridge gem) and on the JRuby interpreter. Antwrap is compatible with Ant versions 1.5.4, 1.6.5 and 1.7.0. For more information, see the Project Info (http://rubyforge.org/projects/antwrap/) page. == SYNOPSIS: Antwrap is a Ruby library that can be used to invoke Ant tasks. It is being used in the Buildr (http://incubator.apache.org/buildr/) project to execute Ant (http://ant.apache.org/) tasks in a Java project. If you are tired of fighting with Ant or Maven XML files in your Java project, take some time to check out Buildr!}
s.email = %q{<EMAIL>}
s.extra_rdoc_files = ["History.txt", "Manifest.txt", "README.txt"]
s.files = ["History.txt", "LICENSE", "Manifest.txt", "README.txt", "Rakefile", "docs/index.html", "docs/index_files/Brander.css", "docs/index_files/blankdot.gif", "docs/index_files/blankdot.html", "docs/index_files/urchin.js", "lib/ant_project.rb", "lib/ant_task.rb", "lib/antwrap.rb", "lib/antwrap_utilities.rb", "lib/jruby_modules.rb", "lib/rjb_modules.rb"]
s.homepage = %q{http://rubyforge.org/projects/antwrap/}
s.rdoc_options = ["--main", "README.txt"]
s.require_paths = ["lib"]
s.required_ruby_version = Gem::Requirement.new("> 0.0.0")
s.rubyforge_project = %q{antwrap}
s.rubygems_version = %q{1.3.3}
s.summary = %q{A Ruby module that wraps the Apache Ant build tool. Antwrap can be used to invoke Ant Tasks from a Ruby or a JRuby script.}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 1
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<hoe>, [">= 1.3.0"])
else
s.add_dependency(%q<hoe>, [">= 1.3.0"])
end
else
s.add_dependency(%q<hoe>, [">= 1.3.0"])
end
end
|
lioder/LampManager
|
ERPClient/src/main/java/blservice/salesblservice/SalesBLService.java
|
package blservice.salesblservice;
import java.util.ArrayList;
import util.BillState;
import util.Level;
import util.ResultMessage;
import util.UserLimits;
import vo.CustomerVO;
import vo.GoodsItemVO;
import vo.PromotionBargainVO;
import vo.PromotionCustomerVO;
import vo.PromotionTotalVO;
import vo.PurchaseVO;
import vo.SalesVO;
/**
* created by zlk on 2017/10/21
*/
public interface SalesBLService {
/**
* 得到新的进货单编号
* @return
*/
public String getnewPurchaseID();
/**
* 得到新的进货退货单编号
* @return
*/
public String getnewReturnID();
/**
* 得到新的销售进货单编号
* @return
*/
public String getnewSalesID();
/**
* 得到新的销售退货单编号
* @return
*/
public String getnewSalesReturnID();
/**
* 得到合适的特价包促销策略
* @return
*/
public ArrayList <PromotionBargainVO> showBargains();
/**
* 得到合适的会员促销策略
*
* @return 会员促销策略
* @author zlk
*/
public ArrayList <PromotionCustomerVO> getFitPromotionCustomer(Level level);
/**
* 得到合适的总价促销策略
*
* @return 总价促销策略
* @author zlk
*/
public ArrayList <PromotionTotalVO> getFitPromotionTotal(double total);
/**
* 创建一个进货单
*
* @param vo
* @return 得到创建后的进货单
* @author zlk
*/
public ResultMessage addPurchase(PurchaseVO vo);
/**
* 删除进货单据
* @param vo
* @return
*/
public ResultMessage deletePurchase(PurchaseVO vo);
/**
* 更改进货单据
* @param vo
* @return
*/
public ResultMessage updatePurchase(PurchaseVO vo);
/**
* 添加商品清单信息
*
* @param item
* @author zlk
*/
public ResultMessage addGoodsItem(GoodsItemVO item);
/**
* 创建一个销售单
*
* @param vo
* @return 得到创建后的销售单
* @author zlk
*/
public ResultMessage addSales(SalesVO vo);
/**
* 删除销售单据
* @param vo
* @return
*/
public ResultMessage deleteSales(SalesVO vo);
/**
* 更改销售单据
* @param vo
* @return
*/
public ResultMessage updateSales(SalesVO vo);
/**
* 提交进货单
*
* @param pur
* @return 进货单是否提交成功
* @author zlk
*/
public ResultMessage submitPurchase(PurchaseVO pur);
/**
* 提交销售单
*
* @param sal
* @return 销售单是否提交成功
* @author zlk
*/
public ResultMessage submitSales(SalesVO sal);
/**
* 保存进货单到草稿中
*
* @param bill
* @return 进货单据是否成功保存到草稿中
* @author zlk
*/
public ResultMessage saveSales(SalesVO bill);
/**
* 保存销售单到草稿中
*
* @param bill
* @return 销售单据是否成功保存到草稿中
* @author zlk
*/
public ResultMessage savePurchase(PurchaseVO bill);
/**
* 获得当前用户ID
* @return 当前用户ID
*/
public String getUserName();
/**
* 获得所有供应商列表
* @return 供应商VO的列表
*/
public ArrayList<CustomerVO> getAllSupplier();
/**
* 获得所有仓库列表
* @return 仓库VO的列表
*/
public ArrayList<String> getAllInventory();
/**
* 获得所有客户列表
* @return 客户VO的列表
*/
public ArrayList<CustomerVO> getAllCustomer();
/**
* 通过状态得到进货单据
* @param state
* @return
*/
public ArrayList<PurchaseVO> getPurchaseOrderByState(BillState state);
/**
* 通过状态得到进货退货单
* @param state
* @return
*/
public ArrayList<PurchaseVO> getReturnOrderByState(BillState state);
/**
* 通过状态得到销售出货单
* @param state
* @return
*/
public ArrayList<SalesVO> getSalesOrderByState(BillState state);
/**
* 通过单据得到销售退货单
* @param state
* @return
*/
public ArrayList<SalesVO> getSalesreturnOrderByState(BillState state);
/**
* 通过名字查找会员促销策略
* @param name
* @return
*/
public PromotionCustomerVO findPromotionCustomerByName(String name);
/**
* 通过名字查找特价包
* @param name
* @return
*/
public PromotionBargainVO findPromotionBargainByName(String name);
/**
* 通过名字查找总价促销策略
* @param name
* @return
*/
public PromotionTotalVO findPromotionTotalByName(String name);
/**
* 显示当前用户的用户权限
* @return
*/
public UserLimits getCurrentUserLimits();
}
|
mzmero/SnakeDesktop
|
src/main/java/com/neolumia/snake/model/QuestionLevel.java
|
package com.neolumia.snake.model;
/**
* This ENUM class represents the level of the game
*/
public enum QuestionLevel {
ONE("1"), TWO("2"), THREE("3");
private String level;
public String getLevel() {
return this.level;
}
QuestionLevel(String level) {
this.level = level;
}
}
|
wilebeast/FireFox-OS
|
B2G/hardware/ti/omap4xxx/libtiutils/Semaphore.cpp
|
/*
* Copyright (C) Texas Instruments - http://www.ti.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Semaphore.h"
#include "ErrorUtils.h"
#include <utils/Log.h>
#include <time.h>
namespace android {
/**
@brief Constructor for the semaphore class
@param none
@return none
*/
Semaphore::Semaphore()
{
///Initialize the semaphore to NULL
mSemaphore = NULL;
}
/**
@brief Destructor of the semaphore class
@param none
@return none
*/
Semaphore::~Semaphore()
{
Release();
}
/**
@brief: Releases semaphore
@param count >=0
@return NO_ERROR On Success
@return One of the android error codes based on semaphore de-initialization
*/
status_t Semaphore::Release()
{
int status = 0;
///Destroy only if the semaphore has been created
if(mSemaphore)
{
status = sem_destroy(mSemaphore);
free(mSemaphore);
mSemaphore = NULL;
}
///Initialize the semaphore and return the status
return ErrorUtils::posixToAndroidError(status);
}
/**
@brief Create the semaphore with initial count value
@param count >=0
@return NO_ERROR On Success
@return NO_MEMORY If unable to allocate memory for the semaphore
@return BAD_VALUE If an invalid count value is passed (<0)
@return One of the android error codes based on semaphore initialization
*/
status_t Semaphore::Create(int count)
{
status_t ret = NO_ERROR;
///count cannot be less than zero
if(count<0)
{
return BAD_VALUE;
}
ret = Release();
if ( NO_ERROR != ret )
{
return ret;
}
///allocate memory for the semaphore
mSemaphore = (sem_t*)malloc(sizeof(sem_t)) ;
///if memory is unavailable, return error
if(!mSemaphore)
{
return NO_MEMORY;
}
///Initialize the semaphore and return the status
return ErrorUtils::posixToAndroidError(sem_init(mSemaphore, 0x00, count));
}
/**
@brief Wait operation
@param none
@return BAD_VALUE if the semaphore is not initialized
@return NO_ERROR On success
@return One of the android error codes based on semaphore wait operation
*/
status_t Semaphore::Wait()
{
///semaphore should have been created first
if(!mSemaphore)
{
return BAD_VALUE;
}
///Wait and return the status after signalling
return ErrorUtils::posixToAndroidError(sem_wait(mSemaphore));
}
/**
@brief Signal operation
@param none
@return BAD_VALUE if the semaphore is not initialized
@return NO_ERROR On success
@return One of the android error codes based on semaphore signal operation
*/
status_t Semaphore::Signal()
{
///semaphore should have been created first
if(!mSemaphore)
{
return BAD_VALUE;
}
///Post to the semaphore
return ErrorUtils::posixToAndroidError(sem_post(mSemaphore));
}
/**
@brief Current semaphore count
@param none
@return Current count value of the semaphore
*/
int Semaphore::Count()
{
int val;
///semaphore should have been created first
if(!mSemaphore)
{
return BAD_VALUE;
}
///get the value of the semaphore
sem_getvalue(mSemaphore, &val);
return val;
}
/**
@brief Wait operation with a timeout
@param timeoutMicroSecs The timeout period in micro seconds
@return BAD_VALUE if the semaphore is not initialized
@return NO_ERROR On success
@return One of the android error codes based on semaphore wait operation
*/
status_t Semaphore::WaitTimeout(int timeoutMicroSecs)
{
status_t ret = NO_ERROR;
struct timespec timeSpec;
struct timeval currentTime;
///semaphore should have been created first
if( NULL == mSemaphore)
{
ret = BAD_VALUE;
}
if ( NO_ERROR == ret )
{
///setup the timeout values - timeout is specified in seconds and nanoseconds
gettimeofday(¤tTime, NULL);
timeSpec.tv_sec = currentTime.tv_sec;
timeSpec.tv_nsec = currentTime.tv_usec * 1000;
timeSpec.tv_sec += ( timeoutMicroSecs / 1000000 );
timeSpec.tv_nsec += ( timeoutMicroSecs % 1000000) * 1000;
///Wait for the timeout or signal and return the result based on whichever event occurred first
ret = sem_timedwait(mSemaphore, &timeSpec);
}
if ( NO_ERROR != ret )
{
Signal();
Create(0);
}
return ret;
}
};
|
thinkthroughmath/status_site
|
spec/models/email_subcription_spec.rb
|
<reponame>thinkthroughmath/status_site
require 'spec_helper'
describe EmailSubscription do
describe 'creating a subscription' do
it "makes a valid new unconfirmed subscription" do
subscription = EmailSubscription.new_unconfirmed_subscription('<EMAIL>')
subscription.save.should == true
end
it "won't create a new unconfirmed subscription with an email that has a subscription" do
current_subscription = FactoryGirl.create(:email_subscription)
subscription = EmailSubscription
.new_unconfirmed_subscription(current_subscription.email)
subscription.save.should == false
end
end
describe 'validating a token' do
it 'knows when a token in valid' do
EmailSubscription.any_instance.stub(:token).and_return('<PASSWORD>')
subscription = EmailSubscription.new
subscription.valid_token?('<PASSWORD>').should == true
end
it 'knows when a token is not valid' do
EmailSubscription.any_instance.stub(:token).and_return('<PASSWORD>')
subscription = EmailSubscription.new
subscription.valid_token?('<PASSWORD>').should == false
end
end
describe 'confirming a subscription' do
it 'confirms a subscription for a valid token' do
EmailSubscription.any_instance.stub(:valid_token?).and_return(true)
subscription = FactoryGirl.create(:email_subscription)
subscription.confirm_subscription('tacos')
subscription.reload.confirmed.should == true
end
it "won't confirm a subcription with an invalid token" do
EmailSubscription.any_instance.stub(:valid_token?).and_return(false)
subscription = FactoryGirl.create(:email_subscription)
subscription.confirm_subscription('tamales')
subscription.reload.confirmed.should == false
end
end
end
|
lyy289065406/exp-libs-refactor
|
exp-libs-base/src/test/java/exp/libs/utils/other/ObjUtilsTest.java
|
package exp.libs.utils.other;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class ObjUtilsTest {
@BeforeEach
public void setUp() throws Exception {
}
@AfterEach
public void tearDown() throws Exception {
}
@Test
public void testToObj() {
fail("Not yet implemented");
}
@Test
public void testToStrObjectClassOfQ() {
fail("Not yet implemented");
}
@Test
public void testToStrObject() {
fail("Not yet implemented");
}
@Test
public void testIsSubclass() {
fail("Not yet implemented");
}
@Test
public void testCloneObject() {
fail("Not yet implemented");
}
@Test
public void testInstanceClass() {
fail("Not yet implemented");
}
@Test
public void testGetAllChildClass() {
fail("Not yet implemented");
}
@Test
public void testToBean() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("number", 1234);
map.put("name", "sky");
map.put("id", 22);
Person p = (Person) ObjUtils.toBean(map, Person.class);
System.out.println(p.getName());
System.out.println(p.getNumber());
}
}
|
unsw-cse-soc/Data-curation-API
|
src/main/java/unsw/curation/api/linking/ConceptNet.java
|
<gh_stars>1-10
package unsw.curation.api.linking;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.json.JsonObject;
import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser;
import org.json.JSONObject;
import weka.filters.unsupervised.attribute.ReplaceMissingValues;
public class ConceptNet {
private final String USER_AGENT = "Mozilla/5.0";
private String FindUrl(String terms) throws Exception
{
String str=terms.replaceAll(" ","_");
String url=" http://conceptnet5.media.mit.edu/data/5.4/uri?language=en&text="+str;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
String returnVal="";
while ((inputLine = in.readLine()) != null)
{
if(inputLine.length()>2)
{
returnVal=inputLine.split(":")[1];
}
}
return returnVal;
}
public void ConceptNetLookUp(String terms) throws Exception
{
String getString=FindUrl(terms);
getString=getString.replace("\"", "").trim();
String url="http://conceptnet5.media.mit.edu/data/5.4"+getString;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
String jsonText="";
while ((inputLine = in.readLine()) != null)
{
jsonText+=inputLine;
}
in.close();
JSONObject jsonObject=new JSONObject(jsonText);
int objectCount=jsonObject.getJSONArray("edges").length();
List<String> lstValues=new ArrayList<>();
for(int i=0;i<objectCount;i++)
{
lstValues.add(jsonObject.getJSONArray("edges").getJSONObject(i).get("surfaceText").toString());
}
System.out.println(lstValues.stream().distinct().collect(Collectors.toList()));
}
public void ConceptNetPartOfSearch(String terms, int count) throws Exception
{
String getString=FindUrl(terms);
getString=getString.replace("\"", "").trim();
//String url="http://conceptnet5.media.mit.edu/data/5.4"+getString;
String url="http://conceptnet5.media.mit.edu/data/5.4/search?rel=/r/PartOf&end="+getString+"&limit="+count;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
String jsonText="";
while ((inputLine = in.readLine()) != null)
{
jsonText+=inputLine;
}
in.close();
JSONObject jsonObject=new JSONObject(jsonText);
int objectCount=jsonObject.getJSONArray("edges").length();
List<String> lstValues=new ArrayList<>();
for(int i=0;i<objectCount;i++)
{
lstValues.add(jsonObject.getJSONArray("edges").getJSONObject(i).get("surfaceText").toString());
}
System.out.println(lstValues.stream().distinct().collect(Collectors.toList()));
}
public void ConceptNetAssociation(String terms) throws Exception
{
String getString=FindUrl(terms);
getString=getString.replace("\"", "").trim();
//String url="http://conceptnet5.media.mit.edu/data/5.4"+getString;
String url="http://conceptnet5.media.mit.edu/data/5.4/assoc"+getString;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
String jsonText="";
while ((inputLine = in.readLine()) != null)
{
jsonText+=inputLine;
}
in.close();
JSONObject jsonObject=new JSONObject(jsonText);
int objectCount=jsonObject.getJSONArray("similar").length();
System.out.println(objectCount);
List<String> lstValues=new ArrayList<>();
for(int i=0;i<objectCount;i++)
{
System.out.println(jsonObject.getJSONArray("similar").optString(i));
}
}
public void ConceptNetAssociationSimilarity(String object1, String object2) throws Exception
{
String getString1=FindUrl(object1);
getString1=getString1.replace("\"", "").trim();
String getString2=FindUrl(object2);
getString2=getString2.replace("\"", "").trim();
//String url="http://conceptnet5.media.mit.edu/data/5.4"+getString;
String url="http://conceptnet5.media.mit.edu/data/5.4/assoc"+getString1+"?filter="+getString2+"/.&limit=1";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
String jsonText="";
while ((inputLine = in.readLine()) != null)
{
jsonText+=inputLine;
}
in.close();
JSONObject jsonObject=new JSONObject(jsonText);
int objectCount=jsonObject.getJSONArray("similar").length();
System.out.println(objectCount);
List<String> lstValues=new ArrayList<>();
for(int i=0;i<objectCount;i++)
{
System.out.println(jsonObject.getJSONArray("similar").optString(i));
}
}
public void ConceptNetAssociationWords(String [] wordList) throws Exception
{
String commaWord="";
for(String word: wordList)
{
commaWord+=word+",";
}
commaWord=commaWord.substring(0,commaWord.length()-1);
//String getString2=FindUrl(object2);
//getString2=getString2.replace("\"", "").trim();
//String url="http://conceptnet5.media.mit.edu/data/5.4"+getString;
String url="http://conceptnet5.media.mit.edu/data/5.4/assoc/list/en/"+commaWord;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
String jsonText="";
while ((inputLine = in.readLine()) != null)
{
jsonText+=inputLine;
}
in.close();
JSONObject jsonObject=new JSONObject(jsonText);
int objectCount=jsonObject.getJSONArray("similar").length();
System.out.println(objectCount);
List<String> lstValues=new ArrayList<>();
for(int i=0;i<objectCount;i++)
{
System.out.println(jsonObject.getJSONArray("similar").optString(i));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.