repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
TDYe123/Algorithm | src/LeetCode/L628.cpp | #include<bits/stdc++.h>
using namespace std;
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
return max(nums[0]*nums[1]*nums[nums.size()-1], nums[nums.size()-1]*nums[nums.size()-2]*nums[nums.size()-3]);
}
int main() {
vector<int> vec = {-1,-2,-3,-4};
printf("%d", maximumProduct(vec));
return 0;
}
|
CDann3r/ambari | ambari-server/src/main/java/org/apache/ambari/server/orm/dao/KerberosKeytabDAO.java | <filename>ambari-server/src/main/java/org/apache/ambari/server/orm/dao/KerberosKeytabDAO.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ambari.server.orm.dao;
import java.util.Collections;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.apache.ambari.server.orm.RequiresSession;
import org.apache.ambari.server.orm.entities.KerberosKeytabEntity;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;
@Singleton
public class KerberosKeytabDAO {
@Inject
Provider<EntityManager> entityManagerProvider;
@Inject
KerberosKeytabPrincipalDAO kerberosKeytabPrincipalDAO;
@Transactional
public void create(KerberosKeytabEntity kerberosKeytabEntity) {
entityManagerProvider.get().persist(kerberosKeytabEntity);
}
public void create(String keytabPath) {
create(new KerberosKeytabEntity(keytabPath));
}
@Transactional
public KerberosKeytabEntity merge(KerberosKeytabEntity kerberosKeytabEntity) {
return entityManagerProvider.get().merge(kerberosKeytabEntity);
}
@Transactional
public void remove(KerberosKeytabEntity kerberosKeytabEntity) {
entityManagerProvider.get().remove(merge(kerberosKeytabEntity));
}
public void remove(String keytabPath) {
KerberosKeytabEntity kke = find(keytabPath);
if (kke != null) {
remove(kke);
}
}
@Transactional
public void refresh(KerberosKeytabEntity kerberosKeytabEntity) {
entityManagerProvider.get().refresh(kerberosKeytabEntity);
}
@RequiresSession
public KerberosKeytabEntity find(String keytabPath) {
return entityManagerProvider.get().find(KerberosKeytabEntity.class, keytabPath);
}
@RequiresSession
public List<KerberosKeytabEntity> findByPrincipalAndHost(String principalName, Long hostId) {
if(hostId == null) {
return findByPrincipalAndNullHost(principalName);
}
TypedQuery<KerberosKeytabEntity> query = entityManagerProvider.get().
createNamedQuery("KerberosKeytabEntity.findByPrincipalAndHost", KerberosKeytabEntity.class);
query.setParameter("hostId", hostId);
query.setParameter("principalName", principalName);
List<KerberosKeytabEntity> result = query.getResultList();
if(result == null) {
return Collections.emptyList();
}
return result;
}
@RequiresSession
public List<KerberosKeytabEntity> findByPrincipalAndNullHost(String principalName) {
TypedQuery<KerberosKeytabEntity> query = entityManagerProvider.get().
createNamedQuery("KerberosKeytabEntity.findByPrincipalAndNullHost", KerberosKeytabEntity.class);
query.setParameter("principalName", principalName);
List<KerberosKeytabEntity> result = query.getResultList();
if(result == null) {
return Collections.emptyList();
}
return result;
}
@RequiresSession
public List<KerberosKeytabEntity> findAll() {
TypedQuery<KerberosKeytabEntity> query = entityManagerProvider.get().
createNamedQuery("KerberosKeytabEntity.findAll", KerberosKeytabEntity.class);
List<KerberosKeytabEntity> result = query.getResultList();
if(result == null) {
return Collections.emptyList();
}
return result;
}
@RequiresSession
public boolean exists(String keytabPath) {
return find(keytabPath) != null;
}
@RequiresSession
public boolean exists(KerberosKeytabEntity kerberosKeytabEntity) {
return find(kerberosKeytabEntity.getKeytabPath()) != null;
}
public void remove(List<KerberosKeytabEntity> entities) {
if (entities != null) {
for (KerberosKeytabEntity entity : entities) {
remove(entity);
}
}
}
}
|
elmendavies/ldaptive | core/src/main/java/org/ldaptive/DefaultConnectionFactory.java | <gh_stars>10-100
/* See LICENSE for licensing and NOTICE for copyright. */
package org.ldaptive;
import org.ldaptive.transport.Transport;
import org.ldaptive.transport.TransportFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Creates connections for performing ldap operations.
*
* @author <NAME>
*/
public class DefaultConnectionFactory implements ConnectionFactory
{
/** Logger for this class. */
protected final Logger logger = LoggerFactory.getLogger(getClass());
/** Transport used by this factory. */
private Transport transport;
/** Connection configuration used by this factory. */
private ConnectionConfig config;
/** Default constructor. */
public DefaultConnectionFactory()
{
this(TransportFactory.getTransport(DefaultConnectionFactory.class));
}
/**
* Creates a new default connection factory. Be sure to invoke {@link #close()} if the supplied transport has
* resources to cleanup.
*
* @param t transport
*/
public DefaultConnectionFactory(final Transport t)
{
transport = t;
}
/**
* Creates a new default connection factory.
*
* @param ldapUrl to connect to
*/
public DefaultConnectionFactory(final String ldapUrl)
{
this(new ConnectionConfig(ldapUrl));
}
/**
* Creates a new default connection factory. Be sure to invoke {@link #close()} if the supplied transport has
* resources to cleanup.
*
* @param ldapUrl to connect to
* @param t transport
*/
public DefaultConnectionFactory(final String ldapUrl, final Transport t)
{
this(new ConnectionConfig(ldapUrl), t);
}
/**
* Creates a new default connection factory.
*
* @param cc connection configuration
*/
public DefaultConnectionFactory(final ConnectionConfig cc)
{
this(cc, TransportFactory.getTransport(DefaultConnectionFactory.class));
}
/**
* Creates a new default connection factory. Be sure to invoke {@link #close()} if the supplied transport has
* resources to cleanup.
*
* @param cc connection configuration
* @param t transport
*/
public DefaultConnectionFactory(final ConnectionConfig cc, final Transport t)
{
transport = t;
setConnectionConfig(cc);
}
@Override
public ConnectionConfig getConnectionConfig()
{
return config;
}
/**
* Sets the connection config. Once invoked the supplied connection config is made immutable. See {@link
* ConnectionConfig#makeImmutable()}.
*
* @param cc connection config
*/
public void setConnectionConfig(final ConnectionConfig cc)
{
config = cc;
config.makeImmutable();
}
/**
* Returns the ldap transport.
*
* @return ldap transport
*/
public Transport getTransport()
{
return transport;
}
/**
* Creates a new connection. Connections returned from this method must be opened before they can perform ldap
* operations.
*
* @return connection
*/
@Override
public Connection getConnection()
{
return transport.create(config);
}
@Override
public void close()
{
transport.close();
}
@Override
public String toString()
{
return new StringBuilder("[").append(
getClass().getName()).append("@").append(hashCode()).append("::")
.append("transport=").append(transport).append(", ")
.append("config=").append(config).append("]").toString();
}
/**
* Creates a builder for this class.
*
* @return new builder
*/
public static Builder builder()
{
return new Builder();
}
// CheckStyle:OFF
public static class Builder
{
private final DefaultConnectionFactory object = new DefaultConnectionFactory();
protected Builder() {}
public Builder config(final ConnectionConfig cc)
{
object.setConnectionConfig(cc);
return this;
}
public DefaultConnectionFactory build()
{
return object;
}
}
// CheckStyle:ON
}
|
CiscoDevNet/ydk-cpp | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ptp_pd_cfg.cpp |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XR_ptp_pd_cfg.hpp"
using namespace ydk;
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_ptp_pd_cfg {
LogServoRoot::LogServoRoot()
:
servo_event_enable{YType::boolean, "servo-event-enable"}
{
yang_name = "log-servo-root"; yang_parent_name = "Cisco-IOS-XR-ptp-pd-cfg"; is_top_level_class = true; has_list_ancestor = false;
}
LogServoRoot::~LogServoRoot()
{
}
bool LogServoRoot::has_data() const
{
if (is_presence_container) return true;
return servo_event_enable.is_set;
}
bool LogServoRoot::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(servo_event_enable.yfilter);
}
std::string LogServoRoot::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ptp-pd-cfg:log-servo-root";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > LogServoRoot::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (servo_event_enable.is_set || is_set(servo_event_enable.yfilter)) leaf_name_data.push_back(servo_event_enable.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> LogServoRoot::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> LogServoRoot::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void LogServoRoot::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "servo-event-enable")
{
servo_event_enable = value;
servo_event_enable.value_namespace = name_space;
servo_event_enable.value_namespace_prefix = name_space_prefix;
}
}
void LogServoRoot::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "servo-event-enable")
{
servo_event_enable.yfilter = yfilter;
}
}
std::shared_ptr<ydk::Entity> LogServoRoot::clone_ptr() const
{
return std::make_shared<LogServoRoot>();
}
std::string LogServoRoot::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string LogServoRoot::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function LogServoRoot::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> LogServoRoot::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool LogServoRoot::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "servo-event-enable")
return true;
return false;
}
}
}
|
nchriqui/24hWeather | Doc/html/search/functions_f.js | var searchData=
[
['recipient_0',['recipient',['../class_p_h_p_mailer_1_1_p_h_p_mailer_1_1_s_m_t_p.html#a3fe758d41853a59d4ccfdce815f006a2',1,'PHPMailer::PHPMailer::SMTP']]],
['recordlasttransactionid_1',['recordLastTransactionID',['../class_p_h_p_mailer_1_1_p_h_p_mailer_1_1_s_m_t_p.html#a7ca35ef525499613bea7afe470e570bd',1,'PHPMailer::PHPMailer::SMTP']]],
['reset_2',['reset',['../class_p_h_p_mailer_1_1_p_h_p_mailer_1_1_s_m_t_p.html#ace903ddfc53a6c998f694cf894266fa4',1,'PHPMailer::PHPMailer::SMTP']]],
['rfcdate_3',['rfcDate',['../class_p_h_p_mailer_1_1_p_h_p_mailer_1_1_p_h_p_mailer.html#a1c35f9ec17924309c683f123856866de',1,'PHPMailer::PHPMailer::PHPMailer']]]
];
|
YifanShenSZ/pytorch | torch/csrc/jit/codegen/cuda/ir_utils.h | #pragma once
#include <torch/csrc/jit/codegen/cuda/ir_all_nodes.h>
#include <torch/csrc/jit/codegen/cuda/type.h>
#include <iterator>
#include <unordered_map>
namespace torch {
namespace jit {
namespace fuser {
namespace cuda {
namespace ir_utils {
// Replace values in fusion using ValReplacementMutator
void replaceValue(
Fusion*,
const std::unordered_map<Val*, Val*>& replacement_map);
template <typename FilterType, typename Iterator>
class FilterIterator {
public:
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = FilterType*;
using pointer = value_type*;
using reference = value_type&;
FilterIterator(Iterator begin, Iterator end) : current_(begin), end_(end) {
advance();
}
FilterType* operator*() const {
return (*current_)->template as<FilterType>();
}
FilterType* operator->() const {
return (*this);
}
FilterIterator& operator++() {
++current_;
advance();
return *this;
}
FilterIterator operator++(int) {
const auto before_increment = *this;
++current_;
advance();
return before_increment;
}
bool operator==(const FilterIterator& other) const {
TORCH_INTERNAL_ASSERT(
end_ == other.end_,
"Comparing two FilteredViews that originate from different containers");
return current_ == other.current_;
}
bool operator!=(const FilterIterator& other) const {
return !(*this == other);
}
private:
void advance() {
current_ = std::find_if(current_, end_, [](const auto& val) {
return dynamic_cast<const FilterType*>(val) != nullptr;
});
}
private:
Iterator current_;
Iterator end_;
};
// An iterable view to a given container of Val pointers. Only returns
// Vals of a given Val type.
// NOTE: Add a non-const iterator if needed.
template <typename FilterType, typename InputIt>
class FilteredView {
public:
using value_type = FilterType*;
using const_iterator = FilterIterator<FilterType, InputIt>;
FilteredView(InputIt first, InputIt last) : input_it_(first), last_(last) {}
const_iterator cbegin() const {
return const_iterator(input_it_, last_);
}
const_iterator begin() const {
return cbegin();
}
const_iterator cend() const {
return const_iterator(last_, last_);
}
const_iterator end() const {
return cend();
}
bool empty() const {
return begin() == end();
}
private:
const InputIt input_it_;
const InputIt last_;
};
template <typename FilterType, typename InputIt>
auto filterByType(InputIt first, InputIt last) {
return FilteredView<FilterType, InputIt>(first, last);
}
template <typename FilterType, typename ContainerType>
auto filterByType(const ContainerType&& inputs) = delete;
template <typename FilterType, typename ContainerType>
auto filterByType(const ContainerType& inputs) {
return filterByType<FilterType>(inputs.cbegin(), inputs.cend());
}
//! Returns a list of new-to-old mappings.
//!
//! This funcion canonicalizes the dimensions and validates that multiple old
//! dimension are mapped to the same new dimension.
std::vector<int64_t> normalizeNew2Old(
const std::vector<int64_t>& new2old_in,
size_t ndims);
//! Returns a list of new-to-old mappings.
//!
//! The input map does not need to be complete. Missing axes are
//! assumed not to be affected.
//!
//! This is used to preprocess broadcast and transpose arguments.
//!
//! Example: (N := ndims)
//! {{0, 1}} -> [1, 0, ...., N-1]
//! Transposes the first two axes with no other change.
//!
//! {{0, -1}} -> [N-1, ...., 0]
//! Swaps the first and last axes.
std::vector<int> normalizeOld2New(
const std::unordered_map<int, int>& old2new_in,
size_t ndims);
// Replace all uses of reference with substitute in expr. Return the Expr.
// Warning: Invalidates provided Expr.
// Warning: Removes connection of reference through provided Expr.
// Warning: Creates new Expr connecting substitue.
// Reference is found through direct pointer comparison.
Expr* replaceValInExpr(Expr* expr, Val* reference, Val* substitute);
// Makes rfactor generic with reduction ops and Welford
TORCH_CUDA_CU_API TensorView* rfactorHelper(
TensorView* red_tv,
const std::vector<int>& axes);
// Return immediate producers of val, this function can be used on any Val and
// will return producers through Exprs.
//
// Warning: returned val's are not guaranteed to be between fusion inputs and
// outputs. This function simply uses val->definition() or val->uses() which is
// limited to not go through fusion inputs/outputs, but if on a path that isn't
// strictly between fusion inputs/outputs, it could effectively return dead
// code.
TORCH_CUDA_CU_API std::vector<Val*> producerValsOf(Val* val);
// Return immediate consumers of val, this function can be used on any Val and
// will return consumers through Exprs.
//
// Warning: returned val's are not guaranteed to be between fusion inputs and
// outputs. This function simply uses val->definition() or val->uses() which is
// limited to not go through fusion inputs/outputs, but if on a path that isn't
// strictly between fusion inputs/outputs, it could effectively return dead
// code.
TORCH_CUDA_CU_API std::vector<Val*> consumerValsOf(Val* val);
// Return immediate producers of vals, this function can be used on any vals and
// will return producers through Exprs.
//
// Warning: returned val's are not guaranteed to be between fusion inputs and
// outputs. This function simply uses val->definition() or val->uses() which is
// limited to not go through fusion inputs/outputs, but if on a path that isn't
// strictly between fusion inputs/outputs, it could effectively return dead
// code.
TORCH_CUDA_CU_API std::vector<Val*> producerValsOf(
const std::vector<Val*>& vals);
// Return immediate consumers of vals, this function can be used on any vals and
// will return consumers through Exprs.
//
// Warning: returned val's are not guaranteed to be between fusion inputs and
// outputs. This function simply uses val->definition() or val->uses() which is
// limited to not go through fusion inputs/outputs, but if on a path that isn't
// strictly between fusion inputs/outputs, it could effectively return dead
// code.
TORCH_CUDA_CU_API std::vector<Val*> consumerValsOf(
const std::vector<Val*>& vals);
// Return immediate producers of tv, this function will return all immediate
// producers of tv through Exprs.
//
// Warning: returned tv's are not guaranteed to be between fusion inputs and
// outputs. This function simply uses tv->definition() or tv->uses() which is
// limited to not go through fusion inputs/outputs, but if on a path that isn't
// strictly between fusion inputs/outputs, it could effectively return dead
// code.
TORCH_CUDA_CU_API std::vector<TensorView*> producerTvsOf(TensorView* tv);
// Return immediate consumers of tv, this function will return all immediate
// consumers of tv through Exprs.
//
// Warning: returned tv's are not guaranteed to be between fusion inputs and
// outputs. This function simply uses tv->definition() or tv->uses() which is
// limited to not go through fusion inputs/outputs, but if on a path that isn't
// strictly between fusion inputs/outputs, it could effectively return dead
// code.
TORCH_CUDA_CU_API std::vector<TensorView*> consumerTvsOf(TensorView* tv);
// Return immediate producers of tvs, this function will return all immediate
// producers of tvs through Exprs.
//
// Warning: returned tv's are not guaranteed to be between fusion inputs and
// outputs. This function simply uses tv->definition() or tv->uses() which is
// limited to not go through fusion inputs/outputs, but if on a path that isn't
// strictly between fusion inputs/outputs, it could effectively return dead
// code.
TORCH_CUDA_CU_API std::vector<TensorView*> producerTvsOf(
const std::vector<TensorView*>& tvs);
// Return immediate consumers of tvs, this function will return all immediate
// consumers of tvs through Exprs.
//
// Warning: returned tv's are not guaranteed to be between fusion inputs and
// outputs. This function simply uses tv->definition() or tv->uses() which is
// limited to not go through fusion inputs/outputs, but if on a path that isn't
// strictly between fusion inputs/outputs, it could effectively return dead
// code.
TORCH_CUDA_CU_API std::vector<TensorView*> consumerTvsOf(
const std::vector<TensorView*>& tvs);
// Returns producers of tv that are inputs of fusion
TORCH_CUDA_CU_API std::vector<TensorView*> inputTvsOf(TensorView* tv);
// Returns consumers of tv that are outputs of fusion
TORCH_CUDA_CU_API std::vector<TensorView*> outputTvsOf(TensorView* tv);
// Returns producers of tvs that are inputs of fusion
TORCH_CUDA_CU_API std::vector<TensorView*> inputTvsOf(
std::vector<TensorView*> tvs);
// Returns consumers of tvs that are outputs of fusion
TORCH_CUDA_CU_API std::vector<TensorView*> outputTvsOf(
std::vector<TensorView*> tvs);
// returns all tensor views in fusion that are used between outputs and inputs.
TORCH_CUDA_CU_API std::vector<TensorView*> allTvs(Fusion* fusion);
TORCH_CUDA_CU_API std::vector<Expr*> getReductionOps(
Fusion* fusion,
bool ignore_trivial = true);
// Returns the initialization value of tv or nullptr if not initialized.
TORCH_CUDA_CU_API Val* getReductionInitValOf(TensorView* tv);
template <typename T>
std::string toString(const T& nodes) {
std::stringstream ss;
for (Statement* stmt : nodes) {
if (ss.tellp() != 0) {
ss << ", ";
}
ss << stmt->toString();
}
return ss.str();
}
} // namespace ir_utils
} // namespace cuda
} // namespace fuser
} // namespace jit
} // namespace torch
|
plbogen/MinorThird | src/main/java/edu/cmu/minorthird/classify/transform/AugmentedInstance.java | package edu.cmu.minorthird.classify.transform;
import edu.cmu.minorthird.classify.*;
import edu.cmu.minorthird.util.*;
import edu.cmu.minorthird.util.gui.*;
import java.util.*;
/**
* Add some features to an instance.
*
* @author <NAME>
*/
public class AugmentedInstance implements Instance{
private Instance instance;
private Feature[] newFeatures;
private double[] newValues;
public AugmentedInstance(Instance instance,String[] newFeatureNames,
double[] newVals){
if(instance==null)
throw new IllegalArgumentException("can't use null instance!");
this.instance=instance;
this.newFeatures=new Feature[newFeatureNames.length];
this.newValues=new double[newVals.length];
for(int i=0;i<newFeatureNames.length;i++){
this.newFeatures[i]=new Feature(newFeatureNames[i]);
this.newValues[i]=newVals[i];
}
}
//
// delegate to wrapped instance
//
@Override
final public Object getSource(){
return instance.getSource();
}
@Override
final public String getSubpopulationId(){
return instance.getSubpopulationId();
}
@Override
final public Iterator<Feature> binaryFeatureIterator(){
return instance.binaryFeatureIterator();
}
//
// extend the numeric feature set
//
@Override
final public Iterator<Feature> numericFeatureIterator(){
return new UnionIterator<Feature>(new MyIterator(),instance
.numericFeatureIterator());
}
@Override
final public Iterator<Feature> featureIterator(){
return new UnionIterator<Feature>(new MyIterator(),instance
.featureIterator());
}
@Override
final public int numFeatures(){
return newFeatures.length+instance.numFeatures();
}
@Override
final public double getWeight(Feature f){
for(int i=0;i<newFeatures.length;i++){
if(newFeatures[i].equals(f)){
return newValues[i];
}
}
return instance.getWeight(f);
}
@Override
public String toString(){
return "[AugmentedInstance: "+instance+StringUtil.toString(newFeatures)+
StringUtil.toString(newValues)+"]";
}
@Override
final public Viewer toGUI(){
return new GUI.InstanceViewer(this);
}
public class MyIterator implements Iterator<Feature>{
private int i=0;
@Override
public void remove(){
throw new UnsupportedOperationException("can't remove");
}
@Override
public boolean hasNext(){
return i<newFeatures.length;
}
@Override
public Feature next(){
return newFeatures[i++];
}
}
static public void main(String[] argv){
MutableInstance inst=new MutableInstance();
inst.addBinary(new Feature("william"));
double[] vals=new double[argv.length];
for(int i=0;i<vals.length;i++)
vals[i]=i+1;
AugmentedInstance aug=new AugmentedInstance(inst,argv,vals);
System.out.println(aug.toString());
for(int i=0;i<argv.length;i++){
Feature f=new Feature(argv[i]);
System.out.println("weight of "+f+"="+aug.getWeight(f));
}
for(Iterator<Feature> i=aug.featureIterator();i.hasNext();){
Feature f=i.next();
System.out.println("in aug: weight of "+f+"="+aug.getWeight(f));
}
}
}
|
tranlinh281/museum_FE | src/components/Modal/ModalUpdateVisitor.js | <reponame>tranlinh281/museum_FE<filename>src/components/Modal/ModalUpdateVisitor.js
import React, { useState } from "react";
import "./style.css"
import 'reactjs-popup/dist/index.css';
import GridItem from "components/Grid/GridItem.js";
import GridContainer from "components/Grid/GridContainer.js";
import Button from "components/CustomButtons/Button.js";
import Card from "components/Card/Card.js";
import CardHeader from "components/Card/CardHeader.js";
import CardBody from "components/Card/CardBody.js";
import CardFooter from "components/Card/CardFooter.js";
import TextField from '@material-ui/core/TextField';
import axios from "axios";
import ConfirmDialog from "./ConfirmDialog";
import Swal from "sweetalert2";
const ModalUpdateVisitor = (props) => {
const { close, dataParentToChild } = props;
const [name, setName] = useState(dataParentToChild.name)
const [phone, setPhone] = useState(dataParentToChild.phone);
const visitorId = dataParentToChild.visitorId;
const [confirmDialog, setConfirmDialog] = useState({ isOpen: false, title: '', subTitle: '' });
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
"Authorization": "Bearer " + sessionStorage.getItem('jwtToken')
};
const updateVisitor = {
name: name,
phone: phone,
visitorId: dataParentToChild.visitorId
}
const BASE_URL = "http://localhost:8080";
const onSubmit = (e) => {
e.preventDefault();
if (phone.length != 10) {
Swal.fire({
title: "Thất bại",
text: 'Số điện thoại phải 10 số!',
icon: "warning",
}).then(() => {
return;
})
} else {
axios.post(BASE_URL + "/api/v1/visitors/update", updateVisitor, { headers: headers })
.then(res => {
Swal.fire({
title: "Thành công",
text: 'Cập nhật thông tin khách tham quan thành công!',
icon: "success",
}).then(() => {
close()
// location.reload();
})
})
.catch(e => {
let errMes = '';
if (e.response.status === 400) {
errMes = e.response.data.message
} else if (e.response.status === 404) {
errMes = e.response.data.message
} else {
errMes = 'Không cập nhật được thông tin'
}
Swal.fire({
title: "Thất bại",
text: errMes,
icon: "error",
}).then(() => {
return;
})
})
}
}
return (
<form onSubmit={onSubmit} autoComplete="off">
<div className="modal" >
<a className="close"
onClick={() => {
setConfirmDialog({
isOpen: true,
title: 'Bạn có chắc muốn thoát?',
onConfirm: () => {
close();
}
})
}}>
×
</a>
<div >
<GridContainer>
<GridItem xs={12} sm={12} md={12}>
<Card profile>
<CardHeader color="primary">
<h4 >Chi tiết khách tham quan</h4>
</CardHeader>
<CardBody>
<GridContainer>
<GridItem xs={12} sm={12} md={12} style={{ marginTop: "1vh" }}>
<TextField
label="<NAME>"
value={name}
required
onChange={(e) => { setName(e.target.value) }}
fullWidth={true}
variant="outlined"
/>
</GridItem>
<GridItem xs={12} sm={12} md={12} style={{ marginTop: "1vh" }}>
<TextField
label="<NAME>"
value={phone}
required
type="number"
onInput = {(e) =>{
e.target.value = Math.max(0, parseInt(e.target.value) ).toString().slice(0,10)
}}
onChange={(e) => { setPhone(e.target.value) }}
fullWidth={true}
variant="outlined"
/>
</GridItem>
</GridContainer>
</CardBody>
<CardFooter>
<Button color="primary" type="submit">Cập nhật</Button>
</CardFooter>
</Card>
<ConfirmDialog
confirmDialog={confirmDialog}
setConfirmDialog={setConfirmDialog}
/>
</GridItem>
</GridContainer>
</div>
</div>
</form>
)
}
export default ModalUpdateVisitor; |
danpal/OpenSAML | src/main/java/org/opensaml/saml2/metadata/impl/AffiliationDescriptorMarshaller.java | /*
* Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package org.opensaml.saml2.metadata.impl;
import java.util.Map.Entry;
import javax.xml.namespace.QName;
import org.opensaml.Configuration;
import org.opensaml.common.impl.AbstractSAMLObjectMarshaller;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.common.CacheableSAMLObject;
import org.opensaml.saml2.common.TimeBoundSAMLObject;
import org.opensaml.saml2.metadata.AffiliationDescriptor;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.util.XMLHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
/**
* A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AffiliationDescriptor} objects.
*/
public class AffiliationDescriptorMarshaller extends AbstractSAMLObjectMarshaller {
/** Class logger. */
private final Logger log = LoggerFactory.getLogger(AffiliationDescriptorMarshaller.class);
/**
* Constructor.
*/
public AffiliationDescriptorMarshaller() {
super(SAMLConstants.SAML20MD_NS, AffiliationDescriptor.DEFAULT_ELEMENT_LOCAL_NAME);
}
/**
* Constructor.
*
* @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this
* marshaller operates on
* @param targetLocalName the local name of either the schema type QName or element QName of the elements this
* marshaller operates on
*/
protected AffiliationDescriptorMarshaller(String targetNamespaceURI, String targetLocalName) {
super(targetNamespaceURI, targetLocalName);
}
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException {
AffiliationDescriptor descriptor = (AffiliationDescriptor) samlElement;
// Set affiliationOwnerID
if (descriptor.getOwnerID() != null) {
domElement.setAttributeNS(null, AffiliationDescriptor.OWNER_ID_ATTRIB_NAME, descriptor.getOwnerID());
}
// Set ID
if (descriptor.getID() != null) {
domElement.setAttributeNS(null, AffiliationDescriptor.ID_ATTRIB_NAME, descriptor.getID());
domElement.setIdAttributeNS(null, AffiliationDescriptor.ID_ATTRIB_NAME, true);
}
// Set the validUntil attribute
if (descriptor.getValidUntil() != null) {
log.debug("Writting validUntil attribute to AffiliationDescriptor DOM element");
String validUntilStr = Configuration.getSAMLDateFormatter().print(descriptor.getValidUntil());
domElement.setAttributeNS(null, TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME, validUntilStr);
}
// Set the cacheDuration attribute
if (descriptor.getCacheDuration() != null) {
log.debug("Writting cacheDuration attribute to AffiliationDescriptor DOM element");
String cacheDuration = XMLHelper.longToDuration(descriptor.getCacheDuration());
domElement.setAttributeNS(null, CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME, cacheDuration);
}
Attr attribute;
for (Entry<QName, String> entry : descriptor.getUnknownAttributes().entrySet()) {
attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey());
attribute.setValue(entry.getValue());
domElement.setAttributeNodeNS(attribute);
if (Configuration.isIDAttribute(entry.getKey())
|| descriptor.getUnknownAttributes().isIDAttribute(entry.getKey())) {
attribute.getOwnerElement().setIdAttributeNode(attribute, true);
}
}
}
} |
jitwxs/addax | easydata/src/test/java/io/github/jitwxs/easydata/common/cache/EnumCacheTest.java | <reponame>jitwxs/addax<gh_stars>1-10
package io.github.jitwxs.easydata.common.cache;
import io.github.jitwxs.easydata.common.enums.ClassDiffVerifyStrategyEnum;
import io.github.jitwxs.easydata.core.verify.EasyVerify;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class EnumCacheTest {
enum TestEnum1 {
JAVA,
C
}
@Getter
@AllArgsConstructor
enum TestEnum2 {
JAVA(1),
C(2)
;
private final int code;
}
@Test
public void testEnumByOrdinal() {
final EnumCache.EnumProperty property = EnumCache.tryGet(TestEnum1.class);
assertNotNull(property);
EasyVerify
.with(new HashMap<Integer, TestEnum1>() {{
put(0, TestEnum1.JAVA);
put(1, TestEnum1.C);
}}, property.getIdMap())
.ignoreClassDiff(ClassDiffVerifyStrategyEnum.CONVERT_SAME_CLASS)
.verify();
}
@Test
public void testEnumByCustom() {
final EnumCache.EnumProperty property = EnumCache.tryGet(TestEnum2.class, one -> ((TestEnum2) one).getCode());
assertNotNull(property);
EasyVerify
.with(new HashMap<Integer, TestEnum2>() {{
put(1, TestEnum2.JAVA);
put(2, TestEnum2.C);
}}, property.getIdMap())
.ignoreClassDiff(ClassDiffVerifyStrategyEnum.CONVERT_SAME_CLASS)
.verify();
}
} |
shangfeiSF/grunt-grope | main/src/jshint/fixed/01.Enforcing/22.maxparams.js | <gh_stars>0
/*
* maxparams
* http://jshint.com/docs/options/#maxparams
* This option lets you set the max number of formal parameters allowed per function.
* */
function maxparams(arg1, arg2) {
return arg1 + arg2;
}
maxparams(1, 2); |
shimomura314/AtcoderCodes | ABC023/D.py | <filename>ABC023/D.py
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
def main():
n = int(input())
hs = [tuple(map(int,input().split())) for _ in range(n)]
ok = 10**16
ng = 0
while ok-ng > 1:
mid = (ok+ng)//2
box = []
for i in range(n):
x = (mid-hs[i][0]) // hs[i][1]
box.append(x)
box.sort()
flag = False
for i in range(n):
if box[i] < i:
ng = mid
flag = True
if not flag:
ok = mid
print(ok)
if __name__ == "__main__":
main() |
UCHI-DB/codecdb-queryengine | cpp/src/lqf/ssb/query1_1.cc | //
// Created by Harper on 1/2/21.
//
#include "query1.h"
#include <iostream>
namespace lqf {
using namespace agg;
namespace ssb {
namespace q1_1 {
double discount_from = 1;
double discount_to = 3;
int quantity_upper = 25;
ByteArray year_from("19940101");
ByteArray year_to("19941231");
}
using namespace sboost;
using namespace parallel;
using namespace q1;
using namespace q1_1;
// This impl uses a scan to replace the date table join.
void executeQ1_1Plain() {
auto lineorderTable = ParquetTable::Open(LineOrder::path,
{LineOrder::ORDERDATE, LineOrder::DISCOUNT, LineOrder::QUANTITY,
LineOrder::EXTENDEDPRICE});
ColFilter colFilter(
{/*new SboostPredicate<DoubleType>(LineOrder::DISCOUNT,
bind(DoubleDictBetween::build, discount_from, discount_to)),*/
new SboostPredicate<Int32Type>(LineOrder::QUANTITY,
bind(Int32DictLess::build, quantity_upper)),
new SboostPredicate<ByteArrayType>(LineOrder::ORDERDATE,
bind(ByteArrayDictBetween::build, year_from, year_to))
});
auto filtered = colFilter.filter(*lineorderTable);
cout << filtered->size()<<'\n';
// SimpleAgg agg([]() { return vector<AggField *>({new RevenueField()}); });
// auto agged = agg.agg(*filtered);
//
// Printer printer(PBEGIN PD(0) PEND);
// printer.print(*agged);
}
void executeQ1_1() {
ExecutionGraph graph;
auto lineorder = ParquetTable::Open(LineOrder::path,
{LineOrder::ORDERDATE, LineOrder::DISCOUNT, LineOrder::QUANTITY,
LineOrder::EXTENDEDPRICE});
auto lineorderTable = graph.add(new TableNode(lineorder), {});
auto colFilter = graph.add(new ColFilter(
{new SboostPredicate<DoubleType>(LineOrder::DISCOUNT,
bind(DoubleDictBetween::build, discount_from, discount_to)),
new SboostPredicate<Int32Type>(LineOrder::QUANTITY,
bind(Int32DictLess::build, quantity_upper)),
new SboostPredicate<ByteArrayType>(LineOrder::ORDERDATE,
bind(ByteArrayDictBetween::build, year_from, year_to))
}), {lineorderTable});
auto agg = graph.add(new SimpleAgg([]() { return vector<AggField *>({new RevenueField()}); }), {colFilter});
graph.add(new Printer(PBEGIN PD(0) PEND), {agg});
graph.execute(true);
}
}
} |
mapp-digital/Mapp-Intelligence-Java-Tracking | tracking/src/main/java/com/mapp/intelligence/tracking/util/MappIntelligenceDebugLogger.java | package com.mapp.intelligence.tracking.util;
import com.mapp.intelligence.tracking.MappIntelligenceLogger;
import com.mapp.intelligence.tracking.MappIntelligenceMessages;
/**
* @author Mapp Digital c/o Webtrekk GmbH
* @version 0.0.1
*/
public final class MappIntelligenceDebugLogger implements MappIntelligenceLogger {
/**
* Mapp Intelligence logger.
*/
private MappIntelligenceLogger logger;
/**
* @param l Mapp Intelligence logger.
*/
public MappIntelligenceDebugLogger(MappIntelligenceLogger l) {
this.logger = l;
}
/**
* @param msg Debug message
*/
@Override
public void log(String msg) {
if (this.logger != null) {
this.logger.log(MappIntelligenceMessages.MAPP_INTELLIGENCE + msg);
}
}
/**
* @param format String format
* @param args Arguments
*/
@Override
public void log(String format, Object... args) {
if (this.logger != null) {
this.logger.log(MappIntelligenceMessages.MAPP_INTELLIGENCE + String.format(format, args));
}
}
}
|
BlocksHub/web-frontend | dist/controllers/www/Groups.spec.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Groups_1 = require("./Groups");
const chai_1 = require("chai");
const model = require("../../models");
const groups = new Groups_1.GroupsController();
groups.Users = {};
groups.Forums = {};
groups.Games = {};
groups.Support = {};
groups.Staff = {};
groups.Groups = {};
describe('groups.Index()', () => {
it('Should return WWWTemplate ', () => {
const res = groups.Index();
chai_1.expect(res).to.be.instanceOf(model.WWWTemplate);
});
});
describe('groups.Index()', () => {
it('Should return WWWTemplate ', () => {
const res = groups.Index();
chai_1.expect(res).to.be.instanceOf(model.WWWTemplate);
});
});
describe('groups.groupCreate()', () => {
it('Should return WWWTemplate ', () => {
const res = groups.groupCreate();
chai_1.expect(res).to.be.instanceOf(model.WWWTemplate);
});
});
describe('groups.redirectToGroupPage()', () => {
it('Should redirect to groups page (OK)', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 0;
let callsToRedirect = 0;
const res = {
redirect: (url) => {
chai_1.expect(url).to.equal('/groups/' + groupId + '/' + groupName);
callsToRedirect++;
},
};
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
}
};
await groups.redirectToGroupPage(res, groupId);
chai_1.expect(callsToRedirect).to.equal(1);
});
it('Should redirect to groups page (locked)', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 1;
let callsToRedirect = 0;
const res = {
redirect: (url) => {
chai_1.expect(url).to.equal('/groups/' + groupId + '/Locked-Group');
callsToRedirect++;
},
};
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
}
};
await groups.redirectToGroupPage(res, groupId);
chai_1.expect(callsToRedirect).to.equal(1);
});
});
describe('groups.GroupPage()', () => {
it('Should return WWWtemplate with group info (OK)', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 0;
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
}
};
const data = await groups.GroupPage(groupId, groupName);
chai_1.expect(data).to.be.instanceOf(model.WWWTemplate);
if (!data.page) {
throw new Error('data.page is undefined');
}
});
it('Should return WWWtemplate with minimal group info (Locked)', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 1;
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
}
};
const data = await groups.GroupPage(groupId, groupName);
chai_1.expect(data).to.be.instanceOf(model.WWWTemplate);
if (!data.page) {
throw new Error('data.page is undefined');
}
chai_1.expect(data.page.groupEncodedName).to.equal('Locked-Group');
});
});
describe('groups.groupCatalogItemCreate()', () => {
it('Should return WWWtemplate with group info (OK)', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 0;
const info = {
userId: 1,
};
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
},
getUserRole: async (providedGroup, providedUser) => {
chai_1.expect(providedGroup).to.equal(groupId);
chai_1.expect(providedUser).to.equal(info.userId);
return {
permissions: {
manage: 1,
}
};
},
};
let callsToRedirect = 0;
const res = {
redirect: (url) => {
callsToRedirect++;
},
};
const data = await groups.groupCatalogItemCreate(res, info, groupId, groupName);
chai_1.expect(data).to.be.instanceOf(model.WWWTemplate);
if (!data || !data.page) {
throw new Error('data.page is undefined');
}
chai_1.expect(callsToRedirect).to.equal(0);
});
it('Should redirect due to requester lacking permissions', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 0;
const info = {
userId: 1,
};
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
},
getUserRole: async (providedGroup, providedUser) => {
chai_1.expect(providedGroup).to.equal(groupId);
chai_1.expect(providedUser).to.equal(info.userId);
return {
permissions: {
manage: 0,
}
};
},
};
let callsToRedirect = 0;
const res = {
redirect: (url) => {
callsToRedirect++;
},
};
await groups.groupCatalogItemCreate(res, info, groupId, groupName);
chai_1.expect(callsToRedirect).to.equal(1);
});
it('Should throw 404 due to locked group', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 1;
const info = {
userId: 1,
};
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
},
getUserRole: async (providedGroup, providedUser) => {
chai_1.expect(providedGroup).to.equal(groupId);
chai_1.expect(providedUser).to.equal(info.userId);
return {
permissions: {
manage: 0,
}
};
},
};
let callsToRedirect = 0;
const res = {
redirect: (url) => {
callsToRedirect++;
},
};
try {
await groups.groupCatalogItemCreate(res, info, groupId, groupName);
throw new Error('Request passed for locked group');
}
catch (err) {
if (!(err instanceof groups.NotFound)) {
throw err;
}
chai_1.expect(callsToRedirect).to.equal(0);
chai_1.expect(err.message).to.equal('InvalidGroupId');
}
});
});
describe('groups.groupManage()', () => {
it('Should return WWWtemplate with group info (OK)', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 0;
const info = {
userId: 1,
};
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
},
getUserRole: async (providedGroup, providedUser) => {
chai_1.expect(providedGroup).to.equal(groupId);
chai_1.expect(providedUser).to.equal(info.userId);
return {
permissions: {
manage: 1,
}
};
},
};
let callsToRedirect = 0;
const res = {
redirect: (url) => {
callsToRedirect++;
},
};
const data = await groups.groupManage(info, res, groupId, groupName);
chai_1.expect(data).to.be.instanceOf(model.WWWTemplate);
if (!data || !data.page) {
throw new Error('data.page is undefined');
}
chai_1.expect(callsToRedirect).to.equal(0);
});
it('Should redirect due to requester lacking permissions', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 0;
const info = {
userId: 1,
};
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
},
getUserRole: async (providedGroup, providedUser) => {
chai_1.expect(providedGroup).to.equal(groupId);
chai_1.expect(providedUser).to.equal(info.userId);
return {
permissions: {
manage: 0,
}
};
},
};
let callsToRedirect = 0;
const res = {
redirect: (url) => {
callsToRedirect++;
},
};
await groups.groupManage(info, res, groupId, groupName);
chai_1.expect(callsToRedirect).to.equal(1);
});
it('Should throw 404 due to locked group', async () => {
const groupId = 25;
const groupName = 'hello';
const groupStatus = 1;
const info = {
userId: 1,
};
groups.Groups = {
getInfo: async (providedId) => {
chai_1.expect(providedId).to.equal(groupId);
return {
groupId,
groupName,
groupStatus,
};
},
getUserRole: async (providedGroup, providedUser) => {
chai_1.expect(providedGroup).to.equal(groupId);
chai_1.expect(providedUser).to.equal(info.userId);
return {
permissions: {
manage: 0,
}
};
},
};
let callsToRedirect = 0;
const res = {
redirect: (url) => {
callsToRedirect++;
},
};
try {
await groups.groupManage(info, res, groupId, groupName);
throw new Error('Request passed for locked group');
}
catch (err) {
if (!(err instanceof groups.NotFound)) {
throw err;
}
chai_1.expect(callsToRedirect).to.equal(0);
chai_1.expect(err.message).to.equal('InvalidGroupId');
}
});
});
|
rxchen/micropython | tests/unix/ffi_float.py | <gh_stars>1000+
# test ffi float support
try:
import ffi
except ImportError:
print("SKIP")
raise SystemExit
def ffi_open(names):
err = None
for n in names:
try:
mod = ffi.open(n)
return mod
except OSError as e:
err = e
raise err
libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib"))
try:
strtof = libc.func("f", "strtof", "sp")
except OSError:
# Some libc's (e.g. Android's Bionic) define strtof as macro/inline func
# in terms of strtod().
print("SKIP")
raise SystemExit
print("%.6f" % strtof("1.23", None))
strtod = libc.func("d", "strtod", "sp")
print("%.6f" % strtod("1.23", None))
# test passing double and float args
libm = ffi_open(("libm.so", "libm.so.6", "libc.so.0", "libc.so.6", "libc.dylib"))
tgamma = libm.func("d", "tgamma", "d")
for fun_name in ("tgamma",):
fun = globals()[fun_name]
for val in (0.5, 1, 1.0, 1.5, 4, 4.0):
print(fun_name, "%.5f" % fun(val))
# test passing 2x float/double args
powf = libm.func("f", "powf", "ff")
pow = libm.func("d", "pow", "dd")
for fun_name in ("powf", "pow"):
fun = globals()[fun_name]
for args in ((0, 1), (1, 0), (2, 0.5), (3, 4)):
print(fun_name, "%.5f" % fun(*args))
|
im97mori-github/AdvertisingDataParser | profile/rcp/central/src/main/java/org/im97mori/ble/profile/rcp/central/ReconnectionConfigurationProfileCallback.java | package org.im97mori.ble.profile.rcp.central;
import org.im97mori.ble.profile.central.ProfileCallback;
import org.im97mori.ble.service.bms.central.BondManagementServiceCallback;
import org.im97mori.ble.service.rcs.central.ReconnectionConfigurationServiceCallback;
/**
* Reconnection Configuration Profile callback
*
* @see ReconnectionConfigurationServiceCallback
* @see BondManagementServiceCallback
* @see ProfileCallback
*/
public interface ReconnectionConfigurationProfileCallback extends ReconnectionConfigurationServiceCallback, BondManagementServiceCallback, ProfileCallback {
}
|
rayson1223/gym-workflow | analysis/action_epsiode.py | import numpy as np
import matplotlib.pyplot as plt
import csv
import sys
import os
import json
from collections import namedtuple
csv.field_size_limit(sys.maxsize)
def plot_episode_analysis(data, reward_data, epi):
X = list(range(1, len(data)+1, 1))
plt.clf()
plt.xlabel("Cycle")
plt.ylabel("Action Taken")
plt.title("Action Taken in {} Episode".format(epi))
plt.ylim([0, 11])
plt.axhspan(9, 11, alpha=0.5)
plt.grid()
plt.plot(X, data, label="Action Taken")
plt.plot(X, reward_data, label="Rewards")
plt.legend(loc="lower left")
plt.show()
def plot_action_distribution(data):
fig = plt.figure(1, figsize=(40, 15))
ax = fig.add_subplot(111)
plt.xlabel("Episode")
plt.ylabel("Action Distribution")
plt.title('Action distribution over episode')
ax.boxplot(data, showfliers=False)
plt.show()
def main():
# {epi: {state: [], action, reward}}
x = {}
boxplot_data = {}
with open('../agents/records/exp-3-epi-100-train-0-maintain-all-terminal-100-2.csv') as f:
# with open('./data/exp4/exp-4-training-epi-200-vm-100.csv') as f:
reader = csv.DictReader(f)
for line in reader:
epi = int(line['episode']) + 1
if epi not in x:
x[epi] = {"state": [], "action": [], "reward": []}
boxplot_data[epi] = []
x[epi]["state"].append(int(line["state"]))
x[epi]["action"].append(int(line["action"]) + 1)
x[epi]["reward"].append(float(line["reward"]))
boxplot_data[epi].append(int(line["action"]) + 1)
# plot_action_distribution(boxplot_data.values())
last_epi = 61 # len(x)
plot_episode_analysis(x[last_epi]["action"], x[last_epi]["reward"], last_epi-1)
print(sum(x[last_epi]["reward"]))
# reward counter
# for k, v in x.items():
# print("reward counter {}".format(len(list(filter(lambda x: x > 0, v["reward"])))))
# print("correct action counter {}".format(len(list(filter(lambda x: x > 7, v["action"])))))
if __name__ == '__main__':
sys.exit(main())
|
sparkslabs/kamaelia_orig | Sketches/PO/testingMulticore/pprocess/ProcessPipelineNotComponent.py | <reponame>sparkslabs/kamaelia_orig
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
#...x....1....x....2....x....3....x....4....x....5....x.
import Axon
from Axon.Scheduler import scheduler
import Axon.LikeFile
import pprocess
import time
import pprint
class ProcessWrapComponent(object):
def __init__(self, somecomponent):
self.wrapped = somecomponent.__class__.__name__
print "wrapped a", self.wrapped
self.exchange = pprocess.Exchange()
self.channel = None
self.inbound = []
self.C = somecomponent
self.ce = None
self.tick = time.time()
def _print(self, *args):
print self.wrapped," ".join([str(x) for x in args])
def tick_print(self, *args):
if time.time() - self.tick > 0.5:
self._print(*args)
self.tick = time.time()
def run(self, channel):
self.exchange.add(channel)
self.channel = channel
from Axon.LikeFile import likefile, background
background(zap=True).start()
time.sleep(0.1)
self.ce = likefile(self.C)
for i in self.main():
pass
def activate(self):
channel = pprocess.start(self.run)
return channel
def getDataFromReadyChannel(self):
chan = self.exchange.ready(0)[0]
D = chan._receive()
return D
def passOnDataToComponent(self, D):
self._print("pwc:- SEND", D, "TO", self.C.name)
self.ce.put(*D)
self._print("SENT")
def main(self):
while 1:
self.tick_print("")
if self.exchange.ready(0):
D = self.getDataFromReadyChannel()
self.passOnDataToComponent(D)
D = self.ce.anyReady()
if D:
for boxname in D:
D = self.ce.get(boxname)
self.channel._send((D, boxname))
yield 1
if self.channel.closed:
self._print(self.channel.closed)
def ProcessPipeline(*components):
exchange = pprocess.Exchange()
debug = False
chans = []
print "TESTING ME"
for comp in components:
A = ProcessWrapComponent( comp )
chan = A.activate()
chans.append( chan )
exchange.add(chan )
mappings = {}
for i in xrange(len(components)-1):
ci, cin = chans[i], chans[i+1]
mappings[ (ci, "outbox") ] = (cin, "inbox")
mappings[ (ci, "signal") ] = (cin, "control")
while 1:
for chan in exchange.ready(0):
D = chan._receive()
try:
dest = mappings[ ( chan, D[1] ) ]
dest[0]._send( (D[0], dest[1] ) )
print "FORWARDED", D
except KeyError:
if debug:
print "WARNING: unlinked box sent data"
print "This may be an error for your logic"
print "chan, D[1] D[0]",
print chan, D[1], repr(D[0])
pprint.pprint( mappings )
time.sleep(0.1)
|
HipsterBrown/test_track_rails_client | spec/models/test_track/remote/split_config_spec.rb | <reponame>HipsterBrown/test_track_rails_client
require 'rails_helper'
RSpec.describe TestTrack::Remote::SplitConfig do
let(:params) { { name: "my_split", weighting_registry: { foo: 25, bar: 75 } } }
let(:create_url) { "http://testtrack.dev/api/v1/split_configs" }
let(:destroy_url) { "http://testtrack.dev/api/v1/split_configs/some_split" }
subject { described_class.new(params) }
before do
stub_request(:post, create_url)
.with(basic_auth: %w(dummy fakepassword))
.to_return(status: 204, body: "")
stub_request(:delete, destroy_url)
.with(basic_auth: %w(dummy fakepassword))
.to_return(status: 204, body: "")
end
describe "#save" do
it "doesn't hit the remote in test mode" do
expect(subject.save).to eq true
expect(WebMock).not_to have_been_requested
end
it "hits the server when enabled" do
with_test_track_enabled { subject.save }
expect(WebMock).to have_requested(:post, create_url).with(body: params.to_json)
end
end
describe ".destroy_existing" do
it "doesn't hit the remote in test mode" do
described_class.destroy_existing(:some_split)
expect(WebMock).not_to have_been_requested
end
it "hits the server when enabled" do
with_test_track_enabled { described_class.destroy_existing(:some_split) }
expect(WebMock).to have_requested(:delete, destroy_url)
end
end
end
|
michaelkantor/wavemaker | wavemaker/wavemaker-runtime/src/test/java/com/wavemaker/runtime/data/sample/db2sampledb/DB2Sample.java | <reponame>michaelkantor/wavemaker<gh_stars>0
/*
* Copyright (C) 2009 WaveMaker Software, Inc.
*
* This file is part of the WaveMaker Server Runtime.
*
* 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.wavemaker.runtime.data.sample.db2sampledb;
import java.util.List;
import com.wavemaker.common.util.SpringUtils;
import com.wavemaker.runtime.data.DataServiceManager;
import com.wavemaker.runtime.data.DataServiceManagerAccess;
import com.wavemaker.runtime.data.QueryOptions;
import com.wavemaker.runtime.data.TaskManager;
/**
* Generated for service "db2sample" on 02/07/2008 13:48:00
*/
@SuppressWarnings({ "unchecked" })
public class DB2Sample implements DataServiceManagerAccess {
private DataServiceManager dsMgr;
private TaskManager taskMgr;
public Integer getCustomerCount(Customer searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Customer();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getCustomerCount(Customer searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Customer();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getCustomerCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Customer.class);
}
public List<Org> getOrgList(Org searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Org();
}
return (List<Org>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Org> getOrgList(Org searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Org();
}
return (List<Org>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Org> getOrgList() {
return (List<Org>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Org.class);
}
public List<Vastrde2> getVastrde2List(Vastrde2 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vastrde2();
}
return (List<Vastrde2>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vastrde2> getVastrde2List(Vastrde2 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vastrde2();
}
return (List<Vastrde2>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vastrde2> getVastrde2List() {
return (List<Vastrde2>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vastrde2.class);
}
public void deleteVphone(Vphone vphone) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vphone);
}
public void deleteInTray(InTray inTray) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), inTray);
}
public Customer insertCustomer(Customer customer) {
return (Customer) this.dsMgr.invoke(this.taskMgr.getInsertTask(), customer);
}
public void deleteEmployee(Employee employee) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), employee);
}
public Vprojre1 insertVprojre1(Vprojre1 vprojre1) {
return (Vprojre1) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vprojre1);
}
public List<Productsupplier> getProductsupplierList(Productsupplier searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Productsupplier();
}
return (List<Productsupplier>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Productsupplier> getProductsupplierList(Productsupplier searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Productsupplier();
}
return (List<Productsupplier>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Productsupplier> getProductsupplierList() {
return (List<Productsupplier>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Productsupplier.class);
}
public Integer getVdepmg1Count(Vdepmg1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vdepmg1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVdepmg1Count(Vdepmg1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vdepmg1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVdepmg1Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vdepmg1.class);
}
public Integer getVhdeptCount(Vhdept searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vhdept();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVhdeptCount(Vhdept searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vhdept();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVhdeptCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vhdept.class);
}
public List<Sales> getSalesList(Sales searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Sales();
}
return (List<Sales>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Sales> getSalesList(Sales searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Sales();
}
return (List<Sales>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Sales> getSalesList() {
return (List<Sales>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Sales.class);
}
public void updatePurchaseorder(Purchaseorder purchaseorder) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), purchaseorder);
}
public void updateVprojact(Vprojact vprojact) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vprojact);
}
public void updateProductsupplier(Productsupplier productsupplier) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), productsupplier);
}
public void deleteVemp(Vemp vemp) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vemp);
}
public Projact getProjactById(ProjactId id) {
List<Projact> rtn = (List<Projact>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getProjactById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Staff getStaffById(StaffId id) {
List<Staff> rtn = (List<Staff>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getStaffById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Vastrde1 getVastrde1ById(Vastrde1Id id) {
List<Vastrde1> rtn = (List<Vastrde1>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVastrde1ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Vastrde1 insertVastrde1(Vastrde1 vastrde1) {
return (Vastrde1) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vastrde1);
}
public Project insertProject(Project project) {
return (Project) this.dsMgr.invoke(this.taskMgr.getInsertTask(), project);
}
public Act getActById(Short id) {
List<Act> rtn = (List<Act>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getActById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Integer getEmpPhotoCount(EmpPhoto searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.EmpPhoto();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getEmpPhotoCount(EmpPhoto searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.EmpPhoto();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getEmpPhotoCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), EmpPhoto.class);
}
public Integer getStaffCount(Staff searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Staff();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getStaffCount(Staff searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Staff();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getStaffCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Staff.class);
}
public Integer getVempprojactCount(Vempprojact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vempprojact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVempprojactCount(Vempprojact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vempprojact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVempprojactCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vempprojact.class);
}
public void updateVprojre1(Vprojre1 vprojre1) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vprojre1);
}
public void updateVphone(Vphone vphone) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vphone);
}
public void deleteEmpprojact(Empprojact empprojact) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), empprojact);
}
public List<Vdept> getVdeptList(Vdept searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vdept();
}
return (List<Vdept>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vdept> getVdeptList(Vdept searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vdept();
}
return (List<Vdept>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vdept> getVdeptList() {
return (List<Vdept>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vdept.class);
}
public Catalog getCatalogById(String id) {
List<Catalog> rtn = (List<Catalog>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getCatalogById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void deleteCatalog(Catalog catalog) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), catalog);
}
public Vastrde2 insertVastrde2(Vastrde2 vastrde2) {
return (Vastrde2) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vastrde2);
}
public Integer getProjactCount(Projact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Projact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getProjactCount(Projact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Projact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getProjactCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Projact.class);
}
public void deleteVproj(Vproj vproj) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vproj);
}
public void updateAct(Act act) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), act);
}
public Integer getEmpmdcCount(Empmdc searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Empmdc();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getEmpmdcCount(Empmdc searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Empmdc();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getEmpmdcCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Empmdc.class);
}
public void deleteCustomer(Customer customer) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), customer);
}
public Vstafac2 getVstafac2ById(Vstafac2Id id) {
List<Vstafac2> rtn = (List<Vstafac2>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVstafac2ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Sales insertSales(Sales sales) {
return (Sales) this.dsMgr.invoke(this.taskMgr.getInsertTask(), sales);
}
public void deleteProject(Project project) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), project);
}
public void deleteVstafac1(Vstafac1 vstafac1) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vstafac1);
}
public Vdept insertVdept(Vdept vdept) {
return (Vdept) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vdept);
}
public Vemplp getVemplpById(VemplpId id) {
List<Vemplp> rtn = (List<Vemplp>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVemplpById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public EmpPhoto getEmpPhotoById(EmpPhotoId id) {
List<EmpPhoto> rtn = (List<EmpPhoto>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getEmpPhotoById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Vproj insertVproj(Vproj vproj) {
return (Vproj) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vproj);
}
public Integer getProductsupplierCount(Productsupplier searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Productsupplier();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getProductsupplierCount(Productsupplier searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Productsupplier();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getProductsupplierCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Productsupplier.class);
}
public void deleteEmpResume(EmpResume empResume) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), empResume);
}
public void deleteVempdpt1(Vempdpt1 vempdpt1) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vempdpt1);
}
public Foo1 insertFoo1(Foo1 foo1) {
return (Foo1) this.dsMgr.invoke(this.taskMgr.getInsertTask(), foo1);
}
public Department getDepartmentById(String id) {
List<Department> rtn = (List<Department>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getDepartmentById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Productsupplier getProductsupplierById(ProductsupplierId id) {
List<Productsupplier> rtn = (List<Productsupplier>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getProductsupplierById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void updateVempdpt1(Vempdpt1 vempdpt1) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vempdpt1);
}
public List<Vempprojact> getVempprojactList(Vempprojact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vempprojact();
}
return (List<Vempprojact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vempprojact> getVempprojactList(Vempprojact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vempprojact();
}
return (List<Vempprojact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vempprojact> getVempprojactList() {
return (List<Vempprojact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vempprojact.class);
}
public Integer getClSchedCount(ClSched searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.ClSched();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getClSchedCount(ClSched searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.ClSched();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getClSchedCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), ClSched.class);
}
public void updateEmpPhoto(EmpPhoto empPhoto) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), empPhoto);
}
public Integer getProjectCount(Project searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Project();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getProjectCount(Project searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Project();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getProjectCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Project.class);
}
public Purchaseorder getPurchaseorderById(Long id) {
List<Purchaseorder> rtn = (List<Purchaseorder>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getPurchaseorderById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void deletePurchaseorder(Purchaseorder purchaseorder) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), purchaseorder);
}
public Vempprojact getVempprojactById(VempprojactId id) {
List<Vempprojact> rtn = (List<Vempprojact>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVempprojactById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Productsupplier insertProductsupplier(Productsupplier productsupplier) {
return (Productsupplier) this.dsMgr.invoke(this.taskMgr.getInsertTask(), productsupplier);
}
public List<Vemp> getVempList(Vemp searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vemp();
}
return (List<Vemp>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vemp> getVempList(Vemp searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vemp();
}
return (List<Vemp>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vemp> getVempList() {
return (List<Vemp>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vemp.class);
}
public Suppliers insertSuppliers(Suppliers suppliers) {
return (Suppliers) this.dsMgr.invoke(this.taskMgr.getInsertTask(), suppliers);
}
public List<Empprojact> getEmpprojactList(Empprojact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Empprojact();
}
return (List<Empprojact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Empprojact> getEmpprojactList(Empprojact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Empprojact();
}
return (List<Empprojact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Empprojact> getEmpprojactList() {
return (List<Empprojact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Empprojact.class);
}
public Vstafac2 insertVstafac2(Vstafac2 vstafac2) {
return (Vstafac2) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vstafac2);
}
public Integer getVactCount(Vact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVactCount(Vact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVactCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vact.class);
}
public Integer getVdeptCount(Vdept searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vdept();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVdeptCount(Vdept searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vdept();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVdeptCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vdept.class);
}
public void updateVempprojact(Vempprojact vempprojact) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vempprojact);
}
public Vstafac1 insertVstafac1(Vstafac1 vstafac1) {
return (Vstafac1) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vstafac1);
}
public Integer getSuppliersCount(Suppliers searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Suppliers();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getSuppliersCount(Suppliers searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Suppliers();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getSuppliersCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Suppliers.class);
}
public Purchaseorder insertPurchaseorder(Purchaseorder purchaseorder) {
return (Purchaseorder) this.dsMgr.invoke(this.taskMgr.getInsertTask(), purchaseorder);
}
public Vdepmg1 insertVdepmg1(Vdepmg1 vdepmg1) {
return (Vdepmg1) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vdepmg1);
}
public Vempdpt1 getVempdpt1ById(Vempdpt1Id id) {
List<Vempdpt1> rtn = (List<Vempdpt1>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVempdpt1ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Integer getVphoneCount(Vphone searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vphone();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVphoneCount(Vphone searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vphone();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVphoneCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vphone.class);
}
public void updateCustomer(Customer customer) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), customer);
}
public void updateVpstrde1(Vpstrde1 vpstrde1) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vpstrde1);
}
public List<InTray> getInTrayList(InTray searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.InTray();
}
return (List<InTray>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<InTray> getInTrayList(InTray searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.InTray();
}
return (List<InTray>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<InTray> getInTrayList() {
return (List<InTray>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), InTray.class);
}
public void deleteEmpmdc(Empmdc empmdc) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), empmdc);
}
public void updateVforpla(Vforpla vforpla) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vforpla);
}
public Project getProjectById(String id) {
List<Project> rtn = (List<Project>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getProjectById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public List<Vdepmg1> getVdepmg1List(Vdepmg1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vdepmg1();
}
return (List<Vdepmg1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vdepmg1> getVdepmg1List(Vdepmg1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vdepmg1();
}
return (List<Vdepmg1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vdepmg1> getVdepmg1List() {
return (List<Vdepmg1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vdepmg1.class);
}
public InTray insertInTray(InTray inTray) {
return (InTray) this.dsMgr.invoke(this.taskMgr.getInsertTask(), inTray);
}
public List<Vastrde1> getVastrde1List(Vastrde1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vastrde1();
}
return (List<Vastrde1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vastrde1> getVastrde1List(Vastrde1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vastrde1();
}
return (List<Vastrde1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vastrde1> getVastrde1List() {
return (List<Vastrde1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vastrde1.class);
}
public Integer getVstafac1Count(Vstafac1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vstafac1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVstafac1Count(Vstafac1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vstafac1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVstafac1Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vstafac1.class);
}
public Vpstrde2 insertVpstrde2(Vpstrde2 vpstrde2) {
return (Vpstrde2) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vpstrde2);
}
public List<Vprojre1> getVprojre1List(Vprojre1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vprojre1();
}
return (List<Vprojre1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vprojre1> getVprojre1List(Vprojre1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vprojre1();
}
return (List<Vprojre1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vprojre1> getVprojre1List() {
return (List<Vprojre1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vprojre1.class);
}
public EmpResume insertEmpResume(EmpResume empResume) {
return (EmpResume) this.dsMgr.invoke(this.taskMgr.getInsertTask(), empResume);
}
public Vforpla insertVforpla(Vforpla vforpla) {
return (Vforpla) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vforpla);
}
public List<Vhdept> getVhdeptList(Vhdept searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vhdept();
}
return (List<Vhdept>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vhdept> getVhdeptList(Vhdept searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vhdept();
}
return (List<Vhdept>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vhdept> getVhdeptList() {
return (List<Vhdept>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vhdept.class);
}
public List<Vemplp> getVemplpList(Vemplp searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vemplp();
}
return (List<Vemplp>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vemplp> getVemplpList(Vemplp searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vemplp();
}
return (List<Vemplp>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vemplp> getVemplpList() {
return (List<Vemplp>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vemplp.class);
}
public void deleteFoo1(Foo1 foo1) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), foo1);
}
public void deleteOrg(Org org) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), org);
}
public void deleteVemplp(Vemplp vemplp) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vemplp);
}
public Empmdc getEmpmdcById(EmpmdcId id) {
List<Empmdc> rtn = (List<Empmdc>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getEmpmdcById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void updateVact(Vact vact) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vact);
}
public void updateSales(Sales sales) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), sales);
}
public EmpPhoto insertEmpPhoto(EmpPhoto empPhoto) {
return (EmpPhoto) this.dsMgr.invoke(this.taskMgr.getInsertTask(), empPhoto);
}
public List<Vact> getVactList(Vact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vact();
}
return (List<Vact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vact> getVactList(Vact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vact();
}
return (List<Vact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vact> getVactList() {
return (List<Vact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vact.class);
}
public List<Vstafac2> getVstafac2List(Vstafac2 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vstafac2();
}
return (List<Vstafac2>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vstafac2> getVstafac2List(Vstafac2 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vstafac2();
}
return (List<Vstafac2>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vstafac2> getVstafac2List() {
return (List<Vstafac2>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vstafac2.class);
}
public Vhdept insertVhdept(Vhdept vhdept) {
return (Vhdept) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vhdept);
}
public List<Product> getProductList(Product searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Product();
}
return (List<Product>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Product> getProductList(Product searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Product();
}
return (List<Product>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Product> getProductList() {
return (List<Product>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Product.class);
}
public Act insertAct(Act act) {
return (Act) this.dsMgr.invoke(this.taskMgr.getInsertTask(), act);
}
public Integer getDepartmentCount(Department searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Department();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getDepartmentCount(Department searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Department();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getDepartmentCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Department.class);
}
public Vact insertVact(Vact vact) {
return (Vact) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vact);
}
public Integer getVforplaCount(Vforpla searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vforpla();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVforplaCount(Vforpla searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vforpla();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVforplaCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vforpla.class);
}
public void deleteVprojact(Vprojact vprojact) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vprojact);
}
public void deleteSuppliers(Suppliers suppliers) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), suppliers);
}
public List<Vphone> getVphoneList(Vphone searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vphone();
}
return (List<Vphone>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vphone> getVphoneList(Vphone searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vphone();
}
return (List<Vphone>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vphone> getVphoneList() {
return (List<Vphone>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vphone.class);
}
public void updateVastrde2(Vastrde2 vastrde2) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vastrde2);
}
public List<Customer> getCustomerList(Customer searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Customer();
}
return (List<Customer>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Customer> getCustomerList(Customer searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Customer();
}
return (List<Customer>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Customer> getCustomerList() {
return (List<Customer>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Customer.class);
}
public List<Employee> getEmployeeList(Employee searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Employee();
}
return (List<Employee>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Employee> getEmployeeList(Employee searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Employee();
}
return (List<Employee>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Employee> getEmployeeList() {
return (List<Employee>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Employee.class);
}
public void updateVastrde1(Vastrde1 vastrde1) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vastrde1);
}
public Integer getVemplpCount(Vemplp searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vemplp();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVemplpCount(Vemplp searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vemplp();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVemplpCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vemplp.class);
}
public Integer getEmpprojactCount(Empprojact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Empprojact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getEmpprojactCount(Empprojact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Empprojact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getEmpprojactCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Empprojact.class);
}
public void deleteAct(Act act) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), act);
}
public Vastrde2 getVastrde2ById(Vastrde2Id id) {
List<Vastrde2> rtn = (List<Vastrde2>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVastrde2ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public List<Vpstrde1> getVpstrde1List(Vpstrde1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vpstrde1();
}
return (List<Vpstrde1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vpstrde1> getVpstrde1List(Vpstrde1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vpstrde1();
}
return (List<Vpstrde1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vpstrde1> getVpstrde1List() {
return (List<Vpstrde1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vpstrde1.class);
}
public List<Staff> getStaffList(Staff searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Staff();
}
return (List<Staff>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Staff> getStaffList(Staff searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Staff();
}
return (List<Staff>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Staff> getStaffList() {
return (List<Staff>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Staff.class);
}
public Org getOrgById(OrgId id) {
List<Org> rtn = (List<Org>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getOrgById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public List<Purchaseorder> getPurchaseorderList(Purchaseorder searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Purchaseorder();
}
return (List<Purchaseorder>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Purchaseorder> getPurchaseorderList(Purchaseorder searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Purchaseorder();
}
return (List<Purchaseorder>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Purchaseorder> getPurchaseorderList() {
return (List<Purchaseorder>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Purchaseorder.class);
}
public void deleteVempprojact(Vempprojact vempprojact) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vempprojact);
}
public void updateDepartment(Department department) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), department);
}
public Inventory getInventoryById(String id) {
List<Inventory> rtn = (List<Inventory>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getInventoryById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void updateInventory(Inventory inventory) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), inventory);
}
public List<Act> getActList(Act searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Act();
}
return (List<Act>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Act> getActList(Act searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Act();
}
return (List<Act>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Act> getActList() {
return (List<Act>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Act.class);
}
public Vemplp insertVemplp(Vemplp vemplp) {
return (Vemplp) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vemplp);
}
public Integer getEmployeeCount(Employee searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Employee();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getEmployeeCount(Employee searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Employee();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getEmployeeCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Employee.class);
}
public List<Catalog> getCatalogList(Catalog searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Catalog();
}
return (List<Catalog>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Catalog> getCatalogList(Catalog searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Catalog();
}
return (List<Catalog>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Catalog> getCatalogList() {
return (List<Catalog>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Catalog.class);
}
public Integer getPurchaseorderCount(Purchaseorder searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Purchaseorder();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getPurchaseorderCount(Purchaseorder searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Purchaseorder();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getPurchaseorderCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Purchaseorder.class);
}
public Org insertOrg(Org org) {
return (Org) this.dsMgr.invoke(this.taskMgr.getInsertTask(), org);
}
public void deleteVastrde1(Vastrde1 vastrde1) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vastrde1);
}
public void deleteStaff(Staff staff) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), staff);
}
public Vprojre1 getVprojre1ById(Vprojre1Id id) {
List<Vprojre1> rtn = (List<Vprojre1>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVprojre1ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void deleteProjact(Projact projact) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), projact);
}
public void deleteInventory(Inventory inventory) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), inventory);
}
public List<Department> getDepartmentList(Department searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Department();
}
return (List<Department>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Department> getDepartmentList(Department searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Department();
}
return (List<Department>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Department> getDepartmentList() {
return (List<Department>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Department.class);
}
public void updateEmpprojact(Empprojact empprojact) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), empprojact);
}
public void updateEmployee(Employee employee) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), employee);
}
public void deleteVastrde2(Vastrde2 vastrde2) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vastrde2);
}
public void deleteProduct(Product product) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), product);
}
public Integer getCatalogCount(Catalog searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Catalog();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getCatalogCount(Catalog searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Catalog();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getCatalogCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Catalog.class);
}
public Integer getFoo1Count(Foo1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Foo1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getFoo1Count(Foo1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Foo1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getFoo1Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Foo1.class);
}
public void updateVdept(Vdept vdept) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vdept);
}
public Vprojact getVprojactById(VprojactId id) {
List<Vprojact> rtn = (List<Vprojact>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVprojactById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void updateFoo1(Foo1 foo1) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), foo1);
}
public Foo1 getFoo1ById(Long id) {
List<Foo1> rtn = (List<Foo1>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getFoo1ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Integer getVempCount(Vemp searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vemp();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVempCount(Vemp searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vemp();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVempCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vemp.class);
}
public Vdepmg1 getVdepmg1ById(Vdepmg1Id id) {
List<Vdepmg1> rtn = (List<Vdepmg1>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVdepmg1ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Empmdc insertEmpmdc(Empmdc empmdc) {
return (Empmdc) this.dsMgr.invoke(this.taskMgr.getInsertTask(), empmdc);
}
public void deleteClSched(ClSched clSched) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), clSched);
}
public List<Vstafac1> getVstafac1List(Vstafac1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vstafac1();
}
return (List<Vstafac1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vstafac1> getVstafac1List(Vstafac1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vstafac1();
}
return (List<Vstafac1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vstafac1> getVstafac1List() {
return (List<Vstafac1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vstafac1.class);
}
public List<Empmdc> getEmpmdcList(Empmdc searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Empmdc();
}
return (List<Empmdc>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Empmdc> getEmpmdcList(Empmdc searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Empmdc();
}
return (List<Empmdc>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Empmdc> getEmpmdcList() {
return (List<Empmdc>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Empmdc.class);
}
public Suppliers getSuppliersById(String id) {
List<Suppliers> rtn = (List<Suppliers>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getSuppliersById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void updateProjact(Projact projact) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), projact);
}
public Vemp insertVemp(Vemp vemp) {
return (Vemp) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vemp);
}
public Vstafac1 getVstafac1ById(Vstafac1Id id) {
List<Vstafac1> rtn = (List<Vstafac1>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVstafac1ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void updateProduct(Product product) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), product);
}
public void deleteVdepmg1(Vdepmg1 vdepmg1) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vdepmg1);
}
public Department insertDepartment(Department department) {
return (Department) this.dsMgr.invoke(this.taskMgr.getInsertTask(), department);
}
public List<Projact> getProjactList(Projact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Projact();
}
return (List<Projact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Projact> getProjactList(Projact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Projact();
}
return (List<Projact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Projact> getProjactList() {
return (List<Projact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Projact.class);
}
public Vforpla getVforplaById(VforplaId id) {
List<Vforpla> rtn = (List<Vforpla>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVforplaById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Vhdept getVhdeptById(VhdeptId id) {
List<Vhdept> rtn = (List<Vhdept>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVhdeptById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public List<Suppliers> getSuppliersList(Suppliers searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Suppliers();
}
return (List<Suppliers>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Suppliers> getSuppliersList(Suppliers searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Suppliers();
}
return (List<Suppliers>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Suppliers> getSuppliersList() {
return (List<Suppliers>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Suppliers.class);
}
public Customer getCustomerById(Long id) {
List<Customer> rtn = (List<Customer>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getCustomerById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void updateProject(Project project) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), project);
}
public Integer getEmpResumeCount(EmpResume searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.EmpResume();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getEmpResumeCount(EmpResume searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.EmpResume();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getEmpResumeCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), EmpResume.class);
}
public void updateEmpmdc(Empmdc empmdc) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), empmdc);
}
public List<Project> getProjectList(Project searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Project();
}
return (List<Project>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Project> getProjectList(Project searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Project();
}
return (List<Project>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Project> getProjectList() {
return (List<Project>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Project.class);
}
public void deleteDepartment(Department department) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), department);
}
public Vphone getVphoneById(VphoneId id) {
List<Vphone> rtn = (List<Vphone>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVphoneById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void deleteVhdept(Vhdept vhdept) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vhdept);
}
public ClSched getClSchedById(ClSchedId id) {
List<ClSched> rtn = (List<ClSched>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getClSchedById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public List<EmpResume> getEmpResumeList(EmpResume searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.EmpResume();
}
return (List<EmpResume>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<EmpResume> getEmpResumeList(EmpResume searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.EmpResume();
}
return (List<EmpResume>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<EmpResume> getEmpResumeList() {
return (List<EmpResume>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), EmpResume.class);
}
public Integer getInTrayCount(InTray searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.InTray();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getInTrayCount(InTray searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.InTray();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getInTrayCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), InTray.class);
}
public Empprojact getEmpprojactById(EmpprojactId id) {
List<Empprojact> rtn = (List<Empprojact>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getEmpprojactById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Integer getInventoryCount(Inventory searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Inventory();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getInventoryCount(Inventory searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Inventory();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getInventoryCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Inventory.class);
}
public Vphone insertVphone(Vphone vphone) {
return (Vphone) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vphone);
}
public void updateVpstrde2(Vpstrde2 vpstrde2) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vpstrde2);
}
public Integer getActCount(Act searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Act();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getActCount(Act searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Act();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getActCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Act.class);
}
public ClSched insertClSched(ClSched clSched) {
return (ClSched) this.dsMgr.invoke(this.taskMgr.getInsertTask(), clSched);
}
public void deleteVprojre1(Vprojre1 vprojre1) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vprojre1);
}
public Integer getVempdpt1Count(Vempdpt1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vempdpt1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVempdpt1Count(Vempdpt1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vempdpt1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVempdpt1Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vempdpt1.class);
}
public Product insertProduct(Product product) {
return (Product) this.dsMgr.invoke(this.taskMgr.getInsertTask(), product);
}
public Staff insertStaff(Staff staff) {
return (Staff) this.dsMgr.invoke(this.taskMgr.getInsertTask(), staff);
}
public void updateVhdept(Vhdept vhdept) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vhdept);
}
public void deleteVact(Vact vact) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vact);
}
public Vpstrde1 insertVpstrde1(Vpstrde1 vpstrde1) {
return (Vpstrde1) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vpstrde1);
}
public List<Vproj> getVprojList(Vproj searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vproj();
}
return (List<Vproj>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vproj> getVprojList(Vproj searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vproj();
}
return (List<Vproj>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vproj> getVprojList() {
return (List<Vproj>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vproj.class);
}
public Integer getVprojre1Count(Vprojre1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vprojre1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVprojre1Count(Vprojre1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vprojre1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVprojre1Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vprojre1.class);
}
public Sales getSalesById(SalesId id) {
List<Sales> rtn = (List<Sales>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getSalesById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void updateSuppliers(Suppliers suppliers) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), suppliers);
}
public Integer getVstafac2Count(Vstafac2 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vstafac2();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVstafac2Count(Vstafac2 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vstafac2();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVstafac2Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vstafac2.class);
}
public void updateInTray(InTray inTray) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), inTray);
}
public void updateClSched(ClSched clSched) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), clSched);
}
public Vempdpt1 insertVempdpt1(Vempdpt1 vempdpt1) {
return (Vempdpt1) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vempdpt1);
}
public Employee getEmployeeById(String id) {
List<Employee> rtn = (List<Employee>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getEmployeeById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Product getProductById(String id) {
List<Product> rtn = (List<Product>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getProductById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Catalog insertCatalog(Catalog catalog) {
return (Catalog) this.dsMgr.invoke(this.taskMgr.getInsertTask(), catalog);
}
public Empprojact insertEmpprojact(Empprojact empprojact) {
return (Empprojact) this.dsMgr.invoke(this.taskMgr.getInsertTask(), empprojact);
}
public void deleteVdept(Vdept vdept) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vdept);
}
public Integer getVpstrde1Count(Vpstrde1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vpstrde1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVpstrde1Count(Vpstrde1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vpstrde1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVpstrde1Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vpstrde1.class);
}
public void updateVemplp(Vemplp vemplp) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vemplp);
}
public void updateOrg(Org org) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), org);
}
public Integer getProductCount(Product searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Product();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getProductCount(Product searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Product();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getProductCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Product.class);
}
public EmpResume getEmpResumeById(EmpResumeId id) {
List<EmpResume> rtn = (List<EmpResume>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getEmpResumeById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Vpstrde1 getVpstrde1ById(Vpstrde1Id id) {
List<Vpstrde1> rtn = (List<Vpstrde1>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVpstrde1ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Vemp getVempById(VempId id) {
List<Vemp> rtn = (List<Vemp>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVempById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public List<Vempdpt1> getVempdpt1List(Vempdpt1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vempdpt1();
}
return (List<Vempdpt1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vempdpt1> getVempdpt1List(Vempdpt1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vempdpt1();
}
return (List<Vempdpt1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vempdpt1> getVempdpt1List() {
return (List<Vempdpt1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vempdpt1.class);
}
public void updateVstafac2(Vstafac2 vstafac2) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vstafac2);
}
public Projact insertProjact(Projact projact) {
return (Projact) this.dsMgr.invoke(this.taskMgr.getInsertTask(), projact);
}
public Integer getOrgCount(Org searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Org();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getOrgCount(Org searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Org();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getOrgCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Org.class);
}
public InTray getInTrayById(InTrayId id) {
List<InTray> rtn = (List<InTray>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getInTrayById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public List<Vforpla> getVforplaList(Vforpla searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vforpla();
}
return (List<Vforpla>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vforpla> getVforplaList(Vforpla searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vforpla();
}
return (List<Vforpla>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vforpla> getVforplaList() {
return (List<Vforpla>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vforpla.class);
}
public Integer getVastrde2Count(Vastrde2 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vastrde2();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVastrde2Count(Vastrde2 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vastrde2();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVastrde2Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vastrde2.class);
}
public Vdept getVdeptById(VdeptId id) {
List<Vdept> rtn = (List<Vdept>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVdeptById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public Integer getVprojactCount(Vprojact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vprojact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVprojactCount(Vprojact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vprojact();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVprojactCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vprojact.class);
}
public void deleteProductsupplier(Productsupplier productsupplier) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), productsupplier);
}
public void updateVdepmg1(Vdepmg1 vdepmg1) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vdepmg1);
}
public Vprojact insertVprojact(Vprojact vprojact) {
return (Vprojact) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vprojact);
}
public Integer getSalesCount(Sales searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Sales();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getSalesCount(Sales searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Sales();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getSalesCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Sales.class);
}
public Vact getVactById(VactId id) {
List<Vact> rtn = (List<Vact>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVactById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public List<Vprojact> getVprojactList(Vprojact searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vprojact();
}
return (List<Vprojact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vprojact> getVprojactList(Vprojact searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vprojact();
}
return (List<Vprojact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vprojact> getVprojactList() {
return (List<Vprojact>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vprojact.class);
}
public void deleteVforpla(Vforpla vforpla) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vforpla);
}
public void updateVstafac1(Vstafac1 vstafac1) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vstafac1);
}
public List<EmpPhoto> getEmpPhotoList(EmpPhoto searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.EmpPhoto();
}
return (List<EmpPhoto>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<EmpPhoto> getEmpPhotoList(EmpPhoto searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.EmpPhoto();
}
return (List<EmpPhoto>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<EmpPhoto> getEmpPhotoList() {
return (List<EmpPhoto>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), EmpPhoto.class);
}
public List<Inventory> getInventoryList(Inventory searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Inventory();
}
return (List<Inventory>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Inventory> getInventoryList(Inventory searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Inventory();
}
return (List<Inventory>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Inventory> getInventoryList() {
return (List<Inventory>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Inventory.class);
}
public void updateCatalog(Catalog catalog) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), catalog);
}
public void updateVemp(Vemp vemp) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vemp);
}
public void deleteSales(Sales sales) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), sales);
}
public Vempprojact insertVempprojact(Vempprojact vempprojact) {
return (Vempprojact) this.dsMgr.invoke(this.taskMgr.getInsertTask(), vempprojact);
}
public List<Vpstrde2> getVpstrde2List(Vpstrde2 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vpstrde2();
}
return (List<Vpstrde2>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Vpstrde2> getVpstrde2List(Vpstrde2 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vpstrde2();
}
return (List<Vpstrde2>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Vpstrde2> getVpstrde2List() {
return (List<Vpstrde2>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Vpstrde2.class);
}
public void deleteVstafac2(Vstafac2 vstafac2) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vstafac2);
}
public Vproj getVprojById(VprojId id) {
List<Vproj> rtn = (List<Vproj>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVprojById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void updateEmpResume(EmpResume empResume) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), empResume);
}
public Integer getVprojCount(Vproj searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vproj();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVprojCount(Vproj searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vproj();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVprojCount() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vproj.class);
}
public Employee insertEmployee(Employee employee) {
return (Employee) this.dsMgr.invoke(this.taskMgr.getInsertTask(), employee);
}
public List<ClSched> getClSchedList(ClSched searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.ClSched();
}
return (List<ClSched>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<ClSched> getClSchedList(ClSched searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.ClSched();
}
return (List<ClSched>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<ClSched> getClSchedList() {
return (List<ClSched>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), ClSched.class);
}
public Integer getVastrde1Count(Vastrde1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vastrde1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVastrde1Count(Vastrde1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vastrde1();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVastrde1Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vastrde1.class);
}
public Inventory insertInventory(Inventory inventory) {
return (Inventory) this.dsMgr.invoke(this.taskMgr.getInsertTask(), inventory);
}
public void updateStaff(Staff staff) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), staff);
}
public void deleteVpstrde1(Vpstrde1 vpstrde1) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vpstrde1);
}
public void deleteVpstrde2(Vpstrde2 vpstrde2) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), vpstrde2);
}
public Integer getVpstrde2Count(Vpstrde2 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vpstrde2();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance, options);
}
public Integer getVpstrde2Count(Vpstrde2 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Vpstrde2();
}
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), searchInstance);
}
public Integer getVpstrde2Count() {
return (Integer) this.dsMgr.invoke(this.taskMgr.getCountTask(), Vpstrde2.class);
}
public void updateVproj(Vproj vproj) {
this.dsMgr.invoke(this.taskMgr.getUpdateTask(), vproj);
}
public Vpstrde2 getVpstrde2ById(Vpstrde2Id id) {
List<Vpstrde2> rtn = (List<Vpstrde2>) this.dsMgr.invoke(this.taskMgr.getQueryTask(), "getVpstrde2ById", id);
if (rtn.isEmpty()) {
return null;
} else {
return rtn.get(0);
}
}
public void deleteEmpPhoto(EmpPhoto empPhoto) {
this.dsMgr.invoke(this.taskMgr.getDeleteTask(), empPhoto);
}
public List<Foo1> getFoo1List(Foo1 searchInstance, QueryOptions options) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Foo1();
}
return (List<Foo1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance, options);
}
public List<Foo1> getFoo1List(Foo1 searchInstance) {
if (searchInstance == null) {
searchInstance = new com.wavemaker.runtime.data.sample.db2sampledb.Foo1();
}
return (List<Foo1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), searchInstance);
}
public List<Foo1> getFoo1List() {
return (List<Foo1>) this.dsMgr.invoke(this.taskMgr.getSearchTask(), Foo1.class);
}
public void begin() {
this.dsMgr.begin();
}
public void commit() {
this.dsMgr.commit();
}
public void rollback() {
this.dsMgr.rollback();
}
@Override
public DataServiceManager getDataServiceManager() {
return this.dsMgr;
}
public void setDataServiceManager(DataServiceManager dsMgr) {
this.dsMgr = dsMgr;
}
public TaskManager getTaskManager() {
return this.taskMgr;
}
public void setTaskManager(TaskManager taskMgr) {
this.taskMgr = taskMgr;
}
public static final void main(String[] args) {
String cfg = "db2sample.spring.xml";
String beanName = "db2sample";
com.wavemaker.runtime.data.sample.db2sampledb.DB2Sample s = (com.wavemaker.runtime.data.sample.db2sampledb.DB2Sample) SpringUtils.getBean(
cfg, beanName);
System.out.print("getCustomerCount: ");
System.out.println(s.getCustomerCount());
}
}
|
andrenjunior/Linguagem-de-Programa-o-Python | Tele_Aula 4/DataFrame.py | import pandas as pd
import numpy as np
df = pd.DataFrame ({
'nome' : ['André', 'Junior', 'Nascimento'],
'idade': [38, 37, 36],
'cidade': ['RJ','SP','MG']
})
print(df)
print('\n')
vetor = np.array([5, 6, 7, 8])
v = pd.Series(vetor)
print(vetor)
print(v)
print('\n\n')
print(df.nome) # retorna somente com a coluna nome
print('\n\n')
print(df.idade.mean()) # Retorna com a média de idade |
opala-studios/ck | src/ck/core/fixedstring.h | #pragma once
#include "ck/core/platform.h"
#include "ck/core/string.h"
namespace Cki
{
template <int N>
class FixedString : public String
{
public:
FixedString();
FixedString(const char*);
FixedString(const String&);
// FixedString(const char*, int n);
// FixedString(const String&, int n);
FixedString(const FixedString<N>&);
FixedString& operator=(const FixedString<N>&);
~FixedString();
enum { k_bufSize = N };
enum { k_capacity = N-1 }; // not including null
private:
char m_array[N]; // storage for N chars (string length N-1)
};
typedef FixedString<32> FixedString32;
typedef FixedString<64> FixedString64;
typedef FixedString<128> FixedString128;
typedef FixedString<256> FixedString256;
}
|
hiloWang/notes | JavaEE/Code/Servlet-Base/src/main/java/com/ztiany/serbase/servlets/http/DownloadServlet.java | package com.ztiany.serbase.servlets.http;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 演示让浏览器以下载方式读取数据
*
* @author Ztiany
* Email <EMAIL>
* Date 18.4.14 17:10
*/
public class DownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
//通知浏览器以下载的方式打开
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=android.jpg");
//通过ServletContext的getRealPath获取文件相对路径:相对于应用来说,是固定的
//构建文件的输入流
String realPath = getServletContext().getRealPath("/images/android.jpg");
InputStream in = new FileInputStream(realPath);
//用response对象的输出流输出
OutputStream out = response.getOutputStream();
int len;
byte b[] = new byte[1024];
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
//关闭资源
in.close();
out.close();
}
}
|
sun-iot/IceFireDB-Proxy | pkg/monitor/runtime_exporter.go | /*
*
* * Licensed to the Apache Software Foundation (ASF) under one or more
* * contributor license agreements. See the NOTICE file distributed with
* * this work for additional information regarding copyright ownership.
* * The ASF licenses this file to You under the Apache License, Version 2.0
* * (the "License"); you may not use this file except in compliance with
* * the License. You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package monitor
import (
"runtime"
"github.com/sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus"
)
var runtimeGaugeVec = map[string]*prometheus.Desc{
"cpu.count": NewDesc("cpu_count", "Count of logical CPUs usable by the current process.", BasicLabels),
"cpu.goroutines": NewDesc("cpu_goroutines", "Count of goroutines that currently exist.", BasicLabels),
"mem.alloc": NewDesc("mem_alloc", "mem_alloc is the same as HeapAlloc.", BasicLabels),
"mem.total": NewDesc("mem_total", "mem_total is cumulative bytes allocated for heap objects.", BasicLabels),
"mem.sys": NewDesc("mem_sys", "mem_sys is the total bytes of memory obtained from the OS.", BasicLabels),
"mem.lookups": NewDesc("mem_lookups", "mem_lookups is the number of pointer lookups performed by the runtime.", BasicLabels),
"mem.malloc": NewDesc("mem_malloc", "mem_malloc is the cumulative count of heap objects allocated.", BasicLabels),
"mem.frees": NewDesc("mem_frees", "mem_frees is the cumulative count of heap objects freed.", BasicLabels),
"mem.heap.alloc": NewDesc("mem_heap_alloc", "mem_heap_alloc is bytes of allocated heap objects.", BasicLabels),
"mem.heap.sys": NewDesc("mem_heap_sys", "mem_heap_sys is bytes of heap memory obtained from the OS.", BasicLabels),
"mem.heap.idle": NewDesc("mem_heap_idle", "mem_heap_idle is bytes in idle (unused) spans.", BasicLabels),
"mem.heap.inuse": NewDesc("mem_heap_inuse", "mem_heap_inuse is bytes in in-use spans.", BasicLabels),
"mem.heap.released": NewDesc("mem_heap_released", "mem_heap_released is bytes of physical memory returned to the OS.", BasicLabels),
"mem.heap.objects": NewDesc("mem_heap_objects", "mem_heap_objects is the number of allocated heap objects.", BasicLabels),
"mem.stack.inuse": NewDesc("mem_stack_inuse", "mem_stack_inuse is bytes in stack spans.", BasicLabels),
"mem.stack.sys": NewDesc("mem_stack_sys", "mem_stack_sys is bytes of stack memory obtained from the OS.", BasicLabels),
"mem.stack.mspan_inuse": NewDesc("mem_stack_mspan_inuse", "mem_stack_mspan_inuse Off-heap memory statistics.", BasicLabels),
"mem.stack.mspan_sys": NewDesc("mem_stack_mspan_sys", "mem_stack_mspan_sys is bytes of memory obtained from the OS for mspan.", BasicLabels),
"mem.stack.mcache_inuse": NewDesc("mem_stack_mcache_inuse", "mem_stack_mcache_inuse is bytes of allocated mcache structures.", BasicLabels),
"mem.stack.mcache_sys": NewDesc("mem_stack_mcache_sys", "mem_stack_mcache_sys is bytes of memory obtained from the OS for mcache structures.", BasicLabels),
"mem.othersys": NewDesc("mem_othersys", "mem_othersys is bytes of memory in miscellaneous off-heap runtime allocations.", BasicLabels),
"mem.gc.sys": NewDesc("mem_gc_sys", "mem_gc_sys is bytes of memory in garbage collection metadata.", BasicLabels),
"mem.gc.next": NewDesc("mem_gc_next", "mem_gc_next is the target heap size of the next GC cycle.", BasicLabels),
"mem.gc.last": NewDesc("mem_gc_last", "mem_gc_last is the time the last garbage collection finished, as nanoseconds since 1970 (the UNIX epoch).", BasicLabels),
"mem.gc.pause_total": NewDesc("mem_gc_pause_total", "mem_gc_pause_total is the cumulative nanoseconds in GC stop-the-world pauses since the program started.", BasicLabels),
"mem.gc.pause": NewDesc("mem_gc_pause", "mem_gc_pause is a circular buffer of recent GC stop-the-world pause times in nanoseconds.", BasicLabels),
"mem.gc.count": NewDesc("mem_gc_count", "mem_gc_count is the number of completed GC cycles.", BasicLabels),
"mem.gc.cpu_fraction": NewDesc("mem_gc_next_cpu_fraction", "mem_gc_next_cpu_fraction is the fraction of this program's available CPU time used by the GC since the program started.", BasicLabels),
}
type RuntimeExporter struct {
collect *collector
runtimeMetrics map[string]*prometheus.Desc
basicConf *ExporterConf
}
func NewRuntimeExport(c *ExporterConf) *RuntimeExporter {
metrics := make(map[string]*prometheus.Desc)
for k, v := range runtimeGaugeVec {
metrics[k] = v
}
return &RuntimeExporter{
basicConf: c,
runtimeMetrics: metrics,
collect: &collector{
EnableCPU: c.RunTimeExporterConf.EnableCPU,
EnableMem: c.RunTimeExporterConf.EnableMem,
EnableGC: c.RunTimeExporterConf.EnableGC,
},
}
}
func (r *RuntimeExporter) Describe(ch chan<- *prometheus.Desc) {
for _, metric := range r.runtimeMetrics {
ch <- metric
}
}
func (r *RuntimeExporter) Collect(ch chan<- prometheus.Metric) {
defer func() {
if r := recover(); r != nil {
logrus.Error("runtime promethues collect panic", r)
}
}()
fields := r.collect.oneOff()
values := fields.Values()
for metricKey, runtimeMetric := range r.runtimeMetrics {
if value, ok := values[metricKey]; ok {
switch value.(type) {
case int64:
ch <- prometheus.MustNewConstMetric(
runtimeMetric,
prometheus.GaugeValue,
float64(value.(int64)),
r.basicConf.Host,
)
case float64:
ch <- prometheus.MustNewConstMetric(
runtimeMetric,
prometheus.GaugeValue,
value.(float64),
r.basicConf.Host,
)
default:
ch <- prometheus.MustNewConstMetric(
runtimeMetric,
prometheus.GaugeValue,
0,
r.basicConf.Host,
)
}
}
}
}
type FieldsFunc func(Fields)
type collector struct {
EnableCPU bool
EnableMem bool
EnableGC bool
}
func (c *collector) oneOff() Fields {
return c.collectStats()
}
func (c *collector) collectStats() Fields {
fields := Fields{}
if c.EnableCPU {
cStats := cpuStats{
NumGoroutine: int64(runtime.NumGoroutine()),
NumCPU: int64(runtime.NumCPU()),
}
c.collectCPUStats(&fields, &cStats)
}
if c.EnableMem {
m := &runtime.MemStats{}
runtime.ReadMemStats(m)
c.collectMemStats(&fields, m)
if c.EnableGC {
c.collectGCStats(&fields, m)
}
}
return fields
}
func (*collector) collectCPUStats(fields *Fields, s *cpuStats) {
fields.NumCPU = s.NumCPU
fields.NumGoroutine = s.NumGoroutine
}
func (*collector) collectMemStats(fields *Fields, m *runtime.MemStats) {
fields.Alloc = int64(m.Alloc)
fields.TotalAlloc = int64(m.TotalAlloc)
fields.Sys = int64(m.Sys)
fields.Lookups = int64(m.Lookups)
fields.Mallocs = int64(m.Mallocs)
fields.Frees = int64(m.Frees)
fields.HeapAlloc = int64(m.HeapAlloc)
fields.HeapSys = int64(m.HeapSys)
fields.HeapIdle = int64(m.HeapIdle)
fields.HeapInuse = int64(m.HeapInuse)
fields.HeapReleased = int64(m.HeapReleased)
fields.HeapObjects = int64(m.HeapObjects)
fields.StackInuse = int64(m.StackInuse)
fields.StackSys = int64(m.StackSys)
fields.MSpanInuse = int64(m.MSpanInuse)
fields.MSpanSys = int64(m.MSpanSys)
fields.MCacheInuse = int64(m.MCacheInuse)
fields.MCacheSys = int64(m.MCacheSys)
fields.OtherSys = int64(m.OtherSys)
}
func (*collector) collectGCStats(fields *Fields, m *runtime.MemStats) {
fields.GCSys = int64(m.GCSys)
fields.NextGC = int64(m.NextGC)
fields.LastGC = int64(m.LastGC)
fields.PauseTotalNs = int64(m.PauseTotalNs)
fields.PauseNs = int64(m.PauseNs[(m.NumGC+255)%256])
fields.NumGC = int64(m.NumGC)
fields.GCCPUFraction = float64(m.GCCPUFraction)
}
type cpuStats struct {
NumCPU int64
NumGoroutine int64
}
type Fields struct {
NumCPU int64 `json:"cpu.count"`
NumGoroutine int64 `json:"cpu.goroutines"`
Alloc int64 `json:"mem.alloc"`
TotalAlloc int64 `json:"mem.total"`
Sys int64 `json:"mem.sys"`
Lookups int64 `json:"mem.lookups"`
Mallocs int64 `json:"mem.malloc"`
Frees int64 `json:"mem.frees"`
HeapAlloc int64 `json:"mem.heap.alloc"`
HeapSys int64 `json:"mem.heap.sys"`
HeapIdle int64 `json:"mem.heap.idle"`
HeapInuse int64 `json:"mem.heap.inuse"`
HeapReleased int64 `json:"mem.heap.released"`
HeapObjects int64 `json:"mem.heap.objects"`
StackInuse int64 `json:"mem.stack.inuse"`
StackSys int64 `json:"mem.stack.sys"`
MSpanInuse int64 `json:"mem.stack.mspan_inuse"`
MSpanSys int64 `json:"mem.stack.mspan_sys"`
MCacheInuse int64 `json:"mem.stack.mcache_inuse"`
MCacheSys int64 `json:"mem.stack.mcache_sys"`
OtherSys int64 `json:"mem.othersys"`
GCSys int64 `json:"mem.gc.sys"`
NextGC int64 `json:"mem.gc.next"`
LastGC int64 `json:"mem.gc.last"`
PauseTotalNs int64 `json:"mem.gc.pause_total"`
PauseNs int64 `json:"mem.gc.pause"`
NumGC int64 `json:"mem.gc.count"`
GCCPUFraction float64 `json:"mem.gc.cpu_fraction"`
}
func (f *Fields) Values() map[string]interface{} {
return map[string]interface{}{
"cpu.count": f.NumCPU,
"cpu.goroutines": f.NumGoroutine,
"mem.alloc": f.Alloc,
"mem.total": f.TotalAlloc,
"mem.sys": f.Sys,
"mem.lookups": f.Lookups,
"mem.malloc": f.Mallocs,
"mem.frees": f.Frees,
"mem.heap.alloc": f.HeapAlloc,
"mem.heap.sys": f.HeapSys,
"mem.heap.idle": f.HeapIdle,
"mem.heap.inuse": f.HeapInuse,
"mem.heap.released": f.HeapReleased,
"mem.heap.objects": f.HeapObjects,
"mem.stack.inuse": f.StackInuse,
"mem.stack.sys": f.StackSys,
"mem.stack.mspan_inuse": f.MSpanInuse,
"mem.stack.mspan_sys": f.MSpanSys,
"mem.stack.mcache_inuse": f.MCacheInuse,
"mem.stack.mcache_sys": f.MCacheSys,
"mem.othersys": f.OtherSys,
"mem.gc.sys": f.GCSys,
"mem.gc.next": f.NextGC,
"mem.gc.last": f.LastGC,
"mem.gc.pause_total": f.PauseTotalNs,
"mem.gc.pause": f.PauseNs,
"mem.gc.count": f.NumGC,
"mem.gc.cpu_fraction": float64(f.GCCPUFraction),
}
}
|
mzw/RevAjaxMutator | src/main/java/jp/mzw/revajaxmutator/fixer/DOMCloningToNoOpFixer.java | package jp.mzw.revajaxmutator.fixer;
import jp.mzw.ajaxmutator.mutatable.DOMCloning;
/**
* Replacing DOM cloning to No-op.
*/
public class DOMCloningToNoOpFixer extends ReplacingToNoOpFixer<DOMCloning> {
public DOMCloningToNoOpFixer() {
super(DOMCloning.class);
}
}
|
khangtran2020/contentDP | test.py | <reponame>khangtran2020/contentDP
import sys
a = int(sys.argv[1])
sum_t = 0
for i in range(a):
sum_t += a
print(sum_t)
|
safarmer/intellij-haskell | gen/intellij/haskell/psi/HaskellConstr1.java | // This is a generated file. Not intended for manual editing.
package intellij.haskell.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface HaskellConstr1 extends HaskellCompositeElement {
@NotNull
List<HaskellFielddecl> getFielddeclList();
@NotNull
List<HaskellPragma> getPragmaList();
@Nullable
HaskellQName getQName();
}
|
maxemiliang/vscode-ext | extensions/donjayamanne.python-0.3.21/out/public/index.js | <gh_stars>0
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require('react');
var react_dom_1 = require('react-dom');
require('isomorphic-fetch');
var Hello = (function (_super) {
__extends(Hello, _super);
function Hello() {
_super.call(this);
this.state = { value: "Initial State" };
}
Hello.prototype.componentDidMount = function () {
var _this = this;
var port = window.location.port;
var url = "http://localhost:" + port + "/test";
console.log("componentDidMount");
fetch(url).then(function (res) {
console.log("Got it");
return res.json();
}).then(function (values) {
console.log("values=");
console.log(values);
console.log("State set");
_this.setState({ value: values + '' });
}).catch(function (err) {
console.log("Error=");
console.log(err);
_this.setState({ value: 'Error: ' + err });
});
};
Hello.prototype.render = function () {
return (<div>Hello world from extension with state = {this.state.value}</div>);
};
return Hello;
}(React.Component));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Hello;
react_dom_1.render(<Hello />, document.getElementById('root'));
//# sourceMappingURL=index.js.map |
ineunetOS/knife | knife-core/src/main/java/com/ineunet/knife/api/dataflow/IDataFlowDefinition.java | /*
* Copyright 2013-2016 iNeunet OpenSource and 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 com.ineunet.knife.api.dataflow;
import java.util.List;
import com.ineunet.knife.core.dataflow.DataFlowMode;
/**
*
* @author <NAME>
* @since 2.0.2
* Created on 2015-3-21
*/
public interface IDataFlowDefinition {
/**
* @return id e.g. as a function code
*/
String getId();
void setId(String id);
/**
* @return flow name. e.g. as a function name
*/
String getName();
void setName(String name);
List<IDataFlowNode> getNodes();
void setNodes(List<IDataFlowNode> flowNodes);
/**
* Add the node if this flow not contains it.
*/
void addNode(IDataFlowNode node);
IDataFlowNode getNode(String id);
boolean containsNode(IDataFlowNode node);
DataFlowMode getMode();
void setMode(DataFlowMode mode);
String getNextRule();
void setNextRule(String nextRule);
String getBackRule();
void setBackRule(String backRule);
}
|
xxdavid/pensieve-web | src/components/modals/ResetDeckModal.js | <filename>src/components/modals/ResetDeckModal.js
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Button, Modal } from "semantic-ui-react";
class ResetDeckModal extends Component {
render() {
const { open, onClose, onSubmit } = this.props;
return (
<Modal open={open} onClose={onClose} size="tiny" className="position-relative">
<Modal.Header>Reset Deck</Modal.Header>
<Modal.Content>
<p>
<strong>
Resetting a deck will remove all your progress studying its cards. This action is
irreversible.
</strong>
{" "}
Are you sure you want to reset them?
</p>
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Close</Button>
<Button onClick={onSubmit} negative>
Reset
</Button>
</Modal.Actions>
</Modal>
);
}
}
ResetDeckModal.propTypes = {
open: PropTypes.bool,
onClose: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
};
export default ResetDeckModal;
|
kaleidot725/first-time-javascript | Chapter08/ex08-04-4/main.js | <reponame>kaleidot725/first-time-javascript<gh_stars>0
function 記号表現に変換する(カード){
const マーク名_絵文字
= { 'ハート': '💖', 'クローバー': '🍀', 'ダイア': '💎', 'スペード': '♠' };
const 数字からAJQK = { 1: 'A', 11: 'J', 12: 'Q', 13: "K" };
for(let i=2; i<=10; i++) 数字からAJQK[i] = i;
return マーク名_絵文字[カード.マーク]+数字からAJQK[カード.数字];
}
const カードの束 = [];
for(let マーク of ['ハート', 'クローバー', 'ダイア', 'スペード'])
for (let 数字=1; 数字<=13; 数字++)
カードの束.push({ マーク, 数字});
let 選択されたカード_記号表現 = カードの束.filter(カード => カード.数字 === 2).map(記号表現に変換する);
console.log(選択されたカード_記号表現);
選択されたカード_記号表現 = カードの束.filter(カード => カード.マーク === 'ダイア').map(記号表現に変換する);
console.log(選択されたカード_記号表現);
選択されたカード_記号表現= カードの束.filter(カード => カード.数字 > 10 && カード.マーク === 'ハート').map(記号表現に変換する);
console.log(選択されたカード_記号表現); |
KoehlerSB747/sd-tools | src/main/java/org/sd/nlp/entity/ExtractedEntityLoader.java | <reponame>KoehlerSB747/sd-tools<gh_stars>0
/*
Copyright 2008-2016 Semantic Discovery, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.sd.nlp.entity;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.sd.io.FileUtil;
/**
* Utility for loading multiple files with the same input lines of the form:
* inputLine \t entitiesXml
* <p>
* Note that files are grouped by having matching prefix names up to the first
* non-alphanumeric character.
*
* @author <NAME>
*/
public class ExtractedEntityLoader {
public static final boolean FAIL_ON_MISMATCH = true;
private List<File> files;
private String fileGroupName;
private TreeMap<Long, String> inputLines; // mapped by lineNum
private Map<Long, EntityContainer> entities; // mapped by lineNum
public ExtractedEntityLoader() {
this.files = null;
this.fileGroupName = null;
this.inputLines = new TreeMap<Long, String>();
this.entities = new HashMap<Long, EntityContainer>();
}
/**
* Load the file if it belongs to this loader's group, meaning either
* it is the first file to be loaded or its group name matches that of the
* first file loaded.
*
* @param file The file to load.
*
* @return true if loaded or false if the file doesn't belong to this loader's group
*/
public boolean load(File file) throws IOException {
boolean result = false;
final String curGroupName = getGroupName(file);
if (fileGroupName == null || curGroupName.equals(fileGroupName)) {
if (fileGroupName == null) fileGroupName = curGroupName;
doLoad(file);
result = true;
}
return result;
}
/**
* Get the (possibly null) files loaded in this loader.
*/
public List<File> getFiles() {
return files;
}
/**
* Get the (possibly null) file group name common to all files in this loader.
*/
public String getFileGroupName() {
return fileGroupName;
}
/**
* Set the file group name, but only if it hasn't yet been established by
* loading the first file.
*/
public ExtractedEntityLoader setFileGroupName(String fileGroupName) {
if (this.fileGroupName == null) {
this.fileGroupName = fileGroupName;
}
return this;
}
/**
* Get all (possibly null) input lines, referenced by line number.
*/
public TreeMap<Long, String> getInputLines() {
return inputLines;
}
/**
* Get all (possibly null) entities referenced by line number.
*/
public Map<Long, EntityContainer> getEntities() {
return entities;
}
public List<Entity> addLine(long lineNum, String inputLine, String entitiesXmlString) {
List<Entity> result = null;
final EntityLineAligner aligner = new EntityLineAligner(inputLine);
//NOTE: inputLine must be aligner's baseLine for correct entity positional data
// check/add lineNum to inputLine mapping
synchronized (inputLines) {
String curline = inputLines.get(lineNum);
if (curline == null) {
inputLines.put(lineNum, inputLine);
}
else {
aligner.setAltLine(curline);
if (FAIL_ON_MISMATCH) {
if (!aligner.aligns()) {
if (entitiesXmlString != null && !"".equals(entitiesXmlString)) {
throw new IllegalStateException("ERROR: mismatched lines '" + curline + "' -vs- '" + inputLine + "'");
}
}
}
}
}
// add entities
if (entitiesXmlString != null && !"".equals(entitiesXmlString)) {
synchronized (entities) {
EntityContainer entityContainer = entities.get(lineNum);
if (entityContainer == null) {
entityContainer = new EntityContainer();
entities.put(lineNum, entityContainer);
}
result = entityContainer.add(lineNum, entitiesXmlString, aligner);
}
}
return result;
}
private final void doLoad(File file) throws IOException {
if (files == null) {
this.files = new ArrayList<File>();
}
this.files.add(file);
long lineNum = 0;
String line = null;
final BufferedReader reader = FileUtil.getReader(file);
try {
while ((line = reader.readLine()) != null) {
if ("".equals(line) || line.startsWith("#")) continue;
final String[] parts = line.split("\\t");
final String inputLine = parts[0];
final String entitiesString = (parts.length > 1) ? parts[1] : null;
addLine(lineNum, inputLine, entitiesString);
++lineNum;
}
}
finally {
reader.close();
}
}
/**
* Compute the group name for the file, where files with a matching group name
* all contain the same lines but with perhaps different or no extracted entities.
* <p>
* This can be overridden by extenders. The default implementation uses the
* file name from its first character to its first non-alpha-numeric character.
*
* @param file The file whose group name to get
*
* @return the group name for the file.
*/
protected String getGroupName(File file) {
final String filename = file.getName();
return filename.split("\\W")[0];
}
}
|
farchanjo/webcron | src/main/java/br/eti/archanjo/webcron/dtos/JobsDTO.java | package br.eti.archanjo.webcron.dtos;
import br.eti.archanjo.webcron.enums.AsyncType;
import br.eti.archanjo.webcron.enums.Status;
import br.eti.archanjo.webcron.pojo.EnvironmentDTO;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.data.mongodb.core.index.TextIndexed;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/*
* Created by fabricio on 10/07/17.
*/
@Builder
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Getter
@Setter
@ToString
@EqualsAndHashCode
@JsonInclude(JsonInclude.Include.NON_NULL)
public class JobsDTO implements Serializable {
private static final long serialVersionUID = -7517693919191046339L;
private Long id;
@TextIndexed
private String name;
private AsyncType async;
private Integer fixedRate;
private Status status;
private List<EnvironmentDTO> environments;
private TimeUnit unit;
private SystemUsersDTO system;
private String command;
private String cron;
private Long userId;
private String directory;
private Date created;
private Date modified;
} |
spacegithub/steedos-platform | server/bundle/programs/server/packages/dburles_collection-helpers.js | <reponame>spacegithub/steedos-platform
(function () {
/* Imports */
var Meteor = Package.meteor.Meteor;
var global = Package.meteor.global;
var meteorEnv = Package.meteor.meteorEnv;
var _ = Package.underscore._;
var MongoInternals = Package.mongo.MongoInternals;
var Mongo = Package.mongo.Mongo;
(function(){
//////////////////////////////////////////////////////////////////////////////
// //
// packages/dburles_collection-helpers/collection-helpers.js //
// //
//////////////////////////////////////////////////////////////////////////////
//
Mongo.Collection.prototype.helpers = function(helpers) {
var self = this;
if (self._transform && ! self._helpers)
throw new Meteor.Error("Can't apply helpers to '" +
self._name + "' a transform function already exists!");
if (! self._helpers) {
self._helpers = function Document(doc) { return _.extend(this, doc); };
self._transform = function(doc) {
return new self._helpers(doc);
};
}
_.each(helpers, function(helper, key) {
self._helpers.prototype[key] = helper;
});
};
//////////////////////////////////////////////////////////////////////////////
}).call(this);
/* Exports */
Package._define("dburles:collection-helpers");
})();
|
eamanu/HistorialClinica-LaRioja | back-end/hospital-api/src/main/java/net/pladema/clinichistory/documents/service/domain/PatientInfoBo.java | <reponame>eamanu/HistorialClinica-LaRioja
package net.pladema.clinichistory.documents.service.domain;
import lombok.*;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class PatientInfoBo{
private Integer id;
private Short genderId;
private Short age;
} |
JoJo2nd/Heart | heart/src/lua/hLuaStateManager.h | /********************************************************************
Written by <NAME>
Please see the file HEART_LICENSE.txt in the source's root directory.
*********************************************************************/
#ifndef LUASTATEMANAGER_H__
#define LUASTATEMANAGER_H__
#include "base/hTypes.h"
extern "C" {
# include "lua.h"
# include "lualib.h"
# include "lauxlib.h"
}
#include "base/hLinkedList.h"
#include "base/hFunctor.h"
namespace Heart
{
#define HEART_LUA_GET_ENGINE(L) \
hHeartEngine* engine = (hHeartEngine*)lua_topointer(L, lua_upvalueindex(1)); \
if (!engine) luaL_error(L, "Unable to grab engine pointer" ); \
class hIFileSystem;
class hEntity;
class hComponent;
class hLuaScriptComponent;
typedef hFunctor< hBool (*)( lua_State* ) >::type VMYieldCallback;
typedef hFunctor< void (*)( lua_State* ) >::type VMResumeCallback;
struct hLuaThreadState : hLinkedListElement< hLuaThreadState >
{
hLuaThreadState()
: lua_(NULL)
, status_(0)
, yieldRet_(0)
{}
lua_State* lua_;
hUint32 status_;
hInt32 yieldRet_;
};
class hLuaStateManager
{
public:
hLuaStateManager();
virtual ~hLuaStateManager();
void Initialise();
void Destroy();
void ExecuteBuffer( const hChar* buff, hUint32 size );
void Update();
void RegisterLuaFunctions( luaL_Reg* );
lua_State* GetMainState() { return mainLuaState_; }
private:
typedef hLinkedList< hLuaThreadState > ThreadList;
hBool RunLuaThread( hLuaThreadState* i );
lua_State* NewLuaState( lua_State* parent );
static void* LuaAlloc( void *ud, void *ptr, size_t osize, size_t nsize );
static int LuaPanic (lua_State* L);
static void LuaHook( lua_State* L, lua_Debug* LD );
lua_State* mainLuaState_;
ThreadList luaThreads_;
};
}
#endif // SQUIRRELWRAPPER_H__ |
darthbinamira/bazel-intellij | cpp/src/com/google/idea/blaze/cpp/BlazeCompilerSettings.java | <filename>cpp/src/com/google/idea/blaze/cpp/BlazeCompilerSettings.java
/*
* Copyright 2016 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.cpp;
import com.google.common.collect.ImmutableList;
import com.google.idea.blaze.base.model.primitives.WorkspaceRoot;
import com.google.idea.sdkcompat.cidr.CompilerInfoCacheAdapter;
import com.google.idea.sdkcompat.cidr.OCCompilerSettingsAdapter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.cidr.lang.OCLanguageKind;
import com.jetbrains.cidr.lang.toolchains.CidrCompilerSwitches;
import com.jetbrains.cidr.lang.toolchains.CidrSwitchBuilder;
import com.jetbrains.cidr.lang.workspace.compiler.OCCompilerKind;
import java.io.File;
import java.util.List;
import javax.annotation.Nullable;
final class BlazeCompilerSettings extends OCCompilerSettingsAdapter {
private final Project project;
@Nullable private final File cCompiler;
@Nullable private final File cppCompiler;
private final CidrCompilerSwitches cCompilerSwitches;
private final CidrCompilerSwitches cppCompilerSwitches;
private final String compilerVersion;
private final CompilerInfoCacheAdapter compilerInfoCache;
BlazeCompilerSettings(
Project project,
@Nullable File cCompiler,
@Nullable File cppCompiler,
ImmutableList<String> cFlags,
ImmutableList<String> cppFlags,
String compilerVersion,
CompilerInfoCacheAdapter compilerInfoCache) {
this.project = project;
this.cCompiler = cCompiler;
this.cppCompiler = cppCompiler;
this.cCompilerSwitches = getCompilerSwitches(cFlags);
this.cppCompilerSwitches = getCompilerSwitches(cppFlags);
this.compilerVersion = compilerVersion;
this.compilerInfoCache = compilerInfoCache;
}
@Override
public OCCompilerKind getCompiler(OCLanguageKind languageKind) {
if (languageKind == OCLanguageKind.C || languageKind == OCLanguageKind.CPP) {
return OCCompilerKind.CLANG;
}
return OCCompilerKind.UNKNOWN;
}
@Override
public File getCompilerExecutable(OCLanguageKind lang) {
if (lang == OCLanguageKind.C) {
return cCompiler;
} else if (lang == OCLanguageKind.CPP) {
return cppCompiler;
}
// We don't support objective c/c++.
return null;
}
@Override
public File getCompilerWorkingDir() {
return WorkspaceRoot.fromProject(project).directory();
}
@Override
public CidrCompilerSwitches getCompilerSwitches(
OCLanguageKind lang, @Nullable VirtualFile sourceFile) {
if (lang == OCLanguageKind.C) {
return cCompilerSwitches;
}
if (lang == OCLanguageKind.CPP) {
return cppCompilerSwitches;
}
return new CidrSwitchBuilder().build();
}
private static CidrCompilerSwitches getCompilerSwitches(List<String> allCompilerFlags) {
return new CidrSwitchBuilder().addAllRaw(allCompilerFlags).build();
}
String getCompilerVersion() {
return compilerVersion;
}
@Override
public Project getProject() {
return project;
}
@Override
public CompilerInfoCacheAdapter getCompilerInfo() {
return compilerInfoCache;
}
@Override
public String getCompilerKeyString(
OCLanguageKind ocLanguageKind, @Nullable VirtualFile virtualFile) {
return getCompiler(ocLanguageKind) + "-" + ocLanguageKind;
}
}
|
fieldenms/ | platform-pojo-bl/src/main/java/ua/com/fielden/platform/basic/IPropertyEnum.java | package ua.com.fielden.platform.basic;
/**
* this interface must implement each enumeration class in order to represent the property with the radio buttons those must have tool tips and text. If one want's to specified
* some text for the radio button then toString method must be overridden
*
* @author oleh
*
*/
public interface IPropertyEnum {
/**
* returns the tool tip text for the choice
*
* @return
*/
String getTooltip();
/**
* Returns the Title for the choice.
*
* @return
*/
String getTitle();
}
|
JeffreyRiggle/budgapp | test/models/category.js | class Category {
constructor(client, name) {
this.client = client;
this.name = name;
}
async findCategory() {
const categoryContainer = await this.client.$('.existing-categories')
const categories = await categoryContainer.$$('.category');
for (let category of categories) {
const content = await category.$('.name');
const contextText = await content.getText();
if (contextText === this.name) {
return category;
}
}
}
async setAmount(amount) {
const category = await this.findCategory();
const amountInput = await category.$('input[type="text"]');
await amountInput.setValue(amount);
return this;
}
async toggleRollover() {
const category = await this.findCategory();
const rolloverInput = await category.$('input[type="checkbox"]');
await rolloverInput.click();
return this;
}
async getAmount() {
const category = await this.findCategory();
const amountInput = await category.$('input[type="text"]');
return await amountInput.getValue();
}
}
module.exports = {
Category
};
|
vishnuk007/service-fabric | src/prod/src/data/interop/ReliableCollectionRuntimeImpl/ConfigurationPackageChangeHandler.cpp | <reponame>vishnuk007/service-fabric
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace Data;
using namespace Data::Interop;
HRESULT ConfigurationPackageChangeHandler::Create(
__in Utilities::PartitionedReplicaId const & traceType,
__in IFabricStatefulServicePartition* statefulServicePartition,
__in IFabricPrimaryReplicator* fabricPrimaryReplicator,
__in wstring const & configPackageName,
__in wstring const & replicatorSettingsSectionName,
__in wstring const & replicatorSecuritySectionName,
__in KAllocator & allocator,
__out ComPointer<IFabricConfigurationPackageChangeHandler>& result)
{
ConfigurationPackageChangeHandler * pointer = _new(RELIABLECOLLECTIONRUNTIME_TAG, allocator) ConfigurationPackageChangeHandler(
traceType,
statefulServicePartition,
fabricPrimaryReplicator,
configPackageName,
replicatorSettingsSectionName,
replicatorSecuritySectionName);
if (!pointer)
{
RCREventSource::Events->ExceptionError(
traceType.TracePartitionId,
traceType.ReplicaId,
L"Failed to Create ConfigurationPackageChangeHandler due to insufficient memory in ConfigurationPackageChangeHandler::Create",
E_OUTOFMEMORY);
return E_OUTOFMEMORY;
}
result.SetAndAddRef(pointer);
return S_OK;
}
void ConfigurationPackageChangeHandler::OnPackageAdded(
__in IFabricCodePackageActivationContext *source,
__in IFabricConfigurationPackage *configPackage)
{
UNREFERENCED_PARAMETER(source);
HRESULT hr;
Common::ScopedHeap heap;
FABRIC_REPLICATOR_SETTINGS const * fabricReplicatorSettings = nullptr;
ReplicatorConfigSettingsResult configSettingsResult;
const FABRIC_CONFIGURATION_PACKAGE_DESCRIPTION * packageDescription = configPackage->get_Description();
ASSERT_IF(NULL == packageDescription, "Unexpected configuration package description");
RCREventSource::Events->ConfigurationPackageChangeHandlerEvent(
TracePartitionId,
ReplicaId,
configPackageName_,
packageDescription->Name);
if (!Common::StringUtility::AreEqualCaseInsensitive(configPackageName_, packageDescription->Name))
{
// this config package does not contain replicator settings
return;
}
IFabricTransactionalReplicator* fabricTransactionalReplicator = dynamic_cast<IFabricTransactionalReplicator*>(fabricPrimaryReplicator_.GetRawPointer());
if (fabricTransactionalReplicator == nullptr)
{
RCREventSource::Events->ExceptionError(
TracePartitionId,
ReplicaId,
L"ConfigurationPackageChangeHandler: Dynamic cast to IFabricTransactionalReplicator failed",
STATUS_OBJECT_TYPE_MISMATCH);
statefulServicePartition_->ReportFault(FABRIC_FAULT_TYPE_TRANSIENT);
return;
}
hr = LoadReplicatorSettingsFromConfigPackage(
*PartitionedReplicaIdentifier,
heap,
configSettingsResult,
configPackageName_,
replicatorSettingsSectionName_,
replicatorSecuritySectionName_,
&fabricReplicatorSettings,
nullptr,
nullptr);
if (FAILED(hr))
{
RCREventSource::Events->ConfigPackageLoadFailed(TracePartitionId, ReplicaId, configPackageName_, replicatorSettingsSectionName_, replicatorSecuritySectionName_, hr);
statefulServicePartition_->ReportFault(FABRIC_FAULT_TYPE_TRANSIENT);
return;
}
hr = fabricTransactionalReplicator->UpdateReplicatorSettings(fabricReplicatorSettings);
if (FAILED(hr))
{
RCREventSource::Events->ExceptionError(
TracePartitionId,
ReplicaId,
L"ConfigurationPackageChangeHandler: UpdateReplicatorSettings failed",
hr);
statefulServicePartition_->ReportFault(FABRIC_FAULT_TYPE_TRANSIENT);
return;
}
}
void ConfigurationPackageChangeHandler::OnPackageRemoved(
__in IFabricCodePackageActivationContext *source,
__in IFabricConfigurationPackage *configPackage)
{
UNREFERENCED_PARAMETER(source);
UNREFERENCED_PARAMETER(configPackage);
}
void ConfigurationPackageChangeHandler::OnPackageModified(
__in IFabricCodePackageActivationContext *source,
__in IFabricConfigurationPackage *previousConfigPackage,
__in IFabricConfigurationPackage *configPackage)
{
UNREFERENCED_PARAMETER(previousConfigPackage);
OnPackageAdded(source, configPackage);
}
ConfigurationPackageChangeHandler::ConfigurationPackageChangeHandler(
__in Utilities::PartitionedReplicaId const & partitionedReplicaId,
__in IFabricStatefulServicePartition* statefulServicePartition,
__in IFabricPrimaryReplicator* fabricPrimaryReplicator,
__in wstring const & configPackageName,
__in wstring const & replicatorSettingsSectionName,
__in wstring const & replicatorSecuritySectionName)
: KObject()
, KShared()
, PartitionedReplicaTraceComponent(partitionedReplicaId)
, configPackageName_(configPackageName)
, replicatorSettingsSectionName_(replicatorSettingsSectionName)
, replicatorSecuritySectionName_(replicatorSecuritySectionName)
{
RCREventSource::Events->ConfigurationPackageChangeHandlerCtor(
TracePartitionId,
ReplicaId,
reinterpret_cast<uintptr_t>(fabricPrimaryReplicator),
configPackageName,
replicatorSettingsSectionName,
replicatorSecuritySectionName);
fabricPrimaryReplicator_.SetAndAddRef(fabricPrimaryReplicator);
statefulServicePartition_.SetAndAddRef(statefulServicePartition);
}
ConfigurationPackageChangeHandler::~ConfigurationPackageChangeHandler()
{
}
|
joshualucas84/jasper-soft-server | jasperserver/jasperserver-war/src/main/webapp/optimized-scripts/core.edition.js | <reponame>joshualucas84/jasper-soft-server<filename>jasperserver/jasperserver-war/src/main/webapp/optimized-scripts/core.edition.js<gh_stars>1-10
function isProVersion(){return"PRO"==js_edition}var js_edition="OS"; |
vishwaphansal/MERN | 02-express-tutorial/final/11-methods.js | <reponame>vishwaphansal/MERN<filename>02-express-tutorial/final/11-methods.js
const express = require('express')
const app = express()
let { people } = require('./data')
// static assets
app.use(express.static('./methods-public'))
// parse form data
app.use(express.urlencoded({ extended: false }))
// parse json
app.use(express.json())
app.get('/api/people', (req, res) => {
res.status(200).json({ success: true, data: people })
})
app.post('/api/people', (req, res) => {
const { name } = req.body
if (!name) {
return res
.status(400)
.json({ success: false, msg: 'please provide name value' })
}
res.status(201).json({ success: true, person: name })
})
app.post('/api/postman/people', (req, res) => {
const { name } = req.body
if (!name) {
return res
.status(400)
.json({ success: false, msg: 'please provide name value' })
}
res.status(201).json({ success: true, data: [...people, name] })
})
app.post('/login', (req, res) => {
const { name } = req.body
if (name) {
return res.status(200).send(`Welcome ${name}`)
}
res.status(401).send('Please Provide Credentials')
})
app.put('/api/people/:id', (req, res) => {
const { id } = req.params
const { name } = req.body
const person = people.find((person) => person.id === Number(id))
if (!person) {
return res
.status(404)
.json({ success: false, msg: `no person with id ${id}` })
}
const newPeople = people.map((person) => {
if (person.id === Number(id)) {
person.name = name
}
return person
})
res.status(200).json({ success: true, data: newPeople })
})
app.delete('/api/people/:id', (req, res) => {
const person = people.find((person) => person.id === Number(req.params.id))
if (!person) {
return res
.status(404)
.json({ success: false, msg: `no person with id ${req.params.id}` })
}
const newPeople = people.filter(
(person) => person.id !== Number(req.params.id)
)
return res.status(200).json({ success: true, data: newPeople })
})
app.listen(5000, () => {
console.log('Server is listening on port 5000....')
})
|
ValentineLebedeva/fizteh-java-2014 | src/ru/fizteh/fivt/students/artem_gritsay/MultiFile/MultiWrite.java | package ru.fizteh.fivt.students.artem_gritsay.MultiFile;
import java.io.IOException;
import java.util.HashMap;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class MultiWrite {
private String fileMapPath;
public MultiWrite(String path) {
fileMapPath = path;
}
public void writeDataToFile(HashMap<String, String> fileMap) throws IOException {
DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(fileMapPath));
for (HashMap.Entry<String, String> entry : fileMap.entrySet()) {
writeWord(dataOutputStream, entry.getKey());
writeWord(dataOutputStream, entry.getValue());
}
}
private void writeWord(DataOutputStream dataOutputStream, String word) throws IOException {
byte[] byteWord = word.getBytes("UTF-8");
dataOutputStream.writeInt(byteWord.length);
dataOutputStream.write(byteWord);
}
}
|
danboyle8637/fww | src/components/Website/WhatWeDo/TextMessageSection/LeadSection.js | <filename>src/components/Website/WhatWeDo/TextMessageSection/LeadSection.js
import React from "react";
import styled from "styled-components";
import {
SectionContainer,
ContentContainer,
} from "../../../../styles/Containers";
import TextMessageSection from "./TextMessageSection";
import Headline3 from "./Headline3";
import Headline1 from "./Headline1";
import Headline2 from "./Headline2";
import FWWLogo from "../../../../svgs/FWWLogo";
import IphoneX from "../../../../svgs/IphoneX";
import { above } from "../../../../styles/Theme";
const LeadSection = () => {
return (
<SectionContainer>
<ContentContainer>
<div id="what-we-do-lead" />
<Headline3 />
</ContentContainer>
<TextMessageContainer>
<TextMessageSection />
<IPhoneBackground color="#101010" />
</TextMessageContainer>
<ContentContainer>
<Headline1 />
<Logo />
<Headline2 />
</ContentContainer>
</SectionContainer>
);
};
export default LeadSection;
const TextMessageContainer = styled.div`
padding: 0 1rem;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
width: 100%;
max-width: 34rem;
${above.mobile`
margin: 40px 0 0 0;
`}
`;
const Logo = styled(FWWLogo)`
margin: 80px 0;
width: 180px;
align-self: center;
`;
const IPhoneBackground = styled(IphoneX)`
grid-column: 1 / -1;
grid-row: 1 / -1;
align-self: center;
${above.mobile`
width: 70%;
justify-self: center;
`}
`;
|
alipay/antchain-openapi-prod-sdk | shuziwuliu/java/src/main/java/com/antgroup/antchain/openapi/shuziwuliu/models/UploadShippingEblRequest.java | <filename>shuziwuliu/java/src/main/java/com/antgroup/antchain/openapi/shuziwuliu/models/UploadShippingEblRequest.java<gh_stars>1-10
// This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.shuziwuliu.models;
import com.aliyun.tea.*;
public class UploadShippingEblRequest extends TeaModel {
// OAuth模式下的授权token
@NameInMap("auth_token")
public String authToken;
@NameInMap("product_instance_id")
public String productInstanceId;
// 船公司名称
@NameInMap("carrier_name")
@Validation(required = true)
public String carrierName;
// 收货人did
@NameInMap("consignee_did")
@Validation(required = true)
public String consigneeDid;
// 电子提单类型
@NameInMap("ebl_category")
@Validation(required = true)
public String eblCategory;
// 电子提单copy文件hash
@NameInMap("ebl_copy_pdf_file_hash")
@Validation(required = true)
public String eblCopyPdfFileHash;
// copy电子提单pdf文件id
@NameInMap("ebl_copy_pdf_file_id")
@Validation(required = true)
public String eblCopyPdfFileId;
// 电子提单编号
@NameInMap("ebl_no")
@Validation(required = true)
public String eblNo;
// 电子甜的原文件hash
@NameInMap("ebl_original_pdf_file_hash")
public String eblOriginalPdfFileHash;
// 原电子提单pdf文件id
@NameInMap("ebl_original_pdf_file_id")
public String eblOriginalPdfFileId;
// 议付行did
@NameInMap("negotiating_bank_did")
@Validation(required = true)
public String negotiatingBankDid;
// 托运人did
@NameInMap("shipper_did")
@Validation(required = true)
public String shipperDid;
public static UploadShippingEblRequest build(java.util.Map<String, ?> map) throws Exception {
UploadShippingEblRequest self = new UploadShippingEblRequest();
return TeaModel.build(map, self);
}
public UploadShippingEblRequest setAuthToken(String authToken) {
this.authToken = authToken;
return this;
}
public String getAuthToken() {
return this.authToken;
}
public UploadShippingEblRequest setProductInstanceId(String productInstanceId) {
this.productInstanceId = productInstanceId;
return this;
}
public String getProductInstanceId() {
return this.productInstanceId;
}
public UploadShippingEblRequest setCarrierName(String carrierName) {
this.carrierName = carrierName;
return this;
}
public String getCarrierName() {
return this.carrierName;
}
public UploadShippingEblRequest setConsigneeDid(String consigneeDid) {
this.consigneeDid = consigneeDid;
return this;
}
public String getConsigneeDid() {
return this.consigneeDid;
}
public UploadShippingEblRequest setEblCategory(String eblCategory) {
this.eblCategory = eblCategory;
return this;
}
public String getEblCategory() {
return this.eblCategory;
}
public UploadShippingEblRequest setEblCopyPdfFileHash(String eblCopyPdfFileHash) {
this.eblCopyPdfFileHash = eblCopyPdfFileHash;
return this;
}
public String getEblCopyPdfFileHash() {
return this.eblCopyPdfFileHash;
}
public UploadShippingEblRequest setEblCopyPdfFileId(String eblCopyPdfFileId) {
this.eblCopyPdfFileId = eblCopyPdfFileId;
return this;
}
public String getEblCopyPdfFileId() {
return this.eblCopyPdfFileId;
}
public UploadShippingEblRequest setEblNo(String eblNo) {
this.eblNo = eblNo;
return this;
}
public String getEblNo() {
return this.eblNo;
}
public UploadShippingEblRequest setEblOriginalPdfFileHash(String eblOriginalPdfFileHash) {
this.eblOriginalPdfFileHash = eblOriginalPdfFileHash;
return this;
}
public String getEblOriginalPdfFileHash() {
return this.eblOriginalPdfFileHash;
}
public UploadShippingEblRequest setEblOriginalPdfFileId(String eblOriginalPdfFileId) {
this.eblOriginalPdfFileId = eblOriginalPdfFileId;
return this;
}
public String getEblOriginalPdfFileId() {
return this.eblOriginalPdfFileId;
}
public UploadShippingEblRequest setNegotiatingBankDid(String negotiatingBankDid) {
this.negotiatingBankDid = negotiatingBankDid;
return this;
}
public String getNegotiatingBankDid() {
return this.negotiatingBankDid;
}
public UploadShippingEblRequest setShipperDid(String shipperDid) {
this.shipperDid = shipperDid;
return this;
}
public String getShipperDid() {
return this.shipperDid;
}
}
|
timboudreau/ANTLR4-Plugins-for-NetBeans | antlr-language-spi/src/main/java/org/nemesis/antlr/spi/language/EmbeddingHelper.java | /*
* Copyright 2020 Mastfrog Technologies.
*
* 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.nemesis.antlr.spi.language;
import org.netbeans.api.lexer.InputAttributes;
import org.netbeans.api.lexer.LanguagePath;
import org.netbeans.api.lexer.Token;
import org.netbeans.api.lexer.TokenId;
import org.netbeans.spi.lexer.LanguageHierarchy;
/**
*
* @author <NAME>
*/
public interface EmbeddingHelper {
<T extends TokenId> String mimeTypeForEmbedding( LanguageHierarchy<T> languageHierarchy, Token<T> token,
LanguagePath languagePath, InputAttributes inputAttributes );
}
|
ablack3/WebAPI | src/test/java/org/ohdsi/webapi/tagging/CohortTaggingTest.java | <filename>src/test/java/org/ohdsi/webapi/tagging/CohortTaggingTest.java
package org.ohdsi.webapi.tagging;
import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository;
import org.ohdsi.webapi.cohortdefinition.dto.CohortDTO;
import org.ohdsi.webapi.cohortdefinition.dto.CohortRawDTO;
import org.ohdsi.webapi.service.CohortDefinitionService;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
public class CohortTaggingTest extends BaseTaggingTest<CohortDTO, Integer> {
private static final String JSON_PATH = "/tagging/cohort.json";
@Autowired
private CohortDefinitionService service;
@Autowired
private CohortDefinitionRepository repository;
@Override
public void doCreateInitialData() throws IOException {
String expression = getExpression(getExpressionPath());
CohortDTO dto = deserializeExpression(expression);
initialDTO = service.createCohortDefinition(dto);
}
private CohortDTO deserializeExpression(String expression) {
CohortRawDTO rawDTO = new CohortRawDTO();
rawDTO.setExpression(expression);
CohortDTO dto = conversionService.convert(rawDTO, CohortDTO.class);
dto.setName("test dto name");
dto.setDescription("test dto description");
return dto;
}
@Override
protected void doClear() {
repository.deleteAll();
}
@Override
protected String getExpressionPath() {
return JSON_PATH;
}
@Override
protected void assignTag(Integer id, boolean isPermissionProtected) {
service.assignTag(id, getTag(isPermissionProtected).getId());
}
@Override
protected void unassignTag(Integer id, boolean isPermissionProtected) {
service.unassignTag(id, getTag(isPermissionProtected).getId());
}
@Override
protected void assignProtectedTag(Integer id, boolean isPermissionProtected) {
service.assignPermissionProtectedTag(id, getTag(isPermissionProtected).getId());
}
@Override
protected void unassignProtectedTag(Integer id, boolean isPermissionProtected) {
service.unassignPermissionProtectedTag(id, getTag(isPermissionProtected).getId());
}
@Override
protected CohortDTO getDTO(Integer id) {
return service.getCohortDefinition(id);
}
@Override
protected Integer getId(CohortDTO dto) {
return dto.getId();
}
}
|
kopok2/algorithms | Math/TowerOfHanoi.py | # coding=utf-8
"""Tower of Hanoi algorithm Python implementation."""
def th(n, f, t, a):
if n == 1:
print("Move disk 1 from {0} to {1}".format(f, t))
else:
th(n - 1, f, a, t)
print("Move disk {0} from {1} to {2}".format(n, f, t))
th(n - 1, a, t, f)
if __name__ == '__main__':
n = 2
th(n, "A", "B", "C")
|
BossaNova/cantaloupe | src/main/java/kdu_jni/Jpx_composition.java | package kdu_jni;
public class Jpx_composition {
static {
System.loadLibrary("kdu_jni");
Native_init_class();
}
private static native void Native_init_class();
protected long _native_ptr = 0;
protected Jpx_composition(long ptr) {
_native_ptr = ptr;
}
public Jpx_composition() {
this(0);
}
public native boolean Exists() throws KduException;
public native void Copy(Jpx_composition _src) throws KduException;
public native int Get_global_info(Kdu_coords _size) throws KduException;
public native long Get_track_idx() throws KduException;
public native long Get_timescale() throws KduException;
public native boolean Count_tracks(long[] _count, boolean _global_only) throws KduException;
public boolean Count_tracks(long[] _count) throws KduException
{
return Count_tracks(_count,(boolean) false);
}
public native boolean Count_track_frames(long _track_idx, int[] _count) throws KduException;
public native boolean Count_track_time(long _track_idx, long[] _count) throws KduException;
public native boolean Count_track_frames_before_time(long _track_idx, long _max_end_time, int[] _count) throws KduException;
public native Jpx_frame Access_frame(long _track_idx, int _frame_idx, boolean _must_exist, boolean _include_persistents) throws KduException;
public Jpx_frame Access_frame(long _track_idx, int _frame_idx, boolean _must_exist) throws KduException
{
return Access_frame(_track_idx,_frame_idx,_must_exist,(boolean) true);
}
public native int Find_layer_match(Jpx_frame _frame, int[] _inst_idx, long _track_idx, int[] _layers, int _num_layers, int _container_id, boolean _include_persistents, int _flags) throws KduException;
public int Find_layer_match(Jpx_frame _frame, int[] _inst_idx, long _track_idx, int[] _layers, int _num_layers) throws KduException
{
return Find_layer_match(_frame,_inst_idx,_track_idx,_layers,_num_layers,(int) -1,(boolean) true,(int) 0);
}
public int Find_layer_match(Jpx_frame _frame, int[] _inst_idx, long _track_idx, int[] _layers, int _num_layers, int _container_id) throws KduException
{
return Find_layer_match(_frame,_inst_idx,_track_idx,_layers,_num_layers,_container_id,(boolean) true,(int) 0);
}
public int Find_layer_match(Jpx_frame _frame, int[] _inst_idx, long _track_idx, int[] _layers, int _num_layers, int _container_id, boolean _include_persistents) throws KduException
{
return Find_layer_match(_frame,_inst_idx,_track_idx,_layers,_num_layers,_container_id,_include_persistents,(int) 0);
}
public native int Find_numlist_match(Jpx_frame _frame, int[] _inst_idx, long _track_idx, Jpx_metanode _numlist, int _max_inferred_layers, boolean _include_persistents, int _flags) throws KduException;
public int Find_numlist_match(Jpx_frame _frame, int[] _inst_idx, long _track_idx, Jpx_metanode _numlist) throws KduException
{
return Find_numlist_match(_frame,_inst_idx,_track_idx,_numlist,(int) 0,(boolean) true,(int) 0);
}
public int Find_numlist_match(Jpx_frame _frame, int[] _inst_idx, long _track_idx, Jpx_metanode _numlist, int _max_inferred_layers) throws KduException
{
return Find_numlist_match(_frame,_inst_idx,_track_idx,_numlist,_max_inferred_layers,(boolean) true,(int) 0);
}
public int Find_numlist_match(Jpx_frame _frame, int[] _inst_idx, long _track_idx, Jpx_metanode _numlist, int _max_inferred_layers, boolean _include_persistents) throws KduException
{
return Find_numlist_match(_frame,_inst_idx,_track_idx,_numlist,_max_inferred_layers,_include_persistents,(int) 0);
}
public native long Get_next_frame(long _last_frame) throws KduException;
public native long Get_prev_frame(long _last_frame) throws KduException;
public native Jpx_composition Access_owner(long _frame_ref) throws KduException;
public native Jpx_frame Get_interface_for_frame(long _frame, int _iteration_idx, boolean _include_persistents) throws KduException;
public Jpx_frame Get_interface_for_frame(long _frame, int _iteration_idx) throws KduException
{
return Get_interface_for_frame(_frame,_iteration_idx,(boolean) true);
}
public native void Get_frame_info(long _frame_ref, int[] _num_instructions, int[] _duration, int[] _repeat_count, boolean[] _is_persistent) throws KduException;
public native long Get_last_persistent_frame(long _frame_ref) throws KduException;
public native boolean Get_instruction(long _frame_ref, int _instruction_idx, int[] _rel_layer_idx, int[] _rel_increment, boolean[] _is_reused, Kdu_dims _source_dims, Kdu_dims _target_dims, Jpx_composited_orientation _orientation) throws KduException;
public native boolean Get_original_iset(long _frame_ref, int _instruction_idx, int[] _iset_idx, int[] _inum_idx) throws KduException;
public native int Map_rel_layer_idx(int _rel_layer_idx) throws KduException;
public native long Add_frame(int _duration, int _repeat_count, boolean _is_persistent) throws KduException;
public native int Add_instruction(long _frame_ref, int _rel_layer_idx, int _rel_increment, Kdu_dims _source_dims, Kdu_dims _target_dims, Jpx_composited_orientation _orient) throws KduException;
public native void Set_loop_count(int _count) throws KduException;
}
|
collinkleest/lrnwebcomponents | elements/progress-donut/propgress-donut-stories.js | <reponame>collinkleest/lrnwebcomponents<filename>elements/progress-donut/propgress-donut-stories.js
import { html } from "lit-element/lit-element.js";
import { ProgressDonut } from "@lrnwebcomponents/progress-donut/progress-donut.js";
import { withKnobs, withWebComponentsKnobs } from "@open-wc/demoing-storybook";
import { StorybookUtilities } from "@lrnwebcomponents/storybook-utilities/storybook-utilities.js";
export default {
title: "Charts|Progress Donut",
component: "progress-donut",
decorators: [withKnobs, withWebComponentsKnobs],
parameters: {
options: { selectedPanel: "storybookjs/knobs/panel" },
},
};
const utils = new StorybookUtilities();
export const ProgressDonutStory = () => {
return utils.makeElementFromClass(
ProgressDonut,
{
accentColor: utils.randomColor(),
animation: 500,
animationDelay: 500,
desc:
"You have completed 5,4,8,12,6,3,4, and 3 points of work out of 50 points.",
complete: [5, 4, 8, 12, 6, 3, 4, 3],
imageSrc: new URL(`./demo/images/profile1.jpg`, import.meta.url),
width: "300px",
total: 50,
},
[{ css: "width" }, { css: "maxWidth" }]
);
};
|
Taritsyn/ChakraCore | lib/Runtime/Library/JavascriptRegExpConstructor.h | <filename>lib/Runtime/Library/JavascriptRegExpConstructor.h<gh_stars>1000+
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
namespace Js
{
class JavascriptRegExpConstructor : public RuntimeFunction
{
friend class RegexHelper;
private:
static PropertyId const specialPropertyIds[];
static PropertyId const specialnonEnumPropertyIds[];
static PropertyId const specialEnumPropertyIds[];
static const int NumCtorCaptures = 10;
DEFINE_MARSHAL_OBJECT_TO_SCRIPT_CONTEXT(JavascriptRegExpConstructor);
protected:
//To prevent lastMatch from being cleared from cross-site marshalling
DEFINE_VTABLE_CTOR_MEMBER_INIT(JavascriptRegExpConstructor, RuntimeFunction, lastMatch);
public:
JavascriptRegExpConstructor(DynamicType* type, ConstructorCache* cache);
virtual PropertyQueryFlags HasPropertyQuery(PropertyId propertyId, _Inout_opt_ PropertyValueInfo* info) override;
virtual PropertyQueryFlags GetPropertyQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext) override;
virtual PropertyQueryFlags GetPropertyQuery(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext) override;
virtual PropertyQueryFlags GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext) override;
virtual BOOL SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info) override;
virtual BOOL SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info) override;
virtual BOOL InitProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags = PropertyOperation_None, PropertyValueInfo* info = NULL) override;
virtual BOOL DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags) override;
virtual BOOL DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags) override;
virtual BOOL GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext) override;
virtual BOOL GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext) override;
virtual BOOL IsEnumerable(PropertyId propertyId) override;
virtual BOOL IsConfigurable(PropertyId propertyId) override;
virtual BOOL GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, EnumeratorCache * enumeratorCache = nullptr) override;
BOOL GetSpecialNonEnumerablePropertyName(uint32 index, Var *propertyName, ScriptContext * requestContext);
uint GetSpecialNonEnumerablePropertyCount() const;
PropertyId const * GetSpecialNonEnumerablePropertyIds() const;
BOOL GetSpecialEnumerablePropertyName(uint32 index, JavascriptString ** propertyName, ScriptContext * requestContext);
uint GetSpecialEnumerablePropertyCount() const;
PropertyId const * GetSpecialEnumerablePropertyIds() const;
virtual BOOL GetSpecialPropertyName(uint32 index, JavascriptString ** propertyName, ScriptContext * requestContext) override;
virtual uint GetSpecialPropertyCount() const override;
virtual PropertyId const * GetSpecialPropertyIds() const override;
UnifiedRegex::RegexPattern* GetLastPattern() const { return lastPattern; }
private:
bool GetPropertyBuiltIns(PropertyId propertyId, Var* value, BOOL* result);
bool SetPropertyBuiltIns(PropertyId propertyId, Var value, BOOL* result);
void SetLastMatch(UnifiedRegex::RegexPattern* lastPattern, JavascriptString* lastInput, UnifiedRegex::GroupInfo lastMatch);
void InvalidateLastMatch(UnifiedRegex::RegexPattern* lastPattern, JavascriptString* lastInput);
void EnsureValues();
Field(UnifiedRegex::RegexPattern*) lastPattern;
Field(JavascriptString*) lastInput;
Field(UnifiedRegex::GroupInfo) lastMatch;
Field(bool) invalidatedLastMatch; // true if last match must be recalculated before use
Field(bool) reset; // true if following fields must be recalculated from above before first use
Field(Var) lastParen;
Field(Var) lastIndex;
Field(Var) index;
Field(Var) leftContext;
Field(Var) rightContext;
Field(Var) captures[NumCtorCaptures];
};
class JavascriptRegExpConstructorProperties
{
public:
static bool IsSpecialProperty(PropertyId id)
{
switch (id)
{
case PropertyIds::input:
case PropertyIds::$_:
case PropertyIds::lastMatch:
case PropertyIds::$Ampersand:
case PropertyIds::lastParen:
case PropertyIds::$Plus:
case PropertyIds::leftContext:
case PropertyIds::$BackTick:
case PropertyIds::rightContext:
case PropertyIds::$Tick:
case PropertyIds::$1:
case PropertyIds::$2:
case PropertyIds::$3:
case PropertyIds::$4:
case PropertyIds::$5:
case PropertyIds::$6:
case PropertyIds::$7:
case PropertyIds::$8:
case PropertyIds::$9:
case PropertyIds::index:
return true;
}
return false;
}
};
} // namespace Js
|
genome-vendor/apollo | src/java/apollo/gui/annotinfo/GeneEditPanel.java | <reponame>genome-vendor/apollo
package apollo.gui.annotinfo;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.util.*;
import java.io.IOException;
import junit.framework.TestCase;
import apollo.datamodel.*;
import apollo.editor.AddTransaction;
import apollo.editor.DeleteTransaction;
import apollo.editor.AnnotationCompoundEvent;
import apollo.editor.AnnotationEditor;
import apollo.editor.AnnotationUpdateEvent;
import apollo.editor.ChangeList;
import apollo.editor.CompoundTransaction;
import apollo.editor.Transaction;
import apollo.editor.TransactionSubpart;
import apollo.editor.TransactionUtil;
import apollo.editor.UpdateTransaction;
import apollo.editor.UserName;
import apollo.config.Config;
import apollo.config.FeatureProperty;
import apollo.config.PeptideStatus;
import apollo.gui.event.*;
import apollo.gui.synteny.GuiCurationState;
import apollo.util.SeqFeatureUtil;
import apollo.util.HTMLUtil;
import apollo.util.GuiUtil;
import apollo.dataadapter.chadoxml.ChadoXmlWrite;
import org.apache.log4j.*;
/**
* GeneEditPanel
*
* Panel to layout comments, gene and transcript names, etc
*
* Editing is disabled in browser mode. In browser mode just used
* to view the comments.
*/
public class GeneEditPanel extends FeatureEditPanel {
// -----------------------------------------------------------------------
// Class/static variables
// -----------------------------------------------------------------------
protected final static Logger logger = LogManager.getLogger(GeneEditPanel.class);
/** There is only one row of data, which is 32 high on Linux, but on Mac,
needs more room. */
private static final Dimension tableSize = new Dimension(250,80);
// -----------------------------------------------------------------------
// Instance variables
// -----------------------------------------------------------------------
private TranscriptEditPanel transcriptPanel; // transcript editor
private ReadWriteField featureTypeList;
/** bigCommentField is where all the comments from gene and trans
are displayed, not edited */
JTextArea bigCommentField = new JTextArea(12,3);
// private JLabel peptideStatusLabel = new JLabel();
private ReadWriteField peptideStatus;
JTextArea sequencingComments = new JTextArea();
private JCheckBox isDicistronicCheckbox = new JCheckBox();
// Kludge to deal with problem where selecting a row in the table triggers
// the event TWICE.
private int table_row_selected = -1;
/** Vector of feature properties for type field, not used for readOnly */
private Vector annotFeatureProps;
private DbxRefTableModel dbXRefModel; // dbxref table model
Box dataBox = new Box(BoxLayout.Y_AXIS);
JButton addAnnotComment;
JButton addTransComment;
private Commentator commentator;
private String GO_URL = "http://godatabase.org/cgi-bin/go.cgi?view=details&search_constraint=terms&depth=0&query="; // Should go in style
private boolean warnedAboutEditingIDs = false;
private IDFocusListener idFocusListener; // inner class for id edits
private GeneNameListener geneNameListener; // inner class for name edits
private JTable dbxrefTable;
GeneEditPanel(FeatureEditorDialog featureEditorDialog,
boolean isReadOnly) {
super (featureEditorDialog, isReadOnly);
if (isReadOnly) {
featureTypeList = new ReadWriteField(false);
peptideStatus = new ReadWriteField(false);
}
else {
featureTypeList = new ReadWriteField(true);
peptideStatus = new ReadWriteField(true);
}
/* This is a vector of FeatureProperty (not Strings)
that includes all the valid annotation types */
this.annotFeatureProps = getAnnotationFeatureProps();
jbInit();
attachListeners();
}
protected void jbInit() {
super.jbInit ();
// ids include "DEBUG" to indicate that Apollo is in debug mode
// TODO - introduce a parameter that controls this feature, instead of using global DEBUG (deprecated)w
if (Config.getStyle().showIdField() || Config.DEBUG) {
String dbg = Config.DEBUG && !Config.getStyle().showIdField() ? "(DEBUG)" : "";
addField ("ID"+dbg, featureIDField.getComponent());
}
addSynonymGui();
addIsProblematicCheckbox();
addField("Type",featureTypeList.getComponent());
featureTypeList.setListBackground(bgColor);
loadTypes(); // populate featureTypeList and add listener
if (Config.getStyle().showIsDicistronicCheckbox()) {
addField("Is dicistronic?", isDicistronicCheckbox);
isDicistronicCheckbox.setEnabled(!isReadOnly);
isDicistronicCheckbox.setBackground(bgColor);
isDicistronicCheckbox.addActionListener(new DicistronicButtonListener());
}
if (Config.getStyle().showEvalOfPeptide()) {
addField("Evaluation of peptide", peptideStatus.getComponent());
peptideStatus.setListBackground(bgColor);
}
// pad out bottom of fields panel, for layout - otherwise syns will consume
super.addFieldsPanelBottomGlue();
// a box for all the gene fields and the dbxref table
Box dataBox = new Box(BoxLayout.Y_AXIS);
dataBox.add(fieldsPanel);
dataBox.add(Box.createVerticalStrut(5));
if (showDbXRefs()) {
JPanel dbxrefPanel = new JPanel();
dbxrefPanel.setBackground(bgColor);
dbxrefPanel.add(getDbTablePane());
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
buttonPanel.setBackground(bgColor);
final JButton newDbxref = new JButton("add");
//final JButton editDbxref = new JButton("edit");
final JButton deleteDbxref = new JButton("delete");
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
JFrame parentFrame = (JFrame)SwingUtilities.getAncestorOfClass(JFrame.class, GeneEditPanel.this);
if (ae.getSource() == newDbxref) {
DbXref dbxref = new DbXref("id", "", "");
new DbxrefDialog(parentFrame, "Add DbXref", dbxref);
dbXRefModel.addDbxRef(dbxref);
}
/*
else if (ae.getSource() == editDbxref) {
int idx = dbxrefTable.getSelectedRow();
if (idx >= 0) {
DbXref newDbxref = dbXRefModel.getDbxrefAt(idx);
DbXref oldDbxref = new DbXref(newDbxref);
new DbxrefDialog(parentFrame,
"Edit DbXref", newDbxref);
dbXRefModel.updateDbxRef(oldDbxref, newDbxref);
}
}
*/
else if (ae.getSource() == deleteDbxref) {
int idx = dbxrefTable.getSelectedRow();
if (idx >= 0) {
DbXref dbxref = dbXRefModel.getDbxrefAt(idx);
dbXRefModel.deleteDbxRef(dbxref);
}
}
}
};
newDbxref.addActionListener(al);
//editDbxref.addActionListener(al);
deleteDbxref.addActionListener(al);
setupSynButton(newDbxref);
//setupSynButton(editDbxref);
setupSynButton(deleteDbxref);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(newDbxref, c);
//c.gridy = 1;
//buttonPanel.add(editDbxref, c);
c.gridy = 2;
buttonPanel.add(deleteDbxref, c);
dbxrefPanel.add(buttonPanel);
/*
c.fill = GridBagConstraints.HORIZONTAL;
c.gridheight = 1;
c.gridx = 1;
dbxrefPanel.add(newDbxref, c);
c.gridy = 1;
dbxrefPanel.add(editDbxref, c);
c.gridy = 2;
//dbxrefPanel.add(deleteDbxref, c);
*/
dataBox.add(dbxrefPanel);
}
Box topBox = new Box(BoxLayout.X_AXIS);
topBox.add(dataBox);
topBox.add(Box.createHorizontalStrut(12));
transcriptPanel = new TranscriptEditPanel(featureEditorDialog, isReadOnly);
topBox.add(transcriptPanel);
Box bottomBox = getCommentBox();
featureBox.add(topBox);
// Add some space between data panel and big comment field
featureBox.add(Box.createVerticalStrut(12));
featureBox.add(bottomBox);
border = new TitledBorder("Annotation");
border.setTitleColor (Color.black);
featureBox.setBorder(border);
}
private boolean showDbXRefs() {
return Config.getStyle().showDbXRefTable();
}
private class DicistronicButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
boolean b = isDicistronicCheckbox.isSelected();
setBooleanSubpart(b,TransactionSubpart.IS_DICISTRONIC);
}
}
private JScrollPane getDbTablePane() {
dbXRefModel = new DbxRefTableModel();
/* table needs to be declared final so it can be accessed
from inside ListSelectionListener */
dbxrefTable = new JTable(dbXRefModel);
dbxrefTable.getTableHeader().setReorderingAllowed(false);
dbxrefTable.getColumnModel().getColumn(0).setHeaderValue("ID Value");
dbxrefTable.getColumnModel().getColumn(1).setHeaderValue("DB Name");
dbxrefTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
dbxrefTable.getSelectionModel().addListSelectionListener
(new ListSelectionListener() {
/* For some reason, this is triggered TWICE whenever
you select something in the table. */
public void valueChanged(ListSelectionEvent e) {
int row_index = dbxrefTable.getSelectedRow();
/* Don't do anything if the same row is selected twice in a row
(which always happens because for some reason valueChanged
is triggered twice for every selection) */
if (row_index == table_row_selected)
return;
table_row_selected = row_index;
String id = (String) dbXRefModel.getValueAt(row_index, 0);
String dbname = (String) dbXRefModel.getValueAt(row_index, 1);
if (id.startsWith("FBgn") ||
id.startsWith("GO:") ||
id.startsWith("FBti")) {
String url = "";
if (id.startsWith("FB")) {
if (apollo.config.Config.getExternalRefURL()==null)
return;
url = apollo.config.Config.getExternalRefURL() + id;
}
else if (id.startsWith("GO:"))
url = GO_URL + id;
HTMLUtil.loadIntoBrowser(url);
}
else {
logger.warn("Don't know how to pull up info for id " + id + ", db = " + dbname);
}
}
}
);
JScrollPane tableHolder = new JScrollPane(dbxrefTable);
// Need to constrain table or else it takes up too much space
tableHolder.setPreferredSize(GeneEditPanel.tableSize);
tableHolder.setMaximumSize(GeneEditPanel.tableSize);
tableHolder.setBackground(bgColor);
return tableHolder;
}
private Box getCommentBox() {
bigCommentField.setWrapStyleWord(true);
bigCommentField.setLineWrap(true);
bigCommentField.setEditable(false);
JScrollPane bigCommentPane
= new JScrollPane(bigCommentField,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
bigCommentPane.setPreferredSize(new Dimension(450, 300));
Box commentBox = new Box(BoxLayout.X_AXIS);
commentBox.add(Box.createHorizontalStrut(12));
commentBox.add(bigCommentPane);
commentBox.add(Box.createHorizontalStrut(8));
Box buttonBox = new Box(BoxLayout.Y_AXIS);
buttonBox.add(Box.createVerticalStrut(20));
if (!isReadOnly) {
commentator = new Commentator(featureEditorDialog);
commentator.setVisible(false);
addAnnotComment = initCommentButton();
addTransComment = initCommentButton();
buttonBox.add(addAnnotComment);
buttonBox.add(Box.createVerticalStrut(20));
buttonBox.add(addTransComment);
buttonBox.add(Box.createVerticalStrut(20));
}
if (Config.getStyle().seqErrorEditingIsEnabled()) {
sequencingComments.setWrapStyleWord(true);
sequencingComments.setLineWrap(true);
sequencingComments.setEditable(false);
sequencingComments.setPreferredSize(new Dimension(250, 160));
sequencingComments.setBackground(new Color(255, 250, 205));
JScrollPane seqPane
= new JScrollPane(sequencingComments,
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Border border = new TitledBorder("Genomic sequencing errors");
seqPane.setBorder(border);
seqPane.setBackground(bgColor);
seqPane.setPreferredSize(new Dimension(250, 160));
buttonBox.add(seqPane);
}
commentBox.add(buttonBox);
commentBox.add(Box.createHorizontalGlue());
commentBox.setBorder(new TitledBorder("Comments and properties"));
return commentBox;
}
private JButton initCommentButton() {
JButton addComment = new JButton();
addComment.setBackground (Color.white);
Dimension buttonSize = new Dimension(250, 40);
addComment.setMaximumSize(buttonSize);
addComment.setMinimumSize(buttonSize);
addComment.setPreferredSize(buttonSize);
addComment.setText("Edit comments"); // this gets replaced
addComment.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editComments(e);
}
}
);
return addComment;
}
void clearFields() {
super.clearFields();
isDicistronicCheckbox.setSelected(false);
}
protected void disposeCommentator() {
if (!isReadOnly)
commentator.dispose();
}
/** Overrides FeatureEditPanel.loadSelectedFeature */
protected void loadSelectedFeature() {
if (getEditedFeature() == null) {
clearFields();
return;
}
isGoodUser();
setGuiNameFromModel();
getNameField().setEditable(goodUser);
setGuiIDFromModel();
if(idIsEditable())
featureIDField.setEditable(goodUser);
else
featureIDField.setEditable(idIsEditable());
loadSynonymGui();
isProblematicCheckbox.setSelected(getEditedFeature().isProblematic());
isProblematicCheckbox.setEnabled(goodUser);
/* This is to repair any differences that are solely a result
of case differences */
FeatureProperty fp = getFeatureProperty();
featureTypeList.setValue(fp.getDisplayType());
featureTypeList.setEnabled(goodUser);
refreshCommentField(getEditedFeature());
if (getEditedFeature().isProteinCodingGene()) {
StringBuffer buf = new StringBuffer();
HashMap adjustments = getEditedFeature().getGenomicErrors();
if (adjustments != null) {
Iterator positions = adjustments.keySet().iterator();
while (positions.hasNext()) {
String position = (String) positions.next();
SequenceEdit seq_edit = (SequenceEdit) adjustments.get(position);
String more_info = (seq_edit.getResidue() != null ?
" of " + seq_edit.getResidue() : "");
if (seq_edit.getEditType().equals(SequenceI.SUBSTITUTION)) {
// also say what is being replaced
SequenceI refSeq = getEditedFeature().getRefSequence();
if (refSeq != null &&
refSeq.isSequenceAvailable(seq_edit.getPosition())) {
char base = refSeq.getBaseAt(seq_edit.getPosition());
more_info = more_info + " for " + base;
}
}
buf.append(seq_edit.getEditType() + more_info +
" at base " + position + "\n");
}
}
sequencingComments.setText(buf.toString());
sequencingComments.setVisible(true);
}
else
sequencingComments.setVisible(false);
if (showDbXRefs()) {
dbXRefModel.setListData(collectDbXrefs());
}
setPeptideStatus (getEditedFeature());
if (getEditedFeature().isProteinCodingGene()) {
if (getEditedFeature().getProperty("dicistronic").equals("true"))
isDicistronicCheckbox.setSelected(true);
else
isDicistronicCheckbox.setSelected(false);
}
isDicistronicCheckbox.setVisible(getEditedFeature().isProteinCodingGene());
border.setTitle(getEditedFeature().getFeatureType() + " " + getEditedFeature().getName());
loadTranscript();
setWindowTitleWithFeatureName();
updateUI();
}
private FeatureProperty getFeatureProperty() {
return Config.getPropertyScheme().getFeatureProperty(getEditedFeature().getFeatureType());
}
// No longer used, it looks like
// private UpdateTransaction makeUpdateTransaction(TransactionSubpart ts) {
// UpdateTransaction u = new UpdateTransaction(getEditedFeature(),ts);
// u.setSource(getFeatureEditorDialog());
// return u;
// }
// /** Set model name to gui name, return name UpdateTransaction */
// private UpdateTransaction commitGeneNameChange() {
// String guiName = getGuiName();
// String oldName = getEditedFeature().getName();
// UpdateTransaction ut = makeUpdateTransaction(TransactionSubpart.NAME);
// ut.setPreValue(oldName);
// ut.setSubpartValue(guiName);
// ut.editModel();
// return ut;
// }
private CompoundTransaction commitGeneAndTranscriptNameChange() {
if (!nameHasChanged())
return null;
String newName = getGuiName();
logger.debug("GeneEditPanel changing name from "+getModelName()+" to "+getGuiName());
CompoundTransaction ct = getNameAdapter().setAnnotName(getEditedFeature(),newName);
// CompoundTransaction compTrans = new CompoundTransaction();
// // should their ba a nameAdapter.setGeneName that does everything? probably
// compTrans.addTransaction(commitGeneNameChange());
// compTrans.addTransaction(updateTranscriptNames());
ct.setSource(getFeatureEditorDialog());
setWindowTitleWithFeatureName();
//loadSelectedFeature(); // cant do here - screws up id change
//transcriptPanel.loadSelectedFeature();
return ct;
// Would like to reset list of genes as well as window title
// Problem is that we don't really have access to that list to
// stick the new changed gene in there.
// featureEditorDialog.loadGUI(getEditedFeature()); // ?
}
// If annotation name changes, change the transcript names to match.
// private CompoundTransaction updateTranscriptNames() {
// AnnotatedFeatureI annot = getEditedFeature();
// //ChangeList changes = createChangeList();
// CompoundTransaction compTrans = new CompoundTransaction();
// for(int i=0; i < annot.size(); i++) {
// AnnotatedFeatureI trans = annot.getFeatureAt(i).getAnnotatedFeature();
// // Set transcript name based on parent's name
// Transaction t = getNameAdapter().setTranscriptNameFromAnnot(trans, annot);
// compTrans.addTransaction(t);
// }
// // Need to force the Transcript name field in TranscriptPanel to update
// transcriptPanel.loadSelectedFeature();
// //updateFeature(); // i dont think this is needed anymore //return changes;
// return compTrans;
// }
private void setWindowTitleWithFeatureName() {
String title = getEditedFeature().getName() + " Annotation Information";
getFeatureEditorDialog().setTitle(title);
}
private boolean idIsEditable() {
// if the id is not displayed theres no way to edit it
// super user always returns true at this point (see Style.isSuperUser)
return Config.getStyle().showIdField()
&& Config.getStyle().isSuperUser(UserName.getUserName());
}
/** sets id in annot feat from gui, returns update id event (shouldnt this also do
transcript ids? where does that happen? */
//private AnnotationCompoundEvent commitIdChange() {
private CompoundTransaction commitIdChange() {
//AnnotationUpdateEvent aue = makeUpdateEvent(TransactionSubpart.ID);
//aue.setOldString(getEditedFeature().getId());
//aue.setOldId(getEditedFeature().getId());
//getEditedFeature().setId(getGuiId());
// eventually should return a ChangeList
//getNameAdapter().setId(getEditedFeature(),getGuiId());
// fly name adapter sets all transcript ids as well
//// --- TransactionUtil.setId(getEditedFeature(),getGuiId(),getNameAdapter());
CompoundTransaction ct = getNameAdapter().setAnnotId(getEditedFeature(),getGuiId());
ct.setSource(getFeatureEditorDialog());
// TODO - introduce a parameter that controls this feature, instead of using global DEBUG (deprecated)
if (Config.DEBUG) transcriptPanel.loadSelectedFeature(); // debug trans id
//AnnotationCompoundEvent ae = new AnnotationCompoundEvent(ct); //return ae;
return ct;
}
private String getGuiId() { return featureIDField.getValue().trim(); }
private void setGuiIDFromModel() {
setGuiId(getEditedFeature().getId());
}
private void setGuiId(String id) {
featureIDField.setValue(id);
}
// Should we be sorting these in alphabetical order or something?
private Vector collectDbXrefs() {
Vector db_xrefs = new Vector();
db_xrefs.addAll(getEditedFeature().getDbXrefs());
for(int i=0; i < getEditedFeature().size(); i++) {
Transcript t = (Transcript) getEditedFeature().getFeatureAt(i);
db_xrefs.addAll(t.getDbXrefs());
// Chado XML has dbxrefs for peptides--collect these, too.
//SequenceI pep = t.getPeptideSequence();
AnnotatedFeatureI pep = t.getProteinFeat();
if (pep != null)
db_xrefs.addAll(pep.getDbXrefs());
}
return db_xrefs;
}
/** Return true if id has changed */
private boolean idChanged(String new_id, String current_id) {
return (new_id != null &&
!new_id.equals("") &&
!new_id.equals(current_id));
}
/**
* provides a list of valid annotation types (as feature properties)
*/
protected static Vector getAnnotationFeatureProps() {
return Config.getPropertyScheme().getAnnotationFeatureProps();
}
protected FeatureProperty findFeatureProp(String typeName) {
Iterator props = annotFeatureProps.iterator();
FeatureProperty prop = null;
while (props.hasNext()) {
prop = (FeatureProperty)props.next();
String t = prop.getDisplayType();
if (t.equals(typeName))
return prop;
}
return null;
}
// loads typeList (annotation types--gene, tRNA, etc.) into pulldown list
void loadTypes() {
Iterator props = annotFeatureProps.iterator();
int numTypes = 0;
while (props.hasNext()) {
featureTypeList.addItem(((FeatureProperty)props.next()).getDisplayType());
++numTypes;
}
featureTypeList.setMaximumRowCount(numTypes);
// We only want to react to action events AFTER populating the list
if (!isReadOnly) {
FeatureTypeItemListener ftil = new FeatureTypeItemListener();
((JComboBox)featureTypeList.getComponent()).addItemListener(ftil);
}
}
void refreshCommentField() {
refreshCommentField(getEditedFeature());
}
private void refreshCommentField(AnnotatedFeatureI editedFeature) {
// update clone with latest comments
if (!isReadOnly) {
String shortName = apollo.gui.DetailInfo.getName(editedFeature);
addAnnotComment.setText("Edit " + shortName + " comments");
}
bigCommentField.setText(getCommentString(editedFeature));
bigCommentField.setCaretPosition(0);
}
private String getCommentString(AnnotatedFeatureI sf) {
StringBuffer commentList = new StringBuffer();
String desc = sf.getDescription();
if (desc != null && !desc.equals("")) {
commentList.append(sf.getName() + " description:\n");
commentList.append(desc + "\n");
}
Vector comments = sf.getComments();
int cnum = 0;
for(int i=0; i < comments.size(); i++) {
Comment comment = (Comment) comments.elementAt(i);
if ((!comment.isInternal() || apollo.config.Config.internalMode())
&& !comment.getText().equals("")) {
if (++cnum == 1)
commentList.append(sf.getName() + " comments:\n");
commentList.append(" " + (cnum) + ". " +
comment.getText()+"\n");
}
}
// Add desired properties for this annotation and transcripts
commentList.append(showProperties(sf));
// Go through transcripts (but not exons!) in alphabetical order
if (!(sf instanceof Transcript) && sf.canHaveChildren() && sf.size() > 0) {
FeatureSetI fs = (FeatureSetI)sf;
Vector sorted_set
= SeqFeatureUtil.sortFeaturesAlphabetically(fs.getFeatures());
for(int i=0; i < sorted_set.size(); i++) {
AnnotatedFeatureI t = (AnnotatedFeatureI)sorted_set.elementAt(i);
commentList.append(getCommentString(t));
}
}
return commentList.toString();
}
/** For the specified SeqFeature, find all properties of interest,
* label with the appropriate label, and return a string buffer
* that can be appended to the string buffer that holds the
* comments for that transcript. */
private StringBuffer showProperties(SeqFeatureI sf) {
Hashtable properties = sf.getPropertiesMulti();
StringBuffer propList = new StringBuffer();
boolean first = true;
Enumeration e = properties.keys();
boolean hasProperties = false;
// For one-level annots, put owner here IF we're in internal mode
if (getFeatureEditorDialog().getTranscript() == null &&
apollo.config.Config.internalMode()) {
propList.append(sf.getName() + " properties:\n");
first = false;
propList.append(" " + "Author: " + ((AnnotatedFeature)sf).getOwner());
propList.append("\n");
}
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String label = key.toUpperCase();
if (label.equalsIgnoreCase("DATE"))
label = "LAST MODIFIED ON";
if (!key.equalsIgnoreCase("sp_status") &&
(!key.equalsIgnoreCase("internal_synonym") ||
apollo.config.Config.internalMode()) &&
!key.equalsIgnoreCase("encoded_symbol") &&
!key.equalsIgnoreCase("problem") &&
!key.equalsIgnoreCase("status") &&
!key.equalsIgnoreCase("dicistronic") &&
!key.equalsIgnoreCase("symbol") &&
// If data was read from Chado XML, there may be boring properties
// that we don't want to show.
!ChadoXmlWrite.isSpecialProperty(key)) {
if (first) {
propList.append(sf.getName() + " properties:\n");
first = false;
}
Vector values = (Vector) properties.get(key);
if (values != null && values.size() > 0) {
hasProperties = true;
propList.append(" " + label + ": ");
for (int i = 0; i < values.size(); i++) {
if (i > 0)
propList.append(", ");
String value = (String) values.elementAt(i);
if (value.startsWith(apollo.dataadapter.chadoxml.ChadoXmlAdapter.FIELD_LABEL))
value = value.substring((apollo.dataadapter.chadoxml.ChadoXmlAdapter.FIELD_LABEL).length());
propList.append(value);
}
propList.append("\n");
}
// } else if (key.equalsIgnoreCase("internal_synonym") ||
// key.equals("encoded_symbol")) {
// // Whoa, do we really want to REMOVE the internal_synonym?
// // This isn't going to happen, since we deal with it in the "if" above.
// sf.removeProperty(key);
}
}
if (hasProperties)
propList.append("\n");
return propList;
}
/** Was called setGene, but that was confusing, because all it does
is set the peptide status. */
private void setPeptideStatus (AnnotatedFeatureI g) {
peptideStatus.removeAllItems ();
if (!g.isProteinCodingGene()) {
peptideStatus.addItem ("NOT A PEPTIDE");
peptideStatus.setValue ("NOT A PEPTIDE");
}
else {
Hashtable curator_values = Config.getPeptideStates();
String pep_status = g.getProperty ("sp_status");
PeptideStatus this_status = Config.getPeptideStatus (pep_status);
/* these are the computed values that cannot be over-ridden
by a curator
*/
peptideStatus.addItem (this_status.getText());
Enumeration e = curator_values.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
PeptideStatus a_status = (PeptideStatus) curator_values.get (key);
if (a_status.getPrecedence() >= this_status.getPrecedence() &&
!a_status.getText().equals (this_status.getText()) &&
a_status.getCurated()) {
peptideStatus.addItem (a_status.getText());
}
}
peptideStatus.setValue (this_status.getText());
}
}
/** Called by GeneEditPanel.loadSelectedFeature */
private void loadTranscript () {
Transcript trans = getFeatureEditorDialog().getTranscript();
// if trans is null then we have hit a 1 level annot and disable trans
if (trans == null) {
//if (Config.DO_ONE_LEVEL_ANNOTS)
enableTranscripts(false);
//else logger.error("loadTranscript: transcript is null");
return;
}
//transcriptPanel.setOriginalFeature(realTrans);
// Don't just use the first transcript! Use the one user selected.
//Transcript t = featureEditorDialog.getTranscriptClone();
// Load even if it's not a protein coding gene, in order to get any
// name changes. If it's not protein coding, we won't show the transcript panel.
transcriptPanel.loadAnnotation(trans); // hmmmmm...
// 02/23/2004: Sima has declared that all annotations (except miscellaneous curator's
// observations) have transcripts. // should check numLevels == 1
// if (trans.isProteinCodingGene()) {
// 11/17/2005: Wow, do we really want "miscellaneous curator's observation" hardcoded
// here, when there are now so many types of one-level annots??
if (!trans.getRefFeature().getTopLevelType().equalsIgnoreCase("miscellaneous curator's observation")) {
enableTranscripts(true);
if (!isReadOnly) {
String shortName = apollo.gui.DetailInfo.getName(trans);
addTransComment.setText("Edit " + shortName + " comments");
}
}
// Annot with no transcripts/kids (right now, only miscellaneous curator's observations)
else {
// nullifies transcript clone - otherwise new annot would take on
// someone elses transcript
enableTranscripts(false);
}
}
private void enableTranscripts(boolean enable) {
if (!isReadOnly) {
addTransComment.setEnabled(enable && !isReadOnly);
addTransComment.setVisible(enable && !isReadOnly);
}
transcriptPanel.setVisible(enable);
}
/** Pull up comment editor */
private void editComments(ActionEvent e) {
// before we wipe out the old commentator it has to commit any edits that are hanging
commentator.commitCurrentComment();
JButton button = (JButton) e.getSource();
if (button == addAnnotComment) {
commentator.setFeature(getEditedFeature(), getBackground());
commentator.setType(commentator.ANNOTATION);
}
else {
// transcript.getSelectedClonedAnnot
commentator.setFeature(transcriptPanel.getEditedFeature(),
transcriptPanel.getBackground());
commentator.setType(commentator.TRANSCRIPT);
}
if (commentator.getState() == Frame.ICONIFIED)
commentator.setState(Frame.NORMAL);
commentator.setVisible(true);
}
// not used anymore
// private boolean idAndNameHaveSameFormat() {
// AnnotatedFeatureI af = getEditedFeature();
// return getNameAdapter().idAndNameHaveSameFormat(af,getGuiId(),getGuiName());
// }
/** Returns true if name and id have same format but are unequal */
private boolean idAndNameInconsistent() {
// if name and id in same format, should be identical
AnnotatedFeatureI af = getEditedFeature();
if (!getNameAdapter().idAndNameHaveSameFormat(af,getGuiId(),getGuiName()))
return false; // not same format - cant be inconsistent
return !getGuiId().equals(getGuiName());
}
private boolean nameAndIdAreEqual() {
return getGuiId().equals(getGuiName());
}
/** User has changed id and wants name to be id as well. */
private CompoundTransaction setGuiAndModelName(String newName) {
// change gui
setGuiName(newName);
// commit to model
CompoundTransaction compTrans = commitGeneAndTranscriptNameChange();
return compTrans;
}
/** Focus driven edits occur in textboxes -> synonyms, names, and ids. If the user
selects a new annot in annot tree the focus event comes too late AFTER the
loading of new annot, so this checks for edits before loadAnnotation sets the
new annotation in place. this just checks syns, gene & trans panels override
to check name & ids. */
protected void checkFocusDrivenEdits() {
super.checkFocusDrivenEdits(); // synonyms
if (idIsEditable()) // no need to check if id cant even be edited
idFocusListener.updateIdFromGui();
geneNameListener.updateName();
}
/** Listens for item selected events from featureTypeList.
* 1st check that type has actually changed. If so set clones type and biotype.
* If protein coding gene set translation start. Also update peptide status
* list for new type.
* This was an anonymous class - i felt it was too big for that - confusing.
* I probably made this anonymous class to begin with - I guess im losing
* my enthusiasm for anonymous classes - MG
*
* Also need to possibly change the gene id,name and trans and exon!
*/
private class FeatureTypeItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (!(e.getStateChange() == ItemEvent.SELECTED))
return; // This is not an event we want to respond to.
changeType();
}
private void changeType() {
String oldType = getEditedFeature().getFeatureType();
FeatureProperty fp = findFeatureProp(featureTypeList.getValue());
// there can be more than one analysis type??
// YES and this is problematic! analysis types are analogous to datatypes
// in the tiers file and there can be many datatypes per FeatureProps which
// are analogous to a tiers file Type. yikes! so the picking of the first one
// is somewhat arbitrary but is now an awkward standard. BUT to see if the type
// has changed we should examine all of the analysis types to see if the
// oldType matches it. otherwise if you load a type that is not first in the
// list this will mistaeknly think that you have changed the type
// we need SO!!
String newType = fp.getAnalysisType(0);
// if (oldType.equals(newType)) return;// if type hasnt changed nothing to do
for (int i=0; i<fp.getAnalysisTypesSize(); i++) {
if (oldType.equals(fp.getAnalysisType(i)))
return; // if type hasnt changed nothing to do
}
// This is a multi-event! change type & possibly change translation
// & possibly change ids and names
TransactionSubpart ts = TransactionSubpart.TYPE;
UpdateTransaction ut = new UpdateTransaction(getEditedFeature(),ts);
ut.setSource(getFeatureEditorDialog());
ut.setOldSubpartValue(oldType);
ut.setNewSubpartValue(newType); // should be setNewValue()
// ID Change - type may change id - put this in AnnEditor?
//String newIdPrefix = getNameAdapter().getIDPrefix(getEditedFeature());
//if (!newIdPrefix.equals(oldIdPrefix)) {
String oldId = getEditedFeature().getId();
ut.setOldId(oldId);
if (getNameAdapter().typeChangeCausesIdChange(oldType,newType)) {
//StrandedFeatureSetI annots = getCurSet().getAnnots();
//String cn = getCurSet().getName();
//String tempId = getNameAdapter().generateId(annots,cn,getEditedFeature());
String newId = getNameAdapter().getNewIdFromTypeChange(oldId,oldType,newType);
ut.setNewId(newId);
// this is a bit funny but the transaction will need the name adapter to do
// an undo. if we were sending out all the id and name events/transactions
// this wouldnt be needed - but we arent at the moment (theres no need with
// type change doing a del-add, but its worth considering adding these events
// also TransactionManager would have to not do its changing of id events
// to del-adds (until commit time). for now this will do.
ut.setNameAdapter(getNameAdapter());
//AnnotationUpdateEvent ae = getEditor().setID(getEditedFeature(),newId);
//setIdsAndNamesFromId(newId); // -> Transaction.editModel
// dont fire event, for now type change does delete and add, might need to
// be more subtle with an integrated db - but hard with 3 and 1 level annots
//fireAnnotEvent(ae);
}
// Have to do type change after id change. need old id to detect if same format
// as name above.
//ut.setFeatureId(oldId);
// this does type change and id & name change
ut.editModel(); // trying this out - i think this is the way to go!
//getEditedFeature().setType(newType);
//getEditedFeature().setBioType(newType);
// if protein coding gene (type->gene), set transaction start
if (getEditedFeature().isProteinCodingGene()) {
int trans_count = getEditedFeature().size();
for (int i = 0; i < trans_count; i++) {
AnnotatedFeatureI transClone
= (AnnotatedFeatureI)getEditedFeature().getFeatureAt(i);
if (transClone.getTranslationStart() == 0)
transClone.calcTranslationStartForLongestPeptide();
// send out translation start & stop event
}
}
// for now this is the only event we need - causes delete and add in
// transaction manager - may need to be more subtle some day (integrated db)
// AnnotatedFeatureI annot = getEditedFeature();
// Object source = getFeatureEditorDialog();
//AnnotationUpdateEvent a = new AnnotationUpdateEvent(source,annot,ts,true);
// new way to try -
AnnotationUpdateEvent a = new AnnotationUpdateEvent(ut);
//a.setOldId(oldId);
//a.setOldString(oldType);
fireAnnotEvent(a);
// May need to reset the peptide status box
setPeptideStatus(getEditedFeature());
loadSelectedFeature();
//updateFeature(); // why is this needed?
}
// private CurationSet getCurSet() { // not used anymore
// return getCurState().getCurationSet();
// }
// private AnnotationEditor getEditor() { // not used anymore
// return getCurState().getAnnotationEditor(getEditedFeature().isForwardStrand());
// }
// private GuiCurationState getCurState() { / not used anymore
// return getFeatureEditorDialog().getCurationState();
// }
} // --- end of FeatureTypeItemListener inner class ---
private void attachListeners() {
featureIDField.getComponent().addKeyListener(new IDKeyListener());
idFocusListener = new IDFocusListener();
featureIDField.addFocusListener(idFocusListener);
geneNameListener = new GeneNameListener(getNameField());
}
private class IDKeyListener implements KeyListener {
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
if (!warnedAboutEditingIDs) {
// !! Make this an annoying popup warning
logger.warn("Warning: editing IDs is considered dangerous! Proceed at your own risk.");
warnedAboutEditingIDs = true;
}
}
}
/** ID FOCUS LISTENER INNER CLASS
Inner Class for dealing with ID edits - if id has been edited and
there is a focus lost from id field than check out the id - if ok
change model and fire event - if not revert it back to old id -
this is a quickie standin for a real ID gui */
private class IDFocusListener implements FocusListener {
boolean idBeingEdited = false;
public void focusGained(FocusEvent f) {
idBeingEdited = true;
}
public void focusLost(FocusEvent f) {
updateIdFromGui();
idBeingEdited = false;
}
/** Change annot id from gui if id is acceptable. If not revert gui to model kinda
funny but without proper ID gui this is the best we can do at the moment */
private void updateIdFromGui() {
// checkForFocusDrivenEdits can call this when the gui has not been edited
// but the id has been edited (split) which is detected here
if (!idBeingEdited)
return;
if (getGuiId().equals(getEditedFeature().getId()))
return; // if no net changes to id -> return
if (!idFormatOk()) {
badIdFormatErrorPopup(); // error msg
setGuiIDFromModel(); // revert
return; // done
}
CompoundTransaction compTrans = new CompoundTransaction(this);
// If id and name have same format but are not equal bring up dialog asking
// if user wants to make name the same as id - if not cancel/revert, if
// so commit both name and id changes
if (idAndNameInconsistent()) {
boolean userWantsNameAndIdChange = queryUserOnNameChange();
if (!userWantsNameAndIdChange) {
setGuiIDFromModel(); // revert back to model id
return; // cancel/exit
}
// else make name change, id change done below
CompoundTransaction nameTrans = setGuiAndModelName(getGuiId());
compTrans.addTransaction(nameTrans);
}
// id changes
CompoundTransaction idTrans = commitIdChange();
compTrans.addTransaction(idTrans);
compTrans.setSource(featureEditorDialog);
AnnotationCompoundEvent ace = new AnnotationCompoundEvent(compTrans);
fireAnnotEvent(ace);
loadSelectedFeature();
}
/** Brings up dialog. Returns true if user wants both name and id changed. */
private boolean queryUserOnNameChange() {
String nm = getEditedFeature().getName();
String m = "Name "+nm+" and ID "+getGuiId()+" have the same pattern but are"
+" not the same.\nWould you like to change the name as well or cancel your ID"
+" edit?";
String title = "Change both name and ID?";
int question = JOptionPane.QUESTION_MESSAGE;
String updateName = "Update name";
String cancel = "Cancel ID Update";
Object[] vals = new Object[] {updateName,cancel};
int opt = JOptionPane.DEFAULT_OPTION;
int i = JOptionPane.showOptionDialog(null,m,title,opt,question,null,vals,null);
return i == 0; // 0 is update name
}
private boolean idFormatOk() {
String guiID = getGuiId();
// Make sure ID is in a legal format
return getNameAdapter().checkFormat(getEditedFeature(),guiID);
}
private void badIdFormatErrorPopup() {
String err = "Error: annotation ID is not in a valid format: " + getGuiId();
if (haveIdFormat())
err += "\nID format should be: " + getIdFormat();
errorPopup(err);
}
private boolean haveIdFormat() {
FeatureProperty fp = getFeatureProperty();
return fp != null && fp.getIdFormat() != null;
}
private String getIdFormat() {
return getFeatureProperty().getIdFormat();
}
} // --- end of IDFocusListener inner class ---
/** on focus lost from name field, checks name and commits it if ok.
commit is modifying model and firing update event. */
private class GeneNameListener implements FocusListener,// KeyListener,
DocumentListener {
private boolean inFocus = false;
private boolean documentEdited = false;
//private boolean gotKeystroke = false;
private boolean nameCommitted = true;
private GeneNameListener(ReadWriteField nameField) {
nameField.addFocusListener(this);
//nameField.addKeyListener(this);
nameField.getDocument().addDocumentListener(this);
}
private boolean nameBeingEdited() {
// cant require keystroke as can edit with pasting from mouse w no keystroke
return inFocus && documentEdited && !nameCommitted; // && gotKeystroke
}
/** FocusListener */
public void focusGained(FocusEvent e) {
// replaced with document listener, focus events can be willy nilly
inFocus = true;
}
/** FocusListener */
public void focusLost(FocusEvent e) {
updateName();
resetEditFlags();
}
private void resetEditFlags() {
nameCommitted = true;
inFocus = false;
documentEdited = false;
//gotKeystroke = false;
}
// /** KeyListener */
// public void keyPressed(KeyEvent e) {
// gotKeystroke = true;
// }
// public void keyReleased(KeyEvent e) {
// gotKeystroke = true;
// }
// public void keyTyped(KeyEvent e) {
// gotKeystroke = true;
// }
private void setDocumentEdited() {
//if (!gotKeystroke)
// return;
documentEdited = true;
nameCommitted = false;
}
public void removeUpdate(DocumentEvent d) {
setDocumentEdited();
}
public void insertUpdate(DocumentEvent d) {
setDocumentEdited();
}
public void changedUpdate(DocumentEvent d) {
setDocumentEdited();
}
/** Check if name is in same format as id. If so and they are not equal,
reject the edit - if id editing is enabled suggest editing the id. */
private void updateName() {
// checkForFocusDrivenEdits can call this when the gui has not been edited
// but the name has been edited (split) which is detected here
if (!nameBeingEdited())
return;
//if (getGuiName().equals(getModelName())) {
if (!nameHasChanged()) { // checks for "" which doesnt count as name change
resetEditFlags();
return; // no change -> exit
}
if(getNameAdapter().checkName(getGuiName(),getEditedFeature().getClass()))
{
logger.info("checking for duplicate name");
String e = "Error: gene name already exists in data store " + getGuiName();
errorPopup(e);
setGuiNameFromModel();
resetEditFlags();
return;
}
if (idAndNameInconsistent()) {
String e = "Error: annotation symbol " + getGuiName() +
" is inconsistent with ID " + getGuiId();
if (idIsEditable())
e += "\nTo do this edit use the ID field.";
errorPopup(e);
setGuiNameFromModel();
resetEditFlags();
return;
}
// name checks out -> commit
CompoundTransaction compTrans = commitGeneAndTranscriptNameChange();
AnnotationCompoundEvent ace = new AnnotationCompoundEvent(compTrans);
fireAnnotEvent(ace);
loadSelectedFeature();
resetEditFlags();
} // end of updateName()
} // end of NameFocusListener inner class
void testNameUndo(TestCase testCase) {
// track original name
String originalName = getModelName(); // same as gui name at this point
// trigger editing model with focus lost & gained
geneNameListener.focusGained(null);
//geneNameListener.keyTyped(null); // dont do keys - pasting
geneNameListener.insertUpdate(null);
// edit gui
setGuiName("new-name-test");
geneNameListener.focusLost(null);
// test that model now reflects gui name
testCase.assertEquals(getGuiName(),getModelName());
// now undo the change
getFeatureEditorDialog().undo();
// now make sure original name is reinstated
testCase.assertEquals(originalName,getModelName());
}
private void initDbXRefPanel()
{
JPanel dbxrefPanel = new JPanel();
//dbxrefPanel.setLayout(new GridBagLayout());
//GridBagConstraints c = new GridBagConstraints();
//c.gridheight = GridBagConstraints.REMAINDER;
//dbxrefPanel.setBackground(bgColor);
dbxrefPanel.add(getDbTablePane());
dataBox.add(dbxrefPanel);
}
private class DbxrefDialog extends JDialog
{
private JLabel currentLabel;
private JCheckBox currentCheckBox;
private JLabel dbNameLabel;
private JTextField dbNameField;
private JLabel descriptionLabel;
private JTextField descriptionField;
/*
private JLabel idTypeLabel;
private JTextField idTypeField;
*/
private JLabel idValueLabel;
private JTextField idValueField;
private JLabel versionLabel;
private JTextField versionField;
private JLabel ontologyLabel;
private JCheckBox ontologyCheckBox;
private JButton okButton;
private JButton cancelButton;
public DbxrefDialog(Frame owner, String title, final DbXref dbxref)
{
super(owner, title, true);
int textFieldLength = 15;
/*
idTypeLabel = new JLabel("Id type");
idTypeField = new JTextField(dbxref.getIdType(), textFieldLength);
*/
idValueLabel = new JLabel("ID");
idValueLabel.setForeground(Color.RED);
idValueField = new JTextField(dbxref.getIdValue(), textFieldLength);
dbNameLabel = new JLabel("Database");
dbNameLabel.setForeground(Color.RED);
dbNameField = new JTextField(dbxref.getDbName(), textFieldLength);
descriptionLabel = new JLabel("Description");
descriptionField = new JTextField(dbxref.getDescription(), textFieldLength);
versionLabel = new JLabel("Version");
versionField = new JTextField(dbxref.getVersion(), textFieldLength);
currentLabel = new JLabel("Is current?");
currentCheckBox = new JCheckBox("", dbxref.getCurrent() > 0);
ontologyLabel = new JLabel("Is ontology?");
ontologyCheckBox = new JCheckBox("", dbxref.isOntology());
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.anchor = GridBagConstraints.WEST;
panel.add(idValueLabel, c);
c.gridx = 0;
c.gridx = 1;
panel.add(idValueField, c);
c.gridy = 1;
c.gridx = 0;
panel.add(dbNameLabel, c);
c.gridy = 1;
c.gridx = 1;
panel.add(dbNameField, c);
c.gridy = 2;
c.gridx = 0;
panel.add(descriptionLabel, c);
c.gridy = 2;
c.gridx = 1;
panel.add(descriptionField, c);
/*
c.gridy = 3;
c.gridx = 0;
panel.add(idTypeLabel, c);
c.gridy = 3;
c.gridx = 1;
panel.add(idTypeField, c);
*/
c.gridy = 4;
c.gridx = 0;
panel.add(versionLabel, c);
c.gridy = 4;
c.gridx = 1;
panel.add(versionField, c);
c.gridy = 5;
c.gridx = 0;
panel.add(currentLabel, c);
c.gridy = 5;
c.gridx = 1;
panel.add(currentCheckBox, c);
c.gridy = 6;
c.gridx = 0;
panel.add(ontologyLabel, c);
c.gridy = 6;
c.gridx = 1;
panel.add(ontologyCheckBox, c);
add(panel);
ActionListener okCancelListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
boolean done = true;
if (ae.getSource() == okButton) {
String id = idValueField.getText().trim();
String db = dbNameField.getText().trim();
String description = descriptionField.getText().trim();
String version = versionField.getText().trim();
int current = currentCheckBox.isSelected() ? 1 : 0;
boolean ontology = ontologyCheckBox.isSelected();
if (id.length() == 0 || db.length() == 0) {
done = false;
JOptionPane.showMessageDialog(DbxrefDialog.this, "Both ID and database must be provided",
"Error", JOptionPane.ERROR_MESSAGE);
}
dbxref.setIdValue(id);
dbxref.setDbName(db);
if (description.length() > 0) {
dbxref.setDescription(description);
}
if (version.length() > 0) {
dbxref.setVersion(version);
}
dbxref.setCurrent(current);
dbxref.setIsOntology(ontology);
}
if (done) {
dispose();
}
}
};
okButton = new JButton("OK");
okButton.addActionListener(okCancelListener);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(okCancelListener);
JPanel okCancelPanel = new JPanel();
okCancelPanel.add(okButton);
okCancelPanel.add(cancelButton);
c.gridy = 10;
c.gridx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(okCancelPanel, c);
pack();
setVisible(true);
}
}
/***
** DBXREFTABLEMODEL class
*/
private class DbxRefTableModel extends AbstractTableModel {
private Vector data;
DbxRefTableModel() {
data = new Vector();
}
void setListData(Vector in) {
data = in;
fireTableDataChanged();
}
public int getRowCount() {
return data.size();
}
public boolean isCellEditable(int r, int c) {
return false;
}
public void setValueAt(Object o, int row, int column) {
DbXref db = (DbXref) data.elementAt(row);
if (column == 0)
db.setIdValue((String) o);
else
db.setDbName((String) o);
}
public int getColumnCount() {
return 2;
}
public Object getValueAt(int row, int column) {
DbXref db = (DbXref) data.elementAt(row);
if (column == 0)
return db.getIdValue();
else
return db.getDbName();
}
public DbXref getDbxrefAt(int idx)
{
return (DbXref)data.get(idx);
}
public void addDbxRef(DbXref dbxref)
{
int idx = data.size();
data.add(dbxref);
getEditedFeature().addDbXref(dbxref);
TransactionSubpart ts = TransactionSubpart.DBXREF;
int subpartRank = getEditedFeature().getDbXrefs().size()-1;
AddTransaction at = new AddTransaction(this, getEditedFeature(), ts, dbxref, subpartRank);;
fireAnnotEvent(at.generateAnnotationChangeEvent());
fireTableRowsInserted(idx, idx);
}
public void deleteDbxRef(DbXref dbxref)
{
int idx = dbxrefTable.getSelectedRow();
data.removeElementAt(idx);
getEditedFeature().getIdentifier().deleteDbXref(dbxref);
// since the selected row is no longer available, need to reset
// stored selected index as well
table_row_selected = -1;
TransactionSubpart ts = TransactionSubpart.DBXREF;
int subpartRank = getEditedFeature().getDbXrefs().indexOf(dbxref);
DeleteTransaction dt = new DeleteTransaction(this, getEditedFeature(), ts, dbxref, subpartRank);;
fireAnnotEvent(dt.generateAnnotationChangeEvent());
fireTableRowsDeleted(idx, 0);
}
/*
public void updateDbxRef(DbXref oldDbxref, DbXref newDbxref)
{
int idx = dbxrefTable.getSelectedRow();
CompoundTransaction ct = new CompoundTransaction(this);
ct.addTransaction(generateDeleteTransaction(oldDbxref));
ct.addTransaction(generateAddTransaction(newDbxref));
fireAnnotEvent(new AnnotationCompoundEvent(ct));
fireTableDataChanged();
}
*/
/*
private AddTransaction generateAddTransaction(DbXref dbxref)
{
data.add(dbxref);
getEditedFeature().addDbXref(dbxref);
TransactionSubpart ts = TransactionSubpart.DBXREF;
int subpartRank = getEditedFeature().getDbXrefs().size()-1;
return new AddTransaction(this, getEditedFeature(), ts, dbxref, subpartRank);
}
*/
/*
private DeleteTransaction generateDeleteTransaction(DbXref dbxref)
{
int idx = dbxrefTable.getSelectedRow();
data.removeElementAt(idx);
getEditedFeature().getIdentifier().deleteDbXref(dbxref);
// since the selected row is no longer available, need to reset
// stored selected index as well
table_row_selected = -1;
TransactionSubpart ts = TransactionSubpart.DBXREF;
int subpartRank = getEditedFeature().getDbXrefs().indexOf(dbxref);
return new DeleteTransaction(this, getEditedFeature(), ts, dbxref, subpartRank);
}
*/
} // end of DbxRefTableModel class - make inner class?
} // end of GeneEditPanel class
|
iabernikhin/VK-GL-CTS | framework/delibs/deutil/deSocket.h | <filename>framework/delibs/deutil/deSocket.h
#ifndef _DESOCKET_H
#define _DESOCKET_H
/*-------------------------------------------------------------------------
* drawElements Utility Library
* ----------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Socket abstraction.
*
* Socket API is thread-safe except to:
* - listen()
* - connect()
* - destroy()
*//*--------------------------------------------------------------------*/
#include "deDefs.h"
DE_BEGIN_EXTERN_C
/* Socket types. */
typedef struct deSocket_s deSocket;
typedef struct deSocketAddress_s deSocketAddress;
typedef enum deSocketFamily_e
{
DE_SOCKETFAMILY_INET4 = 0,
DE_SOCKETFAMILY_INET6,
DE_SOCKETFAMILY_LAST
} deSocketFamily;
typedef enum deSocketType_e
{
DE_SOCKETTYPE_STREAM = 0,
DE_SOCKETTYPE_DATAGRAM,
DE_SOCKETTYPE_LAST
} deSocketType;
typedef enum deSocketProtocol_e
{
DE_SOCKETPROTOCOL_TCP = 0,
DE_SOCKETPROTOCOL_UDP,
DE_SOCKETPROTOCOL_LAST
} deSocketProtocol;
typedef enum deSocketFlag_e
{
DE_SOCKET_KEEPALIVE = (1<<0),
DE_SOCKET_NODELAY = (1<<1),
DE_SOCKET_NONBLOCKING = (1<<2),
DE_SOCKET_CLOSE_ON_EXEC = (1<<3)
} deSocketFlag;
/* \todo [2012-07-09 pyry] Separate closed bits for send and receive channels. */
typedef enum deSocketState_e
{
DE_SOCKETSTATE_CLOSED = 0,
DE_SOCKETSTATE_CONNECTED = 1,
DE_SOCKETSTATE_LISTENING = 2,
DE_SOCKETSTATE_DISCONNECTED = 3,
DE_SOCKETSTATE_LAST
} deSocketState;
typedef enum deSocketResult_e
{
DE_SOCKETRESULT_SUCCESS = 0,
DE_SOCKETRESULT_WOULD_BLOCK = 1,
DE_SOCKETRESULT_CONNECTION_CLOSED = 2,
DE_SOCKETRESULT_CONNECTION_TERMINATED = 3,
DE_SOCKETRESULT_ERROR = 4,
DE_SOCKETRESULT_LAST
} deSocketResult;
typedef enum deSocketChannel_e
{
DE_SOCKETCHANNEL_RECEIVE = (1<<0),
DE_SOCKETCHANNEL_SEND = (1<<1),
DE_SOCKETCHANNEL_BOTH = DE_SOCKETCHANNEL_RECEIVE|DE_SOCKETCHANNEL_SEND
} deSocketChannel;
/* Socket API, similar to Berkeley sockets. */
deSocketAddress* deSocketAddress_create (void);
void deSocketAddress_destroy (deSocketAddress* address);
deBool deSocketAddress_setFamily (deSocketAddress* address, deSocketFamily family);
deSocketFamily deSocketAddress_getFamily (const deSocketAddress* address);
deBool deSocketAddress_setType (deSocketAddress* address, deSocketType type);
deSocketType deSocketAddress_getType (const deSocketAddress* address);
deBool deSocketAddress_setProtocol (deSocketAddress* address, deSocketProtocol protocol);
deSocketProtocol deSocketAddress_getProtocol (const deSocketAddress* address);
deBool deSocketAddress_setPort (deSocketAddress* address, int port);
int deSocketAddress_getPort (const deSocketAddress* address);
deBool deSocketAddress_setHost (deSocketAddress* address, const char* host);
const char* deSocketAddress_getHost (const deSocketAddress* address);
deSocket* deSocket_create (void);
void deSocket_destroy (deSocket* socket);
deSocketState deSocket_getState (const deSocket* socket);
deUint32 deSocket_getOpenChannels (const deSocket* socket);
deBool deSocket_setFlags (deSocket* socket, deUint32 flags);
deBool deSocket_listen (deSocket* socket, const deSocketAddress* address);
deSocket* deSocket_accept (deSocket* socket, deSocketAddress* clientAddress);
deBool deSocket_connect (deSocket* socket, const deSocketAddress* address);
deBool deSocket_shutdown (deSocket* socket, deUint32 channels);
deBool deSocket_close (deSocket* socket);
deSocketResult deSocket_send (deSocket* socket, const void* buf, size_t bufSize, size_t* numSent);
deSocketResult deSocket_receive (deSocket* socket, void* buf, size_t bufSize, size_t* numReceived);
/* Utilities. */
const char* deGetSocketFamilyName (deSocketFamily family);
const char* deGetSocketResultName (deSocketResult result);
DE_END_EXTERN_C
#endif /* _DESOCKET_H */
|
jbauermanncode/Curso_Em_Video_Python | Python_Exercicios/Mundo1/Condições em Python (if..else)/python_030.py | '''
Crie um programa que leia um número inteiro e mostre na tela se ele é par ou ímpar.
'''
# Ler um número
n = int(input('Digite um número: '))
# Estrutura Condicional if/else
if n % 2 == 0:
print('O número {} é par!'.format(n))
else:
print('O número {} é ímpar!'.format(n)) |
Mr-TelegramBot/python-tdlib | py_tdlib/constructors/get_all_passport_elements.py | <reponame>Mr-TelegramBot/python-tdlib
from ..factory import Method
class getAllPassportElements(Method):
password = None # type: "string"
|
PranavPurwar/java-n-IDE-for-Android | app/src/main/assets/sample/CommonlyUsedJavaClasses/JavaString/src/main/java/sample/JavaStringExample.java | <filename>app/src/main/assets/sample/CommonlyUsedJavaClasses/JavaString/src/main/java/sample/JavaStringExample.java
package sample;
/*
Java String example.
This Java String example describes how Java String object is created and used.
*/
public class JavaStringExample {
public static void main(String args[]) {
/*
String in java represents the character sequence.
*/
/* creates new empty string */
String str1 = new String("");
/* creates new string object whose content would be Hello World */
String str2 = new String("Hello world");
/* creates new string object whose content would be Hello World */
String str3 = "Hello Wolrd";
/*
IMPORTANT : Difference between above given two approaches is, string object
created using new operator will always return new string ojbect.
While the other may return the reference of already created string
ojbect with same content , if any.
*/
System.out.println(str1.length());
}
}
/*
OUTPUT of the above given Java String Example would be :
*/
|
iceant/point-tools | point-agent/src/main/java/com/github/iceant/point/agent/services/CommandService.java | package com.github.iceant.point.agent.services;
import com.github.iceant.point.agent.utils.IOUtil;
import com.github.iceant.point.agent.utils.OSUtil;
import com.github.iceant.point.common.dto.CommandResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
@Service
public class CommandService {
@Autowired
ExecutorService executorService;
@Value("${app.console.charset:UTF-8}")
String consoleCharset;
public static String[] makeCommand(String ... command){
if(OSUtil.isWindows()){
return new String[]{"cmd", "/C", String.join(" ", command)};
}else{
return new String[]{"/bin/sh", "-c", String.join(" ", command)};
}
}
public <T> CompletableFuture<CommandResult> execute(ICommandCallback callback, String ... command){
return execute(callback, null, command);
}
public <T> CompletableFuture<CommandResult> execute(ICommandCallback callback, File path, String ... command){
return CompletableFuture.supplyAsync(new Supplier<Process>() {
@Override
public Process get() {
try {
return Runtime.getRuntime().exec(command, null, path);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, executorService).thenApplyAsync(new Function<Process, CommandResult>() {
@Override
public CommandResult apply(Process process) {
CommandResult result = CommandResult.builder().build();
try {
result.setOutput(IOUtil.readAsString(process.getInputStream(), consoleCharset));
result.setError(IOUtil.readAsString(process.getErrorStream(), consoleCharset));
result.setCode(process.waitFor());
return result;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
process.destroy();
}
}
}, executorService);
}
public Future executeAndWait(ICommandCallback callback, long timeout, TimeUnit unit, File path, String ... command){
return executorService.submit(new Runnable() {
@Override
public void run() {
Process process = null;
try{
process = Runtime.getRuntime().exec(command, null, path);
if(process!=null) {
callback.onSuccess(process.getInputStream());
callback.onError(process.getErrorStream());
callback.onReturn(process.waitFor(timeout, unit)?0:-1);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if(process!=null){
process.destroy();
process=null;
}
}
}
});
}
}
|
Bernardo-MG/symbaroum-toolkit-webapp | src/main/js/root/containers/Root.js | <gh_stars>0
/**
* Root application.
*
* There are two options, depending on if this is a production or development build.
*/
module.exports = (process.env.NODE_ENV === 'production') ? require('root/containers/Root.prod') : require('root/containers/Root.dev');
|
caramirezal/Drop-seq | src/tests/java/org/broadinstitute/dropseqrna/barnyard/digitalallelecounts/LikelihoodUtilsTest.java | <filename>src/tests/java/org/broadinstitute/dropseqrna/barnyard/digitalallelecounts/LikelihoodUtilsTest.java<gh_stars>0
/*
* MIT License
*
* Copyright 2017 Broad Institute
*
* 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 org.broadinstitute.dropseqrna.barnyard.digitalallelecounts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.broadinstitute.dropseqrna.barnyard.digitalallelecounts.LikelihoodUtils;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import htsjdk.samtools.util.StringUtil;
import htsjdk.variant.variantcontext.GenotypeType;
/**
* Note that the likelihoods have been changed from log to log 10.
* @author nemesh
*
*/
public class LikelihoodUtilsTest {
@Test(enabled=true)
public void testMixedLikelihoodMultiRead () {
GenotypeType [] g = {GenotypeType.HOM_REF, GenotypeType.HET, GenotypeType.HOM_VAR};
List<GenotypeType> genotypes = Arrays.asList(g);
Double [] m = {new Double(2), new Double(1), new Double(1)};
List<Double> mixture = Arrays.asList(m);
char refAllele ='A';
char altAllele ='T';
Byte [] b = {StringUtil.charToByte('A'), StringUtil.charToByte('A')};
List<Byte> bases = Arrays.asList(b);
Byte [] q = {new Byte ((byte)10), new Byte ((byte)10)};
List<Byte> qualities =Arrays.asList(q);
double result = LikelihoodUtils.getInstance().getLogLikelihoodMixedModel(refAllele, altAllele, genotypes, mixture, bases, qualities, null, null, null);
Assert.assertEquals(result, Math.log10(0.36), 0.001);
}
@Test(enabled=true)
public void testMixedLikelihood () {
GenotypeType [] g = {GenotypeType.HOM_REF, GenotypeType.HET, GenotypeType.HOM_VAR};
List<GenotypeType> genotypes = Arrays.asList(g);
Double [] m = {new Double(2), new Double(1), new Double(1)};
List<Double> mixture = Arrays.asList(m);
char refAllele ='A';
char altAllele ='T';
List<Byte> bases = Collections.singletonList(StringUtil.charToByte('A'));
List<Byte> qualities =Collections.singletonList(new Byte ((byte)10));
double result = LikelihoodUtils.getInstance().getLogLikelihoodMixedModel(refAllele, altAllele, genotypes, mixture, bases, qualities, null, null, null);
Assert.assertEquals(result, Math.log10(0.6), 0.001);
double [] likes = LikelihoodUtils.getInstance().getLikelihoodManyObservations ((byte) refAllele, (byte) altAllele, genotypes, bases.get(0), qualities.get(0), null, null, null);
double result2=LikelihoodUtils.getInstance().getLikelihoodMixedModel(likes, mixture);
Assert.assertEquals(Math.log10(result2), Math.log10(0.6), 0.001);
}
@Test(enabled=true)
public void testLogLikelihood1 () {
char [] b = {'A','A','A','A','A'};
List<Byte> bases = convert (b);
byte [] q = {10,10,10,10,10};
List<Byte> qualities = convert (q);
// probability if genotype is AA
double result = LikelihoodUtils.getInstance().getLogLikelihood('A', 'A', bases, qualities, null, null);
// > log10 (getRefLikelihood(5,0,0.9))
// [1] -0.2287875
double expected = -0.2287875;
Assert.assertEquals(result, expected, 0.000001);
// probability if genotype is TT
result = LikelihoodUtils.getInstance().getLogLikelihood('T', 'T', bases, qualities, null, null);
// > log10 (getRefLikelihood(0,5,0.9))
// [1] -5
expected = -5.000002;
Assert.assertEquals(result, expected, 0.00001);
// probability if genotype is AT
result = LikelihoodUtils.getInstance().getLogLikelihood('A', 'T', bases, qualities, null, null);
// log10(getHetLikelihood(5,0,0.9))
// [1] -1.50515
expected = -1.50515;
Assert.assertEquals(result, expected, 0.00001);
}
@Test(enabled=true)
// true het genotype
public void testLogLikelihood2 () {
char [] b = {'A','A','A','T','T'};
List<Byte> bases = convert (b);
byte [] q = {20,20,20,20,20};
List<Byte> qualities = convert (q);
// probability if genotype is AA
double result = LikelihoodUtils.getInstance().getLogLikelihood('A', 'A', bases, qualities, null, null);
// log10 (getRefLikelihood(3,2,0.99))
// [1] -4.013094
double expected = -4.013094;
Assert.assertEquals(result, expected, 0.000001);
// probability if genotype is TT
result = LikelihoodUtils.getInstance().getLogLikelihood('T', 'T', bases, qualities, null, null);
// log10 (getRefLikelihood(2,3,0.99))
// [1] -6.00873
expected = -6.008729;
Assert.assertEquals(result, expected, 0.00001);
// probability if genotype is AT
result = LikelihoodUtils.getInstance().getLogLikelihood('A', 'T', bases, qualities, null, null);
// log10(getHetLikelihood(3,2,0.99))
// [1] -1.50515
expected = -1.50515;
Assert.assertEquals(result, expected, 0.00001);
}
@Test
// Here, we copy the testLogLikelihood2 test, bump up the quality scores > 20, then max the probability at 20.
public void testMaximumObservationProbability () {
char [] b = {'A','A','A','T','T'};
List<Byte> bases = convert (b);
byte [] q = {30,30,30,30,30};
List<Byte> qualities = convert (q);
Double maxProb = 0.01;
// probability if genotype is AA
double result = LikelihoodUtils.getInstance().getLogLikelihood('A', 'A', bases, qualities, null, null);
// log10 (getRefLikelihood(3,2,0.999))
// [1] -6.001304
double expected = -6.001304;
Assert.assertEquals(result, expected, 0.000001);
// log10 (getRefLikelihood(3,2,0.99))
// [1] -4.013094
result = LikelihoodUtils.getInstance().getLogLikelihood('A', 'A', bases, qualities, null, maxProb);
Assert.assertEquals(result, -4.013094, 0.000001);
// probability if genotype is TT
result = LikelihoodUtils.getInstance().getLogLikelihood('T', 'T', bases, qualities, null, null);
// log10 (getRefLikelihood(2,3,0.999))
// [1] -9.000869
expected = -9.000869;
Assert.assertEquals(result, expected, 0.00001);
// log10 (getRefLikelihood(2,3,0.99))
// [1] -6.00873
result = LikelihoodUtils.getInstance().getLogLikelihood('T', 'T', bases, qualities, null, maxProb);
Assert.assertEquals(result, -6.00873, 0.000001);
// probability if genotype is AT
result = LikelihoodUtils.getInstance().getLogLikelihood('A', 'T', bases, qualities, null, null);
// log10(getHetLikelihood(3,2,0.99))
// [1] -1.50515
expected = -1.50515;
Assert.assertEquals(result, expected, 0.00001);
result = LikelihoodUtils.getInstance().getLogLikelihood('A', 'T', bases, qualities, null, maxProb);
Assert.assertEquals(result, expected, 0.00001); // doesn't matter what the error rate is for the het genotype state.
}
private List<Byte> convert (final char [] x) {
List<Byte> r = new ArrayList<>();
for (char c: x)
r.add(new Byte((byte)c));
return r;
}
private List<Byte> convert (final byte [] x) {
List<Byte> r = new ArrayList<>();
for (byte c: x)
r.add(c);
return r;
}
@Test(dataProvider = "PhreadToProb")
public void testPhreadScoreToErrorProbability (final Byte phread, final Double prob) {
double actual = LikelihoodUtils.getInstance().phredScoreToErrorProbability(phread);
Assert.assertEquals(actual, prob, 0.0000001);
}
@Test
public void testPhreadScoreToErrorProbability2 () {
byte phread = 37;
double prob=0.0001995262;
double actual = LikelihoodUtils.getInstance().phredScoreToErrorProbability(phread);
Assert.assertEquals(actual, prob, 0.00000001);
}
@Test(dataProvider = "PhreadToProb")
public void testErrorProbabilityToPhreadScore (final Byte phread, final Double prob) {
byte actual = LikelihoodUtils.getInstance().errorProbabilityToPhredScore(prob);
Assert.assertEquals(actual, phread.byteValue());
}
@Test()
public void testErrorProbabilityToPhreadScore2 () {
double prob=0.0001995262;
byte phread = 37;
byte actual = LikelihoodUtils.getInstance().errorProbabilityToPhredScore(prob);
Assert.assertEquals(actual, phread);
}
@Test
public void testGetOneMinusPvalueFromLog10Likelihood () {
LikelihoodUtils u = LikelihoodUtils.getInstance();
byte [] phreds = new byte [] {60,50,40,35,30,20,10,5};
double [] likes = new double [phreds.length];
for (int i=0; i<phreds.length; i++ ) {
likes[i]= u.phredScoreToErrorProbability(phreds[i]);
likes[i] = Math.log10(likes[i]);
}
double result = LikelihoodUtils.getInstance().getOneMinusPvalueFromLog10Likelihood(likes);
double expected =0.26055;
Assert.assertEquals(result, expected, 0.00001);
}
@Test
public void testGetPvalueFromLog10Likelihood () {
LikelihoodUtils u = LikelihoodUtils.getInstance();
byte [] phreds = new byte [] {60,50,40,35,30,20,10,5};
double [] likes = new double [phreds.length];
for (int i=0; i<phreds.length; i++ ) {
likes[i]= u.phredScoreToErrorProbability(phreds[i]);
likes[i] = Math.log10(likes[i]);
}
double resultOneMinus = LikelihoodUtils.getInstance().getOneMinusPvalueFromLog10Likelihood(likes);
double expected =1-resultOneMinus;
double result=LikelihoodUtils.getInstance().getPvalueFromLog10Likelihood(likes);
Assert.assertEquals(result, expected, 0.00001);
}
@DataProvider(name = "PhreadToProb")
//https://en.wikipedia.org/wiki/Phred_quality_score
public Object[][] createData1() {
return new Object[][] {
{ new Byte((byte) 8), new Double(0.1584893) },
{ new Byte((byte) 10), new Double(0.1) },
{ new Byte((byte) 13), new Double(0.05011872) },
{ new Byte((byte) 20), new Double(0.01) },
{ new Byte((byte) 27), new Double(0.001995262) },
{ new Byte((byte) 30), new Double(0.001) },
{ new Byte((byte) 32), new Double(0.0006309573) },
{ new Byte((byte) 37), new Double(0.0001995262) },
{ new Byte((byte) 40), new Double(0.0001) },
{ new Byte((byte) 50), new Double(0.00001) },
{ new Byte((byte) 60), new Double(0.000001) }
};
}
}
|
mongodb-js/scope-client | lib/subscription.js | <filename>lib/subscription.js
var util = require('util');
var stream = require('stream');
var _lastId = 0;
var generateId = function() {
return _lastId++;
};
function Subscription(client, url, opts) {
if (!(this instanceof Subscription)) {
return new Subscription(client, url, opts);
}
Subscription.super_.call(this, {
objectMode: true
});
opts = opts || {};
this.client = client;
this.url = url;
this.payload = {
token: this.client.connection.token,
instance_id: this.client.connection.instance_id
};
Object.keys(opts).map(function(key) {
this.payload[key] = opts.key;
}.bind(this));
this.id = generateId();
this.listening = false;
this.debug = require('debug')('mongodb-scope-client:subscription:' + this.id);
client.on('close', this.close.bind(this));
this.debug('subscription created for ' + this.url);
}
util.inherits(Subscription, stream.Readable);
Subscription.prototype._read = function() {
if (this.listening) {
return this;
}
this.listening = true;
this.debug('sending payload', this.payload);
this.client.io
.on(this.url, this.onData.bind(this))
.on(this.url + '/error', this.onError.bind(this))
.emit(this.url, this.payload);
return this;
};
Subscription.prototype.onData = function(data) {
this.debug('got data', data);
this.push(data);
};
Subscription.prototype.onError = function(data) {
var err = new Error();
err.code = data.code;
err.http = data.http;
err.message = data.message;
Error.captureStackTrace(err, this);
this.emit('error', err);
};
Subscription.prototype.close = function() {
// TODO: check io.closed instead?
if (!this.client.io.connected) {
this.debug('client already closed');
return;
}
this.client.io
.off(this.url)
.on(this.url + '/unsubscribe_complete', function() {
this.push(null);
}.bind(this))
.emit(this.url + '/unsubscribe', this.payload);
};
module.exports = Subscription;
|
FLEXXXXX-00/soDLA | src/main/scala/nvdla/pdp/NV_NVDLA_PDP_CORE_unit2d_part1.scala | <reponame>FLEXXXXX-00/soDLA
package nvdla
import chisel3._
import chisel3.util._
class NV_NVDLA_PDP_CORE_CAL2D_pnum_flush(implicit val conf: nvdlaConfig) extends Module {
val io = IO(new Bundle {
//clk
val nvdla_core_clk = Input(Clock())
val unit2d_cnt_pooling = Input(UInt(3.W))
val unit2d_cnt_pooling_max = Input(UInt(3.W))
val last_line_in = Input(Bool())
val pnum_flush = Output(Vec(7, Bool()))
})
//
// ┌─┐ ┌─┐
// ┌──┘ ┴───────┘ ┴──┐
// │ │
// │ ─── │
// │ ─┬┘ └┬─ │
// │ │
// │ ─┴─ │
// │ │
// └───┐ ┌───┘
// │ │
// │ │
// │ │
// │ └──────────────┐
// │ │
// │ ├─┐
// │ ┌─┘
// │ │
// └─┐ ┐ ┌───────┬──┐ ┌──┘
// │ ─┤ ─┤ │ ─┤ ─┤
// └──┴──┘ └──┴──┘
withClock(io.nvdla_core_clk){
val unit2d_cnt_pooling_a = VecInit((0 to 7)
map {i => io.unit2d_cnt_pooling +& i.U})
val pnum_flush_reg = Reg(Vec(7, UInt(3.W)))
//pooling No. in flush time
when(io.last_line_in){
when(unit2d_cnt_pooling_a(0) === io.unit2d_cnt_pooling_max){
pnum_flush_reg(0) := 0.U
pnum_flush_reg(1) := 1.U
pnum_flush_reg(2) := 2.U
pnum_flush_reg(3) := 3.U
pnum_flush_reg(4) := 4.U
pnum_flush_reg(5) := 5.U
pnum_flush_reg(6) := 6.U
}
.elsewhen(unit2d_cnt_pooling_a(1) === io.unit2d_cnt_pooling_max){
pnum_flush_reg(0) := io.unit2d_cnt_pooling_max
pnum_flush_reg(1) := 0.U
pnum_flush_reg(2) := 1.U
pnum_flush_reg(3) := 2.U
pnum_flush_reg(4) := 3.U
pnum_flush_reg(5) := 4.U
pnum_flush_reg(6) := 5.U
}
.elsewhen(unit2d_cnt_pooling_a(2) === io.unit2d_cnt_pooling_max){
pnum_flush_reg(0) := io.unit2d_cnt_pooling +& 1.U
pnum_flush_reg(1) := io.unit2d_cnt_pooling_max
pnum_flush_reg(2) := 0.U
pnum_flush_reg(3) := 1.U
pnum_flush_reg(4) := 2.U
pnum_flush_reg(5) := 3.U
pnum_flush_reg(6) := 4.U
}
.elsewhen(unit2d_cnt_pooling_a(3) === io.unit2d_cnt_pooling_max){
pnum_flush_reg(0) := io.unit2d_cnt_pooling +& 1.U
pnum_flush_reg(1) := io.unit2d_cnt_pooling +& 2.U
pnum_flush_reg(2) := io.unit2d_cnt_pooling_max
pnum_flush_reg(3) := 0.U
pnum_flush_reg(4) := 1.U
pnum_flush_reg(5) := 2.U
pnum_flush_reg(6) := 3.U
}
.elsewhen(unit2d_cnt_pooling_a(4) === io.unit2d_cnt_pooling_max){
pnum_flush_reg(0) := io.unit2d_cnt_pooling +& 1.U
pnum_flush_reg(1) := io.unit2d_cnt_pooling +& 2.U
pnum_flush_reg(2) := io.unit2d_cnt_pooling +& 3.U
pnum_flush_reg(3) := io.unit2d_cnt_pooling_max
pnum_flush_reg(4) := 0.U
pnum_flush_reg(5) := 1.U
pnum_flush_reg(6) := 2.U
}
.elsewhen(unit2d_cnt_pooling_a(5) ===io. unit2d_cnt_pooling_max){
pnum_flush_reg(0) := io.unit2d_cnt_pooling +& 1.U
pnum_flush_reg(1) := io.unit2d_cnt_pooling +& 2.U
pnum_flush_reg(2) := io.unit2d_cnt_pooling +& 3.U
pnum_flush_reg(3) := io.unit2d_cnt_pooling +& 4.U
pnum_flush_reg(4) := io.unit2d_cnt_pooling_max
pnum_flush_reg(5) := 0.U
pnum_flush_reg(6) := 1.U
}
.elsewhen(unit2d_cnt_pooling_a(6) === io.unit2d_cnt_pooling_max){
pnum_flush_reg(0) := io.unit2d_cnt_pooling +& 1.U
pnum_flush_reg(1) := io.unit2d_cnt_pooling +& 2.U
pnum_flush_reg(2) := io.unit2d_cnt_pooling +& 3.U
pnum_flush_reg(3) := io.unit2d_cnt_pooling +& 4.U
pnum_flush_reg(4) := io.unit2d_cnt_pooling +& 5.U
pnum_flush_reg(5) := io.unit2d_cnt_pooling_max
pnum_flush_reg(6) := 0.U
}
.elsewhen(unit2d_cnt_pooling_a(7) === io.unit2d_cnt_pooling_max){
pnum_flush_reg(0) := io.unit2d_cnt_pooling +& 1.U
pnum_flush_reg(1) := io.unit2d_cnt_pooling +& 2.U
pnum_flush_reg(2) := io.unit2d_cnt_pooling +& 3.U
pnum_flush_reg(3) := io.unit2d_cnt_pooling +& 4.U
pnum_flush_reg(4) := io.unit2d_cnt_pooling +& 5.U
pnum_flush_reg(5) := io.unit2d_cnt_pooling +& 6.U
pnum_flush_reg(6) := io.unit2d_cnt_pooling_max
}
}
//assign output
for(i <- 0 to 6){
io.pnum_flush(i) := pnum_flush_reg(i)
}
}}
class NV_NVDLA_PDP_CORE_CAL2D_pnum_updt(implicit val conf: nvdlaConfig) extends Module {
val io = IO(new Bundle {
//clk
val nvdla_core_clk = Input(Clock())
val padding_v_cfg = Input(UInt(3.W))
val stride = Input(UInt(5.W))
val up_pnum = Output(Vec(6, Bool()))
})
//
// ┌─┐ ┌─┐
// ┌──┘ ┴───────┘ ┴──┐
// │ │
// │ ─── │
// │ ─┬┘ └┬─ │
// │ │
// │ ─┴─ │
// │ │
// └───┐ ┌───┘
// │ │
// │ │
// │ │
// │ └──────────────┐
// │ │
// │ ├─┐
// │ ┌─┘
// │ │
// └─┐ ┐ ┌───────┬──┐ ┌──┘
// │ ─┤ ─┤ │ ─┤ ─┤
// └──┴──┘ └──┴──┘
withClock(io.nvdla_core_clk){
//-------------------------
//update pooling No. in line2 of next surface
//-------------------------
val up_pnum_reg = Reg(Vec(6, Bool()))
up_pnum_reg(0) := 0.U
when(io.padding_v_cfg === 0.U){
up_pnum_reg(1) := 0.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
when(io.padding_v_cfg === 1.U){
when(io.stride === 1.U){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
.otherwise{
up_pnum_reg(1) := 0.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
}
when(io.padding_v_cfg === 2.U){
when(io.stride === 1.U){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 2.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
.elsewhen(io.stride === 2.U){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
.otherwise{
up_pnum_reg(1) := 0.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
}
when(io.padding_v_cfg === 3.U){
when(io.stride === 1.U){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 2.U
up_pnum_reg(3) := 3.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
.elsewhen((io.stride === 2.U) | (io.stride === 3.U)){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
.otherwise{
up_pnum_reg(1) := 0.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
}
when(io.padding_v_cfg === 4.U){
when(io.stride === 1.U){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 2.U
up_pnum_reg(3) := 3.U
up_pnum_reg(4) := 4.U
up_pnum_reg(5) := 0.U
}
.elsewhen(io.stride === 2.U){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 2.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
.elsewhen((io.stride === 3.U) | (io.stride === 4.U)){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
.otherwise{
up_pnum_reg(1) := 0.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
}
when(io.padding_v_cfg === 5.U){
when(io.stride === 1.U){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 2.U
up_pnum_reg(3) := 3.U
up_pnum_reg(4) := 4.U
up_pnum_reg(5) := 5.U
}
.elsewhen(io.stride === 2.U){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 2.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
.elsewhen((io.stride === 3.U) | (io.stride === 4.U) | (io.stride === 5.U)){
up_pnum_reg(1) := 1.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
.otherwise{
up_pnum_reg(1) := 0.U
up_pnum_reg(2) := 0.U
up_pnum_reg(3) := 0.U
up_pnum_reg(4) := 0.U
up_pnum_reg(5) := 0.U
}
}
for(i <- 0 to 5){
io.up_pnum(i) := up_pnum_reg(i)
}
}}
class NV_NVDLA_PDP_CORE_CAL2D_bubble_control_begin(implicit val conf: nvdlaConfig) extends Module {
val io = IO(new Bundle {
//clk
val nvdla_core_clk = Input(Clock())
val pdp_op_start = Input(Bool())
val flush_num = Input(UInt(3.W))
val first_out_num = Input(UInt(3.W))
val up_pnum = Input(Vec(6, Bool()))
val pnum_flush = Input(Vec(7, UInt(3.W)))
val bubble_add = Output(UInt(3.W))
val flush_in_next_surf = Output(UInt(3.W))
})
//
// ┌─┐ ┌─┐
// ┌──┘ ┴───────┘ ┴──┐
// │ │
// │ ─── │
// │ ─┬┘ └┬─ │
// │ │
// │ ─┴─ │
// │ │
// └───┐ ┌───┘
// │ │
// │ │
// │ │
// │ └──────────────┐
// │ │
// │ ├─┐
// │ ┌─┘
// │ │
// └─┐ ┐ ┌───────┬──┐ ┌──┘
// │ ─┤ ─┤ │ ─┤ ─┤
// └──┴──┘ └──┴──┘
withClock(io.nvdla_core_clk){
val bubble_num = RegInit("b0".asUInt(3.W))
when(io.pdp_op_start){
when(io.flush_num >= io.first_out_num){
bubble_num := io.flush_num -& io.first_out_num +& 1.U
}
.otherwise{
bubble_num := 0.U
}
}
io.flush_in_next_surf := io.flush_num - bubble_num
///////////////
val next_pnum = MixedVecInit((0 to 7) map { i => VecInit(Seq.fill(i+1)("b0".asUInt(3.W)))})
//begin
when(io.flush_in_next_surf === 2.U){
when(bubble_num === 0.U){
next_pnum(2)(1) := io.pnum_flush(1)
next_pnum(2)(0) := io.pnum_flush(0)
}
.elsewhen(bubble_num === 1.U){
next_pnum(2)(1) := io.pnum_flush(2)
next_pnum(2)(0) := io.pnum_flush(1)
}
.elsewhen(bubble_num === 2.U){
next_pnum(2)(1) := io.pnum_flush(3)
next_pnum(2)(0) := io.pnum_flush(2)
}
.elsewhen(bubble_num === 3.U){
next_pnum(2)(1) := io.pnum_flush(4)
next_pnum(2)(0) := io.pnum_flush(3)
}
.elsewhen(bubble_num === 4.U){
next_pnum(2)(1) := io.pnum_flush(5)
next_pnum(2)(0) := io.pnum_flush(4)
}
.otherwise{
next_pnum(2)(1) := io.pnum_flush(6)
next_pnum(2)(0) := io.pnum_flush(5)
}
}
.otherwise{
next_pnum(2)(1) := 0.U
next_pnum(2)(0) := 0.U
}
when(io.flush_in_next_surf === 3.U){
when(bubble_num === 0.U){
next_pnum(3)(2) := io.pnum_flush(2)
next_pnum(3)(1) := io.pnum_flush(1)
next_pnum(3)(0) := io.pnum_flush(0)
}
.elsewhen(bubble_num === 1.U){
next_pnum(3)(2) := io.pnum_flush(3)
next_pnum(3)(1) := io.pnum_flush(2)
next_pnum(3)(0) := io.pnum_flush(1)
}
.elsewhen(bubble_num === 2.U){
next_pnum(3)(2) := io.pnum_flush(4)
next_pnum(3)(1) := io.pnum_flush(3)
next_pnum(3)(0) := io.pnum_flush(2)
}
.elsewhen(bubble_num === 3.U){
next_pnum(3)(2) := io.pnum_flush(5)
next_pnum(3)(1) := io.pnum_flush(4)
next_pnum(3)(0) := io.pnum_flush(3)
}
.otherwise{
next_pnum(3)(2) := io.pnum_flush(6)
next_pnum(3)(1) := io.pnum_flush(5)
next_pnum(3)(0) := io.pnum_flush(4)
}
}
.otherwise{
next_pnum(3)(2) := 0.U
next_pnum(3)(1) := 0.U
next_pnum(3)(0) := 0.U
}
when(io.flush_in_next_surf === 4.U){
when(bubble_num === 0.U){
next_pnum(4)(3) := io.pnum_flush(3)
next_pnum(4)(2) := io.pnum_flush(2)
next_pnum(4)(1) := io.pnum_flush(1)
next_pnum(4)(0) := io.pnum_flush(0)
}
.elsewhen(bubble_num === 1.U){
next_pnum(4)(3) := io.pnum_flush(4)
next_pnum(4)(2) := io.pnum_flush(3)
next_pnum(4)(1) := io.pnum_flush(2)
next_pnum(4)(0) := io.pnum_flush(1)
}
.elsewhen(bubble_num === 2.U){
next_pnum(4)(3) := io.pnum_flush(5)
next_pnum(4)(2) := io.pnum_flush(4)
next_pnum(4)(1) := io.pnum_flush(3)
next_pnum(4)(0) := io.pnum_flush(2)
}
.otherwise{
next_pnum(4)(3) := io.pnum_flush(6)
next_pnum(4)(2) := io.pnum_flush(5)
next_pnum(4)(1) := io.pnum_flush(4)
next_pnum(4)(0) := io.pnum_flush(3)
}
}
.otherwise{
next_pnum(4)(3) := 0.U
next_pnum(4)(2) := 0.U
next_pnum(4)(1) := 0.U
next_pnum(4)(0) := 0.U
}
when(io.flush_in_next_surf === 5.U){
when(bubble_num === 0.U){
next_pnum(5)(4) := io.pnum_flush(4)
next_pnum(5)(3) := io.pnum_flush(3)
next_pnum(5)(2) := io.pnum_flush(2)
next_pnum(5)(1) := io.pnum_flush(1)
next_pnum(5)(0) := io.pnum_flush(0)
}
.elsewhen(bubble_num === 1.U){
next_pnum(5)(4) := io.pnum_flush(5)
next_pnum(5)(3) := io.pnum_flush(4)
next_pnum(5)(2) := io.pnum_flush(3)
next_pnum(5)(1) := io.pnum_flush(2)
next_pnum(5)(0) := io.pnum_flush(1)
}
.otherwise{
next_pnum(5)(4) := io.pnum_flush(6)
next_pnum(5)(3) := io.pnum_flush(5)
next_pnum(5)(2) := io.pnum_flush(4)
next_pnum(5)(1) := io.pnum_flush(3)
next_pnum(5)(0) := io.pnum_flush(2)
}
}
.otherwise{
next_pnum(5)(4) := 0.U
next_pnum(5)(3) := 0.U
next_pnum(5)(2) := 0.U
next_pnum(5)(1) := 0.U
next_pnum(5)(0) := 0.U
}
when(io.flush_in_next_surf === 6.U){
when(bubble_num === 0.U){
next_pnum(6)(5) := io.pnum_flush(5)
next_pnum(6)(4) := io.pnum_flush(4)
next_pnum(6)(3) := io.pnum_flush(3)
next_pnum(6)(2) := io.pnum_flush(2)
next_pnum(6)(1) := io.pnum_flush(1)
next_pnum(6)(0) := io.pnum_flush(0)
}
.otherwise{
next_pnum(6)(5) := io.pnum_flush(6)
next_pnum(6)(4) := io.pnum_flush(5)
next_pnum(6)(3) := io.pnum_flush(4)
next_pnum(6)(2) := io.pnum_flush(3)
next_pnum(6)(1) := io.pnum_flush(2)
next_pnum(6)(0) := io.pnum_flush(1)
}
}
.otherwise{
next_pnum(6)(5) := 0.U
next_pnum(6)(4) := 0.U
next_pnum(6)(3) := 0.U
next_pnum(6)(2) := 0.U
next_pnum(6)(1) := 0.U
next_pnum(6)(0) := 0.U
}
when(io.flush_in_next_surf === 7.U){
next_pnum(7)(6) := io.pnum_flush(6)
next_pnum(7)(5) := io.pnum_flush(5)
next_pnum(7)(4) := io.pnum_flush(4)
next_pnum(7)(3) := io.pnum_flush(3)
next_pnum(7)(2) := io.pnum_flush(2)
next_pnum(7)(1) := io.pnum_flush(1)
next_pnum(7)(0) := io.pnum_flush(0)
}
.otherwise{
next_pnum(7)(6) := 0.U
next_pnum(7)(5) := 0.U
next_pnum(7)(4) := 0.U
next_pnum(7)(3) := 0.U
next_pnum(7)(2) := 0.U
next_pnum(7)(1) := 0.U
next_pnum(7)(0) := 0.U
}
val bubble_add_reg = RegInit("b0".asUInt(3.W))
//default case
bubble_add_reg := 0.U
//begin
for(i <- 2 to 7){
when(io.flush_in_next_surf === i.U){
for(j <- 0 to i-1){
when(VecInit((0 to 5) map { k => (io.up_pnum(k) === next_pnum(i)(j))}).asUInt.orR){
bubble_add_reg := (j+1).U
}
}
}
}
io.bubble_add := bubble_add_reg
}}
class NV_NVDLA_PDP_CORE_CAL2D_mem_rd(implicit val conf: nvdlaConfig) extends Module {
val io = IO(new Bundle {
//clk
val nvdla_core_clk = Input(Clock())
val load_din = Input(Bool())
val wr_line_dat_done = Input(Bool())
val unit2d_en = Input(Vec(8, Bool()))
val unit2d_set = Input(Vec(8, Bool()))
val buffer_lines_num = Input(UInt(4.W))
val wr_sub_lbuf_cnt = Input(UInt(3.W))
val mem_re = Output(Vec(4, Vec(8, Bool())))
val mem_re_1st = Output(Vec(4, Vec(8, Bool())))
val mem_re_sel = Output(Vec(4, Bool()))
})
//
// ┌─┐ ┌─┐
// ┌──┘ ┴───────┘ ┴──┐
// │ │
// │ ─── │
// │ ─┬┘ └┬─ │
// │ │
// │ ─┴─ │
// │ │
// └───┐ ┌───┘
// │ │
// │ │
// │ │
// │ └──────────────┐
// │ │
// │ ├─┐
// │ ┌─┘
// │ │
// └─┐ ┐ ┌───────┬──┐ ┌──┘
// │ ─┤ ─┤ │ ─┤ ─┤
// └──┴──┘ └──┴──┘
withClock(io.nvdla_core_clk){
val mem_re_sel_reg = RegInit(VecInit(Seq.fill(4)(false.B)))
mem_re_sel_reg(0) := io.buffer_lines_num === 1.U
mem_re_sel_reg(1) := io.buffer_lines_num === 2.U
mem_re_sel_reg(2) := (io.buffer_lines_num === 3.U) | (io.buffer_lines_num === 4.U)
mem_re_sel_reg(3) := io.buffer_lines_num === 5.U
for(i <- 0 to 3){
io.mem_re_sel(i) := mem_re_sel_reg(i)
}
//memory read
//mem bank0 enable
//
//memory first read
val unit2d_mem_1strd = RegInit(VecInit(Seq.fill(8)(false.B)))
for(i <- 0 to 7){
unit2d_mem_1strd(i) := Mux(io.unit2d_set(i), true.B,
Mux(io.wr_line_dat_done, false.B,
unit2d_mem_1strd(i)))
}
//line buffer number 1
for(i <- 0 to 7){
io.mem_re(0)(i) := io.unit2d_en(0) & io.load_din & (io.wr_sub_lbuf_cnt === i.U) & mem_re_sel_reg(0)
io.mem_re_1st(0)(i) := unit2d_mem_1strd(0) & mem_re_sel_reg(0)
}
//line buffer number 2
//4 bank read enable
for(i <- 0 to 3){
io.mem_re(1)(i) := io.unit2d_en(0) & io.load_din & (io.wr_sub_lbuf_cnt === i.U) & mem_re_sel_reg(1)
io.mem_re_1st(1)(i) := unit2d_mem_1strd(0) & mem_re_sel_reg(1)
}
for(i <- 4 to 7){
io.mem_re(1)(i) := io.unit2d_en(1) & io.load_din & (io.wr_sub_lbuf_cnt === (i-4).U) & mem_re_sel_reg(1)
io.mem_re_1st(1)(i) := unit2d_mem_1strd(1) & mem_re_sel_reg(1)
}
//line buffer number 3 4
for(i <- 0 to 1){
io.mem_re(2)(i) := io.unit2d_en(0) & io.load_din & (io.wr_sub_lbuf_cnt === i.U) & mem_re_sel_reg(2)
io.mem_re_1st(2)(i) := unit2d_mem_1strd(0) & mem_re_sel_reg(2)
}
for(i <- 2 to 3){
io.mem_re(2)(i) := io.unit2d_en(1) & io.load_din & (io.wr_sub_lbuf_cnt === (i-2).U) & mem_re_sel_reg(2)
io.mem_re_1st(2)(i) := unit2d_mem_1strd(1) & mem_re_sel_reg(2)
}
for(i <- 4 to 5){
io.mem_re(2)(i) := io.unit2d_en(2) & io.load_din & (io.wr_sub_lbuf_cnt === (i-4).U) & mem_re_sel_reg(2)
io.mem_re_1st(2)(i) := unit2d_mem_1strd(2) & mem_re_sel_reg(2)
}
for(i <- 6 to 7){
io.mem_re(2)(i) := io.unit2d_en(3) & io.load_din & (io.wr_sub_lbuf_cnt === (i-6).U) & mem_re_sel_reg(2)
io.mem_re_1st(2)(i) := unit2d_mem_1strd(3) & mem_re_sel_reg(2)
}
//line buffer 5 6 7 8
for(i <- 0 to 7){
io.mem_re(3)(i) := io.unit2d_en(i) & io.load_din & (io.wr_sub_lbuf_cnt === 0.U) & mem_re_sel_reg(3)
io.mem_re_1st(3)(i) := unit2d_mem_1strd(i) & mem_re_sel_reg(3)
}
}}
class NV_NVDLA_PDP_CORE_CAL2D_rd_control_in_disable_time(implicit val conf: nvdlaConfig) extends Module {
val io = IO(new Bundle {
//clk
val nvdla_core_clk = Input(Clock())
val line_end = Input(Bool())
val cur_datin_disable = Input(Bool())
val wr_surface_dat_done = Input(Bool())
val wr_line_dat_done = Input(Bool())
val wr_sub_lbuf_cnt = Input(UInt(3.W))
val last_out_en = Input(Bool())
val one_width_norm_rdy = Input(Bool())
val load_din = Input(Bool())
val load_din_all = Input(Bool())
val wr_data_stage0_prdy = Input(Bool())
val wr_data_stage1_prdy = Input(Bool())
val load_wr_stage1 = Input(Bool())
val load_wr_stage1_all = Input(Bool())
val load_wr_stage2 = Input(Bool())
val load_wr_stage2_all = Input(Bool())
val unit2d_cnt_pooling = Input(UInt(3.W))
val unit2d_cnt_pooling_max = Input(UInt(3.W))
val mem_re_sel = Input(Vec(4, Bool()))
val mem_data_lst = Input(Vec(8, UInt((conf.NVDLA_PDP_THROUGHPUT * (conf.NVDLA_PDP_BWPE+6) + 3).W)))
val mem_re_last_2d = Output(UInt(8.W))
val flush_read_en = Output(Bool())
val mem_re_last = Output(UInt(8.W))
val pout_mem_data_last = Output(UInt((conf.NVDLA_PDP_THROUGHPUT * (conf.NVDLA_PDP_BWPE+6) + 3).W))
})
//
// ┌─┐ ┌─┐
// ┌──┘ ┴───────┘ ┴──┐
// │ │
// │ ─── │
// │ ─┬┘ └┬─ │
// │ │
// │ ─┴─ │
// │ │
// └───┐ ┌───┘
// │ │
// │ │
// │ │
// │ └──────────────┐
// │ │
// │ ├─┐
// │ ┌─┘
// │ │
// └─┐ ┐ ┌───────┬──┐ ┌──┘
// │ ─┤ ─┤ │ ─┤ ─┤
// └──┴──┘ └──┴──┘
withClock(io.nvdla_core_clk){
val unit2d_cnt_pooling_last = RegInit("b0".asUInt(3.W))
val mem_re1_sel_last = RegInit(false.B)
val mem_re2_sel_last = RegInit(false.B)
val mem_re3_sel_last = RegInit(false.B)
val unit2d_cnt_pooling_last_end = Wire(Bool())
when(io.wr_surface_dat_done){
unit2d_cnt_pooling_last := Mux(io.unit2d_cnt_pooling === io.unit2d_cnt_pooling_max, "d0".asUInt(3.W), io.unit2d_cnt_pooling + 1.U)
mem_re1_sel_last := io.mem_re_sel(1)
mem_re2_sel_last := io.mem_re_sel(2)
mem_re3_sel_last := io.mem_re_sel(3)
}
.elsewhen(((io.line_end & io.cur_datin_disable) | (io.wr_line_dat_done & io.last_out_en)) & io.one_width_norm_rdy){
when(unit2d_cnt_pooling_last_end){
unit2d_cnt_pooling_last := 0.U
}
.otherwise{
unit2d_cnt_pooling_last := unit2d_cnt_pooling_last + 1.U
}
}
unit2d_cnt_pooling_last_end := (unit2d_cnt_pooling_last === io.unit2d_cnt_pooling_max)
io.flush_read_en := (io.cur_datin_disable | io.last_out_en) & io.one_width_norm_rdy
val unit2d_en_last = VecInit((0 to 7) map { i => io.flush_read_en & (unit2d_cnt_pooling_last === i.U)})
val mem_re1_last = Wire(Vec(8, Bool()))
for(i <- 0 to 3){
mem_re1_last(i) := unit2d_en_last(0) & (io.wr_sub_lbuf_cnt === i.U) & mem_re1_sel_last
}
for(i <- 4 to 7){
mem_re1_last(i) := unit2d_en_last(1) & (io.wr_sub_lbuf_cnt === (i-4).U) & mem_re1_sel_last
}
val mem_re2_last = Wire(Vec(8, Bool()))
for(i <- 0 to 1){
mem_re2_last(i) := unit2d_en_last(0) & (io.wr_sub_lbuf_cnt === i.U) & mem_re2_sel_last
}
for(i <- 2 to 3){
mem_re2_last(i) := unit2d_en_last(1) & (io.wr_sub_lbuf_cnt === (i-2).U) & mem_re2_sel_last
}
for(i <- 4 to 5){
mem_re2_last(i) := unit2d_en_last(2) & (io.wr_sub_lbuf_cnt === (i-4).U) & mem_re2_sel_last
}
for(i <- 6 to 7){
mem_re2_last(i) := unit2d_en_last(3) & (io.wr_sub_lbuf_cnt === (i-6).U) & mem_re2_sel_last
}
val mem_re3_last = Wire(Vec(8, Bool()))
for(i <- 0 to 7){
mem_re3_last(i) := unit2d_en_last(i) & (io.wr_sub_lbuf_cnt === 0.U) & mem_re3_sel_last
}
io.mem_re_last := mem_re1_last.asUInt | mem_re2_last.asUInt | mem_re3_last.asUInt
val flush_read_en_d = RegInit(false.B)
when((io.load_din & io.mem_re_last.orR)| (io.cur_datin_disable & io.one_width_norm_rdy)){
flush_read_en_d := io.flush_read_en
}
val mem_re_last_d = RegInit("b0".asUInt(8.W))
when((io.load_din)| (io.cur_datin_disable & io.one_width_norm_rdy)){
mem_re_last_d := io.mem_re_last
}
//2d
val unit2d_cnt_pooling_last_d = RegInit("b0".asUInt(3.W))
when((io.load_din & io.mem_re_last.orR)| (io.cur_datin_disable & io.one_width_norm_rdy)){
unit2d_cnt_pooling_last_d := unit2d_cnt_pooling_last
}
val cur_datin_disable_d = RegInit(false.B)
when(io.load_din_all){
cur_datin_disable_d := io.cur_datin_disable
}
val one_width_disable_d = RegInit(false.B)
val mem_re_last_2d_reg = RegInit("b0".asUInt(8.W))
when(io.load_wr_stage1|(cur_datin_disable_d & io.wr_data_stage0_prdy)){
mem_re_last_2d_reg := mem_re_last_d
}
io.mem_re_last_2d := mem_re_last_2d_reg
//2d
val unit2d_cnt_pooling_last_2d = RegInit("b0".asUInt(3.W))
when((io.load_wr_stage1 & mem_re_last_d.orR)|(cur_datin_disable_d & io.wr_data_stage0_prdy)){
unit2d_cnt_pooling_last_2d := unit2d_cnt_pooling_last_d
}
val cur_datin_disable_2d = RegInit(false.B)
when(io.load_wr_stage1_all){
cur_datin_disable_2d := cur_datin_disable_d
}
val one_width_disable_2d = RegInit(false.B)
when(io.load_wr_stage1_all){
one_width_disable_2d := one_width_disable_d
}
//3d
val cur_datin_disable_3d = RegInit(false.B)
when(io.load_wr_stage2_all){
cur_datin_disable_3d := cur_datin_disable_2d
}
val one_width_disable_3d = RegInit(false.B)
when(io.load_wr_stage2_all){
one_width_disable_3d := one_width_disable_2d
}
//line buffer2
val pout_mem_data_sel_1_last = Wire(Vec(8, Bool()))
for(i <- 0 to 3){
pout_mem_data_sel_1_last(i) := (io.load_wr_stage2 | (cur_datin_disable_2d & io.wr_data_stage1_prdy)) &
mem_re_last_2d_reg(i) & (unit2d_cnt_pooling_last_2d === 0.U) & io.mem_re_sel(1);
}
for(i <- 4 to 7){
pout_mem_data_sel_1_last(i) := (io.load_wr_stage2 | (cur_datin_disable_2d & io.wr_data_stage1_prdy)) &
mem_re_last_2d_reg(i) & (unit2d_cnt_pooling_last_2d === 1.U) & io.mem_re_sel(1);
}
//line buffer3, 4
val pout_mem_data_sel_2_last = Wire(Vec(8, Bool()))
for(i <- 0 to 1){
pout_mem_data_sel_2_last(i) := (io.load_wr_stage2 | (cur_datin_disable_2d & io.wr_data_stage1_prdy)) &
mem_re_last_2d_reg(i) & (unit2d_cnt_pooling_last_2d === 0.U) & io.mem_re_sel(2);
}
for(i <- 2 to 3){
pout_mem_data_sel_2_last(i) := (io.load_wr_stage2 | (cur_datin_disable_2d & io.wr_data_stage1_prdy)) &
mem_re_last_2d_reg(i) & (unit2d_cnt_pooling_last_2d === 1.U) & io.mem_re_sel(2);
}
for(i <- 4 to 5){
pout_mem_data_sel_2_last(i) := (io.load_wr_stage2 | (cur_datin_disable_2d & io.wr_data_stage1_prdy)) &
mem_re_last_2d_reg(i) & (unit2d_cnt_pooling_last_2d === 2.U) & io.mem_re_sel(2);
}
for(i <- 6 to 7){
pout_mem_data_sel_2_last(i) := (io.load_wr_stage2 | (cur_datin_disable_2d & io.wr_data_stage1_prdy)) &
mem_re_last_2d_reg(i) & (unit2d_cnt_pooling_last_2d === 3.U) & io.mem_re_sel(2);
}
//line buffer 5,6,7,8
val pout_mem_data_sel_3_last = Wire(Vec(8, Bool()))
for(i <- 0 to 7){
pout_mem_data_sel_3_last(i) := (io.load_wr_stage2 | (cur_datin_disable_2d & io.wr_data_stage1_prdy)) &
mem_re_last_2d_reg(i) & (unit2d_cnt_pooling_last_2d === i.U) & io.mem_re_sel(3);
}
val pout_mem_data_sel_last = pout_mem_data_sel_3_last.asUInt | pout_mem_data_sel_2_last.asUInt | pout_mem_data_sel_1_last.asUInt
io.pout_mem_data_last := VecInit((0 to 7)
map {i => (io.mem_data_lst(i) & Fill((conf.NVDLA_PDP_THROUGHPUT * (conf.NVDLA_PDP_BWPE+6) + 3), pout_mem_data_sel_last(i)))}).reduce(_|_)
}}
|
nulano/mc-image-helper | src/main/java/me/itzg/helpers/sync/CopyingFileProcessor.java | package me.itzg.helpers.sync;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
@Slf4j
public class CopyingFileProcessor implements FileProcessor {
@Override
public void processFile(Path srcFile, Path destFile) throws IOException {
log.info("Copying {} -> {}", srcFile, destFile);
Files.copy(srcFile, destFile, COPY_ATTRIBUTES, REPLACE_EXISTING);
}
}
|
SpyrosDellas/algorithms-i | collinear/Test.java | /* *****************************************************************************
* Name:
* Date:
* Description:
**************************************************************************** */
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
double[] test = {
Double.NaN, Double.POSITIVE_INFINITY, +0.0, -0.0,
Double.NEGATIVE_INFINITY, 10, Double.NaN
};
double[] test1 = Arrays.copyOf(test, test.length);
QuickSortX.sort(test);
Arrays.sort(test1);
for (double d : test) {
System.out.print(d + " ");
}
System.out.println();
for (double d : test1) {
System.out.print(d + " ");
}
boolean less = -0.0 > 0.0;
System.out.println("\n" + less);
}
}
|
panfeiyy/ambari | ambari-server/src/main/java/org/apache/ambari/server/state/stack/upgrade/ExecuteHostType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ambari.server.state.stack.upgrade;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
/**
* The {@link ExecuteHostType} enum is used to represent where an
* {@link ExecuteTask} will run.
*/
@XmlEnum
public enum ExecuteHostType {
/**
* The term "master" can mean something unique to each service. In terms of
* where to run, this means calculate which is the "master" component and run
* it on that.
*/
@XmlEnumValue("master")
MASTER,
/**
* Run on a single host that satifies the condition of the {@link ExecuteTask}
* .
*/
@XmlEnumValue("any")
ANY,
/**
* Run on a single host that is picked by alphabetically sorting all hosts that satisfy the condition of the {@link ExecuteTask}
* .
*/
@XmlEnumValue("first")
FIRST,
/**
* Run on all of the hosts.
*/
@XmlEnumValue("all")
ALL;
}
|
lenxin/spring-security | oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolver.java | package org.springframework.security.oauth2.server.resource.web;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.Assert;
/**
* Generic resolver extracting pre-authenticated JWT identity from a custom header.
*
* @author <NAME>
* @since 5.2
*/
public class HeaderBearerTokenResolver implements BearerTokenResolver {
private String header;
public HeaderBearerTokenResolver(String header) {
Assert.hasText(header, "header cannot be empty");
this.header = header;
}
@Override
public String resolve(HttpServletRequest request) {
return request.getHeader(this.header);
}
}
|
lechium/tvOS142Headers | System/Library/Frameworks/MLCompute.framework/MLCActivationLayer.h | /*
* This header is generated by classdump-dyld 1.5
* on Tuesday, November 10, 2020 at 10:18:58 PM Mountain Standard Time
* Operating System: Version 14.2 (Build 18K57)
* Image Source: /System/Library/Frameworks/MLCompute.framework/MLCompute
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
#import <MLCompute/MLCLayer.h>
@class MLCActivationDescriptor;
@interface MLCActivationLayer : MLCLayer {
MLCActivationDescriptor* _descriptor;
}
@property (nonatomic,copy,readonly) MLCActivationDescriptor * descriptor; //@synthesize descriptor=_descriptor - In the implementation block
+(id)layerWithDescriptor:(id)arg1 ;
+(id)reluLayer;
+(id)relu6Layer;
+(id)leakyReLULayer;
+(id)leakyReLULayerWithNegativeSlope:(float)arg1 ;
+(id)linearLayerWithScale:(float)arg1 bias:(float)arg2 ;
+(id)sigmoidLayer;
+(id)hardSigmoidLayer;
+(id)tanhLayer;
+(id)absoluteLayer;
+(id)softPlusLayer;
+(id)softPlusLayerWithBeta:(float)arg1 ;
+(id)softSignLayer;
+(id)eluLayer;
+(id)eluLayerWithA:(float)arg1 ;
+(id)relunLayerWithA:(float)arg1 b:(float)arg2 ;
+(id)logSigmoidLayer;
+(id)seluLayer;
+(id)celuLayer;
+(id)celuLayerWithA:(float)arg1 ;
+(id)hardShrinkLayer;
+(id)hardShrinkLayerWithA:(float)arg1 ;
+(id)softShrinkLayer;
+(id)softShrinkLayerWithA:(float)arg1 ;
+(id)tanhShrinkLayer;
+(id)thresholdLayerWithThreshold:(float)arg1 replacement:(float)arg2 ;
+(id)geluLayer;
-(id)description;
-(MLCActivationDescriptor *)descriptor;
-(id)initWithDescriptor:(id)arg1 ;
-(BOOL)compileForDevice:(id)arg1 sourceTensors:(id)arg2 resultTensor:(id)arg3 ;
-(id)summarizedDOTDescription;
-(BOOL)isSupportedShapeForTensorSources:(id)arg1 ;
-(id)resultTensorFromSources:(id)arg1 ;
@end
|
wilsonGmn/pyrin | src/pyrin/security/manager.py | # -*- coding: utf-8 -*-
"""
security manager module.
"""
import pyrin.security.encryption.services as encryption_services
import pyrin.security.hashing.services as hashing_services
from pyrin.core.globals import _
from pyrin.core.structs import Manager
from pyrin.security import SecurityPackage
from pyrin.security.exceptions import InvalidPasswordLengthError, \
InvalidEncryptionTextLengthError
class SecurityManager(Manager):
"""
security manager class.
"""
package_class = SecurityPackage
def get_password_hash(self, password, **options):
"""
gets the given password's hash.
:param str password: password to get it's hash.
:keyword bool is_encrypted: specifies that given password is encrypted.
defaults to False if not provided.
:raises InvalidPasswordLengthError: invalid password length error.
:rtype: str
"""
if password is None or len(password) == 0:
raise InvalidPasswordLengthError(_('Input password has invalid length.'))
decrypted_password = password
is_encrypted = options.get('is_encrypted', False)
if is_encrypted is True:
decrypted_password = encryption_services.decrypt(password)
hashed_password = hashing_services.generate_hash(decrypted_password)
return hashed_password
def encrypt(self, text, **options):
"""
encrypts the given text and returns the encrypted value.
:param str text: text to be encrypted.
:raises InvalidEncryptionTextLengthError: invalid encryption text length error.
:rtype: str
"""
if text is None or len(text) == 0:
raise InvalidEncryptionTextLengthError(_('Input text has invalid length.'))
return encryption_services.encrypt(text)
|
takumihonda/AIP_realtime | python/3p_obs.py | <gh_stars>0
import sys
import numpy as np
from datetime import datetime
from tools_AIP import read_obs_grads, prep_proj_multi, read_nc_topo, read_mask, read_obs_grads_latlon
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.colors import BoundaryNorm
quick = True
def main( INFO, time_l=[], hgt=3000.0 ):
lon2d_4, lat2d_4, topo2d_4 = read_nc_topo( dom=4 )
mz1d, mlon2d, mlat2d = read_obs_grads_latlon()
mzidx = np.argmin( np.abs( mz1d - hgt ) )
mask = read_mask()
mask2d = mask[mzidx,:,:]
fig, (( ax1,ax2,ax3 )) = plt.subplots( 1, 3, figsize=( 13, 4.5 ) )
fig.subplots_adjust( left=0.05, bottom=0.03, right=0.96, top=0.95,
wspace=0.15, hspace=0.02)
ax_l = [ ax1, ax2, ax3, ]
if quick:
res = "l"
else:
res = "h"
lons = lon2d_4[0,0]
lone = lon2d_4[-1,-1]
lats = lat2d_4[0,0]
late = lat2d_4[-1,-1]
lon_0 = None
lat_0 = None
method = "merc"
lon_r = 139.609
lat_r = 35.861
res = 'l'
contc = "palegreen"
oc = "w"
m_l = prep_proj_multi( method, ax_l, fs=7, res=res, lw=0.0,
ll_lon=lons, ur_lon=lone, ll_lat=lats, ur_lat=late,
pdlon=0.5, pdlat=0.5, blon=lon_r, blat=lat_0,
contc=contc, oc=oc )
time = datetime( 2019, 8, 24, 15, 0, 30 )
obs3d, olon2d, olat2d, oz1d = read_obs_grads( INFO, itime=time )
ozidx = np.argmin( np.abs( oz1d - hgt ) )
# for pcolormesh
olon2d -= np.abs( olon2d[1,0] - olon2d[0,0] )
olat2d -= np.abs( olat2d[0,1] - olat2d[0,0] )
mlon2d -= np.abs( mlon2d[1,0] - mlon2d[0,0] )
mlat2d -= np.abs( mlat2d[0,1] - mlat2d[0,0] )
x2d, y2d = m_l[0]( olon2d, olat2d )
mx2d, my2d = m_l[0]( mlon2d, mlat2d )
x2d_, y2d_ = m_l[0]( lon2d_4, lat2d_4 )
levs_dbz= np.array( [ 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65 ] )
cmap_dbz = mcolors.ListedColormap(['cyan', 'b', 'dodgerblue',
'lime','yellow',
'orange', 'red', 'firebrick', 'magenta',
'purple'])
cmap_dbz.set_over('gray', alpha=1.0)
cmap_dbz.set_under('w', alpha=0.0)
i1d = np.arange( lon2d_4.shape[0] ) + 1.0
j1d = np.arange( lon2d_4.shape[1] ) + 1.0
i1d -= np.mean( i1d )
j1d -= np.mean( j1d )
# 0.5km mesh
j2d, i2d = np.meshgrid( i1d*0.5, j1d*0.5 )
dist2d = np.sqrt( np.square(i2d) + np.square(j2d) )
norm = BoundaryNorm( levs_dbz, ncolors=cmap_dbz.N, clip=False)
x_r, y_r = m_l[0]( lon_r, lat_r )
for i , ax in enumerate( ax_l ):
obs3d, _, _, _ = read_obs_grads( INFO, itime=time_l[i] )
ax.pcolormesh( x2d, y2d, obs3d[ozidx,:,: ],
cmap=cmap_dbz, vmin=np.min(levs_dbz),
vmax=np.max(levs_dbz),
norm=norm,
)
CONT = ax.contour( x2d_, y2d_, dist2d,
levels=[20, 40, 60], zorder=1,
colors='k', linewidths=0.5,
linestyles='dashed',
)
ax.clabel( CONT, CONT.levels, inline=True, #inline_spacing=1,
fontsize=8, fmt='%.0fkm', colors="k" )
ax.plot( x_r, y_r, ms=4.0, marker='o', color='r',
markeredgecolor='w' )
# ax.pcolormesh( mx2d, my2d, mask2d, )
plt.show()
############3
TOP = "/data_ballantine02/miyoshi-t/honda/SCALE-LETKF/AIP_D4_VERIFY"
EXP = "D4_500m_CTRL"
# data should be stored in EXP/[time0]/dafcst
time0 = datetime( 2019, 8, 24, 15, 0, 0 )
INFO = { "TOP": TOP,
"EXP": EXP,
"time0": time0,
}
time_l = [
datetime( 2019, 8, 24, 15, 20),
datetime( 2019, 8, 24, 15, 40),
datetime( 2019, 8, 24, 16, 0),
]
hgt = 3000.0
main( INFO, time_l=time_l, hgt=hgt )
|
enfoTek/tomato.linksys.e2000.nvram-mod | release/src/linux/linux/include/config/mtd/jedec.h | #undef CONFIG_MTD_JEDEC
|
SuperMap/iClient-for-JavaScript | libs/SuperMap/Format/WFST/v1_0_0.js | <filename>libs/SuperMap/Format/WFST/v1_0_0.js
/* COPYRIGHT 2012 SUPERMAP
* 本程序只能在有效的授权许可下使用。
* 未经许可,不得以任何手段擅自使用或传播。*/
/**
* @requires SuperMap/Format/WFST/v1.js
* @requires SuperMap/Format/Filter/v1_0_0.js
*/
/**
* Class: SuperMap.Format.WFST.v1_0_0
* 创建WFS1.0.0版本处理(transactions)的格式类。
* 通过 <SuperMap.Format.WFST.v1_0_0> 构造函数创建一个新实例。
*
* Inherits from:
* - <SuperMap.Format.Filter.v1_0_0>
* - <SuperMap.Format.WFST.v1>
*/
SuperMap.Format.WFST.v1_0_0 = SuperMap.Class(
SuperMap.Format.Filter.v1_0_0, SuperMap.Format.WFST.v1, {
/**
* Property: version
* {String} WFS version number.
*/
version: "1.0.0",
/**
* APIProperty: srsNameInQuery
* {Boolean} 设置为true时,参考系通过"srsName"属性被传递到Query请求的
* "wfs:Query"元素节点,这个属性默认为false因为它不被WFS1.0.0版本所
* 支持。
*/
srsNameInQuery: false,
/**
* Property: schemaLocations
* {Object} Properties are namespace aliases, values are schema locations.
*/
schemaLocations: {
"wfs": "http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd"
},
/**
* Constructor: SuperMap.Format.WFST.v1_0_0
* 用来解析和生成WFS1.0.0版本处理(transactions)的类。
*
* Parameters:
* options - {Object} 可选对象,其属性将被设置到实例。
*
* 有效的选项(options)属性:
* featureType - {String} 要素类型名(必要的),可以理解成数据集(不带数据
* 源前缀)。
* featureNS - {String} 要素的命名空间 (可选)。
* featurePrefix - {String} 要素的命名空间别名 (可选 - 只有当featureNS被提供
* 了才会被使用)。 默认值是 'feature'。可以理解成“数据源”。
* geometryName - {String} 几何图形属性名称。 默认值是 'the_geom'.
*/
initialize: function(options) {
SuperMap.Format.Filter.v1_0_0.prototype.initialize.apply(this, [options]);
SuperMap.Format.WFST.v1.prototype.initialize.apply(this, [options]);
},
/**
* Method: readNode
* Shorthand for applying one of the named readers given the node
* namespace and local name. Readers take two args (node, obj) and
* generally extend or modify the second.
*
* Parameters:
* node - {DOMElement} The node to be read (required).
* obj - {Object} The object to be modified (optional).
* first - {Boolean} Should be set to true for the first node read. This
* is usually the readNode call in the read method. Without this being
* set, auto-configured properties will stick on subsequent reads.
*
* Returns:
* {Object} The input object, modified (or a new one if none was provided).
*/
readNode: function(node, obj, first) {
// Not the superclass, only the mixin classes inherit from
// Format.GML.v2. We need this because we don't want to get readNode
// from the superclass's superclass, which is SuperMap.Format.XML.
return SuperMap.Format.GML.v2.prototype.readNode.apply(this, [node, obj]);
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"wfs": SuperMap.Util.applyDefaults({
"WFS_TransactionResponse": function(node, obj) {
obj.insertIds = [];
obj.success = false;
this.readChildNodes(node, obj);
},
"InsertResult": function(node, container) {
var obj = {fids: []};
this.readChildNodes(node, obj);
container.insertIds.push(obj.fids[0]);
},
"TransactionResult": function(node, obj) {
this.readChildNodes(node, obj);
},
"Status": function(node, obj) {
this.readChildNodes(node, obj);
},
"SUCCESS": function(node, obj) {
obj.success = true;
}
}, SuperMap.Format.WFST.v1.prototype.readers["wfs"]),
"gml": SuperMap.Format.GML.v2.prototype.readers["gml"],
"feature": SuperMap.Format.GML.v2.prototype.readers["feature"],
"ogc": SuperMap.Format.Filter.v1_0_0.prototype.readers["ogc"]
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"wfs": SuperMap.Util.applyDefaults({
"Query": function(options) {
options = SuperMap.Util.extend({
featureNS: this.featureNS,
featurePrefix: this.featurePrefix,
featureType: this.featureType,
srsName: this.srsName,
srsNameInQuery: this.srsNameInQuery
}, options);
var prefix = options.featurePrefix;
var node = this.createElementNSPlus("wfs:Query", {
attributes: {
typeName: (prefix ? prefix + ":" : "") +
options.featureType
}
});
if(options.srsNameInQuery && options.srsName) {
node.setAttribute("srsName", options.srsName);
}
if(options.featureNS) {
node.setAttribute("xmlns:" + prefix, options.featureNS);
}
if(options.propertyNames) {
for(var i=0,len = options.propertyNames.length; i<len; i++) {
this.writeNode(
"ogc:PropertyName",
{property: options.propertyNames[i]},
node
);
}
}
if(options.filter) {
this.setFilterProperty(options.filter);
this.writeNode("ogc:Filter", options.filter, node);
}
return node;
}
}, SuperMap.Format.WFST.v1.prototype.writers["wfs"]),
"gml": SuperMap.Format.GML.v2.prototype.writers["gml"],
"feature": SuperMap.Format.GML.v2.prototype.writers["feature"],
"ogc": SuperMap.Format.Filter.v1_0_0.prototype.writers["ogc"]
},
CLASS_NAME: "SuperMap.Format.WFST.v1_0_0"
});
|
LiteraturePro/test | app/src/main/java/cn/ovzv/idioms/navigation/main/Main_couplet.java | package cn.ovzv.idioms.navigation.main;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.umeng.commonsdk.debug.D;
import java.util.HashMap;
import java.util.Map;
import cn.leancloud.LCCloud;
import cn.ovzv.idioms.R;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
public class Main_couplet extends AppCompatActivity implements View.OnTouchListener{
private TextView mTextView;
private ImageView mImageView;
private ViewFlipper viewFlipper;
private float startX; //手指按下时的x坐标
private float endX; //手指抬起时的x坐标
private float moveX = 100f; //判断是否切换页面的标准值
private GestureDetector gestureDetector; //创建手势监听器
private JSONArray DataJSONArray;
private View mGridView;
private LinearLayout mLinearLayout_right,mLinearLayout_left;//对应于主布局中用来添加子布局的View
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main_couplet);
initView();
}
/**
* 设置view
* */
public void initView(){
mTextView = (TextView) findViewById(R.id.title);
mTextView.setText("成语对联");
mImageView = (ImageView)findViewById(R.id.back);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
viewFlipper.addView(createViewWithXml(), viewFlipper.getChildCount());
viewFlipper.setOnTouchListener(this);
gestureDetector = new GestureDetector(this, new MyGestureListener());
}
/**
* 自定义手势监听类
*/
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e2.getX() - e1.getX() > moveX) {
viewFlipper.setInAnimation(Main_couplet.this, R.anim.left_in);
viewFlipper.setOutAnimation(Main_couplet.this, R.anim.right_out);
viewFlipper.showPrevious();
} else if (e2.getX() - e1.getX() < moveX) {
viewFlipper.removeAllViews();
viewFlipper.addView(createViewWithXml(), viewFlipper.getChildCount());
viewFlipper.setInAnimation(Main_couplet.this, R.anim.right_in);
viewFlipper.setOutAnimation(Main_couplet.this, R.anim.left_out);
viewFlipper.showNext();
}
return true;
}
}
/**
* 触摸监听事件
*
* @param v
* @param event
* @return
*/
@Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
private View createViewWithXml() {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMarginEnd(40);
lp.setMarginStart(40);
View view = LayoutInflater.from(this).inflate(R.layout.fragment_main_couplet_item, null);//也可以从XML中加载布局
view.setLayoutParams(lp);//设置布局参数
// 构建传递给服务端的参数字典
Map<String, Object> dicParameters = new HashMap<>();
dicParameters.put("test", "test");
// 调用指定名称的云函数 averageStars,并且传递参数(默认不使用缓存)
LCCloud.callFunctionInBackground("DB_Get_couplet", dicParameters).subscribe(new Observer<Object>() {
@Override
public void onSubscribe(Disposable disposable) {
}
@Override
public void onNext(Object object) {
// succeed.
JSONObject json = (JSONObject) JSONObject.toJSON(object);
DataJSONArray = json.getJSONArray("data");
// 楷体
AssetManager mgr = getAssets();
Typeface tf = Typeface.createFromAsset(mgr, "fonts/kaiti_GB2312.ttf");
mLinearLayout_left = (LinearLayout) findViewById(R.id.study_words_left);
mLinearLayout_right = (LinearLayout) findViewById(R.id.study_words_right);
char left_str[] = DataJSONArray.get(0).toString().toCharArray();//利用toCharArray方法转换
for (int j = 0; j < left_str.length; j++) {
System.out.println(left_str[j]);
mGridView = View.inflate(getApplicationContext(), R.layout.fragment_main_study_words, null);
TextView txt = mGridView.findViewById(R.id.words_text);
txt.setText(String.valueOf(left_str[j]));
txt.setTextSize(40);
txt.setTypeface(tf);
mLinearLayout_left.addView(mGridView, 140, 140);
}
char right_str[] = DataJSONArray.get(1).toString().toCharArray();//利用toCharArray方法转换
for (int j = 0; j < right_str.length; j++) {
System.out.println(right_str[j]);
mGridView = View.inflate(getApplicationContext(), R.layout.fragment_main_study_words, null);
TextView txt = mGridView.findViewById(R.id.words_text);
txt.setText(String.valueOf(right_str[j]));
txt.setTextSize(40);
txt.setTypeface(tf);
mLinearLayout_right.addView(mGridView, 140, 140);
}
}
@Override
public void onError(Throwable throwable) {
// failed.
}
@Override
public void onComplete() {
}
});
return view;
}
} |
ScalablyTyped/SlinkyTyped | s/styled-system/src/main/scala/typingsSlinky/styledSystem/mod/FlexBasisProps.scala | <reponame>ScalablyTyped/SlinkyTyped<filename>s/styled-system/src/main/scala/typingsSlinky/styledSystem/mod/FlexBasisProps.scala
package typingsSlinky.styledSystem.mod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait FlexBasisProps[ThemeType /* <: Theme[TLengthStyledSystem] */, TVal] extends StObject {
// TODO: The FlexBasisValue currently really only exists for documentation
// purposes, because flex-basis also accepts `Nem` and `Npx` strings.
// Not sure there’s a way to still have the union values show up as
// auto-completion results.
var flexBasis: js.UndefOr[ResponsiveValue[TVal, ThemeType]] = js.native
}
object FlexBasisProps {
@scala.inline
def apply[ThemeType /* <: Theme[TLengthStyledSystem] */, TVal](): FlexBasisProps[ThemeType, TVal] = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[FlexBasisProps[ThemeType, TVal]]
}
@scala.inline
implicit class FlexBasisPropsMutableBuilder[Self <: FlexBasisProps[_, _], ThemeType /* <: Theme[TLengthStyledSystem] */, TVal] (val x: Self with (FlexBasisProps[ThemeType, TVal])) extends AnyVal {
@scala.inline
def setFlexBasis(value: ResponsiveValue[TVal, ThemeType]): Self = StObject.set(x, "flexBasis", value.asInstanceOf[js.Any])
@scala.inline
def setFlexBasisNull: Self = StObject.set(x, "flexBasis", null)
@scala.inline
def setFlexBasisUndefined: Self = StObject.set(x, "flexBasis", js.undefined)
@scala.inline
def setFlexBasisVarargs(value: (TVal | Null)*): Self = StObject.set(x, "flexBasis", js.Array(value :_*))
}
}
|
chobberoni/typos | node_modules/chromatic/node_modules/.cache/esm/e5775dbc34e7ddee.js | <reponame>chobberoni/typos
let HTTPClient;_34e.x([["default",()=>GraphQLClient]]);_34e.w("./HTTPClient",[["default",["HTTPClient"],function(v){HTTPClient=v}]]);
class GraphQLClient {
constructor({ uri, ...httpClientOptions }) {
if (!uri) throw new Error('Option `uri` required.');
this.uri = uri;
this.client = new HTTPClient(httpClientOptions);
this.headers = { 'Content-Type': 'application/json' };
}
setAuthorization(token) {
this.headers.Authorization = `Bearer ${token}`;
}
async runQuery(query, variables, headers) {
const response = await this.client.fetch(this.uri, {
body: JSON.stringify({ query, variables }),
headers: { ...this.headers, ...headers },
method: 'post',
});
const { data, errors } = await response.json();
if (errors) {
if (Array.isArray(errors)) {
errors.forEach(err => {
// eslint-disable-next-line no-param-reassign
err.name = err.name || 'GraphQLError';
// eslint-disable-next-line no-param-reassign
err.at = `${err.path.join('.')} ${err.locations
.map(l => `${l.line}:${l.column}`)
.join(', ')}`;
});
throw errors.length === 1 ? errors[0] : errors;
}
throw errors;
}
return data;
}
// Convenience static method.
static async runQuery(options, query, variables) {
return new GraphQLClient(options).runQuery(query, variables);
}
}
|
jumski/alle_api | db/migrate/20130523114135_increase_limits_on_source_fields.rb | class IncreaseLimitsOnSourceFields < ActiveRecord::Migration
def up
change_column :alle_api_post_buy_forms, :source, :text
change_column :alle_api_payments, :source, :text
end
def down
change_column :alle_api_post_buy_forms, :source, :string, limit: 2000
change_column :alle_api_payments, :source, :string, limit: 2000
end
end
|
germix/sanos | utils/emul/src/msvcrt/malloc.c | #include "msvcrt.h"
void *_malloc(size_t size)
{
return malloc(size);
}
void *_calloc(size_t num, size_t size)
{
return calloc(num, size);
}
void *_realloc(void *mem, size_t size)
{
return realloc(mem, size);
}
void _free(void *mem)
{
free(mem);
}
|
yuanhawk/InfoSys1D | PUG/app/src/main/java/tech/sutd/pickupgame/di/data/RoomModule.java | package tech.sutd.pickupgame.di.data;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import tech.sutd.pickupgame.data.AppExecutors;
import tech.sutd.pickupgame.data.DataManager;
import tech.sutd.pickupgame.data.ui.helper.PastRoomHelper;
import tech.sutd.pickupgame.data.ui.helper.UpcomingRoomHelper;
import tech.sutd.pickupgame.data.ui.helper.UserRoomHelper;
import tech.sutd.pickupgame.data.ui.new_activity.NewRoom;
import tech.sutd.pickupgame.data.ui.past_activity.PastRoom;
import tech.sutd.pickupgame.data.ui.upcoming_activity.UpcomingRoom;
import tech.sutd.pickupgame.data.ui.user.UserDao;
import tech.sutd.pickupgame.data.ui.user.UserDatabase;
import tech.sutd.pickupgame.data.ui.user.UserRoom;
import tech.sutd.pickupgame.data.ui.your_activity.YourRoom;
import tech.sutd.pickupgame.data.AppDataManager;
import tech.sutd.pickupgame.data.ui.helper.YourRoomHelper;
import tech.sutd.pickupgame.data.ui.your_activity.YourDatabase;
import tech.sutd.pickupgame.data.ui.helper.NewRoomHelper;
import tech.sutd.pickupgame.models.User;
@Module(includes = {RoomDatabaseModule.class})
public class RoomModule {
@Singleton
@Provides
static DataManager provideDataManager(YourRoomHelper yourRoomHelper, UserRoomHelper userRoomHelper,
NewRoomHelper newRoomHelper, UpcomingRoomHelper upcomingRoomHelper,
PastRoomHelper pastRoomHelper) {
return new AppDataManager(yourRoomHelper, userRoomHelper, newRoomHelper, upcomingRoomHelper, pastRoomHelper);
}
@Singleton
@Provides
static NewRoomHelper provideNewRoomHelper(NewRoom helper) {
return helper;
}
@Singleton
@Provides
static YourRoomHelper provideYourRoomHelper(YourRoom helper) {
return helper;
}
@Singleton
@Provides
static UserRoomHelper provideUserRoomHelper(UserRoom helper) {
return helper;
}
@Singleton
@Provides
static UpcomingRoomHelper provideUpcomingRoomHelper(UpcomingRoom helper) {
return helper;
}
@Singleton
@Provides
static PastRoomHelper pastRoomHelper(PastRoom helper) {
return helper;
}
}
|
gagandeepkalra/dotty | tests/run/main-annotation-birthday.scala | <reponame>gagandeepkalra/dotty<filename>tests/run/main-annotation-birthday.scala
import scala.annotation.newMain
/**
* Wishes a happy birthday to lucky people!
*
* @param age the age of the people whose birthday it is
* @param name the name of the luckiest person!
* @param others all the other lucky people
*/
@newMain def happyBirthday(age: Int, name: String, others: String*) =
val suffix =
age % 100 match
case 11 | 12 | 13 => "th"
case _ =>
age % 10 match
case 1 => "st"
case 2 => "nd"
case 3 => "rd"
case _ => "th"
val bldr = new StringBuilder(s"Happy $age$suffix birthday, $name")
for other <- others do bldr.append(" and ").append(other)
println(bldr)
object Test:
def callMain(args: Array[String]): Unit =
val clazz = Class.forName("happyBirthday")
val method = clazz.getMethod("main", classOf[Array[String]])
method.invoke(null, args)
def main(args: Array[String]): Unit =
callMain(Array("23", "Lisa", "Peter"))
end Test
|
yu3mars/proconVSCodeGcc | atcoder/abc/abc118/b.cpp | <gh_stars>0
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1};
int main(){
int n,m,ans=0;
cin>>n>>m;
bool ls[30][30];
for(int i = 0; i < 30; i++)
{
for(int j = 0; j < 30; j++)
{
ls[i][j]=false;
}
}
for(int person = 0; person < n; person++)
{
int k;
cin>>k;
for(int i = 0; i < k; i++)
{
int a;
cin>>a;
a--;
ls[person][a]=true;
}
}
for(int food = 0; food < m; food++)
{
bool ok = true;
for(int person = 0; person < n; person++)
{
if(ls[person][food]==false)
{
ok=false;
break;
}
}
if(ok) ans++;
}
cout<<ans<<endl;
return 0;
} |
ThorntonMatthewD/caseflow | app/models/appeal_series.rb | <reponame>ThorntonMatthewD/caseflow
# frozen_string_literal: true
class AppealSeries < CaseflowRecord
has_many :appeals, class_name: "LegacyAppeal", dependent: :nullify
# Timeliness is returned as a range of integer months from 50 to 84.1%tile.
# TODO: Replace these hardcoded values with dynamic data
SOC_TIMELINESS = [10, 26].freeze # 75%tile = 20
SSOC_TIMELINESS = [5, 13].freeze # 75%tile = 10
CERTIFICATION_TIMELINESS = [2, 8].freeze # 75%tile = 5
DECISION_TIMELINESS = [1, 2].freeze # 75%tile = 1
REMAND_TIMELINESS = [16, 29].freeze # 75%tile = 25
REMAND_SSOC_TIMELINESS = [3, 11].freeze # 75%tile = 9
RETURN_TIMELINESS = [1, 2].freeze # 75%tile = 2
delegate :vacols_id,
:active?,
:type_code,
:representative_name,
:aod,
:ramp_election,
:eligible_for_ramp?,
:form9_date,
to: :latest_appeal
def vacols_ids
appeals.map(&:vacols_id)
end
def latest_appeal
@latest_appeal ||= fetch_latest_appeal
end
def api_sort_key
earliest_nod = appeals.map(&:nod_date).compact.min
earliest_nod ? earliest_nod.in_time_zone.to_f : Float::INFINITY
end
def location
%w[Advance Remand].include?(latest_appeal.status) ? :aoj : :bva
end
def program
programs = appeals.flat_map { |appeal| appeal.issues.map(&:program) }.reject(&:nil?).uniq
(programs.length > 1) ? :multiple : programs.first
end
def aoj
appeals.lazy.flat_map(&:issues).map(&:aoj).find { |aoj| !aoj.nil? } || :other
end
def status
@status ||= fetch_status
end
def docket
@docket ||= fetch_docket
end
def docket_hash
docket.try(:to_hash)
end
def at_front
docket.try(:at_front)
end
# Appeals from the same series contain many of the same events. We unique them,
# using the property of AppealEvent that any two events with the same type and
# date are considered equal.
def events
appeals.flat_map(&:events).uniq.sort_by(&:date)
end
def alerts
@alerts ||= AppealSeriesAlerts.new(appeal_series: self).all
end
def issues
@issues ||= AppealSeriesIssues.new(appeal_series: self).all
end
def description
ordered_issues = latest_appeal.issues
.select(&:codes?)
.sort_by(&:vacols_sequence_id)
.partition(&:diagnostic_code).flatten
return "VA needs to record issues" if ordered_issues.empty?
marquee_issue_description = ordered_issues.first.friendly_description_without_new_material
return marquee_issue_description if issues.length == 1
comma = (marquee_issue_description.count(",") > 0) ? "," : ""
issue_count = issues.count - 1
"#{marquee_issue_description}#{comma} and #{issue_count} #{'other'.pluralize(issue_count)}"
end
def fetch_status
case latest_appeal.status
when "Advance"
disambiguate_status_advance
when "Active"
disambiguate_status_active
when "Complete"
disambiguate_status_complete
when "Remand"
disambiguate_status_remand
when "Motion"
:motion
when "CAVC"
:cavc
end
end
# rubocop:disable Metrics/CyclomaticComplexity
def fetch_details_for_status
case status
when :scheduled_hearing
hearing = latest_appeal.scheduled_hearings.min_by(&:scheduled_for)
{
date: hearing.scheduled_for.to_date,
type: hearing.readable_request_type.downcase,
location: hearing.request_type_location
}
when :pending_hearing_scheduling
{ type: latest_appeal.current_hearing_request_type }
when :pending_form9, :pending_certification, :pending_certification_ssoc
{
last_soc_date: last_soc_date,
certification_timeliness: CERTIFICATION_TIMELINESS.dup,
ssoc_timeliness: SSOC_TIMELINESS.dup
}
when :pending_soc
{ soc_timeliness: SOC_TIMELINESS.dup }
when :at_vso
{ vso_name: representative_name }
when :decision_in_progress
{ decisionTimeliness: DECISION_TIMELINESS.dup }
when :remand
{
issues: issues_for_last_decision,
remand_timeliness: REMAND_TIMELINESS.dup
}
when :remand_ssoc
{
last_soc_date: last_soc_date,
return_timeliness: RETURN_TIMELINESS.dup,
remand_ssoc_timeliness: REMAND_SSOC_TIMELINESS.dup
}
when :bva_decision
{ issues: issues_for_last_decision }
else
{}
end
end
# rubocop:enable Metrics/CyclomaticComplexity
private
def fetch_latest_appeal
latest_active_appeal_by_last_location_change_date || latest_appeal_by_decision_date
end
def latest_active_appeal_by_last_location_change_date
appeals.select(&:active?).max_by(&:last_location_change_date)
end
def latest_appeal_by_decision_date
# explicit cast to_i to allow for nil comparison with Time object
appeals.max_by { |appeal| appeal.decision_date.to_i }
end
def fetch_docket
return unless active? && %w[original post_remand].include?(type_code) && form9_date && !aod
DocketSnapshot.latest.docket_tracer_for_form9_date(form9_date)
end
def last_soc_date
events.reverse.detect { |event| [:soc, :ssoc].include? event.type }.date.to_date
end
def issues_for_last_decision
latest_appeal.issues.select { |issue| [:allowed, :remanded, :denied].include? issue.disposition }.map do |issue|
{
description: issue.friendly_description,
disposition: issue.disposition
}
end
end
def disambiguate_status_advance
if latest_appeal.certification_date
return :scheduled_hearing if latest_appeal.hearing_scheduled?
return :pending_hearing_scheduling if latest_appeal.hearing_pending?
return :on_docket
end
if latest_appeal.form9_date
return :pending_certification_ssoc if latest_appeal.ssoc_dates.present?
return :pending_certification
end
return :pending_form9 if latest_appeal.soc_date
:pending_soc
end
def disambiguate_status_active
return :scheduled_hearing if latest_appeal.hearing_scheduled?
case latest_appeal.location_code
when "49"
:stayed
when "55"
:at_vso
when "19", "20"
:bva_development
when "14", "16", "18", "24"
latest_appeal.case_assignment_exists ? :bva_development : :on_docket
else
latest_appeal.case_assignment_exists ? :decision_in_progress : :on_docket
end
end
def disambiguate_status_complete
case latest_appeal.disposition
when "Allowed", "Denied"
:bva_decision
when "Advance Allowed in Field", "Benefits Granted by AOJ"
:field_grant
when "Withdrawn", "Advance Withdrawn by Appellant/Rep",
"Recon Motion Withdrawn", "Withdrawn from Remand"
:withdrawn
when "Advance Failure to Respond", "Remand Failure to Respond"
:ftr
when "RAMP Opt-in"
:ramp
when "AMA SOC/SSOC Opt-in"
:statutory_opt_in
when "Dismissed, Death", "Advance Withdrawn Death of Veteran"
:death
when "Reconsideration by Letter"
:reconsideration
when "Merged Appeal"
:merged
else
:other_close
end
end
def disambiguate_status_remand
post_decision_ssocs = latest_appeal.ssoc_dates&.select { |ssoc| ssoc > latest_appeal.decision_date }
return :remand_ssoc if !post_decision_ssocs.empty?
:remand
end
end
|
DBatOWL/tutorials | core-java-modules/core-java-security-3/src/main/java/com/baeldung/hmac/HMACUtil.java | <filename>core-java-modules/core-java-security-3/src/main/java/com/baeldung/hmac/HMACUtil.java
package com.baeldung.hmac;
import org.apache.commons.codec.digest.HmacUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.SHA384Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class HMACUtil {
public static String hmacWithJava(String algorithm, String data, String key)
throws NoSuchAlgorithmException, InvalidKeyException {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(secretKeySpec);
return bytesToHex(mac.doFinal(data.getBytes()));
}
public static String hmacWithApacheCommons(String algorithm, String data, String key) {
String hmac = new HmacUtils(algorithm, key).hmacHex(data);
return hmac;
}
public static String hmacWithBouncyCastle(String algorithm, String data, String key) {
Digest digest = getHashDigest(algorithm);
HMac hMac = new HMac(digest);
hMac.init(new KeyParameter(key.getBytes()));
byte[] hmacIn = data.getBytes();
hMac.update(hmacIn, 0, hmacIn.length);
byte[] hmacOut = new byte[hMac.getMacSize()];
hMac.doFinal(hmacOut, 0);
return bytesToHex(hmacOut);
}
private static Digest getHashDigest(String algorithm) {
switch (algorithm) {
case "HmacMD5":
return new MD5Digest();
case "HmacSHA256":
return new SHA256Digest();
case "HmacSHA384":
return new SHA384Digest();
case "HmacSHA512":
return new SHA512Digest();
}
return new SHA256Digest();
}
public static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte h : hash) {
String hex = Integer.toHexString(0xff & h);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
|
tannnb/weibo | server/src/routes/profile.js | const router = require('koa-router')()
const { getToken } = require('../middlewares/loginCheck')
const {follow,getFollowers} = require('../controller/userRelationController')
router.prefix('/api/profile')
/**
* <获取当前用户下的粉丝>
*/
router.post('/follow',async (ctx,next) => {
const {id:myUserId} = await getToken(ctx)
const {userId:currentId} = ctx.request.body
ctx.body = await follow(myUserId,currentId)
})
/**
* <获取关注人>
*/
router.get('/followers',async (ctx,next) => {
const {id} = await getToken(ctx)
ctx.body = await getFollowers(id)
})
module.exports = router
|
neoremind/protostuff | protostuff-core/src/main/java/io/protostuff/LimitedInputStream.java | //========================================================================
//Copyright 2007-2010 <NAME> <EMAIL>
//------------------------------------------------------------------------
//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.
//========================================================================
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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 Google Inc. 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 io.protostuff;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An InputStream implementations which reads from some other InputStream but is limited to a particular number of
* bytes.
*
* @author <NAME>
* @created Jan 14, 2010
*/
public final class LimitedInputStream extends FilterInputStream
{
private int limit;
public LimitedInputStream(InputStream in)
{
super(in);
}
public LimitedInputStream(InputStream in, int limit)
{
super(in);
this.limit = limit;
}
LimitedInputStream limit(int limit)
{
this.limit = limit;
return this;
}
@Override
public int available() throws IOException
{
return Math.min(super.available(), limit);
}
@Override
public int read() throws IOException
{
if (limit <= 0)
{
return -1;
}
final int result = super.read();
if (result >= 0)
{
--limit;
}
return result;
}
@Override
public int read(final byte[] b, final int off, int len) throws IOException
{
if (limit <= 0)
{
return -1;
}
len = Math.min(len, limit);
final int result = super.read(b, off, len);
if (result >= 0)
{
limit -= result;
}
return result;
}
@Override
public long skip(final long n) throws IOException
{
final long result = super.skip(Math.min(n, limit));
if (result >= 0)
{
limit -= result;
}
return result;
}
}
|
w2fish/CSparse | Demo/cs_ex2.9.c | /* 20150402 */
/* test cs_compress2 */
#include "cs.h"
int main(int argc, char * argv[])
{
cs *T = NULL, *A = NULL ;
FILE *fp ;
char fileMatrix[256] = "fileMatrix" ;
/* read T from file */
fp = fopen(fileMatrix, "r") ;
T = cs_load(fp) ; /* load triplet matrix T from stdin */
fclose(fp);
if(!T)
{
printf("load T fail, quit\n") ;
return 1 ;
}
printf("T = \n") ; cs_print(T, 0) ;
/* create CSC from T , sorted, no duplicate, no numerically zero entry */
A = cs_compress2(T) ;
printf("A = \n") ; cs_print(A, 0) ;
/* release */
cs_spfree(T) ;
cs_spfree(A) ;
}
|
pscedu/slash2-next | slash2/slashd/coh.c | /* $Id$ */
/*
* %GPL_START_LICENSE%
* ---------------------------------------------------------------------
* Copyright 2008-2018, Pittsburgh Supercomputing Center
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License contained in the file
* `COPYING-GPL' at the top of this distribution or at
* https://www.gnu.org/licenses/gpl-2.0.html for more details.
* ---------------------------------------------------------------------
* %END_LICENSE%
*/
/*
* Routines for orchestrating coherency/properness across bmap lease
* assignments so e.g. multiple IOS do not get assigned.
*/
#include <time.h>
#include "pfl/atomic.h"
#include "pfl/cdefs.h"
#include "pfl/completion.h"
#include "pfl/ctlsvr.h"
#include "pfl/listcache.h"
#include "pfl/log.h"
#include "pfl/rpc.h"
#include "pfl/rsx.h"
#include "pfl/workthr.h"
#include "bmap.h"
#include "bmap_mds.h"
#include "cache_params.h"
#include "fidc_mds.h"
#include "rpc_mds.h"
#include "slashd.h"
#include "slashrpc.h"
#define SLM_CBARG_SLOT_CSVC 0
#define SLM_CBARG_SLOT_BML 1
/*
* Notify clients that a file/directory has been removed.
*/
void
slm_coh_delete_file(__unusedx struct fidc_membh *c)
{
}
void
slm_coh_bml_release(struct bmap_mds_lease *bml)
{
struct bmap_mds_info *bmi;
struct bmap *b;
bmi = bml->bml_bmi;
b = bmi_2_bmap(bmi);
BMAP_LOCK(b);
bmi->bmi_diocb--;
bml->bml_flags &= ~BML_DIOCB;
mds_bmap_bml_release(bml);
}
int
slm_rcm_bmapdio_cb(struct pscrpc_request *rq,
__unusedx struct pscrpc_async_args *a)
{
struct slrpc_cservice *csvc =
rq->rq_async_args.pointer_arg[SLM_CBARG_SLOT_CSVC];
struct bmap_mds_lease *bml =
rq->rq_async_args.pointer_arg[SLM_CBARG_SLOT_BML];
struct srm_bmap_dio_req *mq;
char buf[PSCRPC_NIDSTR_SIZE];
struct bmap_mds_info *bmi;
struct bmap *b;
int rc;
mq = pscrpc_msg_buf(rq->rq_reqmsg, 0, sizeof(*mq));
/*
* We need to retry if the RPC timed out or when the lease
* timeout, which ever comes first.
*/
SL_GET_RQ_STATUS_TYPE(csvc, rq, struct srm_bmap_dio_rep, rc);
if (rc && rc != -ENOENT)
goto out;
bmi = bml->bml_bmi;
b = bmi_2_bmap(bmi);
BMAP_LOCK(b);
bml->bml_flags |= BML_DIO;
BMAP_ULOCK(b);
out:
DEBUG_BMAP(rc ? PLL_WARN : PLL_DIAG, bml_2_bmap(bml),
"cli=%s seq=%"PRId64" rc=%d",
pscrpc_id2str(rq->rq_import->imp_connection->c_peer,
buf), mq->seq, rc);
slm_coh_bml_release(bml);
sl_csvc_decref(csvc);
return (0);
}
/*
* Request a lease holder to do direct I/O as the result of a
* conflicting access request.
*
* Note: @bml is unlocked upon return.
*/
int
mdscoh_req(struct bmap_mds_lease *bml)
{
struct slrpc_cservice *csvc = NULL;
struct pscrpc_request *rq = NULL;
struct srm_bmap_dio_req *mq;
struct srm_bmap_dio_rep *mp;
struct bmap_mds_info *bmi;
struct bmap *b;
int rc;
PFLOG_BML(PLL_DIAG, bml, "send BMAPDIO");
bmi = bml->bml_bmi;
b = bmi_2_bmap(bmi);
BMAP_LOCK_ENSURE(b);
if (bml->bml_flags & BML_RECOVER) {
psc_assert(!bml->bml_exp);
PFL_GOTOERR(out, rc = -PFLERR_NOTCONN);
}
psc_assert(bml->bml_exp);
csvc = slm_getclcsvc(bml->bml_exp, 0);
if (csvc == NULL)
PFL_GOTOERR(out, rc = -PFLERR_NOTCONN);
rc = SL_RSX_NEWREQ(csvc, SRMT_BMAPDIO, rq, mq, mp);
if (rc)
PFL_GOTOERR(out, rc);
mq->fid = fcmh_2_fid(bml_2_bmap(bml)->bcm_fcmh);
mq->bno = bml_2_bmap(bml)->bcm_bmapno;
mq->seq = bml->bml_seq;
mq->dio = 1;
/* Take a reference for the asynchronous RPC. */
bmi->bmi_diocb++;
bml->bml_refcnt++;
bml->bml_flags |= BML_DIOCB;
rq->rq_async_args.pointer_arg[SLM_CBARG_SLOT_CSVC] = csvc;
rq->rq_async_args.pointer_arg[SLM_CBARG_SLOT_BML] = bml;
rq->rq_interpret_reply = slm_rcm_bmapdio_cb;
rc = SL_NBRQSET_ADD(csvc, rq);
if (rc == 0)
return (0);
bml->bml_flags &= ~BML_DIOCB;
bmi->bmi_diocb--;
out:
pscrpc_req_finished(rq);
if (csvc)
sl_csvc_decref(csvc);
if (rc == PFLERR_NOTCONN)
PFLOG_BML(PLL_WARN, bml, "not connected");
else
PFLOG_BML(PLL_WARN, bml, "rc=%d", rc);
return (rc);
}
|
jasonTangxd/clockwork | clockwork-common/src/main/java/com/creditease/adx/clockwork/common/enums/UploadFileStatus.java | package com.creditease.adx.clockwork.common.enums;
/**
* 上传文件(运行脚本、依赖jar包、参数文件等)的状态
*/
public enum UploadFileStatus {
// 删除
DELETED("deleted"),
// 有效
ENABLE("enable");
private String value;
UploadFileStatus(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
|
KCBootcamp/KCMyRestaurant | app/src/main/java/es/bhavishchandnani/myrestaurant/model/Tables.java | package es.bhavishchandnani.myrestaurant.model;
import java.util.List;
public class Tables {
private static Tables instance;
private List<Table> tables;
private Tables() {}
public static Tables getInstance() {
if (instance == null){
instance = new Tables();
}
return instance;
}
public List<Table> getTables() {
return tables;
}
public void setTables(List<Table> tables) {
this.tables = tables;
}
public Table getTable(int position){
return tables.get(position);
}
public void setTable(int position, Table table){
tables.set(position, table);
}
public int getCount() {
return tables.size();
}
}
|
aniu2002/sparrow-egg | sparrow-web/sparrow-manager/src/main/java/com/sparrow/app/data/app/DataProviderCommand.java | package com.sparrow.app.data.app;
import com.sparrow.http.command.BaseCommand;
import com.sparrow.http.command.BeanWrapper;
import com.sparrow.http.command.Request;
import com.sparrow.http.command.Response;
import com.sparrow.http.command.resp.FreeMarkerResponse;
import com.sparrow.http.command.resp.JsonResponse;
import com.sparrow.http.command.resp.OkResponse;
import com.sparrow.orm.page.PageResult;
import com.sparrow.app.services.provider.*;
import com.sparrow.common.source.SourceManager;
import java.util.List;
public class DataProviderCommand extends BaseCommand {
public static ProviderStore providerStore = new ProviderStore();
public DataProviderCommand() {
SourceManager.regSourceHandler("srcCfg", providerStore);
}
@Override
public Response doPost(Request request) {
String _t = request.get("_t");
if ("sp".equals(_t)) {
providerStore.saveProviderSource(request.get("app"));
return OkResponse.OK;
} else if ("ss".equals(_t)) {
providerStore.saveSourceConfig(request.get("app"));
return OkResponse.OK;
} else if ("sf".equals(_t)) {
SourceConfig item = BeanWrapper.wrapBean(SourceConfig.class, request);
providerStore.addSourceConfig(request.get("app"), item);
return OkResponse.OK;
} else {
ProviderItem item = BeanWrapper.wrapBean(ProviderItem.class, request);
providerStore.addProviderItem(request.get("app"), item);
providerStore.saveProviderSource(request.get("app"));
return OkResponse.OK;
//new RedirectResponse("/cmd/sys/pdc?_t=gp&source=" + item.getSource() + "&label=" + item.getDesc() + "&app=" + item.getName());
}
}
@Override
public Response doPut(Request request) {
String _t = request.get("_t");
if ("sf".equals(_t)) {
SourceConfig item = BeanWrapper.wrapBean(SourceConfig.class, request);
providerStore.updateSourceConfig(request.get("app"), item);
return OkResponse.OK;
} else {
ProviderItem item = BeanWrapper.wrapBean(ProviderItem.class, request);
providerStore.updateProviderItem(request.get("app"), item);
providerStore.saveProviderSource(request.get("app"));
return OkResponse.OK;
}
}
@Override
public Response doDelete(Request request) {
String _t = request.get("_t");
List<String> names = request.getStringList("id");
if ("sf".equals(_t)) {
if (names != null) {
for (String name : names)
providerStore.deleteSourceConfig(request.get("app"), name);
}
return OkResponse.OK;
} else {
if (names != null) {
for (String name : names)
providerStore.deleteProviderItem(request.get("app"), name);
}
return OkResponse.OK;
}
}
@Override
public Response doGet(Request request) {
String t = request.get("_t");
if ("sl".equals(t)) {
return new FreeMarkerResponse("#provider/source_list", request.getParas());
} else if ("se".equals(t)) {
return new FreeMarkerResponse("#provider/source_edit", request.getParas());
} else if ("sa".equals(t)) {
return new FreeMarkerResponse("#provider/source_add", request.getParas());
} else if ("sd".equals(t)) {
return new FreeMarkerResponse("#provider/source_detail", request.getParas());
} else if ("list".equals(t)) {
return new FreeMarkerResponse("#provider/provider_list", request.getParas());
} else if ("add".equals(t)) {
return new FreeMarkerResponse("#provider/provider_add", request.getParas());
} else if ("edit".equals(t)) {
return new FreeMarkerResponse("#provider/provider_edit", request.getParas());
} else if ("detail".equals(t)) {
return new FreeMarkerResponse("#provider/provider_detail", request.getParas());
} else if ("ds".equals(t)) {
SourceConfig info = providerStore.getSourceConfig(request.get("app"), request.get("name"));
return new JsonResponse(info);
} else if ("dp".equals(t)) {
ProviderItem info = providerStore.getProviderItem(request.get("app"), request.get("name"));
return new JsonResponse(info);
} else if ("sf".equals(t)) {
SourceConfigWrapper sw = providerStore.getSourceConfig(request.get("app"));
if (sw == null)
return new JsonResponse(PageResult.EMPTY);
List<?> rows = sw.getSources();
PageResult page = new PageResult();
page.setRows(rows);
page.setTotal(rows.size());
return new JsonResponse(page);
} else {
ProviderSource ps = providerStore.getProviderSource(request.get("app"));
if (ps == null)
return new JsonResponse(PageResult.EMPTY);
List<?> rows = ps.getItems();
PageResult page = new PageResult();
page.setRows(rows);
page.setTotal(rows.size());
return new JsonResponse(page);
}
}
} |
pebble2015/cpoi | src/org/apache/poi/ss/formula/functions/Sumproduct.cpp | <reponame>pebble2015/cpoi<gh_stars>0
// Generated from /POI/java/org/apache/poi/ss/formula/functions/Sumproduct.java
#include <org/apache/poi/ss/formula/functions/Sumproduct.hpp>
#include <java/lang/ArrayStoreException.hpp>
#include <java/lang/Class.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/RuntimeException.hpp>
#include <java/lang/String.hpp>
#include <java/lang/StringBuilder.hpp>
#include <java/lang/System.hpp>
#include <org/apache/poi/ss/formula/TwoDEval.hpp>
#include <org/apache/poi/ss/formula/eval/AreaEval.hpp>
#include <org/apache/poi/ss/formula/eval/BlankEval.hpp>
#include <org/apache/poi/ss/formula/eval/ErrorEval.hpp>
#include <org/apache/poi/ss/formula/eval/EvaluationException.hpp>
#include <org/apache/poi/ss/formula/eval/NumberEval.hpp>
#include <org/apache/poi/ss/formula/eval/NumericValueEval.hpp>
#include <org/apache/poi/ss/formula/eval/RefEval.hpp>
#include <org/apache/poi/ss/formula/eval/StringEval.hpp>
#include <org/apache/poi/ss/formula/eval/ValueEval.hpp>
#include <ObjectArray.hpp>
#include <SubArray.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace poi
{
namespace ss
{
namespace formula
{
namespace eval
{
typedef ::SubArray< ::poi::ss::formula::eval::ValueEval, ::java::lang::ObjectArray > ValueEvalArray;
} // eval
typedef ::SubArray< ::poi::ss::formula::TwoDEval, ::java::lang::ObjectArray, ::poi::ss::formula::eval::ValueEvalArray > TwoDEvalArray;
} // formula
} // ss
} // poi
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
poi::ss::formula::functions::Sumproduct::Sumproduct(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::ss::formula::functions::Sumproduct::Sumproduct()
: Sumproduct(*static_cast< ::default_init_tag* >(0))
{
ctor();
}
poi::ss::formula::eval::ValueEval* poi::ss::formula::functions::Sumproduct::evaluate(::poi::ss::formula::eval::ValueEvalArray* args, int32_t srcCellRow, int32_t srcCellCol)
{
auto maxN = npc(args)->length;
if(maxN < 1) {
return ::poi::ss::formula::eval::ErrorEval::VALUE_INVALID();
}
auto firstArg = (*args)[int32_t(0)];
try {
if(dynamic_cast< ::poi::ss::formula::eval::NumericValueEval* >(firstArg) != nullptr) {
return evaluateSingleProduct(args);
}
if(dynamic_cast< ::poi::ss::formula::eval::RefEval* >(firstArg) != nullptr) {
return evaluateSingleProduct(args);
}
if(dynamic_cast< ::poi::ss::formula::TwoDEval* >(firstArg) != nullptr) {
auto ae = java_cast< ::poi::ss::formula::TwoDEval* >(firstArg);
if(npc(ae)->isRow() && npc(ae)->isColumn()) {
return evaluateSingleProduct(args);
}
return evaluateAreaSumProduct(args);
}
} catch (::poi::ss::formula::eval::EvaluationException* e) {
return npc(e)->getErrorEval();
}
throw new ::java::lang::RuntimeException(::java::lang::StringBuilder().append(u"Invalid arg type for SUMPRODUCT: ("_j)->append(npc(npc(firstArg)->getClass())->getName())
->append(u")"_j)->toString());
}
poi::ss::formula::eval::ValueEval* poi::ss::formula::functions::Sumproduct::evaluateSingleProduct(::poi::ss::formula::eval::ValueEvalArray* evalArgs) /* throws(EvaluationException) */
{
clinit();
auto maxN = npc(evalArgs)->length;
auto term = 1.0;
for (auto n = int32_t(0); n < maxN; n++) {
auto val = getScalarValue((*evalArgs)[n]);
term *= val;
}
return new ::poi::ss::formula::eval::NumberEval(term);
}
double poi::ss::formula::functions::Sumproduct::getScalarValue(::poi::ss::formula::eval::ValueEval* arg) /* throws(EvaluationException) */
{
clinit();
::poi::ss::formula::eval::ValueEval* eval;
if(dynamic_cast< ::poi::ss::formula::eval::RefEval* >(arg) != nullptr) {
auto re = java_cast< ::poi::ss::formula::eval::RefEval* >(arg);
if(npc(re)->getNumberOfSheets() > 1) {
throw new ::poi::ss::formula::eval::EvaluationException(::poi::ss::formula::eval::ErrorEval::VALUE_INVALID());
}
eval = npc(re)->getInnerValueEval(npc(re)->getFirstSheetIndex());
} else {
eval = arg;
}
if(eval == nullptr) {
throw new ::java::lang::RuntimeException(u"parameter may not be null"_j);
}
if(dynamic_cast< ::poi::ss::formula::eval::AreaEval* >(eval) != nullptr) {
auto ae = java_cast< ::poi::ss::formula::eval::AreaEval* >(eval);
if(!npc(ae)->isColumn() || !npc(ae)->isRow()) {
throw new ::poi::ss::formula::eval::EvaluationException(::poi::ss::formula::eval::ErrorEval::VALUE_INVALID());
}
eval = npc(ae)->getRelativeValue(0, 0);
}
return getProductTerm(eval, true);
}
poi::ss::formula::eval::ValueEval* poi::ss::formula::functions::Sumproduct::evaluateAreaSumProduct(::poi::ss::formula::eval::ValueEvalArray* evalArgs) /* throws(EvaluationException) */
{
clinit();
auto maxN = npc(evalArgs)->length;
auto args = new ::poi::ss::formula::TwoDEvalArray(maxN);
try {
::java::lang::System::arraycopy(evalArgs, 0, args, 0, maxN);
} catch (::java::lang::ArrayStoreException* e) {
return ::poi::ss::formula::eval::ErrorEval::VALUE_INVALID();
}
auto firstArg = (*args)[int32_t(0)];
auto height = npc(firstArg)->getHeight();
auto width = npc(firstArg)->getWidth();
if(!areasAllSameSize(args, height, width)) {
for (auto i = int32_t(1); i < npc(args)->length; i++) {
throwFirstError((*args)[i]);
}
return ::poi::ss::formula::eval::ErrorEval::VALUE_INVALID();
}
double acc = int32_t(0);
for (auto rrIx = int32_t(0); rrIx < height; rrIx++) {
for (auto rcIx = int32_t(0); rcIx < width; rcIx++) {
auto term = 1.0;
for (auto n = int32_t(0); n < maxN; n++) {
auto val = getProductTerm(npc((*args)[n])->getValue(rrIx, rcIx), false);
term *= val;
}
acc += term;
}
}
return new ::poi::ss::formula::eval::NumberEval(acc);
}
void poi::ss::formula::functions::Sumproduct::throwFirstError(::poi::ss::formula::TwoDEval* areaEval) /* throws(EvaluationException) */
{
clinit();
auto height = npc(areaEval)->getHeight();
auto width = npc(areaEval)->getWidth();
for (auto rrIx = int32_t(0); rrIx < height; rrIx++) {
for (auto rcIx = int32_t(0); rcIx < width; rcIx++) {
auto ve = npc(areaEval)->getValue(rrIx, rcIx);
if(dynamic_cast< ::poi::ss::formula::eval::ErrorEval* >(ve) != nullptr) {
throw new ::poi::ss::formula::eval::EvaluationException(java_cast< ::poi::ss::formula::eval::ErrorEval* >(ve));
}
}
}
}
bool poi::ss::formula::functions::Sumproduct::areasAllSameSize(::poi::ss::formula::TwoDEvalArray* args, int32_t height, int32_t width)
{
clinit();
for (auto i = int32_t(0); i < npc(args)->length; i++) {
auto areaEval = (*args)[i];
if(npc(areaEval)->getHeight() != height) {
return false;
}
if(npc(areaEval)->getWidth() != width) {
return false;
}
}
return true;
}
double poi::ss::formula::functions::Sumproduct::getProductTerm(::poi::ss::formula::eval::ValueEval* ve, bool isScalarProduct) /* throws(EvaluationException) */
{
clinit();
if(dynamic_cast< ::poi::ss::formula::eval::BlankEval* >(ve) != nullptr || ve == nullptr) {
if(isScalarProduct) {
throw new ::poi::ss::formula::eval::EvaluationException(::poi::ss::formula::eval::ErrorEval::VALUE_INVALID());
}
return 0;
}
if(dynamic_cast< ::poi::ss::formula::eval::ErrorEval* >(ve) != nullptr) {
throw new ::poi::ss::formula::eval::EvaluationException(java_cast< ::poi::ss::formula::eval::ErrorEval* >(ve));
}
if(dynamic_cast< ::poi::ss::formula::eval::StringEval* >(ve) != nullptr) {
if(isScalarProduct) {
throw new ::poi::ss::formula::eval::EvaluationException(::poi::ss::formula::eval::ErrorEval::VALUE_INVALID());
}
return 0;
}
if(dynamic_cast< ::poi::ss::formula::eval::NumericValueEval* >(ve) != nullptr) {
auto nve = java_cast< ::poi::ss::formula::eval::NumericValueEval* >(ve);
return npc(nve)->getNumberValue();
}
throw new ::java::lang::RuntimeException(::java::lang::StringBuilder().append(u"Unexpected value eval class ("_j)->append(npc(npc(ve)->getClass())->getName())
->append(u")"_j)->toString());
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::ss::formula::functions::Sumproduct::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.functions.Sumproduct", 46);
return c;
}
java::lang::Class* poi::ss::formula::functions::Sumproduct::getClass0()
{
return class_();
}
|
vaish567/BotFramework-WebChat | packages/test/page-object/src/globals/pageConditions/allOutgoingActivitiesSent.js | <reponame>vaish567/BotFramework-WebChat
import became from './became';
import getActivities from '../pageObjects/getActivities';
export default function allOutgoingActivitiesSent() {
return became(
'all outgoing activities sent',
() =>
getActivities()
.filter(({ from: { role }, name, type }) => role === 'user' && name !== '__RUN_HOOK' && type === 'message')
.every(({ channelData: { state } = {} }) => state === 'sent'),
15000
);
}
|
Goodbird-git/CustomNPC-Plus | src/main/java/noppes/npcs/items/ItemSoulstoneEmpty.java | package noppes.npcs.items;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomItems;
import noppes.npcs.CustomNpcs;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.constants.EnumRoleType;
import noppes.npcs.controllers.ServerCloneController;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.roles.RoleCompanion;
import noppes.npcs.roles.RoleFollower;
import cpw.mods.fml.common.registry.GameRegistry;
public class ItemSoulstoneEmpty extends Item {
public ItemSoulstoneEmpty(){
this.setMaxStackSize(64);
}
@Override
public Item setUnlocalizedName(String name){
super.setUnlocalizedName(name);
GameRegistry.registerItem(this, name);
return this;
}
public boolean store(EntityLivingBase entity, ItemStack stack, EntityPlayer player) {
if(!hasPermission(entity, player) || entity instanceof EntityPlayer)
return false;
ItemStack stone = new ItemStack(CustomItems.soulstoneFull);
NBTTagCompound compound = new NBTTagCompound();
if(!entity.writeToNBTOptional(compound))
return false;
ServerCloneController.Instance.cleanTags(compound);
if(stone.stackTagCompound == null)
stone.stackTagCompound = new NBTTagCompound();
stone.stackTagCompound.setTag("Entity", compound);
String name = EntityList.getEntityString(entity);
if (name == null)
name = "generic";
stone.stackTagCompound.setString("Name", "entity." + name + ".name");
if(entity instanceof EntityNPCInterface){
EntityNPCInterface npc = (EntityNPCInterface) entity;
stone.stackTagCompound.setString("DisplayName", entity.getCommandSenderName());
if(npc.advanced.role == EnumRoleType.Companion){
RoleCompanion role = (RoleCompanion) npc.roleInterface;
stone.stackTagCompound.setString("ExtraText", "companion.stage,: ," + role.stage.name);
}
}
else if(entity instanceof EntityLiving && ((EntityLiving)entity).hasCustomNameTag())
stone.stackTagCompound.setString("DisplayName", ((EntityLiving)entity).getCustomNameTag());
NoppesUtilServer.GivePlayerItem(player, player, stone);
if(!player.capabilities.isCreativeMode){
stack.splitStack(1);
if(stack.stackSize <= 0)
player.destroyCurrentEquippedItem();
}
entity.isDead = true;
return true;
}
public boolean hasPermission(EntityLivingBase entity, EntityPlayer player){
if(NoppesUtilServer.isOp(player) && player.capabilities.isCreativeMode)
return true;
if(CustomNpcsPermissions.enabled() && CustomNpcsPermissions.hasPermission(player, CustomNpcsPermissions.SOULSTONE_ALL))
return true;
if(entity instanceof EntityNPCInterface){
EntityNPCInterface npc = (EntityNPCInterface) entity;
if(npc.advanced.role == EnumRoleType.Companion){
RoleCompanion role = (RoleCompanion) npc.roleInterface;
if(role.getOwner() == player)
return true;
}
if(npc.advanced.role == EnumRoleType.Follower){
RoleFollower role = (RoleFollower) npc.roleInterface;
if(role.getOwner() == player)
return !role.refuseSoulStone;
}
return CustomNpcs.SoulStoneNPCs;
}
if(entity instanceof EntityAnimal)
return CustomNpcs.SoulStoneAnimals;
return false;
}
}
|
nimbul/nimbul | vendor/bundle/ruby/1.8/gems/fastthread-1.0.7/ext/fastthread/extconf.rb | version_components = RUBY_VERSION.split('.').map { |c| c.to_i }
need_fastthread = ( !defined? RUBY_ENGINE )
need_fastthread &= ( RUBY_PLATFORM != 'java' )
need_fastthread &= version_components[0..1] == [1, 8]
if need_fastthread
require 'mkmf'
create_makefile('fastthread')
else
require 'rbconfig'
File.open('Makefile', 'w') do |stream|
Config::CONFIG.each do |key, value|
stream.puts "#{key} = #{value}"
end
stream.puts
stream << <<EOS
RUBYARCHDIR = $(sitearchdir)$(target_prefix)
default:
install:
mkdir -p $(RUBYARCHDIR)
touch $(RUBYARCHDIR)/fastthread.rb
EOS
end
end
|
SteveMinhNguyen/FE-develop | src/assets/js/coin.js | <reponame>SteveMinhNguyen/FE-develop
export const ProjectCoin = 'BURGER';
export const ChainCoin = 'BURGER';
|
UranusBlockStack/ovirt-engine | backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/CanDoActionTestUtils.java | package org.ovirt.engine.core.bll;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.text.MessageFormat;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
/**
* Utilities for testing the {@link CommandBase#canDoAction()} command's behavior.
*/
public class CanDoActionTestUtils {
/**
* Run the canDoAction and assert that it fails with the given message, while printing the messages (for easier
* debug if test fails).
*
* @param command
* The command to check canDoAction for.
* @param message
* The message that should be in the failed messages.
*
* @return The failure messages, so that they can be further examined if needed.
*/
public static List<String> runAndAssertCanDoActionFailure(CommandBase<?> command, VdcBllMessages message) {
return runAndAssertCanDoActionFailure("", command, message);
}
/**
* Run the canDoAction and assert that it fails with the given message, while printing the messages (for easier
* debug if test fails).
*
* @param assertionMessage
* The message to add to the assertion statement.
* @param command
* The command to check canDoAction for.
* @param message
* The message that should be in the failed messages.
*
* @return The failure messages, so that they can be further examined if needed.
*/
public static List<String> runAndAssertCanDoActionFailure
(String assertionMessage, CommandBase<?> command, VdcBllMessages message) {
assertFalse("Command's canDoAction expected to fail, but succeeded", command.canDoAction());
return assertCanDoActionMessages(assertionMessage, command, message);
}
/**
* Run the canDoAction and assert that it succeeds, while printing the messages (for easier debug if test fails).
*
* @param command
* The command to check canDoAction for.
*/
public static void runAndAssertCanDoActionSuccess(CommandBase<?> command) {
boolean canDoAction = command.canDoAction();
List<String> canDoActionMessages = command.getReturnValue().getCanDoActionMessages();
assertTrue(MessageFormat.format("Command''s canDoAction expected to succeed, but failed, messages are: {0}",
canDoActionMessages), canDoAction);
assertTrue(MessageFormat.format("Command''s canDoAction succeeded, but added the following messages: {0}",
canDoActionMessages), canDoActionMessages.isEmpty());
}
/**
* Run the canDoAction and assert that it contains the given messages, while printing the messages (for easier debug
* if test fails).
*
* @param command
* The command to check canDoAction for.
* @param messages
* The messages that should be set.
*
* @return The action messages, so that they can be further examined if needed.
*/
public static List<String> runAndAssertSetActionMessageParameters
(CommandBase<?> command, VdcBllMessages... messages) {
return runAndAssertSetActionMessageParameters("", command, messages);
}
/**
* Run the canDoAction and assert that it contains the given messages, while printing the messages (for easier debug
* if test fails).
*
* @param assertionMessage
* The message to add to the assertion statement.
* @param command
* The command to check canDoAction for.
* @param messages
* The messages that should be set.
*
* @return The action messages, so that they can be further examined if needed.
*/
public static List<String> runAndAssertSetActionMessageParameters
(String assertionMessage, CommandBase<?> command, VdcBllMessages... messages) {
command.setActionMessageParameters();
for (VdcBllMessages message : messages) {
assertCanDoActionMessages(assertionMessage, command, message);
}
return command.getReturnValue().getCanDoActionMessages();
}
public static List<String> assertCanDoActionMessages(String assertionMessage,
CommandBase<?> command,
VdcBllMessages message) {
List<String> canDoActionMessages = command.getReturnValue().getCanDoActionMessages();
assertTrue(MessageFormat.format("{0}canDoAction messages doesn''t contain expected message: {1}, messages are: {2}",
optionalMessage(assertionMessage),
message.name(),
canDoActionMessages),
canDoActionMessages.contains(message.name()));
return canDoActionMessages;
}
private static String optionalMessage(String assertionMessage) {
if (!StringUtils.isEmpty(assertionMessage)) {
assertionMessage += ". ";
}
return assertionMessage;
}
}
|
amichard/tfrs | backend/api/migrations/0013_auto_20180619_2053.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-06-19 20:53
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0012_credittradecomment'),
]
operations = [
migrations.AddField(
model_name='credittrade',
name='rescinded',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='credittradehistory',
name='rescinded',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='user',
name='cell_phone',
field=models.CharField(blank=True, max_length=17, null=True, validators=[django.core.validators.RegexValidator(message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.", regex='^\\+?1?\\d{9,15}$')]),
),
migrations.AlterField(
model_name='user',
name='phone',
field=models.CharField(blank=True, max_length=17, null=True, validators=[django.core.validators.RegexValidator(message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.", regex='^\\+?1?\\d{9,15}$')]),
),
]
|
7ShaYaN7/SmartLauncher | app/src/main/java/fr/neamar/kiss/loader/LoadSearchPojos.java | package fr.neamar.kiss.loader;
import android.content.Context;
import java.util.ArrayList;
import fr.neamar.kiss.pojo.SearchPojo;
public class LoadSearchPojos extends LoadPojos<SearchPojo> {
public LoadSearchPojos(Context context) {
super(context, "none://");
}
@Override
protected ArrayList<SearchPojo> doInBackground(Void... params) {
return null;
}
}
|
AlliumCepa/webgui | www/extras/yui-webgui/build/form/jsontable.js |
// Initialize namespace
if (typeof WebGUI == "undefined") {
var WebGUI = {};
}
if (typeof WebGUI.Form == "undefined") {
WebGUI.Form = {};
}
/****************************************************************************
* WebGUI.Form.JsonTable( fieldName, tableId, columns )
* Create a JsonTable object.
*
* fieldName holds the current JSON-encoded array of hashrefs of values.
*
* tableId is where to put the rows and add all the events.
*
* columns is an array of hashes of column data with the following keys:
* type -- The type of column, one of "text", "select",
* "id", "hidden", "readonly"
* name -- The name of the column
* label -- The label of the column
* options -- select only. An array of name, label of options.
*
*/
WebGUI.Form.JsonTable
= function ( fieldName, tableId, columns ) {
this.fieldName = fieldName;
this.tableId = tableId;
this.columns = columns;
this.table = document.getElementById( this.tableId );
this.tbody = this.table.getElementsByTagName( "tbody" )[0];
// Find the form
this.form = this.table;
while ( this.form.nodeName != "FORM" ) {
this.form = this.form.parentNode;
}
this.field = this.form.elements[ this.fieldName ];
this.json = this.field.value;
this.newRow = YAHOO.util.Dom.getElementsByClassName( "new_row", "tr", this.table )[0];
try {
this.data = YAHOO.lang.JSON.parse( this.json );
}
catch (err) {
this.data = [];
}
// Add submit listener to update JSON
YAHOO.util.Event.addListener( this.form, "submit", this.update, this, true );
this.addButton = this.table.getElementsByTagName( "button" )[0];
YAHOO.util.Event.addListener( this.addButton, "click",
function(e) {
this.addRow();
e.preventDefault();
return false;
},
this, true
);
this.i18n
= new WebGUI.i18n( {
namespaces : {
'WebGUI' : [
"576",
"Up",
"Down"
]
},
onpreload : {
fn : WebGUI.Form.JsonTable.prototype.init,
obj : this,
override : true
}
} );
return this;
};
/****************************************************************************
* addActions( row )
* Add the row actions to the given row
* Delay creating this so that the i18n object exists
*/
WebGUI.Form.JsonTable.prototype.addActions
= function (row) {
// Add row actions
var buttonCell = row.lastChild;
var deleteButton = document.createElement('input');
deleteButton.type = "button";
deleteButton.value = this.i18n.get('WebGUI', '576');
YAHOO.util.Event.addListener( deleteButton, "click",
function (e) {
this.deleteRow( row );
},
this, true
);
buttonCell.appendChild( deleteButton );
var moveUpButton = document.createElement('input');
moveUpButton.type = "button";
moveUpButton.value = this.i18n.get('WebGUI', 'Up');
YAHOO.util.Event.addListener( moveUpButton, "click",
function (e) {
this.moveRowUp( row );
},
this, true
);
buttonCell.appendChild( moveUpButton );
var moveDownButton = document.createElement('input');
moveDownButton.type = "button";
moveDownButton.value = this.i18n.get('WebGUI', 'Down');
YAHOO.util.Event.addListener( moveDownButton, "click",
function (e) {
this.moveRowDown( row );
},
this, true
);
buttonCell.appendChild( moveDownButton );
};
/****************************************************************************
* addRow ( )
* Add a new row to the bottom of the table
*/
WebGUI.Form.JsonTable.prototype.addRow
= function () {
var newRow = this.newRow.cloneNode(true);
this.tbody.appendChild( newRow );
newRow.className = "";
newRow.style.display = "table-row";
this.addActions( newRow );
return newRow;
};
/****************************************************************************
* deleteRow( row )
* Delete the row from the table
*/
WebGUI.Form.JsonTable.prototype.deleteRow
= function ( row ) {
row.parentNode.removeChild( row );
};
/****************************************************************************
* init ( )
* Initialize the JsonTable by adding rows for every datum
*/
WebGUI.Form.JsonTable.prototype.init
= function () {
for ( var row in this.data ) {
// Copy new_row
var newRow = this.addRow();
// Fill in values based on field type
var cells = newRow.getElementsByTagName( "td" );
for ( var i = 0; i < this.columns.length; i++ ) { // Last cell is for buttons
var cell = cells[i];
var column = this.columns[i];
var field = cell.childNodes[0];
var value = this.data[row][column.name] || '';
if ( column.type == "text" || column.type == "id"
|| column.type == "hidden" ) {
field.value = value;
}
else if ( column.type == "select" ) {
for ( var x = 0; x < field.options.length; x++ ) {
if ( field.options[x].value == value ) {
field.options[x].selected = true;
}
}
}
else { // "readonly" or unknown
cell.appendChild( document.createTextNode( value ) );
}
}
}
};
/****************************************************************************
* moveRowDown( row )
* Move the row down in the table
*/
WebGUI.Form.JsonTable.prototype.moveRowDown
= function ( row ) {
var after = row.nextSibling;
if ( after ) {
row.parentNode.insertBefore( after, row );
}
};
/****************************************************************************
* moveRowUp( row )
* Move the row up in the table
*/
WebGUI.Form.JsonTable.prototype.moveRowUp
= function ( row ) {
var before = row.previousSibling;
if ( before && before.className != "new_row" ) {
row.parentNode.insertBefore( row, before );
}
};
/****************************************************************************
* update ( )
* Update the value in our field with the correct JSON
*/
WebGUI.Form.JsonTable.prototype.update
= function (e) {
var rows = this.tbody.getElementsByTagName( 'tr' );
var data = [];
for ( var i = 1; i < rows.length; i++ ) {
var cells = rows[i].getElementsByTagName( 'td' );
var rowData = {};
for ( var x = 0; x < this.columns.length; x++ ) {
var cell = cells[x];
var column = this.columns[x];
var field = cell.childNodes[0];
if ( field.nodeName == "INPUT" ) {
rowData[ column.name ] = field.value;
}
else if ( field.nodeName == "SELECT" ) {
var value = field.options[ field.selectedIndex ].value;
rowData[ column.name ] = field.value;
}
}
data.push( rowData );
}
this.field.value = YAHOO.lang.JSON.stringify( data );
};
|
litecoin-foundation/litecoin | src/libmw/test/framework/include/test_framework/Deserializer.h | #pragma once
// Copyright (c) 2018-2019 <NAME>
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#include <mw/common/Traits.h>
#include <algorithm>
#include <boost/optional.hpp>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
class Deserializer
{
public:
Deserializer(std::vector<uint8_t> bytes)
: m_bytes(std::move(bytes)), m_reader(SER_NETWORK, PROTOCOL_VERSION, m_bytes, 0) {}
template <class T, typename SFINAE = std::enable_if_t<std::is_integral<T>::value || std::is_base_of<Traits::ISerializable, T>::value>>
T Read()
{
T value;
m_reader >> value;
return value;
}
std::vector<uint8_t> ReadVector(const uint64_t numBytes)
{
std::vector<uint8_t> vec(numBytes);
m_reader.read((char*)vec.data(), numBytes);
return vec;
}
private:
std::vector<uint8_t> m_bytes;
VectorReader m_reader;
};
|
rweyrauch/PBrtJ | src/main/java/org/pbrt/core/Film.java |
/*
* PBrtJ -- Port of pbrt v3 to Java.
* Copyright (c) 2017 <NAME>.
*
* pbrt source code is Copyright(c) 1998-2016
* <NAME>, <NAME>, and <NAME>.
*
*/
package org.pbrt.core;
public class Film {
// Film Private Data
private class Pixel {
Pixel() {}
float xyz[] = {0, 0, 0};
float filterWeightSum = 0;
AtomicFloat splatXYZ[] = {new AtomicFloat(0), new AtomicFloat(0), new AtomicFloat(0)};
}
private Pixel[] pixels;
private static final int filterTableWidth = 16;
private float filterTable[] = new float[filterTableWidth * filterTableWidth];
private final float scale;
private final float maxSampleLuminance;
// FilmTilePixel Declarations
public class FilmTilePixel {
Spectrum contribSum = new Spectrum(0);
float filterWeightSum = 0;
}
public class FilmTile {
// FilmTile Public Methods
public FilmTile(Bounds2i pixelBounds, Vector2f filterRadius,
float[] filterTable, int filterTableSize, float maxSampleLuminance) {
this.pixelBounds = pixelBounds;
this.filterRadius = filterRadius;
this.invFilterRadius = new Vector2f(1 / filterRadius.x, 1 / filterRadius.y);
this.filterTable = filterTable;
this.filterTableSize = filterTableSize;
this.maxSampleLuminance = maxSampleLuminance;
this.pixels = new FilmTilePixel[Math.max(0, pixelBounds.Area())];
for (int i = 0; i < this.pixels.length; i++) {
this.pixels[i] = new FilmTilePixel();
}
}
public void AddSample(Point2f pFilm, Spectrum L, float sampleWeight) {
if (L.y() > maxSampleLuminance)
L.scale(maxSampleLuminance / L.y());
// Compute sample's raster bounds
Point2f pFilmDiscrete = pFilm.subtract(new Vector2f(0.5f, 0.5f));
Point2i p0 = new Point2i(Point2f.Ceil(pFilmDiscrete.subtract(filterRadius)));
Point2i p1 = new Point2i(Point2f.Floor(pFilmDiscrete.add(filterRadius))).add(new Point2i(1, 1));
p0 = Point2i.Max(p0, pixelBounds.pMin);
p1 = Point2i.Min(p1, pixelBounds.pMax);
// Loop over filter support and add sample to pixel arrays
// Precompute $x$ and $y$ filter table offsets
int[] ifx = new int[p1.x - p0.x];
for (int x = p0.x; x < p1.x; ++x) {
float fx = Math.abs((x - pFilmDiscrete.x) * invFilterRadius.x *
filterTableSize);
ifx[x - p0.x] = Math.min((int)Math.floor(fx), filterTableSize - 1);
}
int[] ify = new int[p1.y - p0.y];
for (int y = p0.y; y < p1.y; ++y) {
float fy = Math.abs((y - pFilmDiscrete.y) * invFilterRadius.y *
filterTableSize);
ify[y - p0.y] = Math.min((int)Math.floor(fy), filterTableSize - 1);
}
for (int y = p0.y; y < p1.y; ++y) {
for (int x = p0.x; x < p1.x; ++x) {
// Evaluate filter value at $(x,y)$ pixel
int offset = ify[y - p0.y] * filterTableSize + ifx[x - p0.x];
float filterWeight = filterTable[offset];
// Update pixel values with filtered sample contribution
FilmTilePixel pixel = GetPixel(new Point2i(x, y));
pixel.contribSum = Spectrum.Add(pixel.contribSum, Spectrum.Scale(L, sampleWeight * filterWeight));
pixel.filterWeightSum += filterWeight;
}
}
}
public FilmTilePixel GetPixel(Point2i p) {
assert (Bounds2i.InsideExclusive(p, pixelBounds));
int width = pixelBounds.pMax.x - pixelBounds.pMin.x;
int offset = (p.x - pixelBounds.pMin.x) + (p.y - pixelBounds.pMin.y) * width;
return pixels[offset];
}
public Bounds2i GetPixelBounds() { return pixelBounds; }
// FilmTile Private Data
private Bounds2i pixelBounds;
private Vector2f filterRadius, invFilterRadius;
private float[] filterTable;
private int filterTableSize;
private FilmTilePixel[] pixels;
private float maxSampleLuminance;
}
// Film Public Methods
public Film(Point2i resolution, Bounds2f cropWindow, Filter filter, float diagonal, String filename, float scale, float maxSampleLuminance) {
this.fullResolution = resolution;
this.diagonal = diagonal * 0.001f;
this.filter = filter;
this.filename = filename;
this.scale = scale;
this.maxSampleLuminance = maxSampleLuminance;
// Compute film image bounds
this.croppedPixelBounds =
new Bounds2i(new Point2i((int)Math.ceil(fullResolution.x * cropWindow.pMin.x),
(int)Math.ceil(fullResolution.y * cropWindow.pMin.y)),
new Point2i((int)Math.ceil(fullResolution.x * cropWindow.pMax.x),
(int)Math.ceil(fullResolution.y * cropWindow.pMax.y)));
PBrtTLogger.Info("Created film with full resolution %s. Crop window of %s -> croppedPixelBounds %s", resolution.toString(), cropWindow, croppedPixelBounds);
// Allocate film image storage
this.pixels = new Pixel[croppedPixelBounds.Area()];
for (int i = 0; i < this.pixels.length; i++) this.pixels[i] = new Pixel();
filmPixelMemory.increment(croppedPixelBounds.Area() * 8*4);
// Precompute filter weight table
int offset = 0;
for (int y = 0; y < filterTableWidth; ++y) {
for (int x = 0; x < filterTableWidth; ++x, ++offset) {
Point2f p = new Point2f();
p.x = (x + 0.5f) * filter.radius.x / filterTableWidth;
p.y = (y + 0.5f) * filter.radius.y / filterTableWidth;
filterTable[offset] = filter.Evaluate(p);
}
}
}
public Bounds2i GetSampleBounds() {
Vector2f halfPixel = new Vector2f(0.5f, 0.5f);
Bounds2f floatBounds = new Bounds2f(Point2f.Floor(new Point2f(croppedPixelBounds.pMin).add(halfPixel.subtract(filter.radius))),
Point2f.Ceil(new Point2f(croppedPixelBounds.pMax).subtract(halfPixel.add(filter.radius))));
return new Bounds2i(floatBounds);
}
public Bounds2f GetPhysicalExtent() {
float aspect = (float)fullResolution.y / (float)fullResolution.x;
float x = (float)Math.sqrt(diagonal * diagonal / (1 + aspect * aspect));
float y = aspect * x;
return new Bounds2f(new Point2f(-x / 2, -y / 2), new Point2f(x / 2, y / 2));
}
public FilmTile GetFilmTile(Bounds2i sampleBounds) {
// Bound image pixels that samples in _sampleBounds_ contribute to
Vector2f halfPixel = new Vector2f(0.5f, 0.5f);
Bounds2f floatBounds = new Bounds2f(sampleBounds);
Point2i p0 = new Point2i(Point2f.Ceil(floatBounds.pMin.subtract(halfPixel).subtract(filter.radius)));
Point2i p1 = new Point2i(Point2f.Floor(floatBounds.pMax.subtract(halfPixel).add(filter.radius))).add(new Point2i(1, 1));
Bounds2i tilePixelBounds = Bounds2i.Intersect(new Bounds2i(p0, p1), croppedPixelBounds);
return new FilmTile(tilePixelBounds, filter.radius, filterTable, filterTableWidth, maxSampleLuminance);
}
public void MergeFilmTile(FilmTile tile) {
//Api.logger.trace("Merging film tile %s", tile.pixelBounds.toString());
//std::lock_guard<std::mutex> lock(mutex);
for (int y = tile.GetPixelBounds().pMin.y; y < tile.GetPixelBounds().pMax.y; y++) {
for (int x = tile.GetPixelBounds().pMin.x; x < tile.GetPixelBounds().pMax.x; x++) {
Point2i pixel = new Point2i(x, y);
// Merge _pixel_ into _Film::pixels_
final FilmTilePixel tilePixel = tile.GetPixel(pixel);
Pixel mergePixel = GetPixel(pixel);
float[] xyz = tilePixel.contribSum.toXYZ();
for (int i = 0; i < 3; ++i) mergePixel.xyz[i] += xyz[i];
mergePixel.filterWeightSum += tilePixel.filterWeightSum;
SetPixel(pixel, mergePixel);
}
}
}
public void SetImage(Spectrum[] img) {
int nPixels = croppedPixelBounds.Area();
for (int i = 0; i < nPixels; ++i) {
Pixel p = pixels[i];
p.xyz = img[i].toXYZ();
p.filterWeightSum = 1;
p.splatXYZ[0].set(0);
p.splatXYZ[1].set(0);
p.splatXYZ[2].set(0);
}
}
public void AddSplat(Point2f p, Spectrum v) {
if (v.hasNaNs()) {
PBrtTLogger.Error("Ignoring splatted spectrum with NaN values at (%f, %f)", p.x, p.y);
return;
} else if (v.y() < 0) {
PBrtTLogger.Error("Ignoring splatted spectrum with negative luminance %f at (%f, %f)", v.y(), p.x, p.y);
return;
} else if (Float.isInfinite(v.y())) {
PBrtTLogger.Error("Ignoring splatted spectrum with infinite luminance at (%f, %f)", p.x, p.y);
return;
}
Point2i pi = new Point2i((int)Math.floor(p.x), (int)Math.floor(p.y));
if (!Bounds2i.InsideExclusive(pi, croppedPixelBounds)) return;
if (v.y() > maxSampleLuminance)
v = v.scale(maxSampleLuminance / v.y());
float[] xyz = v.toXYZ();
Pixel pixel = GetPixel(pi);
for (int i = 0; i < 3; ++i) pixel.splatXYZ[i].add(xyz[i]);
}
public void WriteImage(float splatScale) {
// Convert image to RGB and compute final pixel values
//LOG(INFO) << "Converting image to RGB and computing final weighted pixel values";
float[] pixRGB = new float[3];
float[] splatRGB = new float[3];
float[] rgb = new float[3 * croppedPixelBounds.Area()];
int offset = 0;
for (int py = croppedPixelBounds.pMin.y; py < croppedPixelBounds.pMax.y; py++) {
for (int px = croppedPixelBounds.pMin.x; px < croppedPixelBounds.pMax.x; px++) {
Point2i p = new Point2i(px, py);
// Convert pixel XYZ color to RGB
Pixel pixel = GetPixel(p);
pixRGB = Spectrum.XYZToRGB(pixel.xyz, pixRGB);
rgb[3 * offset] = pixRGB[0];
rgb[3 * offset+1] = pixRGB[1];
rgb[3 * offset+2] = pixRGB[2];
// Normalize pixel with weight sum
float filterWeightSum = pixel.filterWeightSum;
if (filterWeightSum != 0) {
float invWt = 1 / filterWeightSum;
rgb[3 * offset] = Math.max(0, rgb[3 * offset] * invWt);
rgb[3 * offset + 1] = Math.max(0, rgb[3 * offset + 1] * invWt);
rgb[3 * offset + 2] = Math.max(0, rgb[3 * offset + 2] * invWt);
}
// Add splat value at pixel
float[] splatXYZ = {pixel.splatXYZ[0].get(), pixel.splatXYZ[1].get(), pixel.splatXYZ[2].get()};
splatRGB = Spectrum.XYZToRGB(splatXYZ, splatRGB);
rgb[3 * offset] += splatScale * splatRGB[0];
rgb[3 * offset + 1] += splatScale * splatRGB[1];
rgb[3 * offset + 2] += splatScale * splatRGB[2];
// Scale pixel value by _scale_
rgb[3 * offset] *= scale;
rgb[3 * offset + 1] *= scale;
rgb[3 * offset + 2] *= scale;
++offset;
}
}
// Write RGB image
PBrtTLogger.Info("Writing image %s with bounds %s", filename, croppedPixelBounds.toString());
ImageIO.Write(filename, rgb, croppedPixelBounds, fullResolution);
}
public void Clear() {
for (int py = croppedPixelBounds.pMin.y; py < croppedPixelBounds.pMax.y; py++) {
for (int px = croppedPixelBounds.pMin.x; px < croppedPixelBounds.pMax.x; px++) {
Point2i p = new Point2i(px, py);
Pixel pixel = GetPixel(p);
for (int c = 0; c < 3; ++c) {
pixel.splatXYZ[c].set(0);
pixel.xyz[c] = 0;
}
pixel.filterWeightSum = 0;
}
}
}
// Film Public Data
public final Point2i fullResolution;
public final float diagonal;
public Filter filter;
public final String filename;
public Bounds2i croppedPixelBounds;
public static Film Create(ParamSet paramSet, Filter filter) {
String filename = new String();
if (!Pbrt.options.ImageFile.isEmpty()) {
filename = Pbrt.options.ImageFile;
String paramsFilename = paramSet.FindOneString("filename", "");
if (!paramsFilename.isEmpty()) {
PBrtTLogger.Warning("Output filename supplied on command line, \"%s\" is overriding " +
"filename provided in scene description file, \"%s\".",
Pbrt.options.ImageFile, paramsFilename);
} else {
filename = Pbrt.options.ImageFile;
}
}
else {
filename = paramSet.FindOneString("filename", "pbrt.exr");
}
int xres = paramSet.FindOneInt("xresolution", 1280);
int yres = paramSet.FindOneInt("yresolution", 720);
if (Pbrt.options.QuickRender) xres = Math.max(1, xres / 4);
if (Pbrt.options.QuickRender) yres = Math.max(1, yres / 4);
Bounds2f crop = new Bounds2f(new Point2f(0, 0), new Point2f(1, 1));
Float[] cr = paramSet.FindFloat("cropwindow");
if (cr != null && cr.length == 4) {
crop.pMin.x = Pbrt.Clamp(Math.min(cr[0], cr[1]), 0, 1);
crop.pMax.x = Pbrt.Clamp(Math.max(cr[0], cr[1]), 0, 1);
crop.pMin.y = Pbrt.Clamp(Math.min(cr[2], cr[3]), 0, 1);
crop.pMax.y = Pbrt.Clamp(Math.max(cr[2], cr[3]), 0, 1);
} else if (cr != null) {
PBrtTLogger.Error("%d values supplied for \"cropwindow\". Expected 4.", cr.length);
} else {
crop = new Bounds2f(new Point2f(Pbrt.Clamp(Pbrt.options.CropWindow[0][0], 0, 1),
Pbrt.Clamp(Pbrt.options.CropWindow[1][0], 0, 1)),
new Point2f(Pbrt.Clamp(Pbrt.options.CropWindow[0][1], 0, 1),
Pbrt.Clamp(Pbrt.options.CropWindow[1][1], 0, 1)));
}
float scale = paramSet.FindOneFloat("scale", 1);
float diagonal = paramSet.FindOneFloat("diagonal", 35);
float maxSampleLuminance = paramSet.FindOneFloat("maxsampleluminance", Pbrt.Infinity);
return new Film(new Point2i(xres, yres), crop, filter, diagonal, filename, scale, maxSampleLuminance);
}
// Film Private Methods
private Pixel GetPixel(Point2i p) {
assert (Bounds2i.InsideExclusive(p, croppedPixelBounds));
int width = croppedPixelBounds.pMax.x - croppedPixelBounds.pMin.x;
int offset = (p.x - croppedPixelBounds.pMin.x) + (p.y - croppedPixelBounds.pMin.y) * width;
return pixels[offset];
}
private void SetPixel(Point2i p, Pixel pix) {
assert (Bounds2i.InsideExclusive(p, croppedPixelBounds));
int width = croppedPixelBounds.pMax.x - croppedPixelBounds.pMin.x;
int offset = (p.x - croppedPixelBounds.pMin.x) + (p.y - croppedPixelBounds.pMin.y) * width;
pixels[offset] = pix;
}
private static Stats.MemoryCounter filmPixelMemory = new Stats.MemoryCounter("Memory/Film pixels");
} |
thedatanecdotes/DataAnecdotesWebsite | node_modules/@material-ui/icons/esm/SignalCellularNoSimSharp.js | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon( /*#__PURE__*/React.createElement("path", {
d: "M19 3h-9L7.95 5.06 19 16.11zm-15.21.74L2.38 5.15 5 7.77V21h13.23l1.62 1.62 1.41-1.41z"
}), 'SignalCellularNoSimSharp'); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.