repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
yaoshengyi/serviceplatform
|
yshop-api/src/main/java/co/yixiang/modules/shop/entity/EnterpriseTopics.java
|
<filename>yshop-api/src/main/java/co/yixiang/modules/shop/entity/EnterpriseTopics.java<gh_stars>0
package co.yixiang.modules.shop.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import co.yixiang.common.entity.BaseEntity;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author visazhou
* @since 2020-06-05
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value="EnterpriseTopics对象", description="")
public class EnterpriseTopics extends BaseEntity {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "企业名称")
private String name;
@ApiModelProperty(value = "logo图片")
private String logo;
@ApiModelProperty(value = "企业介绍图片")
private String image;
@ApiModelProperty(value = "简介")
private String synopsis;
@ApiModelProperty(value = "长图文内容,信息活动")
private String content;
@ApiModelProperty(value = "是否删除")
private Boolean isDel;
@ApiModelProperty(value = "添加时间")
private Integer addTime;
@ApiModelProperty(value = "是否显示 0/是 1/否")
private Boolean isShow;
}
|
marriott-library/newspaper_works
|
spec/lib/newspaper_works/page_finder_spec.rb
|
require 'spec_helper'
RSpec.describe NewspaperWorks::PageFinder do
# use before(:all) so we only create fixtures once
before(:all) do
@issue = NewspaperIssue.new
@issue.title = ["Yesterday's News: December 7, 1941"]
@page1 = NewspaperPage.new
@page1.title = ['Page 1']
@page2 = NewspaperPage.new
@page2.title = ['Page 2']
@page3 = NewspaperPage.new
@page3.title = ['Page 3']
@issue.ordered_members << @page1
@issue.ordered_members << @page2
@issue.ordered_members << @page3
@issue.save!
@page1.save!
@page2.save!
@page3.save!
@page1_solr_doc = SolrDocument.find(@page1.id)
@page2_solr_doc = SolrDocument.find(@page2.id)
@page3_solr_doc = SolrDocument.find(@page3.id)
end
let(:controller) { NewspaperWorks::NewspapersController.new }
let(:ordered_pages_array) { [@page1_solr_doc, @page2_solr_doc, @page3_solr_doc] }
describe 'pages_for_issue' do
subject { controller.pages_for_issue(@issue.id) }
it 'returns the pages, in order' do
# for some reason, the line below doesn't work, so we compare ids
# expect(subject).to eq ordered_pages_array
expect(subject[0]['id']).to eq ordered_pages_array[0]['id']
expect(subject[1]['id']).to eq ordered_pages_array[1]['id']
expect(subject[2]['id']).to eq ordered_pages_array[2]['id']
end
end
describe '#ordered_pages' do
subject { controller.ordered_pages(ordered_pages_array.shuffle) }
it { is_expected.to eq ordered_pages_array }
end
describe '#get_page_index' do
subject { controller.get_page_index(@page2.id) }
it { is_expected.to eq 1 }
end
end
|
aligungr/ue-ran-sim
|
src/utils/common.cpp
|
<gh_stars>10-100
//
// This file is a part of UERANSIM open source project.
// Copyright (c) 2021 <NAME>.
//
// The software and all associated files are licensed under GPL-3.0
// and subject to the terms and conditions defined in LICENSE file.
//
#include "common.hpp"
#include "constants.hpp"
#include <algorithm>
#include <atomic>
#include <cctype>
#include <chrono>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <thread>
#include <arpa/inet.h>
#include <unistd.h>
static_assert(sizeof(char) == sizeof(uint8_t));
static_assert(sizeof(int) == sizeof(uint32_t));
static_assert(sizeof(long) == sizeof(uint32_t) || sizeof(long) == sizeof(uint64_t));
static_assert(sizeof(float) == sizeof(uint32_t));
static_assert(sizeof(double) == sizeof(uint64_t));
static_assert(sizeof(long long) == sizeof(uint64_t));
static std::atomic<int> g_idCounter = 1;
static bool IPv6FromString(const char *szAddress, uint8_t *address)
{
auto asciiToHex = [](char c) -> int {
c |= 0x20;
if (c >= '0' && c <= '9')
return c - '0';
else if (c >= 'a' && c <= 'f')
return (c - 'a') + 10;
else
return -1;
};
uint16_t acc = 0;
uint8_t colons = 0;
uint8_t pos = 0;
memset(address, 0, 16);
for (uint8_t i = 1; i <= 39; i++)
{
if (szAddress[i] == ':')
{
if (szAddress[i - 1] == ':')
colons = 14;
else if (colons)
colons -= 2;
}
else if (szAddress[i] == '\0')
break;
}
for (uint8_t i = 0; i <= 39 && pos < 16; i++)
{
if (szAddress[i] == ':' || szAddress[i] == '\0')
{
address[pos] = acc >> 8;
address[pos + 1] = acc;
acc = 0;
if (colons && i && szAddress[i - 1] == ':')
pos = colons;
else
pos += 2;
}
else
{
int val = asciiToHex(szAddress[i]);
if (val == -1)
return false;
else
{
acc <<= 4;
acc |= static_cast<uint8_t>(val);
}
}
if (szAddress[i] == '\0')
break;
}
return true;
}
int utils::GetIpVersion(const std::string &address)
{
const std::regex regex4(R"(\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b)");
const std::regex regex6(
"(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-"
"9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-"
"fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-"
"9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|"
"fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,"
"1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:(("
"25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))");
if (std::regex_match(address, regex4))
return 4;
if (std::regex_match(address, regex6))
return 6;
return 0;
}
std::vector<uint8_t> utils::HexStringToVector(const std::string &hex)
{
if (hex.length() % 2 != 0)
throw std::runtime_error("hex string has an odd length");
for (char c : hex)
{
if (c >= '0' && c <= '9')
continue;
if (c >= 'a' && c <= 'f')
continue;
if (c >= 'A' && c <= 'F')
continue;
throw std::runtime_error("hex string contains invalid characters");
}
std::vector<uint8_t> bytes;
for (unsigned int i = 0; i < hex.length(); i += 2)
{
std::string byteString = hex.substr(i, 2);
char byte = (char)strtol(byteString.c_str(), nullptr, 16);
bytes.push_back(byte);
}
return bytes;
}
int utils::NextId()
{
int res = ++g_idCounter;
if (res == 0)
{
// ID counter overflows.
std::terminate();
}
return res;
}
int64_t utils::CurrentTimeMillis()
{
auto time = std::chrono::system_clock::now();
auto sinceEpoch = time.time_since_epoch();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(sinceEpoch);
int64_t now = millis.count();
return now;
}
TimeStamp utils::CurrentTimeStamp()
{
int64_t tms = CurrentTimeMillis();
int64_t baseTime;
if (tms < 2085978496000LL)
baseTime = tms - (-2208988800000LL);
else
baseTime = tms - 2085978496000LL;
int64_t seconds = baseTime / 1000;
int64_t fraction = ((baseTime % 1000) * 0x100000000LL) / 1000;
if (tms < 2085978496000LL)
seconds |= 0x80000000LL;
int64_t time = (seconds << 32LL) | fraction;
return TimeStamp(time);
}
OctetString utils::IpToOctetString(const std::string &address)
{
int ipVersion = GetIpVersion(address);
if (ipVersion == 4)
{
int bytes[4];
char dot;
std::stringstream ss(address);
ss >> bytes[0] >> dot >> bytes[1] >> dot >> bytes[2] >> dot >> bytes[3] >> dot;
std::vector<uint8_t> data(4);
data[0] = bytes[0];
data[1] = bytes[1];
data[2] = bytes[2];
data[3] = bytes[3];
return OctetString(std::move(data));
}
else if (ipVersion == 6)
{
std::vector<uint8_t> data{16};
if (!IPv6FromString(address.c_str(), data.data()))
return {};
return OctetString(std::move(data));
}
else
return {};
}
std::string utils::VectorToHexString(const std::vector<uint8_t> &hex)
{
std::string str(hex.size() * 2, '0');
for (size_t i = 0; i < hex.size(); i++)
{
uint8_t octet = hex[i];
int big = (octet >> 4) & 0xF;
int little = octet & 0xF;
char bigChar = static_cast<char>(big < 10 ? '0' + big : 'A' + (big - 10));
char littleChar = static_cast<char>(little < 10 ? '0' + little : 'A' + (little - 10));
str[i * 2] = bigChar;
str[i * 2 + 1] = littleChar;
}
return str;
}
bool utils::TryParseInt(const std::string &str, int &output)
{
return TryParseInt(str.c_str(), output);
}
bool utils::TryParseInt(const char *str, int &output)
{
int base = 10;
if (strlen(str) > 2)
{
if (str[0] == '0' && str[1] == 'x')
base = 16;
else if (str[0] == '0' && str[1] == 'b')
base = 2;
}
try
{
output = std::stoi(str, nullptr, base);
return true;
}
catch (...)
{
return false;
}
}
int utils::ParseInt(const std::string &str)
{
return ParseInt(str.c_str());
}
int utils::ParseInt(const char *str)
{
int n = 0;
TryParseInt(str, n);
return n;
}
void utils::Sleep(int ms)
{
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}
std::string utils::OctetStringToIp(const OctetString &address)
{
if (address.length() == 4)
{
char buffer[20] = {0};
sprintf(buffer, "%d.%d.%d.%d", address.getI(0), address.getI(1), address.getI(2), address.getI(3));
return std::string{buffer};
}
return address.toHexString();
}
bool utils::IsRoot()
{
return geteuid() == 0;
}
void utils::AssertNodeName(const std::string &str)
{
if (str.length() < cons::MinNodeName)
throw std::runtime_error("Node name assertion failed: string'" + str + "' is too short");
if (str.length() > cons::MaxNodeName)
throw std::runtime_error("Node name assertion failed: string'" + str + "' is too long");
for (char c : str)
{
if (c >= '0' && c <= '9')
continue;
if (c >= 'a' && c <= 'z')
continue;
if (c >= 'A' && c <= 'Z')
continue;
if (c == '-' || c == '_')
continue;
throw std::runtime_error("Node name assertion failed: string '" + str +
"' contains illegal character: " + std::string(1, c));
}
}
bool utils::IsNumeric(const std::string &str)
{
return !str.empty() && std::all_of(str.begin(), str.end(), [](char c) { return (c >= '0' && c <= '9'); });
}
void utils::Trim(std::string &s)
{
if (s.length() == 0)
return;
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); }));
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end());
}
void utils::Trim(std::stringstream &s)
{
std::string str{};
str = s.str();
Trim(str);
s.str(str);
}
bool utils::IsLittleEndian()
{
return htonl(1453) != 1453;
}
|
Jiang6334/goodhelper
|
src/main/java/com/okgo/goodhelper/service/Impl/GoodServiceImpl.java
|
<reponame>Jiang6334/goodhelper<filename>src/main/java/com/okgo/goodhelper/service/Impl/GoodServiceImpl.java<gh_stars>0
package com.okgo.goodhelper.service.Impl;
import com.okgo.goodhelper.mapper.GoodMapper;
import com.okgo.goodhelper.pojo.Good;
import com.okgo.goodhelper.service.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GoodServiceImpl implements GoodService {
@Autowired
private GoodMapper goodMapper;
@Override
public int selectXinazhiAmountByUserId(Integer user_id) {
return goodMapper.selectXinazhiAmountByUserId(user_id);
}
@Override
public boolean updateGoodStatus(Integer good_id, String status) {
return goodMapper.updateGoodStatus(good_id,status);
}
@Override
public List<Good> selectGoodList(Integer user_id) {
return goodMapper.selectGoodList(user_id);
}
@Override
public boolean addGood(Good good) {
return goodMapper.addGood(good);
}
@Override
public int changeGoodImage(String image, Integer good_id) {
return goodMapper.changeGoodImage(image,good_id);
}
@Override
public int addGoodImage(String image, Integer good_id) {
return goodMapper.insertGoodImage(image,good_id);
}
}
|
Phygon/aaf
|
Utilities/AAFAnalyzer/EditProtocolTestImpl/EPAnnotationVisitor.cpp
|
//=---------------------------------------------------------------------=
//
// $Id$ $Name$
//
// The contents of this file are subject to the AAF SDK Public Source
// License Agreement Version 2.0 (the "License"); You may not use this
// file except in compliance with the License. The License is available
// in AAFSDKPSL.TXT, or you may obtain a copy of the License from the
// Advanced Media Workflow Association, Inc., or its successor.
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and limitations
// under the License. Refer to Section 3.3 of the License for proper use
// of this Exhibit.
//
// WARNING: Please contact the Advanced Media Workflow Association,
// Inc., for more information about any additional licenses to
// intellectual property covering the AAF Standard that may be required
// to create and distribute AAF compliant products.
// (http://www.amwa.tv/policies).
//
// Copyright Notices:
// The Original Code of this file is Copyright 1998-2009, licensor of the
// Advanced Media Workflow Association. All rights reserved.
//
//=---------------------------------------------------------------------=
//Edit Protocol Test files
#include "EPAnnotationVisitor.h"
#include "EPAnnotationTest.h"
//Test/Result files
#include <DetailLevelTestResult.h>
#include <TestLevelTestResult.h>
#include <TestRegistry.h>
//Ax files
#include <AxComponent.h>
#include <AxEx.h>
#include <AxTaggedValue.h>
#include <AxKLVData.h>
#include <AxDefObject.h>
//AAF files
#include <AAFResult.h>
namespace {
} // end of namespace
//======================================================================
namespace aafanalyzer {
EPAnnotationVisitor::EPAnnotationVisitor( wostream& log,
boost::shared_ptr<EdgeMap> spEdgeMap,
boost::shared_ptr<TestLevelTestResult> spTestResult )
: _log(log),
_spEdgeMap( spEdgeMap ),
_spTestResult( spTestResult )
{
_isAncestorEssenceTrack.push( false );
_isAncestorEventMobSlot.push( false );
_isParentMobSlot.push( false );
}
EPAnnotationVisitor::~EPAnnotationVisitor()
{}
/*
*
* Components
*
*/
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFTransition>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFSegment>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFSequence>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFFiller>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFSourceReference>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFSourceClip>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFEvent>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFGPITrigger>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFEdgecode>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFTimecode>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFTimecodeStream>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFTimecodeStream12M>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFPulldown>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFOperationGroup>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFNestedScope>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFScopeReference>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFEssenceGroup>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFSelector>& node )
{
boost::shared_ptr<AAFTypedObjNode<IAAFComponent> > spGeneric( node.DownCastToAAF<IAAFComponent>() );
return this->PreOrderVisit( *spGeneric );
}
//Base Cases:
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFDescriptiveMarker>& node )
{
//This is a comment marker subclass, there is nothing that needs to be
//checked, but state must be updated.
_isParentMobSlot.push( false );
return true;
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFCommentMarker>& node )
{
bool testPassed = true;
//Need to ensure that parent is event mob slot
if ( _isAncestorEventMobSlot.top() )
{
_spTestResult->AddSingleResult(
L"REQ_EP_150",
this->GetMobSlotName( _spEdgeMap, node) + L" is an Event Mob Slot that contains a CommentMarker.",
TestResult::PASS,
node );
}
else
{
_spTestResult->AddSingleResult(
L"REQ_EP_150",
this->GetMobSlotName( _spEdgeMap, node) + L" is not an Event Mob Slot but contains a CommentMarker.",
TestResult::FAIL,
node );
testPassed = false;
}
//Update State
//If the traversal is going to stop, then the parent should not change as
//this nodes children will not be visited, and this node will not be post
//order visited.
if ( testPassed )
{
_isParentMobSlot.push( false );
}
return testPassed;
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFComponent>& node )
{
AxComponent axComponent( node.GetAAFObjectOfType() );
//Need to ensure that parent is a comment marker or mob slot
if ( axComponent.CountComments() != 0 )
{
//Component::UserComments is being used
if ( !_isParentMobSlot.top() )
{
//Parent is not a MobSlot and this is not a CommentMarker so fail
//the test.
_spTestResult->AddSingleResult(
L"REQ_EP_147",
this->GetMobSlotName( _spEdgeMap, node ) + L" contains a Component that illegally uses the Component::UserComments property.",
TestResult::FAIL,
node );
return false;
}
}
//Update state
_isParentMobSlot.push( false );
return true;
}
/*
*
* Mob Slot/Tracks
*
*/
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFTimelineMobSlot, EPAudioTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFTimelineMobSlot, EPVideoTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFTimelineMobSlot, EPEssenceTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFTimelineMobSlot, EPTimecodeTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFTimelineMobSlot, EPEdgecodeTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFTimelineMobSlot, EPNonEssenceTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFStaticMobSlot, EPAudioTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFStaticMobSlot, EPVideoTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFStaticMobSlot, EPEssenceTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFStaticMobSlot, EPTimecodeTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFStaticMobSlot, EPEdgecodeTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFStaticMobSlot, EPNonEssenceTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFEventMobSlot, EPAudioTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFEventMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFEventMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFEventMobSlot, EPVideoTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFEventMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFEventMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFEventMobSlot, EPTimecodeTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFEventMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFEventMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFEventMobSlot, EPEdgecodeTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFEventMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFEventMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFMobSlot, EPAudioTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFMobSlot, EPVideoTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFMobSlot, EPTimecodeTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFMobSlot, EPEdgecodeTrack>& node )
{
boost::shared_ptr<EPTypedObjNode<IAAFMobSlot, EPNonEssenceTrack> > spGeneric( node.DownCast<IAAFMobSlot, EPNonEssenceTrack>() );
return this->PreOrderVisit( *spGeneric );
}
//Base cases:
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFEventMobSlot, EPEssenceTrack>& node )
{
_isAncestorEventMobSlot.push( true );
_isParentMobSlot.push( true );
_isAncestorEssenceTrack.push( true );
return true;
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFEventMobSlot, EPNonEssenceTrack>& node )
{
_isAncestorEventMobSlot.push( true );
_isParentMobSlot.push( true );
_isAncestorEssenceTrack.push( false );
return true;
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFMobSlot, EPEssenceTrack>& node )
{
_isAncestorEventMobSlot.push( false );
_isParentMobSlot.push( true );
_isAncestorEssenceTrack.push( true );
return true;
}
bool EPAnnotationVisitor::PreOrderVisit( EPTypedObjNode<IAAFMobSlot, EPNonEssenceTrack>& node )
{
_isAncestorEventMobSlot.push( false );
_isParentMobSlot.push( true );
_isAncestorEssenceTrack.push( false );
return true;
}
/*
*
* Post-Order Visits
*
*/
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFComponent>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFTransition>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFSegment>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFSequence>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFFiller>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFSourceReference>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFSourceClip>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFEvent>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFGPITrigger>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFCommentMarker>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFDescriptiveMarker>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFEdgecode>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFTimecode>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFTimecodeStream>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFTimecodeStream12M>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFPulldown>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFOperationGroup>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFNestedScope>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFScopeReference>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFEssenceGroup>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFSelector>& node )
{
_isParentMobSlot.pop();
return true;
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFTimelineMobSlot>& node )
{
return PopStacks();
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFStaticMobSlot>& node )
{
return PopStacks();
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFEventMobSlot>& node )
{
return PopStacks();
}
bool EPAnnotationVisitor::PostOrderVisit( AAFTypedObjNode<IAAFMobSlot>& node )
{
return PopStacks();
}
/*
*
* TaggedValue/KLVData/Definitions
*
*/
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFTaggedValue>& node )
{
AxTaggedValue axTaggedVal( node.GetAAFObjectOfType() );
_taggedValueNames[axTaggedVal.GetName()] = node.GetSharedPointerToNode();
return false;
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFKLVData>& node )
{
AxKLVData axKLVData( node.GetAAFObjectOfType() );
_klvDataKeys[axKLVData.GetKey()] = node.GetSharedPointerToNode();
return false;
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFTaggedValueDefinition>& node )
{
AxTaggedValueDef axTaggedValDef( node.GetAAFObjectOfType() );
_taggedValueDefs.insert( axTaggedValDef.GetName() );
return false;
}
bool EPAnnotationVisitor::PreOrderVisit( AAFTypedObjNode<IAAFKLVDataDefinition>& node )
{
AxKLVDataDef axKLVDataDef( node.GetAAFObjectOfType() );
_klvDataDefs.insert( axKLVDataDef.GetAUID() );
return false;
}
/*
*
* Helper Functions
*
*/
bool EPAnnotationVisitor::PopStacks()
{
_isAncestorEssenceTrack.pop();
_isAncestorEventMobSlot.pop();
_isParentMobSlot.pop();
return true;
}
/*
*
* Check Functions
*
*/
void EPAnnotationVisitor::CheckForTaggedValueDefinitions()
{
//Remove all registered TaggedValues from the registered set.
set<AxString>::const_iterator dIter;
for ( dIter = _taggedValueDefs.begin(); dIter != _taggedValueDefs.end(); dIter++ )
{
_taggedValueNames.erase( *dIter );
}
//Fail for every unregistered TaggedValue
map<AxString, boost::shared_ptr<Node> >::const_iterator uIter;
for ( uIter = _taggedValueNames.begin(); uIter != _taggedValueNames.end(); uIter++ )
{
_spTestResult->AddSingleResult(
L"REQ_EP_151",
L"TaggedValue \"" + uIter->first + L"\" is not documented in the dictionary.",
TestResult::FAIL,
*uIter->second );
}
}
void EPAnnotationVisitor::CheckForKLVValueDefinitions()
{
//Remove all registered TaggedValues from the registered set.
set<aafUID_t>::const_iterator dIter;
for ( dIter = _klvDataDefs.begin(); dIter != _klvDataDefs.end(); dIter++ )
{
_klvDataKeys.erase( *dIter );
}
//Fail for every unregistered KLV value
map<aafUID_t, boost::shared_ptr<Node> >::const_iterator uIter;
for ( uIter = _klvDataKeys.begin(); uIter != _klvDataKeys.end(); uIter++ )
{
_spTestResult->AddSingleResult(
L"REQ_EP_152",
L"KLVData with key " + AxStringUtil::uid2Str(uIter->first) + L" is not documented in the dictionary.",
TestResult::FAIL,
*uIter->second );
}
}
} // end of namespace aafanalyzer
|
jxerome/tatami
|
web/src/main/webapp/app/shared/services/GroupService.js
|
<reponame>jxerome/tatami
TatamiApp.factory('GroupService', ['$resource', function($resource) {
return $resource('/tatami/rest/groups/:groupId', null,
{
'getStatuses': {
method: 'GET',
isArray: true,
params: { groupId: '@groupId' },
url: '/tatami/rest/groups/:groupId/timeline',
transformResponse: function(statuses) {
statuses = angular.fromJson(statuses);
for(var i = 0; i < statuses.length; i++) {
statuses[i]['avatarURL'] = statuses[i].avatar==='' ? '/assets/img/default_image_profile.png' : '/tatami/avatar/' + statuses[i].avatar + '/photo.jpg';
if(statuses[i].geoLocalization) {
var latitude = statuses[i].geoLocalization.split(',')[0].trim();
var longitude = statuses[i].geoLocalization.split(',')[1].trim();
statuses[i]['locationURL'] =
'https://www.openstreetmap.org/?mlon='
+ longitude + '&mlat=' + latitude;
}
}
return statuses;
}
},
'getMembers': {
method: 'GET',
isArray: true,
params: { groupId: '@groupId' },
url: '/tatami/rest/groups/:groupId/members/',
transformResponse: function(users) {
users = angular.fromJson(users);
for(var i = 0; i < users.length; i++) {
users[i]['avatarURL'] = users[i].avatar==='' ? '/assets/img/default_image_profile.png' : '/tatami/avatar/' + users[i].avatar + '/photo.jpg';
}
return users;
}
},
'getRecommendations': { method: 'GET', isArray: true, url: '/tatami/rest/groupmemberships/suggestions' },
'join': { method: 'PUT', params: { groupId: '@groupId', username: '@username' }, url: '/tatami/rest/groups/:groupId/members/:username' },
'leave': { method: 'DELETE', params: { groupId: '@groupId', username: '@username' }, url: '/tatami/rest/groups/:groupId/members/:username' },
'update': { method: 'PUT', params: { groupId: '@groupId' }, url: '/tatami/rest/groups/:groupId' }
});
}]);
|
albee/astrobee_android_td
|
core_apks/set_wallpaper/app/src/main/java/gov/nasa/arc/astrobee/set_wallpaper/MainActivity.java
|
package gov.nasa.arc.astrobee.set_wallpaper;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.io.IOException;
import java.net.URI;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickSetWallpaper(View v){
Intent intent = new Intent(this, SetupService.class);
startService(intent);
}
}
|
JesusSotoT/NMRepoLog
|
webapp/modulos/nominas/js/autorizacion.js
|
<filename>webapp/modulos/nominas/js/autorizacion.js
function irConfiguracion(){
window.parent.agregatab('../../modulos/nominas/index.php?c=Catalogos&f=configuracion','Configuracion','',2257);
window.parent.preguntar=true;
}
$(document).ready(function(){
$("#auto").on('click', function() {
var btnguardar = $(this);
btnguardar.button("loading");
if(confirm("¿Este proceso actualiza los acumulados y cambiala nomina de trabajo, esta seguro de continuar?")){
$.post("ajax.php?c=Prenomina&f=verificaPagoEmpleado",{
idnomina:$("#idnomina").val(),
fechafin:$("#fechafin").val(),
fechainicio:$("#fechainicio").val(),
idtipoperiodo:$("#idtipoperiodo").val(),
numnomina:$("#numnomina").val()
},function (request){
if(request == 2){
alert("No puede realizar la autorizacion!\nFaltan empleados de calcular en este periodo.");
btnguardar.button("reset");
}else if(request == 1){
alert("Nomina Autorizada");
btnguardar.button("reset");
window.location.reload();
}else{
alert("Error en proceso de autorizacion, intente de nuevo");
btnguardar.button("reset");
}
});
}else{
btnguardar.button("reset");
}
});
});
|
nicchagil/spring-framework
|
spring-test/src/main/java/org/springframework/test/context/web/package-info.java
|
/**
* Web support classes for the <em>Spring TestContext Framework</em>.
*/
@NonNullApi
@NonNullFields
package org.springframework.test.context.web;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
pblxptr/hhctrl-mgmt
|
src/common/command/base_command.hpp
|
#pragma once
#include <cstddef>
#include <common/command/command_id.hpp>
#include <common/command/command_id_generator.hpp>
namespace common::command
{
class BaseCommand
{
public:
explicit BaseCommand(CommandId_t command_id)
: id_{command_id}
{}
BaseCommand(const BaseCommand&) = delete;
BaseCommand(BaseCommand&&) = default;
BaseCommand& operator=(const BaseCommand&) = delete;
BaseCommand& operator=(BaseCommand&&) = default;
CommandId_t id() const
{
return id_;
}
private:
CommandId_t id_;
};
template<class DerivedCommand>
class GenericCommand : public BaseCommand
{
//Protected ctor and friend 'DerivedCommand' serve as a mechanism that prevent from
//wrong type being passsed as a DerivedCommand.
//E.g. one could create: class Derived : public GenericCommand<DerivedSTH> {}
//which would casue undefined behaviour later in the code.
//Unfortunately due to this constraint, each derived class cannot be an aggregate class thus needs to have e.g. a
//user-provided constructor.
protected:
friend DerivedCommand;
GenericCommand() : BaseCommand{CommandIdGenerator::get<DerivedCommand>()}
{}
};
}
|
guotao0628/Gohome
|
src/dal/dao/IClueDao.java
|
<filename>src/dal/dao/IClueDao.java
package dal.dao;
import model.entity.Clue;
import java.util.List;
/**
* @author Huleryo
* @date 2017/8/4
*
* 失踪人员线索数据接口,对应clue_table
*/
public interface IClueDao {
/**
* 插入记录
*
* @param clue 需要插入的记录
* @return true 插入成功
* false 插入失败
* */
boolean addClue(Clue clue);
/**
* 修改状态
*
* @param state 线索状态,0未确认,1确认是,2确认否
* @return true 修改成功
* false 修改失败
* */
boolean updateState(int state, int missingID, int clueID);
/**
* 根据missingID列表查询线索,并按上传时间逆序排列
*
* @param missingIDList missingID列表
* @return 查询到的线索列表
* */
List<Clue> getClueByMissingIDList(List missingIDList);
/**
* 根据missingID与clueID查找线索记录
*
* @param missingID 需要查找记录的missingID
* @param clueID 需要查找记录的clueID
* @return clue 查找到的记录
* null 未查找到记录
* */
Clue getByMissingID(int missingID, int clueID);
/**
* 查找最大的clueID
*
* @return -1 查找失败
* clueID 查找成功
* */
int getMaxClueID();
}
|
qq744788292/cnsoft
|
0.0.x/JAPC-MainHome/src/main/java/org/jfpc/platform/MS0A4/controller/MS0A4Controller.java
|
<filename>0.0.x/JAPC-MainHome/src/main/java/org/jfpc/platform/MS0A4/controller/MS0A4Controller.java
package org.jfpc.platform.MS0A4.controller;
import javax.annotation.Resource;
import org.jfpc.base.support.MyControllerSupport;
import org.jfpc.base.support.MyModelAndViewSupport;
import org.jfpc.platform.MS0A4.service.MS0A4Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("MS0A4")
/** 页面功能按钮定义*/
public class MS0A4Controller extends MyControllerSupport {
private static final Logger logger = LoggerFactory.getLogger(MS0A4Controller.class);
@Resource
protected MS0A4Service MS0A4Service_;
@Override
public MyModelAndViewSupport getModelAndView(){
return new MyModelAndViewSupport("MS0A4");
}
}
|
cyrusccy/Karabiner-Elements
|
src/core/grabber/include/manipulator/details/basic/to_delayed_action.hpp
|
<filename>src/core/grabber/include/manipulator/details/basic/to_delayed_action.hpp
#pragma once
class to_delayed_action final : public pqrs::dispatcher::extra::dispatcher_client {
public:
to_delayed_action(basic& basic,
const nlohmann::json& json) : dispatcher_client(),
basic_(basic),
current_delayed_action_id_(0) {
if (json.is_object()) {
for (auto it = std::begin(json); it != std::end(json); std::advance(it, 1)) {
// it.key() is always std::string.
const auto& key = it.key();
const auto& value = it.value();
if (key == "to_if_invoked") {
if (!value.is_array()) {
logger::get_logger().error("complex_modifications json error: `to_if_invoked` should be array: {0}", json.dump());
continue;
}
for (const auto& j : value) {
to_if_invoked_.emplace_back(j);
}
} else if (key == "to_if_canceled") {
if (!value.is_array()) {
logger::get_logger().error("complex_modifications json error: `to_if_canceled` should be array: {0}", json.dump());
continue;
}
for (const auto& j : value) {
to_if_canceled_.emplace_back(j);
}
} else {
logger::get_logger().error("complex_modifications json error: Unknown key: {0} in {1}", key, json.dump());
}
}
} else {
logger::get_logger().error("complex_modifications json error: `to_delayed_action` should be object: {0}", json.dump());
}
}
virtual ~to_delayed_action(void) {
detach_from_dispatcher([] {
});
}
void setup(const event_queue::entry& front_input_event,
const std::shared_ptr<manipulated_original_event>& current_manipulated_original_event,
const std::shared_ptr<event_queue::queue>& output_event_queue,
std::chrono::milliseconds delay_milliseconds) {
if (front_input_event.get_event_type() != event_type::key_down) {
return;
}
if (to_if_invoked_.empty() &&
to_if_canceled_.empty()) {
return;
}
++current_delayed_action_id_;
front_input_event_ = front_input_event;
current_manipulated_original_event_ = current_manipulated_original_event;
output_event_queue_ = output_event_queue;
auto delayed_action_id = current_delayed_action_id_;
auto now = time_utility::mach_absolute_time();
auto time_stamp = front_input_event.get_event_time_stamp().get_time_stamp();
auto duration = time_utility::to_absolute_time_duration(delay_milliseconds);
if (now < time_stamp) {
duration += time_stamp - now;
}
enqueue_to_dispatcher(
[this, delayed_action_id] {
if (current_delayed_action_id_ != delayed_action_id) {
return;
}
post_events(to_if_invoked_);
},
when_now() + time_utility::to_milliseconds(duration));
}
void cancel(const event_queue::entry& front_input_event) {
if (front_input_event.get_event_type() != event_type::key_down) {
return;
}
++current_delayed_action_id_;
post_events(to_if_canceled_);
}
bool needs_virtual_hid_pointing(void) const {
for (const auto& events : {to_if_invoked_,
to_if_canceled_}) {
if (std::any_of(std::begin(events),
std::end(events),
[](auto& e) {
return e.needs_virtual_hid_pointing();
})) {
return true;
}
}
return false;
}
private:
void post_events(const std::vector<to_event_definition>& events) {
if (front_input_event_) {
if (current_manipulated_original_event_) {
if (auto oeq = output_event_queue_.lock()) {
absolute_time_duration time_stamp_delay(0);
// Release from_mandatory_modifiers
basic_.post_lazy_modifier_key_events(*front_input_event_,
current_manipulated_original_event_->get_from_mandatory_modifiers(),
event_type::key_up,
time_stamp_delay,
*oeq);
// Post events
basic_.post_extra_to_events(*front_input_event_,
events,
*current_manipulated_original_event_,
time_stamp_delay,
*oeq);
// Restore from_mandatory_modifiers
basic_.post_lazy_modifier_key_events(*front_input_event_,
current_manipulated_original_event_->get_from_mandatory_modifiers(),
event_type::key_down,
time_stamp_delay,
*oeq);
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
}
}
}
current_manipulated_original_event_ = nullptr;
}
basic& basic_;
std::vector<to_event_definition> to_if_invoked_;
std::vector<to_event_definition> to_if_canceled_;
boost::optional<event_queue::entry> front_input_event_;
std::shared_ptr<manipulated_original_event> current_manipulated_original_event_;
std::weak_ptr<event_queue::queue> output_event_queue_;
int current_delayed_action_id_;
};
|
tobal/hackerrank
|
problem-solving/algorithms/warmup/plus-minus.scala
|
<reponame>tobal/hackerrank<filename>problem-solving/algorithms/warmup/plus-minus.scala
object Solution {
def plusMinus(arr: Array[Int]): Unit = {
println(arr.filter(_ > 0).size.toFloat / arr.size)
println(arr.filter(_ < 0).size.toFloat / arr.size)
println(arr.filter(_ == 0).size.toFloat / arr.size)
}
def main(args: Array[String]) {
val sc = new java.util.Scanner (System.in);
var n = sc.nextInt();
var arr = new Array[Int](n);
for(arr_i <- 0 to n-1) {
arr(arr_i) = sc.nextInt();
}
plusMinus(arr);
}
}
|
Fmendoza91/Proyecto-Final
|
www/wordpress/wp-content/plugins/wp-user-frontend/assets/js/wpuf-form-builder.js
|
<reponame>Fmendoza91/Proyecto-Final
;(function($) {
'use strict';
/**
* Only proceed if current page is a form builder page
*/
if (!$('#wpuf-form-builder').length) {
return;
}
if (!Array.prototype.hasOwnProperty('swap')) {
Array.prototype.swap = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
}
// check if an element is visible in browser viewport
function is_element_in_viewport (el) {
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
/**
* Vuex Store data
*/
var wpuf_form_builder_store = new Vuex.Store({
state: {
post: wpuf_form_builder.post,
form_fields: wpuf_form_builder.form_fields,
panel_sections: wpuf_form_builder.panel_sections,
field_settings: wpuf_form_builder.field_settings,
notifications: wpuf_form_builder.notifications,
settings: wpuf_form_builder.form_settings,
current_panel: 'form-fields',
editing_field_id: 0, // editing form field id
},
mutations: {
set_form_fields: function (state, form_fields) {
Vue.set(state, 'form_fields', form_fields);
},
set_form_settings: function (state, value) {
Vue.set(state, 'settings', value);
},
// set the current panel
set_current_panel: function (state, panel) {
if ('field-options' !== state.current_panel &&
'field-options' === panel &&
state.form_fields.length
) {
state.editing_field_id = state.form_fields[0].id;
}
state.current_panel = panel;
// reset editing field id
if ('form-fields' === panel) {
state.editing_field_id = 0;
}
},
// add show property to every panel section
panel_add_show_prop: function (state) {
state.panel_sections.map(function (section, index) {
if (!section.hasOwnProperty('show')) {
Vue.set(state.panel_sections[index], 'show', true);
}
});
},
// toggle panel sections
panel_toggle: function (state, index) {
state.panel_sections[index].show = !state.panel_sections[index].show;
},
// open field settings panel
open_field_settings: function (state, field_id) {
var field = state.form_fields.filter(function(item) {
return parseInt(field_id) === parseInt(item.id);
});
if ('field-options' === state.current_panel && field[0].id === state.editing_field_id) {
return;
}
if (field.length) {
state.editing_field_id = 0;
state.current_panel = 'field-options';
setTimeout(function () {
state.editing_field_id = field[0].id;
}, 400);
}
},
update_editing_form_field: function (state, payload) {
var i = 0;
for (i = 0; i < state.form_fields.length; i++) {
// check if the editing field exist in normal fields
if (state.form_fields[i].id === parseInt(payload.editing_field_id)) {
state.form_fields[i][payload.field_name] = payload.value;
}
// check if the editing field belong to a column field
if (state.form_fields[i].template === 'column_field') {
var innerColumnFields = state.form_fields[i].inner_fields;
for (const columnFields in innerColumnFields) {
if (innerColumnFields.hasOwnProperty(columnFields)) {
var columnFieldIndex = 0;
while (columnFieldIndex < innerColumnFields[columnFields].length) {
if (innerColumnFields[columnFields][columnFieldIndex].id === parseInt(payload.editing_field_id)) {
innerColumnFields[columnFields][columnFieldIndex][payload.field_name] = payload.value;
}
columnFieldIndex++;
}
}
}
}
}
},
// add new form field element
add_form_field_element: function (state, payload) {
state.form_fields.splice(payload.toIndex, 0, payload.field);
// bring newly added element into viewport
Vue.nextTick(function () {
var el = $('#form-preview-stage .wpuf-form .field-items').eq(payload.toIndex);
if (el && !is_element_in_viewport(el.get(0))) {
$('#builder-stage section').scrollTo(el, 800, {offset: -50});
}
});
},
// sorting inside stage
swap_form_field_elements: function (state, payload) {
state.form_fields.swap(payload.fromIndex, payload.toIndex);
},
clone_form_field_element: function (state, payload) {
var field = _.find(state.form_fields, function (item) {
return parseInt(item.id) === parseInt(payload.field_id);
});
var clone = $.extend(true, {}, field),
index = parseInt(payload.index) + 1;
clone.id = payload.new_id;
clone.name = clone.name + '_copy';
clone.is_new = true;
state.form_fields.splice(index, 0, clone);
},
// delete a field
delete_form_field_element: function (state, index) {
state.current_panel = 'form-fields';
state.form_fields.splice(index, 1);
},
// set fields for a panel section
set_panel_section_fields: function (state, payload) {
var section = _.find(state.panel_sections, function (item) {
return item.id === payload.id;
});
section.fields = payload.fields;
},
// notifications
addNotification: function(state, payload) {
state.notifications.push(payload);
},
deleteNotification: function(state, index) {
state.notifications.splice(index, 1);
},
cloneNotification: function(state, index) {
var clone = $.extend(true, {}, state.notifications[index]);
index = parseInt(index) + 1;
state.notifications.splice(index, 0, clone);
},
// update by it's property
updateNotificationProperty: function(state, payload) {
state.notifications[payload.index][payload.property] = payload.value;
},
updateNotification: function(state, payload) {
state.notifications[payload.index] = payload.value;
},
// add new form field element to column field
add_column_inner_field_element: function (state, payload) {
var columnFieldIndex = state.form_fields.findIndex(field => field.id === payload.toWhichColumnField);
if (state.form_fields[columnFieldIndex].inner_fields[payload.toWhichColumn] === undefined) {
state.form_fields[columnFieldIndex].inner_fields[payload.toWhichColumn] = [];
}
if (state.form_fields[columnFieldIndex].inner_fields[payload.toWhichColumn] !== undefined) {
var innerColumnFields = state.form_fields[columnFieldIndex].inner_fields[payload.toWhichColumn];
if ( innerColumnFields.filter(innerField => innerField.name === payload.field.name).length <= 0 ) {
state.form_fields[columnFieldIndex].inner_fields[payload.toWhichColumn].splice(payload.toIndex, 0, payload.field);
}
}
},
move_column_inner_fields: function(state, payload) {
var columnFieldIndex = state.form_fields.findIndex(field => field.id === payload.field_id),
innerFields = payload.inner_fields,
mergedFields = [];
Object.keys(innerFields).forEach(function (column) {
// clear column-1, column-2 and column-3 fields if move_to specified column-1
// add column-1, column-2 and column-3 fields to mergedFields, later mergedFields will move to column-1 field
if (payload.move_to === "column-1") {
innerFields[column].forEach(function(field){
mergedFields.push(field);
});
// clear current column inner fields
state.form_fields[columnFieldIndex].inner_fields[column].splice(0, innerFields[column].length);
}
// clear column-2 and column-3 fields if move_to specified column-2
// add column-2 and column-3 fields to mergedFields, later mergedFields will move to column-2 field
if (payload.move_to === "column-2") {
if ( column === "column-2" || column === "column-3" ) {
innerFields[column].forEach(function(field){
mergedFields.push(field);
});
// clear current column inner fields
state.form_fields[columnFieldIndex].inner_fields[column].splice(0, innerFields[column].length);
}
}
});
// move inner fields to specified column
if (mergedFields.length !== 0) {
mergedFields.forEach(function(field){
state.form_fields[columnFieldIndex].inner_fields[payload.move_to].splice(0, 0, field);
});
}
},
// sorting inside column field
swap_column_field_elements: function (state, payload) {
var columnFieldIndex = state.form_fields.findIndex(field => field.id === payload.field_id),
fieldObj = state.form_fields[columnFieldIndex].inner_fields[payload.fromColumn][payload.fromIndex];
if( payload.fromColumn !== payload.toColumn) {
// add the field object to the target column
state.form_fields[columnFieldIndex].inner_fields[payload.toColumn].splice(payload.toIndex, 0, fieldObj);
// remove the field index from the source column
state.form_fields[columnFieldIndex].inner_fields[payload.fromColumn].splice(payload.fromIndex, 1);
}else{
state.form_fields[columnFieldIndex].inner_fields[payload.toColumn].swap(payload.fromIndex, payload.toIndex);
}
},
// open field settings panel
open_column_field_settings: function (state, payload) {
var field = payload.column_field;
if ('field-options' === state.current_panel && field.id === state.editing_field_id) {
return;
}
if (field) {
state.editing_field_id = 0;
state.current_panel = 'field-options';
state.editing_field_type = 'column_field';
state.editing_column_field_id = payload.field_id;
state.edting_field_column = payload.column;
state.editing_inner_field_index = payload.index;
setTimeout(function () {
state.editing_field_id = field.id;
}, 400);
}
},
clone_column_field_element: function (state, payload) {
var columnFieldIndex = state.form_fields.findIndex(field => field.id === payload.field_id);
var field = _.find(state.form_fields[columnFieldIndex].inner_fields[payload.toColumn], function (item) {
return parseInt(item.id) === parseInt(payload.column_field_id);
});
var clone = $.extend(true, {}, field),
index = parseInt(payload.index) + 1;
clone.id = payload.new_id;
clone.name = clone.name + '_copy';
clone.is_new = true;
state.form_fields[columnFieldIndex].inner_fields[payload.toColumn].splice(index, 0, clone);
},
// delete a column field
delete_column_field_element: function (state, payload) {
var columnFieldIndex = state.form_fields.findIndex(field => field.id === payload.field_id);
state.current_panel = 'form-fields';
state.form_fields[columnFieldIndex].inner_fields[payload.fromColumn].splice(payload.index, 1);
},
}
});
/**
* The main form builder vue instance
*/
new Vue({
el: '#wpuf-form-builder',
mixins: wpuf_form_builder_mixins(wpuf_mixins.root),
store: wpuf_form_builder_store,
data: {
is_form_saving: false,
is_form_saved: false,
is_form_switcher: false,
post_title_editing: false,
isDirty: false
},
computed: {
current_panel: function () {
return this.$store.state.current_panel;
},
post: function () {
return this.$store.state.post;
},
form_fields_count: function () {
return this.$store.state.form_fields.length;
},
form_fields: function () {
return this.$store.state.form_fields;
},
notifications: function() {
return this.$store.state.notifications;
},
settings: function() {
return this.$store.state.settings;
}
},
watch: {
form_fields: {
handler: function() {
this.isDirty = true;
},
deep: true
}
},
created: function () {
this.$store.commit('panel_add_show_prop');
/**
* This is the event hub we'll use in every
* component to communicate between them
*/
wpuf_form_builder.event_hub = new Vue();
},
mounted: function () {
// primary nav tabs and their contents
this.bind_tab_on_click($('#wpuf-form-builder > fieldset > .nav-tab-wrapper > a'), '#wpuf-form-builder');
// secondary settings tabs and their contents
var settings_tabs = $('#wpuf-form-builder-settings .nav-tab'),
settings_tab_contents = $('#wpuf-form-builder-settings .tab-contents .group');
settings_tabs.first().addClass('nav-tab-active');
settings_tab_contents.first().addClass('active');
this.bind_tab_on_click(settings_tabs, '#wpuf-form-builder-settings');
var clipboard = new window.Clipboard('.form-id');
$(".form-id").tooltip();
var self = this;
clipboard.on('success', function(e) {
// Show copied tooltip
$(e.trigger)
.attr('data-original-title', 'Copied!')
.tooltip('show');
// Reset the copied tooltip
setTimeout(function() {
$(e.trigger).tooltip('hide')
.attr('data-original-title', self.i18n.copy_shortcode);
}, 1000);
e.clearSelection();
});
window.onbeforeunload = function () {
if ( self.isDirty ) {
return self.i18n.unsaved_changes;
}
};
},
methods: {
// tabs and their contents
bind_tab_on_click: function (tabs, scope) {
tabs.on('click', function (e) {
e.preventDefault();
var button = $(this),
tab_contents = $(scope + ' > fieldset > .tab-contents'),
group_id = button.attr('href');
button.addClass('nav-tab-active').siblings('.nav-tab-active').removeClass('nav-tab-active');
tab_contents.children().removeClass('active');
$(group_id).addClass('active');
});
},
// switch form
switch_form: function () {
this.is_form_switcher = (this.is_form_switcher) ? false : true;
},
// set current sidebar panel
set_current_panel: function (panel) {
this.$store.commit('set_current_panel', panel);
},
// save form builder data
save_form_builder: function () {
var self = this;
if (_.isFunction(this.validate_form_before_submit) && !this.validate_form_before_submit()) {
this.warn({
text: this.validation_error_msg
});
return;
}
self.is_form_saving = true;
self.set_current_panel('form-fields');
wp.ajax.send('wpuf_form_builder_save_form', {
data: {
form_data: $('#wpuf-form-builder').serialize(),
form_fields: JSON.stringify(self.form_fields),
notifications: JSON.stringify(self.notifications)
},
success: function (response) {
if (response.form_fields) {
self.$store.commit('set_form_fields', response.form_fields);
}
if (response.form_settings) {
self.$store.commit('set_form_settings', response.form_settings);
}
self.is_form_saving = false;
self.is_form_saved = true;
setTimeout(function(){
self.isDirty = false;
}, 500);
toastr.success(self.i18n.saved_form_data);
},
error: function () {
self.is_form_saving = false;
}
});
}
}
});
var SettingsTab = {
init: function() {
$(function() {
$('.datepicker').datetimepicker();
$('.wpuf-ms-color').wpColorPicker();
});
$('#wpuf-metabox-settings').on('change', 'select[name="wpuf_settings[redirect_to]"]', this.settingsRedirect);
$('#wpuf-metabox-settings-update').on('change', 'select[name="wpuf_settings[edit_redirect_to]"]', this.settingsRedirect);
$('select[name="wpuf_settings[redirect_to]"]').change();
$('select[name="wpuf_settings[edit_redirect_to]"]').change();
// Form settings: Payment
$('#wpuf-metabox-settings-payment').on('change', 'input[type=checkbox][name="wpuf_settings[payment_options]"]', this.settingsPayment);
$('input[type=checkbox][name="wpuf_settings[payment_options]"]').trigger('change');
// pay per post
$('#wpuf-metabox-settings-payment').on('change', 'input[type=checkbox][name="wpuf_settings[enable_pay_per_post]"]', this.settingsPayPerPost);
$('input[type=checkbox][name="wpuf_settings[enable_pay_per_post]"]').trigger('change');
// force pack purchase
$('#wpuf-metabox-settings-payment').on('change', 'input[type=checkbox][name="wpuf_settings[force_pack_purchase]"]', this.settingsForcePack);
$('input[type=checkbox][name="wpuf_settings[force_pack_purchase]"]').trigger('change');
// Form settings: Submission Restriction
// Form settings: Guest post
$('#wpuf-metabox-submission-restriction').on('change', 'input[type=checkbox][name="wpuf_settings[guest_post]"]', this.settingsGuest);
$('input[type=checkbox][name="wpuf_settings[guest_post]"]').trigger('change');
$('#wpuf-metabox-submission-restriction').on('change', 'input[type=checkbox][name="wpuf_settings[role_base]"]', this.settingsRoles);
$('input[type=checkbox][name="wpuf_settings[role_base]"]').trigger('change');
// From settings: User details
$('#wpuf-metabox-submission-restriction').on('change', 'input[type=checkbox][name="wpuf_settings[guest_details]"]', this.settingsGuestDetails);
// From settings: schedule form
$('#wpuf-metabox-submission-restriction').on('change', 'input[type=checkbox][name="wpuf_settings[schedule_form]"]', this.settingsRestriction);
$('input[type=checkbox][name="wpuf_settings[schedule_form]"]').trigger('change');
// From settings: limit entries
$('#wpuf-metabox-submission-restriction').on('change', 'input[type=checkbox][name="wpuf_settings[limit_entries]"]', this.settingsLimit);
$('input[type=checkbox][name="wpuf_settings[limit_entries]"]').trigger('change');
this.changeMultistepVisibility($('.wpuf_enable_multistep_section :input[type="checkbox"]'));
var self = this;
$('.wpuf_enable_multistep_section :input[type="checkbox"]').click(function() {
self.changeMultistepVisibility($(this));
});
this.showRegFormNotificationFields();
this.integrationsCondFieldsVisibility();
},
settingsGuest: function (e) {
e.preventDefault();
var table = $(this).closest('table');
if ( $(this).is(':checked') ) {
table.find('tr.show-if-guest').show();
table.find('tr.show-if-not-guest').hide();
$('input[type=checkbox][name="wpuf_settings[guest_details]"]').trigger('change');
} else {
table.find('tr.show-if-guest').hide();
table.find('tr.show-if-not-guest').show();
}
},
settingsRoles: function (e) {
e.preventDefault();
var table = $(this).closest('table');
if ( $(this).is(':checked') ) {
table.find('tr.show-if-roles').show();
} else {
table.find('tr.show-if-roles').hide();
}
},
settingsGuestDetails: function (e) {
e.preventDefault();
var table = $(this).closest('table');
if ( $(this).is(':checked') ) {
table.find('tr.show-if-details').show();
} else {
table.find('tr.show-if-details').hide();
}
},
settingsPayment: function (e) {
e.preventDefault();
var table = $(this).closest('table');
if ( $(this).is(':checked') ) {
table.find('tr.show-if-payment').show();
table.find('tr.show-if-force-pack').hide();
} else {
table.find('tr.show-if-payment').hide();
}
},
settingsPayPerPost: function (e) {
e.preventDefault();
var table = $(this).closest('table');
if ( $(this).is(':checked') ) {
table.find('tr.show-if-pay-per-post').show();
} else {
table.find('tr.show-if-pay-per-post').hide();
}
},
settingsForcePack: function (e) {
e.preventDefault();
var table = $(this).closest('table');
if ( $(this).is(':checked') ) {
table.find('tr.show-if-force-pack').show();
} else {
table.find('tr.show-if-force-pack').hide();
}
},
settingsRestriction: function (e) {
e.preventDefault();
var table = $(this).closest('table');
if ( $(this).is(':checked') ) {
table.find('tr.show-if-schedule').show();
} else {
table.find('tr.show-if-schedule').hide();
}
},
settingsLimit: function (e) {
e.preventDefault();
var table = $(this).closest('table');
if ( $(this).is(':checked') ) {
table.find('tr.show-if-limit-entries').show();
} else {
table.find('tr.show-if-limit-entries').hide();
}
},
settingsRedirect: function(e) {
e.preventDefault();
var $self = $(this),
$table = $self.closest('table'),
value = $self.val();
switch( value ) {
case 'post':
$table.find('tr.wpuf-page-id, tr.wpuf-url, tr.wpuf-same-page').hide();
break;
case 'page':
$table.find('tr.wpuf-page-id').show();
$table.find('tr.wpuf-same-page').hide();
$table.find('tr.wpuf-url').hide();
break;
case 'url':
$table.find('tr.wpuf-page-id').hide();
$table.find('tr.wpuf-same-page').hide();
$table.find('tr.wpuf-url').show();
break;
case 'same':
$table.find('tr.wpuf-page-id').hide();
$table.find('tr.wpuf-url').hide();
$table.find('tr.wpuf-same-page').show();
break;
}
},
changeMultistepVisibility: function(target) {
if (target.is(':checked')) {
$('.wpuf_multistep_content').show();
} else {
$('.wpuf_multistep_content').hide();
}
},
showRegFormNotificationFields: function() {
var newUserStatus = $( "input#wpuf_new_user_status" ),
emailVerification = $( "input#notification_type_verification" ),
welcomeEmail = $( "#notification_type_welcome_email" );
if ( newUserStatus.is(':checked') ) {
$('#wpuf_pending_user_admin_notification').show();
$('#wpuf_approved_user_admin_notification').hide();
} else{
$('#wpuf_pending_user_admin_notification').hide();
$('#wpuf_approved_user_admin_notification').show();
}
$( newUserStatus ).on( "click", function() {
$('#wpuf_pending_user_admin_notification').hide();
$('#wpuf_approved_user_admin_notification').show();
if ( newUserStatus.is(':checked') ) {
$('#wpuf_pending_user_admin_notification').show();
$('#wpuf_approved_user_admin_notification').hide();
}
});
if ( emailVerification.is(':checked') ) {
$('.wpuf-email-verification-settings-fields').show();
$('.wpuf-welcome-email-settings-fields').hide();
}
if ( welcomeEmail.is(':checked') ) {
$('.wpuf-welcome-email-settings-fields').show();
$('.wpuf-email-verification-settings-fields').hide();
}
$( emailVerification ).on( "click", function() {
$('.wpuf-email-verification-settings-fields').show();
$('.wpuf-welcome-email-settings-fields').hide();
});
$( welcomeEmail ).on( "click", function() {
$('.wpuf-welcome-email-settings-fields').show();
$('.wpuf-email-verification-settings-fields').hide();
});
},
integrationsCondFieldsVisibility: function() {
var conditional_logic = $( '.wpuf-integrations-conditional-logic' ),
cond_fields_container = $( '.wpuf-integrations-conditional-logic-container' ),
cond_fields = $( '.wpuf_available_conditional_fields' ),
cond_field_options = $( '.wpuf_selected_conditional_field_options' );
$( conditional_logic ).on( "click", function(e) {
$( cond_fields_container ).hide();
if ( e.target.value === 'yes' ) {
$( cond_fields_container ).show();
}
});
$( cond_fields ).on('focus', function(e) {
var form_fields = wpuf_form_builder.form_fields,
options = '';
options += '<option value="-1">- select -</option>';
form_fields.forEach(function(field) {
if ( field.template === 'radio_field' || field.template === 'checkbox_field' || field.template === 'dropdown_field' ) {
options += '<option value="'+field.name+'">'+field.label+'</option>';
}
});
e.target.innerHTML = options;
});
$( cond_fields ).on('change', function(e){
var form_fields = wpuf_form_builder.form_fields,
field_name = e.target.value,
field_options = '';
field_options += '<option value="-1">- select -</option>';
form_fields.forEach(function(field) {
if ( field.name === field_name ) {
var options = field.options;
for (var key in options) {
if (options.hasOwnProperty(key)) {
field_options += '<option value="'+key+'">'+options[key]+'</option>';
}
}
}
});
cond_field_options[0].innerHTML = field_options;
});
}
};
// on DOM ready
$(function() {
resizeBuilderContainer();
$("#collapse-menu").click(function () {
resizeBuilderContainer();
});
function resizeBuilderContainer() {
if ($(document.body).hasClass('folded')) {
$("#wpuf-form-builder").css("width", "calc(100% - 80px)");
} else {
$("#wpuf-form-builder").css("width", "calc(100% - 200px)");
}
}
SettingsTab.init();
});
// Mobile view menu toggle
$('#wpuf-form-builder').on('click', '#wpuf-toggle-field-options, #wpuf-toggle-show-form, .control-buttons .fa-pencil, .ui-draggable-handle', function() {
$('#wpuf-toggle-field-options').toggleClass('hide');
$('#wpuf-toggle-show-form').toggleClass('show');
$('#builder-form-fields').toggleClass('show');
});
$('#wpuf_settings_posttype').on('change', function() {
event.preventDefault();
var post_type = $(this).val();
wp.ajax.send('wpuf_form_setting_post', {
data: {
post_type: post_type,
wpuf_form_builder_setting_nonce: wpuf_form_builder.nonce
},
success: function (response) {
$('.wpuf_settings_taxonomy').remove();
$('.wpuf-post-fromat').after(response.data);
},
error: function ( error ) {
console.log(error);
}
});
});
})(jQuery);
|
xymor/file-metadata-manager
|
imports/ui/components/videos/VideosTable.js
|
<filename>imports/ui/components/videos/VideosTable.js<gh_stars>0
/* global window, confirm */
import React, { Component } from 'react';
import { _ } from 'meteor/underscore';
import { Table, Tr, Td } from 'reactable';
import { Button } from 'react-bootstrap';
import { css } from 'aphrodite';
import Loading from '../loading/Loading';
import UtilityStyles from '../../styles/utility';
import EditVideoModal from './EditVideoModal';
import { deleteVideo } from '../../../api/videos/methods';
class VideosTable extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false,
selectedVideo: null,
};
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
this.callRemoveVideo = this.callRemoveVideo.bind(this);
}
openModal(event, video) {
event.preventDefault();
this.setState({
selectedVideo: video,
showModal: true,
});
}
closeModal() {
this.setState({
showModal: false,
selectedVideo: null,
});
}
callRemoveVideo(videoId) {
if (confirm(
'Are you sure you want to remove this video? All metadata will be '
+ 'removed (but the original video on YouTube will stay in place).')) {
deleteVideo.call({ videoId });
}
}
renderRows() {
return this.props.videos.map(video => (
<Tr key={video.uid}>
<Td column="Title">
<a href="#edit" onClick={(event) => { this.openModal(event, video); }}>
{video.title}
</a>
</Td>
<Td column="Description" data={video.description} />
<Td column="Published Date" data={video.datePublished} />
<Td column="Action">
<div>
<Button
bsStyle="default"
className={`btn-fill ${css(UtilityStyles.marginRight5, UtilityStyles.marginTop2)}`}
onClick={() => {
window.open(`https://www.youtube.com/watch?v=${video.uid}`);
}}
bsSize="xsmall"
>
<i className="fa fa-external-link" />
Open Video
</Button>
<Button
bsStyle="danger"
className={`btn-fill ${css(UtilityStyles.marginTop2)}`}
onClick={() => { this.callRemoveVideo(video._id); }}
bsSize="xsmall"
>
<i className="fa fa-minus-circle" />
Remove
</Button>
</div>
</Td>
</Tr>
));
}
render() {
let content;
if (!this.props.videosReady) {
content = <Loading />;
} else if (this.props.videosReady && _.isEmpty(this.props.videos)) {
content = <p>No videos found.</p>;
} else {
content = (
<Table className="table">
{this.renderRows()}
</Table>
);
}
return (
<div className="videos-table">
{content}
<EditVideoModal
showModal={this.state.showModal}
closeModal={this.closeModal}
metadataSchema={this.props.metadataSchema}
video={this.state.selectedVideo}
/>
</div>
);
}
}
VideosTable.propTypes = {
videosReady: React.PropTypes.bool.isRequired,
videos: React.PropTypes.array.isRequired,
metadataSchema: React.PropTypes.object.isRequired,
};
export default VideosTable;
|
KaiSut0/interactive-hex-meshing
|
hex/src/views/QuadSurfaceView.cpp
|
#include "QuadSurfaceView.h"
#include <vkoo/core/VertexObject.h>
#include <vkoo/st/components/Mesh.h>
#include "logging.h"
namespace hex {
namespace {
const float kWireframeOffset = 1e-4f;
}
QuadSurfaceView::QuadSurfaceView(vkoo::Device& device,
vkoo::st::Node& parent_node,
const Options& options)
: device_{device}, options_{options} {
rand_eng_ = std::default_random_engine(options_.seed);
base_material_.colors["diffuse_color"] = options.base_color;
wireframe_material_.colors["diffuse_color"] = options.wireframe_color;
auto wrapper_node = std::make_unique<vkoo::st::Node>();
wrapper_node_ = wrapper_node.get();
parent_node.AddChild(std::move(wrapper_node));
}
vkoo::st::Node* QuadSurfaceView::GetWrapperNode() const {
return wrapper_node_;
}
std::unique_ptr<vkoo::st::Node> QuadSurfaceView::CreateNodeForAllPatches(
const std::vector<Vector3f>& vertices, const std::vector<Vector4i>& quads,
const std::vector<std::vector<size_t>>& patches,
const std::vector<glm::vec4>& patch_colors) {
auto node = std::make_unique<vkoo::st::Node>();
if (patches.empty()) {
return node;
}
std::vector<glm::vec3> positions;
std::vector<glm::vec3> normals;
std::vector<glm::vec4> colors;
std::vector<uint32_t> indices;
std::vector<glm::vec3> wireframe_positions;
std::vector<uint32_t> wireframe_indices;
for (size_t i = 0; i < patches.size(); i++) {
auto& patch = patches[i];
for (auto& quad_id : patch) {
auto& quad = quads[quad_id];
Vector3f v[4];
for (size_t k = 0; k < 4; k++) {
v[k] = vertices[quad(k)];
}
Vector3f n = (v[1] - v[0]).cross(v[2] - v[0]).normalized();
for (size_t k = 0; k < 4; k++) {
positions.push_back(ToGlm(v[k]));
normals.push_back(ToGlm(n));
colors.push_back(patch_colors.at(i));
wireframe_positions.push_back(positions.back() +
kWireframeOffset * normals.back());
}
uint32_t j = static_cast<uint32_t>(positions.size() - 4);
indices.insert(indices.end(), {j, j + 1, j + 2, j, j + 2, j + 3});
wireframe_indices.insert(
wireframe_indices.end(),
{j, j + 1, j + 1, j + 2, j + 2, j + 3, j + 3, j});
}
}
if (indices.size() > 0) {
auto vertex_object = std::make_shared<vkoo::VertexObject>(device_);
vertex_object->Update("position", positions);
vertex_object->Update("normal", normals);
vertex_object->Update("color", colors);
vertex_object->UpdateIndices(indices);
auto patches_node = std::make_unique<vkoo::st::Node>();
auto& mesh = patches_node->CreateComponent<vkoo::st::Mesh>(vertex_object,
indices.size());
mesh.UpdateShaderVariant(); // FIXME: we are using per-vertex color
// here, but there should be a more
// elegant way.
node->AddChild(std::move(patches_node));
}
if (wireframe_indices.size() > 0) {
auto vertex_object = std::make_shared<vkoo::VertexObject>(device_);
vertex_object->Update("position", wireframe_positions);
vertex_object->Update("normal", normals);
vertex_object->UpdateIndices(wireframe_indices);
auto wireframe_node = std::make_unique<vkoo::st::Node>();
auto& wireframe_mesh = wireframe_node->CreateComponent<vkoo::st::Mesh>(
vertex_object, wireframe_indices.size());
wireframe_mesh.SetMaterial(wireframe_material_);
wireframe_mesh.SetPolygonMode(vkoo::st::PolygonMode::Line);
wireframe_mesh.SetPrimitiveTopology(vkoo::st::PrimitiveTopology::LineList);
wireframe_mesh.SetLineWidth(2.0f);
node->AddChild(std::move(wireframe_node));
}
return node;
}
std::unique_ptr<vkoo::st::Node> QuadSurfaceView::CreateNodeForPatch(
const std::vector<Vector3f>& vertices, const std::vector<Vector4i>& quads,
const std::vector<size_t>& patch, const vkoo::st::Material& material) {
auto node = std::make_unique<vkoo::st::Node>();
if (patch.empty()) {
return node;
}
std::vector<glm::vec3> positions;
std::vector<glm::vec3> normals;
std::vector<uint32_t> indices;
std::vector<glm::vec3> wireframe_positions;
std::vector<uint32_t> wireframe_indices;
for (auto& quad_id : patch) {
auto& quad = quads[quad_id];
Vector3f v[4];
for (size_t k = 0; k < 4; k++) {
v[k] = vertices[quad(k)];
}
Vector3f n = (v[1] - v[0]).cross(v[2] - v[0]).normalized();
for (size_t k = 0; k < 4; k++) {
positions.push_back(ToGlm(v[k]));
normals.push_back(ToGlm(n));
wireframe_positions.push_back(positions.back() +
kWireframeOffset * normals.back());
}
uint32_t j = static_cast<uint32_t>(positions.size() - 4);
indices.insert(indices.end(), {j, j + 1, j + 2, j, j + 2, j + 3});
wireframe_indices.insert(wireframe_indices.end(),
{j, j + 1, j + 1, j + 2, j + 2, j + 3, j + 3, j});
}
{
auto vertex_object = std::make_shared<vkoo::VertexObject>(device_);
vertex_object->Update("position", positions);
vertex_object->Update("normal", normals);
vertex_object->UpdateIndices(indices);
auto patch_node = std::make_unique<vkoo::st::Node>();
auto& mesh = patch_node->CreateComponent<vkoo::st::Mesh>(vertex_object,
indices.size());
mesh.SetMaterial(material);
node->AddChild(std::move(patch_node));
}
{
auto vertex_object = std::make_shared<vkoo::VertexObject>(device_);
vertex_object->Update("position", wireframe_positions);
vertex_object->Update("normal", normals);
vertex_object->UpdateIndices(wireframe_indices);
auto wireframe_node = std::make_unique<vkoo::st::Node>();
auto& wireframe_mesh = wireframe_node->CreateComponent<vkoo::st::Mesh>(
vertex_object, wireframe_indices.size());
wireframe_mesh.SetMaterial(wireframe_material_);
wireframe_mesh.SetPolygonMode(vkoo::st::PolygonMode::Line);
wireframe_mesh.SetPrimitiveTopology(vkoo::st::PrimitiveTopology::LineList);
wireframe_mesh.SetLineWidth(2.0f);
node->AddChild(std::move(wireframe_node));
}
return node;
}
void QuadSurfaceView::Update(const QuadComplex& quad_complex,
const std::vector<glm::vec4>& patch_colors) {
wrapper_node_->RemoveAllChildren();
auto& complex_vertices = quad_complex.GetVertices();
auto& complex_quads = quad_complex.GetQuads();
auto& complex_patches = quad_complex.GetPatches();
auto node = CreateNodeForAllPatches(complex_vertices, complex_quads,
complex_patches, patch_colors);
wrapper_node_->AddChild(std::move(node));
}
void QuadSurfaceView::Update(const QuadrilateralMesh& quad_mesh) {
wrapper_node_->RemoveAllChildren();
auto& vertices = quad_mesh.GetVertices();
auto& quads = quad_mesh.GetQuads();
// Create a dummy patch that is the entire quad mesh.
std::vector<size_t> patch;
for (size_t i = 0; i < quads.size(); i++) {
patch.push_back(i);
}
auto node = CreateNodeForPatch(vertices, quads, patch, base_material_);
wrapper_node_->AddChild(std::move(node));
}
const vkoo::st::Material& QuadSurfaceView::GetPatchMaterial(size_t patch_id) {
std::uniform_real_distribution<float> dis(0.0f, 1.0f);
auto it = patch_materials_.find(patch_id);
if (it == patch_materials_.end()) {
glm::vec4 new_color((float)dis(rand_eng_), (float)dis(rand_eng_),
(float)dis(rand_eng_), 1.0f);
vkoo::st::Material new_material;
new_material.colors["diffuse_color"] = new_color;
auto emplace_it = patch_materials_.emplace(patch_id, new_material);
assert(emplace_it.second);
it = emplace_it.first;
}
return it->second;
}
} // namespace hex
|
sunnywang-arm/edk2-test
|
uefi-sct/SctPkg/TestCase/UEFI/IHV/Protocol/GraphicsOutput/BlackBoxTest/GraphicsOutputBBTestConformance.c
|
/** @file
Copyright 2006 - 2012 Unified EFI, Inc.<BR>
Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
/*++
Module Name:
GraphicsOutputBBTestConformance.c
Abstract:
Conformance Test Cases of Graphics Output Protocol
References:
UEFI 2.0 Specification
Graphics Output Protocol Test Design Specification
UEFI/Tiano DXE Test Case Writer's Guide
--*/
#include "SctLib.h"
#include "GraphicsOutputBBTest.h"
//
// TDS 4.2.1
//
EFI_STATUS
BBTestQueryModeConformanceAutoTest (
IN EFI_BB_TEST_PROTOCOL *This,
IN VOID *ClientInterface,
IN EFI_TEST_LEVEL TestLevel,
IN EFI_HANDLE SupportHandle
)
/*++
Routine Description:
Entrypoint for EFI_GRAPHICS_OUTPUT_PROTOCOL.QueryMode() Conformance Test
Arguments:
This - A pointer of EFI_BB_TEST_PROTOCOL
ClientInterface - A pointer to the interface to be tested
TestLevel - Test "thoroughness" control
SupportHandle - A handle containing protocols required
Returns:
EFI_SUCCESS - Finish the test successfully
--*/
{
EFI_STANDARD_TEST_LIBRARY_PROTOCOL *StandardLib;
EFI_STATUS Status;
EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput;
EFI_TEST_ASSERTION AssertionType;
EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *info;
UINTN sizeofInfo;
UINT32 mode;
GraphicsOutput = (EFI_GRAPHICS_OUTPUT_PROTOCOL *) ClientInterface;
if ((Status = InitTestEnv (SupportHandle, &StandardLib, GraphicsOutput)) != EFI_SUCCESS) {
return Status;
}
info = NULL;
sizeofInfo = 0;
//
// Assertion Point
// QueryMode should not succeed with invalid parameter
//
//
// mode number is invalid
//
mode = GraphicsOutput->Mode->MaxMode;
sizeofInfo = sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION);
Status = GraphicsOutput->QueryMode (
GraphicsOutput,
mode,
&sizeofInfo,
&info
);
if (Status != EFI_INVALID_PARAMETER) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
} else {
AssertionType = EFI_TEST_ASSERTION_PASSED;
}
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputQueryModeConformanceTestAssertionGuid001,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.QueryMode - QueryMode() with MaxMode",
L"%a:%d:maxmode: %d,Status:%r, Expected:%r",
__FILE__,
(UINTN)__LINE__,
mode,
Status,
EFI_INVALID_PARAMETER
);
mode = GraphicsOutput->Mode->Mode;
//
// &sizeofInfo is invalid
//
Status = GraphicsOutput->QueryMode (
GraphicsOutput,
mode,
NULL,
&info
);
if (Status != EFI_INVALID_PARAMETER) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
} else {
AssertionType = EFI_TEST_ASSERTION_PASSED;
}
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputQueryModeConformanceTestAssertionGuid002,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.QueryMode - QueryMode() with NULL &SizeofInfo",
L"%a:%d: Input invalide &SizeofInfo,Status:%r, Expected:%r",
__FILE__,
(UINTN)__LINE__,
Status,
EFI_INVALID_PARAMETER
);
//
// &info is invalid
//
Status = GraphicsOutput->QueryMode (
GraphicsOutput,
mode,
&sizeofInfo,
NULL
);
if (Status != EFI_INVALID_PARAMETER) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
} else {
AssertionType = EFI_TEST_ASSERTION_PASSED;
}
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputQueryModeConformanceTestAssertionGuid003,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.QueryMode - QueryMode() with NULL &info",
L"%a:%d:, Input invalid &Info, Status:%r, Expected:%r",
__FILE__,
(UINTN)__LINE__,
Status,
EFI_INVALID_PARAMETER
);
//
//
//
for (mode = 0; mode < GraphicsOutput->Mode->MaxMode; mode++) {
sizeofInfo = 0;
info = NULL;
Status = GraphicsOutput->QueryMode (
GraphicsOutput,
mode,
&sizeofInfo,
&info
);
if (Status == EFI_INVALID_PARAMETER) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
} else {
AssertionType = EFI_TEST_ASSERTION_PASSED;
}
if (info == NULL) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
}
if (sizeofInfo != sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION)) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
}
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputQueryModeConformanceTestAssertionGuid004,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.QueryMode - QueryMode() with valid ModeNumber",
L"%a:%d:,size_out:%d,ModeNumber:%d,Status:%r, Expected:any value except %r",
(UINTN) __FILE__,
(UINTN) (UINTN)__LINE__,
(UINTN) sizeofInfo,
(UINTN) mode,
(UINTN) Status,
EFI_INVALID_PARAMETER
);
if (info != NULL) {
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputQueryModeConformanceTestAssertionGuid005,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.QueryMode - QueryMode() with ModeNumber, dump info structure",
L"%a:%d:,ModeNumber:%d,dump of info: version:%d, horizonResolution:%d, VerticalResolution:%d, PixelFormat:%d, RedMask:%x,GreenMask:%x,BlueMask:%x,ReserveMask:%x,PixelPerScanline:%d",
(UINTN) __FILE__,
(UINTN) (UINTN)__LINE__,
(UINTN) mode,
(UINTN) info->Version,
(UINTN) info->HorizontalResolution,
(UINTN) info->VerticalResolution,
(UINTN) info->PixelFormat,
(UINTN) info->PixelInformation.RedMask,
(UINTN) info->PixelInformation.GreenMask,
(UINTN) info->PixelInformation.BlueMask,
(UINTN) info->PixelInformation.ReservedMask,
(UINTN) info->PixelsPerScanLine
);
gtBS->FreePool ((VOID *)info);
}
}
//
// Check the mode structure
//
AssertionType = EFI_TEST_ASSERTION_PASSED;
if (GraphicsOutput->Mode == NULL) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
}
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputQueryModeConformanceTestAssertionGuid006,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.QueryMode - Dump the Mode structure",
L"%a:%d:, dump of Mode: MaxMode:%d, current mode:%d, Info addre:%x, sizeofInfo:%d, frameBufferBase:%x, FrameBufferSize:%x",
(UINTN) __FILE__,
(UINTN) (UINTN)__LINE__,
(UINTN) GraphicsOutput->Mode->MaxMode,
(UINTN) GraphicsOutput->Mode->Mode,
(UINTN) GraphicsOutput->Mode->Info,
(UINTN) GraphicsOutput->Mode->SizeOfInfo,
(UINTN) GraphicsOutput->Mode->FrameBufferBase,
(UINTN) GraphicsOutput->Mode->FrameBufferSize
);
return EFI_SUCCESS;
}
//
// TDS 4.2.3
//
EFI_STATUS
BBTestBltConformanceAutoTest (
IN EFI_BB_TEST_PROTOCOL *This,
IN VOID *ClientInterface,
IN EFI_TEST_LEVEL TestLevel,
IN EFI_HANDLE SupportHandle
)
/*++
Routine Description:
Entrypoint for EFI_GRAPHICS_OUTPUT_PROTOCOL.Blt() Conformance Test
Arguments:
This - A pointer of EFI_BB_TEST_PROTOCOL
ClientInterface - A pointer to the interface to be tested
TestLevel - Test "thoroughness" control
SupportHandle - A handle containing protocols required
Returns:
EFI_SUCCESS - Finish the test successfully
--*/
{
EFI_STANDARD_TEST_LIBRARY_PROTOCOL *StandardLib;
EFI_STATUS Status;
EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput;
EFI_TEST_ASSERTION AssertionType;
EFI_GRAPHICS_OUTPUT_BLT_PIXEL BltBuffer[10];
UINTN SourceX;
UINTN SourceY;
UINTN DestinationX;
UINTN DestinationY;
UINTN Width;
UINTN Height;
UINTN Delta;
UINTN Index;
EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation;
SourceX = 0;
SourceY = 0;
DestinationX = 0;
DestinationY = 0;
Width = 1;
Height = 1;
Delta = 0;
GraphicsOutput = (EFI_GRAPHICS_OUTPUT_PROTOCOL *) ClientInterface;
if ((Status = InitTestEnv (SupportHandle, &StandardLib, GraphicsOutput)) != EFI_SUCCESS) {
return Status;
}
//
// Assertion Point
// Blt should not succeed with invalid parameter
//
for (Index = 0; Index < 6; Index++) {
switch (Index) {
case 0:
BltOperation = EfiGraphicsOutputBltOperationMax;
break;
case 1:
BltOperation = EfiGraphicsOutputBltOperationMax + 1;
break;
case 2:
BltOperation = EfiGraphicsOutputBltOperationMax + 10;
break;
case 3:
BltOperation = EfiGraphicsOutputBltOperationMax + 100;
break;
case 4:
BltOperation = EfiGraphicsOutputBltOperationMax + 1000;
break;
case 5:
BltOperation = -1;
break;
default:
BltOperation = EfiGraphicsOutputBltOperationMax - 1;
break;
}
//
// test data verification
//
Status = GraphicsOutput->Blt (
GraphicsOutput,
BltBuffer,
BltOperation,
SourceX,
SourceY,
DestinationX,
DestinationY,
Width,
Height,
Delta
);
if (Status != EFI_INVALID_PARAMETER) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
} else {
AssertionType = EFI_TEST_ASSERTION_PASSED;
}
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputBltConformanceTestAssertionGuid001,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.Blt - Blt() with invalid BltOperation",
L"%a:%d: Status = %r,Expected = %r, Source=(%dx%d), Destination=(%dx%d), Width=%d, Height=%d, Delta=%d,BltOperation=%d",
__FILE__,
(UINTN)__LINE__,
Status,
EFI_INVALID_PARAMETER,
DestinationX,
DestinationY,
0,
0,
Width,
Height,
Delta,
BltOperation
);
}
return EFI_SUCCESS;
}
//
// TDS 4.2.2
//
EFI_STATUS
BBTestSetModeConformanceAutoTest (
IN EFI_BB_TEST_PROTOCOL *This,
IN VOID *ClientInterface,
IN EFI_TEST_LEVEL TestLevel,
IN EFI_HANDLE SupportHandle
)
/*++
Routine Description:
Entrypoint for EFI_GRAPHICS_OUTPUT_PROTOCOL.SetMode() Conformance Test
Arguments:
This - A pointer of EFI_BB_TEST_PROTOCOL
ClientInterface - A pointer to the interface to be tested
TestLevel - Test "thoroughness" control
SupportHandle - A handle containing protocols required
Returns:
EFI_SUCCESS - Finish the test successfully
--*/
{
EFI_STANDARD_TEST_LIBRARY_PROTOCOL *StandardLib;
EFI_STATUS Status;
EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput;
EFI_TEST_ASSERTION AssertionType;
UINT32 Index;
UINT32 CurrentMode;
UINT32 MaxMode;
UINTN sizeofInfo;
EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *info;
GraphicsOutput = (EFI_GRAPHICS_OUTPUT_PROTOCOL *) ClientInterface;
CurrentMode = GraphicsOutput->Mode->Mode;
if ((Status = InitTestEnv (SupportHandle, &StandardLib, GraphicsOutput)) != EFI_SUCCESS) {
return Status;
}
//
// Assertion Point
//
//
MaxMode = GraphicsOutput->Mode->MaxMode;
for (Index = 0; Index < MaxMode; Index++) {
Status = GraphicsOutput->SetMode (
GraphicsOutput,
Index
);
if (Status == EFI_UNSUPPORTED) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
} else {
AssertionType = EFI_TEST_ASSERTION_PASSED;
}
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputSetModeConformanceTestAssertionGuid001,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.SetMode - SetMode() with valid mode",
L"%a:%d: mode:%d,Status = %r,Expected = not EFI_UNSUPPORTED ",
__FILE__,
(UINTN)__LINE__,
Index,
Status
);
//
// Check the content of info
//
if (Status == EFI_SUCCESS) {
sizeofInfo = 0;
info = NULL;
Status = GraphicsOutput->QueryMode (
GraphicsOutput,
Index,
&sizeofInfo,
&info
);
if (Status != EFI_SUCCESS) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
} else {
AssertionType = EFI_TEST_ASSERTION_PASSED;
}
if (SctCompareMem ((VOID *) info,
(void *) GraphicsOutput->Mode->Info,
sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION)
) != 0) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
}
if (info != NULL) {
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputSetModeConformanceTestAssertionGuid002,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.SetMode - SetMode() then QueryMode(), compare Info structure",
L"%a:%d: dump of query result:ver:%d, hRes:%d, VRes:%d, PixelFmt:%d, RMsk:%x,GMsk:%x,BMsk:%x,ReserveMask:%x,PixelPerScanline:%d\n dump of GOP->Info:ver:%d, hRes:%d, VRes:%d, PixelFmt:%d, RMsk:%x,GMsk:%x,BMsk:%x,ReserveMask:%x,PixelPerScanline:%d",
(UINTN) __FILE__,
(UINTN) (UINTN)__LINE__,
(UINTN) info->Version,
(UINTN) info->HorizontalResolution,
(UINTN) info->VerticalResolution,
(UINTN) info->PixelFormat,
(UINTN) info->PixelInformation.RedMask,
(UINTN) info->PixelInformation.GreenMask,
(UINTN) info->PixelInformation.BlueMask,
(UINTN) info->PixelInformation.ReservedMask,
(UINTN) info->PixelsPerScanLine,
(UINTN) GraphicsOutput->Mode->Info->Version,
(UINTN) GraphicsOutput->Mode->Info->HorizontalResolution,
(UINTN) GraphicsOutput->Mode->Info->VerticalResolution,
(UINTN) GraphicsOutput->Mode->Info->PixelFormat,
(UINTN) GraphicsOutput->Mode->Info->PixelInformation.RedMask,
(UINTN) GraphicsOutput->Mode->Info->PixelInformation.GreenMask,
(UINTN) GraphicsOutput->Mode->Info->PixelInformation.BlueMask,
(UINTN) GraphicsOutput->Mode->Info->PixelInformation.ReservedMask,
(UINTN) GraphicsOutput->Mode->Info->PixelsPerScanLine
);
gtBS->FreePool (info);
}
}
}
Status = GraphicsOutput->SetMode (
GraphicsOutput,
MaxMode
);
if (Status != EFI_UNSUPPORTED) {
AssertionType = EFI_TEST_ASSERTION_FAILED;
} else {
AssertionType = EFI_TEST_ASSERTION_PASSED;
}
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gGraphicsOutputSetModeConformanceTestAssertionGuid003,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.SetMode - SetMode() with invalid (max)mode",
L"%a:%d: mode:%d,Status = %r,Expected = EFI_UNSUPPORTED ",
__FILE__,
(UINTN)__LINE__,
MaxMode,
Status
);
//
// restore
// restore the orignal Mode
//
Status = GraphicsOutput->SetMode (GraphicsOutput, CurrentMode);
if (Status == EFI_SUCCESS) {
AssertionType = EFI_TEST_ASSERTION_PASSED;
} else {
AssertionType = EFI_TEST_ASSERTION_FAILED;
}
StandardLib->RecordAssertion (
StandardLib,
AssertionType,
gTestGenericFailureGuid,
L"EFI_GRAPHICS_OUTPUT_PROTOCOL.SetMode - SetMode() Function Test,restore the orignal Mode",
L"%a:%d:Status:%r, Expected:EFI_SUCCESS",
__FILE__,
(UINTN)__LINE__,
Status
);
return EFI_SUCCESS;
}
|
ScalablyTyped/SlinkyTyped
|
d/devexpress-web/src/main/scala/typingsSlinky/devexpressWeb/global/ASPxClientRichEditKeyDownEventArgs.scala
|
package typingsSlinky.devexpressWeb.global
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
/**
* Provides data for the ASPxClientRichEdit.KeyDown event.
*/
@JSGlobal("ASPxClientRichEditKeyDownEventArgs")
@js.native
class ASPxClientRichEditKeyDownEventArgs protected ()
extends typingsSlinky.devexpressWeb.ASPxClientRichEditKeyDownEventArgs {
/**
* Initializes a new instance of the ASPxClientRichEditKeyDownEventArgs object. For internal use only.
* @param htmlEvent A DHTML event object that relates to the processed event.
* @param handled true if the event is handled and no default processing is required; otherwise false.
*/
def this(htmlEvent: js.Any, handled: Boolean) = this()
}
|
uhef/Oskari-Routing-frontend
|
bundles/framework/bundle/userguide/locale/fi.js
|
Oskari.registerLocalization(
{
"lang": "fi",
"key": "userinterface.UserGuide",
"value": {
"title": "Ohje",
"desc": "",
"flyout": {
"title": "Käyttöohje",
"loadingtxt": "<p>ladataan sisältöä</p>"
},
"tile": {
"title": "Käyttöohjeet"
},
"error": {
"title": "Virhe!",
"generic": "Ohjeen lataaminen epäonnistui. Yritä myöhemmin uudelleen."
},
"tabs": [
{"title": "Karttaikkuna", "tags": "ohje_karttaikkuna"},
{"title": "Kartan julkaisu", "tags": "ohje_karttajulkaisu"},
{"title": "Teemakartat", "tags": "ohje_teemakartat"},
{"title": "Analyysi", "tags": "ohje_analyysi"}
],
"help": {
"tags": "karttaikkuna,pikaohje",
"contentPart": "body"
}
}
}
);
|
smohan-dw/connector-app
|
e2e/claim-offer.spec.js
|
<filename>e2e/claim-offer.spec.js
describe('Claim Offer', () => {
it('Received Claim Offer and Accept', async () => {
// verify Claim Offer popup shows up
// verify close button, attributes, ignore, and accept button is present
// tap on Accept
// verify Continue popup shows up
// tap on continue
// verify user is redirected to Dashboard screen
// tap on Connection bubble from which Claim Offer came
// verify Connection History popup shows up
// verify delete connection, close popup, connection logo, and connection history are present
// verify claim offer "RECEIVED" entry is present
// tap on "RECEIVED"
// verify History Details screen shows up
// verify attributes is present
// verify back button is present
// tap on back button
// user should come back to connection history popup
// tap close button
// user should back to dashboard screen
})
it('Received Claim Offer and Ignore', async () => {
// verify Claim Offer popup shows up
// verify close button, attributes, ignore, and accept button is present
// tap on Ignore
// verify user is redirected to Dashboard screen
})
})
|
lechium/tvOS144Headers
|
usr/libexec/passd/PDDiscoveryService.h
|
<gh_stars>1-10
//
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <PassKitCore/PDXPCService.h>
#import "PDDiscoveryServiceExportedInterface-Protocol.h"
@class NSString, PDDiscoveryManager, PDRuleManager, PKEntitlementWhitelist;
@interface PDDiscoveryService : PDXPCService <PDDiscoveryServiceExportedInterface>
{
PKEntitlementWhitelist *_whitelist; // 8 = 0x8
_Bool _entitledForDiscoveryUse; // 16 = 0x10
PDDiscoveryManager *_discoveryManager; // 24 = 0x18
PDRuleManager *_ruleManager; // 32 = 0x20
}
- (void).cxx_destruct; // IMP=0x00000001001e18e4
@property(retain, nonatomic) PDRuleManager *ruleManager; // @synthesize ruleManager=_ruleManager;
@property(retain, nonatomic) PDDiscoveryManager *discoveryManager; // @synthesize discoveryManager=_discoveryManager;
- (void)removeDiscoveryUserNotificationsWithCompletion:(CDUnknownBlockType)arg1; // IMP=0x00000001001e172c
- (void)evaluateRulesWithIdentifiers:(id)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x00000001001e15f4
- (void)deleteRuleWithIdentifier:(id)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x00000001001e14a4
- (void)insertRule:(id)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x00000001001e1354
- (void)rulesWithCompletion:(CDUnknownBlockType)arg1; // IMP=0x00000001001e11dc
- (void)displayedDiscoveryItemWithIdentifier:(id)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x00000001001e108c
- (void)displayedDiscoveryEngagementMessageWithIdentifier:(id)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x00000001001e0f3c
- (void)removeDiscoveryMessageWithIdentifier:(id)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x00000001001e0d98
- (void)insertDiscoveryEngagementMessages:(id)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x00000001001e0bf4
- (void)updateDiscoveryEngagementMessageWithIdentifier:(id)arg1 forAction:(long long)arg2 completion:(CDUnknownBlockType)arg3; // IMP=0x00000001001e09c4
- (void)discoveryEngagementMessagesForPassUniqueIdentifier:(id)arg1 active:(unsigned long long)arg2 completion:(CDUnknownBlockType)arg3; // IMP=0x00000001001e07fc
- (void)processDiscoveryItemsAndMessagesWithCompletion:(CDUnknownBlockType)arg1; // IMP=0x00000001001e068c
- (void)insertDiscoveryItems:(id)arg1 discoveryArticleLayouts:(id)arg2 completion:(CDUnknownBlockType)arg3; // IMP=0x00000001001e0498
- (void)discoveryItemsWithCompletion:(CDUnknownBlockType)arg1; // IMP=0x00000001001e0320
- (void)updateDiscoveryManifestWithCompletion:(CDUnknownBlockType)arg1; // IMP=0x00000001001e0228
- (void)updateDiscoveryItemWithIdentifier:(id)arg1 forAction:(long long)arg2 completion:(CDUnknownBlockType)arg3; // IMP=0x00000001001dffcc
- (void)discoveryArticleLayoutForItemWithIdentifier:(id)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x00000001001dfde4
- (void)discoveryArticleLayoutsWithCompletion:(CDUnknownBlockType)arg1; // IMP=0x00000001001dfc6c
- (void)dispatchDiscoveryRequestBlock:(CDUnknownBlockType)arg1 errorBlock:(CDUnknownBlockType)arg2; // IMP=0x00000001001df9ec
- (id)remoteObjectProxyWithErrorHandler:(CDUnknownBlockType)arg1; // IMP=0x00000001001df9b0
- (id)remoteObjectProxy; // IMP=0x00000001001df974
- (void)sendDiscoveryEngagementMessagesUpdated; // IMP=0x00000001001df918
- (void)sendDiscoveryArticleLayoutsUpdated:(id)arg1; // IMP=0x00000001001df88c
- (id)initWithConnection:(id)arg1; // IMP=0x00000001001df7d0
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
PrachiPrakash/flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/metrics/DescriptiveStatisticsHistogramStatistics.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.flink.runtime.metrics;
import org.apache.flink.metrics.HistogramStatistics;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import java.util.Arrays;
/**
* DescriptiveStatistics histogram statistics implementation returned by {@link DescriptiveStatisticsHistogram}.
* The statistics class wraps a {@link DescriptiveStatistics} instance and forwards the method calls accordingly.
*/
public class DescriptiveStatisticsHistogramStatistics extends HistogramStatistics {
private final DescriptiveStatistics descriptiveStatistics;
public DescriptiveStatisticsHistogramStatistics(DescriptiveStatistics latencyHistogram) {
this.descriptiveStatistics = latencyHistogram;
}
@Override
public double getQuantile(double quantile) {
return descriptiveStatistics.getPercentile(quantile * 100);
}
@Override
public long[] getValues() {
return Arrays.stream(descriptiveStatistics.getValues()).mapToLong(i -> (long) i).toArray();
}
@Override
public int size() {
return (int) descriptiveStatistics.getN();
}
@Override
public double getMean() {
return descriptiveStatistics.getMean();
}
@Override
public double getStdDev() {
return descriptiveStatistics.getStandardDeviation();
}
@Override
public long getMax() {
return (long) descriptiveStatistics.getMax();
}
@Override
public long getMin() {
return (long) descriptiveStatistics.getMin();
}
}
|
matzew/eventing-kafka
|
pkg/channel/distributed/dispatcher/dispatcher/dispatcher_test.go
|
package dispatcher
import (
"encoding/json"
"fmt"
"os"
"github.com/Shopify/sarama"
"github.com/ghodss/yaml"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
commonconfig "knative.dev/eventing-kafka/pkg/channel/distributed/common/config"
"knative.dev/eventing-kafka/pkg/channel/distributed/common/constants"
kafkaconsumer "knative.dev/eventing-kafka/pkg/channel/distributed/common/kafka/consumer"
kafkatesting "knative.dev/eventing-kafka/pkg/channel/distributed/common/kafka/testing"
eventingduck "knative.dev/eventing/pkg/apis/duck/v1"
"knative.dev/eventing/pkg/channel"
logtesting "knative.dev/pkg/logging/testing"
"knative.dev/pkg/system"
"testing"
"time"
)
// Test Data
const (
id123 = "123"
id456 = "456"
id789 = "789"
uid123 = types.UID(id123)
uid456 = types.UID(id456)
uid789 = types.UID(id789)
TestConfigNet = `
Net:
TLS:
Config:
ClientAuth: 0
SASL:
Mechanism: PLAIN
Version: 1
`
TestConfigConsumer = `
Consumer:
Offsets:
AutoCommit:
Interval: 5000000000
Retention: 604800000000000
Return:
Errors: true
`
TestConfigMeta = `
Metadata:
RefreshFrequency: 300000000000`
TestConfigBase = TestConfigNet + TestConfigMeta + TestConfigConsumer
TestConfigMetadataChange = TestConfigNet + `
Metadata:
RefreshFrequency: 200000` + TestConfigConsumer
TestConfigProducerChange = TestConfigNet + TestConfigMeta + `
Producer:
MaxMessageBytes: 300` + TestConfigConsumer
TestConfigConsumerAdd = TestConfigNet + TestConfigMeta + TestConfigConsumer + `
Fetch:
Min: 200
`
TestConfigConsumerChange = TestConfigNet + TestConfigMeta + `
Consumer:
Offsets:
AutoCommit:
Interval: 5000000000
Retention: 604800000000001
Return:
Errors: true
`
TestConfigAdminChange = `
Admin:
Retry:
Max: 100` + TestConfigNet + TestConfigMeta + TestConfigConsumer
)
// Test The NewSubscriberWrapper() Functionality
func TestNewSubscriberWrapper(t *testing.T) {
// Test Data
subscriber := eventingduck.SubscriberSpec{UID: uid123}
groupId := "TestGroupId"
consumerGroup := kafkatesting.NewMockConsumerGroup(t)
// Perform The Test
subscriberWrapper := NewSubscriberWrapper(subscriber, groupId, consumerGroup)
// Verify Results
assert.NotNil(t, subscriberWrapper)
assert.Equal(t, subscriber.UID, subscriberWrapper.UID)
assert.Equal(t, consumerGroup, subscriberWrapper.ConsumerGroup)
assert.Equal(t, groupId, subscriberWrapper.GroupId)
assert.NotNil(t, subscriberWrapper.StopChan)
}
// Test The NewDispatcher() Functionality
func TestNewDispatcher(t *testing.T) {
// Test Data
dispatcherConfig := DispatcherConfig{}
// Perform The Test
dispatcher := NewDispatcher(dispatcherConfig)
// Verify The Results
assert.NotNil(t, dispatcher)
}
// Test The Dispatcher's Shutdown() Functionality
func TestShutdown(t *testing.T) {
// Create Mock ConsumerGroups To Register Close() Requests
consumerGroup1 := kafkatesting.NewMockConsumerGroup(t)
consumerGroup2 := kafkatesting.NewMockConsumerGroup(t)
consumerGroup3 := kafkatesting.NewMockConsumerGroup(t)
// Create Test Subscribers To Close The ConsumerGroups Of
subscriber1 := eventingduck.SubscriberSpec{UID: id123}
subscriber2 := eventingduck.SubscriberSpec{UID: id456}
subscriber3 := eventingduck.SubscriberSpec{UID: id789}
groupId1 := fmt.Sprintf("kafka.%s", subscriber1.UID)
groupId2 := fmt.Sprintf("kafka.%s", subscriber2.UID)
groupId3 := fmt.Sprintf("kafka.%s", subscriber3.UID)
// Create The Dispatcher To Test With Existing Subscribers
dispatcher := &DispatcherImpl{
DispatcherConfig: DispatcherConfig{
Logger: logtesting.TestLogger(t).Desugar(),
},
subscribers: map[types.UID]*SubscriberWrapper{
subscriber1.UID: NewSubscriberWrapper(subscriber1, groupId1, consumerGroup1),
subscriber2.UID: NewSubscriberWrapper(subscriber2, groupId2, consumerGroup2),
subscriber3.UID: NewSubscriberWrapper(subscriber3, groupId3, consumerGroup3),
},
}
// Perform The Test
dispatcher.Shutdown()
// Verify The Results
assert.True(t, consumerGroup1.Closed)
assert.True(t, consumerGroup2.Closed)
assert.True(t, consumerGroup3.Closed)
assert.Len(t, dispatcher.subscribers, 0)
}
func getSaramaConfigFromYaml(t *testing.T, saramaYaml string) *sarama.Config {
var config *sarama.Config
jsonSettings, err := yaml.YAMLToJSON([]byte(saramaYaml))
assert.Nil(t, err)
assert.Nil(t, json.Unmarshal(jsonSettings, &config))
return config
}
// Test The UpdateSubscriptions() Functionality
func TestUpdateSubscriptions(t *testing.T) {
// Define The TestCase Struct
type fields struct {
DispatcherConfig DispatcherConfig
subscribers map[types.UID]*SubscriberWrapper
}
type args struct {
subscriberSpecs []eventingduck.SubscriberSpec
}
type testCase struct {
name string
fields fields
args args
want map[eventingduck.SubscriberSpec]error
}
// Define The Test Cases
tests := []testCase{
{
name: "Add First Subscription",
fields: fields{
DispatcherConfig: DispatcherConfig{
SaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),
Logger: logtesting.TestLogger(t).Desugar(),
},
subscribers: map[types.UID]*SubscriberWrapper{},
},
args: args{
subscriberSpecs: []eventingduck.SubscriberSpec{
{UID: uid123},
},
},
want: map[eventingduck.SubscriberSpec]error{},
},
{
name: "Add Second Subscription",
fields: fields{
DispatcherConfig: DispatcherConfig{
SaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),
Logger: logtesting.TestLogger(t).Desugar(),
},
subscribers: map[types.UID]*SubscriberWrapper{
uid123: createSubscriberWrapper(t, uid123),
},
},
args: args{
subscriberSpecs: []eventingduck.SubscriberSpec{
{UID: uid123},
{UID: uid456},
},
},
want: map[eventingduck.SubscriberSpec]error{},
},
{
name: "Add And Remove Subscriptions",
fields: fields{
DispatcherConfig: DispatcherConfig{
SaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),
Logger: logtesting.TestLogger(t).Desugar(),
},
subscribers: map[types.UID]*SubscriberWrapper{
uid123: createSubscriberWrapper(t, uid123),
uid456: createSubscriberWrapper(t, uid456),
},
},
args: args{
subscriberSpecs: []eventingduck.SubscriberSpec{
{UID: uid456},
{UID: uid789},
},
},
want: map[eventingduck.SubscriberSpec]error{},
},
{
name: "Remove Penultimate Subscription",
fields: fields{
DispatcherConfig: DispatcherConfig{
SaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),
Logger: logtesting.TestLogger(t).Desugar(),
},
subscribers: map[types.UID]*SubscriberWrapper{
uid123: createSubscriberWrapper(t, uid123),
uid456: createSubscriberWrapper(t, uid456),
},
},
args: args{
subscriberSpecs: []eventingduck.SubscriberSpec{
{UID: uid123},
},
},
want: map[eventingduck.SubscriberSpec]error{},
},
{
name: "Remove Last Subscription",
fields: fields{
DispatcherConfig: DispatcherConfig{
SaramaConfig: getSaramaConfigFromYaml(t, TestConfigBase),
Logger: logtesting.TestLogger(t).Desugar(),
},
subscribers: map[types.UID]*SubscriberWrapper{
uid123: createSubscriberWrapper(t, uid123),
},
},
args: args{
subscriberSpecs: []eventingduck.SubscriberSpec{},
},
want: map[eventingduck.SubscriberSpec]error{},
},
}
// Execute The Test Cases (Create A DispatcherImpl & UpdateSubscriptions() :)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Mock ConsumerGroup To Test With
consumerGroup := kafkatesting.NewMockConsumerGroup(t)
// Replace The NewConsumerGroupWrapper With Mock For Testing & Restore After TestCase
newConsumerGroupWrapperPlaceholder := kafkaconsumer.NewConsumerGroupWrapper
kafkaconsumer.NewConsumerGroupWrapper = func(brokersArg []string, groupIdArg string, configArg *sarama.Config) (sarama.ConsumerGroup, error) {
return consumerGroup, nil
}
defer func() {
kafkaconsumer.NewConsumerGroupWrapper = newConsumerGroupWrapperPlaceholder
}()
// Create A New DispatcherImpl To Test
dispatcher := &DispatcherImpl{
DispatcherConfig: tt.fields.DispatcherConfig,
subscribers: tt.fields.subscribers,
}
// Perform The Test
got := dispatcher.UpdateSubscriptions(tt.args.subscriberSpecs)
// Verify Results
assert.Equal(t, tt.want, got)
// Verify The Dispatcher's Tracking Of Subscribers Matches Specified State
assert.Len(t, dispatcher.subscribers, len(tt.args.subscriberSpecs))
for _, subscriber := range tt.args.subscriberSpecs {
assert.NotNil(t, dispatcher.subscribers[subscriber.UID])
}
// Shutdown The Dispatcher to Cleanup Resources
dispatcher.Shutdown()
assert.Len(t, dispatcher.subscribers, 0)
// Pause Briefly To Let Any Async Shutdown Finish (Lame But Only For Visual Confirmation Of Logging ;)
time.Sleep(500 * time.Millisecond)
})
}
}
// Utility Function For Creating A SubscriberWrapper With Specified UID & Mock ConsumerGroup
func createSubscriberWrapper(t *testing.T, uid types.UID) *SubscriberWrapper {
return NewSubscriberWrapper(eventingduck.SubscriberSpec{UID: uid}, fmt.Sprintf("kafka.%s", string(uid)), kafkatesting.NewMockConsumerGroup(t))
}
func getBaseConfigMap() *corev1.ConfigMap {
return &corev1.ConfigMap{
TypeMeta: v1.TypeMeta{
Kind: "ConfigMap",
APIVersion: corev1.SchemeGroupVersion.String(),
},
ObjectMeta: v1.ObjectMeta{
Name: commonconfig.SettingsConfigMapName,
Namespace: system.Namespace(),
},
Data: map[string]string{
commonconfig.SaramaSettingsConfigKey: TestConfigBase,
},
}
}
// Test The Dispatcher's ConfigChanged Functionality
func TestConfigChanged(t *testing.T) {
logger := logtesting.TestLogger(t).Desugar()
// Setup Environment
assert.Nil(t, os.Setenv(system.NamespaceEnvKey, constants.KnativeEventingNamespace))
// Create Mocks
var dispatcher Dispatcher
dispatcher = &DispatcherImpl{
DispatcherConfig: DispatcherConfig{Logger: logger},
subscribers: make(map[types.UID]*SubscriberWrapper),
messageDispatcher: channel.NewMessageDispatcher(logger),
}
// Apply a change to the Consumer config
dispatcher = runConfigChangedTest(t, dispatcher, getBaseConfigMap(), TestConfigConsumerChange, true)
// Apply an additional setting to the Consumer config
dispatcher = runConfigChangedTest(t, dispatcher, getBaseConfigMap(), TestConfigConsumerAdd, true)
// Change one of the metadata settings
dispatcher = runConfigChangedTest(t, dispatcher, getBaseConfigMap(), TestConfigMetadataChange, true)
// Change one of the admin settings
dispatcher = runConfigChangedTest(t, dispatcher, getBaseConfigMap(), TestConfigAdminChange, true)
// Verify that Producer changes do not cause Reconfigure to be called
dispatcher = runConfigChangedTest(t, dispatcher, getBaseConfigMap(), TestConfigProducerChange, false)
}
func runConfigChangedTest(t *testing.T, originalDispatcher Dispatcher, base *corev1.ConfigMap, changed string, expectedNewDispatcher bool) Dispatcher {
// Change the Consumer settings to the base config
newDispatcher := originalDispatcher.ConfigChanged(base)
if newDispatcher != nil {
// Simulate what happens in main() when the dispatcher changes
originalDispatcher = newDispatcher
}
// Alter the configmap to use the changed settings
newConfig := base
newConfig.Data[commonconfig.SaramaSettingsConfigKey] = changed
// Inform the Dispatcher that the config has changed to the new settings
newDispatcher = originalDispatcher.ConfigChanged(newConfig)
// Verify that a new dispatcher was created or not, as expected
assert.Equal(t, expectedNewDispatcher, newDispatcher != nil)
// Return either the new or original dispatcher for use by the rest of the TestConfigChanged test
if expectedNewDispatcher {
return newDispatcher
}
return originalDispatcher
}
|
marques-work/gocd
|
agent/src/main/java/com/thoughtworks/go/agent/AgentMain.java
|
/*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.agent;
import com.thoughtworks.go.agent.common.AgentBootstrapperArgs;
import com.thoughtworks.go.agent.common.AgentCLI;
import com.thoughtworks.go.logging.LogConfigurator;
import com.thoughtworks.go.util.SystemEnvironment;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Map;
public final class AgentMain {
private static final String DEFAULT_LOGBACK_CONFIGURATION_FILE = "agent-logback.xml";
public static void main(String... argv) {
AgentBootstrapperArgs args = new AgentCLI().parse(argv);
LogConfigurator logConfigurator = new LogConfigurator(DEFAULT_LOGBACK_CONFIGURATION_FILE);
logConfigurator.initialize();
new SystemEnvironment().setProperty("go.process.type", "agent");
Map<String, String> stringStringMap = args.toProperties();
new SystemEnvironment().setProperty(SystemEnvironment.SERVICE_URL, args.getServerUrl().toString());
for (Map.Entry<String, String> entry : stringStringMap.entrySet()) {
new SystemEnvironment().setProperty(entry.getKey(), entry.getValue());
}
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.registerShutdownHook();
}
}
|
SAP/cloud-odata-java
|
com.sap.core.odata.processor.core/src/main/java/com/sap/core/odata/processor/core/jpa/model/JPAEdmEntityContainer.java
|
/*******************************************************************************
* Copyright 2013 SAP AG
*
* 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.sap.core.odata.processor.core.jpa.model;
import java.util.ArrayList;
import java.util.List;
import com.sap.core.odata.api.edm.provider.EntityContainer;
import com.sap.core.odata.processor.api.jpa.access.JPAEdmBuilder;
import com.sap.core.odata.processor.api.jpa.exception.ODataJPAModelException;
import com.sap.core.odata.processor.api.jpa.exception.ODataJPARuntimeException;
import com.sap.core.odata.processor.api.jpa.model.JPAEdmAssociationSetView;
import com.sap.core.odata.processor.api.jpa.model.JPAEdmEntityContainerView;
import com.sap.core.odata.processor.api.jpa.model.JPAEdmEntitySetView;
import com.sap.core.odata.processor.api.jpa.model.JPAEdmFunctionImportView;
import com.sap.core.odata.processor.api.jpa.model.JPAEdmSchemaView;
import com.sap.core.odata.processor.core.jpa.access.model.JPAEdmNameBuilder;
public class JPAEdmEntityContainer extends JPAEdmBaseViewImpl implements
JPAEdmEntityContainerView {
private JPAEdmEntitySetView entitySetView;
private JPAEdmSchemaView schemaView;
private JPAEdmAssociationSetView associationSetView;
private EntityContainer currentEntityContainer;
private List<EntityContainer> consistentEntityContainerList;
public JPAEdmEntityContainer(final JPAEdmSchemaView view) {
super(view);
schemaView = view;
}
@Override
public JPAEdmBuilder getBuilder() {
if (builder == null) {
builder = new JPAEdmEntityContainerBuilder();
}
return builder;
}
@Override
public EntityContainer getEdmEntityContainer() {
return currentEntityContainer;
}
@Override
public List<EntityContainer> getConsistentEdmEntityContainerList() {
return consistentEntityContainerList;
}
@Override
public JPAEdmEntitySetView getJPAEdmEntitySetView() {
return entitySetView;
}
@Override
public JPAEdmAssociationSetView getEdmAssociationSetView() {
return associationSetView;
}
@Override
public void clean() {
super.clean();
entitySetView = null;
associationSetView = null;
currentEntityContainer = null;
consistentEntityContainerList = null;
}
private class JPAEdmEntityContainerBuilder implements JPAEdmBuilder {
/*
*
* Each call to build method creates a new Entity Container and builds
* the entity container with Association Sets and Entity Sets. The newly
* created and built entity container is added to the exiting Entity
* Container List.
*
* ************************************************************ Build
* EDM Entity Container - STEPS
* ************************************************************ 1)
* Instantiate New EDM Entity Container 2) Build Name for EDM Entity
* Container 2) Create Entity Container List (if does not exists) 3)
* Build EDM Entity Set 4) Add EDM Entity Set to EDM Entity Container 6)
* Build EDM Association Set 7) Add EDM Association Set to EDM Entity
* Container 8) Add EDM Entity Container to the Container List
* ************************************************************ Build
* EDM Entity Container - STEPS
* ************************************************************
*/
@Override
public void build() throws ODataJPAModelException,
ODataJPARuntimeException {
currentEntityContainer = new EntityContainer();
if (consistentEntityContainerList == null) {
currentEntityContainer.setDefaultEntityContainer(true);
consistentEntityContainerList = new ArrayList<EntityContainer>();
}
entitySetView = new JPAEdmEntitySet(schemaView);
entitySetView.getBuilder().build();
if (entitySetView.isConsistent()) {
currentEntityContainer.setEntitySets(entitySetView
.getConsistentEdmEntitySetList());
} else {
isConsistent = false;
return;
}
if (!schemaView.getJPAEdmAssociationView().isConsistent()) {
schemaView.getJPAEdmAssociationView().getBuilder().build();
}
associationSetView = new JPAEdmAssociationSet(schemaView);
associationSetView.getBuilder().build();
if (associationSetView.isConsistent()) {
currentEntityContainer.setAssociationSets(associationSetView
.getConsistentEdmAssociationSetList());
} else {
isConsistent = false;
return;
}
JPAEdmNameBuilder.build(JPAEdmEntityContainer.this);
if (schemaView.getJPAEdmExtension() != null) {
JPAEdmFunctionImportView functionImportView = new JPAEdmFunctionImport(
schemaView);
functionImportView.getBuilder().build();
if (functionImportView.getConsistentFunctionImportList() != null) {
currentEntityContainer
.setFunctionImports(functionImportView
.getConsistentFunctionImportList());
}
}
consistentEntityContainerList.add(currentEntityContainer);
isConsistent = true;
}
}
}
|
tanel/wardrobe-organizer
|
ui/weight_entries_page.go
|
package ui
import (
"encoding/json"
"github.com/juju/errors"
"github.com/tanel/wardrobe-organizer/model"
"github.com/tanel/webapp/ui"
)
// WeightEntriesPage represents weights page
type WeightEntriesPage struct {
ui.Page
Weights []model.WeightEntry
WeightChartDataJSON string
}
// NewWeightEntriesPage returns a new weights page
func NewWeightEntriesPage(userID string, weights []model.WeightEntry) (*WeightEntriesPage, error) {
page := WeightEntriesPage{
Page: *ui.NewPageWithUserID(userID),
Weights: weights,
}
if err := page.prepareChartData(); err != nil {
return nil, errors.Annotate(err, "preparing chart data failed")
}
return &page, nil
}
func (page *WeightEntriesPage) prepareChartData() error {
var data []float64
for i := len(page.Weights) - 1; i >= 0; i-- {
data = append(data, page.Weights[i].Value)
}
b, err := json.Marshal(data)
if err != nil {
return errors.Annotate(err, "marshalling data to JSON failed")
}
page.WeightChartDataJSON = string(b)
return nil
}
|
iamhuwjones/hermes
|
corvus-sfrm/src/main/java/hk/hku/cecid/edi/sfrm/task/AcknowledgementTask.java
|
<reponame>iamhuwjones/hermes
/**
* Active Task to query the database which message need to fire the acknowledgment request. Then send an acknowledgment to
* receiver to enquiry the status of SFRM message in the receiver side.
* @auther <NAME>
* @version 2.0.0
* @since 2.0.0
*/
package hk.hku.cecid.edi.sfrm.task;
import hk.hku.cecid.edi.sfrm.spa.SFRMException;
import hk.hku.cecid.edi.sfrm.spa.SFRMLog;
import hk.hku.cecid.edi.sfrm.spa.SFRMProcessor;
import hk.hku.cecid.piazza.commons.dao.DAOException;
import hk.hku.cecid.piazza.commons.module.ActiveTaskAdaptor;
import hk.hku.cecid.piazza.commons.security.KeyStoreManager;
import hk.hku.cecid.piazza.commons.io.IOHandler;
import hk.hku.cecid.edi.sfrm.dao.SFRMMessageDVO;
import hk.hku.cecid.edi.sfrm.dao.SFRMMessageSegmentDVO;
import hk.hku.cecid.edi.sfrm.dao.SFRMPartnershipDVO;
import hk.hku.cecid.edi.sfrm.handler.AcknowledgementHandler;
import hk.hku.cecid.edi.sfrm.handler.OutgoingMessageHandler;
import hk.hku.cecid.edi.sfrm.handler.SFRMMessageFactory;
import hk.hku.cecid.edi.sfrm.pkg.SFRMAcknowledgementBuilder;
import hk.hku.cecid.edi.sfrm.pkg.SFRMConstant;
import hk.hku.cecid.edi.sfrm.pkg.SFRMMessage;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.List;
import javax.mail.MessagingException;
/**
* Active task responsible for handling the action of sending the acknowledgement request to receiver
* @author <NAME>
* @since 2.0.0
*/
public class AcknowledgementTask extends ActiveTaskAdaptor {
private final SFRMMessageDVO messageDVO;
private final SFRMPartnershipDVO partnershipDVO;
public AcknowledgementTask(SFRMMessageDVO messageDVO, SFRMPartnershipDVO partenershipDVO){
this.messageDVO = messageDVO;
this.partnershipDVO = partenershipDVO;
}
public void execute() throws Exception{
String ackContent = buildAckContent();
SFRMMessage ackMessage = SFRMMessageFactory
.getInstance()
.createAcknowledgement(messageDVO, partnershipDVO, SFRMConstant.MSGT_ACK_REQUEST, ackContent);
//Send the acknowledgement
//TODO: To refactor or add a method that can receive the response message from acknowledgement
SFRMMessage responseMessage = OutgoingMessageHandler.getInstance().sendMessageWithMessageResponse(
ackMessage, messageDVO.getPartnerEndpoint(), messageDVO.getIsHostnameVerified(),
messageDVO.getSignAlgorithm(), messageDVO.getEncryptAlgorithm(), messageDVO.getPartnerX509Certificate());
unpackIncomingMessage(responseMessage, partnershipDVO);
BufferedReader ackReader = new BufferedReader(new InputStreamReader(responseMessage.getBodyPart().getInputStream()));
String ackResponseContent = IOHandler.readString(ackReader);
ackReader.close();
AcknowledgementHandler ackHandler = SFRMProcessor.getInstance().getAcknowledgementHandler();
ackHandler.processAcknowledgementResponse(ackResponseContent);
}
private String buildAckContent() throws DAOException{
SFRMAcknowledgementBuilder builder = new SFRMAcknowledgementBuilder();
builder.setMessage(messageDVO.getMessageId(), messageDVO.getStatus());
if(messageDVO.getStatus().equalsIgnoreCase(SFRMConstant.MSGS_PROCESSING) || messageDVO.getStatus().equalsIgnoreCase(SFRMConstant.MSGS_SEGMENTING)){
List segDVOs = SFRMProcessor.getInstance()
.getMessageSegmentHandler()
.retrieveDeliveredSegmentForMessage(messageDVO.getMessageId());
for(int i=0; segDVOs.size() > i ; i++){
SFRMMessageSegmentDVO segDVO = (SFRMMessageSegmentDVO) segDVOs.get(i);
builder.setSegment(messageDVO.getMessageId(), segDVO.getSegmentNo(), segDVO.getStatus());
}
}
return builder.toString();
}
/**
* Invoke when failure occur
* @param e
*/
public void onFaulure(Throwable e){
SFRMProcessor.getInstance().getLogger().error(SFRMLog.AT_CALLER + "Unknown Error", e);
}
// Philip 2009-07-31
// same as IncomingMessageHandler.unpackIncomingMessage
public void unpackIncomingMessage(SFRMMessage message, SFRMPartnershipDVO partnershipDVO) throws SFRMException {
KeyStoreManager keyman = SFRMProcessor.getInstance().getKeyStoreManager();
// Encryption enforcement check and decrypt
if (partnershipDVO.getEncryptAlgorithm() != null) {
if (!message.isEncryptedContentType()) {
SFRMProcessor.getInstance().getLogger().error(
SFRMLog.AT_CALLER + "Encryption enforcement check failed: "
+ message);
throw new SFRMException("Insufficient message security");
} else {
try {
message.decrypt(keyman.getX509Certificate(), keyman.getPrivateKey());
} catch (SFRMException e) {
SFRMProcessor.getInstance().getLogger().error(
SFRMLog.AT_CALLER + "Unable to decrypt "
+ message, e);
throw e;
} catch (NoSuchAlgorithmException e) {
SFRMProcessor.getInstance().getLogger().error(
SFRMLog.AT_CALLER + "Unable to decrypt "
+ message, e);
throw new SFRMException(e.getMessage(), e);
} catch (UnrecoverableKeyException e) {
SFRMProcessor.getInstance().getLogger().error(
SFRMLog.AT_CALLER + "Unable to decrypt "
+ message, e);
throw new SFRMException(e.getMessage(), e);
}
}
}
// Signing enforcement check and unpack verified signature
if (partnershipDVO.getSignAlgorithm() != null) {
if (!message.isSignedContentType()) {
SFRMProcessor.getInstance().getLogger().error(
SFRMLog.AT_CALLER + "Signature enforcement check failed: "
+ message);
throw new SFRMException("Insufficient message security");
} else {
try {
message.verify(partnershipDVO.getVerifyX509Certificate());
} catch (SFRMException e) {
SFRMProcessor.getInstance().getLogger().error(
SFRMLog.AT_CALLER + "Unable to verify "
+ message, e);
throw e;
}
}
}
// Log information
try {
SFRMProcessor.getInstance().getLogger().info(
SFRMLog.AT_CALLER + SFRMLog.UNPACK_SGT
+ " msg id: " + message.getMessageID()
+ " with payload size : "
+ message.getBodyPart().getSize());
} catch (MessagingException e) {
throw new SFRMException("Unable to get body part size");
}
}
}
|
Sdcrouse/my-verses
|
spec/features/application_features_spec.rb
|
require 'rails_helper'
RSpec.describe "Feature Test: Page Links", type: :feature do
let (:all_page_paths) do
[root_path, signup_path]
end
describe "Each page" do
it "has a link to the homepage" do
all_page_paths.each do |pagepath|
visit pagepath
click_button("Home")
expect(current_path).to eq("/")
end
end
end
# Add separate tests for when the user is logged out and logged in.
# The available pages will be different.
end
|
omerlewitz/ravendb-go-client
|
circle_criteria.go
|
package ravendb
// CircleCriteria describes circle criteria
type CircleCriteria struct {
SpatialCriteriaCommon
_radius float64
_latitude float64
_longitude float64
_radiusUnits SpatialUnits
}
// NewCircleCriteria returns new CircleCriteria
func NewCircleCriteria(radius float64, latitude float64, longitude float64, radiusUnits SpatialUnits, relation SpatialRelation, distErrorPercent float64) *CircleCriteria {
res := &CircleCriteria{
_radius: radius,
_latitude: latitude,
_longitude: longitude,
_radiusUnits: radiusUnits,
}
res._relation = relation
res._distanceErrorPct = distErrorPercent
return res
}
// ToQueryToken creates a token
func (c *CircleCriteria) ToQueryToken(fieldName string, addQueryParameter func(interface{}) string) queryToken {
return c.SpatialCriteriaCommon.toQueryTokenCommon(c, fieldName, addQueryParameter)
}
// GetShapeToken returns shapeToken
func (c *CircleCriteria) GetShapeToken(addQueryParameter func(interface{}) string) *shapeToken {
return shapeTokenCircle(addQueryParameter(c._radius), addQueryParameter(c._latitude),
addQueryParameter(c._longitude), c._radiusUnits)
}
|
imajid/systemc-compiler
|
sc_tool/lib/sc_tool/dyn_elab/MangledTypeDB.cpp
|
/******************************************************************************
* Copyright (c) 2020, Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
*
*****************************************************************************/
/**
* Author: <NAME>
*/
#include <sc_tool/dyn_elab/MangledTypeDB.h>
#include <clang/ASTMatchers/ASTMatchers.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/AST/Mangle.h>
using namespace clang;
using namespace clang::ast_matchers;
namespace sc_elab {
MangledTypeDB::MangledTypeDB(clang::ASTContext &astCtx)
{
auto recordDeclMatches = match(cxxRecordDecl().bind("cxxRecordDecl"), astCtx);
MangleContext *mangleCtx = astCtx.createMangleContext();
std::string mangledName;
llvm::raw_string_ostream osStr{mangledName};
// Iterate over all types in design and generated mangled names for them
for (auto type : astCtx.getTypes()) {
if (!type->isPlaceholderType() &&
!type->isDependentType() &&
!type ->isFixedPointType() && (
type->isRecordType() ||
type->isPointerType() ||
type->isBuiltinType() ||
type->isEnumeralType())) {
if (auto builtinType = type->getAs<BuiltinType>()) {
// Skip types not yet supported on Windows
if (builtinType->getKind() == BuiltinType::Kind::Float128)
continue;
if (builtinType->getKind() == BuiltinType::Kind::Char8)
continue;
}
auto cannonType = type->getCanonicalTypeInternal();
//llvm::outs() << "Is placeholder? " << cannonType->isPlaceholderType() << " "<< cannonType.getAsString() << "\n";
mangleCtx->mangleTypeName(cannonType, osStr);
osStr.str();
#ifndef _MSC_VER
// Remove _ZTS
mangledName = mangledName.substr(4);
#else
// // Remove ?A
// mangledName = mangledName.substr(2);
#endif // !_MSC_VER
// llvm::outs() << mangledName << "\n";
typeMap.emplace(mangledName, cannonType);
mangledName.clear();
}
}
}
clang::QualType MangledTypeDB::getType(llvm::StringRef mangledTypeName)
{
return typeMap.at(mangledTypeName);
}
} // namespace sc_elab
|
jufeng98/b2c-master
|
maven-parent/b2c-cloud-test-parent-fundamental/b2c-cloud-test-pattern/src/main/java/com/javamaster/b2c/cloud/test/pattern/facade/mac/DvdPlayer.java
|
package com.javamaster.b2c.cloud.test.pattern.facade.mac;
public class DvdPlayer {
public void on() {
System.out.println("dvd player on");
}
public void off() {
System.out.println("dvd player off");
}
public void play() {
System.out.println("dvd player play");
}
public void stop() {
System.out.println("dvd player stop");
}
}
|
RideShark/transitland-datastore
|
app/models/gtfs_agency.rb
|
<reponame>RideShark/transitland-datastore
# == Schema Information
#
# Table name: gtfs_agencies
#
# id :integer not null, primary key
# agency_id :string not null
# agency_name :string not null
# agency_url :string not null
# agency_timezone :string not null
# agency_lang :string not null
# agency_phone :string not null
# agency_fare_url :string not null
# agency_email :string not null
# created_at :datetime not null
# updated_at :datetime not null
# feed_version_id :integer not null
#
# Indexes
#
# index_gtfs_agencies_on_agency_id (agency_id)
# index_gtfs_agencies_on_agency_name (agency_name)
# index_gtfs_agencies_unique (feed_version_id,agency_id) UNIQUE
#
class GTFSAgency < ActiveRecord::Base
include GTFSEntity
has_many :routes, class_name: 'GTFSRoute', foreign_key: 'agency_id'
has_many :trips, through: :routes
has_many :stops, -> { distinct }, through: :trips
has_many :shapes, -> { distinct }, through: :trips
has_many :stop_times, through: :trips
belongs_to :feed_version
belongs_to :entity, class_name: 'Operator'
validates :feed_version, presence: true, unless: :skip_association_validations
validates :agency_name, presence: true
validates :agency_url, presence: true
validates :agency_timezone, presence: true
end
|
YunZhang2014/mockito-instant
|
src/test/java/com/blogspot/toomuchcoding/chapters/topFeaturesYouNeedToKnowAbout/_03WorkingWithVoidMethodsAndThrownExceptionsTest.java
|
package com.blogspot.toomuchcoding.chapters.topFeaturesYouNeedToKnowAbout;
import com.blogspot.toomuchcoding.topFeaturesYouNeedToKnowAbout.exception.IAmTooLazyToDoItException;
import com.blogspot.toomuchcoding.topFeaturesYouNeedToKnowAbout.service.*;
import org.junit.Test;
import org.mockito.Mockito;
import static com.googlecode.catchexception.CatchException.catchException;
import static com.googlecode.catchexception.CatchException.caughtException;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class _03WorkingWithVoidMethodsAndThrownExceptionsTest {
KitchenService kitchenServiceMock = mock(KitchenService.class);
@Test
public void shouldReturnTrueIfKitchenNotCleanedPreviously() throws Exception {
//given
WaiterImpl objectUnderTest = new WaiterImpl(kitchenServiceMock);
//when
boolean canCloseRestaurant = objectUnderTest.closeTheRestaurant();
//then
assertThat(canCloseRestaurant, is(true));
verify(kitchenServiceMock).cleanTheKitchen();
}
@Test
public void shouldReturnFalseIfAnExceptionHasBeenThrownWhileCleaning() throws Exception {
//given
WaiterImpl objectUnderTest = new WaiterImpl(kitchenServiceMock);
Mockito.doThrow(new IAmTooLazyToDoItException()).when(kitchenServiceMock).cleanTheKitchen();
//when
boolean canCloseRestaurant = objectUnderTest.closeTheRestaurant();
//then
assertThat(canCloseRestaurant, is(false));
verify(kitchenServiceMock).cleanTheKitchen();
}
@Test
public void shouldReturnFalseWhenTryingToCloseRestaurantWhenKitchenServiceIsLazy() throws Exception {
//given
WaiterImpl objectUnderTest = new WaiterImpl(kitchenServiceMock);
doThrow(new IAmTooLazyToDoItException()).doNothing().when(kitchenServiceMock).cleanTheKitchen();
//when
boolean canCloseRestaurantWhenKitchenServiceIsLazy = objectUnderTest.closeTheRestaurant();
boolean canCloseRestaurant = objectUnderTest.closeTheRestaurant();
//then
assertThat(canCloseRestaurantWhenKitchenServiceIsLazy, is(false));
assertThat(canCloseRestaurant, is(true));
verify(kitchenServiceMock, times(2)).cleanTheKitchen();
}
@Test(expected = IAmTooLazyToDoItException.class)
public void shouldThrowAnExceptionWhenCheckingForChangedOutfitButInFactAdministrativeServiceThrowsIt() throws Exception {
//given
WaiterImpl objectUnderTest = new WaiterImpl(kitchenServiceMock, new LazyAdministrativeService());
when(kitchenServiceMock.isOutfitChanged()).thenThrow(new IAmTooLazyToDoItException());
//when
objectUnderTest.readyToTakeAnOrder();
}
@Test
public void shouldThrowAnExceptionWhenCheckingForChangedOutfitAndNoMoreInteractionsTakePlaceInKitchen() throws Exception {
//given
WaiterImpl objectUnderTest = new WaiterImpl(kitchenServiceMock, new GreatAdministrativeService());
when(kitchenServiceMock.isOutfitChanged()).thenThrow(new IAmTooLazyToDoItException());
//when
try {
objectUnderTest.readyToTakeAnOrder();
fail();
} catch (IAmTooLazyToDoItException exception) {
}
//then
verify(kitchenServiceMock).isOutfitChanged();
verifyNoMoreInteractions(kitchenServiceMock);
}
@Test
public void shouldThrowAnExceptionWhenCheckingForChangedOutfitAndNoMoreInteractionsTakePlaceInKitchenUsingCatchException() throws Exception {
//given
WaiterImpl objectUnderTest = new WaiterImpl(kitchenServiceMock, new GreatAdministrativeService());
when(kitchenServiceMock.isOutfitChanged()).thenThrow(new IAmTooLazyToDoItException());
//when
catchException(objectUnderTest).readyToTakeAnOrder();
//then
assertThat(caughtException(), is(IAmTooLazyToDoItException.class));
verify(kitchenServiceMock).isOutfitChanged();
verifyNoMoreInteractions(kitchenServiceMock);
}
}
|
devasateam/api
|
app/models/Discount.java
|
package models;
/**
@Author Pramod
Email:<EMAIL>
*/
public class Discount {
}
|
mitch-seymour/ksql
|
ksql-metastore/src/test/java/io/confluent/ksql/metastore/model/StructuredDataSourceMatchers.java
|
<filename>ksql-metastore/src/test/java/io/confluent/ksql/metastore/model/StructuredDataSourceMatchers.java
/*
* Copyright 2019 Confluent Inc.
*
* Licensed under the Confluent Community License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.ksql.metastore.model;
import static org.hamcrest.Matchers.is;
import java.util.Optional;
import org.apache.kafka.connect.data.Field;
import org.apache.kafka.connect.data.Schema;
import org.hamcrest.Description;
import org.hamcrest.FeatureMatcher;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
public final class StructuredDataSourceMatchers {
private StructuredDataSourceMatchers() {
}
public static Matcher<StructuredDataSource<?>> hasName(final String name) {
return new FeatureMatcher<StructuredDataSource<?>, String>
(is(name), "source with name", "name") {
@Override
protected String featureValueOf(final StructuredDataSource<?> actual) {
return actual.getName();
}
};
}
public static Matcher<StructuredDataSource<?>> hasKeyField(final String keyFieldName) {
return hasKeyField(OptionalMatchers.of(FieldMatchers.hasName(keyFieldName)));
}
public static Matcher<StructuredDataSource<?>> hasKeyField(
final Matcher<Optional<Field>> fieldMatcher
) {
return new FeatureMatcher<StructuredDataSource<?>, Optional<Field>>
(fieldMatcher, "source with key field", "key field") {
@Override
protected Optional<Field> featureValueOf(final StructuredDataSource<?> actual) {
return actual.getKeyField();
}
};
}
public static final class FieldMatchers {
private FieldMatchers() {
}
public static Matcher<Field> hasName(final String name) {
return new FeatureMatcher<Field, String>
(is(name), "field with name", "name") {
@Override
protected String featureValueOf(final Field actual) {
return actual.name();
}
};
}
public static Matcher<Field> hasIndex(final int index) {
return new FeatureMatcher<Field, Integer>
(is(index), "field with index", "index") {
@Override
protected Integer featureValueOf(final Field actual) {
return actual.index();
}
};
}
public static Matcher<Field> hasSchema(final Schema schema) {
return new FeatureMatcher<Field, Schema>
(is(schema), "field with schema", "schema") {
@Override
protected Schema featureValueOf(final Field actual) {
return actual.schema();
}
};
}
}
public static final class OptionalMatchers {
private OptionalMatchers() {
}
public static <T> Matcher<Optional<T>> of(final Matcher<T> valueMatcher) {
return new TypeSafeDiagnosingMatcher<Optional<T>>() {
@Override
protected boolean matchesSafely(
final Optional<T> item,
final Description mismatchDescription
) {
if (!item.isPresent()) {
mismatchDescription.appendText("not present");
return false;
}
if (!valueMatcher.matches(item.get())) {
valueMatcher.describeMismatch(item.get(), mismatchDescription);
return false;
}
return true;
}
@Override
public void describeTo(final Description description) {
description.appendText("optional ").appendDescriptionOf(valueMatcher);
}
};
}
}
}
|
Quest1mc/full-app
|
graphql-types/InputKeywordType.js
|
<reponame>Quest1mc/full-app
const {
// GraphQLID,
// GraphQLInt,
GraphQLString,
// GraphQLList,
// GraphQLNonNull,
// GraphQLObjectType,
GraphQLInputObjectType,
// GraphQLObjectType
} = require('graphql');
// input KeywordInput {
// keyword: String
// }
// const InputKeywordType = new GraphQLInputObjectType({
// name: 'InputKeyword',
// description: 'this is how you update Keyword on user\'s array',
// fields: () => ({
// id: { type: GraphQLInt },
// keyword: { type: GraphQLString },
// })
// });
const InputKeywordType = new GraphQLInputObjectType({
name: 'InputKeyword',
description: 'this is a tag or key word each one represents is search able and if you search it wshould return a list of users that share this keyword',
fields: () => ({
id: { type: GraphQLString },
keyword: { type: GraphQLString },
/* this is a list of all the keywords we have and should eventually be
populated using alvinios list */
})
});
module.exports = InputKeywordType;
|
w4bo/Alchemist
|
alchemist/alchemist-implementationbase/src/main/java/it/unibo/alchemist/model/implementations/linkingrules/ConnectionBeam.java
|
/*
* Copyright (C) 2010-2014, <NAME> and contributors
* listed in the project's pom.xml file.
*
* This file is part of Alchemist, and is distributed under the terms of
* the GNU General Public License, with a linking exception, as described
* in the file LICENSE in the Alchemist distribution's top directory.
*/
package it.unibo.alchemist.model.implementations.linkingrules;
import static org.apache.commons.math3.util.FastMath.PI;
import static org.apache.commons.math3.util.FastMath.atan2;
import static org.apache.commons.math3.util.FastMath.cos;
import static org.apache.commons.math3.util.FastMath.nextAfter;
import static org.apache.commons.math3.util.FastMath.nextUp;
import static org.apache.commons.math3.util.FastMath.sin;
import it.unibo.alchemist.model.implementations.neighborhoods.CachedNeighborhood;
import it.unibo.alchemist.model.interfaces.Environment;
import it.unibo.alchemist.model.interfaces.Environment2DWithObstacles;
import it.unibo.alchemist.model.interfaces.Neighborhood;
import it.unibo.alchemist.model.interfaces.Node;
import it.unibo.alchemist.model.interfaces.Position;
import java.awt.geom.Area;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
import org.danilopianini.lang.HashUtils;
/**
* Connects two nodes if, throwing a beam from one to the other, there exists at
* least one path entirely inside the beam that connects the two nodes. This
* rule is ideal for environments with obstacles, where the user wants some
* tolerance in connection breaking.
*
* @param <T>
*/
public class ConnectionBeam<T> extends EuclideanDistance<T> {
private static final long serialVersionUID = -6303232843110524434L;
private static final int COORDS = 6;
private final double range;
private transient Environment2DWithObstacles<?, ?> oenv;
private transient Area obstacles = new Area();
/**
* @param radius
* beam maximum length
* @param beamSize
* beam span (tolerance)
*/
public ConnectionBeam(final double radius, final double beamSize) {
super(radius);
range = beamSize;
}
@Override
public Neighborhood<T> computeNeighborhood(final Node<T> center, final Environment<T> env) {
final Neighborhood<T> normal = super.computeNeighborhood(center, env);
if (!HashUtils.pointerEquals(env, oenv)) {
if (!(env instanceof Environment2DWithObstacles<?, ?>)) {
return normal;
}
oenv = (Environment2DWithObstacles<?, ?>) env;
obstacles.reset();
oenv.getObstacles().forEach((obs) -> {
/*
* Doubles are prone to approximation errors. Use nextAfter to get rid of them
*/
final Rectangle2D bounds = obs.getBounds2D();
final double mx = nextAfter(bounds.getMinX(), java.lang.Double.NEGATIVE_INFINITY);
final double my = nextAfter(bounds.getMinY(), java.lang.Double.NEGATIVE_INFINITY);
final double ex = nextUp(bounds.getMaxX());
final double ey = nextUp(bounds.getMaxY());
obstacles.add(new Area(new Rectangle2D.Double(mx, my, ex - mx, ey - my)));
});
}
if (!normal.isEmpty()) {
final Position cp = env.getPosition(center);
final List<Node<T>> neighs = normal.getNeighbors().stream()
.filter((neigh) -> {
final Position np = env.getPosition(neigh);
return !oenv.intersectsObstacle(cp, np) || projectedBeamOvercomesObstacle(cp, np);
})
.collect(ArrayList::new, (l, el) -> l.add(el), (l1, l2) -> l1.addAll(l2));
return new CachedNeighborhood<>(center, neighs, env);
}
return normal;
}
private boolean projectedBeamOvercomesObstacle(final Position pos1, final Position pos2) {
final double p1x = pos1.getCoordinate(0);
final double p1y = pos1.getCoordinate(1);
final double p2x = pos2.getCoordinate(0);
final double p2y = pos2.getCoordinate(1);
final double x = p2x - p1x;
final double y = p2y - p1y;
/*
* Compute the angle
*/
final double angle = atan2(y, x);
/*
* Deduce surrounding beam vertices
*/
final double dx = range * cos(PI / 2 + angle);
final double dy = range * sin(PI / 2 + angle);
/*
* Enlarge the beam
*/
final double cx = range * cos(angle);
final double cy = range * sin(angle);
/*
* Create the beam
*/
final Path2D.Double beamShape = new Path2D.Double();
beamShape.moveTo(p1x + dx - cx, p1y + dy - cy);
beamShape.lineTo(p1x - dx - cx, p1y - dy - cy);
beamShape.lineTo(p2x - dx + cx, p2y - dy + cy);
beamShape.lineTo(p2x + dx + cx, p2y + dy + cy);
beamShape.closePath();
final Area beam = new Area(beamShape);
/*
* Perform subtraction
*/
beam.subtract(obstacles);
/*
* Rebuild single areas
*/
final List<Path2D.Double> subareas = new ArrayList<>();
Path2D.Double curpath = new Path2D.Double();
final PathIterator pi = beam.getPathIterator(null);
final double[] coords = new double[COORDS];
while (!pi.isDone()) {
switch(pi.currentSegment(coords)) {
case PathIterator.SEG_MOVETO :
curpath = new Path2D.Double();
curpath.moveTo(coords[0], coords[1]);
break;
case PathIterator.SEG_LINETO :
curpath.lineTo(coords[0], coords[1]);
break;
case PathIterator.SEG_CLOSE :
curpath.closePath();
subareas.add(curpath);
break;
default : throw new IllegalArgumentException();
}
pi.next();
}
/*
* At least one area must contain both points
*/
for (final Path2D.Double p : subareas) {
if (p.contains(p1x, p1y) && p.contains(p2x, p2y)) {
return true;
}
}
return false;
}
private void readObject(final ObjectInputStream o) throws ClassNotFoundException, IOException {
o.defaultReadObject();
oenv = null;
obstacles = new Area();
}
}
|
Build-The-Web/bootils
|
src/bootils/util/dataformats.py
|
<filename>src/bootils/util/dataformats.py
# -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
""" Data format support & extensions.
"""
# Copyright © 2015 1&1 Group <<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.
from __future__ import absolute_import, unicode_literals, print_function
import os
import sys
from collections import OrderedDict
import yaml
def _represent_odict(dump, mapping, flow_style=None):
""" Like BaseRepresenter.represent_mapping, but does not issue the sort().
See `this blog post <http://blog.elsdoerfer.name/2012/07/26/make-pyyaml-output-an-ordereddict/>`_.
"""
tag = u'tag:yaml.org,2002:map'
value = []
node = yaml.MappingNode(tag, value, flow_style=flow_style)
if dump.alias_key is not None:
dump.represented_objects[dump.alias_key] = node
best_style = True
if hasattr(mapping, 'items'):
mapping = mapping.items()
for item_key, item_value in mapping:
node_key = dump.represent_data(item_key)
node_value = dump.represent_data(item_value)
if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style):
best_style = False
if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style):
best_style = False
value.append((node_key, node_value))
if flow_style is None:
if dump.default_flow_style is not None:
node.flow_style = dump.default_flow_style
else:
node.flow_style = best_style
return node
def yaml_add_odict():
"""Add YAML serialization support for ``OrderedDict`` objects."""
if OrderedDict not in yaml.SafeDumper.yaml_representers:
yaml.SafeDumper.add_representer(OrderedDict, _represent_odict)
|
shubhamg931/datahub
|
datahub-web/@datahub/shared/app/authenticators/aad-sso.js
|
export { default } from '@datahub/shared/authenticators/aad-sso';
|
kcyu2014/nas-landmarkreg
|
nasws/cnn/search_space/monodepth/landmark_procedure.py
|
"""
Add landmark as regualrization inside.
"""
import torch
import math
import logging
from random import randint
import IPython
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
"""
In general there are many ways to compute such ranking loss.
- we could directly compare against the loss value
- or we use the distance loss (cosine distance) between data points
"""
class SearchSpace:
def __init__(self, ids, specs, weights):
super().__init__()
self._landmark_ids = ids
self._landmark_specs = specs
self._landmark_weights = weights
@property
def landmark_topologies(self):
return self._landmark_ids, self._landmark_specs
@property
def landmark_weights(self):
return self._landmark_weights
def _summarize_shared_train(curr_step, loss, rankloss, acc=0, acc_5=0, lr=0.0, epoch_steps=1, writer=None):
"""Logs a set of training steps."""
logging.info(f'| step {curr_step:3d} '
f'| lr {lr:4.2f} '
f'| rank loss {rankloss:.2f} '
f'| loss {loss:.2f} '
f'| acc {acc:8.2f}'
f'| acc-5 {acc_5: 8.2f}')
def adjust_landmark_coef(epoch, args, batch_idx=1, total_batchs=1):
world_size = args.world_size
if args.landmark_warmup_epoch > 0 and epoch < args.landmark_warmup_epoch:
# warming up the landmark coef
epoch += float(batch_idx + 1) / total_batchs
if world_size > 1:
coef_adf = 1. / world_size * (epoch * (world_size - 1) / args.landmark_warmup_epoch + 1)
else:
coef_adf = min(1, epoch / (args.landmark_warmup_epoch + 1))
elif args.landmark_loss_coef_scheduler == "constant":
coef_adf = 1.
elif args.landmark_loss_coef_scheduler == "linear_step_decrease":
if epoch < 100:
coef_adf = 1.
elif epoch < 150:
coef_adf = 1e-1
elif epoch < 200:
coef_adf = 1e-2
else:
coef_adf = 1e-3
elif args.landmark_loss_coef_scheduler == "linear_step_increase":
if epoch < 100:
coef_adf = 0.
elif epoch < 150:
coef_adf = 1e-2
elif epoch < 200:
coef_adf = 1e-1
else:
coef_adf = 1.
elif args.landmark_loss_coef_scheduler == "cosine_decrease":
# self.init_lr * 0.5 * (1 + math.cos(math.pi * T_cur / T_total))
run_epochs = epoch - args.landmark_warmup_epoch
total_epochs = args.epochs - args.landmark_warmup_epoch
T_cur = float(run_epochs * total_batchs) + batch_idx
T_total = float(total_epochs * total_batchs)
coef_adf = 0.5 * (1 + math.cos(math.pi * T_cur / T_total))
return coef_adf * args.landmark_loss_coef
def rank_cross_entropy_loss(l1, l2):
logit = torch.sigmoid(l1-l2)
# logit = F.prelu(logit, torch.tensor(0.1))
return -torch.log(1 - logit)
def rank_infinite_loss_v1(l1, l2, w1, w2):
d = (l1 - l2) / (w1 - w2)
# in this case: l1 < l2 and w1 < w2, or l1 > l2 and w1 > w2, d > 0. but we should
p = torch.sigmoid(-d)
return F.relu(0.5 - p)
def rank_infinite_loss_v2(l1, l2, w1, w2):
d = (l1 - l2) / (w1 - w2)
p = torch.sigmoid(-d)
return F.softplus(0.5 - p)
def rank_infinite_relu(l1, l2, w1, w2):
d = (l1 - l2) * (w1 - w2)
return F.relu(d)
def rank_infinite_softplus(l1, l2, w1, w2):
d = (l1 - l2) * (w1 - w2)
return F.softplus(d, beta=5)
def rank_hinge_sign_infinite(l1, l2, w1, w2):
return F.relu(1 - (l1 - l2) * torch.sign(w2 - w1))
def rank_cross_entropy_focal_loss(l1, l2, gamma=5):
logit = torch.sigmoid(l1 - l2)
# logit = F.prelu(logit, torch.tensor(0.1))
return - (logit).pow(gamma) * torch.log(1 - logit)
def rank_mixed_cross_entropy_loss(l1, l2):
if l1 < l2:
return rank_cross_entropy_focal_loss(l1, l2)
else:
return rank_cross_entropy_loss(l1, l2)
def tanh_sign_infinite(l1, l2, w1, w2):
# given the fact that, l1 < l2 == w1 > w2.
l = torch.tanh(l1 - l2) * torch.sign(w1 - w2)
return F.relu(l)
def tanh_infinite(l1, l2, w1, w2):
# given the fact that, l1 < l2 == w1 > w2.
l = torch.tanh(l1 - l2) * torch.tanh(w1 - w2)
return F.relu(l)
def tanh_infinite_norelu(l1, l2, w1, w2):
# given the fact that, l1 < l2 == w1 > w2.
return torch.tanh(l1 - l2) * torch.tanh(w1 - w2)
# to compute the rank loss for each pair of input losses.
_loss_fn = {
'mae_relu': lambda l1, l2 : F.relu(l1 - l2),
'mae_sign_relu': lambda l1, l2 : F.relu(torch.sign(l1 - l2)),
'mae_sign_tanh_relu': lambda l1, l2: F.relu(torch.sign(torch.tanh(l1 - l2))),
'mae_tanh_relu': lambda l1, l2: F.relu(torch.tanh(l1 - l2)),
'mae_softplus': lambda l1, l2: F.softplus(l1 - l2),
'mae_softplus_beta3': lambda l1, l2: F.softplus(l1 - l2, beta=3),
'mae_softplus_beta5': lambda l1, l2: F.softplus(l1 - l2, beta=5),
'mae_softplus_beta7': lambda l1, l2: F.softplus(l1 - l2, beta=7),
'focal_loss': rank_cross_entropy_focal_loss,
'mae_relu_norm': lambda l1, l2 : F.relu((l1 - l2) / (l1 - l2).abs() * (l1 + l2) / 2),
'mae_tanh_infinite': tanh_infinite,
'tanh_infinite': tanh_infinite_norelu,
'mae_sign_tanh_infinite': tanh_sign_infinite,
'mae_relu_sigmoid_infinite': rank_infinite_loss_v1,
'mae_relu_infinite': rank_infinite_relu,
'softplus_infinite': rank_infinite_softplus,
'sigmoid_softplus_infinite': rank_infinite_loss_v2,
'hinge_sign_infinite': rank_hinge_sign_infinite,
'crossentropy': rank_cross_entropy_loss,
'mixed_focal': rank_mixed_cross_entropy_loss,
}
def get_rank_loss_fn(name, weighted):
"""
All of these loss will penalize l1 > l2, i.e. ground truth label is l1 < l2.
:param name: args.landmark_loss_fn
:param weighted: weighted to add a subscript.
:return: loss fn.
"""
if weighted == 'embed':
return lambda l1, l2, w : w * _loss_fn[name](l1, l2)
elif weighted == 'infinite':
return _loss_fn[name + '_infinite']
return _loss_fn[name]
def pairwise_landmark_ranking_loss_step(model, data, search_space, criterion, args,
change_model_spec_fn, module_forward_fn,
rank_obj=None, pair_indicies=None):
"""
Compute the ranking loss:
for landmark models, m1, m2, ...., suppose they are in descending order
FOR i > j, L_rank = sum_{i,j} max(0, L(m_j) - L(m_i))
if landmark_loss_adjacent, i = j + 1 for sure. otherwise, i = j+1, j+2 ..., n
Version 1.0
:param model:
:param data:
:param search_space:
:param criterion:
:param args:
:param change_model_spec_fn: change model spec function, this should be associated with search space.
:param module_forward_fn: return the current loss and next loss for now.
:param rank_obj:
:param landmark_weights: weights you would like to associate with each landmark architecture.
:return:
"""
# input, target = data
# for the sake of memory, we do not store the features, but we just compute the graph all the time.
coeff = adjust_landmark_coef(args.tmp_epoch, args)
rank_loss_fn = get_rank_loss_fn(args.landmark_loss_fn, args.landmark_loss_weighted)
landmark_ids, landmark_specs = search_space.landmark_topologies
if pair_indicies is None:
pair_indicies = []
for ind, model_id in enumerate(landmark_ids[:-1]): # skip the last one
end = min(ind + 1 + args.landmark_loss_adjacent_step, len(landmark_ids)) \
if args.landmark_loss_adjacent else len(landmark_ids)
for jnd in range(ind+1, end):
pair_indicies.append((ind, jnd))
for ind, jnd in pair_indicies:
# currently, landmarks id loss should decrease!
# change the model to current one
change_model_spec_fn(model, landmark_specs[ind])
curr_loss, _, _ = module_forward_fn(model, data, criterion)
change_model_spec_fn(model, landmark_specs[jnd])
next_loss, _, _ = module_forward_fn(model, data, criterion)
# IPython.embed()
# weighted landmark
if args.landmark_loss_weighted == 'embed':
landmark_weights = search_space.landmark_weights
rank_loss = coeff * rank_loss_fn(next_loss, curr_loss, abs(landmark_weights[ind] - landmark_weights[jnd]))
elif args.landmark_loss_weighted == 'infinite':
landmark_weights = search_space.landmark_weights
rank_loss = coeff * rank_loss_fn(
next_loss, curr_loss,
torch.tensor(landmark_weights[jnd]).float(),
torch.tensor(landmark_weights[ind]).float(),
)
else:
rank_loss = coeff * rank_loss_fn(next_loss, curr_loss)
if rank_obj:
rank_obj.update(rank_loss.item(), data['image'].size(0))
rank_obj.landmark_coef = coeff # track the coefficient over epoch
try:
rank_loss.backward() # update grad here.
except Exception as e:
print(e)
IPython.embed()
return rank_loss.item()
def random_pairwise_loss_step(model, data, search_space, criterion, args,
change_model_spec_fn, module_forward_fn,
rank_obj=None):
# each time, random a pair and compare.
pairwise_indicies = []
# landmark_ids, landmark_specs = search_space.landmark_topologies
# landmark_weights = search_space.landmark_weights
num_landmark = len(search_space._landmark_ids)
for _ in range(args.landmark_loss_random_pairs):
a = randint(0, num_landmark - 2)
b = randint(a+1, num_landmark - 1)
pairwise_indicies.append([a, b])
return pairwise_landmark_ranking_loss_step(model, data, search_space, criterion, args,
change_model_spec_fn, module_forward_fn, rank_obj,
pairwise_indicies)
def random_three_pairwise_loss_step(model, data, search_space, criterion, args,
change_model_spec_fn, module_forward_fn,
rank_obj=None):
# each time, random 3 architecture to formulate this
pairwise_indicies = []
num_landmark = len(search_space._landmark_ids)
for _ in range(args.landmark_loss_random_pairs):
a, b, c = sorted(np.random.choice(np.arange(num_landmark), 3, replace=False).tolist())
pairwise_indicies.append([a, b])
pairwise_indicies.append([b, c])
# IPython.embed(header='check three pair')
# here specs contains landmark weights
return pairwise_landmark_ranking_loss_step(model, data, search_space, criterion, args,
change_model_spec_fn, module_forward_fn, rank_obj,
pairwise_indicies)
# def _schedule_coeff(args, lr):
# if args.landmark_loss_coef_scheduler == 'inverse_lr':
# coeff = (args.learning_rate - lr + args.learning_rate_min) * args.landmark_loss_coef
# logging.info(f"landmark loss coefficient (Inverse lr) {coeff}")
# else:
# coeff = args.landmark_loss_coef
# args.tmp_landmark_loss_coef = coeff
# return args
landmark_loss_step_fns = {
'pairwise_loss': pairwise_landmark_ranking_loss_step,
# 'pairwise_loss_normalize': pairwise_landmark_ranking_loss_step,
'random_pairwise_loss': random_pairwise_loss_step,
# 'random_pairwise_infinite_loss_v1': random_pairwise_loss_step,
'random_pariwise_loss_cross_entropy': random_pairwise_loss_step,
'random_pairwise_loss_mixed_focal': random_pairwise_loss_step,
'random_three_pairwise_loss': random_three_pairwise_loss_step,
'pairwise_logits': NotImplementedError("not yet implemented.")
}
|
zuochengyao/MegviiFaceID
|
src/main/java/com/megvii/faceid/model/lite/LiteGetResultResponse.java
|
package com.megvii.faceid.model.lite;
import com.google.gson.annotations.SerializedName;
import com.megvii.faceid.model.base.response.BaseResponse;
import com.megvii.faceid.model.base.response.CompareResponse;
import com.megvii.faceid.model.base.common.FaceGenuineness;
import com.megvii.faceid.model.base.common.IdcardDict;
import com.megvii.faceid.model.base.common.ImageList;
import com.megvii.faceid.model.base.common.Result;
import com.megvii.faceid.model.ocr.idcard.v1.IdCardV1Response;
import com.megvii.faceid.util.Const;
public class LiteGetResultResponse extends BaseResponse
{
private String status;
@SerializedName(Const.API_PARAM_BIZ_INFO)
private BizInfo bizInfo;
@SerializedName(Const.API_PARAM_IDCARD_INFO)
private IdcardInfo idcardInfo;
@SerializedName(Const.API_PARAM_LIVENESS_RESULT)
private LivenessResult livenessResult;
@SerializedName(Const.API_PARAM_VERIFY_RESULT)
private VerifyResult verifyResult;
private ImageList images;
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public BizInfo getBizInfo()
{
return bizInfo;
}
public void setBizInfo(BizInfo bizInfo)
{
this.bizInfo = bizInfo;
}
public IdcardInfo getIdcardInfo()
{
return idcardInfo;
}
public void setIdcardInfo(IdcardInfo idcardInfo)
{
this.idcardInfo = idcardInfo;
}
public LivenessResult getLivenessResult()
{
return livenessResult;
}
public void setLivenessResult(LivenessResult livenessResult)
{
this.livenessResult = livenessResult;
}
public VerifyResult getVerifyResult()
{
return verifyResult;
}
public void setVerifyResult(VerifyResult verifyResult)
{
this.verifyResult = verifyResult;
}
public ImageList getImages()
{
return images;
}
public void setImages(ImageList images)
{
this.images = images;
}
public static class BizInfo
{
@SerializedName(Const.API_PARAM_BIZ_ID)
private String bizId;
@SerializedName(Const.API_PARAM_BIZ_NO)
private String bizNo;
@SerializedName(Const.API_PARAM_BIZ_EXTRA_DATA)
private String bizExtraData;
public String getBizId()
{
return bizId;
}
public void setBizId(String bizId)
{
this.bizId = bizId;
}
public String getBizNo()
{
return bizNo;
}
public void setBizNo(String bizNo)
{
this.bizNo = bizNo;
}
public String getBizExtraData()
{
return bizExtraData;
}
public void setBizExtraData(String bizExtraData)
{
this.bizExtraData = bizExtraData;
}
}
public static class IdcardInfo
{
@SerializedName(Const.API_PARAM_IDCARD_MODE)
private String idcardMode;
@SerializedName(Const.API_PARAM_IDCARD_UNEDITABLE_FIELD)
private String idcardUnEditableField;
@SerializedName(Const.API_PARAM_IDCARD_MODE_USER)
private String idcardModeUser;
@SerializedName(Const.API_PARAM_IDCARD_NUMBER)
private String idcardNumber;
@SerializedName(Const.API_PARAM_IDCARD_NAME)
private String idcardName;
@SerializedName(Const.API_PARAM_IDCARD_VALID_DATE)
private String idcardValidDate;
@SerializedName(Const.API_PARAM_IDCARD_ISSUED_BY)
private String idcardIssuedBy;
@SerializedName(Const.API_PARAM_FRONT_SIDE)
private IdcardSide frontSide;
@SerializedName(Const.API_PARAM_BACK_SIDE)
private IdcardSide backSide;
@SerializedName(Const.API_PARAM_OCR_FRONT_QUALITY)
private IdcardQuality frontQuality;
@SerializedName(Const.API_PARAM_OCR_BACK_QUALITY)
private IdcardQuality backQuality;
public String getIdcardMode()
{
return idcardMode;
}
public void setIdcardMode(String idcardMode)
{
this.idcardMode = idcardMode;
}
public String getIdcardUnEditableField()
{
return idcardUnEditableField;
}
public void setIdcardUnEditableField(String idcardUnEditableField)
{
this.idcardUnEditableField = idcardUnEditableField;
}
public String getIdcardModeUser()
{
return idcardModeUser;
}
public void setIdcardModeUser(String idcardModeUser)
{
this.idcardModeUser = idcardModeUser;
}
public String getIdcardNumber()
{
return idcardNumber;
}
public void setIdcardNumber(String idcardNumber)
{
this.idcardNumber = idcardNumber;
}
public String getIdcardName()
{
return idcardName;
}
public void setIdcardName(String idcardName)
{
this.idcardName = idcardName;
}
public String getIdcardValidDate()
{
return idcardValidDate;
}
public void setIdcardValidDate(String idcardValidDate)
{
this.idcardValidDate = idcardValidDate;
}
public String getIdcardIssuedBy()
{
return idcardIssuedBy;
}
public void setIdcardIssuedBy(String idcardIssuedBy)
{
this.idcardIssuedBy = idcardIssuedBy;
}
public IdcardSide getFrontSide()
{
return frontSide;
}
public void setFrontSide(IdcardSide frontSide)
{
this.frontSide = frontSide;
}
public IdcardSide getBackSide()
{
return backSide;
}
public void setBackSide(IdcardSide backSide)
{
this.backSide = backSide;
}
public IdcardQuality getFrontQuality()
{
return frontQuality;
}
public void setFrontQuality(IdcardQuality frontQuality)
{
this.frontQuality = frontQuality;
}
public IdcardQuality getBackQuality()
{
return backQuality;
}
public void setBackQuality(IdcardQuality backQuality)
{
this.backQuality = backQuality;
}
}
public static class IdcardSide
{
@SerializedName(Const.API_PARAM_OCR_RESULT)
private IdCardV1Response ocrResult;
@SerializedName(Const.API_PARAM_UPLOAD_TIMES_LOWERCASE)
private int uploadTimes;
public IdCardV1Response getOcrResult()
{
return ocrResult;
}
public void setOcrResult(IdCardV1Response ocrResult)
{
this.ocrResult = ocrResult;
}
public int getUploadTimes()
{
return uploadTimes;
}
public void setUploadTimes(int uploadTimes)
{
this.uploadTimes = uploadTimes;
}
}
public static class IdcardQuality
{
private IdcardDict name;
@SerializedName(Const.API_PARAM_IDCARD_NUMBER)
private IdcardDict idcardNumber;
private IdcardDict gender;
@SerializedName(Const.API_PARAM_BIRTH_YEAR)
private IdcardDict birthYear;
@SerializedName(Const.API_PARAM_BIRTH_MONTH)
private IdcardDict birthMonth;
@SerializedName(Const.API_PARAM_BIRTH_DAY)
private IdcardDict birthDay;
private IdcardDict nationality;
private IdcardDict address;
@SerializedName(Const.API_PARAM_ISSUED_BY)
private IdcardDict issuedBy;
@SerializedName(Const.API_PARAM_VALID_DATE_START)
private IdcardDict validDateStart;
@SerializedName(Const.API_PARAM_VALID_DATE_END)
private IdcardDict validDateEnd;
public IdcardDict getName()
{
return name;
}
public void setName(IdcardDict name)
{
this.name = name;
}
public IdcardDict getIdcardNumber()
{
return idcardNumber;
}
public void setIdcardNumber(IdcardDict idcardNumber)
{
this.idcardNumber = idcardNumber;
}
public IdcardDict getGender()
{
return gender;
}
public void setGender(IdcardDict gender)
{
this.gender = gender;
}
public IdcardDict getBirthYear()
{
return birthYear;
}
public void setBirthYear(IdcardDict birthYear)
{
this.birthYear = birthYear;
}
public IdcardDict getBirthMonth()
{
return birthMonth;
}
public void setBirthMonth(IdcardDict birthMonth)
{
this.birthMonth = birthMonth;
}
public IdcardDict getBirthDay()
{
return birthDay;
}
public void setBirthDay(IdcardDict birthDay)
{
this.birthDay = birthDay;
}
public IdcardDict getNationality()
{
return nationality;
}
public void setNationality(IdcardDict nationality)
{
this.nationality = nationality;
}
public IdcardDict getAddress()
{
return address;
}
public void setAddress(IdcardDict address)
{
this.address = address;
}
public IdcardDict getIssuedBy()
{
return issuedBy;
}
public void setIssuedBy(IdcardDict issuedBy)
{
this.issuedBy = issuedBy;
}
public IdcardDict getValidDateStart()
{
return validDateStart;
}
public void setValidDateStart(IdcardDict validDateStart)
{
this.validDateStart = validDateStart;
}
public IdcardDict getValidDateEnd()
{
return validDateEnd;
}
public void setValidDateEnd(IdcardDict validDateEnd)
{
this.validDateEnd = validDateEnd;
}
}
public static class LivenessResult
{
private String result;
@SerializedName(Const.API_PARAM_PROCEDURE_TYPE)
private String procedureType;
private Details details;
@SerializedName(Const.API_PARAM_FACE_GENUINENESS)
private FaceGenuineness faceGenuineness;
public String getResult()
{
return result;
}
public void setResult(String result)
{
this.result = result;
}
public String getProcedureType()
{
return procedureType;
}
public void setProcedureType(String procedureType)
{
this.procedureType = procedureType;
}
public Details getDetails()
{
return details;
}
public void setDetails(Details details)
{
this.details = details;
}
public FaceGenuineness getFaceGenuineness()
{
return faceGenuineness;
}
public void setFaceGenuineness(FaceGenuineness faceGenuineness)
{
this.faceGenuineness = faceGenuineness;
}
}
public static class Details
{
@SerializedName(Const.API_PARAM_UPLOAD_TIMES_UPPERCASE)
private Integer uploadTimes;
@SerializedName(Const.API_PARAM_FACE_NOT_FOUND_UPPERCASE)
private Integer faceNotFound;
@SerializedName(Const.API_PARAM_LOW_FACE_QUALITY_UPPERCASE)
private Integer lowFaceQuality;
@SerializedName(Const.API_PARAM_INVALID_VIDEO_DURATION_UPPERCASE)
private Integer invalidVideoDuration;
@SerializedName(Const.API_PARAM_SR_ERROR_UPPERCASE)
private Integer srError;
@SerializedName(Const.API_PARAM_NOT_SYNCHRONIZED_UPPERCASE)
private Integer notSynchronized;
@SerializedName(Const.API_PARAM_NO_AUDIO_UPPERCASE)
private Integer noAudio;
@SerializedName(Const.API_PARAM_VIDEO_FORMAT_UNSUPPORTED_UPPERCASE)
private Integer videoFormatUnsupported;
@SerializedName(Const.API_PARAM_VIDEO_FACE_INCONSISTENT_UPPERCASE)
private Integer videoFaceInconsistent;
@SerializedName(Const.API_PARAM_FACE_FRONT)
private SelfieDetails faceFront;
@SerializedName(Const.API_PARAM_FACE_SIDE)
private SelfieDetails faceSide;
public int getUploadTimes()
{
return uploadTimes;
}
public void setUploadTimes(int uploadTimes)
{
this.uploadTimes = uploadTimes;
}
public int getFaceNotFound()
{
return faceNotFound;
}
public void setFaceNotFound(int faceNotFound)
{
this.faceNotFound = faceNotFound;
}
public int getLowFaceQuality()
{
return lowFaceQuality;
}
public void setLowFaceQuality(int lowFaceQuality)
{
this.lowFaceQuality = lowFaceQuality;
}
public int getInvalidVideoDuration()
{
return invalidVideoDuration;
}
public void setInvalidVideoDuration(int invalidVideoDuration)
{
this.invalidVideoDuration = invalidVideoDuration;
}
public Integer getSrError()
{
return srError;
}
public void setSrError(Integer srError)
{
this.srError = srError;
}
public Integer getNotSynchronized()
{
return notSynchronized;
}
public void setNotSynchronized(Integer notSynchronized)
{
this.notSynchronized = notSynchronized;
}
public Integer getNoAudio()
{
return noAudio;
}
public void setNoAudio(Integer noAudio)
{
this.noAudio = noAudio;
}
public int getVideoFormatUnsupported()
{
return videoFormatUnsupported;
}
public void setVideoFormatUnsupported(int videoFormatUnsupported)
{
this.videoFormatUnsupported = videoFormatUnsupported;
}
public int getVideoFaceInconsistent()
{
return videoFaceInconsistent;
}
public void setVideoFaceInconsistent(int videoFaceInconsistent)
{
this.videoFaceInconsistent = videoFaceInconsistent;
}
public SelfieDetails getFaceFront()
{
return faceFront;
}
public void setFaceFront(SelfieDetails faceFront)
{
this.faceFront = faceFront;
}
public SelfieDetails getFaceSide()
{
return faceSide;
}
public void setFaceSide(SelfieDetails faceSide)
{
this.faceSide = faceSide;
}
}
public static class SelfieDetails
{
@SerializedName(Const.API_PARAM_FACE_UPLOAD_TIMES_UPPERCASE)
private int faceUploadTimes;
@SerializedName(Const.API_PARAM_FACE_NOT_FOUND_UPPERCASE)
private int faceNotFound;
@SerializedName(Const.API_PARAM_FACE_BLURRED_UPPERCASE)
private int faceBlurred;
@SerializedName(Const.API_PARAM_FACE_MULTIPLE_FACES_UPPERCASE)
private int faceMultipleFaces;
@SerializedName(Const.API_PARAM_FACE_POOR_LIGHT_UPPERCASE)
private int facePoorLight;
@SerializedName(Const.API_PARAM_FACE_NOT_FRONT_UPPERCASE)
private Integer faceNotFront;
@SerializedName(Const.API_PARAM_FACE_NOT_SIDE_UPPERCASE)
private Integer faceNotSide;
@SerializedName(Const.API_PARAM_FACE_NOT_PROPER_POSITION_UPPERCASE)
private int faceNotProperPosition;
@SerializedName(Const.API_PARAM_UNSUPPORTED_FORMAT_UPPERCASE)
private int unsupportedFormat;
public int getFaceUploadTimes()
{
return faceUploadTimes;
}
public void setFaceUploadTimes(int faceUploadTimes)
{
this.faceUploadTimes = faceUploadTimes;
}
public int getFaceNotFound()
{
return faceNotFound;
}
public void setFaceNotFound(int faceNotFound)
{
this.faceNotFound = faceNotFound;
}
public int getFaceBlurred()
{
return faceBlurred;
}
public void setFaceBlurred(int faceBlurred)
{
this.faceBlurred = faceBlurred;
}
public int getFaceMultipleFaces()
{
return faceMultipleFaces;
}
public void setFaceMultipleFaces(int faceMultipleFaces)
{
this.faceMultipleFaces = faceMultipleFaces;
}
public int getFacePoorLight()
{
return facePoorLight;
}
public void setFacePoorLight(int facePoorLight)
{
this.facePoorLight = facePoorLight;
}
public Integer getFaceNotFront()
{
return faceNotFront;
}
public void setFaceNotFront(Integer faceNotFront)
{
this.faceNotFront = faceNotFront;
}
public Integer getFaceNotSide()
{
return faceNotSide;
}
public void setFaceNotSide(Integer faceNotSide)
{
this.faceNotSide = faceNotSide;
}
public int getFaceNotProperPosition()
{
return faceNotProperPosition;
}
public void setFaceNotProperPosition(int faceNotProperPosition)
{
this.faceNotProperPosition = faceNotProperPosition;
}
public int getUnsupportedFormat()
{
return unsupportedFormat;
}
public void setUnsupportedFormat(int unsupportedFormat)
{
this.unsupportedFormat = unsupportedFormat;
}
}
public static class VerifyResult extends CompareResponse
{
@SerializedName(Const.API_PARAM_RESULT_IDCARD_PHOTO)
private Result resultIdcardPhoto;
@SerializedName(Const.API_PARAM_RESULT_IDCARD_DATASOURCE)
private Result resultIdcardDatasource;
public Result getResultIdcardPhoto()
{
return resultIdcardPhoto;
}
public void setResultIdcardPhoto(Result resultIdcardPhoto)
{
this.resultIdcardPhoto = resultIdcardPhoto;
}
public Result getResultIdcardDatasource()
{
return resultIdcardDatasource;
}
public void setResultIdcardDatasource(Result resultIdcardDatasource)
{
this.resultIdcardDatasource = resultIdcardDatasource;
}
}
}
|
sahiljain11/Emacs-Setup
|
elpa/jdee-server-master/src/main/java/jde/parser/syntaxtree/DoStatement.java
|
<gh_stars>0
//
// Generated by JTB 1.1.2
//
package jde.parser.syntaxtree;
/**
* Grammar production:
* <PRE>
* f0 -> "do"
* f1 -> Statement()
* f2 -> "while"
* f3 -> "("
* f4 -> Expression()
* f5 -> ")"
* f6 -> ";"
* </PRE>
*/
public class DoStatement implements Node {
public NodeToken f0;
public Statement f1;
public NodeToken f2;
public NodeToken f3;
public Expression f4;
public NodeToken f5;
public NodeToken f6;
public DoStatement(NodeToken n0, Statement n1, NodeToken n2, NodeToken n3, Expression n4, NodeToken n5, NodeToken n6) {
f0 = n0;
f1 = n1;
f2 = n2;
f3 = n3;
f4 = n4;
f5 = n5;
f6 = n6;
}
public DoStatement(Statement n0, Expression n1) {
f0 = new NodeToken("do");
f1 = n0;
f2 = new NodeToken("while");
f3 = new NodeToken("(");
f4 = n1;
f5 = new NodeToken(")");
f6 = new NodeToken(";");
}
public void accept(jde.parser.visitor.Visitor v) {
v.visit(this);
}
}
|
xwlxwl/WeChat
|
WeChat/WeChat/ViewModel/Search/Music/ItemViewModel/MHSearchMusicHistoryItemViewModel.h
|
<filename>WeChat/WeChat/ViewModel/Search/Music/ItemViewModel/MHSearchMusicHistoryItemViewModel.h<gh_stars>1000+
//
// MHSearchMusicHistoryItemViewModel.h
// WeChat
//
// Created by admin on 2020/5/15.
// Copyright © 2020 CoderMikeHe. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MHSearchMusicHistoryItemViewModel : NSObject
/// musics
@property (nonatomic, readonly, copy) NSString *music;
/// clearMusicCommand
@property (nonatomic, readwrite, strong) RACCommand *clearMusicCommand;
- (instancetype)initWithMusic:(NSString *)music;
@end
NS_ASSUME_NONNULL_END
|
UofTL/yard-sale
|
client/src/components/ProductCard/ProductCard.js
|
<filename>client/src/components/ProductCard/ProductCard.js
import React from "react";
import "./ProductCard.css";
const ProductCard = props => (
<div className="productContainer">
{props.children}
</div>
);
export default ProductCard;
|
rafaelcardoso/design-system
|
packages/table/src/css/index.js
|
<reponame>rafaelcardoso/design-system
import core from '@pluralsight/ps-design-system-core'
export default {
'.psds-table': {
display: 'flex',
width: '100%',
flexFlow: 'column',
justifyContent: 'center'
},
'.psds-table-dark-theme': {
backgroundColor: core.colors.gray06,
},
'.psds-table-header': {
padding: '0 1%',
display: 'flex',
wordBreak: 'break-word',
justifyContent: 'left',
flexDirection: 'row',
textAlign: 'left',
flexGrow: '1',
flexBasis: '0',
color: core.colors.gray02,
fontSize: '12px',
lineHeight: '15px',
height: '38px',
fontWeight: core.type.fontWeightMedium,
},
'.psds-table-header-dark:hover': {
color: core.colors.white,
},
'.psds-table-header-light:hover': {
color: core.colors.black,
},
'.psds-table-header-light': {
color: core.colors.gray03
},
'.psds-table-header--active': {
color: core.colors.white
},
'.psds-table-header-light--active': {
color: core.colors.black
},
'.psds-table-header-controls': {
width: '20px',
height: '20px',
display: 'flex',
marginLeft: '10px',
position: 'relative',
top: '-3px',
},
'.psds-table-header-controls--active': {
top: '0px',
},
'.psds-table-line': {
display: 'flex',
position: 'relative',
borderBottom: `1px solid ${core.colors.gray03}`
},
'.psds-table-line-light': {
borderColor: `${core.colors.gray02}`
},
'.psds-table-sortable-header': {
cursor: 'pointer'
},
'.psds-table-sort-icons': {
position: 'relative',
marginTop: '3px',
width: '15px',
display: 'inline-block',
height: '20px',
lineHeight: '27px',
},
'.psds-table-sort-icon': {
position: 'absolute'
},
'.psds-table-sort--active': {
color: core.colors.white
},
'.psds-table-sort-light--active': {
color: core.colors.black
},
'.psds-table__sort-icon-up': {
top: '-5px',
left: '0px'
},
'.psds-table__sort-icon-down': {
top: '1px',
left: '0px'
},
'.psds-table-row-container': {
display: 'flex',
flexFlow: 'column'
},
'.psds-table-row-container-dark': {
borderBottom: `1px solid ${core.colors.gray03}`
},
'.psds-table-row-container-light': {
borderBottom: `1px solid ${core.colors.gray02}`
},
'.psds-table-row-container-clickable': {
cursor: 'pointer'
},
'.psds-table-row-container-dark-clickable:hover': {
backgroundColor: core.colors.gray04
},
'.psds-table-row-container-light-clickable:hover': {
backgroundColor: core.colors.gray02
},
'.psds-table-row-container-clickable--open': {
marginBottom: '24px',
borderBottom: '0px'
},
'.psds-table-row-container-dark-clickable--open': {
backgroundColor: core.colors.gray04
},
'.psds-table-row-container-light-clickable--open': {
backgroundColor: core.colors.gray02
},
'.psds-table-row': {
display: 'flex',
width: '100%'
},
'.psds-table-row-nested': {
padding: '30px',
cursor: 'default',
backgroundColor: core.colors.gray05
},
'.psds-table-row-nested-light': {
backgroundColor: core.colors.gray01
},
'.psds-table-row-nested-cell-dark': {
color: core.colors.gray02
},
'.psds-table-row-nested-cell-light': {
color: core.colors.gray03
},
'.psds-table-column': {
color: core.colors.white,
padding: '1%',
display: 'flex',
alignItems: 'center',
lineHeight: '18px',
minHeight: '55px',
flexGrow: '1',
flexBasis: '0'
},
'.psds-table-column-light': {
color: core.colors.gray03
}
}
|
bes422/jdi-light
|
jdi-light-html-tests/src/main/java/io/github/com/pages/HomePageFrame.java
|
<filename>jdi-light-html-tests/src/main/java/io/github/com/pages/HomePageFrame.java
package io.github.com.pages;
import com.epam.jdi.light.elements.pageobjects.annotations.simple.Css;
import com.epam.jdi.light.ui.html.common.Icon;
public class HomePageFrame {
@Css("img#user-icon") public Icon userIcon;
}
|
Senthilarun-Sparkout/zipchat-clone-new
|
zipchat-clone/src/main/java/com/chat/zipchat/clone/Activity/PhotoEdit/PhotoEditActivity.java
|
package com.chat.zipchat.clone.Activity.PhotoEdit;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.chat.zipchat.clone.R;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.File;
import java.io.IOException;
import ja.burhanrashid52.photoeditor.PhotoEditor;
import ja.burhanrashid52.photoeditor.PhotoEditorView;
import ja.burhanrashid52.photoeditor.SaveSettings;
import static com.chat.zipchat.clone.Common.BaseClass.PhotoDirectoryPath;
public class PhotoEditActivity extends AppCompatActivity implements View.OnClickListener, StickerBSFragment.StickerListener {
ImageView imagePhotoEditBack, imagePhotoEditUndo, imagePhotoEditRedo,
imagePhotoEditCrop, imagePhotoEditSticker, imagePhotoEditText, imagePhotoEditPaint;
VerticalSlideColorPicker colorPickerView;
PhotoEditorView photoEditorView;
FloatingActionButton fabPhotoDone;
private PhotoEditor mPhotoEditor;
private StickerBSFragment mStickerBSFragment;
private int mSelectedColor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_edit);
imagePhotoEditBack = findViewById(R.id.img_photo_edit_back);
imagePhotoEditUndo = findViewById(R.id.img_photo_edit_undo);
imagePhotoEditRedo = findViewById(R.id.img_photo_edit_redo);
imagePhotoEditCrop = findViewById(R.id.img_photo_edit_crop);
imagePhotoEditSticker = findViewById(R.id.img_photo_edit_stickers);
imagePhotoEditText = findViewById(R.id.img_photo_edit_text);
imagePhotoEditPaint = findViewById(R.id.img_photo_edit_paint);
photoEditorView = findViewById(R.id.photo_editor_view);
fabPhotoDone = findViewById(R.id.fab_photo_done);
mPhotoEditor = new PhotoEditor.Builder(this, photoEditorView)
.setPinchTextScalable(true)
.build();
colorPickerView = findViewById(R.id.color_picker_view);
colorPickerView.setOnColorChangeListener(
new VerticalSlideColorPicker.OnColorChangeListener() {
@Override
public void onColorChange(int selectedColor) {
mSelectedColor = selectedColor;
if (colorPickerView.getVisibility() == View.VISIBLE) {
imagePhotoEditPaint.setBackgroundColor(selectedColor);
mPhotoEditor.setBrushColor(selectedColor);
}
}
});
imagePhotoEditBack.setOnClickListener(this);
imagePhotoEditUndo.setOnClickListener(this);
imagePhotoEditRedo.setOnClickListener(this);
imagePhotoEditCrop.setOnClickListener(this);
imagePhotoEditSticker.setOnClickListener(this);
imagePhotoEditText.setOnClickListener(this);
imagePhotoEditPaint.setOnClickListener(this);
fabPhotoDone.setOnClickListener(this);
mStickerBSFragment = new StickerBSFragment();
mStickerBSFragment.setStickerListener(this);
try {
Uri imageUri = Uri.parse(getIntent().getStringExtra("imageUri"));
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
photoEditorView.getSource().setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.img_photo_edit_back) {
finish();
} else if (i == R.id.img_photo_edit_undo) {
mPhotoEditor.undo();
} else if (i == R.id.img_photo_edit_redo) {
mPhotoEditor.redo();
} else if (i == R.id.img_photo_edit_crop) {
} else if (i == R.id.img_photo_edit_stickers) {
ShowBrush(false);
mStickerBSFragment.show(getSupportFragmentManager(), mStickerBSFragment.getTag());
} else if (i == R.id.img_photo_edit_text) {
ShowBrush(false);
TextEditorDialogFragment textEditorDialogFragment = TextEditorDialogFragment.show(this);
textEditorDialogFragment.setOnTextEditorListener(new TextEditorDialogFragment.TextEditor() {
@Override
public void onDone(String inputText, int colorCode) {
mPhotoEditor.addText(inputText, colorCode);
}
});
} else if (i == R.id.img_photo_edit_paint) {
if (colorPickerView.getVisibility() == View.VISIBLE) {
ShowBrush(false);
} else {
ShowBrush(true);
}
} else if (i == R.id.fab_photo_done) {
saveImage();
}
}
@Override
public void onStickerClick(Bitmap bitmap) {
mPhotoEditor.addImage(bitmap);
}
private void ShowBrush(boolean enableBrush) {
if (enableBrush) {
mPhotoEditor.setBrushColor(mSelectedColor);
imagePhotoEditPaint.setBackgroundColor(mSelectedColor);
mPhotoEditor.setBrushDrawingMode(true);
colorPickerView.setVisibility(View.VISIBLE);
} else {
imagePhotoEditPaint.setBackgroundColor(getResources().getColor(android.R.color.transparent));
mPhotoEditor.setBrushDrawingMode(false);
colorPickerView.setVisibility(View.INVISIBLE);
}
}
/**
* Method to save the edited image
*/
@SuppressLint("MissingPermission")
private void saveImage() {
DatabaseReference referenceMessageInsert = FirebaseDatabase.getInstance().getReference("messages");
final String mGroupId = referenceMessageInsert.push().getKey();
File folder = new File(Environment.getExternalStorageDirectory().toString() + "/WhatsApp Clone/Photos");
if (!folder.isDirectory()) {
folder.mkdirs();
}
File file = new File(PhotoDirectoryPath + "/" + mGroupId + ".jpg");
try {
file.createNewFile();
SaveSettings saveSettings = new SaveSettings.Builder()
.setClearViewsEnabled(true)
.setTransparencyEnabled(true)
.build();
mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
@Override
public void onSuccess(@NonNull String imagePath) {
setResult(RESULT_OK, new Intent().putExtra("imagePath", imagePath));
finish();
}
@Override
public void onFailure(@NonNull Exception exception) {
Toast.makeText(PhotoEditActivity.this, "Failed to save Image", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
|
JamesHutch/alogic
|
src/main/scala/com/argondesign/alogic/passes/RemoveUnused.scala
|
<gh_stars>0
////////////////////////////////////////////////////////////////////////////////
// Argon Design Ltd. Project P8009 Alogic
// Copyright (c) 2018 Argon Design Ltd. All rights reserved.
//
// This file is covered by the BSD (with attribution) license.
// See the LICENSE file for the precise wording of the license.
//
// Module: Alogic Compiler
// Author: <NAME>
//
// DESCRIPTION:
//
// Remove local variable and port symbols which are never used
////////////////////////////////////////////////////////////////////////////////
package com.argondesign.alogic.passes
import com.argondesign.alogic.analysis.ReadSymbols
import com.argondesign.alogic.analysis.WrittenSymbols
import com.argondesign.alogic.ast.TreeTransformer
import com.argondesign.alogic.ast.Trees._
import com.argondesign.alogic.ast.Trees.Expr.InstancePortRef
import com.argondesign.alogic.core.CompilerContext
import com.argondesign.alogic.core.Symbols._
import com.argondesign.alogic.core.Types._
import com.argondesign.alogic.typer.TypeAssigner
import com.argondesign.alogic.util.unreachable
import scala.annotation.tailrec
import scala.collection.immutable.HashSet
import scala.collection.mutable
final class RemoveUnused(unusedSymbols: Set[Symbol])(implicit cc: CompilerContext)
extends TreeTransformer {
private[this] val ourUnused = mutable.HashSet[Symbol]()
override def enter(tree: Tree): Unit = tree match {
case entity: Entity => {
for (Decl(symbol, _) <- entity.declarations if unusedSymbols contains symbol) {
ourUnused add symbol
}
}
case _ => ()
}
def emptyStmt(stmt: Stmt): Boolean = stmt match {
case StmtBlock(Nil) => true
case _: StmtFence => true // TODO: Strip fences earlier
case StmtBlock(body) => body forall emptyStmt
case StmtIf(_, eBody, None) => emptyStmt(eBody)
case StmtIf(_, eBody, Some(tBody)) => emptyStmt(eBody) && emptyStmt(tBody)
case StmtCase(_, cases, defaults) => {
(defaults forall emptyStmt) && {
cases forall { case CaseClause(_, body) => emptyStmt(body) }
}
}
case _ => false
}
override def transform(tree: Tree): Tree = tree match {
////////////////////////////////////////////////////////////////////////////
// Fold empty statements, unless they are already empty
////////////////////////////////////////////////////////////////////////////
case StmtBlock(Nil) => tree
case stmt: Stmt if emptyStmt(stmt) => {
TypeAssigner(StmtBlock(Nil) withLoc tree.loc)
}
////////////////////////////////////////////////////////////////////////////
// Remove assignments that write only unused symbols
////////////////////////////////////////////////////////////////////////////
case StmtAssign(lhs, _) if WrittenSymbols(lhs) forall ourUnused.contains => {
TypeAssigner(StmtBlock(Nil) withLoc tree.loc)
}
////////////////////////////////////////////////////////////////////////////
// Remove declarations and connections to unused symbols
////////////////////////////////////////////////////////////////////////////
case entity: Entity => {
// If we are removing a _q, drop the suffix from the _d
for {
qSymbol <- ourUnused
dSymbol <- qSymbol.attr.flop.get
} {
assert(dSymbol.name endsWith "_d")
dSymbol rename dSymbol.name.dropRight(2)
dSymbol.attr.combSignal set true
}
// Remove declarations of unused symbols
val decls = entity.declarations filterNot {
case Decl(symbol, _) => ourUnused contains symbol
case _ => unreachable
}
// Remove unused instances
val insts = entity.instances filterNot {
case Instance(Sym(symbol), _, _, _) => unusedSymbols contains symbol
case _ => unreachable
}
// Remove connects driving only unused symbols
val conns = entity.connects filterNot {
case Connect(_, List(InstancePortRef(iSymbol, pSymbol))) => {
unusedSymbols.contains(iSymbol) || unusedSymbols.contains(pSymbol)
}
case Connect(_, List(rhs)) => WrittenSymbols(rhs) forall ourUnused.contains
case _ => false
}
TypeAssigner {
entity.copy(
declarations = decls,
instances = insts,
connects = conns
) withVariant entity.variant withLoc tree.loc
}
}
case _ => tree
}
}
object RemoveUnused extends Pass {
val name = "remove-unused"
private def gather(trees: List[Tree])(f: Entity => Iterator[Symbol]): Set[Symbol] = {
HashSet() ++ {
trees.par flatMap {
case entity: Entity => f(entity)
case _ => unreachable
}
}
}
@tailrec
private def loop(trees: List[Tree])(implicit cc: CompilerContext): List[Tree] = {
// TODO: Could prune every entity completely that has only inputs left
// TODO: Rename interconnect for removed ports
// Gather all symbols considered for removal
val candidateSymbols = gather(trees) { entity =>
val Sym(eSymbol) = entity.ref
val isTopLevel = eSymbol.attr.topLevel.get contains true
val isVerbatim = entity.variant == "verbatim"
val eSymbols = if (isTopLevel) Iterator.empty else Iterator.single(eSymbol)
val dSymbols = if (isVerbatim) {
// Retain all definitions for verbatim entities
Iterator.empty
} else {
val stateVarQ = eSymbol.attr.stateVar.get
val stateVarD = stateVarQ map { _.attr.flop.value }
entity.declarations.iterator collect {
case Decl(symbol, _) => symbol
} filterNot { symbol =>
// Retain the state variables if they exist
(stateVarQ contains symbol) || (stateVarD contains symbol)
} filter { // Retain inputs and outputs of top level entities
_.kind match {
case _: TypeIn => !isTopLevel
case _: TypeOut => !isTopLevel
case _ => true
}
}
}
val iSymbols = entity.instances.iterator collect {
case Instance(Sym(iSymbol), _, _, _) => iSymbol
}
eSymbols ++ dSymbols ++ iSymbols
}
// Gather all used symbols. A symbol is used if it's value is consumed,
// this can happen when it is read in an rvalue, read in an lvalue, or
// is instantiated. Furthermore all flop _d signals and array
// _we/_waddr/_wdata signals are used. At the moment we also cannot remove
// symbols that are written through a concatenation lvalue, as they are
// required as placeholders
val usedSymbols = gather(trees) {
_ flatCollect {
case Instance(_, Sym(eSymbol), _, _) => Iterator.single(eSymbol)
case Connect(lhs, List(rhs: ExprCat)) => {
// Concatenation on the right, everything is used, if only as a placeholder
// TODO: if any symbol in the concatenation is used, then all are used
val lSymbols = lhs match {
case InstancePortRef(iSymbol, pSymbol) => Iterator(iSymbol, pSymbol)
case other => ReadSymbols.rval(lhs)
}
val rSymbols = rhs collect { case ExprRef(symbol) => symbol }
lSymbols ++ rSymbols
}
case Connect(InstancePortRef(iSymbol, pSymbol), List(rhs)) => {
// instance.port on left hand side
Iterator(iSymbol, pSymbol) ++ ReadSymbols.lval(rhs)
}
case Connect(lhs, List(InstancePortRef(_, _))) => {
// instance.port on right hand side
ReadSymbols.rval(lhs)
}
case Connect(lhs, List(rhs)) => {
// Everything on the left, but on the right only stuff that is read
ReadSymbols.rval(lhs) ++ ReadSymbols.lval(rhs)
}
case stmt @ StmtAssign(_: ExprCat, _) => {
// Concatenation on the left, everything is used, if only as a placeholder
// TODO: if any symbol in the concatenation is used, then all are used
stmt collect { case ExprRef(symbol) => symbol }
}
case StmtAssign(lhs, rhs) => {
// Everything on the right, but on the left only stuff that is read
ReadSymbols.lval(lhs) ++ ReadSymbols.rval(rhs)
}
case Decl(symbol, _) if symbol.attr.flop.isSet => {
// Flop _d
symbol.attr.flop.get.iterator
}
case Decl(symbol, _) if symbol.attr.memory.isSet => {
// Array _we/_waddr/_wdata
val (we, waddr, wdata) = symbol.attr.memory.value
Iterator(we, waddr, wdata)
}
case ExprRef(symbol) => {
// Any other reference is used
Iterator.single(symbol)
}
}
}
// Compute the unused ports
val unusedSymbols = candidateSymbols diff usedSymbols
if (unusedSymbols.isEmpty) {
trees
} else {
// Remove unused entities
val usedEntities = trees filterNot {
case Entity(Sym(eSymbol), _, _, _, _, _, _, _, _) => unusedSymbols contains eSymbol
case _ => unreachable
}
// Remove symbols
val results = {
usedEntities.par map { tree =>
(new RemoveUnused(unusedSymbols)(cc))(tree).asInstanceOf[Entity]
}
}.seq.toList
// Update type of the entities for removed ports
results foreach { entity =>
val portSymbols = entity.declarations collect {
case Decl(symbol, _) if symbol.kind.isInstanceOf[TypeIn] => symbol
case Decl(symbol, _) if symbol.kind.isInstanceOf[TypeOut] => symbol
}
val Sym(entitySymbol: TypeSymbol) = entity.ref
val newKind = entitySymbol.kind match {
case kind: TypeEntity => kind.copy(portSymbols = portSymbols)
case _ => unreachable
}
entitySymbol.kind = newKind
}
// Iterate until we no longer have any unused ports
loop(results)
}
}
def apply(trees: List[Tree])(implicit cc: CompilerContext): List[Tree] = loop(trees)
}
|
useaname/thinking-in-spring-boot-samples
|
spring-boot-2.0-samples/production-ready-sample/src/main/java/thinking/in/spring/boot/samples/production/ready/jmx/spring/boot/SpringBootJmxAnnotationBootstrap.java
|
<filename>spring-boot-2.0-samples/production-ready-sample/src/main/java/thinking/in/spring/boot/samples/production/ready/jmx/spring/boot/SpringBootJmxAnnotationBootstrap.java
package thinking.in.spring.boot.samples.production.ready.jmx.spring.boot;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import thinking.in.spring.boot.samples.production.ready.jmx.spring.Calculator;
import javax.management.modelmbean.ModelMBean;
import java.io.IOException;
/**
* Spring Boot JMX 注解驱动引导类
*
* @author <a href="mailto:<EMAIL>">Mercy</a>
* @see JmxAutoConfiguration
* @since 1.0.0
*/
@EnableAutoConfiguration
public class SpringBootJmxAnnotationBootstrap {
/**
* 暴露 {@link Calculator} Bean 为 JMX {@link ModelMBean}
*
* @return {@link Calculator} Bean
*/
@Bean
public Calculator calculator() {
return new Calculator();
}
public static void main(String[] args) throws IOException {
ConfigurableApplicationContext context = new SpringApplicationBuilder(SpringBootJmxAnnotationBootstrap.class)
.web(WebApplicationType.NONE) // 非 Web 应用
.run(args);
System.out.println("按任意键结束...");
System.in.read();
context.close();
}
}
|
dimlksin2/dapp
|
lib/dapp/dapp/deps/gitartifact.rb
|
module Dapp
class Dapp
module Deps
module Gitartifact
def gitartifact_container
dappdeps_container(:gitartifact)
end
def git_bin
ruby2go_dappdeps_command(dappdeps: :gitartifact, command: :bin)
end
end # Gitartifact
end # Deps
end # Dapp
end # Dapp
|
calebwhitt/inspec-aws
|
test/integration/verify/controls/aws_ec2_vpn_endpoint.rb
|
# frozen_string_literal: true
client_vpn_endpoint_id = attribute('client_vpn_endpoint_id', value: '', description: '')
skip_control 'aws_ec2_client_vpn_endpoint-1.0' do
impact 1.0
title 'Test the properties of the vpn endpoint.'
describe aws_ec2_client_vpn_endpoint(client_vpn_endpoint_id: client_vpn_endpoint_id) do
it { should exist }
its('client_vpn_endpoint_id') { should eq client_vpn_endpoint_id }
its('description') { should eq "Example Client VPN endpoint" }
its('dns_name') { should_not eq '*.cvpn-endpoint-1234567890.prod.clientvpn.us-east-2.amazonaws.com' }
its('split_tunnel') { should eq false }
its('vpn_protocol') { should eq 'openvpn' }
its('transport_protocol') { should eq 'udp' }
its('vpn_port') { should_not eq 44375 }
its('server_certificate_arn') { should_not eq 'arn:aws:acm:us-east-2:1234567890:certificate/a20fe841-b1ef-4785-aefb-e69838eacdcb' }
end
end
|
dlanghorne0428/dancesport-tracker-projec
|
comps/models/heat.py
|
import time
from datetime import date, datetime, timezone, timedelta
from django.db import models
from comps.models.comp import Comp
from rankings.models import Couple
from comps.scoresheet.calc_points import pro_heat_level, non_pro_heat_level
class Heat(models.Model):
'''Define information for a single heat'''
# refer to the competition that hosted this heat
comp = models.ForeignKey('Comp', on_delete=models.CASCADE)
# the category is either "Heat" or "Pro heat".
# Each category has a separate sequence of heat numbers
PRO_HEAT = 'PH'
NORMAL_HEAT = 'NH'
SOLO = "SO"
FORMATION = "4M"
CATEGORY_CHOICES = [
(PRO_HEAT, "Pro heat"),
(NORMAL_HEAT, "Heat"),
(SOLO, "Solo"),
(FORMATION, "Formation")
]
category = models.CharField(max_length = 2, choices = CATEGORY_CHOICES, default = NORMAL_HEAT)
heat_number = models.IntegerField()
# the extra field is a string with additional info about the heat number
# this can indicate a ballroom, or simply be a letter like A
extra = models.CharField(max_length=20, blank=True)
# the info field stores the description of the heat. It is used to
# determine the level and dance style.
info = models.CharField(max_length=200)
# the different styles of ballroom dancing. couples are ranked in each style.
SMOOTH = "SMOO"
RHYTHM = "RHY"
STANDARD = "STD"
LATIN = "LAT"
CABARET = "CAB" # also includes theater arts and showcases
NIGHTCLUB = "NC"
COUNTRY = "CTRY"
COMBINED = "MIX" # for 9-dance, 10-dance events
UNKNOWN = "UNK"
DANCE_STYLE_CHOICES = [
(SMOOTH, "Smooth"),
(RHYTHM, "Rhythm"),
(STANDARD, "Standard"),
(LATIN, "Latin"),
(CABARET, "Cabaret-Theater_Arts"),
(NIGHTCLUB, "Nightclub"),
(COUNTRY, "Country_Western"),
(COMBINED, "Combined"),
(UNKNOWN, "Unknown"),
]
style = models.CharField(max_length = 4, choices = DANCE_STYLE_CHOICES, default="UNK")
# this field indicates the when the heat is scheduled to be danced
time = models.DateTimeField(blank=True)
# this field indicates this heat is a dance-off that was not in the original heatlist
dance_off = models.BooleanField(default=False)
# this field indicates if the heat had prelim rounds before the Final.
rounds = models.CharField(max_length=20, default="F") # default is Final only
# this field stores the base point value for the winner of a final round only heat
# value increases if preliminary rounds are danced
base_value = models.IntegerField(blank=True)
def set_level(self):
if self.category == "PH":
self.base_value = pro_heat_level(self.info)
else:
self.base_value = non_pro_heat_level(self.info, self.multi_dance())
def remove_info_prefix(self):
if self.info.startswith("L-"):
self.info = self.info[2:]
elif self.info.startswith("G-"):
self.info = self.info[2:]
elif self.info.startswith("AP-"):
self.info = self.info[3:]
elif self.info.startswith("PA-"):
self.info = self.info[3:]
# temporary
def info_prefix(self):
if self.info.startswith("L-"):
return self.info[2:]
elif self.info.startswith("G-"):
return self.info[2:]
elif self.info.startswith("AP-"):
return self.info[3:]
elif self.info.startswith("PA-"):
return self.info[3:]
else:
return self.info
def multi_dance(self):
'''This function returns True if the description indicates a multi-dance heat.'''
s = self.info
if self.category in [Heat.SOLO, Heat.FORMATION]:
return False
if "Solo Star" in s or "NP" in s:
return False
left_pos = s.find('(')
right_pos = s.find(')')
if left_pos > -1 and right_pos > -1:
if "/" in s[left_pos:right_pos] or "," in s[left_pos:right_pos]:
return True
else: # check for brackets
left_pos = s.find('[')
right_pos = s.find(']')
if left_pos == -1 or right_pos == -1:
return False
# ensure more than one character between the brackets
if right_pos > left_pos + 2:
return True
else:
return False
def set_dance_style(self):
'''This function determines the dance style based on the heat description.'''
s = self.info
if "Smooth" in s:
self.style = Heat.SMOOTH
elif "Rhythm" in s:
self.style = Heat.RHYTHM
elif "Latin" in s:
self.style = Heat.LATIN
elif "Standard" in s or "Ballroom" in s or "Balroom" in s or "Ballrom" in s:
self.style = Heat.STANDARD
elif "Nightclub" in s or "Night Club" in s or "NightClub" in s or "Niteclub" in s or "Nite Club" in s or "Caribbean" in s or "Club Dance" in s:
self.style = Heat.NIGHTCLUB
elif "Country" in s:
self.style = Heat.COUNTRY
elif "Cabaret" in s or "Theatre" in s or "Theater" in s or "Exhibition" in s:
self.style = Heat.CABARET
else:
#TODO: ask user?
if self.multi_dance():
print("Unknown style for heat " + s)
self.style = Heat.UNKNOWN
def set_time(self, time_str, day_of_week_str, time_format="%I:%M%p", date_string=None):
if date_string is not None:
date_fields = date_string.split('/')
heat_date = date(int(date_fields[2]), int(date_fields[0]), int(date_fields[1]))
else:
comp_start_date = self.comp.start_date.isocalendar()
days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
try:
isoweekday = days_of_week.index(day_of_week_str) + 1
heat_date = date.fromisocalendar(comp_start_date[0], comp_start_date[1], isoweekday)
except:
print(str(self), "Warning in day of week: " + day_of_week_str)
heat_date = self.comp.end_date
try:
time_of_day = time.strptime(time_str, time_format)
except:
print(str(self) + " Warning in time of day: " + time_str + "!")
time_of_day = time.strptime("23:45", "%H:%M")
tz = timezone(offset=timedelta(hours=0)) # avoid warnings about naive time, treat all times as UTC
# could try to get smarter about where comp was located, but why?
self.time = datetime(heat_date.year, heat_date.month, heat_date.day,
time_of_day.tm_hour, time_of_day.tm_min, tzinfo=tz)
def amateur_heat(self):
'''This function returns True if the description indicates an amateur heat.'''
if "Amateur" in self.comp.title or "BYU" in self.comp.title:
return True
s = self.info
if "AC-" in s or "AA-" in s or "Amateur" in s or "YY-" in s or "AM/AM" in s or "AmAm" in s or "Fordney" in s or "MLA" in s or "Y & Adult Am" in s:
return True
else:
return False
def junior_heat(self):
'''This function returns True if the description indicates a junior or youth heat.'''
s = self.info
s_upper = s.upper()
if "-Y" in s or "YY" in s or "Youth" in s or "YH" in s_upper or "-LY" in s or "YU" in s or "YT" in s or s.startswith("Y") or\
"-J" in s or "JR" in s or "J1" in s or "J2" in s or "Junior" in s or "JU" in s or "JNR" in s or\
"PT" in s or "Preteen" in s or "P1" in s or "P2" in s or "Pre-Teen" in s or "Pre Teen" in s or \
"High School" in s or "Elementary School" in s or \
"-TB" in s or "Teddy Bear" in s or " TB" in s or "TB " in s:
# Under 21 heats and BYU class heats are sometimes listed as youth, but should not be treated as juniors
if "U21" in s or "Under 21" in s or "Under-21" in s or "BYU" in s:
return False
else:
return True
else:
return False
def couple_type(self):
if self.category == "Pro heat" or self.category == "PH": #Heat.PRO_HEAT:
return Couple.PRO_COUPLE
elif self.amateur_heat():
if self.junior_heat():
return Couple.JR_AMATEUR_COUPLE
else:
return Couple.AMATEUR_COUPLE
else:
if self.junior_heat():
return Couple.JR_PRO_AM_COUPLE
else:
return Couple.PRO_AM_COUPLE
def __lt__(self, h):
''' override < operator to sort heats by various fields.'''
# if times are the same, sort by number
if self.time == h.time:
return self.heat_number < h.heat_number
else: # use the time to determine order
return self.time < h.time
def __str__(self):
if self.heat_number is not None and self.category is not None:
return self.comp.title + " " + self.get_category_display() + " " + str(self.heat_number)
else:
return ""
|
yaser-elbatal/SacoSafty
|
src/views/Components/Constant/ConstanceQuery.js
|
import gql from "graphql-tag";
const Get_const = gql`
query Get_scrles {
scalars {
id
created_at
updated_at
organization_hour_price
provider_to_home_price
sitter_hour_price
fine_minute_price
app_percentage
}
}
`;
export default Get_const;
|
davidmc24/cas
|
core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/CasLocaleChangeInterceptor.java
|
<filename>core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/CasLocaleChangeInterceptor.java
package org.apereo.cas.web.support;
import org.apereo.cas.configuration.model.core.web.LocaleProperties;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.util.spring.SpringExpressionLanguageValueResolver;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* This is {@link CasLocaleChangeInterceptor}.
*
* @author <NAME>
* @since 6.4.0
*/
@RequiredArgsConstructor
public class CasLocaleChangeInterceptor extends LocaleChangeInterceptor {
/**
* The Locale properties.
*/
protected final LocaleProperties localeProperties;
/**
* The Argument extractor.
*/
protected final ArgumentExtractor argumentExtractor;
/**
* The Services manager.
*/
protected final ServicesManager servicesManager;
@Setter
private List<String> supportedFlows = new ArrayList<>();
/**
* Configure locale.
*
* @param request the request
* @param response the response
* @param locale the locale
*/
protected static void configureLocale(final HttpServletRequest request,
final HttpServletResponse response,
final Locale locale) {
val localeResolver = RequestContextUtils.getLocaleResolver(request);
if (localeResolver != null) {
localeResolver.setLocale(request, response, locale);
request.setAttribute(Locale.class.getName(), locale);
}
}
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
final Object handler) throws ServletException {
val requestUrl = request.getRequestURL().toString();
if (localeProperties.isForceDefaultLocale()) {
val locale = new Locale(localeProperties.getDefaultValue());
configureLocale(request, response, locale);
return true;
}
val service = this.argumentExtractor.extractService(request);
if (service != null) {
val registeredService = servicesManager.findServiceBy(service);
if (registeredService != null && StringUtils.isNotBlank(registeredService.getLocale())) {
val locale = new Locale(SpringExpressionLanguageValueResolver.getInstance().resolve(registeredService.getLocale()));
configureLocale(request, response, locale);
}
}
val newLocale = request.getParameter(getParamName());
if (newLocale != null) {
val locale = new Locale(newLocale);
configureLocale(request, response, locale);
}
if (request.getLocale() != null && isLocaleConfigured(request)) {
val match = supportedFlows.stream().anyMatch(flowId -> requestUrl.contains('/' + flowId));
if (match) {
configureLocale(request, response, request.getLocale());
}
}
return true;
}
private static boolean isLocaleConfigured(final HttpServletRequest request) {
return request.getAttribute(Locale.class.getName()) == null;
}
}
|
SiliconLabs/gecko_sdk
|
protocol/flex/ble-cli/ble-cli.c
|
/***************************************************************************//**
* @brief
*******************************************************************************
* # License
* <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* SPDX-License-Identifier: Zlib
*
* The licensor of this software is Silicon Laboratories Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
******************************************************************************/
#include "debug_print.h"
#include "sl_cli.h"
#include "sl_bluetooth.h"
void connect_ble_cli_hello_command(sl_cli_command_arg_t *arguments)
{
sl_status_t status = sl_bt_system_hello();
connect_core_debug_print("BLE hello: %s\n",
(status == SL_STATUS_OK) ? "success" : "error");
}
void connect_ble_cli_get_address_command(sl_cli_command_arg_t *arguments)
{
bd_addr ble_address;
sl_status_t status = sl_bt_system_get_identity_address(&ble_address, 0);
connect_core_debug_print("BLE address: [%02X %02X %02X %02X %02X %02X]\n",
ble_address.addr[5], ble_address.addr[4],
ble_address.addr[3], ble_address.addr[2],
ble_address.addr[1], ble_address.addr[0]);
}
void connect_ble_cli_set_adv_params_command(sl_cli_command_arg_t *arguments)
{
uint16_t min_interval = sl_cli_get_argument_uint16(arguments, 0);
uint16_t max_interval = sl_cli_get_argument_uint16(arguments, 1);
sl_status_t status = sl_bt_advertiser_set_timing(0, // handle
min_interval,
max_interval,
0, // continue advertisement until stopped
0); // continue advertisement until stopped
if (status == SL_STATUS_OK) {
connect_core_debug_print("success\n");
} else {
connect_core_debug_print("error: 0x%04X\n", status);
}
}
void connect_ble_cli_start_adv_command(sl_cli_command_arg_t *arguments)
{
static uint8_t adv_handle = 0xFF;
uint8_t discoverable_mode = sl_cli_get_argument_uint8(arguments, 0);
uint8_t connectable_mode = sl_cli_get_argument_uint8(arguments, 1);
if (adv_handle == 0xFF) {
sl_bt_advertiser_create_set(&adv_handle);
}
// Generate the advertising data from the GATT configurator
sl_status_t status = sl_bt_legacy_advertiser_generate_data(adv_handle,
discoverable_mode);
if (status == SL_STATUS_OK) {
connect_core_debug_print("success\n");
} else {
connect_core_debug_print("error: 0x%04X\n", status);
}
status = sl_bt_legacy_advertiser_start(adv_handle,
connectable_mode);
if (status == SL_STATUS_OK) {
connect_core_debug_print("success\n");
} else {
connect_core_debug_print("error: 0x%04X\n", status);
}
}
void connect_ble_cli_open_connection_command(sl_cli_command_arg_t *arguments)
{
size_t arg_length;
uint8_t* contents = sl_cli_get_argument_hex(arguments, 0, &arg_length);
uint8_t address_type = sl_cli_get_argument_uint8(arguments, 1);
bd_addr address;
uint8_t connection_handle;
sl_status_t status;
uint8_t i;
if (arg_length != 6) {
connect_core_debug_print("wrong address length\n");
return;
}
// We do a reverse memcpy here so that we can cut&paste the address from the
// node CLI output.
for (i = 0; i < 6; i++) {
address.addr[i] = contents[6 - 1 - i];
}
status = sl_bt_connection_open(address, address_type, 1, &connection_handle);
if (status == SL_STATUS_OK) {
connect_core_debug_print("success, handle=0x%02X\n", connection_handle);
} else {
connect_core_debug_print("error: 0x%04X\n", status);
}
}
void connect_ble_cli_close_connection_command(sl_cli_command_arg_t *arguments)
{
uint8_t connection_handle = sl_cli_get_argument_uint8(arguments, 0);
sl_status_t status = sl_bt_connection_close(connection_handle);
if (status == SL_STATUS_OK) {
connect_core_debug_print("success\n");
} else {
connect_core_debug_print("error: 0x%04X\n", status);
}
}
void connect_ble_cli_set_connection_params_command(sl_cli_command_arg_t *arguments)
{
uint16_t min_interval = sl_cli_get_argument_uint16(arguments, 0);
uint16_t max_interval = sl_cli_get_argument_uint16(arguments, 1);
uint16_t slave_latency = sl_cli_get_argument_uint16(arguments, 2);
uint16_t supervision_timeout = sl_cli_get_argument_uint16(arguments, 3);
sl_status_t status = sl_bt_connection_set_default_parameters(min_interval,
max_interval,
slave_latency,
supervision_timeout,
0, // min_ce_length
0xFFFF); // max_ce_length
if (status == SL_STATUS_OK) {
connect_core_debug_print("success\n");
} else {
connect_core_debug_print("error: 0x%04X\n", status);
}
}
|
clarkmcc/go-hubspot
|
generated/accounting/model_invoice_update_response.go
|
/*
Accounting Extension
These APIs allow you to interact with HubSpot's Accounting Extension. It allows you to: * Specify the URLs that HubSpot will use when making webhook requests to your external accounting system. * Respond to webhook calls made to your external accounting system by HubSpot
API version: v3
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package accounting
import (
"encoding/json"
"time"
)
// InvoiceUpdateResponse struct for InvoiceUpdateResponse
type InvoiceUpdateResponse struct {
ExternalInvoiceNumber *string `json:"externalInvoiceNumber,omitempty"`
TotalAmountBilled float32 `json:"totalAmountBilled"`
BalanceDue float32 `json:"balanceDue"`
CurrencyCode string `json:"currencyCode"`
DueDate string `json:"dueDate"`
ExternalRecipientId string `json:"externalRecipientId"`
ReceivedByRecipientDate *int64 `json:"receivedByRecipientDate,omitempty"`
ExternalCreateDateTime *int64 `json:"externalCreateDateTime,omitempty"`
IsVoided bool `json:"isVoided"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ArchivedAt *time.Time `json:"archivedAt,omitempty"`
Archived bool `json:"archived"`
ExternalAccountId string `json:"externalAccountId"`
InvoiceStatus string `json:"invoiceStatus"`
Id string `json:"id"`
}
// NewInvoiceUpdateResponse instantiates a new InvoiceUpdateResponse object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewInvoiceUpdateResponse(totalAmountBilled float32, balanceDue float32, currencyCode string, dueDate string, externalRecipientId string, isVoided bool, createdAt time.Time, updatedAt time.Time, archived bool, externalAccountId string, invoiceStatus string, id string) *InvoiceUpdateResponse {
this := InvoiceUpdateResponse{}
this.TotalAmountBilled = totalAmountBilled
this.BalanceDue = balanceDue
this.CurrencyCode = currencyCode
this.DueDate = dueDate
this.ExternalRecipientId = externalRecipientId
this.IsVoided = isVoided
this.CreatedAt = createdAt
this.UpdatedAt = updatedAt
this.Archived = archived
this.ExternalAccountId = externalAccountId
this.InvoiceStatus = invoiceStatus
this.Id = id
return &this
}
// NewInvoiceUpdateResponseWithDefaults instantiates a new InvoiceUpdateResponse object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewInvoiceUpdateResponseWithDefaults() *InvoiceUpdateResponse {
this := InvoiceUpdateResponse{}
return &this
}
// GetExternalInvoiceNumber returns the ExternalInvoiceNumber field value if set, zero value otherwise.
func (o *InvoiceUpdateResponse) GetExternalInvoiceNumber() string {
if o == nil || o.ExternalInvoiceNumber == nil {
var ret string
return ret
}
return *o.ExternalInvoiceNumber
}
// GetExternalInvoiceNumberOk returns a tuple with the ExternalInvoiceNumber field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetExternalInvoiceNumberOk() (*string, bool) {
if o == nil || o.ExternalInvoiceNumber == nil {
return nil, false
}
return o.ExternalInvoiceNumber, true
}
// HasExternalInvoiceNumber returns a boolean if a field has been set.
func (o *InvoiceUpdateResponse) HasExternalInvoiceNumber() bool {
if o != nil && o.ExternalInvoiceNumber != nil {
return true
}
return false
}
// SetExternalInvoiceNumber gets a reference to the given string and assigns it to the ExternalInvoiceNumber field.
func (o *InvoiceUpdateResponse) SetExternalInvoiceNumber(v string) {
o.ExternalInvoiceNumber = &v
}
// GetTotalAmountBilled returns the TotalAmountBilled field value
func (o *InvoiceUpdateResponse) GetTotalAmountBilled() float32 {
if o == nil {
var ret float32
return ret
}
return o.TotalAmountBilled
}
// GetTotalAmountBilledOk returns a tuple with the TotalAmountBilled field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetTotalAmountBilledOk() (*float32, bool) {
if o == nil {
return nil, false
}
return &o.TotalAmountBilled, true
}
// SetTotalAmountBilled sets field value
func (o *InvoiceUpdateResponse) SetTotalAmountBilled(v float32) {
o.TotalAmountBilled = v
}
// GetBalanceDue returns the BalanceDue field value
func (o *InvoiceUpdateResponse) GetBalanceDue() float32 {
if o == nil {
var ret float32
return ret
}
return o.BalanceDue
}
// GetBalanceDueOk returns a tuple with the BalanceDue field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetBalanceDueOk() (*float32, bool) {
if o == nil {
return nil, false
}
return &o.BalanceDue, true
}
// SetBalanceDue sets field value
func (o *InvoiceUpdateResponse) SetBalanceDue(v float32) {
o.BalanceDue = v
}
// GetCurrencyCode returns the CurrencyCode field value
func (o *InvoiceUpdateResponse) GetCurrencyCode() string {
if o == nil {
var ret string
return ret
}
return o.CurrencyCode
}
// GetCurrencyCodeOk returns a tuple with the CurrencyCode field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetCurrencyCodeOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.CurrencyCode, true
}
// SetCurrencyCode sets field value
func (o *InvoiceUpdateResponse) SetCurrencyCode(v string) {
o.CurrencyCode = v
}
// GetDueDate returns the DueDate field value
func (o *InvoiceUpdateResponse) GetDueDate() string {
if o == nil {
var ret string
return ret
}
return o.DueDate
}
// GetDueDateOk returns a tuple with the DueDate field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetDueDateOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.DueDate, true
}
// SetDueDate sets field value
func (o *InvoiceUpdateResponse) SetDueDate(v string) {
o.DueDate = v
}
// GetExternalRecipientId returns the ExternalRecipientId field value
func (o *InvoiceUpdateResponse) GetExternalRecipientId() string {
if o == nil {
var ret string
return ret
}
return o.ExternalRecipientId
}
// GetExternalRecipientIdOk returns a tuple with the ExternalRecipientId field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetExternalRecipientIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ExternalRecipientId, true
}
// SetExternalRecipientId sets field value
func (o *InvoiceUpdateResponse) SetExternalRecipientId(v string) {
o.ExternalRecipientId = v
}
// GetReceivedByRecipientDate returns the ReceivedByRecipientDate field value if set, zero value otherwise.
func (o *InvoiceUpdateResponse) GetReceivedByRecipientDate() int64 {
if o == nil || o.ReceivedByRecipientDate == nil {
var ret int64
return ret
}
return *o.ReceivedByRecipientDate
}
// GetReceivedByRecipientDateOk returns a tuple with the ReceivedByRecipientDate field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetReceivedByRecipientDateOk() (*int64, bool) {
if o == nil || o.ReceivedByRecipientDate == nil {
return nil, false
}
return o.ReceivedByRecipientDate, true
}
// HasReceivedByRecipientDate returns a boolean if a field has been set.
func (o *InvoiceUpdateResponse) HasReceivedByRecipientDate() bool {
if o != nil && o.ReceivedByRecipientDate != nil {
return true
}
return false
}
// SetReceivedByRecipientDate gets a reference to the given int64 and assigns it to the ReceivedByRecipientDate field.
func (o *InvoiceUpdateResponse) SetReceivedByRecipientDate(v int64) {
o.ReceivedByRecipientDate = &v
}
// GetExternalCreateDateTime returns the ExternalCreateDateTime field value if set, zero value otherwise.
func (o *InvoiceUpdateResponse) GetExternalCreateDateTime() int64 {
if o == nil || o.ExternalCreateDateTime == nil {
var ret int64
return ret
}
return *o.ExternalCreateDateTime
}
// GetExternalCreateDateTimeOk returns a tuple with the ExternalCreateDateTime field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetExternalCreateDateTimeOk() (*int64, bool) {
if o == nil || o.ExternalCreateDateTime == nil {
return nil, false
}
return o.ExternalCreateDateTime, true
}
// HasExternalCreateDateTime returns a boolean if a field has been set.
func (o *InvoiceUpdateResponse) HasExternalCreateDateTime() bool {
if o != nil && o.ExternalCreateDateTime != nil {
return true
}
return false
}
// SetExternalCreateDateTime gets a reference to the given int64 and assigns it to the ExternalCreateDateTime field.
func (o *InvoiceUpdateResponse) SetExternalCreateDateTime(v int64) {
o.ExternalCreateDateTime = &v
}
// GetIsVoided returns the IsVoided field value
func (o *InvoiceUpdateResponse) GetIsVoided() bool {
if o == nil {
var ret bool
return ret
}
return o.IsVoided
}
// GetIsVoidedOk returns a tuple with the IsVoided field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetIsVoidedOk() (*bool, bool) {
if o == nil {
return nil, false
}
return &o.IsVoided, true
}
// SetIsVoided sets field value
func (o *InvoiceUpdateResponse) SetIsVoided(v bool) {
o.IsVoided = v
}
// GetCreatedAt returns the CreatedAt field value
func (o *InvoiceUpdateResponse) GetCreatedAt() time.Time {
if o == nil {
var ret time.Time
return ret
}
return o.CreatedAt
}
// GetCreatedAtOk returns a tuple with the CreatedAt field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetCreatedAtOk() (*time.Time, bool) {
if o == nil {
return nil, false
}
return &o.CreatedAt, true
}
// SetCreatedAt sets field value
func (o *InvoiceUpdateResponse) SetCreatedAt(v time.Time) {
o.CreatedAt = v
}
// GetUpdatedAt returns the UpdatedAt field value
func (o *InvoiceUpdateResponse) GetUpdatedAt() time.Time {
if o == nil {
var ret time.Time
return ret
}
return o.UpdatedAt
}
// GetUpdatedAtOk returns a tuple with the UpdatedAt field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetUpdatedAtOk() (*time.Time, bool) {
if o == nil {
return nil, false
}
return &o.UpdatedAt, true
}
// SetUpdatedAt sets field value
func (o *InvoiceUpdateResponse) SetUpdatedAt(v time.Time) {
o.UpdatedAt = v
}
// GetArchivedAt returns the ArchivedAt field value if set, zero value otherwise.
func (o *InvoiceUpdateResponse) GetArchivedAt() time.Time {
if o == nil || o.ArchivedAt == nil {
var ret time.Time
return ret
}
return *o.ArchivedAt
}
// GetArchivedAtOk returns a tuple with the ArchivedAt field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetArchivedAtOk() (*time.Time, bool) {
if o == nil || o.ArchivedAt == nil {
return nil, false
}
return o.ArchivedAt, true
}
// HasArchivedAt returns a boolean if a field has been set.
func (o *InvoiceUpdateResponse) HasArchivedAt() bool {
if o != nil && o.ArchivedAt != nil {
return true
}
return false
}
// SetArchivedAt gets a reference to the given time.Time and assigns it to the ArchivedAt field.
func (o *InvoiceUpdateResponse) SetArchivedAt(v time.Time) {
o.ArchivedAt = &v
}
// GetArchived returns the Archived field value
func (o *InvoiceUpdateResponse) GetArchived() bool {
if o == nil {
var ret bool
return ret
}
return o.Archived
}
// GetArchivedOk returns a tuple with the Archived field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetArchivedOk() (*bool, bool) {
if o == nil {
return nil, false
}
return &o.Archived, true
}
// SetArchived sets field value
func (o *InvoiceUpdateResponse) SetArchived(v bool) {
o.Archived = v
}
// GetExternalAccountId returns the ExternalAccountId field value
func (o *InvoiceUpdateResponse) GetExternalAccountId() string {
if o == nil {
var ret string
return ret
}
return o.ExternalAccountId
}
// GetExternalAccountIdOk returns a tuple with the ExternalAccountId field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetExternalAccountIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ExternalAccountId, true
}
// SetExternalAccountId sets field value
func (o *InvoiceUpdateResponse) SetExternalAccountId(v string) {
o.ExternalAccountId = v
}
// GetInvoiceStatus returns the InvoiceStatus field value
func (o *InvoiceUpdateResponse) GetInvoiceStatus() string {
if o == nil {
var ret string
return ret
}
return o.InvoiceStatus
}
// GetInvoiceStatusOk returns a tuple with the InvoiceStatus field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetInvoiceStatusOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.InvoiceStatus, true
}
// SetInvoiceStatus sets field value
func (o *InvoiceUpdateResponse) SetInvoiceStatus(v string) {
o.InvoiceStatus = v
}
// GetId returns the Id field value
func (o *InvoiceUpdateResponse) GetId() string {
if o == nil {
var ret string
return ret
}
return o.Id
}
// GetIdOk returns a tuple with the Id field value
// and a boolean to check if the value has been set.
func (o *InvoiceUpdateResponse) GetIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Id, true
}
// SetId sets field value
func (o *InvoiceUpdateResponse) SetId(v string) {
o.Id = v
}
func (o InvoiceUpdateResponse) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.ExternalInvoiceNumber != nil {
toSerialize["externalInvoiceNumber"] = o.ExternalInvoiceNumber
}
if true {
toSerialize["totalAmountBilled"] = o.TotalAmountBilled
}
if true {
toSerialize["balanceDue"] = o.BalanceDue
}
if true {
toSerialize["currencyCode"] = o.CurrencyCode
}
if true {
toSerialize["dueDate"] = o.DueDate
}
if true {
toSerialize["externalRecipientId"] = o.ExternalRecipientId
}
if o.ReceivedByRecipientDate != nil {
toSerialize["receivedByRecipientDate"] = o.ReceivedByRecipientDate
}
if o.ExternalCreateDateTime != nil {
toSerialize["externalCreateDateTime"] = o.ExternalCreateDateTime
}
if true {
toSerialize["isVoided"] = o.IsVoided
}
if true {
toSerialize["createdAt"] = o.CreatedAt
}
if true {
toSerialize["updatedAt"] = o.UpdatedAt
}
if o.ArchivedAt != nil {
toSerialize["archivedAt"] = o.ArchivedAt
}
if true {
toSerialize["archived"] = o.Archived
}
if true {
toSerialize["externalAccountId"] = o.ExternalAccountId
}
if true {
toSerialize["invoiceStatus"] = o.InvoiceStatus
}
if true {
toSerialize["id"] = o.Id
}
return json.Marshal(toSerialize)
}
type NullableInvoiceUpdateResponse struct {
value *InvoiceUpdateResponse
isSet bool
}
func (v NullableInvoiceUpdateResponse) Get() *InvoiceUpdateResponse {
return v.value
}
func (v *NullableInvoiceUpdateResponse) Set(val *InvoiceUpdateResponse) {
v.value = val
v.isSet = true
}
func (v NullableInvoiceUpdateResponse) IsSet() bool {
return v.isSet
}
func (v *NullableInvoiceUpdateResponse) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableInvoiceUpdateResponse(val *InvoiceUpdateResponse) *NullableInvoiceUpdateResponse {
return &NullableInvoiceUpdateResponse{value: val, isSet: true}
}
func (v NullableInvoiceUpdateResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableInvoiceUpdateResponse) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
|
jkost/gctoolkit
|
api/src/main/java/com/microsoft/gctoolkit/parser/datatype/TripleState.java
|
<gh_stars>1000+
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package com.microsoft.gctoolkit.parser.datatype;
import java.util.Locale;
/**
* When a boolean just won't do. Parsing a log file is a process of discovery. Nothing is known until it is known.
*/
public enum TripleState {
UNKNOWN,
TRUE,
FALSE;
/**
* Transform boolean to it's corresponding TripleState
* @param value boolean
* @return
*/
public static TripleState valueOf(boolean value) {
return (value) ? TRUE : FALSE;
}
/**
* @return {@code true} if {@code this != TripleState.UNKOWN}
*/
public boolean isKnown() {
return this != UNKNOWN;
}
/**
* @return {@code true} if {@code this == TripleState.TRUE}
*/
public boolean isTrue() {
return this == TRUE;
}
/**
* @return {@code true} if {@code this == TripleState.FALSE}
*/
public boolean isFalse() {
return this == FALSE;
}
public String toString() {
return this.name().toLowerCase(Locale.ROOT);
}
}
|
bazhenovc/WildMagic
|
LibGraphics/CurvesSurfaces/Wm5Float2Array.inl
|
// Geometric Tools, LLC
// Copyright (c) 1998-2012
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
//----------------------------------------------------------------------------
inline int Float2Array::GetNumElements () const
{
return mNumElements;
}
//----------------------------------------------------------------------------
inline Float2* Float2Array::GetData () const
{
return mElements;
}
//----------------------------------------------------------------------------
inline Float2Array::operator const Float2* () const
{
return mElements;
}
//----------------------------------------------------------------------------
inline Float2Array::operator Float2* ()
{
return mElements;
}
//----------------------------------------------------------------------------
inline const Float2& Float2Array::operator[] (int i) const
{
return mElements[i];
}
//----------------------------------------------------------------------------
inline Float2& Float2Array::operator[] (int i)
{
return mElements[i];
}
//----------------------------------------------------------------------------
|
johnrabbit687/Holtzman
|
imports/pages/give/review/Layout.js
|
<filename>imports/pages/give/review/Layout.js
// @flow
import { Component } from "react";
import AccountType from "../../../components/giving/account-type";
import Meta from "../../../components/shared/meta";
import { monetize } from "../../../util/format/";
type ILayout = {
transactions: Object,
total: number,
data: Object,
onSubmit: Function,
};
export default class Layout extends Component {
props: ILayout;
header = () => {
const { personal } = this.props.data;
return (
<h4 className="text-center">
Hi {personal.firstName}! Here are your contribution details.
</h4>
);
}
listItem = (transaction: Object, key: number) => (
<div key={key} className="soft-half-ends hard-sides">
<div className="grid" style={{ verticalAlign: "middle" }}>
<div className="grid__item two-thirds" style={{ verticalAlign: "middle" }}>
<h5 className="text-dark-secondary flush text-left">
{transaction.label}
</h5>
</div>
<div className="grid__item one-third text-right" style={{ verticalAlign: "middle" }}>
<h5 className="text-dark-secondary flush">
{monetize(transaction.value)}
</h5>
</div>
</div>
</div>
)
icon = (icon: string): any => (
<AccountType width="30px" height="21px" type={icon} />
)
render() {
if (!this.props.data) return null;
const transactions = [];
// eslint-disable-next-line
for (const transaction in this.props.transactions) {
transactions.push(this.props.transactions[transaction]);
}
const { personal } = this.props.data;
return (
<div
className="one-whole one-half@palm-wide-and-up soft-double-ends@palm-wide-and-up"
style={{ margin: "0 auto" }}
>
<Meta title="Review Your Contribution" />
<div className="push-double@lap-and-up push">
{this.header()}
</div>
<div className="soft">
<h5 className="text-dark-secodary text-left">
<small><em>{personal.campus} Campus</em></small>
</h5>
<div className="outlined--light outlined--bottom one-whole push-bottom" />
{transactions.map((transaction, key) => (
this.listItem(transaction, key)
))}
<div className="soft-ends hard-sides">
<div className="grid" style={{ verticalAlign: "middle" }}>
<div className="grid__item one-half" style={{ verticalAlign: "middle" }}>
<h5 className="text-dark-secondary flush text-left">
Total
</h5>
</div>
<div className="grid__item one-half text-right" style={{ verticalAlign: "middle" }}>
<h3 className="text-primary flush">
{monetize(this.props.total)}
</h3>
</div>
</div>
</div>
<div className="one-whole text-center">
<button className="btn soft-half-top" onClick={this.props.onSubmit}>
{"Give Now"}
</button>
</div>
</div>
</div>
);
}
}
|
rafbm/easypost-ruby
|
lib/easypost/customs_info.rb
|
class EasyPost::CustomsInfo < EasyPost::Resource
def self.all(filters={}, api_key=nil)
raise NotImplementedError.new('CustomsInfo.all not implemented.')
end
end
|
mxiao666/Dcop
|
doc/html/search/functions_7.js
|
<filename>doc/html/search/functions_7.js
var searchData=
[
['help',['Help',['../classSysCli.html#a79cdadad0680b7fa7fd926a77263c78c',1,'SysCli']]]
];
|
paige-ingram/nwhacks2022
|
node_modules/@fluentui/react-northstar/dist/es/themes/teams/components/Divider/dividerContentStyles.js
|
<filename>node_modules/@fluentui/react-northstar/dist/es/themes/teams/components/Divider/dividerContentStyles.js
import { pxToRem } from '../../../../utils';
export var dividerContentStyles = {
root: function root() {
return {
marginLeft: pxToRem(20),
marginRight: pxToRem(20)
};
}
};
//# sourceMappingURL=dividerContentStyles.js.map
|
TheSledgeHammer/2.11BSD
|
lib/libc/gen/frexp.c
|
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)frexp.c 5.2 (Berkeley) 3/9/86";
#endif LIBC_SCCS and not lint
/*
* the call
* x = frexp(arg,&exp);
* must return a double fp quantity x which is <1.0
* and the corresponding binary exponent "exp".
* such that
* arg = x*2^exp
* if the argument is 0.0, return 0.0 mantissa and 0 exponent.
*/
double
frexp(x,i)
double x;
int *i;
{
int neg;
int j;
j = 0;
neg = 0;
if (x < 0) {
x = -x;
neg = 1;
}
if (x >= 1.0)
while (x >= 1.0) {
j = j + 1;
x = x / 2;
}
else if (x < 0.5 && x != 0.0)
while (x < 0.5) {
j = j - 1;
x = 2 * x;
}
*i = j;
if (neg)
x = -x;
return (x);
}
|
mayarfl/octane-ci-java-sdk
|
integrations-sdk/src/test/java/com/hp/octane/integrations/services/vulnerabilities/VulnerabilitiesServicePluginServicesTest.java
|
/*
* Copyright 2017 EntIT Software LLC, a Micro Focus company, L.P.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.hp.octane.integrations.services.vulnerabilities;
import com.hp.octane.integrations.CIPluginServices;
import com.hp.octane.integrations.OctaneSDK;
import com.hp.octane.integrations.dto.DTOFactory;
import com.hp.octane.integrations.dto.general.CIPluginInfo;
import com.hp.octane.integrations.dto.general.CIServerInfo;
import com.hp.octane.integrations.dto.securityscans.SSCProjectConfiguration;
import com.hp.octane.integrations.testhelpers.OctaneSPEndpointSimulator;
import com.hp.octane.integrations.testhelpers.SSCServerSimulator;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
public class VulnerabilitiesServicePluginServicesTest extends CIPluginServices {
private static DTOFactory dtoFactory = DTOFactory.getInstance();
private Map<String, SSCProjectConfiguration> projectConfigurations = new LinkedHashMap<>();
public VulnerabilitiesServicePluginServicesTest() {
projectConfigurations.put("job-preflight-false #1", dtoFactory.newDTO(SSCProjectConfiguration.class)
.setSSCUrl(OctaneSPEndpointSimulator.getSimulatorUrl())
.setSSCBaseAuthToken("sec-token")
.setProjectName("project-a")
.setProjectVersion("version-a")
.setMaxPollingTimeoutHours(1)
);
projectConfigurations.put("job-preflight-true #1", dtoFactory.newDTO(SSCProjectConfiguration.class)
.setSSCUrl(OctaneSPEndpointSimulator.getSimulatorUrl())
.setSSCBaseAuthToken("<PASSWORD>-token")
.setProjectName("project-a")
.setProjectVersion("version-a")
.setMaxPollingTimeoutHours(1)
);
projectConfigurations.put("jobSSC1 #1", dtoFactory.newDTO(SSCProjectConfiguration.class)
.setSSCUrl(SSCServerSimulator.getSimulatorUrl())
.setSSCBaseAuthToken("<PASSWORD>-token")
.setProjectName("project-a")
.setProjectVersion("version-a")
.setMaxPollingTimeoutHours(1)
);
}
@Override
public CIServerInfo getServerInfo() {
return dtoFactory.newDTO(CIServerInfo.class)
.setUrl("http://localhost:9999")
.setType("custom")
.setVersion("1.1.1");
}
@Override
public CIPluginInfo getPluginInfo() {
return dtoFactory.newDTO(CIPluginInfo.class)
.setVersion(OctaneSDK.SDK_VERSION);
}
@Override
public File getAllowedOctaneStorage() {
return new File("temp");
}
@Override
public SSCProjectConfiguration getSSCProjectConfiguration(String jobId, String buildId) {
return projectConfigurations.get(jobId + " #" + buildId);
}
}
|
GrapeCity/FitnessExplorer
|
app/src/main/java/grapecity/fitnessexplorer/ui/views/DashboardView.java
|
package grapecity.fitnessexplorer.ui.views;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.CardView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;
import grapecity.fitnessexplorer.util.DimensionUtil;
/**
* Created by David.Bickford on 5/26/2016.
*/
public class DashboardView extends CardView
{
public LinearLayout contentLayout;
public TextView title;
public DashboardView(Context context)
{
super(context);
init(context);
}
public DashboardView(Context context, AttributeSet attrs)
{
super(context, attrs);
init(context);
}
public DashboardView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context)
{
contentLayout = new LinearLayout(context);
contentLayout.setGravity(Gravity.CENTER);
title = new TextView(context);
contentLayout.addView(title);
contentLayout.setOrientation(LinearLayout.VERTICAL);
contentLayout.setPadding(DimensionUtil.getDimensionSize(16), DimensionUtil.getDimensionSize(16), DimensionUtil.getDimensionSize(24), DimensionUtil.getDimensionSize(16));
title.setGravity(Gravity.CENTER);
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
title.setTypeface(null, Typeface.BOLD);
this.addView(contentLayout);
}
}
|
padreati/rapaio
|
src/rapaio/core/distributions/Binomial.java
|
/*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* Copyright 2013 - 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package rapaio.core.distributions;
import static rapaio.math.MathTools.*;
import java.io.Serial;
import rapaio.printer.Format;
/**
* Binomial distribution.
* It models the number of successes from n trials, where all trials
* are independent Bernoulli random variables with parameter p.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public final class Binomial implements Distribution {
public static Binomial of(double p, int n) {
return new Binomial(p, n);
}
@Serial
private static final long serialVersionUID = 8813621560796556828L;
private final double p;
private final int n;
private Binomial(double p, int n) {
if (!Double.isFinite(p) || p < 0 || p > 1) {
throw new IllegalArgumentException("Probability must have a finite value in range [0,1].");
}
if (n <= 0) {
throw new IllegalArgumentException("Number of samples must be a positive integer value.");
}
this.p = p;
this.n = n;
}
@Override
public boolean discrete() {
return true;
}
@Override
public String name() {
return "Binomial(p=" + Format.floatFlex(p) + ",n=" + n + ")";
}
@Override
public double pdf(double x) {
if (x < minValue() || x > maxValue()) return 0;
if (abs(rint(x) - x) < 1e-12)
return exp(logBinomial(x, n, p));
return 0.0;
}
@Override
public double cdf(double x) {
if (x >= n) {
return 1.0;
}
x = floor(x);
return betaIncReg(1 - p, n - x, x + 1);
}
@Override
public double quantile(double probability) {
/* if log_p is true, p = -Inf is a legitimate value */
if (!Double.isFinite(probability)) {
return Double.NaN;
}
// R_Q_P01_boundaries(p, 0, n);
/* !log_p */
if (probability < 0 || probability > 1)
return Double.NaN;
if (probability == 0)
return 0;
if (probability == 1)
return n;
if (p == 0. || n == 0) return 0.;
double q = 1 - p;
if (q == 0.) return n; /* covers the full range of the densities */
double mu = n * p;
double sigma = sqrt(n * p * q);
double gamma = (q - p) / sigma;
/* Note : "same" code in qpois.c, qbinom.c, qnbinom.c --
* FIXME: This is far from optimal [cancellation for p ~= 1, etc]: */
/* temporary hack --- FIXME --- */
if (probability + 1.01 * DBL_EPSILON >= 1.) return n;
/* y := approx.value (Cornish-Fisher expansion) : */
double z = Normal.std().quantile(probability);
//y = floor(mu + sigma * (z + gamma * (z*z - 1) / 6) + 0.5);
double y = rint(mu + sigma * (z + gamma * (z * z - 1) / 6));
if (y > n) /* way off */ y = n;
z = Binomial.of(p, n).cdf(y);
/* fuzz to ensure left continuity: */
probability *= 1 - 64 * DBL_EPSILON;
double[] zp = new double[]{z};
if (n < 1e5) return doSearch(y, zp, probability, 1);
/* Otherwise be a bit cleverer in the search */
double incr = floor(n * 0.001), oldincr;
do {
oldincr = incr;
y = doSearch(y, zp, probability, incr);
incr = max(1, floor(incr / 100));
} while (oldincr > 1 && incr > n * 1e-20);
return y;
}
private double doSearch(double y, double[] z, double probability, double incr) {
if (z[0] >= probability) {
/* search to the left */
while (true) {
double newz = cdf(y - incr);
if (y == 0 || newz < probability)
return y;
y = max(0, y - incr);
z[0] = newz;
}
} else { /* search to the right */
while (true) {
y = min(y + incr, n);
if (y == n || (z[0] = cdf(y)) >= probability)
return y;
}
}
}
@Override
public double minValue() {
return 0;
}
@Override
public double maxValue() {
return n;
}
@Override
public double mean() {
return n * p;
}
@Override
public double mode() {
double low = floor((n + 1) * p);
double p1 = pdf(low - 1);
double p2 = pdf(low);
return (p1 > p2) ? low - 1 : low;
}
@Override
public double var() {
return n * p * (1 - p);
}
@Override
public double skewness() {
return (1 - 2 * p) / Math.sqrt(n * p * (1 - p));
}
@Override
public double kurtosis() {
return (1 - 6 * p * (1 - p)) / (n * p * (1 - p));
}
/**
* The wikipedia dedicated page (http://en.wikipedia.org/wiki/Binomial_distribution)
* states that entropy for binomial is:
* $$\frac1 2 \log_2 \big( 2\pi e\, np(1-p) \big) + O \left( \frac{1}{n} \right)$$
* <p>
* According to this page is lighter to use an approximation. The following page
* http://math.stackexchange.com/questions/244455/entropy-of-a-binomial-distribution
* documents how this entropy is approximated.
*
* @return entropy value
*/
@Override
public double entropy() {
return log(2 * PI * Math.E * n * p * (1 - p)) / (2.0 * log(2));
}
}
|
aragozin/stackviewer
|
src/main/java/com/vldocking/swing/docking/event/DockingActionDockableEvent.java
|
/*
VLDocking Framework 3.0
Copyright <NAME>, 2004-2013
www.vldocking.com
<EMAIL>
------------------------------------------------------------------------
This software is distributed under the LGPL license
The fact that you are presently reading this and using this class means that you have had
knowledge of the LGPL license and that you accept its terms.
You can read the complete license here :
http://www.gnu.org/licenses/lgpl.html
*/
package com.vldocking.swing.docking.event;
import com.vldocking.swing.docking.Dockable;
import com.vldocking.swing.docking.DockableState;
import com.vldocking.swing.docking.DockingDesktop;
/** A DockingActionEvent involving a single dockable as source of the action.
*
*
* @author <NAME>, VLSolutions
* @since 2.1
*/
public abstract class DockingActionDockableEvent extends DockingActionEvent {
private Dockable dockable;
public DockingActionDockableEvent(DockingDesktop desktop, Dockable dockable, DockableState.Location initialLocation, DockableState.Location nextLocation, int actionType) {
super(desktop, initialLocation, nextLocation, actionType);
this.dockable = dockable;
}
public Dockable getDockable() {
return dockable;
}
public void setDockable(Dockable dockable) {
this.dockable = dockable;
}
}
|
zoedalley/cql_engine
|
cql-engine/src/main/java/org/opencds/cqf/cql/elm/execution/AliasRefEvaluator.java
|
<reponame>zoedalley/cql_engine
package org.opencds.cqf.cql.elm.execution;
import org.opencds.cqf.cql.execution.Context;
public class AliasRefEvaluator extends org.cqframework.cql.elm.execution.AliasRef {
@Override
protected Object internalEvaluate(Context context) {
return context.resolveAlias(this.getName());
}
}
|
kevsersrca/mattermost-server
|
vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/commands.go
|
<filename>vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/commands.go
package main
import (
"os"
"github.com/hashicorp/go-sockaddr/cmd/sockaddr/command"
"github.com/mitchellh/cli"
)
// Commands is the mapping of all the available CLI commands.
var Commands map[string]cli.CommandFactory
func init() {
ui := &cli.BasicUi{Writer: os.Stdout}
Commands = map[string]cli.CommandFactory{
"dump": func() (cli.Command, error) {
return &command.DumpCommand{
Ui: ui,
}, nil
},
"eval": func() (cli.Command, error) {
return &command.EvalCommand{
Ui: ui,
}, nil
},
"rfc": func() (cli.Command, error) {
return &command.RFCCommand{
Ui: ui,
}, nil
},
"rfc list": func() (cli.Command, error) {
return &command.RFCListCommand{
Ui: ui,
}, nil
},
"tech-support": func() (cli.Command, error) {
return &command.TechSupportCommand{
Ui: ui,
}, nil
},
"version": func() (cli.Command, error) {
return &command.VersionCommand{
HumanVersion: GetHumanVersion(),
Ui: ui,
}, nil
},
}
}
|
qiangxu1996/vmtrace
|
base/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/dsl/AnnotationProcessorOptions.java
|
<reponame>qiangxu1996/vmtrace
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.dsl;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.gradle.process.CommandLineArgumentProvider;
/** Options for configuring Java annotation processors. */
@SuppressWarnings("UnnecessaryInheritDoc")
public class AnnotationProcessorOptions
implements com.android.build.gradle.api.AnnotationProcessorOptions {
@NonNull private final List<String> classNames = Lists.newArrayList();
@NonNull private final Map<String, String> arguments = Maps.newHashMap();
@NonNull
private final List<CommandLineArgumentProvider> compilerArgumentProviders = new ArrayList<>();
@Nullable
private Boolean includeCompileClasspath = null;
/**
* Specifies the annotation processor classes to run.
*
* <p>By default, this property is empty and the plugin automatically discovers and runs
* annotation processors that you add to the annotation processor classpath. To learn more about
* adding annotation processor dependencies to your project, read <a
* href="https://d.android.com/studio/build/dependencies#annotation_processor">Add annotation
* processors</a>.
*/
@NonNull
@Override
public List<String> getClassNames() {
return classNames;
}
public void setClassNames(List<String> classNames) {
this.classNames.clear();
this.classNames.addAll(classNames);
}
public void className(String className) {
classNames.add(className);
}
public void classNames(Collection<String> className) {
classNames.addAll(className);
}
/**
* Specifies arguments that represent primitive types for annotation processors.
*
* <p>If one or more arguments represent files or directories, you must instead use {@link
* #getCompilerArgumentProviders()}.
*
* @see #getCompilerArgumentProviders()
*/
@NonNull
@Override
public Map<String, String> getArguments() {
return arguments;
}
public void setArguments(Map<String, String> arguments) {
this.arguments.clear();
this.arguments.putAll(arguments);
}
public void argument(@NonNull String key, @NonNull String value) {
arguments.put(key, value);
}
public void arguments(Map<String, String> arguments) {
this.arguments.putAll(arguments);
}
/**
* Specifies arguments for annotation processors that you want to pass to the Android plugin
* using the {@link CommandLineArgumentProvider} class.
*
* <p>The benefit of using this class is that it allows you or the annotation processor author
* to improve the correctness and performance of incremental and cached clean builds by applying
* <a
* href="https://docs.gradle.org/current/userguide/more_about_tasks.html#sec:up_to_date_checks">
* incremental build property type annotations</a>.
*
* <p>To learn more about how to use this class to annotate arguments for annotation processors
* and pass them to the Android plugin, read <a
* href="https://developer.android.com/studio/build/dependencies#processor-arguments">Pass
* arguments to annotation processors</a>.
*/
@NonNull
@Override
public List<CommandLineArgumentProvider> getCompilerArgumentProviders() {
return compilerArgumentProviders;
}
public void setCompilerArgumentProviders(
@NonNull List<CommandLineArgumentProvider> compilerArgumentProviders) {
this.compilerArgumentProviders.clear();
this.compilerArgumentProviders.addAll(compilerArgumentProviders);
}
public void compilerArgumentProvider(
@NonNull CommandLineArgumentProvider compilerArgumentProvider) {
this.compilerArgumentProviders.add(compilerArgumentProvider);
}
public void compilerArgumentProviders(
@NonNull List<CommandLineArgumentProvider> compilerArgumentProviders) {
this.compilerArgumentProviders.addAll(compilerArgumentProviders);
}
/**
* Whether to include compile classpath in the processor path.
*
* <p>By default, the Android plugin throws a build error when you add annotation processors to
* your project's compile classpath. You must instead <a
* href="https://developer.android.com/studio/build/dependencies#annotation_processor">add
* annotation processors</a> to the processor classpath using the <code>annotationProcessor
* </code> dependency configuration. This behavior exists to improve build performance by
* separating the compile classpath from the annotation processor classpath.
*
* <p>If, however, you still want to add a dependency that includes an annotation processor to
* the compile classpath, but you don't need to run the processor, you can disable the error
* check by setting this property to <code>false</code>.
*
* <p>If you experience issues after migrating your project's annotation processors to the
* processor classpath, you can allow annotation processors on the compile classpath by setting
* this property to <code>true</code>. However, setting this property to <code>true</code> is
* not recommended, and the option to do so will be removed in a future update.
*
* <p>By default, this property is <code>null</code>.
*/
@Override
@Nullable
public Boolean getIncludeCompileClasspath() {
return includeCompileClasspath;
}
public void setIncludeCompileClasspath(@Nullable Boolean includeCompileClasspath) {
this.includeCompileClasspath = includeCompileClasspath;
}
public void _initWith(com.android.build.gradle.api.AnnotationProcessorOptions aptOptions) {
setClassNames(aptOptions.getClassNames());
setArguments(aptOptions.getArguments());
setCompilerArgumentProviders(aptOptions.getCompilerArgumentProviders());
setIncludeCompileClasspath(aptOptions.getIncludeCompileClasspath());
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("classNames", classNames)
.add("arguments", arguments)
.add("compilerArgumentProviders", compilerArgumentProviders)
.add("includeCompileClasspath", includeCompileClasspath)
.toString();
}
}
|
fjt7tdmi/rafi-1st
|
src/bin/rafi-emu/System.cpp
|
<reponame>fjt7tdmi/rafi-1st<filename>src/bin/rafi-emu/System.cpp
/*
* Copyright 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <rafi/emu.h>
#include "System.h"
namespace rafi { namespace emu {
System::System(XLEN xlen, vaddr_t pc, size_t ramSize)
: m_EventList()
, m_Bus()
, m_Ram(ramSize)
, m_Clint()
, m_Plic()
, m_Uart()
, m_Timer()
, m_ExternalInterruptSource(&m_Plic)
, m_TimerInterruptSource(&m_Clint)
, m_Processor(xlen, &m_Bus, &m_EventList, pc)
{
m_Bus.RegisterMemory(&m_Ram, AddrRam, m_Ram.GetCapacity());
m_Bus.RegisterMemory(&m_Rom, AddrRom, m_Rom.GetCapacity());
// E31 compatible IOs
m_Bus.RegisterIo(&m_Clint, AddrClint, m_Clint.GetSize());
m_Bus.RegisterIo(&m_Plic, AddrPlic, m_Plic.GetSize());
m_Bus.RegisterIo(&m_Uart16550, AddrUart16550, m_Uart16550.GetSize());
m_Bus.RegisterIo(&m_VirtIo1, AddrVirtIo1, m_VirtIo1.GetSize());
m_Bus.RegisterIo(&m_VirtIo2, AddrVirtIo2, m_VirtIo2.GetSize());
m_Bus.RegisterIo(&m_VirtIo3, AddrVirtIo3, m_VirtIo3.GetSize());
m_Bus.RegisterIo(&m_VirtIo4, AddrVirtIo4, m_VirtIo4.GetSize());
m_Bus.RegisterIo(&m_VirtIo5, AddrVirtIo5, m_VirtIo5.GetSize());
m_Bus.RegisterIo(&m_VirtIo6, AddrVirtIo6, m_VirtIo6.GetSize());
m_Bus.RegisterIo(&m_VirtIo7, AddrVirtIo7, m_VirtIo7.GetSize());
m_Bus.RegisterIo(&m_VirtIo8, AddrVirtIo8, m_VirtIo8.GetSize());
// IOs for zephyr
m_Bus.RegisterIo(&m_Uart, AddrUart, m_Uart.GetSize());
m_Bus.RegisterIo(&m_Timer, AddrTimer, m_Timer.GetSize());
m_Processor.RegisterExternalInterruptSource(&m_ExternalInterruptSource);
m_Processor.RegisterTimerInterruptSource(&m_TimerInterruptSource);
m_Clint.RegisterProcessor(&m_Processor);
}
System::~System()
{
}
void System::LoadFileToMemory(const char* path, paddr_t address)
{
m_Bus.LoadFileToMemory(path, address);
}
void System::SetDtbAddress(vaddr_t address)
{
// 11 (a1) holds dtb address
m_Processor.SetIntReg(11, address);
}
void System::SetHostIoAddress(vaddr_t address)
{
m_HostIoAddress = address;
}
void System::ProcessCycle()
{
m_EventList.clear();
m_Clint.ProcessCycle();
m_Uart16550.ProcessCycle();
m_Uart.ProcessCycle();
m_Timer.ProcessCycle();
m_Processor.ProcessCycle();
}
bool System::IsValidMemory(paddr_t addr, size_t size) const
{
return m_Bus.IsValidAddress(addr, size);
}
void System::ReadMemory(void* pOutBuffer, size_t bufferSize, paddr_t addr)
{
return m_Bus.Read(pOutBuffer, bufferSize, addr);
}
void System::WriteMemory(const void* pBuffer, size_t bufferSize, paddr_t addr)
{
return m_Bus.Write(pBuffer, bufferSize, addr);
}
uint32_t System::GetHostIoValue() const
{
uint32_t value;
m_Ram.Read(&value, sizeof(value), m_HostIoAddress - AddrRam);
return value;
}
vaddr_t System::GetPc() const
{
return m_Processor.GetPc();
}
void System::CopyIntReg(trace::NodeIntReg32* pOut) const
{
m_Processor.CopyIntReg(pOut);
}
void System::CopyIntReg(trace::NodeIntReg64* pOut) const
{
m_Processor.CopyIntReg(pOut);
}
void System::CopyFpReg(trace::NodeFpReg* pOut) const
{
m_Processor.CopyFpReg(pOut);
}
const trace::EventList& System::GetEventList() const
{
return m_EventList;
}
void System::PrintStatus() const
{
return m_Processor.PrintStatus();
}
}}
|
abrams27/mimuw
|
sem3/jnp1/playlist/Player.h
|
<reponame>abrams27/mimuw
#ifndef JNPI_PLAYLIST_PLAYER_H
#define JNPI_PLAYLIST_PLAYER_H
#include "Playable.h"
#include "File.h"
#include "Playlist.h"
#include "PlayableFromFileBuilder.h"
#include "PlayerExceptions.h"
#include "SequenceMode.h"
#include <string>
class Player {
private:
inline static const std::string audio_type{"audio"};
inline static const std::string video_type{"video"};
public:
std::shared_ptr<Playable> openFile(const File &file);
std::shared_ptr<Playlist> createPlaylist(const std::string &name);
};
#endif //JNPI_PLAYLIST_PLAYER_H
|
relax-space/python-learning
|
utils/t37.py
|
<reponame>relax-space/python-learning<gh_stars>0
import os
import re
folder_path = r'D:\1.source\pythonpath\xmly-paid\data\12296837'
fileList = os.listdir(folder_path)
for file_name in fileList:
file_name = os.path.join(folder_path, file_name)
if '第一卷' in file_name:
last_index = file_name.rindex('\\')
f_content = file_name[:last_index+1]
l_content = file_name[last_index+1:]
s = re.search(r'\d{3}', l_content)
index = int(s.group())
new_name = f'{f_content}{index} {l_content}'
print(new_name)
os.rename(file_name, new_name)
elif '第二卷' in file_name:
last_index = file_name.rindex('\\')
f_content = file_name[:last_index+1]
l_content = file_name[last_index+1:]
s = re.search(r'\d{3}', l_content)
index = int(s.group()) + 502
new_name = f'{f_content}{index} {l_content}'
print(new_name)
os.rename(file_name, new_name)
|
antonk52/bundlers-comparison
|
app/src/reducers/request/spec.js
|
import * as actionTypes from '../../constants/actionTypes';
import request from './index';
describe('request reducer', () => {
describe('SET_REQUEST_IN_PROCESS', () => {
it('add a request as in process', () => {
const REQUEST_TYPE = 'FOO_REQUEST';
const action = {
type: actionTypes.SET_REQUEST_IN_PROCESS,
inProcess: true,
requestType: REQUEST_TYPE
}
const expectedState = {
[REQUEST_TYPE]: true
};
expect(request(undefined, action)).to.eql(expectedState);
});
it('add a request as not in process', () => {
const REQUEST_TYPE = 'FOO_REQUEST';
const action = {
type: actionTypes.SET_REQUEST_IN_PROCESS,
inProcess: false,
requestType: REQUEST_TYPE
}
const expectedState = {
[REQUEST_TYPE]: false
};
expect(request(undefined, action)).to.eql(expectedState);
});
});
});
|
masasakano/music_i18n
|
test/controllers/users/edit_roles_controller_test.rb
|
# coding: utf-8
require "test_helper"
class Users::EditRolesControllerTest < ActionDispatch::IntegrationTest
# add this
include Devise::Test::IntegrationHelpers
setup do
@moderator = roles(:general_ja_editor).users.first # Editor can manage.
@role_admin = roles(:admin)
end
teardown do
Rails.cache.clear
end
# add to here
# ---------------------------------------------
test "should fail to patch update" do
patch users_edit_role_url(User.first)
assert_not (200...299).include?(response.code.to_i) # maybe :redirect or 403 forbidden
assert_redirected_to new_user_session_path # Devise sing_in route
sign_in users(:user_editor_general_ja) # Editor cannot manage anyone else.
patch users_edit_role_url(users(:user_editor_general_ja2))
assert_response :redirect
# assert_redirected_to root_url # Root URL?? (because alraedy signed in)
end
test "editor should manage update self" do
rolec_g = role_categories(:rc_general_ja)
role = roles( :general_ja_editor )
role_m = roles( :general_ja_moderator )
user = users(:user_editor_general_ja)
assert_equal 1, user.roles.count # fixture sanity check
assert_equal role, user.roles.first #
assert user.qualified_as?(role) #
sign_in user # Editor can manage themselves
patch users_edit_role_url(user)
assert_response :redirect
assert_redirected_to user_path(user)
# Fails
assert_difference('UserRoleAssoc.count', 0){
patch users_edit_role_url(user, params: {"role_ROOT"=>@role_admin.id.to_s,})
assert_redirected_to user_path(user)
}
# Fails in promoting
key_g = "role_"+rolec_g.mname
assert_difference('UserRoleAssoc.count', 0){
patch users_edit_role_url(user, params: {key_g => role_m.id.to_s,})
user.reload
assert_equal role, user.roles.first
}
# Succeeds in cancelling
key_g = "role_"+rolec_g.mname
assert_difference('UserRoleAssoc.count', -1){
patch users_edit_role_url(user, params: {key_g => "-1",})
user.reload
assert_equal 0, user.roles.size
}
end
test "moderator should manage update others" do
rolec_g = role_categories(:rc_general_ja)
rolec_h = role_categories(:rolecattwo)
role_m = roles( :general_ja_moderator )
role_e = roles( :general_ja_editor )
user = users(:user_editor_general_ja)
user_self = users(:user_moderator_general_ja)
assert_equal 1, user.roles.count # fixture sanity check
assert_equal role_e, user.roles.first # fixture sanity check
key_g = "role_"+rolec_g.mname
key_h = "role_"+rolec_h.mname
sign_in user_self
assert user_self.moderator?
# Succeed (cancel the Role)
assert_difference('UserRoleAssoc.count', -1){
patch users_edit_role_url(user, params: {key_g => "-1",})
assert_equal 0, user.roles.count
user.reload
assert_redirected_to user_path(user)
}
# Fails (sysadmin)
sysadmin = users(:user_sysadmin)
assert_difference('UserRoleAssoc.count', 0){
patch users_edit_role_url(sysadmin, params: {key_g => "-1",})
user.reload
assert_response :redirect
assert_redirected_to user_path(sysadmin)
}
# Fails (promote to a Role that he is not qualified as)
assert_difference('UserRoleAssoc.count', 0){
patch users_edit_role_url(user, params: {key_h => roles(:translator).id.to_s,})
user.reload
assert_equal 0, user.roles.count
}
# Fails (promote to a Role that he is not qualified as: key is fabricated)
assert_difference('UserRoleAssoc.count', 0){
patch users_edit_role_url(user, params: {key_g => roles(:translator).id.to_s,})
user.reload
assert_equal 0, user.roles.count
}
# Succeed (promote to his subordinate)
assert_difference('UserRoleAssoc.count', 1){
patch users_edit_role_url(user, params: {key_g => role_e.id.to_s,})
user.reload
assert_equal role_e, user.roles.first
}
# Succeed (no change)
assert_difference('UserRoleAssoc.count', 0){
patch users_edit_role_url(user, params: {key_g => role_e.id.to_s,})
user.reload
assert_equal role_e, user.roles.first
}
# Succeed (promote to the same as self)
assert_difference('UserRoleAssoc.count', 0){
patch users_edit_role_url(user, params: {key_g => role_m.id.to_s,})
user.reload
assert_equal role_m, user.roles.first # changed.
}
# Fails (demote someone at the same rank)
assert_difference('UserRoleAssoc.count', 0){
patch users_edit_role_url(user, params: {key_g => role_e.id.to_s,})
user.reload
assert_equal role_m, user.roles.first
}
# Fails (demote someone at the same rank)
assert_difference('UserRoleAssoc.count', 0){
patch users_edit_role_url(user, params: {key_g => "-1",})
user.reload
assert_equal role_m, user.roles.first
}
end
end
|
TopDogger1/corrosion
|
net/minecraft/block/BlockStoneSlabNew$EnumType.java
|
<gh_stars>0
public class BlockStoneSlabNew$EnumType {
// Failed to decompile, took too long to decompile: net/minecraft/block/BlockStoneSlabNew$EnumType
}
|
wycivil08/blendocv
|
intern/audaspace/intern/AUD_ResampleReader.h
|
<gh_stars>10-100
/*
* $Id: AUD_ResampleReader.h 39792 2011-08-30 09:15:55Z nexyon $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* Copyright 2009-2011 <NAME>
*
* This file is part of AudaSpace.
*
* Audaspace 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.
*
* AudaSpace is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Audaspace; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file audaspace/intern/AUD_ResampleReader.h
* \ingroup audaspaceintern
*/
#ifndef AUD_RESAMPLEREADER
#define AUD_RESAMPLEREADER
#include "AUD_EffectReader.h"
/**
* This is the base class for all resampling readers.
*/
class AUD_ResampleReader : public AUD_EffectReader
{
protected:
/**
* The target sampling rate.
*/
AUD_SampleRate m_rate;
/**
* Creates a resampling reader.
* \param reader The reader to mix.
* \param rate The target sampling rate.
*/
AUD_ResampleReader(AUD_Reference<AUD_IReader> reader, AUD_SampleRate rate);
public:
/**
* Sets the sample rate.
* \param rate The target sampling rate.
*/
virtual void setRate(AUD_SampleRate rate);
/**
* Retrieves the sample rate.
* \return The target sampling rate.
*/
virtual AUD_SampleRate getRate();
};
#endif // AUD_RESAMPLEREADER
|
VirtueDev/synced_repo
|
src/java/com/threerings/msoy/money/data/all/MemberMoney.java
|
<reponame>VirtueDev/synced_repo<gh_stars>10-100
//
// $Id$
package com.threerings.msoy.money.data.all;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* The amount of money a member has in their coins, bars, and bling accounts.
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*/
public class MemberMoney implements IsSerializable
{
public int memberId;
public int coins;
public int bars;
public int bling;
public long accCoins;
public long accBars;
public long accBling;
/** Suitable for unserialization. */
public MemberMoney ()
{
}
public MemberMoney (int memberId)
{
this.memberId = memberId;
}
public MemberMoney (
int memberId, int coins, int bars, int bling,
long accCoins, long accBars, long accBling)
{
this.memberId = memberId;
this.coins = coins;
this.bars = bars;
this.bling = bling;
this.accCoins = accCoins;
this.accBars = accBars;
this.accBling = accBling;
}
/**
* Get the current balance for the specified currency.
* @return one of {@link #coins}, {@link #bars}, or {@link #bling}.
*/
public int getBalance (Currency currency)
{
switch (currency) {
case COINS: default: return coins;
case BARS: return bars;
case BLING: return bling;
}
}
/**
* Get the total accumulated value that has been added to this member's balance over the years.
* @return one of {@link #accCoins}, {@link #accBars}, or {@link #accBling}.
*/
public long getAccumulated (Currency currency)
{
switch (currency) {
case COINS: default: return accCoins;
case BARS: return accBars;
case BLING: return accBling;
}
}
}
|
JoelGRod/Algorithms-py
|
src/algorithms/main/searchs/check_item_nested_list.py
|
<reponame>JoelGRod/Algorithms-py
import time
""" Search in nested list
"""
def search_item(test_list, key):
for item in test_list:
if item == key: return True # Base Case
if isinstance(item, list): # Recursive Case
if(search_item(item, key)): return True
return False
def search_item_two(test_list, key):
if test_list and isinstance(test_list, list):
return any(search_item_two(item, key) for item in test_list)
return test_list == key
nested_list = [
["1", "2", "3",
["one", "two",
["three", "four"]
]
],
["4", "5", "6"],
["7", "8", "9"],
["10", "11", "12"],
["13", "14", "15"],
["16", "17", "18",
["five", "six"]
],
"thing"
]
print("-----------------------\n", "Search In List\n", "-----------------------")
start = time.process_time()
print(search_item(nested_list, "six"))
print(f"{(time.process_time() - start)*1000:8f} ms")
start = time.process_time()
print(search_item_two(nested_list, "six"))
print(f"{(time.process_time() - start)*1000:8f} ms")
|
marnen/catarse_full
|
catarse_full.gemspec
|
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "catarse_full/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "catarse_full"
s.version = CatarseFull::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/marnen/catarse_full"
s.summary = "Gem packaging of Catarse."
s.description = "Gem packaging of Catarse, a crowdfunding application."
s.license = 'MIT'
files = `git ls-files -z`.split("\x0")
s.files = files.grep(%r{^(app|config|db|lib)/})
s.files += ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = files.grep(%r{^(spec)/})
dependencies = {}
dependencies[:runtime] = [
# We got some weird bug concerning encoding of AR objects in rails 3.2.13+
['rails', '3.2.13'],
['mail', '2.5.3'],
['sidekiq', '~> 2.13.0'],
'sinatra', # require: false # required by sidekiq web interface mounted on /sidekiq
# Turns every field on a editable one
'best_in_place',
# State machine for attributes on models
'state_machine', # require: 'state_machine/core'
# paranoid stuff
['paper_trail', '~> 2.7.2'],
# Database and data related
'pg',
'pg_search',
['postgres-copy', '~> 0.6.0'],
'schema_plus',
'schema_associations',
'chartkick',
# Payment engine using Paypal
['catarse_paypal_express', '~> 1.0.0'],
# Payment engine using Moip
['catarse_moip', '~> 1.0.9'],
#gem 'catarse_moip', path: '../catarse_moip'
# Decorators
'draper',
# Frontend stuff
['slim', '>= 1.3.9'],
'jquery-rails',
# Authentication and Authorization
'omniauth',
'omniauth-twitter',
['omniauth-facebook', '1.4.0'],
'devise',
'ezcrypto',
# See https://github.com/ryanb/cancan/tree/2.0 for help about this
# In resume: this version of cancan allow checking for authorization on specific fields on the model
['marnen-cancan', '= 2.0.0.alpha.pre.f1cebde51a87be149b4970a3287826bb63c0ac0b'],
# Email marketing
['marnen-catarse_mailchimp', '= 0.0.1.pre.2ed4f3931dfa292e5c1c62619772f04e41c68629z'],
# HTML manipulation and formatting
['formtastic', '~> 2.2.1'],
["auto_html", '= 1.4.2'],
'kaminari',
# Uploads
['carrierwave', '~> 0.8.0'],
'rmagick',
# Other Tools
'ranked-model',
['feedzirra', '>= 0.0.24', '< 0.8'],
['marnen-validation_reflection', '= 1.0.0.60320e6beb088808fd625a8d958dbd0d2661d494.2'], # based on ncri/validation_reflection
['inherited_resources', '1.3.1'],
'has_scope',
'spectator-validates_email', # require: 'validates_email'
['video_info', '>= 1.1.1', '< 1.6'],
'enumerate_it',
'httparty',
# Translations
'http_accept_language',
'routing-filter',
# Payment
['marnen-moip', '= 1.0.2.pre.39f9dab38fc33fe9bf614deb8e90ca166ab2d6bf'],
['activemerchant', '>= 1.17.0'], # require: 'active_merchant'
['httpclient', '>= 2.2.5']
]
dependencies[:production] = [
['fog', '>= 1.3.1'],
'google-analytics-rails',
['newrelic_rpm', '3.6.5.130'],
'unicorn',
# Enabling Gzip on Heroku
# Not necessary on other hosts.
# ['heroku-deflater', '>= 0.4.1'],
# Using dalli and memcachier have not presented significative performance gains
# Probably this is due to our pattern of cache usage
# + the lack of concurrent procs in our deploy
# 'memcachier',
# 'dalli'
]
dependencies[:doubtful] = [
# FIXME: Not-anymore-on-development
# Gems that are with 1 or more years on the vacuum
'weekdays',
"rack-timeout",
# TODO: Take a look on dependencies. Why not auto_html?
['rails_autolink', '~> 1.0.7'],
# TODO: Take a look on dependencies
"RedCloth"
]
dependencies[:assets] = [
'coffee-rails',
'compass-960-plugin',
"compass-rails",
['sass', '~> 3.2.18'], # see http://stackoverflow.com/a/21118300
'sass-rails',
'uglifier'
]
dependencies[:development] = [
'byebug',
'capybara',
'factory_girl_rails',
'guard-rspec',
'rspec-rails',
['slim-rails', '~> 1.1.1']
]
dependencies.values_at(:runtime, :production, :doubtful, :assets).flatten(1).each {|gem| s.add_dependency *gem }
dependencies[:development].each {|gem| s.add_development_dependency *gem }
end
|
marufsiddiqui/dev-lg
|
views/topbar.js
|
<filename>views/topbar.js
var app = app || {};
$(function ($) {
'use strict';
app.Views.Contributor.Topbar = Backbone.View.extend({
className : "",
initialize : function () {
},
render : function () {
var me = this;
//create short bio
me.createShortBio();
//create nav
me.createNav();
return this;
},
createNav : function () {
var me = this;
me.nav = new app.Views.Contributor.Nav({
model : app.User
});
me.$el.append(me.nav.render().el);
},
createShortBio : function () {
var me = this;
me.shortBio = new app.Views.Contributor.ShortBio({
model : app.User
});
me.$el.append(me.shortBio.render().el);
},
setActiveClass : function (task) {
var me = this, classMap;
classMap = {
'feed' : 0,
'profile' : 1,
'contributions' : 2,
'moderation' : 3
};
me.nav.$el.find('li').removeClass('active');
me.nav.$el.find('li').eq(classMap[task]).addClass('active');
}
});
});
|
cheminfo-js/mf-parser
|
packages/peptide/src/__tests__/peptide.test.js
|
'use strict';
let {
generatePeptideFragments,
calculateIEP,
calculateIEPChart,
getColorForIEP,
calculateCharge,
} = require('..');
describe('generatePeptideFragments', () => {
it('Natural peptide, default options', () => {
let result = generatePeptideFragments('HAlaGlySerOH');
expect(result).toHaveLength(4);
expect(result).toHaveProperty('0', 'HAla(+1)$b1');
});
it('Non natural peptide fragments default options', () => {
let result = generatePeptideFragments('HAla(H-1Ph)Gly(Ts)SerOH');
expect(result).toHaveLength(4);
expect(result).toHaveProperty('0', 'HAla(H-1Ph)(+1)$b1');
});
it('All fragments', () => {
let result = generatePeptideFragments('HAlaGlySerOH', {
a: true,
b: true,
c: true,
x: true,
y: true,
z: true,
});
expect(result).toHaveLength(12);
});
});
describe('isoelectric point', () => {
it('One point', () => {
let result = calculateIEP('HAlaGlySerLysLysHisOH');
expect(result).toBe(10.744);
});
it('calculateIEPChart', () => {
let result = calculateIEPChart('HAlaGlySerLysLysHisOH');
expect(result.y).toHaveLength(1401);
expect(result.yAbs).toHaveLength(1401);
});
it('getColorForIEP', () => {
let result = getColorForIEP(4);
expect(result).toBe('rgb(105,105,255)');
});
it('calculateCharge', () => {
let result = calculateCharge('HAlaGlySerLysLysHisOH', 2.0);
expect(result).toBe(3.334);
});
});
|
uk-gov-mirror/alphagov.content-data-api
|
spec/domain/etl/edition/content/travel_advice_index_spec.rb
|
<filename>spec/domain/etl/edition/content/travel_advice_index_spec.rb<gh_stars>1-10
RSpec.describe Etl::Edition::Content::Parser do
subject { described_class }
it "returns nil if json does not have children array" do
json = { schema_name: "travel_advice_index",
links: {} }
expect(subject.extract_content(json.deep_stringify_keys)).to eq(nil)
end
it "returns content json" do
json = { schema_name: "travel_advice_index",
links: { children: [
{ country: { name: "Portugal" } },
{ country: { name: "Brazil" } },
] } }
expect(subject.extract_content(json.deep_stringify_keys)).to eq("Portugal Brazil")
end
end
|
mndzielski/pomocua-ogloszenia
|
src/main/java/pl/gov/coi/pomocua/ads/health/HealthOfferDefinitionDTO.java
|
package pl.gov.coi.pomocua.ads.health;
import pl.gov.coi.pomocua.ads.BaseOfferDefinitionDTO;
import pl.gov.coi.pomocua.ads.Language;
import pl.gov.coi.pomocua.ads.Location;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import pl.gov.coi.pomocua.ads.health.HealthOffer.HealthCareMode;
public class HealthOfferDefinitionDTO extends BaseOfferDefinitionDTO<HealthOffer> {
@NotEmpty
public List<HealthCareMode> mode;
@NotNull
public HealthCareSpecialization specialization;
@Valid
public Location location;
@NotEmpty
public List<Language> language;
@Override
protected void applyOfferSpecific(HealthOffer offer) {
offer.setMode(mode);
offer.specialization = specialization;
offer.location = location;
offer.setLanguage(language);
}
}
|
dram/metasfresh
|
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/eevolution/model/X_M_Warehouse_Routing.java
|
<filename>backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/eevolution/model/X_M_Warehouse_Routing.java
/** Generated Model - DO NOT CHANGE */
package org.eevolution.model;
import java.sql.ResultSet;
import java.util.Properties;
/** Generated Model for M_Warehouse_Routing
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public class X_M_Warehouse_Routing extends org.compiere.model.PO implements I_M_Warehouse_Routing, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 856567358L;
/** Standard Constructor */
public X_M_Warehouse_Routing (Properties ctx, int M_Warehouse_Routing_ID, String trxName)
{
super (ctx, M_Warehouse_Routing_ID, trxName);
/** if (M_Warehouse_Routing_ID == 0)
{
setDocBaseType (null);
setM_Warehouse_ID (0);
setM_Warehouse_Routing_ID (0);
} */
}
/** Load Constructor */
public X_M_Warehouse_Routing (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/**
* DocBaseType AD_Reference_ID=183
* Reference name: C_DocType DocBaseType
*/
public static final int DOCBASETYPE_AD_Reference_ID=183;
/** GLJournal = GLJ */
public static final String DOCBASETYPE_GLJournal = "GLJ";
/** GLDocument = GLD */
public static final String DOCBASETYPE_GLDocument = "GLD";
/** APInvoice = API */
public static final String DOCBASETYPE_APInvoice = "API";
/** APPayment = APP */
public static final String DOCBASETYPE_APPayment = "APP";
/** ARInvoice = ARI */
public static final String DOCBASETYPE_ARInvoice = "ARI";
/** ARReceipt = ARR */
public static final String DOCBASETYPE_ARReceipt = "ARR";
/** SalesOrder = SOO */
public static final String DOCBASETYPE_SalesOrder = "SOO";
/** ARProFormaInvoice = ARF */
public static final String DOCBASETYPE_ARProFormaInvoice = "ARF";
/** MaterialDelivery = MMS */
public static final String DOCBASETYPE_MaterialDelivery = "MMS";
/** MaterialReceipt = MMR */
public static final String DOCBASETYPE_MaterialReceipt = "MMR";
/** MaterialMovement = MMM */
public static final String DOCBASETYPE_MaterialMovement = "MMM";
/** PurchaseOrder = POO */
public static final String DOCBASETYPE_PurchaseOrder = "POO";
/** PurchaseRequisition = POR */
public static final String DOCBASETYPE_PurchaseRequisition = "POR";
/** MaterialPhysicalInventory = MMI */
public static final String DOCBASETYPE_MaterialPhysicalInventory = "MMI";
/** APCreditMemo = APC */
public static final String DOCBASETYPE_APCreditMemo = "APC";
/** ARCreditMemo = ARC */
public static final String DOCBASETYPE_ARCreditMemo = "ARC";
/** BankStatement = CMB */
public static final String DOCBASETYPE_BankStatement = "CMB";
/** CashJournal = CMC */
public static final String DOCBASETYPE_CashJournal = "CMC";
/** PaymentAllocation = CMA */
public static final String DOCBASETYPE_PaymentAllocation = "CMA";
/** MaterialProduction = MMP */
public static final String DOCBASETYPE_MaterialProduction = "MMP";
/** MatchInvoice = MXI */
public static final String DOCBASETYPE_MatchInvoice = "MXI";
/** MatchPO = MXP */
public static final String DOCBASETYPE_MatchPO = "MXP";
/** ProjectIssue = PJI */
public static final String DOCBASETYPE_ProjectIssue = "PJI";
/** MaintenanceOrder = MOF */
public static final String DOCBASETYPE_MaintenanceOrder = "MOF";
/** ManufacturingOrder = MOP */
public static final String DOCBASETYPE_ManufacturingOrder = "MOP";
/** QualityOrder = MQO */
public static final String DOCBASETYPE_QualityOrder = "MQO";
/** Payroll = HRP */
public static final String DOCBASETYPE_Payroll = "HRP";
/** DistributionOrder = DOO */
public static final String DOCBASETYPE_DistributionOrder = "DOO";
/** ManufacturingCostCollector = MCC */
public static final String DOCBASETYPE_ManufacturingCostCollector = "MCC";
/** Gehaltsrechnung (Angestellter) = AEI */
public static final String DOCBASETYPE_GehaltsrechnungAngestellter = "AEI";
/** Interne Rechnung (Lieferant) = AVI */
public static final String DOCBASETYPE_InterneRechnungLieferant = "AVI";
/** Speditionsauftrag/Ladeliste = MST */
public static final String DOCBASETYPE_SpeditionsauftragLadeliste = "MST";
/** CustomerContract = CON */
public static final String DOCBASETYPE_CustomerContract = "CON";
/** Set Document BaseType.
@param DocBaseType
Logical type of document
*/
@Override
public void setDocBaseType (java.lang.String DocBaseType)
{
set_Value (COLUMNNAME_DocBaseType, DocBaseType);
}
/** Get Document BaseType.
@return Logical type of document
*/
@Override
public java.lang.String getDocBaseType ()
{
return (java.lang.String)get_Value(COLUMNNAME_DocBaseType);
}
@Override
public org.compiere.model.I_M_Warehouse getM_Warehouse() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class);
}
@Override
public void setM_Warehouse(org.compiere.model.I_M_Warehouse M_Warehouse)
{
set_ValueFromPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class, M_Warehouse);
}
/** Set Lager.
@param M_Warehouse_ID
Lager oder Ort für Dienstleistung
*/
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
/** Get Lager.
@return Lager oder Ort für Dienstleistung
*/
@Override
public int getM_Warehouse_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lagerzuordnung.
@param M_Warehouse_Routing_ID Lagerzuordnung */
@Override
public void setM_Warehouse_Routing_ID (int M_Warehouse_Routing_ID)
{
if (M_Warehouse_Routing_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Routing_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Routing_ID, Integer.valueOf(M_Warehouse_Routing_ID));
}
/** Get Lagerzuordnung.
@return Lagerzuordnung */
@Override
public int getM_Warehouse_Routing_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Routing_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
lesorres/Cub3D
|
13_draw_wall_1.c
|
<reponame>lesorres/Cub3D<filename>13_draw_wall_1.c<gh_stars>0
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* 13_draw_wall_1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kmeeseek <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/21 21:54:36 by kmeeseek #+# #+# */
/* Updated: 2021/04/25 22:36:02 by kmeeseek ### ########.fr */
/* */
/* ************************************************************************** */
#include "./cub.h"
static void calculate_params(t_all *all, int x)
{
double cameraX;
cameraX = 2 * x / (double)all->flags.rx - 1;
all->plr.raydir_x = all->plr.dir_x + all->plr.plane_x * cameraX;
all->plr.raydir_y = all->plr.dir_y + all->plr.plane_y * cameraX;
all->plr.map_x = (int)all->plr.pos_x;
all->plr.map_y = (int)all->plr.pos_y;
all->plr.delta_dist_x = fabs(1 / all->plr.raydir_x);
all->plr.delta_dist_y = fabs(1 / all->plr.raydir_y);
}
static void find_step_n_sidedist(t_all *all)
{
if (all->plr.raydir_x < 0)
{
all->plr.step_x = -1;
all->plr.sidedist_x = (all->plr.pos_x - all->plr.map_x)
* all->plr.delta_dist_x;
}
else
{
all->plr.step_x = 1;
all->plr.sidedist_x = (all->plr.map_x + 1.0 - all->plr.pos_x)
* all->plr.delta_dist_x;
}
if (all->plr.raydir_y < 0)
{
all->plr.step_y = -1;
all->plr.sidedist_y = (all->plr.pos_y - all->plr.map_y)
* all->plr.delta_dist_y;
}
else
{
all->plr.step_y = 1;
all->plr.sidedist_y = (all->plr.map_y + 1.0 - all->plr.pos_y)
* all->plr.delta_dist_y;
}
}
static int perform_dda(t_all *all)
{
int hit;
int side;
hit = 0;
while (hit == 0)
{
if (all->plr.sidedist_x < all->plr.sidedist_y)
{
all->plr.sidedist_x += all->plr.delta_dist_x;
all->plr.map_x += all->plr.step_x;
side = 0;
}
else
{
all->plr.sidedist_y += all->plr.delta_dist_y;
all->plr.map_y += all->plr.step_y;
side = 1;
}
if (all->flags.map[all->plr.map_y][all->plr.map_x] == '1')
hit = 1;
}
return (side);
}
static void calculate_dist_n_size_params(t_all *all, int side)
{
if (side == 0)
all->plr.perp_wall_dist = (all->plr.map_x - all->plr.pos_x
+ (1 - all->plr.step_x) / 2) / all->plr.raydir_x;
else
all->plr.perp_wall_dist = (all->plr.map_y - all->plr.pos_y
+ (1 - all->plr.step_y) / 2) / all->plr.raydir_y;
all->plr.line_h = (int)(all->flags.rx / all->plr.perp_wall_dist * 0.75);
all->plr.draw_str = (all->flags.ry - all->plr.line_h) / 2;
if (all->plr.draw_str < 0)
all->plr.draw_str = 0;
all->plr.draw_end = all->flags.ry / 2 + all->plr.line_h / 2;
if (all->plr.draw_end >= all->flags.ry)
all->plr.draw_end = all->flags.ry - 1;
}
void draw_wall(t_all *all)
{
int side;
t_data curr_tex;
int x;
x = 0;
while (x < all->flags.rx)
{
calculate_params(all, x);
find_step_n_sidedist(all);
side = perform_dda(all);
calculate_dist_n_size_params(all, side);
curr_tex = choose_tex(all, side, all->plr.step_x, all->plr.step_y);
calc_tex_param(all, &curr_tex, side);
draw_textures(all, &curr_tex, x);
all->plr.z_buf[x] = all->plr.perp_wall_dist;
x++;
}
draw_sprites(all);
}
|
webmasterdragon/kittenTricks
|
ios/Pods/Headers/Public/ExpoKit/EXKernelService.h
|
<filename>ios/Pods/Headers/Public/ExpoKit/EXKernelService.h
// Copyright 2015-present 650 Industries. All rights reserved.
@class EXKernelAppRecord;
@protocol EXKernelService <NSObject>
@optional
- (void)kernelDidRegisterAppWithRecord:(EXKernelAppRecord *)record;
- (void)kernelWillUnregisterAppWithRecord:(EXKernelAppRecord *)record;
@end
|
dsuarezf/ixa-pipe-ml
|
src/main/java/eus/ixa/ixa/pipe/ml/sequence/SequenceLabelSample.java
|
<reponame>dsuarezf/ixa-pipe-ml<gh_stars>1-10
/*
* 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 eus.ixa.ixa.pipe.ml.sequence;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import eus.ixa.ixa.pipe.ml.utils.Span;
import opennlp.tools.tokenize.WhitespaceTokenizer;
/**
* Class for holding sequences for a single unit of text.
*/
public class SequenceLabelSample {
private final String id;
private final List<String> tokens;
private final List<Span> sequences;
private final String[][] additionalContext;
private final boolean isClearAdaptiveData;
/** The a default type value when there is no type in training data. */
public static final String DEFAULT_TYPE = "default";
public SequenceLabelSample(final String id, final String[] tokens,
Span[] sequences, final String[][] additionalContext,
final boolean clearAdaptiveData) {
this.id = id;
if (tokens == null) {
throw new IllegalArgumentException("sentence must not be null!");
}
if (sequences == null) {
sequences = new Span[0];
}
this.tokens = Collections
.unmodifiableList(new ArrayList<String>(Arrays.asList(tokens)));
this.sequences = Collections
.unmodifiableList(new ArrayList<Span>(Arrays.asList(sequences)));
if (additionalContext != null) {
this.additionalContext = new String[additionalContext.length][];
for (int i = 0; i < additionalContext.length; i++) {
this.additionalContext[i] = new String[additionalContext[i].length];
System.arraycopy(additionalContext[i], 0, this.additionalContext[i], 0,
additionalContext[i].length);
}
} else {
this.additionalContext = null;
}
this.isClearAdaptiveData = clearAdaptiveData;
// TODO: Check that name spans are not overlapping, otherwise throw
// exception
}
/**
* Initializes the current instance.
*
* @param tokens
* training sentence
* @param sequences
* the sequences spans
* @param additionalContext
* any additional context
* @param clearAdaptiveData
* if true the adaptive data of the feature generators is cleared
*/
public SequenceLabelSample(final String[] tokens, final Span[] sequences,
final String[][] additionalContext, final boolean clearAdaptiveData) {
this(null, tokens, sequences, additionalContext, clearAdaptiveData);
}
public SequenceLabelSample(final String[] tokens, final Span[] sequences,
final boolean clearAdaptiveData) {
this(tokens, sequences, null, clearAdaptiveData);
}
public String getId() {
return this.id;
}
public String[] getTokens() {
return this.tokens.toArray(new String[this.tokens.size()]);
}
public Span[] getSequences() {
return this.sequences.toArray(new Span[this.sequences.size()]);
}
public String[][] getAdditionalContext() {
return this.additionalContext;
}
public boolean isClearAdaptiveDataSet() {
return this.isClearAdaptiveData;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof SequenceLabelSample) {
final SequenceLabelSample a = (SequenceLabelSample) obj;
return Arrays.equals(getTokens(), a.getTokens())
&& Arrays.equals(getSequences(), a.getSequences())
&& Arrays.equals(getAdditionalContext(), a.getAdditionalContext())
&& isClearAdaptiveDataSet() == a.isClearAdaptiveDataSet();
} else {
return false;
}
}
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
// If adaptive data must be cleared insert an empty line
// before the sample sentence line
if (isClearAdaptiveDataSet()) {
result.append("\n");
}
for (int tokenIndex = 0; tokenIndex < this.tokens.size(); tokenIndex++) {
// token
for (final Span sequence : this.sequences) {
if (sequence.getStart() == tokenIndex) {
// check if nameTypes is null, or if the nameType for this specific
// entity is empty. If it is, we leave the nameType blank.
if (sequence.getType() == null) {
result.append(SequenceLabelSampleDataStream.START_TAG).append(' ');
} else {
result.append(SequenceLabelSampleDataStream.START_TAG_PREFIX)
.append(sequence.getType()).append("> ");
}
}
if (sequence.getEnd() == tokenIndex) {
result.append(SequenceLabelSampleDataStream.END_TAG).append(' ');
}
}
result.append(this.tokens.get(tokenIndex)).append(' ');
}
if (this.tokens.size() > 1) {
result.setLength(result.length() - 1);
}
for (final Span name : this.sequences) {
if (name.getEnd() == this.tokens.size()) {
result.append(' ').append(SequenceLabelSampleDataStream.END_TAG);
}
}
return result.toString();
}
private static String errorTokenWithContext(final String sentence[],
final int index) {
final StringBuilder errorString = new StringBuilder();
// two token before
if (index > 1) {
errorString.append(sentence[index - 2]).append(" ");
}
if (index > 0) {
errorString.append(sentence[index - 1]).append(" ");
}
// token itself
errorString.append("###");
errorString.append(sentence[index]);
errorString.append("###").append(" ");
// two token after
if (index + 1 < sentence.length) {
errorString.append(sentence[index + 1]).append(" ");
}
if (index + 2 < sentence.length) {
errorString.append(sentence[index + 2]);
}
return errorString.toString();
}
private static final Pattern START_TAG_PATTERN = Pattern
.compile("<START(:([^:>\\s]*))?>");
public static SequenceLabelSample parse(final String taggedTokens,
final boolean isClearAdaptiveData) throws IOException {
return parse(taggedTokens, DEFAULT_TYPE, isClearAdaptiveData);
}
public static SequenceLabelSample parse(final String taggedTokens,
final String defaultType, final boolean isClearAdaptiveData)
// TODO: Should throw another exception, and then convert it into an
// IOException in the stream
throws IOException {
final String[] parts = WhitespaceTokenizer.INSTANCE.tokenize(taggedTokens);
final List<String> tokenList = new ArrayList<String>(parts.length);
final List<Span> seqList = new ArrayList<Span>();
String sequenceType = defaultType;
int startIndex = -1;
int wordIndex = 0;
// we check if at least one name has the a type. If no one has, we will
// leave the SequenceType property of NameSample null.
boolean catchingSequence = false;
for (int pi = 0; pi < parts.length; pi++) {
final Matcher startMatcher = START_TAG_PATTERN.matcher(parts[pi]);
if (startMatcher.matches()) {
if (catchingSequence) {
throw new IOException("Found unexpected annotation"
+ " while handling a name sequence: "
+ errorTokenWithContext(parts, pi));
}
catchingSequence = true;
startIndex = wordIndex;
final String sequenceTypeFromSample = startMatcher.group(2);
if (sequenceTypeFromSample != null) {
if (sequenceTypeFromSample.length() == 0) {
throw new IOException(
"Missing a name type: " + errorTokenWithContext(parts, pi));
}
sequenceType = sequenceTypeFromSample;
}
} else if (parts[pi].equals(SequenceLabelSampleDataStream.END_TAG)) {
if (catchingSequence == false) {
throw new IOException("Found unexpected annotation: "
+ errorTokenWithContext(parts, pi));
}
catchingSequence = false;
// create sequence
seqList.add(new Span(startIndex, wordIndex, sequenceType));
} else {
tokenList.add(parts[pi]);
wordIndex++;
}
}
final String[] tokens = tokenList.toArray(new String[tokenList.size()]);
final Span[] sequences = seqList.toArray(new Span[seqList.size()]);
return new SequenceLabelSample(tokens, sequences, isClearAdaptiveData);
}
}
|
kkretzschmar/PCL
|
src/modules/processes/Image/ExtractAlphaChannelsInterface.cpp
|
<filename>src/modules/processes/Image/ExtractAlphaChannelsInterface.cpp
// ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 02.01.11.0938
// ----------------------------------------------------------------------------
// Standard Image Process Module Version 01.03.00.0437
// ----------------------------------------------------------------------------
// ExtractAlphaChannelsInterface.cpp - Released 2019-01-21T12:06:41Z
// ----------------------------------------------------------------------------
// This file is part of the standard Image PixInsight module.
//
// Copyright (c) 2003-2019 <NAME> S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact <EMAIL>.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by <NAME> and its contributors (http://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 <NAME> OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) 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.
// ----------------------------------------------------------------------------
#include "ExtractAlphaChannelsInterface.h"
#include "ExtractAlphaChannelsParameters.h"
#include "ExtractAlphaChannelsProcess.h"
#include <pcl/ErrorHandler.h>
namespace pcl
{
// ----------------------------------------------------------------------------
ExtractAlphaChannelsInterface* TheExtractAlphaChannelsInterface = nullptr;
// ----------------------------------------------------------------------------
#include "ExtractAlphaChannelsIcon.xpm"
// ----------------------------------------------------------------------------
ExtractAlphaChannelsInterface::ExtractAlphaChannelsInterface() :
instance( TheExtractAlphaChannelsProcess )
{
TheExtractAlphaChannelsInterface = this;
}
// ----------------------------------------------------------------------------
ExtractAlphaChannelsInterface::~ExtractAlphaChannelsInterface()
{
if ( GUI != nullptr )
delete GUI, GUI = nullptr;
}
// ----------------------------------------------------------------------------
IsoString ExtractAlphaChannelsInterface::Id() const
{
return "ExtractAlphaChannels";
}
// ----------------------------------------------------------------------------
MetaProcess* ExtractAlphaChannelsInterface::Process() const
{
return TheExtractAlphaChannelsProcess;
}
// ----------------------------------------------------------------------------
const char** ExtractAlphaChannelsInterface::IconImageXPM() const
{
return ExtractAlphaChannelsIcon_XPM;
}
// ----------------------------------------------------------------------------
void ExtractAlphaChannelsInterface::ApplyInstance() const
{
instance.LaunchOnCurrentWindow();
}
// ----------------------------------------------------------------------------
void ExtractAlphaChannelsInterface::ResetInstance()
{
ExtractAlphaChannelsInstance defaultInstance( TheExtractAlphaChannelsProcess );
ImportProcess( defaultInstance );
}
// ----------------------------------------------------------------------------
bool ExtractAlphaChannelsInterface::Launch( const MetaProcess& P, const ProcessImplementation*, bool& dynamic, unsigned& /*flags*/ )
{
if ( GUI == nullptr )
{
GUI = new GUIData( *this );
SetWindowTitle( "ExtractAlphaChannels" );
UpdateControls();
}
dynamic = false;
return &P == TheExtractAlphaChannelsProcess;
}
// ----------------------------------------------------------------------------
ProcessImplementation* ExtractAlphaChannelsInterface::NewProcess() const
{
return new ExtractAlphaChannelsInstance( instance );
}
// ----------------------------------------------------------------------------
bool ExtractAlphaChannelsInterface::ValidateProcess( const ProcessImplementation& p, pcl::String& whyNot ) const
{
if ( dynamic_cast<const ExtractAlphaChannelsInstance*>( &p ) != nullptr )
return true;
whyNot = "Not an ExtractAlphaChannels instance.";
return false;
}
// ----------------------------------------------------------------------------
bool ExtractAlphaChannelsInterface::RequiresInstanceValidation() const
{
return true;
}
// ----------------------------------------------------------------------------
bool ExtractAlphaChannelsInterface::ImportProcess( const ProcessImplementation& p )
{
instance.Assign( p );
UpdateControls();
return true;
}
// ----------------------------------------------------------------------------
void ExtractAlphaChannelsInterface::UpdateControls()
{
GUI->AllAlphaChannels_RadioButton.SetChecked( instance.channels == EAChannels::AllAlphaChannels );
GUI->ActiveAlphaChannel_RadioButton.SetChecked( instance.channels == EAChannels::ActiveAlphaChannel );
GUI->ChannelList_RadioButton.SetChecked( instance.channels == EAChannels::ChannelList );
GUI->ChannelList_Edit.SetText( instance.channelList );
GUI->ChannelList_Edit.Enable( instance.channels == EAChannels::ChannelList );
GUI->ExtractChannels_CheckBox.SetChecked( instance.extractChannels );
GUI->DeleteChannels_CheckBox.SetChecked( instance.deleteChannels );
}
// ----------------------------------------------------------------------------
void ExtractAlphaChannelsInterface::__Channels_Click( Button& sender, bool checked )
{
if ( sender == GUI->AllAlphaChannels_RadioButton )
instance.channels = EAChannels::AllAlphaChannels;
else if ( sender == GUI->ActiveAlphaChannel_RadioButton )
instance.channels = EAChannels::ActiveAlphaChannel;
else if ( sender == GUI->ChannelList_RadioButton )
instance.channels = EAChannels::ChannelList;
UpdateControls();
}
void ExtractAlphaChannelsInterface::__ChannelList_EditCompleted( Edit& sender )
{
try
{
String s = sender.Text();
s.Trim();
SortedArray<int> list;
ExtractAlphaChannelsInstance::ParseChannelList( list, s );
s.Clear();
for ( size_type i = 0; ; )
{
s.Append( String( list[i] ) );
if ( ++i == list.Length() )
break;
s.Append( ',' );
}
instance.channelList = s;
sender.SetText( s );
}
ERROR_CLEANUP(
sender.SetText( instance.channelList );
sender.SelectAll();
sender.Focus()
)
}
void ExtractAlphaChannelsInterface::__Mode_Click( Button& sender, bool checked )
{
if ( sender == GUI->ExtractChannels_CheckBox )
instance.extractChannels = checked;
else if ( sender == GUI->DeleteChannels_CheckBox )
instance.deleteChannels = checked;
if ( !instance.extractChannels && !instance.deleteChannels )
instance.extractChannels = true;
UpdateControls();
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
ExtractAlphaChannelsInterface::GUIData::GUIData( ExtractAlphaChannelsInterface& w )
{
pcl::Font fnt = w.Font();
int editWidth = fnt.Width( String( 'M', 40 ) );
//
AllAlphaChannels_RadioButton.SetText( "All alpha channels" );
AllAlphaChannels_RadioButton.SetToolTip( "Extract/delete all existing alpha channels." );
AllAlphaChannels_RadioButton.OnClick( (Button::click_event_handler)&ExtractAlphaChannelsInterface::__Channels_Click, w );
ActiveAlphaChannel_RadioButton.SetText( "Active alpha channel" );
ActiveAlphaChannel_RadioButton.SetToolTip( "Extract/delete the active (first) alpha channel only." );
ActiveAlphaChannel_RadioButton.OnClick( (Button::click_event_handler)&ExtractAlphaChannelsInterface::__Channels_Click, w );
ChannelList_RadioButton.SetText( "Channel list" );
ChannelList_RadioButton.SetToolTip( "Specify a comma-separated list of alpha channel indexes to extract/delete." );
ChannelList_RadioButton.OnClick( (Button::click_event_handler)&ExtractAlphaChannelsInterface::__Channels_Click, w );
ChannelList_Edit.SetMinWidth( editWidth );
ChannelList_Edit.OnEditCompleted( (Edit::edit_event_handler)&ExtractAlphaChannelsInterface::__ChannelList_EditCompleted, w );
Channels_Sizer.SetMargin( 6 );
Channels_Sizer.SetSpacing( 4 );
Channels_Sizer.Add( AllAlphaChannels_RadioButton );
Channels_Sizer.Add( ActiveAlphaChannel_RadioButton );
Channels_Sizer.Add( ChannelList_RadioButton );
Channels_Sizer.Add( ChannelList_Edit );
Channels_GroupBox.SetTitle( "Channels" );
Channels_GroupBox.SetSizer( Channels_Sizer );
//
ExtractChannels_CheckBox.SetText( "Extract alpha channels" );
ExtractChannels_CheckBox.SetToolTip( "Extract alpha channels as new images." );
ExtractChannels_CheckBox.OnClick( (Button::click_event_handler)&ExtractAlphaChannelsInterface::__Mode_Click, w );
DeleteChannels_CheckBox.SetText( "Delete alpha channels" );
DeleteChannels_CheckBox.SetToolTip( "Delete specified alpha channels from the target image(s)." );
DeleteChannels_CheckBox.OnClick( (Button::click_event_handler)&ExtractAlphaChannelsInterface::__Mode_Click, w );
Mode_Sizer.SetMargin( 6 );
Mode_Sizer.SetSpacing( 4 );
Mode_Sizer.Add( ExtractChannels_CheckBox );
Mode_Sizer.Add( DeleteChannels_CheckBox );
Mode_GroupBox.SetTitle( "Mode" );
Mode_GroupBox.SetSizer( Mode_Sizer );
//
Global_Sizer.SetMargin( 8 );
Global_Sizer.SetSpacing( 6 );
Global_Sizer.Add( Channels_GroupBox );
Global_Sizer.Add( Mode_GroupBox );
w.SetSizer( Global_Sizer );
w.AdjustToContents();
w.SetFixedHeight();
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF ExtractAlphaChannelsInterface.cpp - Released 2019-01-21T12:06:41Z
|
Peppinux/dero-merchant
|
httperror/error_test.go
|
package httperror
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
var testError = &HTTPError{
Code: http.StatusForbidden,
Message: "Forbidden",
}
func doRequest(r *gin.Engine, path string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", path, nil)
r.ServeHTTP(w, req)
return w
}
func TestError(t *testing.T) {
e := NewHTTPError(testError.Code, testError.Message)
assert.Equal(t, testError, e)
assert.Equal(t, testError.Message, e.Error())
}
func TestSend(t *testing.T) {
// Setup router
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression))
r.POST("/send", func(c *gin.Context) {
Send(c, testError.Code, testError.Message)
})
w := doRequest(r, "/send")
actualBody := w.Body.Bytes()
var actualBodyJSON = make(map[string]*HTTPError)
json.Unmarshal(actualBody, &actualBodyJSON)
expectedBody := map[string]*HTTPError{
"error": testError,
}
assert.Equal(t, testError.Code, w.Code)
assert.Equal(t, expectedBody, actualBodyJSON)
r.POST("/send500", func(c *gin.Context) {
testError := errors.New("Test error")
Send500(c, testError, "Test error happened")
})
w = doRequest(r, "/send500")
actualBody = w.Body.Bytes()
actualBodyJSON = make(map[string]*HTTPError)
json.Unmarshal(actualBody, &actualBodyJSON)
expectedBody = map[string]*HTTPError{
"error": &HTTPError{
Code: http.StatusInternalServerError,
Message: "Internal Server Error",
},
}
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Equal(t, expectedBody, actualBodyJSON)
r.POST("/send500iferr/:shouldErr", func(c *gin.Context) {
shouldErr := c.Param("shouldErr")
var testError error
if shouldErr == "true" {
testError = errors.New("Test error")
}
if Send500IfErr(c, testError, "Test error happened") != nil {
return
}
c.Status(http.StatusOK)
})
w = doRequest(r, "/send500iferr/true")
actualBody = w.Body.Bytes()
actualBodyJSON = make(map[string]*HTTPError)
json.Unmarshal(actualBody, &actualBodyJSON)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Equal(t, expectedBody, actualBodyJSON)
w = doRequest(r, "/send500iferr/false")
assert.Equal(t, http.StatusOK, w.Code)
}
func TestRender(t *testing.T) {
// Setup router
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression))
r.LoadHTMLGlob("../webassets/templates/**/*")
r.POST("/render500", func(c *gin.Context) {
testError := errors.New("Test error")
Render500(c, testError, "Test error happened")
})
w := doRequest(r, "/render500")
assert.Equal(t, http.StatusInternalServerError, w.Code) // Only test for response code. Template is excluded.
r.POST("/render500iferr/:shouldErr", func(c *gin.Context) {
shouldErr := c.Param("shouldErr")
var testError error
if shouldErr == "true" {
testError = errors.New("Test error")
}
if Render500IfErr(c, testError, "Test error happened") != nil {
return
}
c.Status(http.StatusOK)
})
w = doRequest(r, "/render500iferr/true")
assert.Equal(t, http.StatusInternalServerError, w.Code) // Only test for response code. Template is excluded.
w = doRequest(r, "/render500iferr/false")
assert.Equal(t, http.StatusOK, w.Code)
}
|
jssmith/stigdb
|
base/thread_local_global_pool.h
|
/* <base/thread_local_global_pool.h>
Copyright 2010-2014 Stig LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <cassert>
#include <condition_variable>
#include <mutex>
#include <stdexcept>
#include <vector>
#include <sys/mman.h>
#include <syslog.h>
#include <base/assert_true.h>
#include <base/error_utils.h>
#include <base/likely.h>
#include <base/no_copy_semantics.h>
#include <base/spin_lock.h>
#include <inv_con/atomic_unordered_list.h>
namespace Base {
/* TODO */
template <typename TObj, typename... TArgs>
class TThreadLocalGlobalPoolManager {
NO_COPY_SEMANTICS(TThreadLocalGlobalPoolManager);
public:
/* Forward Declaration. */
class TThreadLocalPool;
/* TODO */
class TObjBase {
NO_COPY_SEMANTICS(TObjBase);
public:
protected:
/* TODO */
TObjBase()
: NextObj(nullptr) {}
private:
/* TODO */
TObjBase *NextObj;
friend class TThreadLocalPool;
friend class TThreadLocalGlobalPoolManager;
}; // TObjBase
/* TODO */
class TThreadLocalPool {
NO_COPY_SEMANTICS(TThreadLocalPool);
public:
/* TODO */
static_assert(std::is_base_of<TObjBase, TObj>::value, "TThreadLocalPool requires TObj to be derived from TObjBase");
/* TODO */
typedef InvCon::AtomicUnorderedList::TMembership<TThreadLocalPool, TThreadLocalGlobalPoolManager> TManagerMembership;
/* TODO */
TThreadLocalPool(TThreadLocalGlobalPoolManager *manager)
: FreeQueue(nullptr), AvailableQueue(nullptr), Manager(manager), ManagerMembership(this, &Base::AssertTrue(manager)->PoolCollection) {
assert(manager);
}
/* TODO */
virtual ~TThreadLocalPool() {}
/* TODO */
inline void Free(TObjBase *obj) {
assert(this);
#ifndef NDEBUG
static_cast<TObj *>(obj)->AssertCanFree();
#endif
do {
obj->NextObj = FreeQueue;
} while (!__sync_bool_compare_and_swap(&FreeQueue, obj->NextObj, obj));
}
/* TODO */
inline TObj *Alloc() {
assert(this);
TObjBase *alloc_obj = AvailableQueue;
if (alloc_obj) {
/* Our available queue had something to offer. */
AvailableQueue = alloc_obj->NextObj;
} else {
alloc_obj = TryAllocUncommon();
if (!alloc_obj) {
syslog(LOG_ERR, "Bad Alloc in TThreadLocalPool");
throw std::bad_alloc();
}
}
return static_cast<TObj *>(alloc_obj);
}
/* TODO */
inline TThreadLocalGlobalPoolManager *GetPoolManager() const {
assert(this);
return Manager;
}
private:
/* TODO */
TObjBase *TryAllocUncommon() {
TObjBase *alloc_obj = nullptr;
assert(this);
/* let's swap in our free queue and try to allocate from that. */
TObjBase *cur_tail = __sync_lock_test_and_set(&FreeQueue, nullptr);
if (cur_tail) {
/* There were element(s) on the free queue. */
assert(AvailableQueue == nullptr);
MakeStackAvailable(cur_tail);
assert(AvailableQueue != nullptr);
alloc_obj = AvailableQueue;
AvailableQueue = alloc_obj->NextObj;
} else {
/* the free queue was empty as well. Time to borrow from the global pool */
alloc_obj = Manager->TryAlloc();
if (!alloc_obj) {
/* the global pool was empty as well. Time to try to borrow from other pools...
- We want to borrow starting from our right neighbor.
- Until AtomicUnorderedList supports a "ForEachFromThis" we will use it (possibly) twice to scan right from our current member
*/
bool skip_to = true;
bool reached = false;
auto for_each_cb = [this, &cur_tail, &alloc_obj, &skip_to, &reached](const TThreadLocalPool &pool) {
if (skip_to) {
/* we skip until we reach this */
if (!reached && &pool != this) {
return true;
} else {
reached = true;
}
} else {
/* we pass through until we reach this */
if (&pool == this) {
return false;
}
}
if (&pool != this) {
cur_tail = __sync_lock_test_and_set(&pool.FreeQueue, nullptr);
if (cur_tail) {
/* There were element(s) on the other pool's free queue. */
assert(AvailableQueue == nullptr);
MakeStackAvailable(cur_tail);
assert(AvailableQueue != nullptr);
alloc_obj = AvailableQueue;
AvailableQueue = alloc_obj->NextObj;
return false;
}
}
return true;
};
Manager->PoolCollection.ForEach(for_each_cb);
if (!alloc_obj) {
/* we looked at all the neigbors to our right. Now we start from the left and keep going till we see oursleves. */
skip_to = false;
Manager->PoolCollection.ForEach(for_each_cb);
}
}
}
return alloc_obj;
}
/* TODO */
inline void MakeStackAvailable(TObjBase *cur_tail) {
assert(this);
/* fast pop */
AvailableQueue = cur_tail;
/* reverse pop (circular queue) */
#if 0
TObjBase *new_head = nullptr;
while (cur_tail) {
TObjBase *next = cur_tail->NextObj;
cur_tail->NextObj = new_head;
new_head = cur_tail;
cur_tail = next;
}
AvailableQueue = new_head;
#endif
}
/* TODO */
mutable TObjBase *FreeQueue;
/* TODO */
TObjBase *AvailableQueue;
/* TODO */
TThreadLocalGlobalPoolManager *Manager;
/* TODO */
TObj *MyAlloc;
/* TODO */
typename TManagerMembership::TImpl ManagerMembership;
}; // TThreadLocalPool
/* TODO */
TThreadLocalGlobalPoolManager(size_t num_elems, const TArgs &... args)
: NumElems(num_elems), Alloc(nullptr), PoolCollection(this) {
Alloc = reinterpret_cast<TObj *>(malloc(sizeof(TObj) * num_elems));
Base::IfLt0(mlock(Alloc, sizeof(TObj) * num_elems));
if (unlikely(!Alloc)) {
throw std::bad_alloc();
}
TObjBase *prev_base = nullptr;
for (size_t i = 0; i < num_elems; ++i) {
TObj *const obj = new (Alloc + i) TObj(args...);
TObjBase *const obj_base = static_cast<TObjBase *>(obj);
obj_base->NextObj = prev_base;
prev_base = obj_base;
}
FreeQueue = prev_base;
}
/* TODO */
~TThreadLocalGlobalPoolManager() {
assert(this);
size_t counter = 0UL;
PoolCollection.ForEach([&counter](const TThreadLocalPool &){++counter; return true;});
if (counter != 0UL) {
throw std::logic_error("TThreadLocalGlobalPoolManager should not be destroyed while owning any pools");
}
for (size_t i = 0; i < NumElems; ++i) {
TObj *const obj = Alloc + i;
obj->~TObj();
}
free(Alloc);
}
private:
/* TODO */
inline TObjBase *TryAlloc() {
assert(this);
TObjBase *obj = nullptr;
/* for now we use a spin lock. Anyone allocating from here will contend for this. The idea is that we finely distribute objects to the thread
local pools. Once they are there they can be allocated without a lock. We will hit this function often at the early life of a local pool
and then less often later. Consider it a warm-up semantic. */
Base::TSpinLock::TLock lock(FreeQueueLock);
obj = FreeQueue;
if (obj) {
FreeQueue = obj->NextObj;
}
return obj;
}
/* TODO */
typedef InvCon::AtomicUnorderedList::TCollection<TThreadLocalGlobalPoolManager, TThreadLocalPool> TPoolCollection;
/* TODO */
const size_t NumElems;
/* TODO */
TObj *Alloc;
/* TODO */
Base::TSpinLock FreeQueueLock;
TObjBase *FreeQueue;
/* TODO */
mutable typename TPoolCollection::TImpl PoolCollection;
}; // TThreadLocalGlobalPoolManager
} // Base
|
paullewallencom/spring-978-1-7871-2831-6
|
_src/Chapter13/ch10-deptservice/src/test/java/org/packt/microservice/core/test/TestReactService.java
|
<gh_stars>10-100
package org.packt.microservice.core.test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.packt.microservice.core.HRDeptBootApplication;
import org.packt.microservice.core.config.HttpServerConfig;
import org.packt.microservice.core.config.SpringAsynchConfig;
import org.packt.microservice.core.config.SpringDataConfig;
import org.packt.microservice.core.model.data.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.FluxExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes={ HRDeptBootApplication.class, HttpServerConfig.class, SpringDataConfig.class, SpringAsynchConfig.class })
public class TestReactService {
@Autowired
private WebTestClient webTestClient;
@Test
public void testDeptById(){
FluxExchangeResult<Department> result = webTestClient.get().uri("http://localhost:8090/ch10-dept/selectReactDept/359").accept(MediaType.APPLICATION_JSON_UTF8)
.exchange().returnResult(Department.class);
assertEquals( result.getStatus().value(), 200);
Department dept = result.getResponseBody().blockFirst();
System.out.println(dept.getName());
}
@Test
public void testDeptByIdRouter(){
FluxExchangeResult<Department> result = webTestClient.get().uri("http://localhost:8901/selectDeptById/359").accept(MediaType.APPLICATION_JSON_UTF8)
.exchange().returnResult(Department.class);
assertEquals( result.getStatus().value(), 200);
Department dept = result.getResponseBody().blockFirst();
System.out.println(dept.getName());
}
}
|
zhangkn/iOS14Header
|
System/Library/PrivateFrameworks/MobileTimer.framework/MTIntentRepeatDayResolutionResult.h
|
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:42:40 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/MobileTimer.framework/MobileTimer
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <Intents/INObjectResolutionResult.h>
@interface MTIntentRepeatDayResolutionResult : INObjectResolutionResult
+(id)successWithResolvedRepeatDay:(id)arg1 ;
+(id)disambiguationWithRepeatDaysToDisambiguate:(id)arg1 ;
+(id)confirmationRequiredWithRepeatDayToConfirm:(id)arg1 ;
@end
|
AzDarGee/milieucities
|
app/client/components/DevSites/Preview/locale.js
|
import LocalizedStrings from 'react-localization';
const i18n = new LocalizedStrings({
en:{
messageSent: "Message successfully sent!",
messageNotSent: "Your message was not sent, please try again.",
mustSign: "Must sign in to like a development site.",
openForComments: "Open for Comments",
committee: "Committee of Adjustment",
share: "Share",
devId: "File Number",
ward: "Ward",
status: "Application Status",
buildtype: "Building Type",
applicationFiles:"Application(s)",
description: "Description",
view: "View ",
hide: "Hide ",
file: " attached files",
urbanPlanner: "Urban Planner",
councillor: "Councillor",
name: "Name",
email: "Email",
message: "Message",
notices: 'Notices',
attachments: 'Attachments',
contact: "Contact",
emailCouncillor: "Email the Councillor",
emailUrbanPlanner: "Email the Urban Planner",
linkToPlanningPage: "View on City Web Page for More Information",
},
fr: {
messageSent: "Message envoyé avec succès!",
messageNotSent: "Votre message n'a pas été envoyé, veuillez essayer de nouveau",
mustSign: "Vous devez vous connecter pour continuer.",
openForComments: "Ouvert(e) à commentaires",
committee: "Committee of Adjustment",
share: "Partager",
buildtype: "Type de batiment",
devId: "<NAME>",
ward: "Quartier",
status: "État d’avancement",
applicationFiles:"Type d'application pour cet projet",
description: "Description",
view: "Afficher ", //TODO: Double check!
hide: "Masquer ",
file: " Pièces jointes",
urbanPlanner: "Urbaniste",
councillor: "Conseiller",
name: "Prénom",
email: "Courriel",
message: "Message",
notices: 'Notices',
attachments: 'Attachments',
contact: "Contacter",
emailCouncillor: "Contacter le(la) Conseiller(ère)",
emailUrbanPlanner: "Contacter l'Urbaniste",
linkToPlanningPage: "View on Municipal Planning Page",
}
});
export default i18n;
|
KNMI/VERCE
|
FDSN_Server/server.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import flask
from flask.ext.cache import Cache
import inspect
import obspy
import os
import config
from event_shelve import EventShelve
import station_query
EVENT_ROOT_URL = "/fdsnws/event/1/"
STATION_ROOT_URL = "/fdsnws/station/1/"
PATH = os.path.dirname(os.path.abspath(inspect.getfile(
inspect.currentframe())))
app = flask.Flask("FDSNEventService")
cache = Cache(app, config={"CACHE_TYPE": "simple"})
print("Initializing event shelve...")
# Init the event shelve.
event_shelve = EventShelve(
shelve_path=config.SHELVE_DB_PATH,
root_folder=config.QUAKEML_ROOT_DIR,
quakeml_glob_expr=config.QUAKEML_FILES_GLOB,
regex_expr=config.REGEX_FOR_EVENT_ID)
print("Done initializing event shelve...")
@app.route(EVENT_ROOT_URL + "version")
def version():
"""
Return the version string of the webservice.
"""
return "0.0.1"
@app.route(EVENT_ROOT_URL + "application.wadl")
@cache.cached()
def wadl():
"""
Return the WADL file.
"""
with open(os.path.join(PATH, "application.wadl"), "rb") as fh:
wadl_string = fh.read()
return wadl_string
@app.route(EVENT_ROOT_URL + "query")
def query():
"""
The actual query route.
"""
arguments = {key: value for key, value in flask.request.args.items()}
# Map short to long arguments.
mappings = {
"start": "starttime",
"end": "endtime",
"minlat": "minlatitude",
"maxlat": "maxlatitude",
"minlon": "minlongitude",
"maxlon": "maxlongitude",
"lat": "latitude",
"lon": "longitude",
"minmag": "minmagnitude",
"maxmag": "maxmagnitude",
}
for key, value in mappings.items():
if key in arguments:
arguments[value] = arguments[key]
# Convert times.
if "starttime" in arguments:
arguments["starttime"] = obspy.UTCDateTime(arguments["starttime"])
if "endtime" in arguments:
arguments["endtime"] = obspy.UTCDateTime(arguments["endtime"])
arguments["query_id"] = flask.request.base_url
try:
cat = event_shelve.query(**arguments)
except Exception as e:
return str(e), 500, {}
if cat is None:
return ("Request was properly formatted and submitted but no data "
"matches the selection", 204, {})
return cat
@app.route(STATION_ROOT_URL + "query")
def stations_query():
arguments = {key: value for key, value in flask.request.args.items()}
#query?level=station&starttime=2013-01-01T00:00:00&endtime=2013-08-02T00:00:00&network=*&maxlat=0&minlon=-25&maxlon=70&minlat=-90
try:
cat = station_query.query(**arguments)
except Exception as e:
return str(e), 500, {}
if cat is None:
return ("Request was properly formatted and submitted but no data "
"matches the selection", 204, {})
return cat
if __name__ == "__main__":
if config.PUBLIC is True:
app.run(host="0.0.0.0", port=config.PORT)
else:
app.run(port=config.PORT)
|
onezens/sdks
|
iPhoneOS11.2.sdk/System/Library/Frameworks/GameplayKit.framework/Headers/GKMonteCarloStrategist.h
|
//
// GKMonteCarloStrategist.h
// GameplayKit
//
// Copyright © 2015 Apple. All rights reserved.
//
#import <GameplayKit/GKStrategist.h>
NS_ASSUME_NONNULL_BEGIN
/**
* The Monte Carlo Strategist is a generic AI that selects a game model update for a given player that results
* in the highest likelihood for that player to eventually win the game. It does this by sampling the updates available
* to the player in question. In doing this it will select the update it knows to produce the best result so far, expanding on this
* selection, simulating the rest of the game from that expansion, and then propogating the results (win or loss) upwards.
* It will do this until the budget has been reached, then returning the choice it has deemed best suited for the player in question.
*/
GK_BASE_AVAILABILITY_2 @interface GKMonteCarloStrategist : NSObject <GKStrategist>
/**
* The maximum number of samples that will be processed when searching for a move.
*/
@property (nonatomic, assign) NSUInteger budget;
/**
* A weight that encourages exploration of less visited updates versus the continued exploitation of previously visited updates.
*/
@property (nonatomic, assign) NSUInteger explorationParameter;
@end
NS_ASSUME_NONNULL_END
|
Roopesh2/C.js
|
src/color/random.js
|
<reponame>Roopesh2/C.js<gh_stars>1-10
import { Colors } from "../constants/colors.js";
import { randomInt } from "../math/random.js";
let definedColorList = Object.keys(Colors);
const TR_INDEX = definedColorList.indexOf("TRANSPARENT");
definedColorList = definedColorList.slice(0, TR_INDEX).concat(definedColorList.slice(TR_INDEX + 1));
/**
* returns a random hex color
*
*/
export function randomColor() {
let color = "#";
for (let i = 0; i < 3; i++) {
let randNum = randomInt(255).toString(16);
randNum = randNum.length === 1 ? 0 + randNum : randNum;
color += randNum;
}
return color;
}
/**
* picks a random color from defined ones
*
*/
export function randomDefinedColor() {
return Colors[definedColorList[randomInt(definedColorList.length - 1)]];
}
|
brzyangg/sutil
|
slog/slog_test.go
|
<gh_stars>10-100
// Copyright 2014 The sutil Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package slog
import (
"testing"
"gitlab.pri.ibanyu.com/middleware/seaweed/xlog"
)
func TestShowLog(t *testing.T) {
t0(t)
t1(t)
}
func t0(t *testing.T) {
// 直接用xlog.Error, skip:4, slog.Error, skip:5, slog/slog.Error, skip:6
xlog.SetAppLogSkip(5)
Tracef("Tracef %s", "TT")
Debugf("Debugf %s", "TT")
Infof("Infof %s", "TT")
Warnf("Warnf %s", "TT")
Errorf("Errorf %s", "TT")
//Fatalf("Fatalf %s", "TT")
//Panicf("Panicf %s", "TT")
Traceln("Traceln tt")
Debugln("Debugln tt")
Infoln("Infoln tt")
Warnln("Warnln tt")
Errorln("Errorln tt")
//Fatalln("Fatalln tt")
//Panicln("Panic %s", "TT")
Infoln("FF")
Infoln("FF")
}
func t1(t *testing.T) {
Init("./log", "tt", "TRACE")
Init("./log", "tt", "TRACE")
Init("./log", "tt", "TRACE")
Infoln("log file")
Init("./log", "tt2", "TRACE")
Infoln("log file2")
Init("", "", "TRACE")
Infoln("std out")
}
|
w3arthur/Java-Referance
|
GuitarLessons-ManagmentGUI/src/Classes/Lesson.java
|
<filename>GuitarLessons-ManagmentGUI/src/Classes/Lesson.java<gh_stars>0
package Classes;
import java.io.Serializable;
import Exeption.Illegal_Exception_Message;
import Exeption.Patterns;
import Interface.TeachingInterface;
public class Lesson implements TeachingInterface, Serializable {
private Student student;
private Teacher teacher;
private String location;
private String date;
private String time;
public Lesson(Student student, Teacher teacher, String location, String date, String time) throws Illegal_Exception_Message {
setStudent(student);
setTeacher(teacher);
setLocation(location);
setDate(date);
setTime(time);
}
public Student getStudent() {return student;}
public Teacher getTeacher() {return teacher;}
public String getLocation() {return location;}
public String getDate() {return date;}
public String getDateYear(){return getDate().substring(6,8);}
public String getDateMouth(){return getDate().substring(3,5);}
public String getDateDay(){return getDate().substring(0,2);}
public String getTime() {return time;}
public void setStudent(Student student) {this.student = student;}
public String getStudentID() {return getStudent().getId();}
public String getStudentFirstName() {return getStudent().getFirstName();}
public String getStudentLastName() {return getStudent().getLastName();}
public void setTeacher(Teacher teacher) {this.teacher = teacher;}
public String getTeacherID() {return getTeacher().getId();}
public void setLocation(String location) {
this.location = location;
}
public void setDate(String date) throws Illegal_Exception_Message {
Patterns.lessonDate(date);
this.date = date;
}
public void setTime(String time) throws Illegal_Exception_Message {
Patterns.lessonTime(time);
this.time = time;
}
@Override
public String toString() {
return
"- student("+
((getStudent()==null)? "-" : getStudent().getId()+", "+getStudent().getFirstName()+", "+getStudent().getLastName() )+
") teacher("+
((getTeacher()==null)? "-" : getTeacher().getId()+", "+getTeacher().getFirstName()+", "+getTeacher().getLastName() )+
") lesson set("+getLocation()+", "+getDate()+", "+getTime()+") \n"
;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.