repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
skubit/skubit-comics
|
app/src/main/java/com/skubit/comics/activities/DeleteFromCollectionActivity.java
|
<reponame>skubit/skubit-comics
package com.skubit.comics.activities;
import com.skubit.comics.BuildConfig;
import com.skubit.comics.fragments.DeleteFromCollectionFragment;
import com.skubit.comics.provider.collectionmapping.CollectionMappingSelection;
import com.skubit.dialog.ProgressActivity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
public class DeleteFromCollectionActivity extends ProgressActivity<Bundle> {
public static Intent newInstance(String cid, String cbid) {
Intent i = new Intent();
i.putExtra("cid", cid);
i.putExtra("cbid", cbid);
i.setClassName(BuildConfig.APPLICATION_ID, DeleteFromCollectionActivity.class.getName());
return i;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment frag = getFragmentManager().findFragmentByTag(mUIState);
if (frag != null) {
replaceFragment(frag, mUIState);
} else {
replaceFragment(new DeleteFromCollectionFragment(),
"DeleteFromCollection");
}
}
@Override
public void load(Bundle data, int type) {
//TODO: move off main thread
Bundle d = getIntent().getExtras();
CollectionMappingSelection cs = new CollectionMappingSelection();
cs.cid(d.getString("cid"));
cs.cbid(d.getString("cbid"));
cs.delete(getContentResolver());
finish();
}
}
|
ByBrainmix/CustomItemAPI
|
api/src/main/java/me/brainmix/itemapi/api/delay/ItemDelayAmount.java
|
package me.brainmix.itemapi.api.delay;
import me.brainmix.itemapi.api.CustomItem;
import me.brainmix.itemapi.api.utils.ItemUtils;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class ItemDelayAmount extends ItemDelay implements DelayDisplay {
private CustomItem customItem;
private boolean canMove;
private boolean canDrop;
public ItemDelayAmount(int delay, CustomItem customItem) {
super(delay);
this.customItem = customItem;
this.canMove = customItem.getOptions().isMove();
this.canDrop = customItem.getOptions().isDrop();
}
@Override
public void display(Player player, int timeLeft) {
if(timeLeft == 0) {
customItem.getOptions().setMove(canMove);
customItem.getOptions().setDrop(canDrop);
ItemUtils.replaceItem(player, customItem.getOptions().getItemStack(), customItem.getOptions().getItemStack());
return;
}
customItem.getOptions().setMove(false);
customItem.getOptions().setDrop(false);
ItemStack item = customItem.getOptions().getItemStack().clone();
item.setAmount((timeLeft / 20) + 2);
ItemUtils.replaceItem(player, customItem.getOptions().getItemStack(), item);
}
}
|
peterkrenn/ruby-processing
|
samples/processing_app/3D/form/icosahedra/icosahedron.rb
|
<reponame>peterkrenn/ruby-processing
# fjenett, 2010-03-11:
# Mixing in Processing::Proxy makes classes behave like inner classes(*) of
# a Processing sketch (any class that's defined in a sketch and that is
# inside a .pde file). This is needed for a class to be able to call any
# drawing commands etc.
# (*) Ruby does not know inner classes btw. ...
require 'shape_3D' # load shape_3D.rb
class Icosahedron < Shape3D # extends Shape3D
include Processing::Proxy # mixin Processing::Proxy
attr_accessor :top_point, :top_pent
attr_accessor :bottom_point, :bottom_pent
attr_accessor :angle, :radius
attr_accessor :tri_dist, :tri_ht
attr_accessor :a, :b, :c
def initialize ( *args )
super args # call Shape3D.new( args )
@radius = args.first
@top_pent = Array.new 5
@bottom_pent = Array.new 5
@angle = 0.0
init
end
def init
@c = dist( cos(0) * @radius,
sin(0) * @radius,
cos(radians( 72 )) * @radius,
sin(radians( 72 )) * @radius )
@b = @radius
@a = sqrt(@c*@c - @b*@b)
@tri_ht = sqrt( @c*@c - (@c/2) * (@c/2) )
@top_pent.each_with_index { |v, i|
@top_pent[i] = PVector.new( cos(@angle) * @radius,
sin(@angle) * @radius,
@tri_ht / 2 )
@angle += radians 72
}
@top_point = PVector.new 0, 0, @tri_ht / 2 + @a
@angle = 72.0/2
@bottom_pent.each_with_index { |v, i|
@bottom_pent[i] = PVector.new( cos(@angle) * @radius,
sin(@angle) * @radius,
-@tri_ht / 2 )
@angle += radians 72
}
@bottom_point = PVector.new 0, 0, -(@tri_ht / 2 + @a)
end
def draw
[@top_pent, @bottom_pent].each { |pent| # top and bottom pentagram
(0...pent.length).each { |i|
begin_shape
# next or first
n = i+1
n = n % @top_pent.length # wrap around
# choose point depending on pentagram
pnt = @top_point
pnt = @bottom_point if pent == @bottom_pent
# draw triangle
vertex @x + pent[i].x, @y + pent[i].y, @z + pent[i].z
vertex @x + pnt.x, @y + pnt.y, @z + pnt.z
vertex @x + pent[n].x, @y + pent[n].y, @z + pent[n].z
end_shape CLOSE
}
}
begin_shape TRIANGLE_STRIP
0.upto(6) { |i| # stitch pentagrams together with triangles
j = i
j = j % @top_pent.length
n = i+2
n = n % @bottom_pent.length
vertex @x + @top_pent[j].x, @y + @top_pent[j].y, @z + @top_pent[j].z
vertex @x + @bottom_pent[n].x, @y + @bottom_pent[n].y, @z + @bottom_pent[n].z
}
end_shape
end
end
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
LeetCode/ThousandOne/0748-short_completing_word.cpp
|
#include "leetcode.hpp"
/* 748. 最短完整词
如果单词列表(words)中的一个单词包含牌照(licensePlate)中所有的字母,那么我们称之为完整词。在所有完整词中,最短的单词我们称之为最短完整词。
单词在匹配牌照中的字母时不区分大小写,比如牌照中的 "P" 依然可以匹配单词中的 "p" 字母。
我们保证一定存在一个最短完整词。
当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。
牌照中可能包含多个相同的字符,比如说:对于牌照 "PP",单词 "pair" 无法匹配,但是 "supper" 可以匹配。
示例 1:
输入:licensePlate = "1s3PSt", words = ["step", "steps", "stripe", "stepple"]
输出:"steps"
说明:最短完整词应该包括 "s"、"p"、"s" 以及 "t"。对于 "step" 它只包含一个 "s" 所以它不符合条件。同时在匹配过程中我们忽略牌照中的大小写。
示例 2:
输入:licensePlate = "1s3456", words = ["looks", "pest", "stew", "show"]
输出:"pest"
说明:存在 3 个包含字母 "s" 且有着最短长度的完整词,但我们返回最先出现的完整词。
注意:
牌照(licensePlate)的长度在区域[1, 7]中。
牌照(licensePlate)将会包含数字、空格、或者字母(大写和小写)。
单词列表(words)长度在区间 [10, 1000] 中。
每一个单词 words[i] 都是小写,并且长度在区间 [1, 15] 中。
*/
// https://leetcode.com/problems/shortest-completing-word/discuss/339569/C%2B%2B-Prime-numbers-%2B-modular-arithmetic
// 无聊,抄别人的质数相乘方法
static int const primes[26] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101
};
uint64_t wordmod(string const& word, uint64_t mod = UINT64_MAX)
{
uint64_t t = 1;
for (char c : word)
t = t * primes[c - 'a'] % mod;
return t;
}
string shortestCompletingWord(string licensePlate, vector<string>& words)
{
int len = 0;
for (char c : licensePlate)
{
if (isalpha(c))
licensePlate[len++] = static_cast<char>(tolower(c));
}
licensePlate.resize(len);
uint64_t lp = wordmod(licensePlate);
string ans = "12345678901234567";
for (string& w : words)
{
if ((w.length() < ans.length()) && (wordmod(w, lp) == 0))
w.swap(ans);
}
return ans;
}
int main()
{
string lp = "1s3 PSt";
vector<string> words = { "step", "steps", "stripe", "stepple" };
OutExpr(shortestCompletingWord(lp, words).c_str(), "%s");
}
|
titanium-forks/appcelerator.titanium_mobile_tizen
|
modules/tizen/src/Tizen/_/Messaging/Message.js
|
// Wraps Tizen interface "Message" that resides in Tizen module "Messaging".
define(['Ti/_/declare', 'Tizen/_/Messaging/MessageBody', 'Ti/_/Evented'], function(declare, MessageBody, Evented) {
var message = declare(Evented, {
constructor: function(args, nativeObj) {
if (nativeObj) {
// nativeObj is a native Tizen object; simply wrap it (take ownership of it)
this._obj = nativeObj;
} else {
// Check if the required parameters are present
// Tizen distinguishes between undefined parameter (this gives an error) and missing parameter (correct).
if('type' in args){
// args is a dictionary that the user of the wrapper module passed to the creator function.
this._obj = (typeof args.messageInitDict !== 'undefined') ?
new tizen.Message(args.type, args.messageInitDict) :
new tizen.Message(args.type);
} else {
throw new Error('Constructor with given parameters doesn\'t exist');
}
}
this.body = new MessageBody(this._obj.body);
},
constants: {
id: {
get: function() {
return this._obj.id;
}
},
serviceId: {
get: function() {
return this._obj.serviceId;
}
},
conversationId: {
get: function() {
return this._obj.conversationId;
}
},
folderId: {
get: function() {
return this._obj.folderId;
}
},
type: {
get: function() {
return this._obj.type;
}
},
timestamp: {
get: function() {
return this._obj.timestamp;
}
},
from: {
get: function() {
return this._obj.from;
}
},
hasAttachment: {
get: function() {
return this._obj.hasAttachment;
}
},
messageStatus: {
get: function() {
return this._obj.messageStatus;
}
}
},
properties: {
to: {
get: function() {
return this._obj.to;
},
set: function(value) {
this._obj.to = value;
}
},
cc: {
get: function() {
return this._obj.cc;
},
set: function(value) {
this._obj.cc = value;
}
},
bcc: {
get: function() {
return this._obj.bcc;
},
set: function(value) {
this._obj.bcc = value;
}
},
body: {
set: function(value) {
this._obj.body = value._obj;
return value;
}
},
isRead: {
get: function() {
return this._obj.isRead;
},
set: function(value) {
this._obj.isRead = value;
}
},
isHighPriority: {
get: function() {
return this._obj.isHighPriority;
},
set: function(value) {
this._obj.isHighPriority = value;
}
},
subject: {
get: function() {
return this._obj.subject;
},
set: function(value) {
this._obj.subject = value;
}
},
inResponseTo: {
get: function() {
return this._obj.inResponseTo;
},
set: function(value) {
this._obj.inResponseTo = value;
}
},
attachments: {
get: function() {
return this._obj.attachments;
},
set: function(value) {
this._obj.attachments = value;
}
}
}
});
// Initialize declaredClass, so that toString() works properly on such objects.
// Correct operation of toString() is required for proper wrapping and automated testing.
message.prototype.declaredClass = 'Tizen.Messaging.Message';
return message;
});
|
xxpasixx/BangleApps
|
apps/openwind/app.js
|
OW_CHAR_UUID = '0000cc91-0000-1000-8000-00805f9b34fb';
require("Font7x11Numeric7Seg").add(Graphics);
var gatt = {};
var cx = g.getWidth()/2;
var cy = 24+(g.getHeight()-24)/2;
var w = (g.getWidth()-24)/2;
var y1 = 24;
var y2 = g.getHeight()-1;
var gps_course = { spd: 0 };
var course_marker_len = g.getWidth()/4;
var settings = require("Storage").readJSON('openwindsettings.json', 1) || {};
var pause_gps = false;
var i = 0;
var hullpoly = [];
for (y=-1; y<=1; y+=0.1) {
hullpoly[i++] = cx - (y<0 ? 1+y*0.15 : (Math.sqrt(1-0.7*y*y)-Math.sqrt(0.3))/(1-Math.sqrt(0.3)))*w*0.3;
hullpoly[i++] = cy - y*w*0.7;
}
for (y=1; y>=-1; y-=0.1) {
hullpoly[i++] = cx + (y<0 ? 1+y*0.15 : (Math.sqrt(1-0.7*y*y)-Math.sqrt(0.3))/(1-Math.sqrt(0.3)))*w*0.3;
hullpoly[i++] = cy - y*w*0.7;
}
function wind_updated(ev) {
if (ev.target.uuid == "0xcc91") {
awa = settings.mount_angle+ev.target.value.getInt16(1, true)*0.1;
if (awa<0) awa += 360;
aws = ev.target.value.getInt16(3, true)*0.01;
//console.log(awa, aws);
if (gps_course.spd > 0) {
wv = { // wind vector (in "earth" reference frame)
vlon: Math.sin(Math.PI*(gps_course.course+(awa+180))/180)*aws,
vlat: Math.cos(Math.PI*(gps_course.course+(awa+180))/180)*aws
};
twv = { vlon: wv.vlon+gps_course.vlon, vlat: wv.vlat+gps_course.vlat };
tws = Math.sqrt(Math.pow(twv.vlon,2)+Math.pow(twv.vlat, 2));
twa = 180+Math.atan2(twv.vlon, twv.vlat)*180/Math.PI-gps_course.course;
if (twa<0) twa += 360;
if (twa>360) twa -=360;
}
else {
tws = -1;
twa = 0;
}
draw_compass(awa,aws,twa,tws);
}
}
function draw_compass(awa, aws, twa, tws) {
g.clearRect(0, 24, g.getWidth()-1, g.getHeight()-1);
fh = w*0.15;
g.setColor(0, 0, 1).fillPoly(hullpoly);
g.setFontVector(fh).setColor(g.theme.fg);
g.setFontAlign(0, 0, 0).drawString("0", cx, 24+fh/2);
g.setFontAlign(0, 0, 1).drawString("90", g.getWidth()-12-fh, cy);
g.setFontAlign(0, 0, 2).drawString("180", cx, g.getHeight()-fh/2);
g.setFontAlign(0, 0, 3).drawString("270", 12+fh/2, cy);
for (i=0; i<4; ++i) {
a = i*Math.PI/2+Math.PI/4;
g.drawLineAA(cx+Math.cos(a)*w*0.85, cy+Math.sin(a)*w*0.85, cx+Math.cos(a)*w*0.99, cy+Math.sin(a)*w*0.99);
}
g.setColor(0, 1, 0).fillCircle(cx+Math.sin(Math.PI*awa/180)*w*0.9, cy-Math.cos(Math.PI*awa/180)*w*0.9, w*0.1);
if (tws>0) g.setColor(1, 0, 0).fillCircle(cx+Math.sin(Math.PI*twa/180)*w*0.9, cy+Math.cos(Math.PI*twa/180)*w*0.9, w*0.1);
g.setColor(0, 1, 0).setFont("7x11Numeric7Seg",w*0.06);
g.setFontAlign(0, 0, 0).drawString(aws.toFixed(1), cx, cy-0.32*w);
if (!pause_gps) {
if (tws>0) g.setColor(1, 0, 0).drawString(tws.toFixed(1), cx, cy+0.32*w);
if (settings.truewind && gps_course.spd!=-1) {
spd = gps_course.spd/1.852;
g.setColor(g.theme.fg).setFont("7x11Numeric7Seg", w*0.03).setFontAlign(-1, 1, 0).drawString(spd.toFixed(1), 1, g.getHeight()-1);
}
}
if (pause_gps) g.setColor("#f00").drawImage(atob("DAwBEAKARAKQE4DwHkPqPRGKAEAA"),g.getWidth()-15, g.getHeight()-15);
}
function parseDevice(d) {
device = d;
console.log("Found device");
device.gatt.connect().then(function(ga) {
console.log("Connected");
gatt = ga;
return ga.getPrimaryService("cc90");
}).then(function(s) {
return s.getCharacteristic("cc91");
}).then(function(c) {
c.on('characteristicvaluechanged', (event)=>wind_updated(event));
return c.startNotifications();
}).then(function() {
console.log("Done!");
}).catch(function(e) {
console.log("ERROR"+e);
});}
function connection_setup() {
NRF.setScan();
NRF.setScan(parseDevice, { filters: [{services:["cc90"]}], timeout: 2000});
console.log("Scanning for OW sensor");
}
if (settings.truewind) {
Bangle.on('GPS',function(fix) {
if (fix.fix && fix.satellites>3 && fix.speed>2) { // only uses fixes w/ more than 3 sats and speed > 2kph
gps_course =
{ vlon: Math.sin(Math.PI*fix.course/180)*fix.speed/1.852,
vlat: Math.cos(Math.PI*fix.course/180)*fix.speed/1.852,
lat: fix.lat,
lon: fix.lon,
spd: fix.speed,
course: fix.course
};
}
else gps_course.spd = -1;
});
Bangle.setGPSPower(1, "app");
}
if (settings.truewind) {
Bangle.on("swipe", (d)=>{
if (d==-1 && !pause_gps) {
pause_gps = true;
Bangle.setGPSPower(0);
draw_compass(0, 0, 0, 0);
}
else if (d==1 && pause_gps) {
pause_gps = false;
Bangle.setGPSPower(1, "app");
draw_compass(0, 0, 0, 0);
}
});
}
Bangle.loadWidgets();
Bangle.drawWidgets();
draw_compass(0, 0, 0, 0);
connection_setup();
|
hillyuan/Panzer
|
disc-fe/src/responses/Panzer_ResponseMESupport_Default.hpp
|
// @HEADER
// ***********************************************************************
//
// Panzer: A partial differential equation assembly
// engine for strongly coupled complex multiphysics systems
// Copyright (2011) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact <NAME> (<EMAIL>) and
// <NAME> (<EMAIL>)
// ***********************************************************************
// @HEADER
#ifndef __Panzer_ResponseMESupport_Default_hpp__
#define __Panzer_ResponseMESupport_Default_hpp__
#include "Teuchos_DefaultMpiComm.hpp"
#include "Teuchos_ArrayRCP.hpp"
#include "Teuchos_RCP.hpp"
#include "Teuchos_OpaqueWrapper.hpp"
#include "Panzer_ResponseMESupportBase.hpp"
#include "Thyra_EpetraThyraWrappers.hpp"
#include "Thyra_DefaultSpmdVectorSpace.hpp"
#include "Thyra_SpmdVectorBase.hpp"
#include "Epetra_LocalMap.h"
#include "Epetra_Map.h"
namespace panzer {
template <typename EvalT>
class ResponseMESupport_Default : public ResponseMESupportBase<EvalT> {
public:
ResponseMESupport_Default(const std::string & responseName,MPI_Comm comm)
: ResponseMESupportBase<EvalT>(responseName), useEpetra_(false), eComm_(comm), useThyra_(false)
{
tComm_ = Teuchos::rcp(new Teuchos::MpiComm<Thyra::Ordinal>(Teuchos::opaqueWrapper(comm)));
}
virtual ~ResponseMESupport_Default() {}
//! What is the number of values you need locally
virtual std::size_t localSizeRequired() const = 0;
//! Is the vector distributed (or replicated)
virtual bool vectorIsDistributed() const = 0;
// This is the epetra view of the world
///////////////////////////////////////////////////////////
//! Get the <code>Epetra_Map</code> for this response, map is constructed lazily.
Teuchos::RCP<const Epetra_Map> getMap() const;
/** Set the vector (to be filled) for this response. This must be
* constructed from the vector space returned by <code>getMap</code>.
*/
void setVector(const Teuchos::RCP<Epetra_Vector> & destVec);
// This is the Thyra view of the world
///////////////////////////////////////////////////////////
//! Get the vector space for this response, vector space is constructed lazily.
Teuchos::RCP<const Thyra::VectorSpaceBase<double> > getVectorSpace() const;
/** Set the vector (to be filled) for this response. This must be
* constructed from the vector space returned by <code>getVectorSpace</code>.
*/
void setVector(const Teuchos::RCP<Thyra::VectorBase<double> > & destVec);
//! set the vector space for this response
void setVectorSpace(Teuchos::RCP<const Thyra::VectorSpaceBase<double> > vs)
{ vSpace_ = vs; }
//! Access the response vector
Teuchos::RCP<Thyra::VectorBase<double> > getVector() const
{ return tVector_; }
protected:
//! Get the teuchos comm object
Teuchos::RCP<const Teuchos::Comm<Thyra::Ordinal> > getComm() const { return tComm_; }
//! Is Epetra the right vector
bool useEpetra() const { return useEpetra_; }
//! Is Thyra the right vector
bool useThyra() const { return useThyra_; }
//! Access the epetra vector
Epetra_Vector & getEpetraVector() const;
//! Access the thyra vector
Thyra::ArrayRCP<double> getThyraVector() const;
//! Access the thyra MultiVector
Teuchos::RCP<Thyra::MultiVectorBase<double> > getThyraMultiVector() const
{ return tVector_;}
private:
// hide these methods
ResponseMESupport_Default();
ResponseMESupport_Default(const ResponseMESupport_Default<EvalT> &);
bool useEpetra_;
Epetra_MpiComm eComm_;
mutable Teuchos::RCP<const Epetra_Map> map_;
Teuchos::RCP<Epetra_Vector> eVector_;
bool useThyra_;
mutable Teuchos::RCP<const Thyra::VectorSpaceBase<double> > vSpace_;
Teuchos::RCP<Thyra::VectorBase<double> > tVector_;
Teuchos::RCP<const Teuchos::Comm<Thyra::Ordinal> > tComm_;
};
template < >
class ResponseMESupport_Default<panzer::Traits::Jacobian> : public ResponseMESupportBase<panzer::Traits::Jacobian> {
public:
ResponseMESupport_Default(const std::string & responseName,MPI_Comm comm,
const Teuchos::RCP<const Thyra::VectorSpaceBase<double> > & derivVecSpace=Teuchos::null)
: ResponseMESupportBase<panzer::Traits::Jacobian>(responseName), derivVecSpace_(derivVecSpace)
{ tComm_ = Teuchos::rcp(new Teuchos::MpiComm<Thyra::Ordinal>(Teuchos::opaqueWrapper(comm))); }
virtual ~ResponseMESupport_Default() {}
//! What is the number of values you need locally
virtual std::size_t localSizeRequired() const = 0;
//! Is the vector distributed (or replicated). For derivative assembly this must be false!
virtual bool vectorIsDistributed() const = 0;
//! Does this response support derivative evaluation?
bool supportsDerivative() const { return getDerivativeVectorSpace()!=Teuchos::null; }
/** Get the vector for this response. This must be
* constructed from the vector space returned by <code>getMap</code>.
*/
Teuchos::RCP<Thyra::MultiVectorBase<double> > getDerivative() const
{ return derivative_; }
// This is the epetra view of the world
///////////////////////////////////////////////////////////
//! Get the <code>Epetra_Map</code> for this response, map is constructed lazily.
virtual Teuchos::RCP<Epetra_MultiVector> buildEpetraDerivative() const
{
TEUCHOS_ASSERT(!vectorIsDistributed());
TEUCHOS_ASSERT(localSizeRequired()==1);
TEUCHOS_ASSERT(supportsDerivative());
if(eMap_==Teuchos::null)
eMap_ = Thyra::get_Epetra_Map(*getDerivativeVectorSpace(),Thyra::get_Epetra_Comm(*tComm_));
return Teuchos::rcp(new Epetra_Vector(*eMap_));
}
/** Set the vector (to be filled) for this response. This must be
* constructed from the vector space returned by <code>getMap</code>.
*/
virtual void setDerivative(const Teuchos::RCP<Epetra_MultiVector> & derivative)
{
TEUCHOS_ASSERT(!vectorIsDistributed());
TEUCHOS_ASSERT(localSizeRequired()==1);
TEUCHOS_ASSERT(supportsDerivative());
TEUCHOS_ASSERT(eMap_!=Teuchos::null);
derivative_ = Thyra::create_MultiVector(derivative,getDerivativeVectorSpace());
}
// This is the Thyra view of the world
///////////////////////////////////////////////////////////
//! Get the <code>Epetra_Map</code> for this response, map is constructed lazily.
virtual Teuchos::RCP<Thyra::MultiVectorBase<double> > buildDerivative() const
{
TEUCHOS_ASSERT(!vectorIsDistributed());
TEUCHOS_ASSERT(localSizeRequired()==1);
TEUCHOS_ASSERT(supportsDerivative());
return Thyra::createMember(*getDerivativeVectorSpace());
}
/** Set the vector (to be filled) for this response. This must be
* constructed from the vector space returned by <code>getMap</code>.
*/
virtual void setDerivative(const Teuchos::RCP<Thyra::MultiVectorBase<double> > & derivative)
{
TEUCHOS_ASSERT(!vectorIsDistributed());
TEUCHOS_ASSERT(localSizeRequired()==1);
TEUCHOS_ASSERT(supportsDerivative());
derivative_ = derivative;
}
protected:
//! Get the teuchos comm object
Teuchos::RCP<const Teuchos::Comm<Thyra::Ordinal> > getComm() const { return tComm_; }
//! Get the derivative vector space
Teuchos::RCP<const Thyra::VectorSpaceBase<double> > getDerivativeVectorSpace() const
{ return derivVecSpace_; }
//! Set the derivative vector space
void setDerivativeVectorSpace(const Teuchos::RCP<const Thyra::VectorSpaceBase<double> > & vs)
{ derivVecSpace_ = vs; }
private:
// hide these methods
ResponseMESupport_Default();
ResponseMESupport_Default(const ResponseMESupport_Default<panzer::Traits::Jacobian> &);
Teuchos::RCP<const Teuchos::Comm<Thyra::Ordinal> > tComm_;
Teuchos::RCP<const Thyra::VectorSpaceBase<double> > derivVecSpace_;
mutable Teuchos::RCP<const Epetra_Map> eMap_;
Teuchos::RCP<Thyra::MultiVectorBase<double> > derivative_;
};
template < >
class ResponseMESupport_Default<panzer::Traits::Tangent> : public ResponseMESupportBase<panzer::Traits::Tangent> {
public:
typedef panzer::Traits::Tangent EvalT;
ResponseMESupport_Default(const std::string & responseName,MPI_Comm comm)
: ResponseMESupportBase<EvalT>(responseName), useEpetra_(false), eComm_(comm), useThyra_(false)
{
tComm_ = Teuchos::rcp(new Teuchos::MpiComm<Thyra::Ordinal>(Teuchos::opaqueWrapper(comm)));
}
virtual ~ResponseMESupport_Default() {}
//! What is the number of values you need locally
virtual std::size_t localSizeRequired() const = 0;
//! Is the vector distributed (or replicated)
virtual bool vectorIsDistributed() const = 0;
// This is the epetra view of the world
///////////////////////////////////////////////////////////
//! Get the <code>Epetra_Map</code> for this response, map is constructed lazily.
Teuchos::RCP<const Epetra_Map> getMap() const {
TEUCHOS_TEST_FOR_EXCEPTION(useThyra_,std::logic_error,
"Reponse field \"" << this->getName() << "\" has previously been initialized as a "
"Thyra object, now trying to initalize as a Epetra! Error!");
// lazily construct the map only as needed
if(map_==Teuchos::null) {
if(this->vectorIsDistributed())
map_ = Teuchos::rcp(new Epetra_Map(-1,(int) this->localSizeRequired(),0,eComm_));
else
map_ = Teuchos::rcp(new Epetra_LocalMap((int) this->localSizeRequired(),0,eComm_));
}
return map_;
}
/** Set the vector (to be filled) for this response. This must be
* constructed from the vector space returned by <code>getMap</code>.
*/
void setVector(const Teuchos::RCP<Epetra_MultiVector> & destVec) {
TEUCHOS_TEST_FOR_EXCEPTION(useThyra_,std::logic_error,
"Reponse field \"" << this->getName() << "\" has previously been initialized as a "
"Thyra object, now trying to initalize as a Epetra! Error!");
eVector_ = destVec;
useEpetra_ = true;
}
// This is the Thyra view of the world
///////////////////////////////////////////////////////////
//! Get the vector space for this response, vector space is constructed lazily.
Teuchos::RCP<const Thyra::VectorSpaceBase<double> > getVectorSpace() const {
TEUCHOS_TEST_FOR_EXCEPTION(useEpetra_,std::logic_error,
"Reponse field \"" << this->getName() << "\" has previously been initialized as an "
"Epetra object, now trying to initalize as a Thyra object! Error!");
// lazily build the space and return it
if(vSpace_==Teuchos::null) {
if(this->vectorIsDistributed())
vSpace_ = Thyra::defaultSpmdVectorSpace<double>(tComm_,this->localSizeRequired(),-1);
else
vSpace_ = Thyra::locallyReplicatedDefaultSpmdVectorSpace<double>(tComm_,this->localSizeRequired());
}
return vSpace_;
}
/** Set the vector (to be filled) for this response. This must be
* constructed from the vector space returned by <code>getVectorSpace</code>.
*/
void setVector(const Teuchos::RCP<Thyra::MultiVectorBase<double> > & destVec) {
TEUCHOS_TEST_FOR_EXCEPTION(useEpetra_,std::logic_error,
"Reponse field \"" << this->getName() << "\" has previously been initialized as an "
"Epetra object, now trying to initalize as a Thyra object! Error!");
tVector_ = destVec;
useThyra_ = true;
}
protected:
//! Get the teuchos comm object
Teuchos::RCP<const Teuchos::Comm<Thyra::Ordinal> > getComm() const { return tComm_; }
//! Is Epetra the right vector
bool useEpetra() const { return useEpetra_; }
//! Is Thyra the right vector
bool useThyra() const { return useThyra_; }
//! Access the epetra vector
Epetra_MultiVector & getEpetraMultiVector() const {
TEUCHOS_ASSERT(useEpetra());
return *eVector_;
}
//! Access the thyra vector
Thyra::ArrayRCP< Thyra::ArrayRCP<double> > getThyraMultiVector() const {
TEUCHOS_ASSERT(useThyra());
const int num_col = tVector_->domain()->dim();
Thyra::ArrayRCP< Thyra::ArrayRCP<double> > data(num_col);
for (int i=0; i<num_col; ++i)
Teuchos::rcp_dynamic_cast<Thyra::SpmdVectorBase<double> >(tVector_->col(i),true)->getNonconstLocalData(Teuchos::outArg(data[i]));
return data;
}
//! Return the number of columns in the multivector
int numDeriv() const {
if (useEpetra())
return eVector_->NumVectors();
else
return tVector_->domain()->dim();
}
private:
// hide these methods
ResponseMESupport_Default();
ResponseMESupport_Default(const ResponseMESupport_Default<EvalT> &);
bool useEpetra_;
Epetra_MpiComm eComm_;
mutable Teuchos::RCP<const Epetra_Map> map_;
Teuchos::RCP<Epetra_MultiVector> eVector_;
bool useThyra_;
mutable Teuchos::RCP<const Thyra::VectorSpaceBase<double> > vSpace_;
Teuchos::RCP<Thyra::MultiVectorBase<double> > tVector_;
Teuchos::RCP<const Teuchos::Comm<Thyra::Ordinal> > tComm_;
};
#ifdef Panzer_BUILD_HESSIAN_SUPPORT
template < >
class ResponseMESupport_Default<panzer::Traits::Hessian> : public ResponseMESupportBase<panzer::Traits::Hessian> {
public:
ResponseMESupport_Default(const std::string & responseName,MPI_Comm comm,
const Teuchos::RCP<const Thyra::VectorSpaceBase<double> > & derivVecSpace=Teuchos::null)
: ResponseMESupportBase<panzer::Traits::Hessian>(responseName), derivVecSpace_(derivVecSpace)
{ tComm_ = Teuchos::rcp(new Teuchos::MpiComm<Thyra::Ordinal>(Teuchos::opaqueWrapper(comm))); }
virtual ~ResponseMESupport_Default() {}
//! What is the number of values you need locally
virtual std::size_t localSizeRequired() const = 0;
//! Is the vector distributed (or replicated). For derivative assembly this must be false!
virtual bool vectorIsDistributed() const = 0;
//! Does this response support derivative evaluation?
bool supportsDerivative() const { return getDerivativeVectorSpace()!=Teuchos::null; }
/** Get the vector for this response. This must be
* constructed from the vector space returned by <code>getMap</code>.
*/
Teuchos::RCP<Thyra::MultiVectorBase<double> > getDerivative() const
{ return derivative_; }
//! Get the <code>Epetra_Map</code> for this response, map is constructed lazily.
virtual Teuchos::RCP<Thyra::MultiVectorBase<double> > buildDerivative() const
{
TEUCHOS_ASSERT(!vectorIsDistributed());
TEUCHOS_ASSERT(localSizeRequired()==1);
TEUCHOS_ASSERT(supportsDerivative());
return Thyra::createMember(*getDerivativeVectorSpace());
}
/** Set the vector (to be filled) for this response. This must be
* constructed from the vector space returned by <code>getMap</code>.
*/
virtual void setDerivative(const Teuchos::RCP<Thyra::MultiVectorBase<double> > & derivative)
{
TEUCHOS_ASSERT(!vectorIsDistributed());
TEUCHOS_ASSERT(localSizeRequired()==1);
TEUCHOS_ASSERT(supportsDerivative());
derivative_ = derivative;
}
protected:
//! Get the teuchos comm object
Teuchos::RCP<const Teuchos::Comm<Thyra::Ordinal> > getComm() const { return tComm_; }
//! Get the derivative vector space
Teuchos::RCP<const Thyra::VectorSpaceBase<double> > getDerivativeVectorSpace() const
{ return derivVecSpace_; }
//! Set the derivative vector space
void setDerivativeVectorSpace(const Teuchos::RCP<const Thyra::VectorSpaceBase<double> > & vs)
{ derivVecSpace_ = vs; }
private:
// hide these methods
ResponseMESupport_Default();
ResponseMESupport_Default(const ResponseMESupport_Default<panzer::Traits::Hessian> &);
Teuchos::RCP<const Teuchos::Comm<Thyra::Ordinal> > tComm_;
Teuchos::RCP<const Thyra::VectorSpaceBase<double> > derivVecSpace_;
Teuchos::RCP<Thyra::MultiVectorBase<double> > derivative_;
};
#endif
}
#include "Panzer_ResponseMESupport_Default_impl.hpp"
#endif
|
joejulian/kudo
|
pkg/kudoctl/cmd/init_integration_test.go
|
// +build integration
package cmd
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"testing"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
testutils "github.com/kudobuilder/kuttl/pkg/test/utils"
"github.com/kudobuilder/kudo/pkg/kudoctl/clog"
"github.com/kudobuilder/kudo/pkg/kudoctl/kube"
"github.com/kudobuilder/kudo/pkg/kudoctl/kudoinit"
"github.com/kudobuilder/kudo/pkg/kudoctl/kudoinit/crd"
"github.com/kudobuilder/kudo/pkg/kudoctl/kudoinit/prereq"
)
var testenv testutils.TestEnvironment
func TestMain(m *testing.M) {
var err error
testenv, err = testutils.StartTestEnvironment(testutils.APIServerDefaultArgs)
if err != nil {
log.Fatal(err)
}
exitCode := m.Run()
err = testenv.Environment.Stop()
if err != nil {
log.Fatal(err)
}
os.Exit(exitCode)
}
const (
operatorFileName = "kudo.dev_operators.yaml"
operatorVersionFileName = "kudo.dev_operatorversions.yaml"
instanceFileName = "kudo.dev_instances.yaml"
manifestsDir = "../../../config/crds/"
)
func TestCrds_Config(t *testing.T) {
crds := crd.NewInitializer()
assertManifestFileMatch(t, operatorFileName, crds.Operator)
assertManifestFileMatch(t, operatorVersionFileName, crds.OperatorVersion)
assertManifestFileMatch(t, instanceFileName, crds.Instance)
}
func assertManifestFileMatch(t *testing.T, fileName string, expectedObject runtime.Object) {
expectedContent, err := runtimeObjectAsBytes(expectedObject)
assert.NoError(t, err)
path := filepath.Join(manifestsDir, fileName)
of, err := ioutil.ReadFile(path)
assert.NoError(t, err)
assert.Equal(t, string(expectedContent), string(of), fmt.Sprintf("embedded file %s does not match the source, run 'make generate'", fileName))
}
func assertStringContains(t *testing.T, expected string, actual string) {
assert.True(t, strings.Contains(actual, expected), "Expected to find '%s' in '%s'", expected, actual)
}
func runtimeObjectAsBytes(o runtime.Object) ([]byte, error) {
bytes, err := yaml.Marshal(o)
if err != nil {
return nil, err
}
return append([]byte("\n---\n"), bytes...), nil
}
func TestIntegInitForCRDs(t *testing.T) {
// Kubernetes client caches the types, so we need to re-initialize it.
testClient, err := testutils.NewRetryClient(testenv.Config, client.Options{
Scheme: testutils.Scheme(),
})
assert.NoError(t, err)
kclient := getKubeClient(t)
instance := testutils.NewResource("kudo.dev/v1beta1", "Instance", "zk", "default")
// Verify that we cannot create the instance, because the test environment is empty.
assert.IsType(t, &meta.NoKindMatchError{}, testClient.Create(context.TODO(), instance))
// Install all of the CRDs.
crds := crd.NewInitializer().Resources()
var buf bytes.Buffer
var errBuf bytes.Buffer
cmd := &initCmd{
out: &buf,
errOut: &errBuf,
fs: afero.NewMemMapFs(),
client: kclient,
crdOnly: true,
version: "dev",
}
err = cmd.run()
assert.NoError(t, err)
// WaitForCRDs to be created... the init cmd did NOT wait
assert.NoError(t, testutils.WaitForCRDs(testenv.DiscoveryClient, crds))
defer func() {
assert.NoError(t, deleteObjects(crds, testClient))
}()
// Kubernetes client caches the types, so we need to re-initialize it.
testClient, err = testutils.NewRetryClient(testenv.Config, client.Options{
Scheme: testutils.Scheme(),
})
assert.NoError(t, err)
// make sure that we can create an object of this type now
assert.NoError(t, testClient.Create(context.TODO(), instance))
assert.NoError(t, testClient.Delete(context.TODO(), instance))
}
func TestIntegInitWithNameSpace(t *testing.T) {
namespace := "integration-test"
// Kubernetes client caches the types, so we need to re-initialize it.
testClient, err := testutils.NewRetryClient(testenv.Config, client.Options{
Scheme: testutils.Scheme(),
})
assert.NoError(t, err)
kclient := getKubeClient(t)
instance := testutils.NewResource("kudo.dev/v1beta1", "Instance", "zk", "ns")
// Verify that we cannot create the instance, because the test environment is empty.
assert.IsType(t, &meta.NoKindMatchError{}, testClient.Create(context.TODO(), instance))
// Install all of the CRDs.
crds := crd.NewInitializer().Resources()
var buf bytes.Buffer
var errBuf bytes.Buffer
cmd := &initCmd{
out: &buf,
errOut: &errBuf,
fs: afero.NewMemMapFs(),
client: kclient,
ns: namespace,
selfSignedWebhookCA: true,
version: "dev",
}
// On first attempt, the namespace does not exist, so the error is expected.
err = cmd.run()
require.Error(t, err)
assert.Equal(t, "failed to verify installation requirements", err.Error())
assertStringContains(t, "Namespace integration-test does not exist - KUDO expects that any namespace except the default kudo-system is created beforehand", errBuf.String())
// Then we manually create the namespace.
ns := testutils.NewResource("v1", "Namespace", namespace, "")
assert.NoError(t, testClient.Create(context.TODO(), ns))
defer func() {
assert.NoError(t, testClient.Delete(context.TODO(), ns))
}()
// On second attempt run should succeed.
err = cmd.run()
assert.NoError(t, err)
defer func() {
assert.NoError(t, deleteInitPrereqs(cmd, testClient))
}()
// WaitForCRDs to be created... the init cmd did NOT wait
assert.NoError(t, testutils.WaitForCRDs(testenv.DiscoveryClient, crds))
// make sure that the controller lives in the correct namespace
kclient = getKubeClient(t)
statefulsets, err := kclient.KubeClient.AppsV1().StatefulSets(namespace).List(metav1.ListOptions{})
assert.NoError(t, err)
kudoControllerFound := false
for _, ss := range statefulsets.Items {
if ss.Name == kudoinit.DefaultManagerName {
kudoControllerFound = true
}
}
assert.True(t, kudoControllerFound, fmt.Sprintf("No kudo-controller-manager statefulset found in namespace %s", namespace))
}
/*
Test the below 5 scenarios
1. Run Init command with a serviceAccount that is not present in the cluster.
2. Run init command with a serviceAccount that is present in the cluster, but not in the clusterrole-binding.
3. Run Init command with a serviceAccount that does not have cluster-admin role.
4. Run Init command with a serviceAccount that does have cluster-admin role, but not in the expected namespace.
5. Run Init command with a serviceAccount that is present in the cluster and also has cluster-admin role.
*/
func TestInitWithServiceAccount(t *testing.T) {
tests := []struct {
name string
serviceAccount string
roleBindingRole string
roleBindingNs string
errMessageContains string
}{
{
name: "service account not present",
serviceAccount: "",
errMessageContains: "Service Account test-account does not exists - KUDO expects the serviceAccount to be present in the namespace sa-integration-test-0",
},
{
name: "service account has no rb",
serviceAccount: "test-account",
errMessageContains: "Service Account test-account does not have cluster-admin role - KUDO expects the serviceAccount passed to be in the namespace sa-integration-test-1 and to have cluster-admin role",
},
{
name: "rb has no cluster-admin role",
serviceAccount: "test-account",
roleBindingRole: "not-admin",
errMessageContains: "Service Account test-account does not have cluster-admin role - KUDO expects the serviceAccount passed to be in the namespace sa-integration-test-2 and to have cluster-admin role",
},
{
name: "rb has different ns",
serviceAccount: "test-account",
roleBindingRole: "not-admin",
roleBindingNs: "otherns",
errMessageContains: "Service Account test-account does not have cluster-admin role - KUDO expects the serviceAccount passed to be in the namespace sa-integration-test-3 and to have cluster-admin role",
},
{
name: "rb has admin in different ns",
serviceAccount: "test-account",
roleBindingRole: "cluster-admin",
roleBindingNs: "otherns",
errMessageContains: "Service Account test-account does not have cluster-admin role - KUDO expects the serviceAccount passed to be in the namespace sa-integration-test-4 and to have cluster-admin role",
},
{
name: "rb has cluster-admin role",
serviceAccount: "test-account",
roleBindingRole: "cluster-admin",
errMessageContains: "",
},
}
namespaceBase := "sa-integration-test"
for idx, tt := range tests {
idx := idx
tt := tt
t.Run(tt.name, func(t *testing.T) {
namespace := fmt.Sprintf("%s-%d", namespaceBase, idx)
// Kubernetes client caches the types, so we need to re-initialize it.
testClient, err := testutils.NewRetryClient(testenv.Config, client.Options{
Scheme: testutils.Scheme(),
})
assert.NoError(t, err)
kclient := getKubeClient(t)
instance := testutils.NewResource("kudo.dev/v1beta1", "Instance", "zk", "ns")
// Verify that we cannot create the instance, because the test environment is empty.
assert.IsType(t, &meta.NoKindMatchError{}, testClient.Create(context.TODO(), instance))
// Install all of the CRDs.
crds := crd.NewInitializer().Resources()
var buf bytes.Buffer
var errBuf bytes.Buffer
cmd := &initCmd{
out: &buf,
errOut: &errBuf,
fs: afero.NewMemMapFs(),
client: kclient,
ns: namespace,
serviceAccount: "test-account",
selfSignedWebhookCA: true,
version: "dev",
}
ns := testutils.NewResource("v1", "Namespace", namespace, "")
assert.NoError(t, testClient.Create(context.TODO(), ns))
defer func() {
assert.NoError(t, testClient.Delete(context.TODO(), ns))
}()
if tt.serviceAccount != "" {
sa2 := testutils.NewResource("v1", "ServiceAccount", tt.serviceAccount, namespace)
assert.NoError(t, testClient.Create(context.TODO(), sa2))
defer func() {
assert.NoError(t, testClient.Delete(context.TODO(), sa2))
}()
}
if tt.roleBindingRole != "" {
rbNamespace := tt.roleBindingNs
if rbNamespace == "" {
rbNamespace = namespace
}
crb := testutils.NewClusterRoleBinding("rbac.authorization.k8s.io/v1", "ClusterRoleBinding", "kudo-clusterrole-binding", rbNamespace, tt.serviceAccount, tt.roleBindingRole)
assert.NoError(t, testClient.Create(context.TODO(), crb))
defer func() {
assert.NoError(t, testClient.Delete(context.TODO(), crb))
}()
}
err = cmd.run()
if tt.errMessageContains != "" {
require.Error(t, err)
assert.Equal(t, "failed to verify installation requirements", err.Error())
assertStringContains(t, tt.errMessageContains, errBuf.String())
} else {
assert.NoError(t, err)
defer func() {
assert.NoError(t, deleteInitPrereqs(cmd, testClient))
}()
// WaitForCRDs to be created... the init cmd did NOT wait
assert.NoError(t, testutils.WaitForCRDs(testenv.DiscoveryClient, crds))
// make sure that the controller lives in the correct namespace
kclient = getKubeClient(t)
statefulsets, err := kclient.KubeClient.AppsV1().StatefulSets(namespace).List(metav1.ListOptions{})
assert.NoError(t, err)
kudoControllerFound := false
for _, ss := range statefulsets.Items {
if ss.Name == kudoinit.DefaultManagerName {
kudoControllerFound = true
}
}
assert.True(t, kudoControllerFound, fmt.Sprintf("No kudo-controller-manager statefulset found in namespace %s", namespace))
}
})
}
}
func TestNoErrorOnReInit(t *testing.T) {
// if the CRD exists and we init again there should be no error
testClient, err := testutils.NewRetryClient(testenv.Config, client.Options{
Scheme: testutils.Scheme(),
})
assert.Nil(t, err)
kclient := getKubeClient(t)
instance := testutils.NewResource("kudo.dev/v1beta1", "Instance", "zk", "ns")
// Verify that we cannot create the instance, because the test environment is empty.
assert.IsType(t, &meta.NoKindMatchError{}, testClient.Create(context.TODO(), instance))
// Install all of the CRDs.
crds := crd.NewInitializer().Resources()
var buf bytes.Buffer
clog.InitNoFlag(&buf, clog.Level(4))
defer func() { clog.InitNoFlag(&buf, clog.Level(0)) }()
var errBuf bytes.Buffer
cmd := &initCmd{
out: &buf,
errOut: &errBuf,
fs: afero.NewMemMapFs(),
client: kclient,
crdOnly: true,
version: "dev",
}
err = cmd.run()
assert.NoError(t, err)
// WaitForCRDs to be created... the init cmd did NOT wait
assert.NoError(t, testutils.WaitForCRDs(testenv.DiscoveryClient, crds))
defer func() {
assert.NoError(t, deleteObjects(crds, testClient))
}()
// second run will have an output that it already exists
err = cmd.run()
assert.NoError(t, err)
assert.True(t, strings.Contains(buf.String(), "crd operators.kudo.dev already exists"))
}
func deleteObjects(objs []runtime.Object, client *testutils.RetryClient) error {
for _, obj := range objs {
if err := client.Delete(context.TODO(), obj); err != nil {
return err
}
}
return testutils.WaitForDelete(client, objs)
}
func deleteInitPrereqs(cmd *initCmd, client *testutils.RetryClient) error {
opts := kudoinit.NewOptions(cmd.version, cmd.ns, cmd.serviceAccount, cmd.selfSignedWebhookCA)
objs := append([]runtime.Object{}, prereq.NewWebHookInitializer(opts).Resources()...)
objs = append(objs, prereq.NewServiceAccountInitializer(opts).Resources()...)
objs = append(objs, crd.NewInitializer().Resources()...)
// Namespaced resources aren't waited on after deletion because they aren't GC'ed in this test environment.
for _, ns := range prereq.NewNamespaceInitializer(opts).Resources() {
if err := client.Delete(context.TODO(), ns); err != nil {
return err
}
}
return deleteObjects(objs, client)
}
func getKubeClient(t *testing.T) *kube.Client {
c, err := kubernetes.NewForConfig(testenv.Config)
assert.NoError(t, err)
xc, err := apiextensionsclient.NewForConfig(testenv.Config)
assert.NoError(t, err)
return &kube.Client{KubeClient: c, ExtClient: xc}
}
|
raindigi/Merchello
|
src/Merchello.Web.UI.Client/src/views/collections/dialogs/delete.staticcollection.controller.js
|
angular.module('merchello').controller('Merchello.EntityCollections.Dialogs.DeleteEntityCollectionController', [
'$scope', '$location', 'treeService', 'navigationService', 'notificationsService', 'entityCollectionResource', 'entityCollectionDisplayBuilder',
function($scope, $location, treeService, navigationService, notificationsService, entityCollectionResource, entityCollectionDisplayBuilder) {
$scope.loaded = false;
$scope.dialogData = {};
$scope.entityCollection = {};
$scope.refreshPath = {};
$scope.confirmDelete = confirmDelete;
function init() {
$scope.dialogData = $scope.$parent.currentAction.metaData.dialogData;
$scope.refreshPath = treeService.getPath($scope.$parent.currentNode);
loadEntityCollection();
}
function loadEntityCollection() {
var promise = entityCollectionResource.getByKey($scope.dialogData.collectionKey);
promise.then(function(collection) {
$scope.entityCollection = entityCollectionDisplayBuilder.transform(collection);
$scope.dialogData.name = $scope.entityCollection.name;
$scope.loaded = true;
}, function(reason) {
notificationsService.error("Failted to entity collection", reason.message);
});
}
function confirmDelete() {
var promise = entityCollectionResource.deleteEntityCollection($scope.dialogData.collectionKey);
promise.then(function(){
navigationService.hideNavigation();
treeService.removeNode($scope.currentNode);
notificationsService.success('Collection deleted');
}, function(reason) {
notificationsService.error("Failted to delete entity collection", reason.message);
});
}
// initialize the controller
init();
}]);
|
nithinkumar030/bigmuddy-network-telemetry-pipeline
|
vendor/github.com/cisco/bigmuddy-network-telemetry-proto/proto_go/cisco_ios_xr_ipv6_acl_oper/ipv6_acl_and_prefix_list/oor/details/a.go
|
//go:generate protoc --go_out=plugins=grpc:. ipv6_acl_edm_oor_detail.proto
// Cisco-IOS-XR-ipv6-acl-oper:ipv6-acl-and-prefix-list/oor/details
package cisco_ios_xr_ipv6_acl_oper_ipv6_acl_and_prefix_list_oor_details
|
TigerBSD/FreeBSD-Custom-ThinkPad
|
FreeBSD/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeBreakpointList.h
|
//===-- NativeBreakpointList.h ----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_NativeBreakpointList_h_
#define liblldb_NativeBreakpointList_h_
#include "lldb/lldb-private-forward.h"
#include "lldb/Core/Error.h"
#include "lldb/Host/Mutex.h"
// #include "lldb/Host/NativeBreakpoint.h"
#include <functional>
#include <map>
namespace lldb_private
{
class NativeBreakpointList
{
public:
typedef std::function<Error (lldb::addr_t addr, size_t size_hint, bool hardware, NativeBreakpointSP &breakpoint_sp)> CreateBreakpointFunc;
NativeBreakpointList ();
Error
AddRef (lldb::addr_t addr, size_t size_hint, bool hardware, CreateBreakpointFunc create_func);
Error
DecRef (lldb::addr_t addr);
Error
EnableBreakpoint (lldb::addr_t addr);
Error
DisableBreakpoint (lldb::addr_t addr);
Error
GetBreakpoint (lldb::addr_t addr, NativeBreakpointSP &breakpoint_sp);
Error
RemoveTrapsFromBuffer(lldb::addr_t addr, void *buf, size_t size) const;
private:
typedef std::map<lldb::addr_t, NativeBreakpointSP> BreakpointMap;
Mutex m_mutex;
BreakpointMap m_breakpoints;
};
}
#endif // ifndef liblldb_NativeBreakpointList_h_
|
YorickColeu/cloud
|
authorization/pb/service.pb.go
|
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: github.com/plgd-dev/cloud/authorization/pb/service.proto
package pb
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
func init() {
proto.RegisterFile("github.com/plgd-dev/cloud/authorization/pb/service.proto", fileDescriptor_7d55a688f473dfed)
}
var fileDescriptor_7d55a688f473dfed = []byte{
// 313 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x8c, 0x93, 0xcf, 0x4b, 0xc3, 0x30,
0x14, 0xc7, 0xe7, 0xc1, 0x89, 0x41, 0x04, 0x83, 0xa7, 0x81, 0xa0, 0x55, 0xd4, 0xcb, 0x12, 0xd1,
0x8b, 0xe0, 0x69, 0x22, 0xc8, 0x4e, 0x83, 0xce, 0x81, 0x08, 0x1e, 0xfa, 0xe3, 0xf5, 0x07, 0x6e,
0x49, 0x6c, 0x92, 0x1e, 0xfc, 0x67, 0xfd, 0x57, 0x5c, 0xd6, 0xb5, 0xeb, 0x58, 0xda, 0x7a, 0x0b,
0x79, 0x9f, 0xf7, 0x79, 0x5f, 0x5e, 0x08, 0x7a, 0x8c, 0x53, 0x95, 0x68, 0x9f, 0x04, 0x7c, 0x41,
0xc5, 0x3c, 0x0e, 0x87, 0x21, 0xe4, 0x34, 0x98, 0x73, 0x1d, 0x52, 0x4f, 0xab, 0x84, 0x67, 0xe9,
0x8f, 0xa7, 0x52, 0xce, 0xa8, 0xf0, 0xa9, 0x84, 0x2c, 0x4f, 0x03, 0x20, 0x22, 0xe3, 0x8a, 0xe3,
0x13, 0x1e, 0x44, 0x64, 0x45, 0x12, 0x43, 0x12, 0xe1, 0x0f, 0x50, 0x71, 0x30, 0xe5, 0xfb, 0xdf,
0x7d, 0x74, 0x3a, 0xaa, 0x1b, 0xa6, 0x45, 0x37, 0x9e, 0xa0, 0xfe, 0x34, 0x8d, 0xd9, 0x4c, 0xe0,
0x73, 0xb2, 0xa3, 0x20, 0x45, 0xc9, 0x85, 0x6f, 0x0d, 0x52, 0x0d, 0x2e, 0x5a, 0x08, 0x29, 0x38,
0x93, 0xe0, 0xf4, 0xb0, 0x8b, 0x0e, 0xcc, 0xdd, 0x24, 0x8a, 0x70, 0x13, 0xbf, 0xac, 0x95, 0x4a,
0xa7, 0x0d, 0xa9, 0x9c, 0xeb, 0x90, 0x63, 0xd6, 0x18, 0x72, 0xcc, 0xba, 0x42, 0x1a, 0x62, 0x27,
0xa4, 0x56, 0xcd, 0x21, 0xb5, 0xea, 0x0c, 0x69, 0x90, 0xca, 0xe9, 0xa1, 0x23, 0x17, 0xa2, 0x0c,
0x64, 0xf2, 0xc6, 0xbf, 0x80, 0xe1, 0x6b, 0x4b, 0x57, 0x1d, 0x28, 0xed, 0x37, 0x9d, 0x5c, 0x35,
0xe2, 0x13, 0x1d, 0xbf, 0x82, 0x9a, 0x2d, 0x5f, 0xfe, 0x05, 0xcc, 0xeb, 0x49, 0x7c, 0x6b, 0x69,
0xde, 0x46, 0xca, 0x31, 0x67, 0x16, 0x72, 0x83, 0x39, 0xbd, 0xbb, 0x3d, 0xfc, 0x8e, 0x0e, 0x47,
0x61, 0x58, 0x5c, 0xe0, 0x4b, 0x0b, 0x5f, 0x55, 0x4b, 0xe9, 0x55, 0x3b, 0xb4, 0xbd, 0x9b, 0x05,
0xcf, 0x61, 0x2d, 0xb7, 0xef, 0x66, 0x03, 0xb4, 0xef, 0xa6, 0xce, 0x95, 0x23, 0x9e, 0xe9, 0xc7,
0xf0, 0xff, 0x9f, 0xe7, 0x49, 0xf8, 0x7e, 0x7f, 0xf5, 0x33, 0x1e, 0xfe, 0x02, 0x00, 0x00, 0xff,
0xff, 0x46, 0xba, 0x4a, 0xd2, 0x74, 0x03, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// AuthorizationServiceClient is the client API for AuthorizationService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type AuthorizationServiceClient interface {
SignUp(ctx context.Context, in *SignUpRequest, opts ...grpc.CallOption) (*SignUpResponse, error)
SignOff(ctx context.Context, in *SignOffRequest, opts ...grpc.CallOption) (*SignOffResponse, error)
SignIn(ctx context.Context, in *SignInRequest, opts ...grpc.CallOption) (*SignInResponse, error)
SignOut(ctx context.Context, in *SignOutRequest, opts ...grpc.CallOption) (*SignOutResponse, error)
RefreshToken(ctx context.Context, in *RefreshTokenRequest, opts ...grpc.CallOption) (*RefreshTokenResponse, error)
GetUserDevices(ctx context.Context, in *GetUserDevicesRequest, opts ...grpc.CallOption) (AuthorizationService_GetUserDevicesClient, error)
AddDevice(ctx context.Context, in *AddDeviceRequest, opts ...grpc.CallOption) (*AddDeviceResponse, error)
RemoveDevice(ctx context.Context, in *RemoveDeviceRequest, opts ...grpc.CallOption) (*RemoveDeviceResponse, error)
}
type authorizationServiceClient struct {
cc grpc.ClientConnInterface
}
func NewAuthorizationServiceClient(cc grpc.ClientConnInterface) AuthorizationServiceClient {
return &authorizationServiceClient{cc}
}
func (c *authorizationServiceClient) SignUp(ctx context.Context, in *SignUpRequest, opts ...grpc.CallOption) (*SignUpResponse, error) {
out := new(SignUpResponse)
err := c.cc.Invoke(ctx, "/ocf.cloud.auth.pb.AuthorizationService/SignUp", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authorizationServiceClient) SignOff(ctx context.Context, in *SignOffRequest, opts ...grpc.CallOption) (*SignOffResponse, error) {
out := new(SignOffResponse)
err := c.cc.Invoke(ctx, "/ocf.cloud.auth.pb.AuthorizationService/SignOff", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authorizationServiceClient) SignIn(ctx context.Context, in *SignInRequest, opts ...grpc.CallOption) (*SignInResponse, error) {
out := new(SignInResponse)
err := c.cc.Invoke(ctx, "/ocf.cloud.auth.pb.AuthorizationService/SignIn", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authorizationServiceClient) SignOut(ctx context.Context, in *SignOutRequest, opts ...grpc.CallOption) (*SignOutResponse, error) {
out := new(SignOutResponse)
err := c.cc.Invoke(ctx, "/ocf.cloud.auth.pb.AuthorizationService/SignOut", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authorizationServiceClient) RefreshToken(ctx context.Context, in *RefreshTokenRequest, opts ...grpc.CallOption) (*RefreshTokenResponse, error) {
out := new(RefreshTokenResponse)
err := c.cc.Invoke(ctx, "/ocf.cloud.auth.pb.AuthorizationService/RefreshToken", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authorizationServiceClient) GetUserDevices(ctx context.Context, in *GetUserDevicesRequest, opts ...grpc.CallOption) (AuthorizationService_GetUserDevicesClient, error) {
stream, err := c.cc.NewStream(ctx, &_AuthorizationService_serviceDesc.Streams[0], "/ocf.cloud.auth.pb.AuthorizationService/GetUserDevices", opts...)
if err != nil {
return nil, err
}
x := &authorizationServiceGetUserDevicesClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type AuthorizationService_GetUserDevicesClient interface {
Recv() (*UserDevice, error)
grpc.ClientStream
}
type authorizationServiceGetUserDevicesClient struct {
grpc.ClientStream
}
func (x *authorizationServiceGetUserDevicesClient) Recv() (*UserDevice, error) {
m := new(UserDevice)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *authorizationServiceClient) AddDevice(ctx context.Context, in *AddDeviceRequest, opts ...grpc.CallOption) (*AddDeviceResponse, error) {
out := new(AddDeviceResponse)
err := c.cc.Invoke(ctx, "/ocf.cloud.auth.pb.AuthorizationService/AddDevice", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authorizationServiceClient) RemoveDevice(ctx context.Context, in *RemoveDeviceRequest, opts ...grpc.CallOption) (*RemoveDeviceResponse, error) {
out := new(RemoveDeviceResponse)
err := c.cc.Invoke(ctx, "/ocf.cloud.auth.pb.AuthorizationService/RemoveDevice", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// AuthorizationServiceServer is the server API for AuthorizationService service.
type AuthorizationServiceServer interface {
SignUp(context.Context, *SignUpRequest) (*SignUpResponse, error)
SignOff(context.Context, *SignOffRequest) (*SignOffResponse, error)
SignIn(context.Context, *SignInRequest) (*SignInResponse, error)
SignOut(context.Context, *SignOutRequest) (*SignOutResponse, error)
RefreshToken(context.Context, *RefreshTokenRequest) (*RefreshTokenResponse, error)
GetUserDevices(*GetUserDevicesRequest, AuthorizationService_GetUserDevicesServer) error
AddDevice(context.Context, *AddDeviceRequest) (*AddDeviceResponse, error)
RemoveDevice(context.Context, *RemoveDeviceRequest) (*RemoveDeviceResponse, error)
}
// UnimplementedAuthorizationServiceServer can be embedded to have forward compatible implementations.
type UnimplementedAuthorizationServiceServer struct {
}
func (*UnimplementedAuthorizationServiceServer) SignUp(ctx context.Context, req *SignUpRequest) (*SignUpResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method SignUp not implemented")
}
func (*UnimplementedAuthorizationServiceServer) SignOff(ctx context.Context, req *SignOffRequest) (*SignOffResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method SignOff not implemented")
}
func (*UnimplementedAuthorizationServiceServer) SignIn(ctx context.Context, req *SignInRequest) (*SignInResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method SignIn not implemented")
}
func (*UnimplementedAuthorizationServiceServer) SignOut(ctx context.Context, req *SignOutRequest) (*SignOutResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method SignOut not implemented")
}
func (*UnimplementedAuthorizationServiceServer) RefreshToken(ctx context.Context, req *RefreshTokenRequest) (*RefreshTokenResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RefreshToken not implemented")
}
func (*UnimplementedAuthorizationServiceServer) GetUserDevices(req *GetUserDevicesRequest, srv AuthorizationService_GetUserDevicesServer) error {
return status.Errorf(codes.Unimplemented, "method GetUserDevices not implemented")
}
func (*UnimplementedAuthorizationServiceServer) AddDevice(ctx context.Context, req *AddDeviceRequest) (*AddDeviceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method AddDevice not implemented")
}
func (*UnimplementedAuthorizationServiceServer) RemoveDevice(ctx context.Context, req *RemoveDeviceRequest) (*RemoveDeviceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RemoveDevice not implemented")
}
func RegisterAuthorizationServiceServer(s *grpc.Server, srv AuthorizationServiceServer) {
s.RegisterService(&_AuthorizationService_serviceDesc, srv)
}
func _AuthorizationService_SignUp_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SignUpRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthorizationServiceServer).SignUp(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ocf.cloud.auth.pb.AuthorizationService/SignUp",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthorizationServiceServer).SignUp(ctx, req.(*SignUpRequest))
}
return interceptor(ctx, in, info, handler)
}
func _AuthorizationService_SignOff_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SignOffRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthorizationServiceServer).SignOff(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ocf.cloud.auth.pb.AuthorizationService/SignOff",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthorizationServiceServer).SignOff(ctx, req.(*SignOffRequest))
}
return interceptor(ctx, in, info, handler)
}
func _AuthorizationService_SignIn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SignInRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthorizationServiceServer).SignIn(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ocf.cloud.auth.pb.AuthorizationService/SignIn",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthorizationServiceServer).SignIn(ctx, req.(*SignInRequest))
}
return interceptor(ctx, in, info, handler)
}
func _AuthorizationService_SignOut_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SignOutRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthorizationServiceServer).SignOut(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ocf.cloud.auth.pb.AuthorizationService/SignOut",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthorizationServiceServer).SignOut(ctx, req.(*SignOutRequest))
}
return interceptor(ctx, in, info, handler)
}
func _AuthorizationService_RefreshToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RefreshTokenRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthorizationServiceServer).RefreshToken(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ocf.cloud.auth.pb.AuthorizationService/RefreshToken",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthorizationServiceServer).RefreshToken(ctx, req.(*RefreshTokenRequest))
}
return interceptor(ctx, in, info, handler)
}
func _AuthorizationService_GetUserDevices_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(GetUserDevicesRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(AuthorizationServiceServer).GetUserDevices(m, &authorizationServiceGetUserDevicesServer{stream})
}
type AuthorizationService_GetUserDevicesServer interface {
Send(*UserDevice) error
grpc.ServerStream
}
type authorizationServiceGetUserDevicesServer struct {
grpc.ServerStream
}
func (x *authorizationServiceGetUserDevicesServer) Send(m *UserDevice) error {
return x.ServerStream.SendMsg(m)
}
func _AuthorizationService_AddDevice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddDeviceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthorizationServiceServer).AddDevice(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ocf.cloud.auth.pb.AuthorizationService/AddDevice",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthorizationServiceServer).AddDevice(ctx, req.(*AddDeviceRequest))
}
return interceptor(ctx, in, info, handler)
}
func _AuthorizationService_RemoveDevice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RemoveDeviceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthorizationServiceServer).RemoveDevice(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ocf.cloud.auth.pb.AuthorizationService/RemoveDevice",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthorizationServiceServer).RemoveDevice(ctx, req.(*RemoveDeviceRequest))
}
return interceptor(ctx, in, info, handler)
}
var _AuthorizationService_serviceDesc = grpc.ServiceDesc{
ServiceName: "ocf.cloud.auth.pb.AuthorizationService",
HandlerType: (*AuthorizationServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "SignUp",
Handler: _AuthorizationService_SignUp_Handler,
},
{
MethodName: "SignOff",
Handler: _AuthorizationService_SignOff_Handler,
},
{
MethodName: "SignIn",
Handler: _AuthorizationService_SignIn_Handler,
},
{
MethodName: "SignOut",
Handler: _AuthorizationService_SignOut_Handler,
},
{
MethodName: "RefreshToken",
Handler: _AuthorizationService_RefreshToken_Handler,
},
{
MethodName: "AddDevice",
Handler: _AuthorizationService_AddDevice_Handler,
},
{
MethodName: "RemoveDevice",
Handler: _AuthorizationService_RemoveDevice_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "GetUserDevices",
Handler: _AuthorizationService_GetUserDevices_Handler,
ServerStreams: true,
},
},
Metadata: "github.com/plgd-dev/cloud/authorization/pb/service.proto",
}
|
jcgertig/react-native
|
Examples/UIExplorer/MapViewExample.js
|
<gh_stars>1-10
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
var React = require('react-native');
var StyleSheet = require('StyleSheet');
var {
MapView,
Text,
TextInput,
View,
} = React;
var MapRegionInput = React.createClass({
propTypes: {
region: React.PropTypes.shape({
latitude: React.PropTypes.number,
longitude: React.PropTypes.number,
latitudeDelta: React.PropTypes.number,
longitudeDelta: React.PropTypes.number,
}),
onChange: React.PropTypes.func.isRequired,
},
getInitialState: function() {
return {
latitude: 0,
longitude: 0,
latitudeDelta: 0,
longitudeDelta: 0,
};
},
componentWillReceiveProps: function(nextProps) {
this.setState(nextProps.region);
},
render: function() {
var region = this.state;
return (
<View>
<View style={styles.row}>
<Text>
{'Latitude'}
</Text>
<TextInput
value={'' + region.latitude}
style={styles.textInput}
onChange={this._onChangeLatitude}
/>
</View>
<View style={styles.row}>
<Text>
{'Longitude'}
</Text>
<TextInput
value={'' + region.longitude}
style={styles.textInput}
onChange={this._onChangeLongitude}
/>
</View>
<View style={styles.row}>
<Text>
{'Latitude delta'}
</Text>
<TextInput
value={'' + region.latitudeDelta}
style={styles.textInput}
onChange={this._onChangeLatitudeDelta}
/>
</View>
<View style={styles.row}>
<Text>
{'Longitude delta'}
</Text>
<TextInput
value={'' + region.longitudeDelta}
style={styles.textInput}
onChange={this._onChangeLongitudeDelta}
/>
</View>
<View style={styles.changeButton}>
<Text onPress={this._change}>
{'Change'}
</Text>
</View>
</View>
);
},
_onChangeLatitude: function(e) {
this.setState({latitude: parseFloat(e.nativeEvent.text)});
},
_onChangeLongitude: function(e) {
this.setState({longitude: parseFloat(e.nativeEvent.text)});
},
_onChangeLatitudeDelta: function(e) {
this.setState({latitudeDelta: parseFloat(e.nativeEvent.text)});
},
_onChangeLongitudeDelta: function(e) {
this.setState({longitudeDelta: parseFloat(e.nativeEvent.text)});
},
_change: function() {
this.props.onChange(this.state);
},
});
var MapViewExample = React.createClass({
getInitialState() {
return {
mapRegion: null,
mapRegionInput: null,
};
},
render() {
return (
<View>
<MapView
style={styles.map}
onRegionChange={this._onRegionChanged}
region={this.state.mapRegion}
/>
<MapRegionInput
onChange={this._onRegionInputChanged}
region={this.state.mapRegionInput}
/>
</View>
);
},
_onRegionChanged(region) {
this.setState({mapRegionInput: region});
},
_onRegionInputChanged(region) {
this.setState({
mapRegion: region,
mapRegionInput: region,
});
},
});
var styles = StyleSheet.create({
map: {
height: 150,
margin: 10,
borderWidth: 1,
borderColor: '#000000',
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
},
textInput: {
width: 150,
height: 20,
borderWidth: 0.5,
borderColor: '#aaaaaa',
fontSize: 13,
padding: 4,
},
changeButton: {
alignSelf: 'center',
marginTop: 5,
padding: 3,
borderWidth: 0.5,
borderColor: '#777777',
},
});
exports.title = '<MapView>';
exports.description = 'Base component to display maps';
exports.examples = [
{
title: 'Map',
render(): ReactElement { return <MapViewExample />; }
},
{
title: 'Map shows user location',
render() {
return <MapView style={styles.map} showsUserLocation={true} />;
}
}
];
|
tekktonic/programming
|
C/lisp/num.h
|
#ifndef STAS_NUM_H
#define STAS_NUM_H
#include <glib.h>
#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
#include "object.h"
#include "types.h"
#include "parsehelp.h"
Object *new_Num(gchar *str);
void del_Num(Object *num);
Object *ReadNum(FILE *fp);
void WriteNum(Object *num);
#endif
|
ma16/hantek_dso_2090
|
src/usbExt.h
|
/* BSD 2-Clause License, see github.com/ma16/hantek_dso_2090 */
#ifndef INCLUDE_usbExt_h
#define INCLUDE_usbExt_h
/* some useful extensions of libusb for this project (e.g. do-or-die) */
#include <libusb.h>
#include <stdbool.h>
/* do-or-die */
libusb_context* usbExt_init(void) ;
/* browse thru all usb devices and invoke the given callback on each;
the callback should return true to stop further calls;
returns true if browsing was prematurely stopped by callback */
bool usbExt_browse(libusb_context*,
bool(*callback)(void*,libusb_device*),
void *cb_data) ;
/* do-or-die */
libusb_device_handle* usbExt_open(libusb_device *device) ;
uint16_t usbExt_vendor (libusb_device *device) ;
uint16_t usbExt_product(libusb_device *device) ;
typedef struct
{
char s[32] ; /* 3 + 7*4 +1 */
/* a string of the form: /BUS ('.' PORT)* /
e.g. "1" or "2.1" or "1.2.3.4.1.2.3.4" */
}
UsbExt_Path ;
UsbExt_Path usbExt_path(libusb_device *device) ;
typedef struct
{
char s[8] ; /* 3+1+3 +1 */
/* a string of the form: /BUS ':' DEV_ADDR/ e.g. "2:42" */
}
UsbExt_Addr ;
UsbExt_Addr usbExt_addr(libusb_device *device) ;
libusb_device* usbExt_findAddr(libusb_context*,UsbExt_Addr const*) ;
libusb_device* usbExt_findPath(libusb_context*,UsbExt_Path const*) ;
libusb_device_handle* usbExt_openAddr(libusb_context*,UsbExt_Addr const*) ;
libusb_device_handle* usbExt_openPath(libusb_context*,UsbExt_Path const*) ;
#endif /* INCLUDE_usbExt_h */
|
neurodebian/htcondor
|
src/condor_soapshell/gsoap_soapshell.h
|
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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.
*
***************************************************************/
//gsoap condor service name: condorSoapshell
#import "gsoap_daemon_core_types.h"
#import "gsoap_daemon_core.h"
int condor__runCommandWithClassAd(struct condor__ClassAdStruct ad,
struct condor__runCommandWithClassAdResponse {
struct condor__ClassAdStructAndStatus response;
} & result);
int condor__runCommandWithString(char *adSerializedToString,
struct condor__runCommandWithStringResponse {
struct condor__StringAndStatus response;
} & result );
|
lpea/cppinclude
|
src/model_includes/test/suits/mi_test_analyzer_suits.cpp
|
#include "model_includes/test/fixtures/mi_test_model_includes_fixture.hpp"
#include "model_includes/test/fixtures/wrappers/mi_test_file_wrapper.hpp"
#include "model_includes/test/fixtures/wrappers/mi_test_include_wrapper.hpp"
#include "model_includes/test/fixtures/wrappers/mi_test_model_wrapper.hpp"
#include "model_includes/api/enums/mi_include_status.hpp"
#include "model_includes/api/enums/mi_include_type.hpp"
#include "model_includes/api/mi_model.hpp"
#include <boost/test/unit_test.hpp>
#include <std_fs>
/*------------------------------------------------------------------------------
TEST PLAN:
1. File locations
1.1 Current directory
1.2 Include directory
1.3 File with std library name in project
1.4 Include in local file
2. Include type
2.1 User
2.2 System
2.3 Mix
3. Include status
3.1 Resolved
3.2 Unresolved
3.3 Mix
3.4 Std lib
4. Ignored folders
4.1 Regular project
4.2 CMake project
5. Ignore system includes
6. Ignore files
6.1 Ignore destination
6.2 Ignore source
7. File extensions
7.1 Only C++ files
7.2 Analyze without extension
------------------------------------------------------------------------------*/
namespace model_includes::test
{
//------------------------------------------------------------------------------
// clazy:excludeall=non-pod-global-static
// NOLINTNEXTLINE(fuchsia-statically-constructed-objects,cert-err58-cpp)
BOOST_FIXTURE_TEST_SUITE( AnalyzerTests, ModelIncludesFixture )
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t1_1_file_in_current_directory )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string classAHppName{ "class_a.hpp" };
const std::string classACppName{ "class_a.cpp" };
const std::string mainCppName{ "main.cpp" };
const std::string classAHppPath{ projectDir + classAHppName };
const std::string classACppPath{ projectDir + classACppName };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject( mainCppName, "#include \"" + classAHppName + "\"" );
addFileToProject( classAHppName, "class A{ A(); };" );
addFileToProject(
classACppName, "#include \"" + classAHppName +
"\" \n"
"A::A(); \n" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 3 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHeader = model.findFile( classAHppPath );
BOOST_REQUIRE( classAHeader.isAvailable() );
{
BOOST_REQUIRE( classAHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classAHeader.checkIncludedByCount( 2 ) );
IncludeWrapper includedByMain =
classAHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
IncludeWrapper includedByClassA =
classAHeader.getIncludedBy( classACppPath );
BOOST_CHECK( includedByClassA.checkSource( classACppPath ) );
BOOST_CHECK( includedByClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByClassA.checkStatus( IncludeStatus::Resolved ) );
}
}
{
FileWrapper classACpp = model.findFile( classACppPath );
BOOST_REQUIRE( classACpp.isAvailable() );
{
BOOST_REQUIRE( classACpp.checkIncludesCount( 1 ) );
IncludeWrapper includeClassAToHeader = classACpp.getInclude( 0 );
BOOST_CHECK( includeClassAToHeader.checkSource( classACppPath ) );
BOOST_CHECK(
includeClassAToHeader.checkDestination( classAHppPath ) );
BOOST_CHECK( includeClassAToHeader.checkType( IncludeType::User ) );
BOOST_CHECK(
includeClassAToHeader.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( classACpp.checkIncludedByCount( 0 ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t1_2_file_in_include_directory )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string includeDir{ "/lib/" };
const std::string classAHppName{ "class_a.hpp" };
const std::string classACppName{ "class_a.cpp" };
const std::string mainCppName{ "main.cpp" };
const std::string classAHppPath{ includeDir + classAHppName };
const std::string classACppPath{ includeDir + classACppName };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addIncludePath( includeDir );
addFileToProject( mainCppName, "#include \"" + classAHppName + "\"" );
addFile( classAHppPath, "class A{ A(); };" );
addFile(
classACppPath, "#include \"" + classAHppName +
"\" \n"
"A::A(); \n" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHeader = model.findFile( classAHppPath );
BOOST_REQUIRE( classAHeader.isAvailable() );
{
BOOST_REQUIRE( classAHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classAHeader.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
classAHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t1_3_file_with_std_library_name_in_project )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string classLimitHppName{ "limits.h" };
const std::string classLimitCppName{ "limits.cpp" };
const std::string mainCppName{ "main.cpp" };
const std::string classAHppPath{ projectDir + classLimitHppName };
const std::string classACppPath{ projectDir + classLimitCppName };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject( mainCppName, "#include \"" + classLimitHppName + "\"" );
addFileToProject( classLimitHppName, "class A{ A(); };" );
addFileToProject(
classLimitCppName, "#include \"" + classLimitHppName +
"\" \n"
"A::A(); \n" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 3 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHeader = model.findFile( classAHppPath );
BOOST_REQUIRE( classAHeader.isAvailable() );
{
BOOST_REQUIRE( classAHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classAHeader.checkIncludedByCount( 2 ) );
IncludeWrapper includedByMain =
classAHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
IncludeWrapper includedByClassA =
classAHeader.getIncludedBy( classACppPath );
BOOST_CHECK( includedByClassA.checkSource( classACppPath ) );
BOOST_CHECK( includedByClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByClassA.checkStatus( IncludeStatus::Resolved ) );
}
}
{
FileWrapper classACpp = model.findFile( classACppPath );
BOOST_REQUIRE( classACpp.isAvailable() );
{
BOOST_REQUIRE( classACpp.checkIncludesCount( 1 ) );
IncludeWrapper includeClassAToHeader = classACpp.getInclude( 0 );
BOOST_CHECK( includeClassAToHeader.checkSource( classACppPath ) );
BOOST_CHECK(
includeClassAToHeader.checkDestination( classAHppPath ) );
BOOST_CHECK( includeClassAToHeader.checkType( IncludeType::User ) );
BOOST_CHECK(
includeClassAToHeader.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( classACpp.checkIncludedByCount( 0 ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t1_4_include_in_local_folder )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string includeDir{ "./i/" };
const std::string classIncludeHppName{ "class_i.hpp" };
const std::string classIncludeCppName{ "class_i.cpp" };
const std::string classIncludeHppPath{
projectDir + includeDir + classIncludeHppName };
const std::string classIncludeCppPath{
projectDir + includeDir + classIncludeCppName };
setProjectDir( projectDir );
addFile( classIncludeHppPath, "class I{ I(); };" );
addFile(
classIncludeCppPath, "#include \"" + includeDir + classIncludeHppName +
"\""
"I::I(){}" );
addIncludePath( "." );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper file = model.findFile( classIncludeHppPath );
BOOST_REQUIRE( file.isAvailable() );
{
BOOST_REQUIRE( file.checkIncludesCount( 0 ) );
BOOST_REQUIRE( file.checkIncludedByCount( 1 ) );
IncludeWrapper include = file.getIncludedBy( classIncludeCppPath );
BOOST_CHECK( include.checkSource( classIncludeCppPath ) );
BOOST_CHECK( include.checkDestination( classIncludeHppPath ) );
BOOST_CHECK( include.checkType( IncludeType::User ) );
BOOST_CHECK( include.checkStatus( IncludeStatus::Resolved ) );
}
}
{
FileWrapper file = model.findFile( classIncludeCppPath );
BOOST_REQUIRE( file.isAvailable() );
{
BOOST_REQUIRE( file.checkIncludesCount( 1 ) );
IncludeWrapper include = file.getInclude( 0 );
BOOST_CHECK( include.checkSource( classIncludeCppPath ) );
BOOST_CHECK( include.checkDestination( classIncludeHppPath ) );
BOOST_CHECK( include.checkType( IncludeType::User ) );
BOOST_CHECK( include.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( file.checkIncludedByCount( 0 ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t2_1_include_type_user )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string classAHppName{ "class_a.hpp" };
const std::string mainCppName{ "main.cpp" };
const std::string classAHppPath{ projectDir + classAHppName };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject( mainCppName, "#include \"" + classAHppName + "\"" );
addFile( classAHppPath, "class A{ A(){} };" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHeader = model.findFile( classAHppPath );
BOOST_REQUIRE( classAHeader.isAvailable() );
{
BOOST_REQUIRE( classAHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classAHeader.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
classAHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t2_2_include_type_system )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string systemName{ "iostream" };
const std::string mainCppName{ "main.cpp" };
const std::string & systemPath{ systemName };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject( mainCppName, "#include <" + systemName + ">" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToSystem = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToSystem.checkSource( mainCppPath ) );
BOOST_CHECK( includeMainToSystem.checkDestination( systemPath ) );
BOOST_CHECK( includeMainToSystem.checkType( IncludeType::System ) );
BOOST_CHECK(
includeMainToSystem.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper systemFile = model.findFile( systemPath );
BOOST_REQUIRE( systemFile.isAvailable() );
{
BOOST_REQUIRE( systemFile.checkIncludesCount( 0 ) );
BOOST_REQUIRE( systemFile.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
systemFile.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( systemPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::System ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t2_3_include_type_mix )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string systemName{ "iostream" };
const std::string userHeaderName{ "class_a.hpp" };
const std::string mainCppName{ "main.cpp" };
const std::string & systemPath{ systemName };
const std::string userHeaderPath{ projectDir + userHeaderName };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject(
mainCppName, "#include <" + systemName +
"> \n"
"#include \"" +
userHeaderName + "\" \n" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 3 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 2 ) );
IncludeWrapper includeMainToSystem = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToSystem.checkSource( mainCppPath ) );
BOOST_CHECK( includeMainToSystem.checkDestination( systemPath ) );
BOOST_CHECK( includeMainToSystem.checkType( IncludeType::System ) );
BOOST_CHECK(
includeMainToSystem.checkStatus( IncludeStatus::Resolved ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 1 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( userHeaderName ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Unresolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper systemFile = model.findFile( systemPath );
BOOST_REQUIRE( systemFile.isAvailable() );
{
BOOST_REQUIRE( systemFile.checkIncludesCount( 0 ) );
BOOST_REQUIRE( systemFile.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
systemFile.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( systemPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::System ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
}
}
{
FileWrapper userFile = model.findFile( userHeaderName );
BOOST_REQUIRE( userFile.isAvailable() );
{
BOOST_REQUIRE( userFile.checkIncludesCount( 0 ) );
BOOST_REQUIRE( userFile.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
userFile.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( userHeaderName ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Unresolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t3_1_include_status_resolved )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string userHeaderName{ "class_a.hpp" };
const std::string mainCppName{ "main.cpp" };
const std::string userHeaderPath{ projectDir + userHeaderName };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject( mainCppName, "#include \"" + userHeaderName + "\"" );
addFileToProject( userHeaderName, "class A{ A(){} }'" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( userHeaderPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper userFile = model.findFile( userHeaderPath );
BOOST_REQUIRE( userFile.isAvailable() );
{
BOOST_REQUIRE( userFile.checkIncludesCount( 0 ) );
BOOST_REQUIRE( userFile.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
userFile.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( userHeaderPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t3_2_include_status_unresolved )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string userHeaderName{ "class_a.hpp" };
const std::string mainCppName{ "main.cpp" };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject( mainCppName, "#include \"" + userHeaderName + "\"" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( userHeaderName ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Unresolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper userFile = model.findFile( userHeaderName );
BOOST_REQUIRE( userFile.isAvailable() );
{
BOOST_REQUIRE( userFile.checkIncludesCount( 0 ) );
BOOST_REQUIRE( userFile.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
userFile.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( userHeaderName ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Unresolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t3_3_include_status_mix )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string classAHeaderName{ "class_a.hpp" };
const std::string classBHeaderName{ "class_b.hpp" };
const std::string mainCppName{ "main.cpp" };
const std::string mainCppPath{ projectDir + mainCppName };
const std::string classAHeaderPath{ projectDir + classAHeaderName };
const std::string classBHeaderPath{ projectDir + classBHeaderName };
setProjectDir( projectDir );
addFileToProject(
mainCppName, "#include \"" + classAHeaderName +
"\" \n"
"#include \"" +
classBHeaderName + "\" \n" );
addFileToProject( classAHeaderName, "class A{ A(){} };" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 3 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 2 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( classAHeaderPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
IncludeWrapper includeMainToClassB = mainCpp.getInclude( 1 );
BOOST_CHECK( includeMainToClassB.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassB.checkDestination( classBHeaderName ) );
BOOST_CHECK( includeMainToClassB.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassB.checkStatus( IncludeStatus::Unresolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHeader = model.findFile( classAHeaderPath );
BOOST_REQUIRE( classAHeader.isAvailable() );
{
BOOST_REQUIRE( classAHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classAHeader.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
classAHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classAHeaderPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
}
}
{
FileWrapper classBHeader = model.findFile( classBHeaderName );
BOOST_REQUIRE( classBHeader.isAvailable() );
{
BOOST_REQUIRE( classBHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classBHeader.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
classBHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classBHeaderName ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Unresolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t3_4_include_status_std_lib )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string headerName{ "assert.h" };
const std::string mainCppName{ "main.cpp" };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject( mainCppName, "#include <" + headerName + ">" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK( includeMainToClassA.checkDestination( headerName ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::System ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper userFile = model.findFile( headerName );
BOOST_REQUIRE( userFile.isAvailable() );
{
BOOST_REQUIRE( userFile.checkIncludesCount( 0 ) );
BOOST_REQUIRE( userFile.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
userFile.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( headerName ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::System ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t4_1_ignored_folders_regular_project )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string ignoredDir{ "./i/" };
const std::string classAHppName{ "class_a.hpp" };
const std::string mainCppName{ "main.cpp" };
const std::string classIgnoreHppName{ "class_i.hpp" };
const std::string classIgnoreCppName{ "class_i.cpp" };
const std::string classAHppPath{ projectDir + classAHppName };
const std::string mainCppPath{ projectDir + mainCppName };
const std::string classIgnoreHppPath{
projectDir + ignoredDir + classIgnoreHppName };
const std::string classIgnoreCppPath{
projectDir + ignoredDir + classIgnoreCppName };
setProjectDir( projectDir );
addIgnoredDir( ignoredDir );
addFileToProject( mainCppName, "#include \"" + classAHppName + "\"" );
addFile( classAHppPath, "class A{ A(){} };" );
addFile( classIgnoreHppPath, "class I{ I(); };" );
addFile(
classIgnoreCppPath, "#include \"" + classIgnoreHppName +
"\""
"I::I(){}" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHeader = model.findFile( classAHppPath );
BOOST_REQUIRE( classAHeader.isAvailable() );
{
BOOST_REQUIRE( classAHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classAHeader.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
classAHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t4_2_ignored_folders_cmake_project )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string ignoredDir{ "./i/" };
const std::string classAHppName{ "class_a.hpp" };
const std::string mainCppName{ "main.cpp" };
const std::string classIgnoreHppName{ "class_i.hpp" };
const std::string classIgnoreCppName{ "class_i.cpp" };
const std::string classAHppPath{ projectDir + classAHppName };
const std::string mainCppPath{ projectDir + mainCppName };
const std::string classIgnoreHppPath{
projectDir + ignoredDir + classIgnoreHppName };
const std::string classIgnoreCppPath{
projectDir + ignoredDir + classIgnoreCppName };
setProjectDir( projectDir );
addIgnoredDir( ignoredDir );
addFileToProject( mainCppName, "#include \"" + classAHppName + "\"" );
addFile( classAHppPath, "class A{ A(){} };" );
addFile( classIgnoreHppPath, "class I{ I(); };" );
addFile(
classIgnoreCppPath, "#include \"" + classIgnoreHppName +
"\""
"I::I(){}" );
addFileToCmake( mainCppPath );
addFileToCmake( classIgnoreCppPath );
// Run
ModelWrapper model = analyzeCmake();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHeader = model.findFile( classAHppPath );
BOOST_REQUIRE( classAHeader.isAvailable() );
{
BOOST_REQUIRE( classAHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classAHeader.checkIncludedByCount( 1 ) );
IncludeWrapper includedByMain =
classAHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t5_ignore_system_includes )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string systemName{ "iostream" };
const std::string classA{ "classA.hpp" };
const std::string mainCppName{ "main.cpp" };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject(
mainCppName,
R"(
#include <iostream>
#include "classA.hpp"
)" );
setIgnoreSystemIncludes( true );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClass = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClass.checkSource( mainCppPath ) );
BOOST_CHECK( includeMainToClass.checkDestination( classA ) );
BOOST_CHECK( includeMainToClass.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClass.checkStatus( IncludeStatus::Unresolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t6_1_ignore_files_ignore_destination )
{
// Init
setProjectDir( "/test_project/" );
addFileToProject(
"main.cpp",
R"(
#include <boost/test/unit_test.hpp>
#include "lib/classA.hpp"
)" );
addFileFilter( "boost/.*" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( "/test_project/main.cpp" );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClass = mainCpp.getInclude( 0 );
BOOST_CHECK(
includeMainToClass.checkSource( "/test_project/main.cpp" ) );
BOOST_CHECK(
includeMainToClass.checkDestination( "lib/classA.hpp" ) );
BOOST_CHECK( includeMainToClass.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClass.checkStatus( IncludeStatus::Unresolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHpp = model.findFile( "lib/classA.hpp" );
BOOST_REQUIRE( classAHpp.isAvailable() );
{
BOOST_REQUIRE( classAHpp.checkIncludedByCount( 1 ) );
IncludeWrapper includeMainToClass =
classAHpp.getIncludedBy( "/test_project/main.cpp" );
BOOST_CHECK(
includeMainToClass.checkSource( "/test_project/main.cpp" ) );
BOOST_CHECK(
includeMainToClass.checkDestination( "lib/classA.hpp" ) );
BOOST_CHECK( includeMainToClass.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClass.checkStatus( IncludeStatus::Unresolved ) );
BOOST_REQUIRE( classAHpp.checkIncludesCount( 0 ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t6_2_ignore_files_ignore_source )
{
// Init
setProjectDir( "/test_project/" );
addFileToProject(
"main.cpp",
R"(
#include <boost/test/unit_test.hpp>
#include "lib/classA.hpp"
)" );
addFileToProject(
"lib_impl/classA.cpp",
R"(
#include "lib/classA.hpp"
)" );
addFileFilter( "boost/.*" );
addFileFilter( "lib_impl/.*" );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 2 ) );
{
FileWrapper mainCpp = model.findFile( "/test_project/main.cpp" );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClass = mainCpp.getInclude( 0 );
BOOST_CHECK(
includeMainToClass.checkSource( "/test_project/main.cpp" ) );
BOOST_CHECK(
includeMainToClass.checkDestination( "lib/classA.hpp" ) );
BOOST_CHECK( includeMainToClass.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClass.checkStatus( IncludeStatus::Unresolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHpp = model.findFile( "lib/classA.hpp" );
BOOST_REQUIRE( classAHpp.isAvailable() );
{
BOOST_REQUIRE( classAHpp.checkIncludedByCount( 1 ) );
IncludeWrapper includeMainToClass =
classAHpp.getIncludedBy( "/test_project/main.cpp" );
BOOST_CHECK(
includeMainToClass.checkSource( "/test_project/main.cpp" ) );
BOOST_CHECK(
includeMainToClass.checkDestination( "lib/classA.hpp" ) );
BOOST_CHECK( includeMainToClass.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClass.checkStatus( IncludeStatus::Unresolved ) );
BOOST_REQUIRE( classAHpp.checkIncludesCount( 0 ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t7_1_file_extensions_only_cpp_files )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string classAHppName{ "class_a.hpp" };
const std::string classACppName{ "class_a.cpp" };
const std::string cppHeaderName{ "header.hxx" };
const std::string notCppHeaderName{ "header.txt" };
const std::string mainCppName{ "main.cpp" };
const std::string classAHppPath{ projectDir + classAHppName };
const std::string classACppPath{ projectDir + classACppName };
const std::string cppHeaderPath{ projectDir + cppHeaderName };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject( mainCppName, "#include \"" + classAHppName + "\"" );
addFileToProject( cppHeaderName, "#include \"" + classAHppName + "\"" );
addFileToProject( notCppHeaderName, "#include \"" + classAHppName + "\"" );
addFileToProject( classAHppName, "class A{ A(); };" );
addFileToProject(
classACppName, "#include \"" + classAHppName +
"\" \n"
"A::A(); \n" );
addCppExtensions( { "*.cpp", "*.hpp", "*.hxx" } );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 4 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHeader = model.findFile( classAHppPath );
BOOST_REQUIRE( classAHeader.isAvailable() );
{
BOOST_REQUIRE( classAHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classAHeader.checkIncludedByCount( 3 ) );
IncludeWrapper includedByMain =
classAHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
IncludeWrapper includedByClassA =
classAHeader.getIncludedBy( classACppPath );
BOOST_CHECK( includedByClassA.checkSource( classACppPath ) );
BOOST_CHECK( includedByClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByClassA.checkStatus( IncludeStatus::Resolved ) );
}
}
{
FileWrapper classACpp = model.findFile( classACppPath );
BOOST_REQUIRE( classACpp.isAvailable() );
{
BOOST_REQUIRE( classACpp.checkIncludesCount( 1 ) );
IncludeWrapper includeClassAToHeader = classACpp.getInclude( 0 );
BOOST_CHECK( includeClassAToHeader.checkSource( classACppPath ) );
BOOST_CHECK(
includeClassAToHeader.checkDestination( classAHppPath ) );
BOOST_CHECK( includeClassAToHeader.checkType( IncludeType::User ) );
BOOST_CHECK(
includeClassAToHeader.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( classACpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper cppheaderFile = model.findFile( cppHeaderPath );
BOOST_REQUIRE( cppheaderFile.isAvailable() );
{
BOOST_REQUIRE( cppheaderFile.checkIncludesCount( 1 ) );
IncludeWrapper includeClassAToHeader =
cppheaderFile.getInclude( 0 );
BOOST_CHECK( includeClassAToHeader.checkSource( cppHeaderPath ) );
BOOST_CHECK(
includeClassAToHeader.checkDestination( classAHppPath ) );
BOOST_CHECK( includeClassAToHeader.checkType( IncludeType::User ) );
BOOST_CHECK(
includeClassAToHeader.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( cppheaderFile.checkIncludedByCount( 0 ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( t7_2_file_extensions_analyze_without_extension )
{
// Init
const std::string projectDir{ "/test_project/" };
const std::string classAHppName{ "class_a.hpp" };
const std::string classACppName{ "class_a.cpp" };
const std::string headerName{ "header" };
const std::string mainCppName{ "main.cpp" };
const std::string classAHppPath{ projectDir + classAHppName };
const std::string classACppPath{ projectDir + classACppName };
const std::string headerPath{ projectDir + headerName };
const std::string mainCppPath{ projectDir + mainCppName };
setProjectDir( projectDir );
addFileToProject( mainCppName, "#include \"" + classAHppName + "\"" );
addFileToProject( headerName, "#include \"" + classAHppName + "\"" );
addFileToProject( classAHppName, "class A{ A(); };" );
addFileToProject(
classACppName, "#include \"" + classAHppName +
"\" \n"
"A::A(); \n" );
addCppExtensions( { "*.cpp", "*.hpp" } );
setAnalyzeWithoutExtension( true );
// Run
ModelWrapper model = analyze();
// Check
BOOST_REQUIRE( model.isAvailable() );
BOOST_REQUIRE( model.checkFilesCount( 4 ) );
{
FileWrapper mainCpp = model.findFile( mainCppPath );
BOOST_REQUIRE( mainCpp.isAvailable() );
{
BOOST_REQUIRE( mainCpp.checkIncludesCount( 1 ) );
IncludeWrapper includeMainToClassA = mainCpp.getInclude( 0 );
BOOST_CHECK( includeMainToClassA.checkSource( mainCppPath ) );
BOOST_CHECK(
includeMainToClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includeMainToClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includeMainToClassA.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( mainCpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper classAHeader = model.findFile( classAHppPath );
BOOST_REQUIRE( classAHeader.isAvailable() );
{
BOOST_REQUIRE( classAHeader.checkIncludesCount( 0 ) );
BOOST_REQUIRE( classAHeader.checkIncludedByCount( 3 ) );
IncludeWrapper includedByMain =
classAHeader.getIncludedBy( mainCppPath );
BOOST_CHECK( includedByMain.checkSource( mainCppPath ) );
BOOST_CHECK( includedByMain.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByMain.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByMain.checkStatus( IncludeStatus::Resolved ) );
IncludeWrapper includedByClassA =
classAHeader.getIncludedBy( classACppPath );
BOOST_CHECK( includedByClassA.checkSource( classACppPath ) );
BOOST_CHECK( includedByClassA.checkDestination( classAHppPath ) );
BOOST_CHECK( includedByClassA.checkType( IncludeType::User ) );
BOOST_CHECK(
includedByClassA.checkStatus( IncludeStatus::Resolved ) );
}
}
{
FileWrapper classACpp = model.findFile( classACppPath );
BOOST_REQUIRE( classACpp.isAvailable() );
{
BOOST_REQUIRE( classACpp.checkIncludesCount( 1 ) );
IncludeWrapper includeClassAToHeader = classACpp.getInclude( 0 );
BOOST_CHECK( includeClassAToHeader.checkSource( classACppPath ) );
BOOST_CHECK(
includeClassAToHeader.checkDestination( classAHppPath ) );
BOOST_CHECK( includeClassAToHeader.checkType( IncludeType::User ) );
BOOST_CHECK(
includeClassAToHeader.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( classACpp.checkIncludedByCount( 0 ) );
}
}
{
FileWrapper headerFile = model.findFile( headerPath );
BOOST_REQUIRE( headerFile.isAvailable() );
{
BOOST_REQUIRE( headerFile.checkIncludesCount( 1 ) );
IncludeWrapper includeClassAToHeader = headerFile.getInclude( 0 );
BOOST_CHECK( includeClassAToHeader.checkSource( headerPath ) );
BOOST_CHECK(
includeClassAToHeader.checkDestination( classAHppPath ) );
BOOST_CHECK( includeClassAToHeader.checkType( IncludeType::User ) );
BOOST_CHECK(
includeClassAToHeader.checkStatus( IncludeStatus::Resolved ) );
BOOST_REQUIRE( headerFile.checkIncludedByCount( 0 ) );
}
}
}
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE_END()
//------------------------------------------------------------------------------
}
|
dispyfree/xhstt
|
base/file/Archive.h
|
/*
* File: Archive.h
*
* This class represents one archive, that is, a collection of instances plus a collection
* of solution groups.
*/
#ifndef ARCHIVE_H
#define ARCHIVE_H
extern "C"{
#include "khe.h"
}
#include "ArchiveMetaData.h"
#include "Instance.h"
#include <fstream>
namespace khe{
class SolutionGroup;
class Archive {
public:
using KheType = KHE_ARCHIVE;
Archive(std::ifstream &in);
Archive(const std::string &path);
Archive(const std::string &id, ArchiveMetaData data);
Archive(const Archive& orig);
Archive(KHE_ARCHIVE arc);
std::string getId() const;
ArchiveMetaData getMeta() const;
bool add(const Instance &inst);
void remove(const Instance &inst);
void write(bool with_reports, FILE *fp) const;
void write(const SolutionGroup &grp, bool with_reports, FILE *fp) const;
Instance getInstance(const std::string &id) const;
IR<Instance> getInstances() const;
SolutionGroup getSolutionGroup(const std::string &id) const;
IR<SolutionGroup> getSolutionGroups() const;
void setBack(void *back);
void *getBack() const {
return KheArchiveBack(archive);
}
operator KheType() const{
return archive;
}
protected:
KheType archive;
};
}
#endif /* ARCHIVE_H */
|
THE-STUDNET/front
|
src/app/shared/api/models/items_childs_model.js
|
<reponame>THE-STUDNET/front
angular.module('API')
.factory('items_childs_model',['abstract_model_service',function(abstract_model_service){
var service = new abstract_model_service({
outdated_timeout: 1000*60*60*2, // 2 hours.
cache_size: 40,
cache_model_prefix: 'itm.c.',
cache_list_name: 'itm.c.ids',
_method_get: 'item.getListId',
_buildGetParams: function( ids ){
return { parent_id: ids };
}
});
window.items_childs = service;
return service;
}]);
|
tgpethan/mc-beta-server
|
server/Packets/Packet50PreChunk.js
|
/*
========- Packet50PreChunk.js -=========
Created by Holly (tgpethan) (c) 2021
Licenced under MIT
========================================
*/
const Packet = require("./Packet.js");
class Packet50PreChunk extends Packet {
constructor(x = 0, z = 0, mode = true) {
super(0x32);
this.x = x;
this.z = z;
this.mode = mode;
}
writePacket() {
super.writePacket();
this.writer.writeInt(this.x);
this.writer.writeInt(this.z);
this.writer.writeBool(this.mode);
return this.toBuffer();
}
}
module.exports = Packet50PreChunk;
|
juanse1080/Project-front
|
src/views/Module/Show/components/index.js
|
export { default as Build } from './Build'
export { default as Detail } from './Detail'
|
the-nerbs/HexEdit
|
Tests/utils/AssertHelpers.h
|
#pragma once
#include <cstddef>
#include <sstream>
#include <string>
#include "catch.hpp"
namespace test
{
/// \brief Encapsulates the result of a test assertion and any message it may produce.
struct assert_result
{
bool passed; //!< True if the assertion passed, or false if not.
std::string message; //!< A message describing the result. Typically only set on failure.
assert_result()
: passed{ true }, message{}
{ }
explicit assert_result(bool passed)
: passed{ passed }, message{}
{ }
explicit assert_result(std::string message)
: passed{ false }, message{ std::move(message) }
{ }
assert_result(const assert_result&) = default;
assert_result(assert_result&&) = default;
explicit operator bool() const
{
return passed;
}
};
/// \brief Allows for converting types for assert messages.
template <typename T>
struct for_message
{
static T mutate(T t)
{
return t;
}
};
// print bytes as they're integer values, rather than their character values.
//TODO (cpp17): what about std::byte?
template <>
struct for_message<std::uint8_t>
{
static int mutate(std::uint8_t t)
{
return t;
}
};
/// \brief Determines if two arrays are equal.
///
/// \param expected A pointer to the expected data.
/// \param actual A pointer to the actual data.
/// \param length The number of elements to compare.
/// \param comparer An object defining the comparison.
///
/// \returns An object describing the result of the comparison.
template <typename T, typename Comparer = std::equal_to<T>>
assert_result areEqual(
const T* expected,
const T* actual,
std::size_t length,
Comparer comparer = Comparer{})
{
for (std::size_t i = 0; i < length; i++)
{
if (!comparer(expected[i], actual[i]))
{
std::stringstream buffer;
buffer << "Elements at index " << i << " are not equal. Expected<"
<< for_message<T>::mutate(expected[i]) << ">. Actual<"
<< for_message<T>::mutate(actual[i]) << ">.";
return assert_result{ buffer.str() };
}
}
return assert_result{};
}
/// \brief Determines if two arrays are equal.
///
/// \param expected A pointer to the expected data.
/// \param actual A pointer to the actual data.
/// \param length The number of elements to compare.
/// \param comparer An object defining the comparison.
///
/// \returns An object describing the result of the comparison.
template <typename T, std::size_t N, typename Comparer = std::equal_to<T>>
assert_result areEqual(
const T (&expected)[N],
const T* actual,
std::size_t length,
Comparer comparer = Comparer{})
{
using namespace std::string_literals;
if (length < N)
{
return assert_result{ "actual is shorter than expected."s };
}
return areEqual(&expected[0], actual, length, comparer);
}
/// \brief Determines if two arrays are equal.
///
/// \param expected A pointer to the expected data.
/// \param actual A pointer to the actual data.
/// \param comparer An object defining the comparison.
///
/// \returns An object describing the result of the comparison.
template <typename T, std::size_t N1, std::size_t N2, typename Comparer = std::equal_to<T>>
assert_result areEqual(
const T (&expected)[N1],
const T (&actual)[N2],
Comparer comparer = Comparer{})
{
using namespace std::string_literals;
if (N2 < N1)
{
return assert_result{ "actual is shorter than expected."s };
}
return areEqual(&expected[0], &actual[0], N1, comparer);
}
}
// override Catch2's stringification for assert_result.
// According to the docs, I should be able to override `operator<<` for this, but the
// `operator bool()` conversion seems to take precedence, even if declared explicit,
// meaning it always prints just true/false instead of the message. In case this is
// some compiler bug, the compiler I'm using is MSVC 19.29.30040
namespace Catch
{
template<>
struct StringMaker<test::assert_result>
{
static std::string convert(const test::assert_result& value)
{
return value.message;
}
};
}
|
rostockahoi/nitro
|
command/queue/queue.go
|
<reponame>rostockahoi/nitro
package queue
import (
"fmt"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/spf13/cobra"
"github.com/craftcms/nitro/pkg/config"
"github.com/craftcms/nitro/pkg/containerlabels"
"github.com/craftcms/nitro/pkg/terminal"
)
const exampleText = ` # execute the craft queue command for a site
nitro queue`
// NewCommand returns the command to run queue listen inside of a sites container. It will check if the
// current working directory is a known site and auto-select or prompt a user for a list of sites.
func NewCommand(home string, docker client.CommonAPIClient, output terminal.Outputer) *cobra.Command {
cmd := &cobra.Command{
Use: "queue",
Short: "Run a queue worker",
Example: exampleText,
RunE: func(cmd *cobra.Command, args []string) error {
// get the current working directory
wd, err := os.Getwd()
if err != nil {
return err
}
cfg, err := config.Load(home)
if err != nil {
return err
}
// create a filter for the environment
filter := filters.NewArgs()
filter.Add("label", containerlabels.Nitro)
// get a context aware list of sites
sites := cfg.ListOfSitesByDirectory(home, wd)
// create the options for the sites
var options []string
for _, s := range sites {
options = append(options, s.Hostname)
}
// check if we found a site
var site config.Site
switch len(sites) {
case 0:
// prompt for the site
selected, err := output.Select(cmd.InOrStdin(), "Select a site: ", options)
if err != nil {
return err
}
// set the site we selected
site = sites[selected]
// add the label to get the site
filter.Add("label", containerlabels.Host+"="+sites[selected].Hostname)
case 1:
output.Info("connecting to", sites[0].Hostname)
// set the site we selected
site = sites[0]
// add the label to get the site
filter.Add("label", containerlabels.Host+"="+sites[0].Hostname)
default:
// prompt for the site to ssh into
selected, err := output.Select(cmd.InOrStdin(), "Select a site: ", options)
if err != nil {
return err
}
// set the site we selected
site = sites[selected]
// add the label to get the site
filter.Add("label", containerlabels.Host+"="+sites[selected].Hostname)
}
// find the containers but limited to the site label
containers, err := docker.ContainerList(cmd.Context(), types.ContainerListOptions{Filters: filter, All: true})
if err != nil {
return err
}
// are there any containers??
if len(containers) == 0 {
return fmt.Errorf("unable to find an matching site")
}
// start the container if its not running
if containers[0].State != "running" {
for _, command := range cmd.Root().Commands() {
if command.Use == "start" {
if err := command.RunE(cmd, []string{}); err != nil {
return err
}
}
}
}
// get the container path
var commands []string
path := site.GetContainerPath()
if path != "" {
commands = []string{"php", fmt.Sprintf("%s/%s", path, "craft"), "queue/listen", "--verbose"}
} else {
commands = []string{"php", "craft", "queue/listen", "--verbose"}
}
output.Info("Listening for queue jobs…")
// create an exec
exec, err := docker.ContainerExecCreate(cmd.Context(), containers[0].ID, types.ExecConfig{
AttachStderr: true,
AttachStdout: true,
Cmd: commands,
})
if err != nil {
return err
}
// attach to the exec
resp, err := docker.ContainerExecAttach(cmd.Context(), exec.ID, types.ExecStartCheck{})
if err != nil {
return err
}
defer resp.Close()
done := make(chan error)
go func() {
_, err := stdcopy.StdCopy(cmd.OutOrStdout(), cmd.OutOrStderr(), resp.Reader)
done <- err
}()
select {
case err := <-done:
if err != nil {
return err
}
break
case <-cmd.Context().Done():
return cmd.Context().Err()
}
// get the exit code
exit, err := docker.ContainerExecInspect(cmd.Context(), exec.ID)
if err != nil {
return err
}
// do something with the exit code
output.Info(fmt.Sprintf("%d", exit.ExitCode))
return nil
},
}
return cmd
}
|
crud2/crud2
|
src/main/java/org/crud2/util/ClassNames.java
|
<filename>src/main/java/org/crud2/util/ClassNames.java
package org.crud2.util;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ClassNames {
private static Map<String, String> nameMap = new HashMap<>();
static {
nameMap.put(Integer.class.getSimpleName(), "int");
nameMap.put(String.class.getSimpleName(), "string");
nameMap.put(Date.class.getSimpleName(), "date");
nameMap.put(BigDecimal.class.getSimpleName(), "decimal");
nameMap.put(Long.class.getSimpleName(), "long");
}
public static String simple(Object obj) {
if (obj == null) return "null";
String name = obj.getClass().getSimpleName();
return nameMap.getOrDefault(name, name);
}
}
|
zealoussnow/chromium
|
third_party/blink/renderer/platform/loader/fetch/url_loader/web_url_loader_factory.cc
|
<reponame>zealoussnow/chromium
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/public/platform/web_url_loader_factory.h"
#include "base/check.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "third_party/blink/public/platform/web_back_forward_cache_loader_helper.h"
#include "third_party/blink/public/platform/web_url_loader.h"
using blink::scheduler::WebResourceLoadingTaskRunnerHandle;
namespace blink {
WebURLLoaderFactory::WebURLLoaderFactory(
scoped_refptr<network::SharedURLLoaderFactory> loader_factory,
const WebVector<WebString>& cors_exempt_header_list,
base::WaitableEvent* terminate_sync_load_event)
: loader_factory_(std::move(loader_factory)),
cors_exempt_header_list_(cors_exempt_header_list),
terminate_sync_load_event_(terminate_sync_load_event) {
DCHECK(loader_factory_);
}
WebURLLoaderFactory::WebURLLoaderFactory() = default;
WebURLLoaderFactory::~WebURLLoaderFactory() = default;
std::unique_ptr<WebURLLoader> WebURLLoaderFactory::CreateURLLoader(
const WebURLRequest& request,
std::unique_ptr<WebResourceLoadingTaskRunnerHandle>
freezable_task_runner_handle,
std::unique_ptr<WebResourceLoadingTaskRunnerHandle>
unfreezable_task_runner_handle,
CrossVariantMojoRemote<mojom::KeepAliveHandleInterfaceBase>
keep_alive_handle,
WebBackForwardCacheLoaderHelper back_forward_cache_loader_helper) {
DCHECK(freezable_task_runner_handle);
DCHECK(unfreezable_task_runner_handle);
return std::make_unique<WebURLLoader>(
cors_exempt_header_list_, terminate_sync_load_event_,
std::move(freezable_task_runner_handle),
std::move(unfreezable_task_runner_handle), loader_factory_,
std::move(keep_alive_handle), back_forward_cache_loader_helper);
}
} // namespace blink
|
xu5343/ffmpegtoolkit_CentOS7
|
gpac-0.7.1/modules/aac_in/faad_dec.c
|
<filename>gpac-0.7.1/modules/aac_in/faad_dec.c
/*
* GPAC - Multimedia Framework C SDK
*
* Authors: <NAME>
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / AAC reader module
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/setup.h>
#ifdef GPAC_HAS_FAAD
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#endif
#if !defined(__GNUC__)
# if defined(_WIN32_WCE) || defined (WIN32)
# pragma comment(lib, "libfaad")
# endif
#endif
#include <faad.h>
#include <gpac/modules/codec.h>
#include <gpac/constants.h>
#include <gpac/avparse.h>
typedef struct
{
faacDecHandle codec;
faacDecFrameInfo info;
u32 sample_rate, out_size, num_samples;
u8 num_channels;
/*no support for scalability in FAAD yet*/
u16 ES_ID;
Bool signal_mc;
Bool is_sbr;
char ch_reorder[16];
GF_ESD *esd;
} FAADDec;
#define FAADCTX() FAADDec *ctx = (FAADDec *) ifcg->privateStack
static GF_Err FAAD_AttachStream(GF_BaseDecoder *ifcg, GF_ESD *esd)
{
#ifndef GPAC_DISABLE_AV_PARSERS
GF_Err e;
GF_M4ADecSpecInfo a_cfg;
#endif
FAADCTX();
if (ctx->ES_ID && ctx->ES_ID!=esd->ESID) return GF_NOT_SUPPORTED;
if (!esd->decoderConfig->decoderSpecificInfo || !esd->decoderConfig->decoderSpecificInfo->dataLength) return GF_NON_COMPLIANT_BITSTREAM;
if (!ctx->esd) {
ctx->esd = esd;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CODEC, ("[FAAD] Attaching stream %d\n", esd->ESID));
}
if (ctx->codec) faacDecClose(ctx->codec);
ctx->codec = faacDecOpen();
if (!ctx->codec) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODEC, ("[FAAD] Error initializing decoder\n"));
return GF_IO_ERR;
}
#ifndef GPAC_DISABLE_AV_PARSERS
e = gf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg);
if (e) return e;
#endif
if (faacDecInit2(ctx->codec, (unsigned char *)esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, (unsigned long*)&ctx->sample_rate, (u8*)&ctx->num_channels) < 0)
{
#ifndef GPAC_DISABLE_AV_PARSERS
s8 res;
char *dsi, *s_base_object_type;
u32 dsi_len;
switch (a_cfg.base_object_type) {
case GF_M4A_AAC_MAIN:
s_base_object_type = gf_stringizer(GF_M4A_AAC_MAIN);
goto base_object_type_error;
case GF_M4A_AAC_LC:
s_base_object_type = gf_stringizer(GF_M4A_AAC_LC);
goto base_object_type_error;
case GF_M4A_AAC_SSR:
s_base_object_type = gf_stringizer(GF_M4A_AAC_SSR);
goto base_object_type_error;
case GF_M4A_AAC_LTP:
s_base_object_type = gf_stringizer(GF_M4A_AAC_LTP);
goto base_object_type_error;
case GF_M4A_AAC_SBR:
s_base_object_type = gf_stringizer(GF_M4A_AAC_SBR);
goto base_object_type_error;
case GF_M4A_AAC_PS:
s_base_object_type = gf_stringizer(GF_M4A_AAC_PS);
base_object_type_error: /*error case*/
GF_LOG(GF_LOG_WARNING, GF_LOG_CODEC, ("[FAAD] Error: unsupported %s format for stream %d - defaulting to AAC LC\n", s_base_object_type, esd->ESID));
default:
break;
}
a_cfg.base_object_type = GF_M4A_AAC_LC;
a_cfg.has_sbr = GF_FALSE;
a_cfg.nb_chan = a_cfg.nb_chan > 2 ? 1 : a_cfg.nb_chan;
gf_m4a_write_config(&a_cfg, &dsi, &dsi_len);
res = faacDecInit2(ctx->codec, (unsigned char *) dsi, dsi_len, (unsigned long *) &ctx->sample_rate, (u8 *) &ctx->num_channels);
gf_free(dsi);
if (res < 0)
#endif
{
GF_LOG(GF_LOG_ERROR, GF_LOG_CODEC, ("[FAAD] Error when initializing AAC decoder for stream %d\n", esd->ESID));
return GF_NOT_SUPPORTED;
}
}
#ifndef GPAC_DISABLE_AV_PARSERS
ctx->is_sbr = a_cfg.has_sbr;
#endif
ctx->num_samples = 1024;
ctx->out_size = 2 * ctx->num_samples * ctx->num_channels;
ctx->ES_ID = esd->ESID;
ctx->signal_mc = ctx->num_channels>2 ? GF_TRUE : GF_FALSE;
return GF_OK;
}
static GF_Err FAAD_DetachStream(GF_BaseDecoder *ifcg, u16 ES_ID)
{
FAADCTX();
if (ES_ID != ctx->ES_ID) return GF_BAD_PARAM;
if (ctx->codec) faacDecClose(ctx->codec);
ctx->codec = NULL;
ctx->ES_ID = 0;
ctx->sample_rate = ctx->out_size = ctx->num_samples = 0;
ctx->num_channels = 0;
return GF_OK;
}
static GF_Err FAAD_GetCapabilities(GF_BaseDecoder *ifcg, GF_CodecCapability *capability)
{
u32 i;
FAADCTX();
switch (capability->CapCode) {
/*not tested yet*/
case GF_CODEC_RESILIENT:
capability->cap.valueInt = 1;
break;
case GF_CODEC_OUTPUT_SIZE:
capability->cap.valueInt = ctx->out_size;
break;
case GF_CODEC_SAMPLERATE:
capability->cap.valueInt = ctx->sample_rate;
break;
case GF_CODEC_NB_CHAN:
capability->cap.valueInt = ctx->num_channels;
break;
case GF_CODEC_BITS_PER_SAMPLE:
capability->cap.valueInt = 16;
break;
case GF_CODEC_BUFFER_MIN:
capability->cap.valueInt = 4;
break;
case GF_CODEC_BUFFER_MAX:
capability->cap.valueInt = 12;
break;
/*by default AAC access unit lasts num_samples (timescale being sampleRate)*/
case GF_CODEC_CU_DURATION:
capability->cap.valueInt = ctx->num_samples;
break;
/*to refine, it seems that 4 bytes padding is not enough on all streams ?*/
case GF_CODEC_PADDING_BYTES:
capability->cap.valueInt = 8;
break;
case GF_CODEC_CHANNEL_CONFIG:
capability->cap.valueInt = 0;
for (i=0; i<ctx->num_channels; i++) {
switch (ctx->info.channel_position[i]) {
case FRONT_CHANNEL_CENTER:
capability->cap.valueInt |= GF_AUDIO_CH_FRONT_CENTER;
break;
case FRONT_CHANNEL_LEFT:
capability->cap.valueInt |= GF_AUDIO_CH_FRONT_LEFT;
break;
case FRONT_CHANNEL_RIGHT:
capability->cap.valueInt |= GF_AUDIO_CH_FRONT_RIGHT;
break;
case SIDE_CHANNEL_LEFT:
capability->cap.valueInt |= GF_AUDIO_CH_SIDE_LEFT;
break;
case SIDE_CHANNEL_RIGHT:
capability->cap.valueInt |= GF_AUDIO_CH_SIDE_RIGHT;
break;
case BACK_CHANNEL_LEFT:
capability->cap.valueInt |= GF_AUDIO_CH_BACK_LEFT;
break;
case BACK_CHANNEL_RIGHT:
capability->cap.valueInt |= GF_AUDIO_CH_BACK_RIGHT;
break;
case BACK_CHANNEL_CENTER:
capability->cap.valueInt |= GF_AUDIO_CH_BACK_CENTER;
break;
case LFE_CHANNEL:
capability->cap.valueInt |= GF_AUDIO_CH_LFE;
break;
default:
break;
}
}
break;
default:
capability->cap.valueInt = 0;
break;
}
return GF_OK;
}
static GF_Err FAAD_SetCapabilities(GF_BaseDecoder *ifcg, GF_CodecCapability capability)
{
/*return unsupported to avoid confusion by the player (like SR changing ...) */
return GF_NOT_SUPPORTED;
}
static s8 FAAD_GetChannelPos(FAADDec *ffd, u32 ch_cfg)
{
u32 i;
for (i=0; i<ffd->info.channels; i++) {
switch (ffd->info.channel_position[i]) {
case FRONT_CHANNEL_CENTER:
if (ch_cfg==GF_AUDIO_CH_FRONT_CENTER) return i;
break;
case FRONT_CHANNEL_LEFT:
if (ch_cfg==GF_AUDIO_CH_FRONT_LEFT) return i;
break;
case FRONT_CHANNEL_RIGHT:
if (ch_cfg==GF_AUDIO_CH_FRONT_RIGHT) return i;
break;
case SIDE_CHANNEL_LEFT:
if (ch_cfg==GF_AUDIO_CH_SIDE_LEFT) return i;
break;
case SIDE_CHANNEL_RIGHT:
if (ch_cfg==GF_AUDIO_CH_SIDE_RIGHT) return i;
break;
case BACK_CHANNEL_LEFT:
if (ch_cfg==GF_AUDIO_CH_BACK_LEFT) return i;
break;
case BACK_CHANNEL_RIGHT:
if (ch_cfg==GF_AUDIO_CH_BACK_RIGHT) return i;
break;
case BACK_CHANNEL_CENTER:
if (ch_cfg==GF_AUDIO_CH_BACK_CENTER) return i;
break;
case LFE_CHANNEL:
if (ch_cfg==GF_AUDIO_CH_LFE) return i;
break;
}
}
return -1;
}
static GF_Err FAAD_ProcessData(GF_MediaDecoder *ifcg,
char *inBuffer, u32 inBufferLength,
u16 ES_ID, u32 *CTS,
char *outBuffer, u32 *outBufferLength,
u8 PaddingBits, u32 mmlevel)
{
void *buffer;
unsigned short *conv_in, *conv_out;
u32 i, j;
FAADCTX();
/*check not using scalabilty*/
if (ctx->ES_ID != ES_ID) return GF_BAD_PARAM;
/*if late or seeking don't decode*/
switch (mmlevel) {
case GF_CODEC_LEVEL_SEEK:
// case GF_CODEC_LEVEL_DROP:
*outBufferLength = 0;
return GF_OK;
default:
break;
}
if (ctx->out_size > *outBufferLength) {
*outBufferLength = ctx->out_size;
return GF_BUFFER_TOO_SMALL;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CODEC, ("[FAAD] Decoding AU\n"));
buffer = faacDecDecode(ctx->codec, &ctx->info, (unsigned char *) inBuffer, inBufferLength);
if (ctx->info.error>0) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODEC, ("[FAAD] Error decoding AU %s\n", faacDecGetErrorMessage(ctx->info.error) ));
*outBufferLength = 0;
//reinit if error
FAAD_AttachStream((GF_BaseDecoder *)ifcg, ctx->esd);
return GF_NON_COMPLIANT_BITSTREAM;
}
if (!ctx->info.samples || !buffer || !ctx->info.bytesconsumed) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CODEC, ("[FAAD] empty/non complete AU\n"));
*outBufferLength = 0;
return GF_OK;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CODEC, ("[FAAD] AU decoded\n"));
/*FAAD froces us to decode a frame to get channel cfg*/
if (ctx->signal_mc) {
s32 ch, idx;
ctx->signal_mc = GF_FALSE;
idx = 0;
/*NOW WATCH OUT!! FAAD may very well decide to output more channels than indicated!!!*/
ctx->num_channels = ctx->info.channels;
/*get cfg*/
ch = FAAD_GetChannelPos(ctx, GF_AUDIO_CH_FRONT_LEFT);
if (ch>=0) {
ctx->ch_reorder[idx] = ch;
idx++;
}
ch = FAAD_GetChannelPos(ctx, GF_AUDIO_CH_FRONT_RIGHT);
if (ch>=0) {
ctx->ch_reorder[idx] = ch;
idx++;
}
ch = FAAD_GetChannelPos(ctx, GF_AUDIO_CH_FRONT_CENTER);
if (ch>=0) {
ctx->ch_reorder[idx] = ch;
idx++;
}
ch = FAAD_GetChannelPos(ctx, GF_AUDIO_CH_LFE);
if (ch>=0) {
ctx->ch_reorder[idx] = ch;
idx++;
}
ch = FAAD_GetChannelPos(ctx, GF_AUDIO_CH_BACK_LEFT);
if (ch>=0) {
ctx->ch_reorder[idx] = ch;
idx++;
}
ch = FAAD_GetChannelPos(ctx, GF_AUDIO_CH_BACK_RIGHT);
if (ch>=0) {
ctx->ch_reorder[idx] = ch;
idx++;
}
ch = FAAD_GetChannelPos(ctx, GF_AUDIO_CH_BACK_CENTER);
if (ch>=0) {
ctx->ch_reorder[idx] = ch;
idx++;
}
ch = FAAD_GetChannelPos(ctx, GF_AUDIO_CH_SIDE_LEFT);
if (ch>=0) {
ctx->ch_reorder[idx] = ch;
idx++;
}
ch = FAAD_GetChannelPos(ctx, GF_AUDIO_CH_SIDE_RIGHT);
if (ch>=0) {
ctx->ch_reorder[idx] = ch;
idx++;
}
*outBufferLength = ctx->out_size;
if (sizeof(short) * ctx->info.samples > *outBufferLength) {
*outBufferLength = ctx->out_size = (u32) (sizeof(short)*ctx->info.samples);
}
return GF_BUFFER_TOO_SMALL;
}
if (sizeof(short) * ctx->info.samples > *outBufferLength) {
*outBufferLength = (u32) (sizeof(short)*ctx->info.samples);
return GF_BUFFER_TOO_SMALL;
}
/*we assume left/right order*/
if (ctx->num_channels<=2) {
memcpy(outBuffer, buffer, sizeof(short)* ctx->info.samples);
*outBufferLength = (u32) (sizeof(short)*ctx->info.samples);
return GF_OK;
}
conv_in = (unsigned short *) buffer;
conv_out = (unsigned short *) outBuffer;
for (i=0; i<ctx->info.samples; i+=ctx->info.channels) {
for (j=0; j<ctx->info.channels; j++) {
conv_out[i + j] = conv_in[i + ctx->ch_reorder[j]];
}
}
*outBufferLength = (u32) (sizeof(short)*ctx->info.samples);
return GF_OK;
}
static const char *FAAD_GetCodecName(GF_BaseDecoder *ifcg)
{
FAADCTX();
if (ctx->is_sbr) return "FAAD2 " FAAD2_VERSION " SBR mode";
return "FAAD2 " FAAD2_VERSION;
}
static u32 FAAD_CanHandleStream(GF_BaseDecoder *dec, u32 StreamType, GF_ESD *esd, u8 PL)
{
#ifndef GPAC_DISABLE_AV_PARSERS
GF_M4ADecSpecInfo a_cfg;
#endif
/*audio decs*/
if (StreamType != GF_STREAM_AUDIO) return GF_CODEC_NOT_SUPPORTED;
/*media type query*/
if (!esd) return GF_CODEC_STREAM_TYPE_SUPPORTED;
switch (esd->decoderConfig->objectTypeIndication) {
/*MPEG2 aac*/
case GPAC_OTI_AUDIO_AAC_MPEG2_MP:
case GPAC_OTI_AUDIO_AAC_MPEG2_LCP:
case GPAC_OTI_AUDIO_AAC_MPEG2_SSRP:
/*MPEG4 aac*/
case GPAC_OTI_AUDIO_AAC_MPEG4:
break;
default:
return GF_CODEC_NOT_SUPPORTED;
}
/*this codec currently requires AAC config in ESD*/
if (!esd->decoderConfig->decoderSpecificInfo || !esd->decoderConfig->decoderSpecificInfo->data) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CODEC, ("[FAAD] DecoderSpecificInfo missing - cannot initialize\n"));
return GF_CODEC_NOT_SUPPORTED;
}
#ifndef GPAC_DISABLE_AV_PARSERS
if (gf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg) != GF_OK) return GF_CODEC_NOT_SUPPORTED;
switch (a_cfg.base_object_type) {
case GF_M4A_AAC_MAIN:
case GF_M4A_AAC_LC:
case GF_M4A_AAC_SSR:
case GF_M4A_AAC_LTP:
case GF_M4A_AAC_SBR:
return GF_CODEC_SUPPORTED;
case GF_M4A_ER_AAC_LC:
case GF_M4A_ER_AAC_LTP:
case GF_M4A_ER_AAC_SCALABLE:
case GF_M4A_ER_AAC_LD:
case GF_M4A_AAC_PS:
return GF_CODEC_MAYBE_SUPPORTED;
default:
return GF_CODEC_NOT_SUPPORTED;
}
#endif
return GF_CODEC_SUPPORTED;
}
GF_BaseDecoder *NewFAADDec()
{
GF_MediaDecoder *ifce;
FAADDec *dec;
GF_SAFEALLOC(ifce, GF_MediaDecoder);
if (!ifce) return NULL;
GF_SAFEALLOC(dec, FAADDec);
if (!dec) {
gf_free(dec);
return NULL;
}
GF_REGISTER_MODULE_INTERFACE(ifce, GF_MEDIA_DECODER_INTERFACE, "FAAD2 Decoder", "gpac distribution")
ifce->privateStack = dec;
/*setup our own interface*/
ifce->AttachStream = FAAD_AttachStream;
ifce->DetachStream = FAAD_DetachStream;
ifce->GetCapabilities = FAAD_GetCapabilities;
ifce->SetCapabilities = FAAD_SetCapabilities;
ifce->ProcessData = FAAD_ProcessData;
ifce->CanHandleStream = FAAD_CanHandleStream;
ifce->GetName = FAAD_GetCodecName;
return (GF_BaseDecoder *) ifce;
}
void DeleteFAADDec(GF_BaseDecoder *ifcg)
{
FAADCTX();
if (ctx->codec) faacDecClose(ctx->codec);
gf_free(ctx);
gf_free(ifcg);
}
#endif
|
rgcl/dgrid
|
test/data/createOrderedStore.js
|
define([
'dojo/_base/lang',
'./createSyncStore'
], function (lang, createSyncStore) {
return function createOrderedStore(kwArgs) {
// dstore already supports ordering w/ beforeId,
// but add a copy method to test optional feature supported by DnD
return createSyncStore(lang.mixin({
copy: function (object, options) {
// summary:
// Given an item already in the store, creates a copy of it.
// (i.e., shallow-clones the item sans id, then calls add)
var newObj = lang.mixin({}, object);
// Ensure unique ID by removing it from the cloned item
newObj[this.idProperty] = null;
return this.add(newObj, options);
}
}, kwArgs));
};
});
|
BerniWittmann/beachanmeldung
|
web/vueapp/src/utils/helpers.js
|
<filename>web/vueapp/src/utils/helpers.js
import moment from 'moment';
export function parseDate(dateString) {
return dateString ? moment(dateString, [moment.ISO_8601, 'DD.MM.YYYY']) : undefined;
}
export function parseDateToISOString(date) {
return date ? date.toISOString() : undefined;
}
export function getDateTimeByKey(obj, key) {
if (!obj || !key || !obj[key] || !moment(obj[key]).isValid()) {
return {
date: undefined,
time: undefined,
};
}
const datetime = obj[key];
return {
date: datetime.format('DD.MM.YYYY'),
time: datetime.format('HH:mm'),
};
}
export function checkObjectEmpty(obj) {
if (!obj) return true;
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
export function arrayUnion(arr1, arr2, equalityFunc) {
const union = [].concat(arr1);
arr2.forEach((obj) => {
const index = arr1.findIndex(single => equalityFunc(single, obj));
if (index < 0) {
union.push(obj);
} else {
union[index] = obj;
}
});
return union;
}
export function parseJwt(token) {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}
|
StanPlatinum/VMI-as-a-Service
|
xen-4.6.0/xen/arch/x86/cpu/vpmu.c
|
<filename>xen-4.6.0/xen/arch/x86/cpu/vpmu.c
/*
* vpmu.c: PMU virtualization for HVM domain.
*
* Copyright (c) 2007, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; If not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
*/
#include <xen/config.h>
#include <xen/sched.h>
#include <xen/xenoprof.h>
#include <xen/event.h>
#include <xen/guest_access.h>
#include <asm/regs.h>
#include <asm/types.h>
#include <asm/msr.h>
#include <asm/nmi.h>
#include <asm/p2m.h>
#include <asm/vpmu.h>
#include <asm/hvm/support.h>
#include <asm/hvm/vmx/vmx.h>
#include <asm/hvm/vmx/vmcs.h>
#include <asm/hvm/svm/svm.h>
#include <asm/hvm/svm/vmcb.h>
#include <asm/apic.h>
#include <public/pmu.h>
#include <xsm/xsm.h>
#include <compat/pmu.h>
CHECK_pmu_cntr_pair;
CHECK_pmu_data;
CHECK_pmu_params;
/*
* "vpmu" : vpmu generally enabled
* "vpmu=off" : vpmu generally disabled
* "vpmu=bts" : vpmu enabled and Intel BTS feature switched on.
*/
static unsigned int __read_mostly opt_vpmu_enabled;
unsigned int __read_mostly vpmu_mode = XENPMU_MODE_OFF;
unsigned int __read_mostly vpmu_features = 0;
static void parse_vpmu_param(char *s);
custom_param("vpmu", parse_vpmu_param);
static DEFINE_SPINLOCK(vpmu_lock);
static unsigned vpmu_count;
static DEFINE_PER_CPU(struct vcpu *, last_vcpu);
static void __init parse_vpmu_param(char *s)
{
switch ( parse_bool(s) )
{
case 0:
break;
default:
if ( !strcmp(s, "bts") )
vpmu_features |= XENPMU_FEATURE_INTEL_BTS;
else if ( *s )
{
printk("VPMU: unknown flag: %s - vpmu disabled!\n", s);
break;
}
/* fall through */
case 1:
/* Default VPMU mode */
vpmu_mode = XENPMU_MODE_SELF;
opt_vpmu_enabled = 1;
break;
}
}
void vpmu_lvtpc_update(uint32_t val)
{
struct vpmu_struct *vpmu;
struct vcpu *curr = current;
if ( likely(vpmu_mode == XENPMU_MODE_OFF) )
return;
vpmu = vcpu_vpmu(curr);
vpmu->hw_lapic_lvtpc = PMU_APIC_VECTOR | (val & APIC_LVT_MASKED);
/* Postpone APIC updates for PV(H) guests if PMU interrupt is pending */
if ( is_hvm_vcpu(curr) || !vpmu->xenpmu_data ||
!vpmu_is_set(vpmu, VPMU_CACHED) )
apic_write(APIC_LVTPC, vpmu->hw_lapic_lvtpc);
}
int vpmu_do_msr(unsigned int msr, uint64_t *msr_content,
uint64_t supported, bool_t is_write)
{
struct vcpu *curr = current;
struct vpmu_struct *vpmu;
const struct arch_vpmu_ops *ops;
int ret = 0;
if ( likely(vpmu_mode == XENPMU_MODE_OFF) ||
((vpmu_mode & XENPMU_MODE_ALL) &&
!is_hardware_domain(current->domain)) )
goto nop;
vpmu = vcpu_vpmu(curr);
ops = vpmu->arch_vpmu_ops;
if ( !ops )
goto nop;
if ( is_write && ops->do_wrmsr )
ret = ops->do_wrmsr(msr, *msr_content, supported);
else if ( !is_write && ops->do_rdmsr )
ret = ops->do_rdmsr(msr, msr_content);
else
goto nop;
/*
* We may have received a PMU interrupt while handling MSR access
* and since do_wr/rdmsr may load VPMU context we should save
* (and unload) it again.
*/
if ( !is_hvm_vcpu(curr) && vpmu->xenpmu_data &&
vpmu_is_set(vpmu, VPMU_CACHED) )
{
vpmu_set(vpmu, VPMU_CONTEXT_SAVE);
ops->arch_vpmu_save(curr, 0);
vpmu_reset(vpmu, VPMU_CONTEXT_SAVE | VPMU_CONTEXT_LOADED);
}
return ret;
nop:
if ( !is_write )
*msr_content = 0;
return 0;
}
static inline struct vcpu *choose_hwdom_vcpu(void)
{
unsigned idx;
if ( hardware_domain->max_vcpus == 0 )
return NULL;
idx = smp_processor_id() % hardware_domain->max_vcpus;
return hardware_domain->vcpu[idx];
}
void vpmu_do_interrupt(struct cpu_user_regs *regs)
{
struct vcpu *sampled = current, *sampling;
struct vpmu_struct *vpmu;
struct vlapic *vlapic;
u32 vlapic_lvtpc;
/*
* dom0 will handle interrupt for special domains (e.g. idle domain) or,
* in XENPMU_MODE_ALL, for everyone.
*/
if ( (vpmu_mode & XENPMU_MODE_ALL) ||
(sampled->domain->domain_id >= DOMID_FIRST_RESERVED) )
{
sampling = choose_hwdom_vcpu();
if ( !sampling )
return;
}
else
sampling = sampled;
vpmu = vcpu_vpmu(sampling);
if ( !vpmu->arch_vpmu_ops )
return;
/* PV(H) guest */
if ( !is_hvm_vcpu(sampling) || (vpmu_mode & XENPMU_MODE_ALL) )
{
const struct cpu_user_regs *cur_regs;
uint64_t *flags = &vpmu->xenpmu_data->pmu.pmu_flags;
domid_t domid;
if ( !vpmu->xenpmu_data )
return;
if ( is_pvh_vcpu(sampling) &&
!(vpmu_mode & XENPMU_MODE_ALL) &&
!vpmu->arch_vpmu_ops->do_interrupt(regs) )
return;
if ( vpmu_is_set(vpmu, VPMU_CACHED) )
return;
/* PV guest will be reading PMU MSRs from xenpmu_data */
vpmu_set(vpmu, VPMU_CONTEXT_SAVE | VPMU_CONTEXT_LOADED);
vpmu->arch_vpmu_ops->arch_vpmu_save(sampling, 1);
vpmu_reset(vpmu, VPMU_CONTEXT_SAVE | VPMU_CONTEXT_LOADED);
if ( has_hvm_container_vcpu(sampled) )
*flags = 0;
else
*flags = PMU_SAMPLE_PV;
if ( sampled == sampling )
domid = DOMID_SELF;
else
domid = sampled->domain->domain_id;
/* Store appropriate registers in xenpmu_data */
/* FIXME: 32-bit PVH should go here as well */
if ( is_pv_32bit_vcpu(sampling) )
{
/*
* 32-bit dom0 cannot process Xen's addresses (which are 64 bit)
* and therefore we treat it the same way as a non-privileged
* PV 32-bit domain.
*/
struct compat_pmu_regs *cmp;
cur_regs = guest_cpu_user_regs();
cmp = (void *)&vpmu->xenpmu_data->pmu.r.regs;
cmp->ip = cur_regs->rip;
cmp->sp = cur_regs->rsp;
cmp->flags = cur_regs->eflags;
cmp->ss = cur_regs->ss;
cmp->cs = cur_regs->cs;
if ( (cmp->cs & 3) > 1 )
*flags |= PMU_SAMPLE_USER;
}
else
{
struct xen_pmu_regs *r = &vpmu->xenpmu_data->pmu.r.regs;
if ( (vpmu_mode & XENPMU_MODE_SELF) )
cur_regs = guest_cpu_user_regs();
else if ( !guest_mode(regs) &&
is_hardware_domain(sampling->domain) )
{
cur_regs = regs;
domid = DOMID_XEN;
}
else
cur_regs = guest_cpu_user_regs();
r->ip = cur_regs->rip;
r->sp = cur_regs->rsp;
r->flags = cur_regs->eflags;
if ( !has_hvm_container_vcpu(sampled) )
{
r->ss = cur_regs->ss;
r->cs = cur_regs->cs;
if ( !(sampled->arch.flags & TF_kernel_mode) )
*flags |= PMU_SAMPLE_USER;
}
else
{
struct segment_register seg;
hvm_get_segment_register(sampled, x86_seg_cs, &seg);
r->cs = seg.sel;
hvm_get_segment_register(sampled, x86_seg_ss, &seg);
r->ss = seg.sel;
r->cpl = seg.attr.fields.dpl;
if ( !(sampled->arch.hvm_vcpu.guest_cr[0] & X86_CR0_PE) )
*flags |= PMU_SAMPLE_REAL;
}
}
vpmu->xenpmu_data->domain_id = domid;
vpmu->xenpmu_data->vcpu_id = sampled->vcpu_id;
if ( is_hardware_domain(sampling->domain) )
vpmu->xenpmu_data->pcpu_id = smp_processor_id();
else
vpmu->xenpmu_data->pcpu_id = sampled->vcpu_id;
vpmu->hw_lapic_lvtpc |= APIC_LVT_MASKED;
apic_write(APIC_LVTPC, vpmu->hw_lapic_lvtpc);
*flags |= PMU_CACHED;
vpmu_set(vpmu, VPMU_CACHED);
send_guest_vcpu_virq(sampling, VIRQ_XENPMU);
return;
}
/* HVM guests */
vlapic = vcpu_vlapic(sampling);
/* We don't support (yet) HVM dom0 */
ASSERT(sampling == sampled);
if ( !vpmu->arch_vpmu_ops->do_interrupt(regs) ||
!is_vlapic_lvtpc_enabled(vlapic) )
return;
vlapic_lvtpc = vlapic_get_reg(vlapic, APIC_LVTPC);
switch ( GET_APIC_DELIVERY_MODE(vlapic_lvtpc) )
{
case APIC_MODE_FIXED:
vlapic_set_irq(vlapic, vlapic_lvtpc & APIC_VECTOR_MASK, 0);
break;
case APIC_MODE_NMI:
sampling->nmi_pending = 1;
break;
}
}
void vpmu_do_cpuid(unsigned int input,
unsigned int *eax, unsigned int *ebx,
unsigned int *ecx, unsigned int *edx)
{
struct vpmu_struct *vpmu = vcpu_vpmu(current);
if ( vpmu->arch_vpmu_ops && vpmu->arch_vpmu_ops->do_cpuid )
vpmu->arch_vpmu_ops->do_cpuid(input, eax, ebx, ecx, edx);
}
static void vpmu_save_force(void *arg)
{
struct vcpu *v = (struct vcpu *)arg;
struct vpmu_struct *vpmu = vcpu_vpmu(v);
if ( !vpmu_is_set(vpmu, VPMU_CONTEXT_LOADED) )
return;
vpmu_set(vpmu, VPMU_CONTEXT_SAVE);
if ( vpmu->arch_vpmu_ops )
(void)vpmu->arch_vpmu_ops->arch_vpmu_save(v, 0);
vpmu_reset(vpmu, VPMU_CONTEXT_SAVE);
per_cpu(last_vcpu, smp_processor_id()) = NULL;
}
void vpmu_save(struct vcpu *v)
{
struct vpmu_struct *vpmu = vcpu_vpmu(v);
int pcpu = smp_processor_id();
if ( !vpmu_are_all_set(vpmu, VPMU_CONTEXT_ALLOCATED | VPMU_CONTEXT_LOADED) )
return;
vpmu->last_pcpu = pcpu;
per_cpu(last_vcpu, pcpu) = v;
if ( vpmu->arch_vpmu_ops )
if ( vpmu->arch_vpmu_ops->arch_vpmu_save(v, 0) )
vpmu_reset(vpmu, VPMU_CONTEXT_LOADED);
apic_write(APIC_LVTPC, PMU_APIC_VECTOR | APIC_LVT_MASKED);
}
int vpmu_load(struct vcpu *v, bool_t from_guest)
{
struct vpmu_struct *vpmu = vcpu_vpmu(v);
int pcpu = smp_processor_id();
struct vcpu *prev = NULL;
if ( !vpmu_is_set(vpmu, VPMU_CONTEXT_ALLOCATED) )
return 0;
/* First time this VCPU is running here */
if ( vpmu->last_pcpu != pcpu )
{
/*
* Get the context from last pcpu that we ran on. Note that if another
* VCPU is running there it must have saved this VPCU's context before
* startig to run (see below).
* There should be no race since remote pcpu will disable interrupts
* before saving the context.
*/
if ( vpmu_is_set(vpmu, VPMU_CONTEXT_LOADED) )
{
on_selected_cpus(cpumask_of(vpmu->last_pcpu),
vpmu_save_force, (void *)v, 1);
vpmu_reset(vpmu, VPMU_CONTEXT_LOADED);
}
}
/* Prevent forced context save from remote CPU */
local_irq_disable();
prev = per_cpu(last_vcpu, pcpu);
if ( prev != v && prev )
{
vpmu = vcpu_vpmu(prev);
/* Someone ran here before us */
vpmu_save_force(prev);
vpmu_reset(vpmu, VPMU_CONTEXT_LOADED);
vpmu = vcpu_vpmu(v);
}
local_irq_enable();
/* Only when PMU is counting, we load PMU context immediately. */
if ( !vpmu_is_set(vpmu, VPMU_RUNNING) ||
(!is_hvm_vcpu(vpmu_vcpu(vpmu)) && vpmu_is_set(vpmu, VPMU_CACHED)) )
return 0;
if ( vpmu->arch_vpmu_ops && vpmu->arch_vpmu_ops->arch_vpmu_load )
{
int ret;
apic_write_around(APIC_LVTPC, vpmu->hw_lapic_lvtpc);
/* Arch code needs to set VPMU_CONTEXT_LOADED */
ret = vpmu->arch_vpmu_ops->arch_vpmu_load(v, from_guest);
if ( ret )
{
apic_write_around(APIC_LVTPC,
vpmu->hw_lapic_lvtpc | APIC_LVT_MASKED);
return ret;
}
}
return 0;
}
void vpmu_initialise(struct vcpu *v)
{
struct vpmu_struct *vpmu = vcpu_vpmu(v);
uint8_t vendor = current_cpu_data.x86_vendor;
int ret;
bool_t is_priv_vpmu = is_hardware_domain(v->domain);
BUILD_BUG_ON(sizeof(struct xen_pmu_intel_ctxt) > XENPMU_CTXT_PAD_SZ);
BUILD_BUG_ON(sizeof(struct xen_pmu_amd_ctxt) > XENPMU_CTXT_PAD_SZ);
BUILD_BUG_ON(sizeof(struct xen_pmu_regs) > XENPMU_REGS_PAD_SZ);
BUILD_BUG_ON(sizeof(struct compat_pmu_regs) > XENPMU_REGS_PAD_SZ);
ASSERT(!vpmu->flags && !vpmu->context);
if ( !is_priv_vpmu )
{
/*
* Count active VPMUs so that we won't try to change vpmu_mode while
* they are in use.
* vpmu_mode can be safely updated while dom0's VPMUs are active and
* so we don't need to include it in the count.
*/
spin_lock(&vpmu_lock);
vpmu_count++;
spin_unlock(&vpmu_lock);
}
switch ( vendor )
{
case X86_VENDOR_AMD:
ret = svm_vpmu_initialise(v);
break;
case X86_VENDOR_INTEL:
ret = vmx_vpmu_initialise(v);
break;
default:
if ( vpmu_mode != XENPMU_MODE_OFF )
{
printk(XENLOG_G_WARNING "VPMU: Unknown CPU vendor %d. "
"Disabling VPMU\n", vendor);
opt_vpmu_enabled = 0;
vpmu_mode = XENPMU_MODE_OFF;
}
return; /* Don't bother restoring vpmu_count, VPMU is off forever */
}
if ( ret )
printk(XENLOG_G_WARNING "VPMU: Initialization failed for %pv\n", v);
/* Intel needs to initialize VPMU ops even if VPMU is not in use */
if ( !is_priv_vpmu &&
(ret || (vpmu_mode == XENPMU_MODE_OFF) ||
(vpmu_mode == XENPMU_MODE_ALL)) )
{
spin_lock(&vpmu_lock);
vpmu_count--;
spin_unlock(&vpmu_lock);
}
}
static void vpmu_clear_last(void *arg)
{
if ( this_cpu(last_vcpu) == arg )
this_cpu(last_vcpu) = NULL;
}
void vpmu_destroy(struct vcpu *v)
{
struct vpmu_struct *vpmu = vcpu_vpmu(v);
if ( !vpmu_is_set(vpmu, VPMU_CONTEXT_ALLOCATED) )
return;
/*
* Need to clear last_vcpu in case it points to v.
* We can check here non-atomically whether it is 'v' since
* last_vcpu can never become 'v' again at this point.
* We will test it again in vpmu_clear_last() with interrupts
* disabled to make sure we don't clear someone else.
*/
if ( per_cpu(last_vcpu, vpmu->last_pcpu) == v )
on_selected_cpus(cpumask_of(vpmu->last_pcpu),
vpmu_clear_last, v, 1);
if ( vpmu->arch_vpmu_ops && vpmu->arch_vpmu_ops->arch_vpmu_destroy )
{
/* Unload VPMU first. This will stop counters */
on_selected_cpus(cpumask_of(vcpu_vpmu(v)->last_pcpu),
vpmu_save_force, v, 1);
vpmu->arch_vpmu_ops->arch_vpmu_destroy(v);
}
spin_lock(&vpmu_lock);
if ( !is_hardware_domain(v->domain) )
vpmu_count--;
spin_unlock(&vpmu_lock);
}
static int pvpmu_init(struct domain *d, xen_pmu_params_t *params)
{
struct vcpu *v;
struct vpmu_struct *vpmu;
struct page_info *page;
uint64_t gfn = params->val;
if ( (vpmu_mode == XENPMU_MODE_OFF) ||
((vpmu_mode & XENPMU_MODE_ALL) && !is_hardware_domain(d)) )
return -EINVAL;
if ( (params->vcpu >= d->max_vcpus) || (d->vcpu[params->vcpu] == NULL) )
return -EINVAL;
page = get_page_from_gfn(d, gfn, NULL, P2M_ALLOC);
if ( !page )
return -EINVAL;
if ( !get_page_type(page, PGT_writable_page) )
{
put_page(page);
return -EINVAL;
}
v = d->vcpu[params->vcpu];
vpmu = vcpu_vpmu(v);
spin_lock(&vpmu->vpmu_lock);
if ( v->arch.vpmu.xenpmu_data )
{
spin_unlock(&vpmu->vpmu_lock);
put_page_and_type(page);
return -EEXIST;
}
v->arch.vpmu.xenpmu_data = __map_domain_page_global(page);
if ( !v->arch.vpmu.xenpmu_data )
{
spin_unlock(&vpmu->vpmu_lock);
put_page_and_type(page);
return -ENOMEM;
}
vpmu_initialise(v);
spin_unlock(&vpmu->vpmu_lock);
return 0;
}
static void pvpmu_finish(struct domain *d, xen_pmu_params_t *params)
{
struct vcpu *v;
struct vpmu_struct *vpmu;
uint64_t mfn;
void *xenpmu_data;
if ( (params->vcpu >= d->max_vcpus) || (d->vcpu[params->vcpu] == NULL) )
return;
v = d->vcpu[params->vcpu];
if ( v != current )
vcpu_pause(v);
vpmu = vcpu_vpmu(v);
spin_lock(&vpmu->vpmu_lock);
vpmu_destroy(v);
xenpmu_data = vpmu->xenpmu_data;
vpmu->xenpmu_data = NULL;
spin_unlock(&vpmu->vpmu_lock);
if ( xenpmu_data )
{
mfn = domain_page_map_to_mfn(xenpmu_data);
ASSERT(mfn_valid(mfn));
unmap_domain_page_global(xenpmu_data);
put_page_and_type(mfn_to_page(mfn));
}
if ( v != current )
vcpu_unpause(v);
}
/* Dump some vpmu informations on console. Used in keyhandler dump_domains(). */
void vpmu_dump(struct vcpu *v)
{
struct vpmu_struct *vpmu = vcpu_vpmu(v);
if ( vpmu->arch_vpmu_ops && vpmu->arch_vpmu_ops->arch_vpmu_dump )
vpmu->arch_vpmu_ops->arch_vpmu_dump(v);
}
long do_xenpmu_op(unsigned int op, XEN_GUEST_HANDLE_PARAM(xen_pmu_params_t) arg)
{
int ret;
struct vcpu *curr;
struct xen_pmu_params pmu_params = {.val = 0};
struct xen_pmu_data *xenpmu_data;
struct vpmu_struct *vpmu;
if ( !opt_vpmu_enabled )
return -EOPNOTSUPP;
ret = xsm_pmu_op(XSM_OTHER, current->domain, op);
if ( ret )
return ret;
/* Check major version when parameters are specified */
switch ( op )
{
case XENPMU_mode_set:
case XENPMU_feature_set:
case XENPMU_init:
case XENPMU_finish:
if ( copy_from_guest(&pmu_params, arg, 1) )
return -EFAULT;
if ( pmu_params.version.maj != XENPMU_VER_MAJ )
return -EINVAL;
}
switch ( op )
{
case XENPMU_mode_set:
{
if ( (pmu_params.val &
~(XENPMU_MODE_SELF | XENPMU_MODE_HV | XENPMU_MODE_ALL)) ||
(hweight64(pmu_params.val) > 1) )
return -EINVAL;
/* 32-bit dom0 can only sample itself. */
if ( is_pv_32bit_vcpu(current) &&
(pmu_params.val & (XENPMU_MODE_HV | XENPMU_MODE_ALL)) )
return -EINVAL;
spin_lock(&vpmu_lock);
/*
* We can always safely switch between XENPMU_MODE_SELF and
* XENPMU_MODE_HV while other VPMUs are active.
*/
if ( (vpmu_count == 0) ||
((vpmu_mode ^ pmu_params.val) ==
(XENPMU_MODE_SELF | XENPMU_MODE_HV)) )
vpmu_mode = pmu_params.val;
else if ( vpmu_mode != pmu_params.val )
{
printk(XENLOG_WARNING
"VPMU: Cannot change mode while active VPMUs exist\n");
ret = -EBUSY;
}
spin_unlock(&vpmu_lock);
break;
}
case XENPMU_mode_get:
memset(&pmu_params, 0, sizeof(pmu_params));
pmu_params.val = vpmu_mode;
pmu_params.version.maj = XENPMU_VER_MAJ;
pmu_params.version.min = XENPMU_VER_MIN;
if ( copy_to_guest(arg, &pmu_params, 1) )
ret = -EFAULT;
break;
case XENPMU_feature_set:
if ( pmu_params.val & ~XENPMU_FEATURE_INTEL_BTS )
return -EINVAL;
spin_lock(&vpmu_lock);
if ( (vpmu_count == 0) || (vpmu_features == pmu_params.val) )
vpmu_features = pmu_params.val;
else
{
printk(XENLOG_WARNING "VPMU: Cannot change features while"
" active VPMUs exist\n");
ret = -EBUSY;
}
spin_unlock(&vpmu_lock);
break;
case XENPMU_feature_get:
pmu_params.val = vpmu_features;
if ( copy_field_to_guest(arg, &pmu_params, val) )
ret = -EFAULT;
break;
case XENPMU_init:
ret = pvpmu_init(current->domain, &pmu_params);
break;
case XENPMU_finish:
pvpmu_finish(current->domain, &pmu_params);
break;
case XENPMU_lvtpc_set:
xenpmu_data = current->arch.vpmu.xenpmu_data;
if ( xenpmu_data != NULL )
vpmu_lvtpc_update(xenpmu_data->pmu.l.lapic_lvtpc);
else
ret = -EINVAL;
break;
case XENPMU_flush:
curr = current;
vpmu = vcpu_vpmu(curr);
xenpmu_data = curr->arch.vpmu.xenpmu_data;
if ( xenpmu_data == NULL )
return -EINVAL;
xenpmu_data->pmu.pmu_flags &= ~PMU_CACHED;
vpmu_reset(vpmu, VPMU_CACHED);
vpmu_lvtpc_update(xenpmu_data->pmu.l.lapic_lvtpc);
if ( vpmu_load(curr, 1) )
{
xenpmu_data->pmu.pmu_flags |= PMU_CACHED;
vpmu_set(vpmu, VPMU_CACHED);
ret = -EIO;
}
break ;
default:
ret = -EINVAL;
}
return ret;
}
static int __init vpmu_init(void)
{
int vendor = current_cpu_data.x86_vendor;
if ( !opt_vpmu_enabled )
{
printk(XENLOG_INFO "VPMU: disabled\n");
return 0;
}
/* NMI watchdog uses LVTPC and HW counter */
if ( opt_watchdog && opt_vpmu_enabled )
{
printk(XENLOG_WARNING "NMI watchdog is enabled. Turning VPMU off.\n");
opt_vpmu_enabled = 0;
vpmu_mode = XENPMU_MODE_OFF;
return 0;
}
switch ( vendor )
{
case X86_VENDOR_AMD:
if ( amd_vpmu_init() )
vpmu_mode = XENPMU_MODE_OFF;
break;
case X86_VENDOR_INTEL:
if ( core2_vpmu_init() )
vpmu_mode = XENPMU_MODE_OFF;
break;
default:
printk(XENLOG_WARNING "VPMU: Unknown CPU vendor: %d. "
"Turning VPMU off.\n", vendor);
vpmu_mode = XENPMU_MODE_OFF;
break;
}
if ( vpmu_mode != XENPMU_MODE_OFF )
printk(XENLOG_INFO "VPMU: version " __stringify(XENPMU_VER_MAJ) "."
__stringify(XENPMU_VER_MIN) "\n");
else
opt_vpmu_enabled = 0;
return 0;
}
__initcall(vpmu_init);
|
gecko10000/RedLib
|
src/redempt/redlib/worldgen/NoiseOctave.java
|
package redempt.redlib.worldgen;
import java.util.Random;
/**
* Used to generate noise values for octaves of Perlin Noise
* @author Redempt
*/
public class NoiseOctave {
private NoiseGenerator[] noise;
private double weight = 0;
/**
* Creates a noise octave with the given seed and size. All noise generators within this octave
* will be initialized with the seed plus their position inside this octave.
* @param seed The seed to use
* @param size The number of noise generators to use
*/
public NoiseOctave(long seed, int size) {
noise = new NoiseGenerator[size];
for (int i = 0; i < size; i++) {
noise[i] = new NoiseGenerator(seed + i);
}
weight = size;
}
/**
* Sets the seed of this noise octave.
* @param seed The seed to set
*/
public void setSeed(long seed) {
for (int i = 0; i < noise.length; i++) {
noise[i].setSeed(seed + i);
}
}
/**
* Creates a noise octave with a random seed
* @param size The number of noise generators to use
*/
public NoiseOctave(int size) {
this(new Random().nextLong(), size);
}
/**
* @return The size of this noise octave
*/
public int size() {
return noise.length;
}
/**
* Sets the scale of every noise generator in this octave
* @param scales A vararg of scales to set. The length of this vararg must be the same as the size of this
* noise octave.
*/
public void setScales(double... scales) {
if (scales.length != noise.length) {
throw new IllegalArgumentException("Number of scales passed is not equal to size of NoiseOctave");
}
for (int i = 0; i < noise.length; i++) {
noise[i].setScale(scales[i]);
}
}
/**
* Sets the weight of every noise generator in this octave
* @param weights A vararg of weights to set. The length of this vararg must be the same as the size of this
* noise octave.
*/
public void setWeights(double... weights) {
if (weights.length != noise.length) {
throw new IllegalArgumentException("Number of weights passed is not equal to size of NoiseOctave");
}
double total = 0;
for (int i = 0; i < noise.length; i++) {
noise[i].setWeight(weights[i]);
total += weights[i];
}
weight = total;
}
/**
* Pre-fills gradient vectors in the noise generators in this octave for the given region. Call this method
* whenever you know a region you will be repeatedly requesting noise values from, as it significantly
* increases performance.
* @param x The X coordinate to generate starting at
* @param z The Z coordinate to generate starting at
* @param width The width along the X-axis to fill
* @param length The length along the Z-axis to fill
*/
public void prefill(int x, int z, int width, int length) {
for (NoiseGenerator gen : noise) {
gen.prefill(x, z, width, length);
}
}
/**
* Pre-fills gradient vectors in the noise generators in this octave for the given region. Call this method
* whenever you know a region you will be repeatedly requesting noise values from, as it significantly
* increases performance.
* @param x The X coordinate to generate starting at
* @param y The Y coordinate to generate starting at
* @param z The Z coordinate to generate starting at
* @param width The width along the X-axis to fill
* @param height The height along the Y-axis to fill
* @param length The length along the Z-axis to fill
*/
public void prefill(int x, int y, int z, int width, int height, int length) {
for (NoiseGenerator gen : noise) {
gen.prefill(x, y, z, width, height, length);
}
}
/**
* Gets the noise value at the given point
* @param x The X coordinate to get noise at
* @param z The Z coordinate to get noise at
* @return A noise value between -1 and 1
*/
public double noise(double x, double z) {
double sum = 0;
for (NoiseGenerator gen : noise) {
sum += gen.noise(x, z);
}
return sum / weight;
}
/**
* Gets the noise value at the given point
* @param x The X coordinate to get noise at
* @param y The Y coordinate to get noise at
* @param z The Z coordinate to get noise at
* @return A noise value between -1 and 1
*/
public double noise(double x, double y, double z) {
double sum = 0;
for (NoiseGenerator gen : noise) {
sum += gen.noise(x, y, z);
}
return sum / weight;
}
}
|
domin1101/ANNHelper
|
include/LightBulb/Learning/Evolution/BestSelectionCommand.hpp
|
#pragma once
#ifndef _BESTSELECTIONCOMMAND_H_
#define _BESTSELECTIONCOMMAND_H_
// Library Includes
// Includes
#include "LightBulb/Learning/Evolution/AbstractSelectionCommand.hpp"
namespace LightBulb
{
/**
* \brief A command which selects the best N individuals for mutation/recombination
*/
class BestSelectionCommand : public AbstractSelectionCommand
{
private:
/**
* \brief The amount of individuals which should be selected
*/
int individualCount;
/**
* \brief Alternative: The percentage of individuals which should be selected
*/
double selectionPercentage;
public:
virtual ~BestSelectionCommand() {};
/**
* \brief Creates a command which selects a static amount of individuals.
* \param individualCount_ The amount of individuals.
*/
BestSelectionCommand(int individualCount_);
/**
* \brief Creates a command which selects a percentage of individuals.
* \param selectionPercentage_ The percentage of individuals.
*/
BestSelectionCommand(double selectionPercentage_);
// Inherited:
void execute(std::vector<std::pair<double, AbstractIndividual*>>& highscore, std::vector<AbstractIndividual*>& individual, std::vector<AbstractIndividual*>& notUsedIndividuals) override;
AbstractCloneable* clone() const override;
};
}
#endif
|
punchkub147/Thesis
|
src/model/needWork.js
|
<reponame>punchkub147/Thesis
db.collection('needWork').add({
employer_id: employer.employer_id,
work_id: work.work_id,
employee_id: user.uid,
name: `${user.data.fname} ${user.data.lname}`,
phone: user.data.phone,
pack: 1, //user ต้องการจำนวนกี่ชิ้น
deviceToken: user.data.deviceToken,
})
|
darthmaim/gw2builds
|
src/actions/import.js
|
import { createAction } from 'redux-actions';
export const SET_IMPORT_DIALOG_VISIBLE = 'SET_IMPORT_DIALOG_VISIBLE';
export const ADD_IMPORT_API_KEY = 'ADD_IMPORT_API_KEY';
export const REMOVE_IMPORT_API_KEY = 'REMOVE_IMPORT_API_KEY';
/** Action to set the visibility of the import dialog. Params: { visible } */
export const setImportDialogVisible = createAction(SET_IMPORT_DIALOG_VISIBLE);
/** Action to add a new API key for the import dialog. Params: { apiKey } */
export const addImportApiKey = createAction(ADD_IMPORT_API_KEY);
/** Action to remove a API key for the import dialog. Params: { apiKey } */
export const removeImportApiKey = createAction(REMOVE_IMPORT_API_KEY);
export default {
SET_IMPORT_DIALOG_VISIBLE,
ADD_IMPORT_API_KEY,
REMOVE_IMPORT_API_KEY,
setImportDialogVisible,
addImportApiKey,
removeImportApiKey
};
|
zerohope/OJcodes
|
src/leetcode/CourseSchedule207.java
|
package leetcode;
import java.util.*;
public class CourseSchedule207 {
public boolean canFinish(int numCourses, int[][] prerequisites) {
//List<Integer> sort=new ArrayList<>();
int canFin=0;
if(numCourses<=0)
return false;
//记录每个节点的入度
Map<Integer,Integer> inDegree=new HashMap<>();
//记录每个节点的子节点
Map<Integer,List<Integer>> children=new HashMap<>();
Queue<Integer> curNode=new LinkedList<>();
for(int i=0;i<numCourses;i++){
inDegree.put(i,0);
children.put(i,new ArrayList<Integer>());
}
for(int[] edge:prerequisites){
inDegree.put(edge[1],inDegree.get(edge[1])+1);
children.get(edge[0]).add(edge[1]);
}
for(Map.Entry<Integer,Integer> entry:inDegree.entrySet()){
if(entry.getValue()==0)
curNode.offer(entry.getKey());
}
while(!curNode.isEmpty()){
canFin++;
List<Integer> curChildren=children.get(curNode.poll());
for(int child:curChildren){
int degree=inDegree.get(child)-1;
inDegree.put(child,degree);
if(degree==0)
curNode.offer(child);
}
}
if(canFin!=numCourses)
return false;
return true;
}
}
|
r00ster91/serenity
|
Userland/Libraries/LibJS/Bytecode/Pass/PlaceBlocks.cpp
|
/*
* Copyright (c) 2021, <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Bytecode/PassManager.h>
namespace JS::Bytecode::Passes {
void PlaceBlocks::perform(PassPipelineExecutable& executable)
{
started();
VERIFY(executable.cfg.has_value());
auto cfg = executable.cfg.release_value();
Vector<BasicBlock&> replaced_blocks;
HashTable<BasicBlock const*> reachable_blocks;
// Visit the blocks in CFG order
Function<void(BasicBlock const*)> visit = [&](auto* block) {
if (reachable_blocks.contains(block))
return;
reachable_blocks.set(block);
replaced_blocks.append(*const_cast<BasicBlock*>(block));
for (auto& entry : cfg.get(block).value_or({}))
visit(entry);
};
// Make sure to visit the entry block first
visit(&executable.executable.basic_blocks.first());
for (auto& entry : cfg)
visit(entry.key);
// Put the unreferenced blocks back in at the end
for (auto& entry : static_cast<Vector<NonnullOwnPtr<BasicBlock>>&>(executable.executable.basic_blocks)) {
if (reachable_blocks.contains(entry.ptr()))
(void)entry.leak_ptr();
else
replaced_blocks.append(*entry.leak_ptr()); // Don't try to do DCE here.
}
executable.executable.basic_blocks.clear();
for (auto& block : replaced_blocks)
executable.executable.basic_blocks.append(adopt_own(block));
finished();
}
}
|
OreCruncher/OreLib
|
src/main/java/org/orecruncher/lib/expression/Function.java
|
/*
* Copyright 2012 <NAME>
* Copyright 2016 OreCruncher
*
* http://UdoJava.com/
* http://about.me/udo.klimaschewski
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
// Sourced from: https://github.com/uklimaschewski/EvalEx
package org.orecruncher.lib.expression;
/**
* Abstract definition of a supported expression function. A function is defined
* by a name, the number of parameters and the actual processing implementation.
*/
public abstract class Function extends LazyFunction {
public Function(final String name, final int numParams) {
super(name, numParams);
}
@Override
public LazyVariant lazyEval(final LazyVariant... lazyParams) {
final IVariant[] params = new IVariant[lazyParams.length];
for (int i = 0; i < lazyParams.length; i++)
params[i] = lazyParams[i].eval();
return () -> Function.this.eval(params);
}
/**
* Implementation for this function.
*
* @param params
* Parameters will be passed by the expression evaluator as an array
* of {@link Variant} values.
* @return The function must return a new {@link Variant} value as a computing
* result.
*/
public abstract IVariant eval(final IVariant... params);
}
|
eugeneilyin/mdi-norm
|
src/RoundHistory.js
|
<gh_stars>1-10
import React from 'react'
import { Icon } from './Icon'
import { lf, oj, ok } from './fragments'
export const RoundHistory = /*#__PURE__*/ props => <Icon {...props}>
<path d={"M13.26 3C8.17 2.86 4 6.95 4 12H2.21" + oj + "l2.79 2.8" + lf + "l2.79-2.8" + ok + "H6c0-3.9 3.18-7.05 7.1-7 3.72.05 6.85 3.18 6.9 6.9.05 3.91-3.1 7.1-7 7.1-1.61 0-3.1-.55-4.28-1.48-.4-.31-.96-.28-1.32.08-.42.42-.39 1.13.08 1.49C9 20.29 10.91 21 13 21c5.05 0 9.14-4.17 9-9.26-.13-4.69-4.05-8.61-8.74-8.74zm-.51 5c-.41 0-.75.34-.75.75v3.68c0 .35.19.68.49.86l3.12 1.85c.36.21.82.09 1.03-.26.21-.36.09-.82-.26-1.03l-2.88-1.71v-3.4c0-.4-.34-.74-.75-.74z"}/>
</Icon>
|
TiagoPedroByterev/openvpnclient-ios
|
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/asio/asiosignal.hpp
|
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// A simple class that allows an arbitrary set of posix signals to be
// associated with an Asio handler.
#ifndef OPENVPN_ASIO_ASIOSIGNAL_H
#define OPENVPN_ASIO_ASIOSIGNAL_H
#include <openvpn/io/io.hpp>
#include <openvpn/common/platform.hpp>
#include <openvpn/common/rc.hpp>
namespace openvpn {
class ASIOSignals : public RC<thread_safe_refcount>
{
public:
typedef RCPtr<ASIOSignals> Ptr;
ASIOSignals(openvpn_io::io_context& io_context)
: halt(false), signals_(io_context) {}
enum {
S_SIGINT = (1<<0),
S_SIGTERM = (1<<1),
#ifndef OPENVPN_PLATFORM_WIN
S_SIGQUIT = (1<<2),
S_SIGHUP = (1<<3),
S_SIGUSR1 = (1<<4),
S_SIGUSR2 = (1<<5),
#endif
};
template <typename SignalHandler>
void register_signals(SignalHandler stop_handler, unsigned int sigmask = (S_SIGINT|S_SIGTERM))
{
if (sigmask & S_SIGINT)
signals_.add(SIGINT);
if (sigmask & S_SIGTERM)
signals_.add(SIGTERM);
#ifndef OPENVPN_PLATFORM_WIN
if (sigmask & S_SIGQUIT)
signals_.add(SIGQUIT);
if (sigmask & S_SIGHUP)
signals_.add(SIGHUP);
if (sigmask & S_SIGUSR1)
signals_.add(SIGUSR1);
if (sigmask & S_SIGUSR2)
signals_.add(SIGUSR2);
#endif
signals_.async_wait(stop_handler);
}
template <typename SignalHandler>
void register_signals_all(SignalHandler stop_handler)
{
register_signals(stop_handler,
S_SIGINT
| S_SIGTERM
#ifndef OPENVPN_PLATFORM_WIN
| S_SIGHUP
| S_SIGUSR1
| S_SIGUSR2
#endif
);
}
void cancel()
{
if (!halt)
{
halt = true;
signals_.cancel();
}
}
private:
bool halt;
openvpn_io::signal_set signals_;
};
}
#endif
|
Ilmosal/StationTool
|
stationtool/dataEdit/dataEditField.py
|
"""
Module that contains all dataEditFields.
"""
from datetime import datetime
from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QLabel, QDateTimeEdit,
QDoubleSpinBox, QSpinBox, QLineEdit, QComboBox,
QFileDialog, QPushButton, QCheckBox,
QGridLayout)
from nordb.nordic.response import readResponseArrayToResponse
from pathlib import Path
from PyQt5.QtCore import Qt
from other.utils import qDate2Date, qDateTime2Datetime
class DataEditField(QWidget):
"""
Abstract class for all edit fields
"""
def __init__(self, parent, title, help_text, field):
super(QWidget, self).__init__()
self.label = QLabel(title)
self.help_text = help_text
self.layout = QHBoxLayout()
self.setFixedHeight(50)
self.field.setFixedWidth(220)
self.label.setAlignment(Qt.AlignRight)
self.layout.addWidget(self.label)
self.layout.addWidget(self.field)
self.setLayout(self.layout)
def enterEvent(self, event):
"""
Send the help text to the parent
"""
self.parent().parent().setHelpText(self.help_text)
def clearField(self):
"""
Clear the current field
"""
raise Exception("Default clearing method called! Please implement clearing for {0}".format(self.__class__.__name__))
def getValue(self):
"""
Get the value of the field
"""
raise Exception("getValue function not defined with class {0}".format(self.__class__.__name__))
class DateEditField(DataEditField):
"""
Class for editing date fields.
"""
def __init__(self, parent, title, help_text):
self.field = QDateTimeEdit(datetime.now().date())
self.field.setCalendarPopup(True)
self.field.setDisplayFormat("dd-MM-yyyy")
DataEditField.__init__(self, parent, title, help_text, self.field)
def clearField(self):
"""
Set field to current date
"""
self.field.setDate(datetime.now().date())
def getValue(self):
"""
Get value of DateEditField
"""
return qDate2Date(self.field.date())
class DatetimeEditField(DataEditField):
"""
Class for editing datetime fields.
"""
def __init__(self, parent, title, help_text):
self.field = QDateTimeEdit(datetime.now())
self.field.setCalendarPopup(True)
self.field.setDisplayFormat("dd-MM-yyyy hh:mm:ss")
DataEditField.__init__(self, parent, title, help_text, self.field)
def clearField(self):
"""
Set field to current datetime
"""
self.field.setDateTime(datetime.now())
def getValue(self):
"""
Get value of DateTimeEditField
"""
return qDateTime2Datetime(self.field.dateTime())
class FloatEditField(DataEditField):
"""
Class for editing float field.
"""
def __init__(self, parent, title, help_text, min_val = None, max_val = None, decimals = 4, default_val = None):
if default_val is None:
self.default_val = (min_val + max_val)/2
else:
self.default_val = default_val
self.field = QDoubleSpinBox()
self.field.setStyleSheet("background: white")
self.field.setDecimals(decimals)
if min_val is not None:
self.field.setMinimum(min_val)
else:
min_val = 0.0
if max_val is not None:
self.field.setMaximum(max_val)
else:
max_val = 0.0
self.field.setValue(self.default_val)
DataEditField.__init__(self, parent, title, help_text, self.field)
def clearField(self):
"""
Set float to default value
"""
self.field.setValue(self.default_val)
def getValue(self):
"""
Get the value of FloatEditField
"""
return self.field.value()
class IntegerEditField(DataEditField):
"""
Class for editing integer field.
"""
def __init__(self, parent, title, help_text, min_val = None, max_val = None, default_val = None):
self.field = QSpinBox()
self.field.setStyleSheet("background: white")
if min_val is not None:
self.field.setMinimum(min_val)
else:
min_val = 0
if max_val is not None:
self.field.setMaximum(max_val)
else:
max_val = 0
if default_val is None:
self.default_val = (min_val + max_val) / 2
else:
self.default_val = default_val
self.field.setValue(self.default_val)
DataEditField.__init__(self, parent, title, help_text, self.field)
def clearField(self):
"""
Set integer to default value
"""
self.field.setValue(self.default_val)
def getValue(self):
"""
Get the value of IntegerEditField
"""
return self.field.value()
class ResponseEditField(DataEditField):
"""
Field for picking up a response file
"""
def __init__(self, parent, title, help_text, database_api):
self.field = QLineEdit()
self.field.setReadOnly(True)
DataEditField.__init__(self, parent, title, help_text, self.field)
self.file_button = QPushButton('From file', self)
self.file_button.clicked.connect(self.readResponseFile)
self.db_button = QPushButton('From database', self)
self.db_button.clicked.connect(self.readResponseDB)
self.response = None
self.database_api = database_api
self.layout.addWidget(self.file_button)
self.layout.addWidget(self.db_button)
def readResponseFile(self):
"""
Function for reading a response file
"""
resp_filename = QFileDialog.getOpenFileName(self, "Open Response File", str(Path.home()), '')
try:
resp_file = open(resp_filename[0], 'r')
except:
print("Couldn't get any files from QFileDialog")
return
try:
response = readResponseArrayToResponse(resp_file.read().split('\n'), resp_filename[0].split('/')[-1])
except Exception as e:
response = None
print("Not a valid response file: {0}".format(e))
resp_file.close()
if response is not None:
self.setResponse(response)
def setResponse(self, response):
"""
Set the current response
"""
self.response = response
self.field.setText(response.file_name)
def readResponseDB(self):
"""
Function for reading the response from the database
"""
self.widget = ResponseFilePicker(self, self.database_api)
self.widget.show()
def clearField(self):
"""
Clear the response
"""
self.response = None
self.field.setText('')
def getValue(self):
return self.response
class StringEditField(DataEditField):
"""
Class for editing string fields
"""
def __init__(self, parent, title, help_text, max_len = None):
self.field = QLineEdit()
self.field.setStyleSheet("background: white")
if max_len is not None:
self.field.setMaxLength(max_len)
self.field.setText("")
DataEditField.__init__(self, parent, title, help_text, self.field)
def clearField(self):
"""
Clear string field value
"""
self.field.setText("")
def getValue(self):
"""
Get the value of StringEditField
"""
return self.field.text()
class CheckBoxEditField(DataEditField):
"""
Class for handling checkboxes
"""
def __init__(self, parent, title, help_text, choices):
self.field = CheckBoxFields(self, choices)
DataEditField.__init__(self, parent, title, help_text, self.field)
def clearField(self):
"""
Clear all the checkboxes in the CheckBoxFields class
"""
self.field.clearFields()
def getValue(self):
"""
get all the string values from the CheckBoxFields
"""
return self.field.getValues()
class CheckBoxFields(QWidget):
"""
Container for multiple checkboxes
"""
def __init__(self, parent, choices):
QWidget.__init__(self, parent)
self.layout = QHBoxLayout(self)
self.checkboxes = []
for choice in choices:
self.checkboxes.append(QCheckBox(choice, self))
for cbox in self.checkboxes:
self.layout.addWidget(cbox)
self.layout.setAlignment(Qt.AlignLeft)
def getValues(self):
"""
Get all values from the checkboxes
"""
result = []
for cbox in self.checkboxes:
if cbox.isChecked():
result.append(cbox.text())
return result
def clearFields(self):
"""
Clear all fields
"""
for cbox in self.checkboxes:
cbox.setChecked(False)
class ChoiceEditField(DataEditField):
"""
Class for editing choice fields
"""
def __init__(self, parent, title, help_text, choices):
self.field = QComboBox()
for c in choices:
self.field.addItem(c)
DataEditField.__init__(self, parent, title, help_text, self.field)
def clearField(self):
"""
Set choice edit field to its first value
"""
self.field.setCurrentIndex(0)
def getValue(self):
"""
Get the value of ChoiceEditField
"""
return self.field.currentText()
class ResponseFilePicker(QWidget):
"""
Window to picking a response from database
"""
def __init__(self, response_edit, database_api):
super().__init__()
self.response_edit = response_edit
self.database_api = database_api
self.setWindowTitle("Pick a response from database")
self.response_label = QLabel('Response', self)
self.response_names = set([ins.dfile for ins in self.database_api.getInstruments()])
self.response_box = QComboBox(self)
self.response_box.addItems(self.response_names)
self.cancel_btn = QPushButton('Cancel', self)
self.cancel_btn.clicked.connect(self.pressCancel)
self.add_btn = QPushButton('Add', self)
self.add_btn.clicked.connect(self.pressAdd)
self.layout = QGridLayout(self)
self.layout.addWidget(self.response_label, 0, 0)
self.layout.addWidget(self.response_box, 0, 1, 1, 2)
self.layout.addWidget(self.cancel_btn, 1, 1)
self.layout.addWidget(self.add_btn, 1, 2)
self.setLayout(self.layout)
def pressCancel(self):
"""
Cancel button is pressed
"""
self.close()
def pressAdd(self):
"""
Add button is pressed
"""
for ins in self.database_api.getInstruments():
if ins.dfile == self.response_box.currentText():
self.response_edit.setResponse(ins.response)
self.close()
|
VU-libtech/OLE-INST
|
ole-app/olefs/src/main/java/org/kuali/ole/module/purap/document/validation/impl/InvoiceGrandTotalOverZeroValidation.java
|
/*
* Copyright 2008-2009 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.ole.module.purap.document.validation.impl;
import org.kuali.ole.module.purap.PurapKeyConstants;
import org.kuali.ole.module.purap.PurapPropertyConstants;
import org.kuali.ole.module.purap.document.InvoiceDocument;
import org.kuali.ole.sys.OLEPropertyConstants;
import org.kuali.ole.sys.document.validation.GenericValidation;
import org.kuali.ole.sys.document.validation.event.AttributedDocumentEvent;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.krad.util.GlobalVariables;
public class InvoiceGrandTotalOverZeroValidation extends GenericValidation {
public boolean validate(AttributedDocumentEvent event) {
boolean valid = true;
InvoiceDocument document = (InvoiceDocument) event.getDocument();
GlobalVariables.getMessageMap().clearErrorPath();
GlobalVariables.getMessageMap().addToErrorPath(OLEPropertyConstants.DOCUMENT);
// The Grand Total Amount must be greater than zero.
if (document.getGrandTotal().compareTo(KualiDecimal.ZERO) <= 0) {
GlobalVariables.getMessageMap().putError(PurapPropertyConstants.GRAND_TOTAL, PurapKeyConstants.ERROR_PAYMENT_REQUEST_GRAND_TOTAL_NOT_POSITIVE);
valid &= false;
}
GlobalVariables.getMessageMap().clearErrorPath();
//always returns true, as this is a warning, not an error
return valid;
}
}
|
gardenhq/o
|
bin/o/main.js
|
<filename>bin/o/main.js
module.exports = function(services, combine, inject, register_o)
{
return function()
{
return Promise.all(
Object.values(services)
).then(
combine
).then(
inject
).then(
register_o
);
}
}
|
BadlionNetwork/BadlionClientModAPI
|
bungee/src/main/java/net/badlion/bungeeapi/BungeePluginMessageSender.java
|
<reponame>BadlionNetwork/BadlionClientModAPI
package net.badlion.bungeeapi;
import net.badlion.modapicommon.AbstractPluginMessageSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.protocol.packet.PluginMessage;
import java.util.UUID;
public class BungeePluginMessageSender extends AbstractPluginMessageSender {
private final BungeeBadlionPlugin apiBungee;
public BungeePluginMessageSender(BungeeBadlionPlugin apiBungee) {
this.apiBungee = apiBungee;
}
@Override
public void sendPluginMessage(byte[] data) {
for (ProxiedPlayer player : this.apiBungee.getProxy().getPlayers()) {
this.sendPluginMessagePacket(player, "badlion:modapi", data);
}
}
@Override
public void sendPluginMessage(UUID player, byte[] data) {
ProxiedPlayer proxiedPlayer = ProxyServer.getInstance().getPlayer(player);
if (proxiedPlayer != null) {
this.sendPluginMessagePacket(proxiedPlayer, "badlion:modapi", data);
}
}
public void sendPluginMessagePacket(ProxiedPlayer player, String channel, byte[] data) {
player.unsafe().sendPacket(new PluginMessage(channel, data, false));
}
}
|
world-bit/knowledge
|
backend/src/main/java/org/support/project/knowledge/control/api/internal/articles/AbstractArticleApi.java
|
<filename>backend/src/main/java/org/support/project/knowledge/control/api/internal/articles/AbstractArticleApi.java
package org.support.project.knowledge.control.api.internal.articles;
import java.lang.invoke.MethodHandles;
import org.support.project.common.log.Log;
import org.support.project.common.log.LogFactory;
import org.support.project.common.util.StringUtils;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.knowledge.logic.KnowledgeLogic;
import org.support.project.web.bean.MessageResult;
import org.support.project.web.common.HttpStatus;
import org.support.project.web.control.ApiControl;
import org.support.project.web.exception.InvalidParamException;
@DI(instance = Instance.Prototype)
public abstract class AbstractArticleApi extends ApiControl {
/** ログ */
private static final Log LOG = LogFactory.getLog(MethodHandles.lookup());
/**
* パスに設定されている記事のIDを取得
* @return
* @throws InvalidParamException
*/
protected Long getRouteArticleId() throws InvalidParamException {
String id = super.getRouteParam("id");
LOG.debug(id);
if (!StringUtils.isLong(id)) {
throw new InvalidParamException(new MessageResult(HttpStatus.SC_400_BAD_REQUEST, "BAD_REQUEST"));
}
long knowledgeId = Long.parseLong(id);
if (KnowledgeLogic.get().select(knowledgeId, getLoginedUser()) == null) {
// 存在しない or アクセス権無し
throw new InvalidParamException(new MessageResult(HttpStatus.SC_404_NOT_FOUND, "NOT_FOUND"));
}
return knowledgeId;
}
}
|
Mobile-APPs-Android/Dream-Team
|
Beergram/app/src/main/java/com/example/dreamteam/beergram/auth/login/LoginContract.java
|
package com.example.dreamteam.beergram.auth.login;
import com.example.dreamteam.beergram.BasePresenter;
import com.example.dreamteam.beergram.BaseView;
import com.example.dreamteam.beergram.utils.BeergramProgressDialog;
public interface LoginContract {
interface View extends BaseView<Presenter> {
void setDialog(BeergramProgressDialog progressDialog);
void showRegisterActivity();
void showResetPasswordActivity();
void showHomeActivity();
void showLogoutActivity();
void notifyLoggedInUser(String username);
void notoifyBadEmailOrPassword();
void showDialogForLoggingUser();
void showDialogForLoading();
void dismissDialog();
}
interface Presenter extends BasePresenter {
void loginUser(String email, String password);
void onResetPassword();
void onCreateAccount();
}
}
|
guicamest/bsoneer
|
examples/complex/src/main/java/com/sleepcamel/bsoneer/example/Dog.java
|
<filename>examples/complex/src/main/java/com/sleepcamel/bsoneer/example/Dog.java
package com.sleepcamel.bsoneer.example;
import java.util.List;
import com.sleepcamel.bsoneer.Bsonee;
@Bsonee
public class Dog<Q,U> {
Q q;
U u;
// TODO Do some magic to handle this case in BullDog
List<U> us;
}
|
mudechs/cotrack
|
start/kernel.js
|
<filename>start/kernel.js
'use strict';
/** @type {import('@adonisjs/framework/src/Server')} */
const Server = use('Server');
/*
|--------------------------------------------------------------------------
| Global Middleware
|--------------------------------------------------------------------------
|
| Global middleware are executed on each http request only when the routes
| match.
|
*/
const globalMiddleware = [
'Adonis/Middleware/BodyParser',
'Adonis/Middleware/Session',
'Adonis/Middleware/Shield',
'Adonis/Middleware/AuthInit',
'App/Middleware/ConvertEmptyStringsToNull',
'App/Middleware/TemplateHelper',
'App/Middleware/Setting'
];
/*
|--------------------------------------------------------------------------
| Named Middleware
|--------------------------------------------------------------------------
|
| Named middleware is key/value object to conditionally add middleware on
| specific routes or group of routes.
|
| // define
| {
| auth: 'Adonis/Middleware/Auth'
| }
|
| // use
| Route.get().middleware('auth')
|
*/
const namedMiddleware = {
auth: 'Adonis/Middleware/Auth',
authenticated: 'App/Middleware/Authenticated',
guest: 'Adonis/Middleware/AllowGuestOnly',
publicApi: 'App/Middleware/PublicApiAuth',
userOA: 'App/Middleware/UserOA',
projectCheck: 'App/Middleware/ProjectCheck',
ticketOFRAM: 'App/Middleware/TicketOFRAM',
ticketOA: 'App/Middleware/TicketOA',
isAdmin: 'App/Middleware/IsAdmin',
isSuperAdmin: 'App/Middleware/IsSuperAdmin',
mMode: 'App/Middleware/MaintenanceMode'
};
/*
|--------------------------------------------------------------------------
| Server Middleware
|--------------------------------------------------------------------------
|
| Server level middleware are executed even when route for a given URL is
| not registered. Features like `static assets` and `cors` needs better
| control over request lifecycle.
|
*/
const serverMiddleware = [
'Adonis/Middleware/Static',
'Adonis/Middleware/Cors'
];
Server
.registerGlobal(globalMiddleware)
.registerNamed(namedMiddleware)
.use(serverMiddleware);
|
Lauvak/ray
|
sample/06.CubeWorld/terrain_items.cpp
|
<reponame>Lauvak/ray
// +----------------------------------------------------------------------
// | Project : ray.
// | All rights reserved.
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015.
// +----------------------------------------------------------------------
// | * Redistribution and use of this software in source and binary forms,
// | with or without modification, are permitted provided that the following
// | conditions are met:
// |
// | * Redistributions of source code must retain the above
// | copyright notice, this list of conditions and the
// | following disclaimer.
// |
// | * Redistributions in binary form must reproduce the above
// | copyright notice, this list of conditions and the
// | following disclaimer in the documentation and/or other
// | materials provided with the distribution.
// |
// | * Neither the name of the ray team, nor the names of its
// | contributors may be used to endorse or promote products
// | derived from this software without specific prior
// | written permission of the ray team.
// |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// +----------------------------------------------------------------------
#include "terrain_items.h"
#include <ray/game_object_manager.h>
TerrainGrass::TerrainGrass() noexcept
{
_grass = std::make_shared<Grass>();
_grassObject = ray::GameObjectManager::instance()->findObject("grass");
this->addItem(_grass);
}
TerrainGrass::~TerrainGrass() noexcept
{
}
bool
TerrainGrass::create(TerrainChunk& chunk) noexcept
{
int size = chunk.size();
int half = size >> 1;
int _x, _y, _z;
chunk.getPosition(_x, _y, _z);
int offsetX = _x * size;
int offsetZ = _z * size;
for (int x = 0; x < size; x++)
{
for (int z = 0; z < size; z++)
{
int dx = offsetX + x;
int dz = offsetZ + z;
float f = ray::simplex2(dx * 0.01f, dz * 0.01f, 4, 0.5f, 2);
float g = ray::simplex2(-dx * 0.01f, -dz * 0.01f, 2, 0.9f, 2);
int h = f * (g * size + half);
for (int y = 0; y < h; y++)
{
TerrainData data;
data.x = x;
data.y = y;
data.z = z;
data.instanceID = _grass->getInstance();
chunk.set(data);
}
}
}
return true;
}
bool
TerrainGrass::createObject(TerrainChunk& chunk) noexcept
{
auto mesh = std::make_shared<ray::MeshProperty>();
for (auto& it : chunk.data())
{
if (it.empty() || it.instanceID != _grass->getInstance())
continue;
if (it.y <= 0)
continue;
VisiableFaces faces;
int total = this->visiable(chunk, it, faces);
if (total)
{
int dx = it.x << 1;
int dy = it.y << 1;
int dz = it.z << 1;
this->makeCube(mesh, faces, dx, dy, dz, 1);
}
}
if (mesh->getNumVertices())
{
mesh->computeTangents();
mesh->computeTangentQuats();
mesh->computeBoundingBox();
int mx, my, mz;
chunk.getPosition(mx, my, mz);
int size = chunk.size();
int offsetX = mx * size << 1;
int offsetY = my * size << 1;
int offsetZ = mz * size << 1;
auto gameObject = _grassObject->clone();
gameObject->setName(ray::format("chunk_%d_%d_%d") % offsetX % offsetY % offsetZ);
gameObject->setTranslate(ray::Vector3(offsetX, offsetY, offsetZ));
gameObject->getComponent<ray::MeshComponent>()->setMesh(mesh);
_object = gameObject;
return true;
}
return false;
}
bool
TerrainGrass::setActive(bool active) noexcept
{
if (_object)
{
if (active)
{
_object->setActive(true);
}
else
{
_object->setActive(false);
_object->setParent(nullptr);
}
return true;
}
else
{
return false;
}
}
bool
TerrainGrass::update(TerrainChunk& chunk) noexcept
{
_object->destroy();
_object = nullptr;
this->createObject(chunk);
this->setActive(true);
return true;
}
TerrainObjectPtr
TerrainGrass::clone() noexcept
{
auto result = std::make_shared<TerrainGrass>();
result->_grass = this->_grass;
return result;
}
TerrainTree::TerrainTree() noexcept
{
_wood = std::make_shared<Wood>();
_leaf = std::make_shared<Leaf>();
_woodObject = ray::GameObjectManager::instance()->findObject("wood");
_leafObject = ray::GameObjectManager::instance()->findObject("leaf");
this->addItem(_wood);
this->addItem(_leaf);
}
TerrainTree::~TerrainTree() noexcept
{
for (auto& it : _objects)
{
if (it)
{
it->destroy();
it = nullptr;
}
}
}
bool
TerrainTree::create(TerrainChunk& chunk) noexcept
{
int size = chunk.size();
int half = size >> 1;
int _x, _y, _z;
chunk.getPosition(_x, _y, _z);
int offsetX = _x * size;
int offsetZ = _z * size;
for (int x = 3; x < size - 3; x++)
{
for (int z = 3; z < size - 3; z++)
{
int dx = offsetX + x;
int dz = offsetZ + z;
if (ray::simplex2(dx, dz, 6, 0.5, 2) < 0.86)
continue;
float f = ray::simplex2(dx * 0.01f, dz * 0.01f, 4, 0.5f, 2);
float g = ray::simplex2(-dx * 0.01f, -dz * 0.01f, 2, 0.9f, 2);
int h = f * (g * size + half);
for (int y = h + 3; y < h + 8; y++)
{
for (int ox = -3; ox <= 3; ox++)
{
for (int oz = -3; oz <= 3; oz++)
{
int d = (ox * ox) + (oz * oz) + (y - (h + 4)) * (y - (h + 4));
if (d < 11)
{
TerrainData data;
data.x = x + ox;
data.y = y;
data.z = z + oz;
data.instanceID = _leaf->getInstance();
chunk.set(data);
}
}
}
}
for (int y = h; y < h + 7; y++)
{
TerrainData data;
data.x = x;
data.y = y;
data.z = z;
data.instanceID = _wood->getInstance();
chunk.set(data);
}
}
}
return true;
}
bool
TerrainTree::createObject(TerrainChunk& chunk) noexcept
{
auto woods = std::make_shared<ray::MeshProperty>();
auto leafs = std::make_shared<ray::MeshProperty>();
for (auto& it : chunk.data())
{
if (it.empty())
continue;
if (it.instanceID != _wood->getInstance() &&
it.instanceID != _leaf->getInstance())
continue;
VisiableFaces faces;
int total = this->visiable(chunk, it, faces);
if (total)
{
int dx = it.x << 1;
int dy = it.y << 1;
int dz = it.z << 1;
if (it.instanceID == _wood->getInstance())
this->makeCube(woods, faces, dx, dy, dz, 1);
if (it.instanceID == _leaf->getInstance())
this->makeCube(leafs, faces, dx, dy, dz, 1);
}
}
int mx, my, mz;
chunk.getPosition(mx, my, mz);
int size = chunk.size();
int offsetX = mx * size << 1;
int offsetY = my * size << 1;
int offsetZ = mz * size << 1;
if (woods->getNumVertices())
{
woods->computeTangents();
woods->computeTangentQuats();
woods->computeBoundingBox();
auto gameObject = _woodObject->clone();
gameObject->setName(ray::format("chunk_wood_%d_%d_%d") % offsetX % offsetY % offsetZ);
gameObject->setTranslate(ray::Vector3(offsetX, offsetY, offsetZ));
gameObject->getComponent<ray::MeshComponent>()->setMesh(woods);
_objects.push_back(gameObject);
}
if (leafs->getNumVertices())
{
leafs->computeTangents();
leafs->computeTangentQuats();
leafs->computeBoundingBox();
auto gameObject = _leafObject->clone();
gameObject->setName(ray::format("chunk_leaf_%d_%d_%d") % offsetX % offsetY % offsetZ);
gameObject->setTranslate(ray::Vector3(offsetX, offsetY, offsetZ));
gameObject->getComponent<ray::MeshComponent>()->setMesh(leafs);
_objects.push_back(gameObject);
}
if (!_objects.empty())
return true;
return false;
}
bool
TerrainTree::setActive(bool active) noexcept
{
for (auto& it : _objects)
{
if (active)
{
it->setActive(true);
}
else
{
it->setActive(false);
it->setParent(nullptr);
}
}
return true;
}
bool
TerrainTree::update(TerrainChunk& chunk) noexcept
{
return true;
}
TerrainObjectPtr
TerrainTree::clone() noexcept
{
auto result = std::make_shared<TerrainTree>();
result->_leaf = this->_leaf;
result->_wood = this->_wood;
return result;
}
TerrainClound::TerrainClound() noexcept
{
_clound = std::make_shared<Clound>();
_cloundObject = ray::GameObjectManager::instance()->findObject("clound");
this->addItem(_clound);
}
TerrainClound::~TerrainClound() noexcept
{
if (_object)
{
_object->destroy();
_object = nullptr;
}
}
bool
TerrainClound::create(TerrainChunk& chunk) noexcept
{
int size = chunk.size();
int _x, _y, _z;
chunk.getPosition(_x, _y, _z);
int offsetX = _x * size;
int offsetZ = _z * size;
for (int x = 0; x < size; x++)
{
for (int z = 0; z < size; z++)
{
int dx = offsetX + x;
int dz = offsetZ + z;
for (int y = 64; y < 72; y++)
{
if (ray::simplex3(dx * 0.01f, y * 0.1f, dz * 0.01f, 8, 0.5f, 2) > 0.75)
{
TerrainData data;
data.x = x;
data.y = y;
data.z = z;
data.instanceID = _clound->getInstance();
chunk.set(data);
}
}
}
}
return true;
}
bool
TerrainClound::createObject(TerrainChunk& chunk) noexcept
{
auto mesh = std::make_shared<ray::MeshProperty>();
for (auto& it : chunk.data())
{
if (it.empty())
continue;
if (it.instanceID != _clound->getInstance())
continue;
VisiableFaces faces;
int total = this->visiable(chunk, it, faces);
if (total)
{
int dx = it.x << 1;
int dy = it.y << 1;
int dz = it.z << 1;
this->makeCube(mesh, faces, dx, dy, dz, 1);
}
}
if (mesh->getNumVertices())
{
mesh->computeTangents();
mesh->computeTangentQuats();
mesh->computeBoundingBox();
int mx, my, mz;
chunk.getPosition(mx, my, mz);
int size = chunk.size();
int offsetX = mx * size << 1;
int offsetY = my * size << 1;
int offsetZ = mz * size << 1;
auto gameObject = _cloundObject->clone();
gameObject->setName(ray::format("chunk_%d_%d_%d") % offsetX % offsetY % offsetZ);
gameObject->setTranslate(ray::Vector3(offsetX, offsetY, offsetZ));
gameObject->getComponent<ray::MeshComponent>()->setMesh(mesh);
_object = gameObject;
return true;
}
return false;
}
bool
TerrainClound::setActive(bool active) noexcept
{
if (_object)
{
if (active)
{
_object->setActive(true);
}
else
{
_object->setActive(false);
_object->setParent(nullptr);
}
}
return true;
}
bool
TerrainClound::update(TerrainChunk& chunk) noexcept
{
return true;
}
TerrainObjectPtr
TerrainClound::clone() noexcept
{
auto result = std::make_shared<TerrainClound>();
result->_clound = this->_clound;
return result;
}
TerrainWater::TerrainWater() noexcept
{
_water = std::make_shared<Water>();
_waterObject = ray::GameObjectManager::instance()->findObject("water");
this->addItem(_water);
}
TerrainWater::~TerrainWater() noexcept
{
if (_object)
{
_object->destroy();
_object = nullptr;
}
}
bool
TerrainWater::create(TerrainChunk& chunk) noexcept
{
int size = chunk.size();
int half = size >> 1;
int _x, _y, _z;
chunk.getPosition(_x, _y, _z);
int offsetX = _x * size;
int offsetZ = _z * size;
for (int x = 0; x < size; x++)
{
for (int z = 0; z < size; z++)
{
int dx = offsetX + x;
int dz = offsetZ + z;
float f = ray::simplex2(dx * 0.01f, dz * 0.01f, 4, 0.5f, 2);
float g = ray::simplex2(-dx * 0.01f, -dz * 0.01f, 2, 0.9f, 2);
int h = f * (g * size + half);
if (h < 10)
{
for (int y = h; y < 10; y++)
{
TerrainData data;
data.x = x;
data.y = y;
data.z = z;
data.instanceID = _water->getInstance();
chunk.set(data);
}
}
}
}
return true;
}
bool
TerrainWater::createObject(TerrainChunk& chunk) noexcept
{
auto mesh = std::make_shared<ray::MeshProperty>();
for (auto& it : chunk.data())
{
if (it.empty())
continue;
if (it.instanceID != _water->getInstance())
continue;
VisiableFaces faces;
int total = this->visiable(chunk, it, faces);
if (total)
{
int dx = it.x << 1;
int dy = it.y << 1;
int dz = it.z << 1;
this->makeCube(mesh, faces, dx, dy, dz, 1);
}
}
if (mesh->getNumVertices())
{
mesh->computeTangents();
mesh->computeTangentQuats();
mesh->computeBoundingBox();
int mx, my, mz;
chunk.getPosition(mx, my, mz);
int size = chunk.size();
int offsetX = mx * size << 1;
int offsetY = my * size << 1;
int offsetZ = mz * size << 1;
auto gameObject = _waterObject->clone();
gameObject->setName(ray::format("chunk_%d_%d_%d") % offsetX % offsetY % offsetZ);
gameObject->setTranslate(ray::Vector3(offsetX, offsetY, offsetZ));
gameObject->getComponent<ray::MeshComponent>()->setMesh(mesh);
_object = gameObject;
return true;
}
return false;
}
bool
TerrainWater::setActive(bool active) noexcept
{
if (_object)
{
if (active)
{
_object->setActive(true);
}
else
{
_object->setActive(false);
_object->setParent(nullptr);
}
}
return true;
}
bool
TerrainWater::update(TerrainChunk& chunk) noexcept
{
return false;
}
TerrainObjectPtr
TerrainWater::clone() noexcept
{
auto result = std::make_shared<TerrainWater>();
result->_water = this->_water;
return result;
}
|
danglephuc/jp-postalcode-lookup
|
zipdata/zip-958.js
|
zipdata({
"9580000":[[15,15212,"村上市","ムラカミシ",152120000,""," ",""]],
"9580001":[[15,15212,"村上市","ムラカミシ",152120224,"馬下","マオロシ",""]],
"9580002":[[15,15212,"村上市","ムラカミシ",152120210,"早川","ハヤカワ",""]],
"9580003":[[15,15212,"村上市","ムラカミシ",152120250,"吉浦","ヨシウラ",""]],
"9580004":[[15,15212,"村上市","ムラカミシ",152120076,"柏尾","カシオ",""]],
"9580005":[[15,15212,"村上市","ムラカミシ",152120226,"間島","マジマ",""]],
"9580006":[[15,15212,"村上市","ムラカミシ",152120202,"野潟","ノガタ",""]],
"9580007":[[15,15212,"村上市","ムラカミシ",152120065,"大月","オオヅキ",""]],
"9580008":[[15,15212,"村上市","ムラカミシ",152120029,"岩ケ崎","イワガサキ",""]],
"9580011":[[15,15212,"村上市","ムラカミシ",152120167,"滝の前","タキノマエ",""]],
"9580012":[[15,15212,"村上市","ムラカミシ",152120061,"大平","オオダイラ",""]],
"9580013":[[15,15212,"村上市","ムラカミシ",152120206,"羽下ケ渕","ハゲガフチ",""]],
"9580014":[[15,15212,"村上市","ムラカミシ",152120112,"下渡","ゲド",""]],
"9580021":[[15,15212,"村上市","ムラカミシ",152120158,"瀬波新田町","セナミシンデンマチ",""]],
"9580022":[[15,15212,"村上市","ムラカミシ",152120161,"瀬波横町","セナミヨコマチ",""]],
"9580023":[[15,15212,"村上市","ムラカミシ",152120157,"瀬波上町","セナミカンマチ",""]],
"9580024":[[15,15212,"村上市","ムラカミシ",152120159,"瀬波中町","セナミナカマチ",""]],
"9580025":[[15,15212,"村上市","ムラカミシ",152120230,"松波町","マツナミチョウ",""]],
"9580026":[[15,15212,"村上市","ムラカミシ",152120160,"瀬波浜町","セナミハママチ",""]],
"9580031":[[15,15212,"村上市","ムラカミシ",152120081,"学校町","ガッコウチョウ",""]],
"9580032":[[15,15212,"村上市","ムラカミシ",152120231,"松原町","マツバラチョウ",""]],
"9580033":[[15,15212,"村上市","ムラカミシ",152120234,"緑町","ミドリマチ",""]],
"9580034":[[15,15212,"村上市","ムラカミシ",152120232,"松山","マツヤマ",""]],
"9580035":[[15,15212,"村上市","ムラカミシ",152120233,"三面","ミオモテ",""]],
"9580036":[[15,15212,"村上市","ムラカミシ",152120052,"浦田","ウラタ",""]],
"9580037":[[15,15212,"村上市","ムラカミシ",152120156,"瀬波温泉","セナミオンセン",""]],
"9580038":[[15,15212,"村上市","ムラカミシ",152120208,"浜新田","ハマシンデン",""]],
"9580041":[[15,15212,"村上市","ムラカミシ",152120045,"岩船三日市","イワフネミッカイチ",""]],
"9580042":[[15,15212,"村上市","ムラカミシ",152120038,"岩船北浜町","イワフネキタハママチ",""]],
"9580043":[[15,15212,"村上市","ムラカミシ",152120040,"岩船下大町","イワフネシモオオマチ",""]],
"9580044":[[15,15212,"村上市","ムラカミシ",152120034,"岩船上大町","イワフネカミオオマチ",""]],
"9580045":[[15,15212,"村上市","ムラカミシ",152120035,"岩船上浜町","イワフネカミハママチ",""]],
"9580046":[[15,15212,"村上市","ムラカミシ",152120041,"岩船下浜町","イワフネシモハママチ",""]],
"9580047":[[15,15212,"村上市","ムラカミシ",152120036,"岩船岸見寺町","イワフネガンゲンジマチ",""]],
"9580048":[[15,15212,"村上市","ムラカミシ",152120039,"岩船地蔵町","イワフネジゾウマチ",""]],
"9580051":[[15,15212,"村上市","ムラカミシ",152120037,"岩船上町","イワフネカンマチ",""]],
"9580052":[[15,15212,"村上市","ムラカミシ",152120249,"八日市","ヨウカイチ",""]],
"9580053":[[15,15212,"村上市","ムラカミシ",152120091,"上の山","カミノヤマ",""]],
"9580054":[[15,15212,"村上市","ムラカミシ",152120042,"岩船新田町","イワフネシンデンマチ",""]],
"9580055":[[15,15212,"村上市","ムラカミシ",152120043,"岩船縦新町","イワフネタテシンマチ",""]],
"9580056":[[15,15212,"村上市","ムラカミシ",152120044,"岩船中新町","イワフネナカシンマチ",""]],
"9580057":[[15,15212,"村上市","ムラカミシ",152120047,"岩船横新町","イワフネヨコシンマチ",""]],
"9580058":[[15,15212,"村上市","ムラカミシ",152120046,"岩船港町","イワフネミナトマチ",""]],
"9580061":[[15,15586,"岩船郡粟島浦村","イワフネグンアワシマウラムラ",155860000,""," ",""]],
"9580201":[[15,15212,"村上市","ムラカミシ",152120217,"蒲萄","ブドウ",""]],
"9580202":[[15,15212,"村上市","ムラカミシ",152120058,"大須戸","オオスド",""]],
"9580203":[[15,15212,"村上市","ムラカミシ",152120008,"荒沢","アラサワ",""]],
"9580204":[[15,15212,"村上市","ムラカミシ",152120120,"小須戸","コスド",""]],
"9580205":[[15,15212,"村上市","ムラカミシ",152120137,"塩野町","シオノマチ",""]],
"9580206":[[15,15212,"村上市","ムラカミシ",152120228,"松岡","マツオカ",""]],
"9580211":[[15,15212,"村上市","ムラカミシ",152120165,"高根","タカネ",""]],
"9580212":[[15,15212,"村上市","ムラカミシ",152120100,"北大平","キタオオダイラ",""]],
"9580213":[[15,15212,"村上市","ムラカミシ",152120254,"早稲田","ワセダ",""]],
"9580214":[[15,15212,"村上市","ムラカミシ",152120024,"板屋越","イタヤゴシ",""]],
"9580215":[[15,15212,"村上市","ムラカミシ",152120212,"檜原","ヒバラ",""]],
"9580221":[[15,15212,"村上市","ムラカミシ",152120122,"薦川","コモガワ",""]],
"9580222":[[15,15212,"村上市","ムラカミシ",152120134,"猿田","サルタ",""]],
"9580223":[[15,15212,"村上市","ムラカミシ",152120190,"中原","ナカハラ",""]],
"9580224":[[15,15212,"村上市","ムラカミシ",152120110,"黒田","クロダ",""]],
"9580225":[[15,15212,"村上市","ムラカミシ",152120155,"関口","セキグチ",""]],
"9580226":[[15,15212,"村上市","ムラカミシ",152120003,"朝日中野","アサヒナカノ",""]],
"9580231":[[15,15212,"村上市","ムラカミシ",152120200,"布部","ヌノベ",""]],
"9580232":[[15,15212,"村上市","ムラカミシ",152120012,"新屋","アラヤ",""]],
"9580233":[[15,15212,"村上市","ムラカミシ",152120185,"中新保","ナカシンボ",""]],
"9580234":[[15,15212,"村上市","ムラカミシ",152120222,"堀野","ホリノ",""]],
"9580235":[[15,15212,"村上市","ムラカミシ",152120020,"石住","イシズミ",""]],
"9580236":[[15,15212,"村上市","ムラカミシ",152120090,"上中島","カミナカジマ",""]],
"9580241":[[15,15212,"村上市","ムラカミシ",152120030,"岩崩","イワクズレ",""]],
"9580242":[[15,15212,"村上市","ムラカミシ",152120106,"茎太","クキタ",""]],
"9580243":[[15,15212,"村上市","ムラカミシ",152120170,"千縄","チナワ",""]],
"9580244":[[15,15212,"村上市","ムラカミシ",152120113,"小揚","コアゲ",""]],
"9580245":[[15,15212,"村上市","ムラカミシ",152120083,"釜杭","カマグイ",""]],
"9580246":[[15,15212,"村上市","ムラカミシ",152120129,"笹平","ササダイラ",""]],
"9580251":[[15,15212,"村上市","ムラカミシ",152120032,"岩沢","イワサワ",""]],
"9580252":[[15,15212,"村上市","ムラカミシ",152120145,"下新保","シモシンボ",""]],
"9580253":[[15,15212,"村上市","ムラカミシ",152120066,"大場沢","オオバザワ",""]],
"9580254":[[15,15212,"村上市","ムラカミシ",152120162,"十川","ソガワ",""]],
"9580255":[[15,15212,"村上市","ムラカミシ",152120109,"熊登","クマト",""]],
"9580261":[[15,15212,"村上市","ムラカミシ",152120133,"猿沢","サルサワ",""]],
"9580262":[[15,15212,"村上市","ムラカミシ",152120048,"上野","ウエノ",""]],
"9580263":[[15,15212,"村上市","ムラカミシ",152120094,"川端","カワバタ",""]],
"9580264":[[15,15212,"村上市","ムラカミシ",152120051,"鵜渡路","ウノトロ",""]],
"9580265":[[15,15212,"村上市","ムラカミシ",152120147,"下中島","シモナカジマ",""]],
"9580266":[[15,15212,"村上市","ムラカミシ",152120239,"宮ノ下","ミヤノシタ",""]],
"9580267":[[15,15212,"村上市","ムラカミシ",152120174,"寺尾","テラオ",""]],
"9580268":[[15,15212,"村上市","ムラカミシ",152120068,"小川","オガワ",""]],
"9580269":[[15,15212,"村上市","ムラカミシ",152120219,"古渡路","フルトロ",""]],
"9580270":[[15,15212,"村上市","ムラカミシ",152120002,"あけぼの","アケボノ",""]],
"9580292":[[15,15212,"村上市","ムラカミシ",152120032,"岩沢","イワサワ",""]],
"9580801":[[15,15212,"村上市","ムラカミシ",152120197,"西興屋","ニシコウヤ",""]],
"9580802":[[15,15212,"村上市","ムラカミシ",152120251,"四日市","ヨッカイチ",""]],
"9580803":[[15,15212,"村上市","ムラカミシ",152120176,"天神岡","テンジンオカ",""]],
"9580804":[[15,15212,"村上市","ムラカミシ",152120148,"下山田","シモヤマダ",""]],
"9580805":[[15,15212,"村上市","ムラカミシ",152120092,"上山田","カミヤマダ",""]],
"9580806":[[15,15212,"村上市","ムラカミシ",152120071,"小谷","オダニ",""]],
"9580807":[[15,15212,"村上市","ムラカミシ",152120107,"日下","クサカ",""]],
"9580808":[[15,15212,"村上市","ムラカミシ",152120084,"上相川","カミアイカワ",""]],
"9580809":[[15,15212,"村上市","ムラカミシ",152120141,"下相川","シモアイカワ",""]],
"9580811":[[15,15212,"村上市","ムラカミシ",152120164,"高平","タカダイラ",""]],
"9580812":[[15,15212,"村上市","ムラカミシ",152120059,"大関","オオセキ",""]],
"9580813":[[15,15212,"村上市","ムラカミシ",152120028,"鋳物師","イモジ",""]],
"9580814":[[15,15212,"村上市","ムラカミシ",152120243,"門前","モンゼン",""]],
"9580815":[[15,15212,"村上市","ムラカミシ",152120055,"大栗田","オオクリダ",""]],
"9580816":[[15,15212,"村上市","ムラカミシ",152120001,"赤沢","アカサワ",""]],
"9580817":[[15,15212,"村上市","ムラカミシ",152120152,"菅沼","スガヌマ",""]],
"9580818":[[15,15212,"村上市","ムラカミシ",152120215,"袋","フクロ",""]],
"9580821":[[15,15212,"村上市","ムラカミシ",152120132,"山辺里","サベリ",""]],
"9580822":[[15,15212,"村上市","ムラカミシ",152120173,"坪根","ツボネ",""]],
"9580823":[[15,15212,"村上市","ムラカミシ",152120171,"仲間町","チュウゲンマチ",""]],
"9580824":[[15,15212,"村上市","ムラカミシ",152120241,"本町","モトマチ",""]],
"9580831":[[15,15212,"村上市","ムラカミシ",152120154,"杉原","スギワラ",""]],
"9580832":[[15,15212,"村上市","ムラカミシ",152120021,"石原","イシワラ",""]],
"9580833":[[15,15212,"村上市","ムラカミシ",152120221,"堀片","ホリカタ",""]],
"9580834":[[15,15212,"村上市","ムラカミシ",152120151,"新町","シンマチ",""]],
"9580835":[[15,15212,"村上市","ムラカミシ",152120198,"二之町","ニノチョウ",""]],
"9580836":[[15,15212,"村上市","ムラカミシ",152120204,"羽黒口","ハグログチ",""]],
"9580837":[[15,15212,"村上市","ムラカミシ",152120136,"三之町","サンノチョウ",""]],
"9580841":[[15,15212,"村上市","ムラカミシ",152120121,"小町","コマチ",""]],
"9580842":[[15,15212,"村上市","ムラカミシ",152120067,"大町","オオマチ",""]],
"9580843":[[15,15212,"村上市","ムラカミシ",152120098,"上町","カンマチ",""]],
"9580844":[[15,15212,"村上市","ムラカミシ",152120181,"長井町","ナガイマチ",""]],
"9580845":[[15,15212,"村上市","ムラカミシ",152120123,"細工町","サイクマチ",""]],
"9580846":[[15,15212,"村上市","ムラカミシ",152120010,"安良町","アラマチ",""]],
"9580847":[[15,15212,"村上市","ムラカミシ",152120163,"大工町","ダイクマチ",""]],
"9580848":[[15,15212,"村上市","ムラカミシ",152120069,"小国町","オグニマチ",""]],
"9580849":[[15,15212,"村上市","ムラカミシ",152120175,"寺町","テラマチ",""]],
"9580851":[[15,15212,"村上市","ムラカミシ",152120205,"羽黒町","ハグロマチ",""]],
"9580852":[[15,15212,"村上市","ムラカミシ",152120238,"南町","ミナミマチ",""]],
"9580853":[[15,15212,"村上市","ムラカミシ",152120135,"山居町","サンキョマチ",""]],
"9580854":[[15,15212,"村上市","ムラカミシ",152120169,"田端町","タバタマチ",""]],
"9580855":[[15,15212,"村上市","ムラカミシ",152120017,"飯野西","イイノニシ",""]],
"9580856":[[15,15212,"村上市","ムラカミシ",152120016,"飯野桜ケ丘","イイノサクラガオカ",""]],
"9580857":[[15,15212,"村上市","ムラカミシ",152120015,"飯野","イイノ",""]],
"9580861":[[15,15212,"村上市","ムラカミシ",152120182,"中川原団地","ナカガワラダンチ",""]],
"9580862":[[15,15212,"村上市","ムラカミシ",152120252,"若葉町","ワカバチョウ",""]],
"9580863":[[15,15212,"村上市","ムラカミシ",152120077,"鍛冶町","カジマチ",""]],
"9580864":[[15,15212,"村上市","ムラカミシ",152120125,"肴町","サカナマチ",""]],
"9580865":[[15,15212,"村上市","ムラカミシ",152120124,"幸町","サイワイチョウ",""]],
"9580866":[[15,15212,"村上市","ムラカミシ",152120240,"村上","ムラカミ",""]],
"9580867":[[15,15212,"村上市","ムラカミシ",152120054,"大欠","オオガキ",""]],
"9580871":[[15,15212,"村上市","ムラカミシ",152120108,"久保多町","クボタマチ",""]],
"9580872":[[15,15212,"村上市","ムラカミシ",152120079,"片町","カタマチ",""]],
"9580873":[[15,15212,"村上市","ムラカミシ",152120088,"上片町","カミカタマチ",""]],
"9580874":[[15,15212,"村上市","ムラカミシ",152120149,"庄内町","ショウナイマチ",""]],
"9580875":[[15,15212,"村上市","ムラカミシ",152120074,"加賀町","カガマチ",""]],
"9580876":[[15,15212,"村上市","ムラカミシ",152120138,"塩町","シオマチ",""]],
"9580877":[[15,15212,"村上市","ムラカミシ",152120022,"泉町","イズミマチ",""]],
"9588501":[[15,15212,"村上市","ムラカミシ",152120136,"三之町","サンノチョウ",""]],
"9588533":[[15,15212,"村上市","ムラカミシ",152120234,"緑町","ミドリマチ",""]],
"9588555":[[15,15212,"村上市","ムラカミシ",152120156,"瀬波温泉","セナミオンセン",""]],
"9588558":[[15,15212,"村上市","ムラカミシ",152120171,"仲間町","チュウゲンマチ",""]],
"9588585":[[15,15212,"村上市","ムラカミシ",152120169,"田端町","タバタマチ",""]],
"9588601":[[15,15212,"村上市","ムラカミシ",152120121,"小町","コマチ",""]],
"9588686":[[15,15212,"村上市","ムラカミシ",152120136,"三之町","サンノチョウ",""]]
})
|
cenodis/InfinityLib
|
src/main/java/com/infinityraider/infinitylib/block/multiblock/IMultiBlockPartData.java
|
package com.infinityraider.infinitylib.block.multiblock;
import net.minecraft.nbt.NBTTagCompound;
public interface IMultiBlockPartData {
/**
* @return the relative x-position in the multi-block structure
*/
int posX();
/**
* @return the relative y-position in the multi-block structure
*/
int posY();
/**
* @return the relative z-position in the multi-block structure
*/
int posZ();
/**
* @return the x-size of the multi-block structure
*/
int sizeX();
/**
* @return the y-size of the multi-block structure
*/
int sizeY();
/**
* @return the z-size of the multi-block structure
*/
int sizeZ();
/**
* @return the number of blocks in the multi-block structure
*/
default int size() {
return this.sizeX() * this.sizeY() * this.sizeZ();
}
/**
* @param tag NBT tag to write this part's data to
*/
void writeToNBT(NBTTagCompound tag);
/**
* @param tag NBT tag to read this part's data from
*/
void readFromNBT(NBTTagCompound tag);
}
|
annagitel/ocs-ci
|
ocs_ci/utility/tests/test_version.py
|
from semantic_version import Version
import pytest
from ocs_ci.utility import version
@pytest.mark.parametrize(
"product_version, only_major_minor, ignore_pre_release, expected",
[
("4.4", False, False, Version.coerce("4.4")),
("4.4.5", True, False, version.VERSION_4_4),
("4.4.5", True, True, version.VERSION_4_4),
("4.4.5-182.ci", True, False, version.VERSION_4_4),
("4.4.5-182.ci", False, False, Version.coerce("4.4.5-182.ci")),
],
)
def test_get_semantic_version(
product_version, only_major_minor, ignore_pre_release, expected
):
"""
This test is suppose to test if the get_semantic_version returns
expected values for different combinations of paramters and different values
of string version provided to that function.
"""
tested_version = version.get_semantic_version(
product_version, only_major_minor, ignore_pre_release
)
assert tested_version == expected
@pytest.mark.parametrize(
"product_version, only_major_minor, ignore_pre_release, expected",
[
("4.4", False, False, "4.4.0"),
("4.4.5", True, False, "4.4"),
("4.4.5", True, True, "4.4"),
("4.4.5-182.ci", True, False, "4.4"),
("4.4.5-182.ci", False, False, "4.4.5-182.ci"),
("4.4.5-182.ci", False, True, "4.4.5"),
],
)
def test_get_semantic_version_string_values(
product_version, only_major_minor, ignore_pre_release, expected
):
"""
This test is suppose to test if the get_semantic_version returns
expected values which after the sting formatting are the same as the expected.
Testing all different combinations of parameters and values.
"""
tested_version = version.get_semantic_version(
product_version, only_major_minor, ignore_pre_release
)
assert f"{tested_version}" == expected
def test_compare_from_get_semantic_version():
"""
This teest is testing that semantic version comparison works as expected and
version 4.5.11 is lower than 4.11. Which in the float will not work, but in semantic
versions it should be fine.
"""
tested_version = version.get_semantic_version("4.5.11", only_major_minor=True)
assert tested_version < Version.coerce("4.11")
|
Aelphaeis/tools_stash
|
src/test/java/stash/transformer/PropertyTransformerTest.java
|
package stash.transformer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import stash.config.Instruction;
import stash.config.InstructionBuilder;
import test.stash.util.ResourceFolder;
public class PropertyTransformerTest {
private static final String VALUE3 = "value3";
private static final String VALUE2 = "value2";
private static final String NEW_PROPERTY_1 = "new_property_1";
private static final String DEFAULT_PROPERTY_2 = "default_property_2";
private static final String DEFAULT_PROPERTY_1 = "default_property_1";
private static final String TEST_FILE = "test.properties";
private PropertyTransformer t;
@Rule
public ResourceFolder folder = new ResourceFolder();
@Before
public void setup() {
t = new PropertyTransformer();
}
@Test
public void transform_unwrap_unwrappedCorrectly() {
String input = "value,value2,value3";
String[] valArr = input.split(",");
String value = Arrays.toString(valArr);
Map<String, Instruction> m = new HashMap<>();
InstructionBuilder builder = new InstructionBuilder();
builder.name("name").value(value).directive("unwrap");
m.put("name", builder.build());
t.transform(m);
String result = String.valueOf(t.config.getProperty("name"));
assertEquals("value, value2, value3", result);
}
@Test
public void load_validFile_success() throws IOException {
t.load(new File(folder.getResourceFolder(), TEST_FILE));
assertEquals("value1", t.config.getProperty(DEFAULT_PROPERTY_1));
assertEquals(VALUE2, t.config.getProperty(DEFAULT_PROPERTY_2));
}
@Test
public void transform_newValues_success() throws IOException {
t.load(new File(folder.getResourceFolder(), TEST_FILE));
Map<String, Instruction> addable = new HashMap<>();
InstructionBuilder builder = new InstructionBuilder();
builder.value(VALUE3).name(NEW_PROPERTY_1);
addable.put(NEW_PROPERTY_1, builder.build());
t.transform(addable);
assertEquals("value1", t.config.getProperty(DEFAULT_PROPERTY_1));
assertEquals(VALUE2, t.config.getProperty(DEFAULT_PROPERTY_2));
assertEquals(VALUE3, t.config.getProperty(NEW_PROPERTY_1));
}
@Test
public void transform_replace_success() throws IOException {
t.load(new File(folder.getResourceFolder(), TEST_FILE));
Map<String, Instruction> addable = new HashMap<>();
InstructionBuilder builder = new InstructionBuilder();
builder.name(DEFAULT_PROPERTY_1).value(VALUE3);
addable.put(DEFAULT_PROPERTY_1, builder.build());
t.transform(addable);
assertEquals(VALUE3, t.config.getProperty(DEFAULT_PROPERTY_1));
assertEquals(VALUE2, t.config.getProperty(DEFAULT_PROPERTY_2));
}
@Test
public void transform_save_success() throws IOException {
final String expected = "key=value";
ByteArrayOutputStream os = new ByteArrayOutputStream();
InputStream is = new ByteArrayInputStream(expected.getBytes());
t.load(is);
assertEquals("value", t.config.getProperty("key"));
t.save(os);
String result = new String(os.toByteArray());
assertTrue(result.contains(expected));
}
}
|
dstructs/ndarray
|
lib/btypes.js
|
'use strict';
// BASE TYPES //
var BTYPES = {
'int8': 'Int8Array',
'uint8': 'Uint8Array',
'uint8_clamped': 'Uint8ClampedArray',
'int16': 'Int16Array',
'uint16': 'Uint16Array',
'int32': 'Int32Array',
'uint32': 'Uint32Array',
'float32': 'Float32Array',
'float64': 'Float64Array',
'binary': 'Buffer',
'string': 'Array',
'boolean': 'Array',
'logical': 'Uint8Array',
'generic': 'Array'
};
// EXPORTS //
module.exports = BTYPES;
|
transmute-industries/transmute-vanilla
|
src/components/Pages/Home/TransmuteTerminal/commands/eventStore.js
|
<reponame>transmute-industries/transmute-vanilla
export const handleEventStore = (
command,
mercury,
actions
) => {
let newHistory = []
console.log('command: ', command)
console.log('mercury: ', mercury)
if (command.args[1] === 'create') {
let { from } = command.args
let bindingModel = {
fromAddress: from
}
// console.log('bindingModel: ', bindingModel)
actions.createEventStore(bindingModel)
}
if (command.args[1] === 'show') {
// magically read state here...
let asString = JSON.stringify(mercury.EventStore, null, "\t")
let asLines = asString.split('\n')
let asValues = asLines.map((line) =>{
return {
value: line
}
})
newHistory = newHistory.concat(asValues)
}
if (command.args[1] === 'write') {
// magically read state here...
let { event, from } = command.args
let bindingModel = {
event: JSON.parse(event),
// this is super unsafe... like terrible...
fromAddress: from,
contractAddress: mercury.eventStoreAddress
}
console.log('bindingModel: ', bindingModel)
actions.writeEvent(bindingModel)
}
newHistory.push({
value: '🤖 completed...'
})
return newHistory
}
|
rjw57/tiw-computer
|
emulator/src/devices/bus/dmv/k806.cpp
|
// license:BSD-3-Clause
// copyright-holders:<NAME>
/***************************************************************************
K806 Mouse module
***************************************************************************/
#include "emu.h"
#include "k806.h"
/***************************************************************************
IMPLEMENTATION
***************************************************************************/
ROM_START( dmv_k806 )
ROM_REGION( 0x0400, "mcu", 0 )
ROM_LOAD( "dmv_mouse_8741a.bin", 0x0000, 0x0400, CRC(2163737a) SHA1(b82c14dba6c25cb1f60cf623989ca8c0c1ee4cc3))
ROM_END
static INPUT_PORTS_START( dmv_k806 )
PORT_START("JUMPERS")
PORT_DIPNAME( 0x7f, 0x24, "K806 IFSEL" ) PORT_DIPLOCATION("J:!1,J:!2,J:!3,J:!4,J:!5,J:!6,J:!7")
PORT_DIPSETTING( 0x21, "0A" )
PORT_DIPSETTING( 0x41, "0B" )
PORT_DIPSETTING( 0x22, "1A" )
PORT_DIPSETTING( 0x42, "1B" )
PORT_DIPSETTING( 0x24, "2A" ) // default
PORT_DIPSETTING( 0x44, "2B" )
PORT_DIPSETTING( 0x28, "3A" )
PORT_DIPSETTING( 0x48, "3B" )
PORT_DIPSETTING( 0x30, "4A" )
PORT_DIPSETTING( 0x50, "4B" )
PORT_DIPNAME( 0x380, 0x00, "K806 Mouse" ) PORT_DIPLOCATION("J:!8,J:!9,J:!10")
PORT_DIPSETTING( 0x000, "<NAME>" )
PORT_DIPSETTING( 0x380, "Depraz" )
PORT_START("MOUSE")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_BUTTON1) PORT_NAME("Righ Mouse Button") PORT_CODE(MOUSECODE_BUTTON1)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_BUTTON3) PORT_NAME("Middte Mouse Button") PORT_CODE(MOUSECODE_BUTTON3)
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_BUTTON2) PORT_NAME("Left Mouse Button") PORT_CODE(MOUSECODE_BUTTON2)
PORT_START("MOUSEX")
PORT_BIT( 0xfff, 0x000, IPT_MOUSE_X ) PORT_SENSITIVITY(20) PORT_KEYDELTA(0)
PORT_START("MOUSEY")
PORT_BIT( 0xfff, 0x000, IPT_MOUSE_Y ) PORT_SENSITIVITY(20) PORT_KEYDELTA(0)
INPUT_PORTS_END
//**************************************************************************
// GLOBAL VARIABLES
//**************************************************************************
DEFINE_DEVICE_TYPE(DMV_K806, dmv_k806_device, "dmv_k806", "K806 mouse")
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
//-------------------------------------------------
// dmv_k806_device - constructor
//-------------------------------------------------
dmv_k806_device::dmv_k806_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, DMV_K806, tag, owner, clock)
, device_dmvslot_interface( mconfig, *this )
, m_mcu(*this, "mcu")
, m_jumpers(*this, "JUMPERS")
, m_mouse_buttons(*this, "MOUSE")
, m_mouse_x(*this, "MOUSEX")
, m_mouse_y(*this, "MOUSEY")
, m_bus(nullptr)
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void dmv_k806_device::device_start()
{
m_bus = static_cast<dmvcart_slot_device*>(owner());
}
//-------------------------------------------------
// device_reset - device-specific reset
//-------------------------------------------------
void dmv_k806_device::device_reset()
{
m_mouse.phase = 0;
m_mouse.xa = m_mouse.xb = ASSERT_LINE;
m_mouse.ya = m_mouse.yb = ASSERT_LINE;
m_mouse.x = m_mouse.y = 0;
m_mouse.prev_x = m_mouse.prev_y = 0;
}
//-------------------------------------------------
// device_add_mconfig - add device configuration
//-------------------------------------------------
MACHINE_CONFIG_START(dmv_k806_device::device_add_mconfig)
MCFG_CPU_ADD("mcu", I8741, XTAL(6'000'000))
MCFG_MCS48_PORT_P1_IN_CB(READ8(dmv_k806_device, port1_r))
MCFG_MCS48_PORT_P2_OUT_CB(WRITE8(dmv_k806_device, port2_w))
MCFG_MCS48_PORT_T1_IN_CB(READLINE(dmv_k806_device, portt1_r))
MCFG_TIMER_DRIVER_ADD_PERIODIC("mouse_timer", dmv_k806_device, mouse_timer, attotime::from_hz(1000))
MACHINE_CONFIG_END
//-------------------------------------------------
// input_ports - device-specific input ports
//-------------------------------------------------
ioport_constructor dmv_k806_device::device_input_ports() const
{
return INPUT_PORTS_NAME( dmv_k806 );
}
//-------------------------------------------------
// device_rom_region
//-------------------------------------------------
const tiny_rom_entry *dmv_k806_device::device_rom_region() const
{
return ROM_NAME( dmv_k806 );
}
void dmv_k806_device::io_read(address_space &space, int ifsel, offs_t offset, uint8_t &data)
{
uint8_t jumpers = m_jumpers->read();
if (BIT(jumpers, ifsel) && ((!BIT(offset, 3) && BIT(jumpers, 5)) || (BIT(offset, 3) && BIT(jumpers, 6))))
data = m_mcu->upi41_master_r(space, offset & 1);
}
void dmv_k806_device::io_write(address_space &space, int ifsel, offs_t offset, uint8_t data)
{
uint8_t jumpers = m_jumpers->read();
if (BIT(jumpers, ifsel) && ((!BIT(offset, 3) && BIT(jumpers, 5)) || (BIT(offset, 3) && BIT(jumpers, 6))))
{
m_mcu->upi41_master_w(space, offset & 1, data);
m_bus->m_out_int_cb(CLEAR_LINE);
}
}
READ8_MEMBER( dmv_k806_device::port1_r )
{
// ---- ---x Left button
// ---- --x- Middle button
// ---- -x-- Right button
// ---- x--- XA / Y1
// ---x ---- XB / Y2
// --x- ---- YA / X2
// -x-- ---- YB / X1
// x--- ---- not used
uint8_t data = m_mouse_buttons->read() & 0x07;
data |= (m_mouse.xa != CLEAR_LINE ? 0 : 0x08);
data |= (m_mouse.xb != CLEAR_LINE ? 0 : 0x10);
data |= (m_mouse.ya != CLEAR_LINE ? 0 : 0x20);
data |= (m_mouse.yb != CLEAR_LINE ? 0 : 0x40);
return data;
}
READ_LINE_MEMBER( dmv_k806_device::portt1_r )
{
return BIT(m_jumpers->read(), 7) ? 0 : 1;
}
WRITE8_MEMBER( dmv_k806_device::port2_w )
{
m_bus->m_out_int_cb((data & 1) ? CLEAR_LINE : ASSERT_LINE);
}
/*-------------------------------------------------------------------
Generate a sequence of pulses that have their phases shifted
by 90 degree for simulate the mouse movement.
Right Left
-+ +---+ +---+ +--- ---+ +---+ +---+ +-
XA | | | | | | | | | | | |
+---+ +---+ +---+ +---+ +---+ +---+
---+ +---+ +---+ +- -+ +---+ +---+ +---
XB | | | | | | | | | | | |
+---+ +---+ +---+ +---+ +---+ +---+
Down Up
-+ +---+ +---+ +--- ---+ +---+ +---+ +-
YA | | | | | | | | | | | |
+---+ +---+ +---+ +---+ +---+ +---+
---+ +---+ +---+ +- -+ +---+ +---+ +---
YB | | | | | | | | | | | |
+---+ +---+ +---+ +---+ +---+ +---+
-------------------------------------------------------------------*/
TIMER_DEVICE_CALLBACK_MEMBER(dmv_k806_device::mouse_timer)
{
switch(m_mouse.phase)
{
case 0:
m_mouse.xa = m_mouse.x > m_mouse.prev_x ? CLEAR_LINE : ASSERT_LINE;
m_mouse.xb = m_mouse.x < m_mouse.prev_x ? CLEAR_LINE : ASSERT_LINE;
m_mouse.ya = m_mouse.y > m_mouse.prev_y ? CLEAR_LINE : ASSERT_LINE;
m_mouse.yb = m_mouse.y < m_mouse.prev_y ? CLEAR_LINE : ASSERT_LINE;
break;
case 1:
m_mouse.xa = m_mouse.xb = m_mouse.x != m_mouse.prev_x ? CLEAR_LINE : ASSERT_LINE;
m_mouse.ya = m_mouse.yb = m_mouse.y != m_mouse.prev_y ? CLEAR_LINE : ASSERT_LINE;
break;
case 2:
m_mouse.xa = m_mouse.x < m_mouse.prev_x ? CLEAR_LINE : ASSERT_LINE;
m_mouse.xb = m_mouse.x > m_mouse.prev_x ? CLEAR_LINE : ASSERT_LINE;
m_mouse.ya = m_mouse.y < m_mouse.prev_y ? CLEAR_LINE : ASSERT_LINE;
m_mouse.yb = m_mouse.y > m_mouse.prev_y ? CLEAR_LINE : ASSERT_LINE;
break;
case 3:
m_mouse.xa = m_mouse.xb = ASSERT_LINE;
m_mouse.ya = m_mouse.yb = ASSERT_LINE;
m_mouse.prev_x = m_mouse.x;
m_mouse.prev_y = m_mouse.y;
m_mouse.x = m_mouse_x->read();
m_mouse.y = m_mouse_y->read();
break;
}
m_mouse.phase = (m_mouse.phase + 1) & 3;
}
|
iootclab/openjdk
|
openjdk11/test/jdk/java/awt/image/DrawImage/IncorrectUnmanagedImageRotatedClip.java
|
/*
* Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBufferShort;
import java.awt.image.VolatileImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import static java.awt.Transparency.TRANSLUCENT;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;
/**
* @test
* @key headful
* @bug 8059942
* @summary Tests rotated clip when unmanaged image is drawn to VI.
* Results of the blit to compatibleImage are used for comparison.
* @author <NAME>
*/
public final class IncorrectUnmanagedImageRotatedClip {
public static void main(final String[] args) throws IOException {
BufferedImage bi = makeUnmanagedBI();
fill(bi);
test(bi);
}
private static void test(final BufferedImage bi) throws IOException {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsConfiguration gc = ge.getDefaultScreenDevice()
.getDefaultConfiguration();
VolatileImage vi = gc.createCompatibleVolatileImage(500, 200,
TRANSLUCENT);
BufferedImage gold = gc.createCompatibleImage(500, 200, TRANSLUCENT);
// draw to compatible Image
draw(bi, gold);
// draw to volatile image
int attempt = 0;
BufferedImage snapshot;
while (true) {
if (++attempt > 10) {
throw new RuntimeException("Too many attempts: " + attempt);
}
vi.validate(gc);
if (vi.validate(gc) != VolatileImage.IMAGE_OK) {
continue;
}
draw(bi, vi);
snapshot = vi.getSnapshot();
if (vi.contentsLost()) {
continue;
}
break;
}
// validate images
for (int x = 0; x < gold.getWidth(); ++x) {
for (int y = 0; y < gold.getHeight(); ++y) {
if (gold.getRGB(x, y) != snapshot.getRGB(x, y)) {
ImageIO.write(gold, "png", new File("gold.png"));
ImageIO.write(snapshot, "png", new File("bi.png"));
throw new RuntimeException("Test failed.");
}
}
}
}
private static void draw(final BufferedImage from,final Image to) {
final Graphics2D g2d = (Graphics2D) to.getGraphics();
g2d.setComposite(AlphaComposite.Src);
g2d.setColor(Color.ORANGE);
g2d.fillRect(0, 0, to.getWidth(null), to.getHeight(null));
g2d.rotate(Math.toRadians(45));
g2d.clip(new Rectangle(41, 42, 43, 44));
g2d.drawImage(from, 50, 50, Color.blue, null);
g2d.dispose();
}
private static BufferedImage makeUnmanagedBI() {
final BufferedImage bi = new BufferedImage(500, 200, TYPE_INT_ARGB);
final DataBuffer db = bi.getRaster().getDataBuffer();
if (db instanceof DataBufferInt) {
((DataBufferInt) db).getData();
} else if (db instanceof DataBufferShort) {
((DataBufferShort) db).getData();
} else if (db instanceof DataBufferByte) {
((DataBufferByte) db).getData();
} else {
try {
bi.setAccelerationPriority(0.0f);
} catch (final Throwable ignored) {
}
}
return bi;
}
private static void fill(final Image image) {
final Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setComposite(AlphaComposite.Src);
for (int i = 0; i < image.getHeight(null); ++i) {
graphics.setColor(new Color(i, 0, 0));
graphics.fillRect(0, i, image.getWidth(null), 1);
}
graphics.dispose();
}
}
|
imtubedev/wallet
|
app/models/vote.js
|
import Request from '../utils/RequestUtil';
import {listProducers, getAccountInfo, getUndelegatebwInfo, listAgent, getGlobalInfo, queryRamPrice, listDelegateLoglist} from '../utils/Api';
import store from 'react-native-simple-store';
import { EasyToast } from '../components/Toast';
let newarr = new Array();
export default {
namespace: 'vote',
state: {
voteData:[],
isChecked:false,
accountInfo:[]
},
effects: {
*list({payload, callback},{call,put}) {
try{
const resp = yield call(Request.request, listAgent,"post");
// alert('listAgent :'+JSON.stringify(resp));
// const resp = yield call(Request.request,listAgent,"get");
if(resp && resp.code=='0'){
yield put({ type: 'updateVote', payload: { voteData:resp.data } });
// yield put({ type: 'updateVote', payload: { AgentData:resp.data } });
if (callback) callback(resp.data);
}else{
EasyToast.show(resp.msg);
}
} catch (error) {
EasyToast.show('网络繁忙,请稍后!');
}
},
*up({payload},{call,put}) {
try{
yield put({ type: 'updateSelect', payload: { ...payload } });
// alert(''+JSON.stringify(payload));
} catch (error) {
EasyToast.show('网络繁忙,请稍后!');
}
},
/**
* 获取eos账户信息 获取账户投票信息
*/
*getaccountinfo({payload,callback},{call,put}) {
var accountInfo = yield call(store.get, 'accountInfo');
try{
const resp = yield call(Request.request, getAccountInfo, 'post', payload);
if(resp && resp.code=='0'){
yield put({ type: 'updateAccountInfo', payload: { producers:(resp.data.voter_info ? resp.data.voter_info.producers : "") } });
yield put({ type: 'updateResources', payload: { Resources:resp.data} });
yield call(store.save, 'accountInfo', resp.data);
if (callback) callback(resp.data);
}else{
EasyToast.show(resp.msg);
yield put({ type: 'updateAccountInfo', payload: { producers:(accountInfo.voter_info ? accountInfo.voter_info.producers : "") } });
yield put({ type: 'updateResources', payload: { Resources:accountInfo} });
if (callback) callback(accountInfo);
}
} catch (error) {
EasyToast.show('网络繁忙,请稍后!');
yield put({ type: 'updateAccountInfo', payload: { producers:(accountInfo.voter_info ? accountInfo.voter_info.producers : "") } });
yield put({ type: 'updateResources', payload: { Resources:accountInfo} });
if (callback) callback(accountInfo);
}
},
/**
* 获取eos赎回信息
*/
*getundelegatebwInfo({payload,callback},{call,put}) {
try{
const resp = yield call(Request.request, getUndelegatebwInfo, 'post', payload);
if(resp && resp.code=='0'){
// yield put({ type: 'updateAccountInfo', payload: { accountInfo:resp.data } });
}else{
EasyToast.show(resp.msg);
}
if (callback) callback(resp.data);
} catch (error) {
EasyToast.show('网络繁忙,请稍后!');
}
},
*getGlobalInfo({payload,callback},{call,put}) {
try{
const resp = yield call(Request.request, getGlobalInfo, 'post', payload);
let total = (resp.data.rows[0].max_ram_size / 1024 / 1024 / 1024).toFixed(2);
let used = (resp.data.rows[0].total_ram_bytes_reserved / 1024 / 1024 / 1024).toFixed(2);
let used_Percentage= (((resp.data.rows[0].total_ram_bytes_reserved / 1024 / 1024 / 1024).toFixed(2) / (resp.data.rows[0].max_ram_size / 1024 / 1024 / 1024).toFixed(2)) * 10000 / 100).toFixed()
if(resp && resp.code=='0'){
yield put({ type: 'updateGlobal', payload: { total:total,used:used,used_Percentage:used_Percentage } });
}else{
EasyToast.show(resp.msg);
}
// if (callback) callback({total:total,used:used,used_Percentage:used_Percentage});
} catch (error) {
EasyToast.show('网络繁忙,请稍后!');
}
},
*getqueryRamPrice({payload,callback},{call,put}) {
try{
const resp = yield call(Request.request, queryRamPrice, 'post', payload);
if(resp && resp.code=='0'){
// yield put({ type: 'updatequeryRamPrice', payload: { Currentprice:resp.data } });
}else{
EasyToast.show(resp.msg);
}
if (callback) callback(resp.data);
} catch (error) {
EasyToast.show('网络繁忙,请稍后!');
}
},
*getDelegateLoglist({payload,callback},{call,put}) {
try{
const resp = yield call(Request.request, listDelegateLoglist, 'post', payload);
if(resp && resp.code=='0' && resp.data){
}else{
EasyToast.show(resp.msg);
}
if (callback) callback(resp);
} catch (error) {
EasyToast.show('网络繁忙,请稍后!');
}
},
},
reducers : {
updateVote(state, action) {
return {...state,voteData:action.payload.voteData};
},
updateSelect(state, action) {
let dts = state.voteData;
let newarr = new Array();
dts.map((item)=>{
if(item==action.payload.item){
if(item.isChecked){
item.isChecked=false;
}else{
item.isChecked=true;
}
}
newarr.push(item);
})
return {...state,voteData:newarr};
},
updateAccountInfo(state, action) {
let arr = state.voteData;
let arr1 = [];
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < action.payload.producers.length; j++){
if(action.payload.producers[j] == (arr[i].account)){
arr1.push(arr[i]);
}
}
}
return {...state, producers: arr1};
},
updateResources(state, action) {
return {...state,Resources:action.payload.Resources};
},
updateGlobal(state, action) {
return {...state,globaldata:action.payload};
},
}
}
|
HelixOS/cts
|
suite/audio_quality/lib/src/FileUtil.cpp
|
<filename>suite/audio_quality/lib/src/FileUtil.cpp
/*
* Copyright (C) 2012 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.
*/
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include "Log.h"
#include "Settings.h"
#include "StringUtil.h"
#include "FileUtil.h"
// This class is used by Log. So we cannot use LOG? macros here.
#define _LOGD_(x...) do { fprintf(stderr, x); fprintf(stderr, "\n"); } while(0)
// reported generated under reports/YYYY_MM_DD_HH_MM_SS dir
const char reportTopDir[] = "reports";
android::String8 FileUtil::mDirPath;
bool FileUtil::prepare(android::String8& dirPath)
{
if (mDirPath.length() != 0) {
dirPath = mDirPath;
_LOGD_("mDirPath %s", mDirPath.string());
return true;
}
time_t timeNow = time(NULL);
if (timeNow == ((time_t)-1)) {
_LOGD_("time error");
return false;
}
// tm is allocated in static buffer, and should not be freed.
struct tm* tm = localtime(&timeNow);
if (tm == NULL) {
_LOGD_("localtime error");
return false;
}
int result = mkdir(reportTopDir, S_IRWXU);
if ((result == -1) && (errno != EEXIST)) {
_LOGD_("mkdir of topdir failed, error %d", errno);
return false;
}
android::String8 reportTime;
if (reportTime.appendFormat("%04d_%02d_%02d_%02d_%02d_%02d", tm->tm_year + 1900,
tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec) != 0) {
return false;
}
Settings::Instance()->addSetting(Settings::EREPORT_TIME, reportTime);
android::String8 path;
if (path.appendFormat("%s/%s", reportTopDir, reportTime.string()) != 0) {
return false;
}
result = mkdir(path.string(), S_IRWXU);
if ((result == -1) && (errno != EEXIST)) {
_LOGD_("mkdir of report dir failed, error %d", errno);
return false;
}
mDirPath = path;
dirPath = path;
return true;
}
FileUtil::FileUtil()
{
mBuffer = new char[DEFAULT_BUFFER_SIZE];
if (mBuffer == NULL) {
// cannot use ASSERT here, just crash
*(char*)0 = 0;
}
mBufferSize = DEFAULT_BUFFER_SIZE;
}
FileUtil::~FileUtil()
{
if (mFile.is_open()) {
mFile.close();
}
delete[] mBuffer;
}
bool FileUtil::init(const char* fileName)
{
if (fileName == NULL) {
return true;
}
mFile.open(fileName, std::ios::out | std::ios::trunc);
if (!mFile.is_open()) {
return false;
}
return true;
}
bool FileUtil::doVprintf(bool fileOnly, int logLevel, const char *fmt, va_list ap)
{
// prevent messed up log in multi-thread env. Still multi-line logs can be messed up.
android::Mutex::Autolock lock(mWriteLock);
while (1) {
int start = 0;
if (logLevel != -1) {
mBuffer[0] = '0' + logLevel;
mBuffer[1] = '>';
start = 2;
}
int size;
size = vsnprintf(mBuffer + start, mBufferSize - start - 2, fmt, ap); // 2 for \n\0
if (size < 0) {
fprintf(stderr, "FileUtil::vprintf failed");
return false;
}
if ((size + start + 2) > mBufferSize) {
//default buffer does not fit, increase buffer size and retry
delete[] mBuffer;
mBuffer = new char[2 * size];
if (mBuffer == NULL) {
// cannot use ASSERT here, just crash
*(char*)0 = 0;
}
mBufferSize = 2 * size;
// re-try
continue;
}
size += start;
mBuffer[size] = '\n';
size++;
mBuffer[size] = 0;
if (!fileOnly) {
fprintf(stdout, "%s", mBuffer);
}
if (mFile.is_open()) {
mFile<<mBuffer;
}
return true;
}
}
bool FileUtil::doPrintf(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
bool result = doVprintf(false, -1, fmt, ap);
va_end(ap);
return result;
}
|
paullewallencom/react-978-1-8386-4385-0
|
_/Section 6/6.3/SignUpScreen.js
|
<filename>_/Section 6/6.3/SignUpScreen.js<gh_stars>0
import React, { Component } from "react";
import { View } from "react-native";
import styles from "../Components/Styles/AppStyle";
import { FancyButton } from "../Components/FancyButton";
import CommonForm from '../Components/CommonForm';
export default class SignUpScreen extends Component {
render() {
return (
<View style={styles.container}>
{/* can toggle here to see action */}
<CommonForm isLoggedIn={true}>
<CommonForm.UserInput />
<CommonForm.PasswordInput />
<CommonForm.EmailInput />
</CommonForm>
<FancyButton
text={"Sign Up"}
route={'SignUp'}
{...this.props} />
<FancyButton
style={[styles.fancyButton, {backgroundColor: 'pink'}]}
text={"Sign in"}
route={'Home'}
{...this.props} />
</View>
);
}
}
|
lavalamp/scat
|
procs/writerto.go
|
package procs
import (
"io"
"github.com/Roman2K/scat"
)
type WriterTo struct {
W io.Writer
}
func (wt WriterTo) Process(c *scat.Chunk) <-chan Res {
_, err := io.Copy(wt.W, c.Data().Reader())
return SingleRes(c, err)
}
func (wt WriterTo) Finish() error {
return nil
}
|
rieckpil/learning-samples
|
spring-boot-stackoverflow/src/main/java/de/rieckpil/learning/NullController.java
|
package de.rieckpil.learning;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/null")
public class NullController {
@GetMapping
public String doFoo() {
return null;
}
}
|
cyenyxe/ledger
|
libs/ml/include/ml/layers/multihead_attention.hpp
|
<reponame>cyenyxe/ledger<filename>libs/ml/include/ml/layers/multihead_attention.hpp
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "ml/layers/fully_connected.hpp"
#include "ml/layers/scaled_dot_product_attention.hpp"
#include "ml/ops/add.hpp"
#include "ml/ops/concatenate.hpp"
#include "ml/ops/placeholder.hpp"
#include "ml/saveparams/saveable_params.hpp"
#include <string>
namespace fetch {
namespace ml {
namespace layers {
template <class T>
class MultiheadAttention : public SubGraph<T>
{
public:
using TensorType = T;
using SizeType = typename TensorType::SizeType;
using ArrayPtrType = std::shared_ptr<TensorType>;
using DataType = typename T::Type;
using VecTensorType = typename SubGraph<T>::VecTensorType;
using RegType = fetch::ml::RegularisationType;
using WeightsInitType = fetch::ml::ops::WeightsInitialisation;
using ActivationType = fetch::ml::details::ActivationType;
using SPType = fetch::ml::LayerMultiHeadSaveableParams<T>;
MultiheadAttention() = default;
MultiheadAttention(SizeType n_heads, SizeType model_dim,
DataType dropout = static_cast<DataType>(0.9))
: n_heads_(n_heads)
, model_dim_(model_dim)
, dropout_(dropout)
{
// make sure all heads can be concatenated together to form model_dim
assert(model_dim_ % n_heads_ == 0);
key_dim_ = model_dim_ / n_heads_;
// assuming key_dim is the same as value_dim
value_dim_ = key_dim_;
std::string name = DESCRIPTOR;
// all input shapes are (feature_length, model_dim, batch_num)
std::string query =
this->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>(name + "_Query", {});
std::string key =
this->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>(name + "_Key", {});
std::string value =
this->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>(name + "_Value", {});
std::string mask =
this->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>(name + "_Mask", {});
// do n_heads time linear transformation
std::vector<std::string> heads;
for (SizeType i = 0; i < n_heads_; i++)
{
std::string head_name = name + "_Head_No_" + std::to_string(static_cast<int>(i));
std::string head_attention_output =
create_one_attention_head(head_name, query, key, value, mask);
heads.emplace_back(head_attention_output);
}
// concatenate all attention head outputs
std::string concatenated_attention_heads =
this->template AddNode<fetch::ml::ops::Concatenate<TensorType>>(
name + "_Concatenated_Heads", heads, static_cast<SizeType>(0));
// do the final transformation
std::string transformed_multihead =
this->template AddNode<fetch::ml::layers::FullyConnected<TensorType>>(
name + "_Final_Transformation", {concatenated_attention_heads},
static_cast<SizeType>(model_dim_), static_cast<SizeType>(model_dim_),
ActivationType::NOTHING, RegType::NONE, static_cast<DataType>(0),
WeightsInitType::XAVIER_GLOROT, true);
this->AddInputNode(query);
this->AddInputNode(key);
this->AddInputNode(value);
this->AddInputNode(mask);
this->SetOutputNode(transformed_multihead);
this->Compile();
}
std::string create_one_attention_head(std::string const &head_name, std::string const &query,
std::string const &key, std::string const &value,
std::string const &mask)
{
// transform input vectors to attention space
std::string transformed_query =
this->template AddNode<fetch::ml::layers::FullyConnected<TensorType>>(
head_name + "_Query_Transform", {query}, static_cast<SizeType>(model_dim_),
static_cast<SizeType>(key_dim_), ActivationType::NOTHING, RegType::NONE,
static_cast<DataType>(0), WeightsInitType::XAVIER_GLOROT, true);
std::string transformed_key =
this->template AddNode<fetch::ml::layers::FullyConnected<TensorType>>(
head_name + "_Key_Transform", {key}, static_cast<SizeType>(model_dim_),
static_cast<SizeType>(key_dim_), ActivationType::NOTHING, RegType::NONE,
static_cast<DataType>(0), WeightsInitType::XAVIER_GLOROT, true);
std::string transformed_value =
this->template AddNode<fetch::ml::layers::FullyConnected<TensorType>>(
head_name + "_Value_Transform", {value}, static_cast<SizeType>(model_dim_),
static_cast<SizeType>(value_dim_), ActivationType::NOTHING, RegType::NONE,
static_cast<DataType>(0), WeightsInitType::XAVIER_GLOROT, true);
// do the scaled dot product attention
std::string attention_output =
this->template AddNode<fetch::ml::layers::ScaledDotProductAttention<TensorType>>(
head_name + "_Scaled_Dot_Product_Attention",
{transformed_query, transformed_key, transformed_value, mask}, key_dim_, dropout_);
return attention_output;
}
std::shared_ptr<OpsSaveableParams> GetOpSaveableParams() override
{
auto ret = std::make_shared<SPType>();
// get base class saveable params
std::shared_ptr<OpsSaveableParams> sgsp = SubGraph<TensorType>::GetOpSaveableParams();
// assign base class saveable params to ret
auto sg_ptr1 = std::dynamic_pointer_cast<typename SubGraph<TensorType>::SPType>(sgsp);
auto sg_ptr2 = std::static_pointer_cast<typename SubGraph<TensorType>::SPType>(ret);
*sg_ptr2 = *sg_ptr1;
// asign layer specific params
ret->key_dim = key_dim_;
ret->value_dim = value_dim_;
ret->n_heads = n_heads_;
ret->model_dim = model_dim_;
ret->dropout = dropout_;
return ret;
}
void SetOpSaveableParams(SPType const &sp)
{
// assign layer specific params
key_dim_ = sp.key_dim;
value_dim_ = sp.value_dim;
n_heads_ = sp.n_heads;
model_dim_ = sp.model_dim;
dropout_ = sp.dropout;
}
std::vector<SizeType> ComputeOutputShape(VecTensorType const &inputs) const override
{
return inputs.front()->shape();
}
static constexpr OpType OpCode()
{
return OpType::LAYER_MULTI_HEAD_ATTENTION;
}
static constexpr char const *DESCRIPTOR = "MultiheadAttention";
private:
SizeType key_dim_{};
SizeType value_dim_{};
SizeType n_heads_{};
SizeType model_dim_{};
DataType dropout_{};
};
} // namespace layers
} // namespace ml
} // namespace fetch
|
Ybalrid/orbiter
|
Src/Vessel/DeltaGlider/RcsSubsys.h
|
<gh_stars>1000+
// Copyright (c) <NAME>
// Licensed under the MIT License
// ==============================================================
// ORBITER MODULE: DeltaGlider
// Part of the ORBITER SDK
//
// RcsSubsys.h
// Reaction control subsystem: lin/rot selection, attitude programs
// ==============================================================
#ifndef __RCSSUBSYS_H
#define __RCSSUBSYS_H
#include "DGSwitches.h"
#include "DGSubsys.h"
// ==============================================================
// Reaction control subsystem
// ==============================================================
class RcsModeSelector;
class RcsProgButtons;
class RcsSubsystem: public DGSubsystem {
public:
RcsSubsystem (DeltaGlider *dg);
~RcsSubsystem ();
void SetMode (int mode);
void SetProg (int prog, bool active);
bool clbkLoadPanel2D (int panelid, PANELHANDLE hPanel, DWORD viewW, DWORD viewH);
bool clbkLoadVC (int vcid);
private:
RcsModeSelector *modeselector;
RcsProgButtons *progbuttons;
int ELID_PROGBUTTONS;
};
// ==============================================================
// Control selector dial
// ==============================================================
class RcsModeSelector: public DGSubsystem {
friend class RcsModeDial;
public:
RcsModeSelector (RcsSubsystem *_subsys);
int GetMode () const;
void SetMode (int mode);
bool IncMode ();
bool DecMode ();
bool clbkLoadPanel2D (int panelid, PANELHANDLE hPanel, DWORD viewW, DWORD viewH);
bool clbkLoadVC (int vcid);
public:
RcsModeDial *dial;
int ELID_DIAL;
};
// ==============================================================
// Mode dial
// ==============================================================
class RcsModeDial: public DGDial1 {
public:
RcsModeDial (RcsModeSelector *comp);
void Reset2D (int panelid, MESHHANDLE hMesh);
void ResetVC (DEVMESHHANDLE hMesh);
bool Redraw2D (SURFHANDLE surf);
bool RedrawVC (DEVMESHHANDLE hMesh, SURFHANDLE surf);
bool ProcessMouse2D (int event, int mx, int my);
bool ProcessMouseVC (int event, VECTOR3 &p);
private:
RcsModeSelector *component;
};
// ==============================================================
// RCS program buttons
// ==============================================================
class RcsProgButtons: public PanelElement {
public:
RcsProgButtons (RcsSubsystem *_subsys);
~RcsProgButtons ();
void SetMode (int mode, bool active);
void DefineAnimationsVC (const VECTOR3 &axis, DWORD meshgrp, DWORD meshgrp_label,
DWORD vofs[6], DWORD vofs_label[6]);
void Reset2D (int panelid, MESHHANDLE hMesh);
void ResetVC (DEVMESHHANDLE hMesh);
bool Redraw2D (SURFHANDLE surf);
bool RedrawVC (DEVMESHHANDLE hMesh, SURFHANDLE surf);
bool ProcessMouse2D (int event, int mx, int my);
bool ProcessMouseVC (int event, VECTOR3 &p);
private:
RcsSubsystem *subsys;
DGButton3 *btn[6]; // the list of navmode buttons
};
#endif // !__RCSSUBSYS_H
|
ShubhamThakre/datahub
|
datahub-graphql-core/src/main/java/com/linkedin/datahub/graphql/resolvers/policy/mappers/PolicyUpdateInputInfoMapper.java
|
package com.linkedin.datahub.graphql.resolvers.policy.mappers;
import com.linkedin.common.UrnArray;
import com.linkedin.common.urn.Urn;
import com.linkedin.data.template.StringArray;
import com.linkedin.datahub.graphql.generated.ActorFilterInput;
import com.linkedin.datahub.graphql.generated.PolicyMatchFilterInput;
import com.linkedin.datahub.graphql.generated.PolicyUpdateInput;
import com.linkedin.datahub.graphql.generated.ResourceFilterInput;
import com.linkedin.datahub.graphql.types.mappers.ModelMapper;
import com.linkedin.policy.DataHubActorFilter;
import com.linkedin.policy.DataHubPolicyInfo;
import com.linkedin.policy.DataHubResourceFilter;
import com.linkedin.policy.PolicyMatchCondition;
import com.linkedin.policy.PolicyMatchCriterion;
import com.linkedin.policy.PolicyMatchCriterionArray;
import com.linkedin.policy.PolicyMatchFilter;
import java.net.URISyntaxException;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
/**
* Maps GraphQL {@link PolicyUpdateInput} to DataHub backend {@link DataHubPolicyInfo}.
*/
public class PolicyUpdateInputInfoMapper implements ModelMapper<PolicyUpdateInput, DataHubPolicyInfo> {
public static final PolicyUpdateInputInfoMapper INSTANCE = new PolicyUpdateInputInfoMapper();
public static DataHubPolicyInfo map(@Nonnull final PolicyUpdateInput policyInput) {
return INSTANCE.apply(policyInput);
}
@Override
public DataHubPolicyInfo apply(@Nonnull final PolicyUpdateInput policyInput) {
final DataHubPolicyInfo result = new DataHubPolicyInfo();
result.setDescription(policyInput.getDescription());
result.setType(policyInput.getType().toString());
result.setDisplayName(policyInput.getName());
result.setPrivileges(new StringArray(policyInput.getPrivileges()));
result.setActors(mapActors(policyInput.getActors()));
result.setState(policyInput.getState().toString());
if (policyInput.getResources() != null) {
result.setResources(mapResources(policyInput.getResources()));
}
return result;
}
private DataHubActorFilter mapActors(final ActorFilterInput actorInput) {
final DataHubActorFilter result = new DataHubActorFilter();
result.setAllGroups(actorInput.getAllGroups());
result.setAllUsers(actorInput.getAllUsers());
result.setResourceOwners(actorInput.getResourceOwners());
if (actorInput.getGroups() != null) {
result.setGroups(new UrnArray(actorInput.getGroups().stream().map(this::createUrn).collect(Collectors.toList())));
}
if (actorInput.getUsers() != null) {
result.setUsers(new UrnArray(actorInput.getUsers().stream().map(this::createUrn).collect(Collectors.toList())));
}
return result;
}
private DataHubResourceFilter mapResources(final ResourceFilterInput resourceInput) {
final DataHubResourceFilter result = new DataHubResourceFilter();
if (resourceInput.getAllResources() != null) {
result.setAllResources(resourceInput.getAllResources());
}
// This is an implicit mapping between GQL EntityType and Entity Name as known by GMS.
// Be careful about maintaining this contract.
if (resourceInput.getType() != null) {
result.setType(resourceInput.getType());
}
if (resourceInput.getResources() != null) {
result.setResources(new StringArray(resourceInput.getResources()));
}
if (resourceInput.getFilter() != null) {
result.setFilter(mapFilter(resourceInput.getFilter()));
}
return result;
}
private PolicyMatchFilter mapFilter(final PolicyMatchFilterInput filter) {
return new PolicyMatchFilter().setCriteria(new PolicyMatchCriterionArray(filter.getCriteria()
.stream()
.map(criterion -> new PolicyMatchCriterion().setField(criterion.getField())
.setValues(new StringArray(criterion.getValues()))
.setCondition(PolicyMatchCondition.valueOf(criterion.getCondition().name())))
.collect(Collectors.toList())));
}
private Urn createUrn(String urnStr) {
try {
return Urn.createFromString(urnStr);
} catch (URISyntaxException e) {
throw new RuntimeException(String.format("Failed to convert urnStr %s into an URN object", urnStr), e);
}
}
}
|
ChosenMedInfo/oncopubminer-app
|
xiaonuo-main/src/main/java/com/cn/xiaonuo/utils/CommonCharacters.java
|
package com.cn.xiaonuo.utils;
public class CommonCharacters {
public final static String QX_SPLITER1 = " | ";
public final static String QX_SPLITER1_FOR_SPLIT = " \\| ";
public final static String QX_SPLITER2 = ","; // quanxu, 2021-01-08: 主要针对xmSelect多选值!
public final static String QX_MSG_CANNOT_GET_INSERTED_ID = "无法获取插入后数据的id,请联系管理员!";
public final static String QX_MSG_GENE_MORE_THAN_ONCE = "该基因存在多条,请先对基因进行去重!";
public final static String QX_MSG_GENE_NOT_EXIST = "该基因不存在,请先添加基因!";
public final static String QX_MSG_GENE_ALREADY_EXIST = "该基因已存在,无法再次添加!";
public final static String QX_MSG_ALTER_MORE_THAN_ONCE = "该变异存在多条,请先对变异进行去重!";
public final static String QX_MSG_ALTER_NOT_EXIST = "该变异不存在,请先添加变异!";
public final static String QX_MSG_ALTER_ALREADY_EXIST = "该变异已存在,无法再次添加!";
}
|
maxim4to/Mixbox
|
Frameworks/TestsFoundation/PrivateHeaders/Classdump/XCTAutomationSupport/Xcode_11_0/Xcode_11_0_XCTElementIndexingTransformer.h
|
<filename>Frameworks/TestsFoundation/PrivateHeaders/Classdump/XCTAutomationSupport/Xcode_11_0/Xcode_11_0_XCTElementIndexingTransformer.h
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 && __IPHONE_OS_VERSION_MAX_ALLOWED < 140000
#import "Xcode_11_0_XCTAutomationSupport_CDStructures.h"
#import "Xcode_11_0_SharedHeader.h"
#import "Xcode_11_0_XCTElementSetCodableTransformer.h"
@class XCTIndexingTransformerIterator;
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
@interface XCTElementIndexingTransformer : XCTElementSetCodableTransformer
{
unsigned long long _elementIndex;
XCTIndexingTransformerIterator *_currentIterator;
}
+ (void)provideCapabilitiesToBuilder:(id)arg1;
+ (_Bool)supportsSecureCoding;
@property(retain) XCTIndexingTransformerIterator *currentIterator; // @synthesize currentIterator=_currentIterator;
@property(readonly) unsigned long long elementIndex; // @synthesize elementIndex=_elementIndex;
- (id)iteratorForInput:(id)arg1;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)requiredKeyPathsOrError:(id *)arg1;
- (_Bool)supportsAttributeKeyPathAnalysis;
- (_Bool)supportsRemoteEvaluation;
- (_Bool)canBeRemotelyEvaluatedWithCapabilities:(id)arg1;
- (id)transform:(id)arg1 relatedElements:(id *)arg2;
- (_Bool)isEqual:(id)arg1;
- (unsigned long long)hash;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)initWithElementIndex:(unsigned long long)arg1;
@end
#endif
|
codejsha/infrastructure
|
weblogic/status/get_server_status.py
|
#!/usr/bin/env python
class ansiformat(object):
reset = '\033[0m'
bold = '\033[1m'
underline = '\033[4m'
blink = '\033[5m'
class ansifgcolor(object):
light_red = '\033[91m'
light_green = '\033[92m'
light_yellow = '\033[93m'
light_blue = '\033[94m'
light_magenta = '\033[95m'
light_cyan = '\033[96m'
######################################################################
def print_status_header(_header, _server_names):
print(ansiformat.bold + '%-30s' % _header + ansiformat.reset + '|'),
for _server_name in _server_names:
print('%15s' % _server_name),
print('')
print('-' * (31 + (16 * len(_server_names))))
def print_status_value(_items, _values):
_transposed_values = list(map(list, zip(*_values)))
for _idx in range(len(_items)):
print('%-30s' % _items[_idx][0] + '|'),
if _items[_idx][1] == 'bool':
for v in _transposed_values[_idx]:
if v == 0:
print(''.join(str('%15s' % 'False'))),
else:
print(''.join(str('%15s' % 'True'))),
elif _items[_idx][1] == 'int':
print(' '.join([str('%15i' % v) for v in _transposed_values[_idx]])),
elif _items[_idx][1] == 'long':
print(' '.join([str('%15i' % v) for v in _transposed_values[_idx]])),
elif _items[_idx][1] == 'double':
print(' '.join([str('%15.4f' % v) for v in _transposed_values[_idx]])),
else:
print(' '.join([str('%15s' % v) for v in _transposed_values[_idx]])),
print('')
print('\n')
def get_server_general_status(_servers):
print('%-20s %-10s %-35s %-10s' %
('ServerName', 'State', 'ListenAddress', 'ListenPort'))
print('------------------------------------------------------------------------------')
for _server in _servers:
print('%-20s' % _server.getName()),
if _server.getState() == 'RUNNING':
print(ansifgcolor.light_green + '%-10s' % _server.getState() +
ansiformat.reset),
elif _server.getState() == 'ADMIN':
print(ansifgcolor.light_yellow + '%-10s' % _server.getState() +
ansiformat.reset),
else:
print(ansifgcolor.light_red + '%-10s' % _server.getState() +
ansiformat.reset),
print('%-35s' % _server.getListenAddress()),
print('%10s' % _server.getListenPort())
print('\n')
def get_server_heap_status(_servers):
_server_names = [server.getName() for server in _servers]
_heap_items = [
('HeapSizeMax', 'long'),
('HeapSizeCurrent', 'long'),
('HeapFreeCurrent', 'long'),
('HeapFreePercent', 'int')
]
_heap_values = []
for _server in _servers:
_heap_values.append([
_server.getJVMRuntime().getHeapSizeMax(),
_server.getJVMRuntime().getHeapSizeCurrent(),
_server.getJVMRuntime().getHeapFreeCurrent(),
_server.getJVMRuntime().getHeapFreePercent(),
])
print_status_header('HEAP', _server_names)
print_status_value(_heap_items, _heap_values)
def get_server_threadpool_status(_domain_version, _servers):
_server_names = [server.getName() for server in _servers]
_is_ver_1212_or_later = False
if ('14.' in _domain_version) or ('12.' in _domain_version):
_is_ver_1212_or_later = True
if '12.1.1' in _domain_version:
_is_ver_1212_or_later = False
_threadpool_items = [
('CompletedRequestCount', 'long'),
('ExecuteThreadIdleCount', 'int'),
('ExecuteThreadTotalCount', 'int'),
('HoggingThreadCount', 'int'),
('MinThreadsConstraintsCompleted', 'long'),
('MinThreadsConstraintsPending', 'int'),
('PendingUserRequestCount', 'int'),
('QueueLength', 'int'),
('SharedCapacityForWorkManagers', 'int'),
('StandbyThreadCount', 'int'),
('Throughput', 'double'),
('Suspended', 'bool')
]
if _is_ver_1212_or_later:
_threadpool_items.append(('OverloadRejectedRequestsCount', 'int'))
_threadpool_items.append(('StuckThreadCount', 'int'))
_threadpool_values = []
for _server in _servers:
_list = [
_server.getThreadPoolRuntime().getCompletedRequestCount(),
_server.getThreadPoolRuntime().getExecuteThreadIdleCount(),
_server.getThreadPoolRuntime().getExecuteThreadTotalCount(),
_server.getThreadPoolRuntime().getHoggingThreadCount(),
_server.getThreadPoolRuntime().getMinThreadsConstraintsCompleted(),
_server.getThreadPoolRuntime().getMinThreadsConstraintsPending(),
_server.getThreadPoolRuntime().getPendingUserRequestCount(),
_server.getThreadPoolRuntime().getQueueLength(),
_server.getThreadPoolRuntime().getSharedCapacityForWorkManagers(),
_server.getThreadPoolRuntime().getStandbyThreadCount(),
_server.getThreadPoolRuntime().getThroughput(),
_server.getThreadPoolRuntime().isSuspended(),
]
if _is_ver_1212_or_later:
_list.append(_server.getThreadPoolRuntime().getOverloadRejectedRequestsCount())
_list.append(_server.getThreadPoolRuntime().getStuckThreadCount())
_threadpool_values.append(_list)
print_status_header('THREADPOOL', _server_names)
print_status_value(_threadpool_items, _threadpool_values)
######################################################################
admin_server_listen_address = 'test.example.com'
admin_server_listen_port = '7001'
admin_username = 'weblogic'
admin_password = '<PASSWORD>'
admin_server_url = 't3://' + admin_server_listen_address + ':' + admin_server_listen_port
connect(admin_username, admin_password, admin_server_url)
domain_version = cmo.getDomainVersion()
domainRuntime()
servers = domainRuntimeService.getServerRuntimes()
if len(servers) > 0:
get_server_general_status(servers)
get_server_heap_status(servers)
get_server_threadpool_status(domain_version, servers)
exit()
|
sagarchaurasia260395/Proxima-DEX
|
app/src/components/Swap/index.js
|
import React, { useState, useEffect } from "react";
import { Card, Table } from "react-bootstrap";
import { useSelector, useDispatch } from "react-redux";
import { SWAP } from "../../actions";
import "../PairGovernance/style.css";
import Web3 from "web3";
import { contract } from "../../common/contractconfig";
import ProximaSwapEmoji from "../../assets/swapRewards.png";
import Faucet from "../faucet";
import { Error } from "../../actions";
import Button from "react-bootstrap-button-loader";
function Swap() {
const dispatch = useDispatch();
const address = useSelector((store) => store.wallet.walletAddress);
const swapRewards = useSelector((store) => store.swap.swapRewards);
const currentProvider = useSelector((store) => store.wallet.provider);
const [loaderState, setScreenLoader] = useState(false);
useEffect(() => {
console.log("getting swap rewards", address);
if (address !== "") {
dispatch(SWAP.getSwapRewards(address));
}
}, [address]);
async function claimRewards() {
try {
const web3WalletWrapper = new Web3(currentProvider);
const Instance = new web3WalletWrapper.eth.Contract(
contract.SwapABI,
contract.SwapRewardsAddress
);
let _claimingBal = await Instance.methods
.getUserPendingShares(address)
.call();
console.log("claimAmount", _claimingBal);
if (_claimingBal > 0) {
let _result = await Instance.methods
.releaseUserShare()
.send({ from: address });
console.log(_result);
if (_result) {
dispatch(SWAP.getSwapRewards(address));
Error.toastifyMsg("info", "Claim Success");
} else {
Error.toastifyMsg("err", "Claim Failed");
}
} else {
Error.toastifyMsg("err", "No Claiming Balance");
dispatch(SWAP.getSwapRewards(address));
}
} catch (err) {
Error.toastifyMsg("err", "Claim Failed");
}
setScreenLoader(false);
}
return (
<div className="row marginBtm30" style={{ marginTop: "30px" }}>
<div className="col-md-12">
{/* <Card body className="css-card aligncenter marginBtm30 governance_ad">
<h3 style={{ fontWeight: "600" }}>Proxima Swap Rewards</h3>
<p style={{ fontWeight: "600" }} className="marginBtm0">
Test Proxima Swap Rewards
</p>
</Card> */}
<div
className="row liqProvider_ad"
style={{ margin: "10px 0px 0px 0px" }}
>
<div className="col-md-3">
<img className="ct_happyImageSwap" src={ProximaSwapEmoji} />
</div>
<div id="contentBody" className="col-md-9">
<div id="contentText" className="ct__fs20">
Proxima Swap Rewards
</div>
<div id="contentText" className="ct__fs14">
Claim your reward earned from Swapping on Proxima Swap.
</div>
<a
style={{
textDecorationLine: "underline",
color: "#edf1ff",
fontSize: "14px",
}}
href="https://docs.proxima.finance/guides/user-rewards"
target="_"
>
Read more about Proxima Swap Rewards
</a>
</div>
</div>
{address !== "" ? (
<div>
{swapRewards !== "" ? (
<Card body className="css-card governance_ad">
<div className="row">
<div className="col-md-3"></div>
<div className="col-md-6">
<div
className="displayflex"
style={{ textAlign: "center" }}
>
<Table
bordered
style={{ color: "#fff", marginBottom: "0px" }}
>
<tbody>
<tr>
<th>Current Balance</th>
<td>{swapRewards.balance + ` PXA`}</td>
</tr>
<tr>
<th>Claimable Balance</th>
<td>{swapRewards.claimableBalance + ` PXA`}</td>
</tr>
{/* <tr>
<th>Total Balance</th>
<td>{swapRewards.totalBalance}</td>
</tr> */}
</tbody>
</Table>
</div>
</div>
<div className="col-md-3"></div>
</div>
<div className="row ">
<div className="col-md-3"></div>
<div className="col-md-6">
<div style={{ marginTop: "30px" }}>
<Button
size="sm"
className="claimreward"
loading={loaderState}
onClick={() => {
setScreenLoader(true);
claimRewards();
}}
>
Claim Rewards
</Button>
</div>
</div>
<div className="col-md-3"></div>
</div>
</Card>
) : (
<Card
body
className="css-card aligncenter margintop30 governance_ad"
>
{" "}
<p className="connectwallettext">No data found</p>
</Card>
)}
</div>
) : (
<Card body className="css-card">
<p className="connectwallettext">Connect Wallet</p>
</Card>
)}
<Faucet />
</div>
</div>
);
}
export default Swap;
|
sharplook/tencentcloud-sdk-java-test
|
src/main/java/com/tencentcloudapi/cpdp/v20190820/models/QueryTransferBatchResponse.java
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.cpdp.v20190820.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class QueryTransferBatchResponse extends AbstractModel{
/**
* 商户号。
示例值:19300009329
*/
@SerializedName("MerchantId")
@Expose
private String MerchantId;
/**
* 商家批次单号。
商户系统内部的商家批次单号,此参数只能由数字、字母组成,商户系统内部唯一,UTF8编码,最多32个字符。
示例值:plfk2020042013
*/
@SerializedName("MerchantBatchNo")
@Expose
private String MerchantBatchNo;
/**
* 微信批次单号。
微信商家转账系统返回的唯一标识。
示例值:1030000071100999991182020050700019480001
*/
@SerializedName("BatchId")
@Expose
private String BatchId;
/**
* 直连商户appId。
商户号绑定的appid。
示例值:wxf636efh567hg4356
*/
@SerializedName("MerchantAppId")
@Expose
private String MerchantAppId;
/**
* 批次状态。
ACCEPTED:已受理,批次已受理成功,若发起批量转账的30分钟后,转账批次单仍处于该状态,可能原因是商户账户余额不足等。商户可查询账户资金流水,若该笔转账批次单的扣款已经发生,则表示批次已经进入转账中,请再次查单确认;
PROCESSING:转账中,已开始处理批次内的转账明细单;
FINISHED:已完成,批次内的所有转账明细单都已处理完成;
CLOSED:已关闭,可查询具体的批次关闭原因确认;
示例值:ACCEPTED
*/
@SerializedName("BatchStatus")
@Expose
private String BatchStatus;
/**
* 批次关闭原因。
如果批次单状态为“CLOSED”(已关闭),则有关闭原因;
MERCHANT_REVOCATION:商户主动撤销;
OVERDUE_CLOSE:系统超时关闭。
示例值:OVERDUE_CLOSE
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("CloseReason")
@Expose
private String CloseReason;
/**
* 转账总金额。
转账金额,单位为分。
示例值:4000000
*/
@SerializedName("TotalAmount")
@Expose
private Long TotalAmount;
/**
* 转账总笔数。
一个转账批次最多允许发起三千笔转账。
示例值:200
*/
@SerializedName("TotalNum")
@Expose
private Long TotalNum;
/**
* 批次受理成功时返回,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("CreateTime")
@Expose
private String CreateTime;
/**
* 批次最近一次更新时间,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("UpdateTime")
@Expose
private String UpdateTime;
/**
* 转账成功金额。
转账成功的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("SuccessAmount")
@Expose
private Long SuccessAmount;
/**
* 转账成功的笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("SuccessNum")
@Expose
private Long SuccessNum;
/**
* 转账失败金额。
转账失败的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("FailAmount")
@Expose
private Long FailAmount;
/**
* 转账失败笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("FailNum")
@Expose
private Long FailNum;
/**
* 转账明细列表。
返回明细详情
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("TransferDetails")
@Expose
private TransferDetailResponse [] TransferDetails;
/**
* 批次类型。
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("BatchType")
@Expose
private String BatchType;
/**
* 批次名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("BatchName")
@Expose
private String BatchName;
/**
* 批次标注。
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("BatchRemark")
@Expose
private String BatchRemark;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
@SerializedName("RequestId")
@Expose
private String RequestId;
/**
* Get 商户号。
示例值:19300009329
* @return MerchantId 商户号。
示例值:19300009329
*/
public String getMerchantId() {
return this.MerchantId;
}
/**
* Set 商户号。
示例值:19300009329
* @param MerchantId 商户号。
示例值:19300009329
*/
public void setMerchantId(String MerchantId) {
this.MerchantId = MerchantId;
}
/**
* Get 商家批次单号。
商户系统内部的商家批次单号,此参数只能由数字、字母组成,商户系统内部唯一,UTF8编码,最多32个字符。
示例值:plfk2020042013
* @return MerchantBatchNo 商家批次单号。
商户系统内部的商家批次单号,此参数只能由数字、字母组成,商户系统内部唯一,UTF8编码,最多32个字符。
示例值:plfk2020042013
*/
public String getMerchantBatchNo() {
return this.MerchantBatchNo;
}
/**
* Set 商家批次单号。
商户系统内部的商家批次单号,此参数只能由数字、字母组成,商户系统内部唯一,UTF8编码,最多32个字符。
示例值:plfk2020042013
* @param MerchantBatchNo 商家批次单号。
商户系统内部的商家批次单号,此参数只能由数字、字母组成,商户系统内部唯一,UTF8编码,最多32个字符。
示例值:plfk2020042013
*/
public void setMerchantBatchNo(String MerchantBatchNo) {
this.MerchantBatchNo = MerchantBatchNo;
}
/**
* Get 微信批次单号。
微信商家转账系统返回的唯一标识。
示例值:1030000071100999991182020050700019480001
* @return BatchId 微信批次单号。
微信商家转账系统返回的唯一标识。
示例值:1030000071100999991182020050700019480001
*/
public String getBatchId() {
return this.BatchId;
}
/**
* Set 微信批次单号。
微信商家转账系统返回的唯一标识。
示例值:1030000071100999991182020050700019480001
* @param BatchId 微信批次单号。
微信商家转账系统返回的唯一标识。
示例值:1030000071100999991182020050700019480001
*/
public void setBatchId(String BatchId) {
this.BatchId = BatchId;
}
/**
* Get 直连商户appId。
商户号绑定的appid。
示例值:wxf636efh567hg4356
* @return MerchantAppId 直连商户appId。
商户号绑定的appid。
示例值:wxf636efh567hg4356
*/
public String getMerchantAppId() {
return this.MerchantAppId;
}
/**
* Set 直连商户appId。
商户号绑定的appid。
示例值:wxf636efh567hg4356
* @param MerchantAppId 直连商户appId。
商户号绑定的appid。
示例值:wxf636efh567hg4356
*/
public void setMerchantAppId(String MerchantAppId) {
this.MerchantAppId = MerchantAppId;
}
/**
* Get 批次状态。
ACCEPTED:已受理,批次已受理成功,若发起批量转账的30分钟后,转账批次单仍处于该状态,可能原因是商户账户余额不足等。商户可查询账户资金流水,若该笔转账批次单的扣款已经发生,则表示批次已经进入转账中,请再次查单确认;
PROCESSING:转账中,已开始处理批次内的转账明细单;
FINISHED:已完成,批次内的所有转账明细单都已处理完成;
CLOSED:已关闭,可查询具体的批次关闭原因确认;
示例值:ACCEPTED
* @return BatchStatus 批次状态。
ACCEPTED:已受理,批次已受理成功,若发起批量转账的30分钟后,转账批次单仍处于该状态,可能原因是商户账户余额不足等。商户可查询账户资金流水,若该笔转账批次单的扣款已经发生,则表示批次已经进入转账中,请再次查单确认;
PROCESSING:转账中,已开始处理批次内的转账明细单;
FINISHED:已完成,批次内的所有转账明细单都已处理完成;
CLOSED:已关闭,可查询具体的批次关闭原因确认;
示例值:ACCEPTED
*/
public String getBatchStatus() {
return this.BatchStatus;
}
/**
* Set 批次状态。
ACCEPTED:已受理,批次已受理成功,若发起批量转账的30分钟后,转账批次单仍处于该状态,可能原因是商户账户余额不足等。商户可查询账户资金流水,若该笔转账批次单的扣款已经发生,则表示批次已经进入转账中,请再次查单确认;
PROCESSING:转账中,已开始处理批次内的转账明细单;
FINISHED:已完成,批次内的所有转账明细单都已处理完成;
CLOSED:已关闭,可查询具体的批次关闭原因确认;
示例值:ACCEPTED
* @param BatchStatus 批次状态。
ACCEPTED:已受理,批次已受理成功,若发起批量转账的30分钟后,转账批次单仍处于该状态,可能原因是商户账户余额不足等。商户可查询账户资金流水,若该笔转账批次单的扣款已经发生,则表示批次已经进入转账中,请再次查单确认;
PROCESSING:转账中,已开始处理批次内的转账明细单;
FINISHED:已完成,批次内的所有转账明细单都已处理完成;
CLOSED:已关闭,可查询具体的批次关闭原因确认;
示例值:ACCEPTED
*/
public void setBatchStatus(String BatchStatus) {
this.BatchStatus = BatchStatus;
}
/**
* Get 批次关闭原因。
如果批次单状态为“CLOSED”(已关闭),则有关闭原因;
MERCHANT_REVOCATION:商户主动撤销;
OVERDUE_CLOSE:系统超时关闭。
示例值:OVERDUE_CLOSE
注意:此字段可能返回 null,表示取不到有效值。
* @return CloseReason 批次关闭原因。
如果批次单状态为“CLOSED”(已关闭),则有关闭原因;
MERCHANT_REVOCATION:商户主动撤销;
OVERDUE_CLOSE:系统超时关闭。
示例值:OVERDUE_CLOSE
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getCloseReason() {
return this.CloseReason;
}
/**
* Set 批次关闭原因。
如果批次单状态为“CLOSED”(已关闭),则有关闭原因;
MERCHANT_REVOCATION:商户主动撤销;
OVERDUE_CLOSE:系统超时关闭。
示例值:OVERDUE_CLOSE
注意:此字段可能返回 null,表示取不到有效值。
* @param CloseReason 批次关闭原因。
如果批次单状态为“CLOSED”(已关闭),则有关闭原因;
MERCHANT_REVOCATION:商户主动撤销;
OVERDUE_CLOSE:系统超时关闭。
示例值:OVERDUE_CLOSE
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setCloseReason(String CloseReason) {
this.CloseReason = CloseReason;
}
/**
* Get 转账总金额。
转账金额,单位为分。
示例值:4000000
* @return TotalAmount 转账总金额。
转账金额,单位为分。
示例值:4000000
*/
public Long getTotalAmount() {
return this.TotalAmount;
}
/**
* Set 转账总金额。
转账金额,单位为分。
示例值:4000000
* @param TotalAmount 转账总金额。
转账金额,单位为分。
示例值:4000000
*/
public void setTotalAmount(Long TotalAmount) {
this.TotalAmount = TotalAmount;
}
/**
* Get 转账总笔数。
一个转账批次最多允许发起三千笔转账。
示例值:200
* @return TotalNum 转账总笔数。
一个转账批次最多允许发起三千笔转账。
示例值:200
*/
public Long getTotalNum() {
return this.TotalNum;
}
/**
* Set 转账总笔数。
一个转账批次最多允许发起三千笔转账。
示例值:200
* @param TotalNum 转账总笔数。
一个转账批次最多允许发起三千笔转账。
示例值:200
*/
public void setTotalNum(Long TotalNum) {
this.TotalNum = TotalNum;
}
/**
* Get 批次受理成功时返回,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
* @return CreateTime 批次受理成功时返回,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getCreateTime() {
return this.CreateTime;
}
/**
* Set 批次受理成功时返回,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
* @param CreateTime 批次受理成功时返回,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setCreateTime(String CreateTime) {
this.CreateTime = CreateTime;
}
/**
* Get 批次最近一次更新时间,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
* @return UpdateTime 批次最近一次更新时间,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getUpdateTime() {
return this.UpdateTime;
}
/**
* Set 批次最近一次更新时间,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
* @param UpdateTime 批次最近一次更新时间,遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setUpdateTime(String UpdateTime) {
this.UpdateTime = UpdateTime;
}
/**
* Get 转账成功金额。
转账成功的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
* @return SuccessAmount 转账成功金额。
转账成功的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
*/
public Long getSuccessAmount() {
return this.SuccessAmount;
}
/**
* Set 转账成功金额。
转账成功的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
* @param SuccessAmount 转账成功金额。
转账成功的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setSuccessAmount(Long SuccessAmount) {
this.SuccessAmount = SuccessAmount;
}
/**
* Get 转账成功的笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
* @return SuccessNum 转账成功的笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
*/
public Long getSuccessNum() {
return this.SuccessNum;
}
/**
* Set 转账成功的笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
* @param SuccessNum 转账成功的笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setSuccessNum(Long SuccessNum) {
this.SuccessNum = SuccessNum;
}
/**
* Get 转账失败金额。
转账失败的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
* @return FailAmount 转账失败金额。
转账失败的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
*/
public Long getFailAmount() {
return this.FailAmount;
}
/**
* Set 转账失败金额。
转账失败的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
* @param FailAmount 转账失败金额。
转账失败的金额,单位为分,可能随时变化。
示例值:4000000
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setFailAmount(Long FailAmount) {
this.FailAmount = FailAmount;
}
/**
* Get 转账失败笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
* @return FailNum 转账失败笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
*/
public Long getFailNum() {
return this.FailNum;
}
/**
* Set 转账失败笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
* @param FailNum 转账失败笔数。
可能随时变化。
示例值:200
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setFailNum(Long FailNum) {
this.FailNum = FailNum;
}
/**
* Get 转账明细列表。
返回明细详情
注意:此字段可能返回 null,表示取不到有效值。
* @return TransferDetails 转账明细列表。
返回明细详情
注意:此字段可能返回 null,表示取不到有效值。
*/
public TransferDetailResponse [] getTransferDetails() {
return this.TransferDetails;
}
/**
* Set 转账明细列表。
返回明细详情
注意:此字段可能返回 null,表示取不到有效值。
* @param TransferDetails 转账明细列表。
返回明细详情
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setTransferDetails(TransferDetailResponse [] TransferDetails) {
this.TransferDetails = TransferDetails;
}
/**
* Get 批次类型。
注意:此字段可能返回 null,表示取不到有效值。
* @return BatchType 批次类型。
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getBatchType() {
return this.BatchType;
}
/**
* Set 批次类型。
注意:此字段可能返回 null,表示取不到有效值。
* @param BatchType 批次类型。
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setBatchType(String BatchType) {
this.BatchType = BatchType;
}
/**
* Get 批次名称。
注意:此字段可能返回 null,表示取不到有效值。
* @return BatchName 批次名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getBatchName() {
return this.BatchName;
}
/**
* Set 批次名称。
注意:此字段可能返回 null,表示取不到有效值。
* @param BatchName 批次名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setBatchName(String BatchName) {
this.BatchName = BatchName;
}
/**
* Get 批次标注。
注意:此字段可能返回 null,表示取不到有效值。
* @return BatchRemark 批次标注。
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getBatchRemark() {
return this.BatchRemark;
}
/**
* Set 批次标注。
注意:此字段可能返回 null,表示取不到有效值。
* @param BatchRemark 批次标注。
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setBatchRemark(String BatchRemark) {
this.BatchRemark = BatchRemark;
}
/**
* Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public String getRequestId() {
return this.RequestId;
}
/**
* Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public void setRequestId(String RequestId) {
this.RequestId = RequestId;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "MerchantId", this.MerchantId);
this.setParamSimple(map, prefix + "MerchantBatchNo", this.MerchantBatchNo);
this.setParamSimple(map, prefix + "BatchId", this.BatchId);
this.setParamSimple(map, prefix + "MerchantAppId", this.MerchantAppId);
this.setParamSimple(map, prefix + "BatchStatus", this.BatchStatus);
this.setParamSimple(map, prefix + "CloseReason", this.CloseReason);
this.setParamSimple(map, prefix + "TotalAmount", this.TotalAmount);
this.setParamSimple(map, prefix + "TotalNum", this.TotalNum);
this.setParamSimple(map, prefix + "CreateTime", this.CreateTime);
this.setParamSimple(map, prefix + "UpdateTime", this.UpdateTime);
this.setParamSimple(map, prefix + "SuccessAmount", this.SuccessAmount);
this.setParamSimple(map, prefix + "SuccessNum", this.SuccessNum);
this.setParamSimple(map, prefix + "FailAmount", this.FailAmount);
this.setParamSimple(map, prefix + "FailNum", this.FailNum);
this.setParamArrayObj(map, prefix + "TransferDetails.", this.TransferDetails);
this.setParamSimple(map, prefix + "BatchType", this.BatchType);
this.setParamSimple(map, prefix + "BatchName", this.BatchName);
this.setParamSimple(map, prefix + "BatchRemark", this.BatchRemark);
this.setParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
|
jransijn/picom
|
src/module/dbus/module.c
|
<filename>src/module/dbus/module.c
#include "module.h"
#include "common.h"
#ifdef CONFIG_DBUS
#include "dbus.h"
#endif
struct module_options {
#define OPTION MODULE_DECLARE_OPTION
#include "cfg_mod.h"
#undef OPTION
} options;
struct module_properties {
#define OPTION MODULE_DECLARE_PROPERTY
#include "cfg_mod.h"
#undef OPTION
} prop;
// XXX Still deciding on whether having multiple instances of the same module loaded makes sense
// For now, we just use a single global options struct shared by all instances
// This will of course break, so currently, trying to load the same module twice doesn't work at all
// If we decide we don't need support for multiple module instances we can just inline this, if we want
static inline bool is_module_enabled(module_t *module)
{
UNUSED(module);
return options.enabled;
}
static inline cdbus_session_t *get_cdbus_session(module_t *module)
{
UNUSED(module);
return options.session;
}
static int oninit(modev_t evid, module_t *module, session_t *ps, void *ud)
{
UNUSED(evid);
UNUSED(ud);
if (!is_module_enabled(module)) return 1;
#ifdef CONFIG_DBUS
cdbus_session_t *session = cdbus_create(ps, DisplayString(ps->dpy));
if (session) {
cfg_setpointer(&module->cfg_module, module->options, prop.session, session);
} else {
cfg_setbool(&module->cfg_module, module->options, prop.enabled, false);
}
#else
log_fatal("DBus support not compiled in!");
exit(1);
#endif
return 0;
}
#ifdef CONFIG_DBUS
static int onexit(modev_t evid, module_t *module, session_t *ps, void *ud)
{
UNUSED(evid);
UNUSED(ps);
UNUSED(ud);
if (!is_module_enabled(module)) return 1;
cdbus_session_t *session = get_cdbus_session(module);
assert(session);
cdbus_destroy(session);
return 0;
}
static int onwin_added(modev_t evid, module_t *module, session_t *ps, void *ud)
{
UNUSED(evid);
UNUSED(ps);
if (!is_module_enabled(module)) return 1;
cdbus_session_t *session = get_cdbus_session(module);
cdbus_ev_win_added(session, ud);
return 0;
}
static int onwin_focus(modev_t evid, module_t *module, session_t *ps, void *ud)
{
UNUSED(evid);
UNUSED(ps);
if (!is_module_enabled(module)) return 1;
cdbus_session_t *session = get_cdbus_session(module);
if (evid == MODEV_WIN_FOCUSIN) {
cdbus_ev_win_focusin(session, ud);
} else {
cdbus_ev_win_focusout(session, ud);
}
return 0;
}
static int onwin_destroyed(modev_t evid, module_t *module, session_t *ps, void *ud)
{
UNUSED(evid);
UNUSED(ps);
if (!is_module_enabled(module)) return 1;
cdbus_session_t *session = get_cdbus_session(module);
cdbus_ev_win_destroyed(session, ud);
return 0;
}
static int onwin_unmapped(modev_t evid, module_t *module, session_t *ps, void *ud)
{
UNUSED(evid);
UNUSED(ps);
if (!is_module_enabled(module)) return 1;
cdbus_session_t *session = get_cdbus_session(module);
cdbus_ev_win_unmapped(session, ud);
return 0;
}
static int onwin_mapped(modev_t evid, module_t *module, session_t *ps, void *ud)
{
UNUSED(evid);
UNUSED(ps);
if (!is_module_enabled(module)) return 1;
cdbus_session_t *session = get_cdbus_session(module);
cdbus_ev_win_mapped(session, ud);
return 0;
}
#endif
static int load(session_t *ps, module_t *module, void *ud) {
UNUSED(ps);
UNUSED(ud);
module->options = &options;
#define OPTION(...) MODULE_ADD_OPTION(prop, &module->cfg_module, &options, __VA_ARGS__)
#include "cfg_mod.h"
#undef OPTION
#define OPTION(...) MODULE_SET_OPTION_DEFAULT(prop, &module->cfg_module, &options, __VA_ARGS__)
#include "cfg_mod.h"
#undef OPTION
module_subscribe(module, MODEV_EARLY_INIT, oninit);
#ifdef CONFIG_DBUS
module_subscribe(module, MODEV_EXIT, onexit);
module_subscribe(module, MODEV_WIN_ADDED, onwin_added);
module_subscribe(module, MODEV_WIN_FOCUSIN, onwin_focus);
module_subscribe(module, MODEV_WIN_FOCUSOUT, onwin_focus);
module_subscribe(module, MODEV_WIN_DESTROYED, onwin_destroyed);
module_subscribe(module, MODEV_WIN_UNMAPPED, onwin_unmapped);
module_subscribe(module, MODEV_WIN_MAPPED, onwin_mapped);
#endif
return 0;
}
modinfo_t modinfo_dbus = {
.name = "dbus",
.load = load,
.unload = NULL,
};
|
SleepyRae/IntelligenceCoding
|
hoj-springboot/DataBackup/src/main/java/top/hcode/hoj/pojo/vo/CaptchaVo.java
|
<filename>hoj-springboot/DataBackup/src/main/java/top/hcode/hoj/pojo/vo/CaptchaVo.java
package top.hcode.hoj.pojo.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @Author: Himit_ZH
* @Date: 2022/3/11 16:37
* @Description:
*/
@Data
public class CaptchaVo {
@ApiModelProperty(value = "验证码图片的base64")
private String img;
@ApiModelProperty(value = "验证码key")
private String captchaKey;
}
|
allexjs/sdk
|
src/ws/websuites/relink.js
|
<reponame>allexjs/sdk<gh_stars>1-10
'use strict';
function createRelink (Lib, Node) {
'use strict';
var Fs = Node.Fs,
Path = Node.Path,
recognize = Lib.moduleRecognition,
AllexJS = require('allex_allexjshelperssdklib')(Lib),
ALLEX_WORKSPACE_DIR = AllexJS.ALLEX_WORKSPACE_DIR,
BaseWSWorkerClass = require('../baseclasses.js')(Lib, AllexJS).BaseWSWorkerClass,
Git = require('allex_githelperssdklib')(Lib),
Q = Lib.q,
WebAppTools = require('../../webalizer')(Lib).WebAppTools;
function doRelink (project, suitename, webapp){
if ('./' === webapp) return; ///TODO: anomaly to be resolved
var app = Path.resolve(ALLEX_WORKSPACE_DIR, 'projects', project, 'websolutions', suitename, webapp, '_generated'),
linkdirname = Path.resolve(ALLEX_WORKSPACE_DIR, '.webapps', project, suitename),
link = Path.resolve(linkdirname, webapp);
if (Fs.existsSync(link)) return;
try {
Fs.ensureDirSync(linkdirname);
Fs.symlinkSync (app, link);
}catch (ignore) {
}
}
function push_web_app (project, suitename) {
WebAppTools.findWebApps(Path.resolve(ALLEX_WORKSPACE_DIR, 'projects', project, 'websolutions', suitename)).forEach(doRelink.bind(null, project, suitename));
}
function find_in_solution(project, path){
Fs.readdirSync(path).forEach (push_web_app.bind(null, project))
}
function findSuite (project){
var pp = Path.resolve(ALLEX_WORKSPACE_DIR, 'projects', project, 'websolutions');
if (!Fs.dirExists(pp)) return;
Fs.readdirSync(pp).forEach (find_in_solution.bind(null, project, Path.resolve(ALLEX_WORKSPACE_DIR, 'projects', project, 'websolutions')));
}
function linkDeployment (item) {
var target = Path.resolve(ALLEX_WORKSPACE_DIR, '.webapps', item.project, item.name),
source = Path.resolve(ALLEX_WORKSPACE_DIR, 'projects', item.project, 'webdeployments', item.name);
if (!Fs.dirExists(source)) return;
if (Fs.existsSync(target)) return;
Fs.symlinkSync (source, target);
}
return function () {
var webappsdirname, projects;
webappsdirname = Path.resolve(ALLEX_WORKSPACE_DIR, '.webapps');
Node.Fs.ensureDirSync(webappsdirname);
Node.executeCommandSync ('find '+webappsdirname+' -type l -delete');
projects = Fs.readdirSync (Path.resolve(ALLEX_WORKSPACE_DIR, 'projects'));
projects.forEach (findSuite);
var webds = AllexJS.getAllexJSData().webdeployments;
if (webds){
Lib.traverseShallow (webds, linkDeployment);
}
return Q.resolve('ok');
};
}
module.exports = createRelink;
|
Abdullah108/hugeheart
|
hugeheart/super-admin/src/config/Constant.js
|
export const AcceptedImageFormat = [
'image/jpg',
'image/png',
'image/jpeg',
'image/tiff',
'image/gif',
];
export const AcceptedDocFormat = [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/msword',
'text/plain',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/pdf',
];
|
clfs/relic
|
lib/assuan/assuan.go
|
<reponame>clfs/relic
//
// Copyright (c) SAS Institute 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 assuan
import (
"bufio"
"errors"
"fmt"
"net"
"net/url"
"strings"
"sync"
"github.com/sassoftware/relic/lib/dlog"
)
// Simple libassuan client
//
// See: https://www.gnupg.org/software/libassuan/index.html
const (
StatusOk = "OK"
StatusErr = "ERR"
StatusInquire = "INQUIRE"
StatusData = "D"
StatusLines = "S"
StatusComment = "#"
)
type Conn struct {
conn net.Conn
r *bufio.Reader
mu sync.Mutex
}
type Response struct {
Status string
StatusMessage string
Lines []string
Blob []byte
}
func (r Response) Error() string {
return fmt.Sprintf("response error: %s", r.StatusMessage)
}
type InquireFunc func(inquireLine string, msgLines []string) (string, error)
var InquireCancel = errors.New("inquiry cancelled")
func Dial(path string) (*Conn, error) {
conn, err := net.Dial("unix", path)
if err != nil {
return nil, err
}
s := &Conn{
conn: conn,
r: bufio.NewReader(conn),
}
status, msg, err := s.readLine()
if err != nil {
conn.Close()
return nil, err
} else if status != StatusOk {
conn.Close()
return nil, fmt.Errorf("failed to connect to %s: %s", path, msg)
}
return s, nil
}
func (c *Conn) write(cmd string) error {
dlog.Printf(7, "> %#v", cmd)
_, err := c.conn.Write([]byte(cmd))
return err
}
func (c *Conn) data(data string) error {
data = url.PathEscape(data)
for len(data) > 0 {
n := 512
if n > len(data) {
n = len(data)
}
chunk := data[:n]
data = data[n:]
if err := c.write(fmt.Sprintf("D %s\n", chunk)); err != nil {
return err
}
}
return c.write("END\n")
}
func (c *Conn) readLine() (string, string, error) {
line, err := c.r.ReadString('\n')
if err != nil {
return "", "", err
}
line = line[:len(line)-1]
dlog.Printf(7, "< %#v", line)
parts := strings.SplitN(line, " ", 2)
status := parts[0]
if len(parts) > 1 {
return status, parts[1], nil
}
return status, "", nil
}
func (c *Conn) read(inquire InquireFunc) (res Response, err error) {
var quotedBlob string
var saved error
readloop:
for {
status, msg, err := c.readLine()
if err != nil {
return res, err
}
switch status {
case StatusData:
quotedBlob += msg
case StatusLines:
msg, err := url.PathUnescape(msg)
if err != nil {
return res, err
}
res.Lines = append(res.Lines, msg)
case StatusInquire:
if inquire != nil {
d, err := inquire(msg, res.Lines)
if err != nil {
c.write("CANCEL\n")
if err != InquireCancel {
// raise this once the ERR has been received
saved = err
}
} else {
if err := c.data(d); err != nil {
return res, err
}
}
} else {
c.write("CANCEL\n")
}
case StatusComment:
// no-op
default:
res.Status = status
res.StatusMessage = msg
break readloop
}
}
if len(quotedBlob) > 0 {
blob, err := url.PathUnescape(quotedBlob)
if err != nil {
return res, err
}
res.Blob = []byte(blob)
}
err = saved
return
}
// Execute a command and retrieve the result.
//
// If an INQUIRE is received then inquire() will be invoked with the text after
// INQUIRE and all status lines received so far. It should return data to send,
// or it can return an err of InquireCancel which will cause a CANCEL to be
// sent and the resulting response to be returned. If inquire is nil then a
// CANCEL is always sent.
func (c *Conn) Transact(command string, inquire InquireFunc) (res Response, err error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
return res, errors.New("connection is closed")
}
if err := c.write(command + "\n"); err != nil {
return res, err
}
res, err = c.read(inquire)
if err == nil && res.Status != StatusOk {
err = res
}
return
}
func (c *Conn) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.conn != nil {
c.conn.Close()
c.conn = nil
c.r = nil
}
return nil
}
|
jiben071/DLMyTechBuildUp
|
DLGenTechBuildup/DLGenTechBuildup/Expand/Helper/YMPulsingHaloLayer.h
|
<reponame>jiben071/DLMyTechBuildUp<filename>DLGenTechBuildup/DLGenTechBuildup/Expand/Helper/YMPulsingHaloLayer.h<gh_stars>0
//
// YMPulsingHaloLayer.h
// YM
// 脉冲动画层
// Created by QinMingChuan on 14-5-5.
// Copyright (c) 2014年 QinMingChuan. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface YMPulsingHaloLayer : CALayer
@property (nonatomic) CGFloat radius; // default:60pt
@property (nonatomic) NSTimeInterval animationDuration; // default:3s
@property (nonatomic) NSTimeInterval pulseInterval; // default is 0s
//开始动画并指定延迟开始时间
- (void)beginAnimationAfterDelay:(NSTimeInterval)afterDelay;
//关闭动画
- (void)closeAnimation;
@end
|
serval-uni-lu/ikora-smells
|
src/main/java/lu/uni/serval/ikora/smells/checks/ComplicatedSetupCheck.java
|
<gh_stars>0
package lu.uni.serval.ikora.smells.checks;
/*-
* #%L
* Ikora Smells
* %%
* Copyright (C) 2020 - 2021 University of Luxembourg
* %%
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import lu.uni.serval.ikora.core.model.*;
import lu.uni.serval.ikora.smells.SmellCheck;
import lu.uni.serval.ikora.smells.SmellConfiguration;
import lu.uni.serval.ikora.smells.SmellMetric;
import lu.uni.serval.ikora.smells.SmellResult;
import lu.uni.serval.ikora.core.analytics.KeywordStatistics;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
public class ComplicatedSetupCheck implements SmellCheck {
@Override
public SmellResult computeMetric(TestCase testCase, SmellConfiguration configuration) {
double rawValue = Double.NaN;
double normalizedValue = Double.NaN;
final Set<SourceNode> nodes = new HashSet<>();
final Optional<KeywordCall> setup = testCase.getSetup().flatMap(TestProcessing::getCall);
if(setup.isPresent()){
int setupSize = KeywordStatistics.getSequenceSize(setup.get());
int testCaseSize = KeywordStatistics.getSequenceSize(testCase);
nodes.add(setup.get());
rawValue = setupSize;
normalizedValue = rawValue / (setupSize + testCaseSize);
}
return new SmellResult(SmellMetric.Type.COMPLICATED_SETUP_SCENARIOS, rawValue, normalizedValue, nodes);
}
@Override
public Set<SourceNode> collectInstances(SourceFile file, SmellConfiguration configuration) {
final Set<SourceNode> nodes = new HashSet<>();
for(TestCase testCase: file.getTestCases()){
final SmellResult smellResult = computeMetric(testCase, configuration);
if(smellResult.getNormalizedValue() < configuration.getSetupTestRatio()){
nodes.addAll(smellResult.getNodes());
}
}
return nodes;
}
}
|
dommonty/eligauqa
|
modules/projects/client/controllers/projects.client.controller.js
|
<filename>modules/projects/client/controllers/projects.client.controller.js
(function () {
'use strict';
// Projects controller
angular
.module('projects')
.controller('ProjectsController', ProjectsController);
ProjectsController.$inject = [ '$scope', '$state', 'Authentication', 'projectResolve', 'CustomersService',
'OutcometeamsService', '$window', 'BusinessunitsService', 'SquadsService' ];
function ProjectsController($scope, $state, Authentication, project, CustomersService,
OutcometeamsService, $window, BusinessunitsService, SquadsService) {
var vm = this;
vm.authentication = Authentication;
vm.project = project;
vm.error = null;
vm.form = {};
vm.remove = remove;
vm.save = save;
vm.customers = CustomersService.query();
vm.format = 'dd-MMMM-yyyy';
vm.altInputFormats = [ 'd!/M!/yyyy', 'dd.MM.yyyy' ];
vm.allOutcomeTeams = vm.outcomeTeams = OutcometeamsService.query();
var storyPointsScale, chartSeries;
vm.updateOutcomeTeamsList = updateOutcomeTeamsList;
vm.outcomeTeamChanged = outcomeTeamChanged;
vm.businessUnits = BusinessunitsService.query();
function updateOutcomeTeamsList() {
vm.outcomeTeams = [];
for (var i = 0; i < vm.allOutcomeTeams.length; i++) {
var eachTeam = vm.allOutcomeTeams[ i ];
if (eachTeam.businessUnit._id === vm.project.businessUnit._id)
vm.outcomeTeams.push(eachTeam);
}
}
function outcomeTeamChanged() {
vm.projectManagers = [];
SquadsService.query({outcomeTeamId: vm.project.outcomeTeam._id}).$promise.then(function (squads) {
angular.forEach(squads, function (eachSquad) {
vm.projectManagers.push(eachSquad.squadOwner);
});
});
}
if (vm.project._id) {
outcomeTeamChanged();
vm.project.startDate = new Date(vm.project.startDate); //ui-date-picker expects a JS Date not a string
vm.project.endDate = new Date(vm.project.endDate);
if (project.advisoryCommitteeApprovalDate)
vm.project.advisoryCommitteeApprovalDate = new Date(vm.project.advisoryCommitteeApprovalDate);
}
calculateChartAxisData();
// Remove existing Project
function remove() {
if (confirm('Are you sure you want to delete?')) {
vm.project.$remove($state.go('projects.list'));
}
}
// Save Project
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.projectForm');
return false;
}
// TODO: move create/update logic to service
if (vm.project._id) {
vm.project.$update(successCallback, errorCallback);
} else {
vm.project.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('projects.view', {
projectId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
vm.openStartCalendar = function () {
vm.isStartCalendarOpen = true;
};
vm.openEndCalendar = function () {
vm.isEndCalendarOpen = true;
};
vm.openAdvisoryCalendar = function () {
vm.isAdvisoryCalendarOpen = true;
};
function calculateChartAxisData() {
storyPointsScale = [];
chartSeries = [
{
name: 'Estimated',
data: []
},
{
name: 'Actual',
data: []
}
];
if (vm.project.plannedSprints > 0) {
var pointsPerStoryPoint = Math.round(vm.project.estimatedStoryPoints / vm.project.plannedSprints);
var storyPointsLeft = vm.project.estimatedStoryPoints;
var sprintCount = 0;
var actualStoryPointsLeft = vm.project.estimatedStoryPoints;
for (var i = 1; i <= vm.project.plannedSprints + 1; i++) {
storyPointsScale.push(sprintCount);
chartSeries[ 0 ].data.push(Math.round(storyPointsLeft));
chartSeries[ 1 ].data.push(Math.round(actualStoryPointsLeft));
storyPointsLeft = storyPointsLeft - pointsPerStoryPoint;
if (vm.project.sprints.length >= i)
actualStoryPointsLeft = actualStoryPointsLeft - vm.project.sprints[ i - 1 ].actualStoryPoints;
sprintCount = i;
}
}
}
$window.Highcharts.chart('burndown-container', {
chart: {
type: 'area',
inverted: false
},
title: {
text: 'Project Burn Down Chart'
},
subtitle: {
style: {
position: 'absolute',
right: '0px',
bottom: '10px'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -150,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: ($window.Highcharts.theme && $window.Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
xAxis: {
categories: storyPointsScale,
title: {
text: 'Sprint Number'
}
},
yAxis: {
title: {
text: 'Story Points'
},
labels: {
formatter: function () {
return this.value;
}
},
min: 0
},
plotOptions: {
area: {
fillOpacity: 0.5
}
},
series: chartSeries
});
}
})();
|
spookandpuff/spooky-core
|
.bundle/gems/webmock-1.8.4/lib/webmock/util/json.rb
|
# This is a copy of https://github.com/jnunemaker/crack/blob/master/lib/crack/json.rb
# with date parsing removed
module WebMock
module Util
class JSON
def self.parse(json)
YAML.load(unescape(convert_json_to_yaml(json)))
rescue ArgumentError
raise ParseError, "Invalid JSON string"
end
protected
def self.unescape(str)
str.gsub(/\\u([0-9a-f]{4})/) { [$1.hex].pack("U") }
end
# Ensure that ":" and "," are always followed by a space
def self.convert_json_to_yaml(json) #:nodoc:
scanner, quoting, marks, pos, times = StringScanner.new(json), false, [], nil, []
while scanner.scan_until(/(\\['"]|['":,\\]|\\.)/)
case char = scanner[1]
when '"', "'"
if !quoting
quoting = char
pos = scanner.pos
elsif quoting == char
quoting = false
end
when ":",","
marks << scanner.pos - 1 unless quoting
when "\\"
scanner.skip(/\\/)
end
end
if marks.empty?
json.gsub(/\\\//, '/')
else
left_pos = [-1].push(*marks)
right_pos = marks << json.length
output = []
left_pos.each_with_index do |left, i|
output << json[left.succ..right_pos[i]]
end
output = output * " "
times.each { |i| output[i-1] = ' ' }
output.gsub!(/\\\//, '/')
output
end
end
end
end
end
|
TreeBASE/treebasetest
|
treebase-core/src/main/java/org/cipres/treebase/framework/ExecutionResult.java
|
package org.cipres.treebase.framework;
/**
* Indicates the execution result status. It can has an error message if the execution action fails.
*
* Created on Nov 20, 2006
*
* @author <NAME>
*/
public class ExecutionResult {
private String mErrorMessage;
private int mSuccessfulCount;
private int mFailureCount;
/**
* Constructor.
*/
public ExecutionResult() {
super();
}
/**
* Return the error Message field.
*
* @return String mErrorMessage
*/
public String getErrorMessage() {
if (mErrorMessage == null) {
mErrorMessage = new String();
}
return mErrorMessage;
}
/**
* Add an error Message.
*
* @param String
*/
public void addErrorMessage(String pMessage) {
String msg = getErrorMessage();
if (msg.length() > 1) {
msg += "/n";
}
msg += pMessage;
setErrorMessage(msg);
}
/**
* Report the count of failures for the result.
*
* @return int mFilureCount
*/
public int getFailureCount() {
return mFailureCount;
}
/**
* Set the FilureCount field.
*/
public void setFailureCount(int pNewFilureCount) {
mFailureCount = pNewFilureCount;
}
/**
* Report the count of success for the execution.
*
* @return
*/
public int getSuccessfulCount() {
return mSuccessfulCount;
}
/**
* Set the SuccessfulCount field.
*/
public void setSuccessfulCount(int pNewSuccessfulCount) {
mSuccessfulCount = pNewSuccessfulCount;
}
/**
* Determine if the action was successful
*
* @param boolean
*/
public boolean isSuccessful() {
return getErrorMessage().length() == 0;
}
/**
* @param pErrorMessage the errorMessage to set
*/
private void setErrorMessage(String pErrorMessage) {
mErrorMessage = pErrorMessage;
}
}
|
jddixon/xlTransport_java
|
src/java/org/xlattice/transport/Attachment.java
|
<gh_stars>0
/* Attachment.java */
package org.xlattice.transport;
/**
* @author <NAME>
*/
class Attachment {
// DEBUG
// STATICS //////////////////////////////////////////////////////
static int nextIndex = 0;
static Object indexLock = new Object();
// END
// CONSTANTS ////////////////////////////////////////////////////
public final static int NIX_A = 0;
public final static int ACC_A = 1; // Acceptor
public final static int CNX_A = 2; // Connection
public final static int CTR_A = 3; // Connector
public final static int PKT_A = 4; // PacketPort
// INSTANCE VARIABLES ///////////////////////////////////////////
int type;
Object obj;
// DEBUG
final int index;
// END
// CONSTRUCTORS /////////////////////////////////////////////////
protected Attachment (int t, Object o) {
// DEBUG
synchronized (indexLock) {
index = nextIndex++;
}
// END
if (t < ACC_A || t > PKT_A)
throw new IllegalArgumentException("unrecognized type " + t);
if (o == null)
throw new IllegalArgumentException("object may not be null");
type = t;
obj = o;
}
}
|
AndEditor7/MCPE-Clone
|
Base.java
|
package com.andedit.arcubit;
import com.andedit.arcubit.handles.Inputs;
import com.andedit.arcubit.ui.utils.StageUtils;
import com.andedit.arcubit.utils.BlockPos;
import com.andedit.arcubit.utils.Util;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
public abstract class Base extends Game {
public Stage stage;
public final InputMultiplexer inputs = new InputMultiplexer();
protected Screen newScreen;
@Override
public void render() {
nextScreen();
super.render();
Gdx.gl.glUseProgram(0);
Inputs.reset();
BlockPos.reset();
}
protected void nextScreen() {
if (newScreen == null)
return;
if (screen != null)
screen.hide();
screen = newScreen;
newScreen = null;
stage.clear(); // Always clear UI when switching screen.
inputs.clear(); // Always clear the input processors.
screen.show();
screen.resize(stage.getViewport().getScreenWidth(), stage.getViewport().getScreenHeight());
resize();
}
/** Scale the UI. */
public void scale(int scale) {
final ScreenViewport view = (ScreenViewport)stage.getViewport();
view.setUnitsPerPixel(1 / (float) scale);
view.update(view.getScreenWidth(), view.getScreenHeight(), true);
super.resize(view.getScreenWidth(), view.getScreenHeight());
resize();
}
@Override
public void resize(int width, int height) {
final ScreenViewport view = (ScreenViewport)stage.getViewport();
view.setUnitsPerPixel(1 / (float)Math.max(1, MathUtils.round(height*(Util.isDesktop()?0.0045f:0.0063f)))); // 0.0065f
view.update(width, height, true);
super.resize(width, height);
resize();
Inputs.clear();
}
/** Reqest for UI re-position. */
public void resize() {
StageUtils.resize(stage);
}
@Override
public void setScreen(Screen screen) {
newScreen = screen;
}
@Override
public void dispose() {
if (screen != null) {
screen.dispose();
screen = null;
}
if (newScreen != null) {
newScreen.dispose();
newScreen = null;
}
}
}
|
sethlu/vox
|
src/utils/logging.cpp
|
#include "logging.h"
#define MIN_LOG_LEVEL_UNSET INT_MAX
namespace {
int minLogLevel = MIN_LOG_LEVEL_UNSET;
}
namespace renderbox {
int getMinLogLevel() {
if (minLogLevel == MIN_LOG_LEVEL_UNSET) {
if (const char *envRenderBoxLogLevel = std::getenv("RENDERBOX_LOG_LEVEL")) {
minLogLevel = std::stoi(envRenderBoxLogLevel);
} else {
minLogLevel = MIN_LOG_LEVEL_DEFAULT;
}
}
return minLogLevel;
}
void setMinLogLevel(int level) {
minLogLevel = level;
}
}
|
Wallace4ever/Algorithms
|
src/edu/LeetCode/DP/No188_BestTimeBuySellStockIV.java
|
<reponame>Wallace4ever/Algorithms<gh_stars>0
package edu.LeetCode.DP;
import org.junit.Test;
import java.util.Arrays;
public class No188_BestTimeBuySellStockIV {
public int maxProfit(int k,int[] prices) {
if (k <= 0 || prices == null || prices.length <= 1) return 0;
int n = prices.length;
if (k > n/2) return maxProfit(prices);
int[] min = new int[k];
int[] maxProfit = new int[k];
Arrays.fill(min, Integer.MAX_VALUE);
for (int price : prices) {
for (int i = 0; i < k; i++) {
min[i] = Math.min(min[i], i == 0 ? price : price - maxProfit[i - 1]);
maxProfit[i] = Math.max(maxProfit[i], price - min[i]);
}
}
return maxProfit[k-1];
}
private int maxProfit(int[] prices) {
int totalProfit = 0;
for (int i = 1; i < prices.length; i++) {
int greedyProfit = prices[i] - prices[i - 1];
if (greedyProfit > 0) totalProfit += greedyProfit;
}
return totalProfit;
}
@Test
public void test() {
System.out.println(maxProfit(2,new int[]{3,7,2,5,0,3}));
}
}
|
touxiong88/92_mediatek
|
custom/common/kernel/imgsensor/gc2235_raw/gc2235_Sensor.c
|
/*****************************************************************************
*
* Filename:
* ---------
* sensor.c
*
* Project:
* --------
* RAW
*
* Description:
* ------------
* Source code of Sensor driver
*
*
* Author:
* -------
* <NAME>
*
*============================================================================
* HISTORY
*------------------------------------------------------------------------------
* $Revision:$
* $Modtime:$
* $Log:$
*
* 04 10 2013
* First release MT6589 GC2235 driver Version 1.0
*
*------------------------------------------------------------------------------
*============================================================================
****************************************************************************/
#include <linux/videodev2.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#include <linux/fs.h>
#include <asm/atomic.h>
#include "kd_camera_hw.h"
#include "kd_imgsensor.h"
#include "kd_imgsensor_define.h"
#include "kd_imgsensor_errcode.h"
#include "gc2235_Sensor.h"
#include "gc2235_Camera_Sensor_para.h"
#include "gc2235_CameraCustomized.h"
#ifdef GC2235_DEBUG
#define SENSORDB printk
#else
#define SENSORDB(x,...)
#endif
#if defined(MT6577)||defined(MT6589)
static DEFINE_SPINLOCK(gc2235_drv_lock);
#endif
extern int iReadRegI2C(u8 *a_pSendData , u16 a_sizeSendData, u8 * a_pRecvData, u16 a_sizeRecvData, u16 i2cId);
extern int iWriteRegI2C(u8 *a_pSendData , u16 a_sizeSendData, u16 i2cId);
static GC2235_sensor_struct GC2235_sensor =
{
.eng_info =
{
.SensorId = 128,
.SensorType = CMOS_SENSOR,
.SensorOutputDataFormat = GC2235_COLOR_FORMAT,
},
.Mirror = GC2235_IMAGE_H_MIRROR,
.shutter = 0x20,
.gain = 0x20,
.pclk = GC2235_PREVIEW_CLK,
.frame_height = GC2235_PV_PERIOD_LINE_NUMS,
.line_length = GC2235_PV_PERIOD_PIXEL_NUMS,
};
/*************************************************************************
* FUNCTION
* GC2235_write_cmos_sensor
*
* DESCRIPTION
* This function wirte data to CMOS sensor through I2C
*
* PARAMETERS
* addr: the 16bit address of register
* para: the 8bit value of register
*
* RETURNS
* None
*
* LOCAL AFFECTED
*
*************************************************************************/
static void GC2235_write_cmos_sensor(kal_uint8 addr, kal_uint8 para)
{
kal_uint8 out_buff[2];
out_buff[0] = addr;
out_buff[1] = para;
iWriteRegI2C((u8*)out_buff , (u16)sizeof(out_buff), GC2235_WRITE_ID);
}
/*************************************************************************
* FUNCTION
* GC2035_read_cmos_sensor
*
* DESCRIPTION
* This function read data from CMOS sensor through I2C.
*
* PARAMETERS
* addr: the 16bit address of register
*
* RETURNS
* 8bit data read through I2C
*
* LOCAL AFFECTED
*
*************************************************************************/
static kal_uint8 GC2235_read_cmos_sensor(kal_uint8 addr)
{
kal_uint8 in_buff[1] = {0xFF};
kal_uint8 out_buff[1];
out_buff[0] = addr;
if (0 != iReadRegI2C((u8*)out_buff , (u16) sizeof(out_buff), (u8*)in_buff, (u16) sizeof(in_buff), GC2235_WRITE_ID)) {
SENSORDB("ERROR: GC2235_read_cmos_sensor \n");
}
return in_buff[0];
}
/*************************************************************************
* FUNCTION
* GC2235_SetShutter
*
* DESCRIPTION
* This function set e-shutter of GC2235 to change exposure time.
*
* PARAMETERS
* iShutter : exposured lines
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void GC2235_set_shutter(kal_uint16 iShutter)
{
#if defined(MT6577)||defined(MT6589)
spin_lock(&gc2235_drv_lock);
#endif
GC2235_sensor.shutter = iShutter;
#if defined(MT6577)||defined(MT6589)
spin_unlock(&gc2235_drv_lock);
#endif
if (!iShutter) iShutter = 1; /* avoid 0 */
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235_set_shutter iShutter = %d \n",iShutter);
#endif
if(iShutter < 1) iShutter = 1;
if(iShutter > 8192) iShutter = 8192;//2^13
//Update Shutter
GC2235_write_cmos_sensor(0x04, (iShutter) & 0xFF);
GC2235_write_cmos_sensor(0x03, (iShutter >> 8) & 0x1F);
} /* Set_GC2235_Shutter */
/*************************************************************************
* FUNCTION
* GC2235_SetGain
*
* DESCRIPTION
* This function is to set global gain to sensor.
*
* PARAMETERS
* iGain : sensor global gain(base: 0x40)
*
* RETURNS
* the actually gain set to sensor.
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint16 GC2235_SetGain(kal_uint16 iGain)
{
kal_uint16 iReg,temp;
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235_SetGain iGain = %d \n",iGain);
#endif
iReg = iGain;
if(256> iReg)
{
//analogic gain
GC2235_write_cmos_sensor(0xb0, 0x40); // global gain
GC2235_write_cmos_sensor(0xb1, iReg);//only digital gain 12.13
}
else
{
//analogic gain
temp = 64*iReg/256;
GC2235_write_cmos_sensor(0xb0, temp); // global gain
GC2235_write_cmos_sensor(0xb1, 0xff);//only digital gain 12.13
}
return iGain;
}
/*************************************************************************
* FUNCTION
* GC2235_NightMode
*
* DESCRIPTION
* This function night mode of GC2235.
*
* PARAMETERS
* bEnable: KAL_TRUE -> enable night mode, otherwise, disable night mode
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void GC2235_night_mode(kal_bool enable)
{
/*No Need to implement this function*/
#if 0
const kal_uint16 dummy_pixel = GC2235_sensor.line_length - GC2235_PV_PERIOD_PIXEL_NUMS;
const kal_uint16 pv_min_fps = enable ? GC2235_sensor.night_fps : GC2235_sensor.normal_fps;
kal_uint16 dummy_line = GC2235_sensor.frame_height - GC2235_PV_PERIOD_LINE_NUMS;
kal_uint16 max_exposure_lines;
printk("[GC2235_night_mode]enable=%d",enable);
if (!GC2235_sensor.video_mode) return;
max_exposure_lines = GC2235_sensor.pclk * GC2235_FPS(1) / (pv_min_fps * GC2235_sensor.line_length);
if (max_exposure_lines > GC2235_sensor.frame_height) /* fix max frame rate, AE table will fix min frame rate */
// {
// dummy_line = max_exposure_lines - GC2235_PV_PERIOD_LINE_NUMS;
// }
#endif
} /* GC2235_NightMode */
/* write camera_para to sensor register */
static void GC2235_camera_para_to_sensor(void)
{
kal_uint32 i;
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235_camera_para_to_sensor\n");
#endif
for (i = 0; 0xFFFFFFFF != GC2235_sensor.eng.reg[i].Addr; i++)
{
GC2235_write_cmos_sensor(GC2235_sensor.eng.reg[i].Addr, GC2235_sensor.eng.reg[i].Para);
}
for (i = GC2235_FACTORY_START_ADDR; 0xFFFFFFFF != GC2235_sensor.eng.reg[i].Addr; i++)
{
GC2235_write_cmos_sensor(GC2235_sensor.eng.reg[i].Addr, GC2235_sensor.eng.reg[i].Para);
}
GC2235_SetGain(GC2235_sensor.gain); /* update gain */
}
/* update camera_para from sensor register */
static void GC2235_sensor_to_camera_para(void)
{
kal_uint32 i,temp_data;
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235_sensor_to_camera_para\n");
#endif
for (i = 0; 0xFFFFFFFF != GC2235_sensor.eng.reg[i].Addr; i++)
{
temp_data = GC2235_read_cmos_sensor(GC2235_sensor.eng.reg[i].Addr);
#if defined(MT6577)||defined(MT6589)
spin_lock(&gc2235_drv_lock);
#endif
GC2235_sensor.eng.reg[i].Para = temp_data;
#if defined(MT6577)||defined(MT6589)
spin_unlock(&gc2235_drv_lock);
#endif
}
for (i = GC2235_FACTORY_START_ADDR; 0xFFFFFFFF != GC2235_sensor.eng.reg[i].Addr; i++)
{
temp_data = GC2235_read_cmos_sensor(GC2235_sensor.eng.reg[i].Addr);
#if defined(MT6577)||defined(MT6589)
spin_lock(&gc2235_drv_lock);
#endif
GC2235_sensor.eng.reg[i].Para = temp_data;
#if defined(MT6577)||defined(MT6589)
spin_unlock(&gc2235_drv_lock);
#endif
}
}
/* ------------------------ Engineer mode ------------------------ */
inline static void GC2235_get_sensor_group_count(kal_int32 *sensor_count_ptr)
{
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235_get_sensor_group_count\n");
#endif
*sensor_count_ptr = GC2235_GROUP_TOTAL_NUMS;
}
inline static void GC2235_get_sensor_group_info(MSDK_SENSOR_GROUP_INFO_STRUCT *para)
{
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235_get_sensor_group_info\n");
#endif
switch (para->GroupIdx)
{
case GC2235_PRE_GAIN:
sprintf(para->GroupNamePtr, "CCT");
para->ItemCount = 5;
break;
case GC2235_CMMCLK_CURRENT:
sprintf(para->GroupNamePtr, "CMMCLK Current");
para->ItemCount = 1;
break;
case GC2235_FRAME_RATE_LIMITATION:
sprintf(para->GroupNamePtr, "Frame Rate Limitation");
para->ItemCount = 2;
break;
case GC2235_REGISTER_EDITOR:
sprintf(para->GroupNamePtr, "Register Editor");
para->ItemCount = 2;
break;
default:
ASSERT(0);
}
}
inline static void GC2235_get_sensor_item_info(MSDK_SENSOR_ITEM_INFO_STRUCT *para)
{
const static kal_char *cct_item_name[] = {"SENSOR_BASEGAIN", "Pregain-R", "Pregain-Gr", "Pregain-Gb", "Pregain-B"};
const static kal_char *editer_item_name[] = {"REG addr", "REG value"};
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235_get_sensor_item_info\n");
#endif
switch (para->GroupIdx)
{
case GC2235_PRE_GAIN:
switch (para->ItemIdx)
{
case GC2235_SENSOR_BASEGAIN:
case GC2235_PRE_GAIN_R_INDEX:
case GC2235_PRE_GAIN_Gr_INDEX:
case GC2235_PRE_GAIN_Gb_INDEX:
case GC2235_PRE_GAIN_B_INDEX:
break;
default:
ASSERT(0);
}
sprintf(para->ItemNamePtr, cct_item_name[para->ItemIdx - GC2235_SENSOR_BASEGAIN]);
para->ItemValue = GC2235_sensor.eng.cct[para->ItemIdx].Para * 1000 / BASEGAIN;
para->IsTrueFalse = para->IsReadOnly = para->IsNeedRestart = KAL_FALSE;
para->Min = GC2235_MIN_ANALOG_GAIN * 1000;
para->Max = GC2235_MAX_ANALOG_GAIN * 1000;
break;
case GC2235_CMMCLK_CURRENT:
switch (para->ItemIdx)
{
case 0:
sprintf(para->ItemNamePtr, "Drv Cur[2,4,6,8]mA");
switch (GC2235_sensor.eng.reg[GC2235_CMMCLK_CURRENT_INDEX].Para)
{
case ISP_DRIVING_2MA:
para->ItemValue = 2;
break;
case ISP_DRIVING_4MA:
para->ItemValue = 4;
break;
case ISP_DRIVING_6MA:
para->ItemValue = 6;
break;
case ISP_DRIVING_8MA:
para->ItemValue = 8;
break;
default:
ASSERT(0);
}
para->IsTrueFalse = para->IsReadOnly = KAL_FALSE;
para->IsNeedRestart = KAL_TRUE;
para->Min = 2;
para->Max = 8;
break;
default:
ASSERT(0);
}
break;
case GC2235_FRAME_RATE_LIMITATION:
switch (para->ItemIdx)
{
case 0:
sprintf(para->ItemNamePtr, "Max Exposure Lines");
para->ItemValue = 5998;
break;
case 1:
sprintf(para->ItemNamePtr, "Min Frame Rate");
para->ItemValue = 5;
break;
default:
ASSERT(0);
}
para->IsTrueFalse = para->IsNeedRestart = KAL_FALSE;
para->IsReadOnly = KAL_TRUE;
para->Min = para->Max = 0;
break;
case GC2235_REGISTER_EDITOR:
switch (para->ItemIdx)
{
case 0:
case 1:
sprintf(para->ItemNamePtr, editer_item_name[para->ItemIdx]);
para->ItemValue = 0;
para->IsTrueFalse = para->IsReadOnly = para->IsNeedRestart = KAL_FALSE;
para->Min = 0;
para->Max = (para->ItemIdx == 0 ? 0xFFFF : 0xFF);
break;
default:
ASSERT(0);
}
break;
default:
ASSERT(0);
}
}
inline static kal_bool GC2235_set_sensor_item_info(MSDK_SENSOR_ITEM_INFO_STRUCT *para)
{
kal_uint16 temp_para;
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235_set_sensor_item_info\n");
#endif
switch (para->GroupIdx)
{
case GC2235_PRE_GAIN:
switch (para->ItemIdx)
{
case GC2235_SENSOR_BASEGAIN:
case GC2235_PRE_GAIN_R_INDEX:
case GC2235_PRE_GAIN_Gr_INDEX:
case GC2235_PRE_GAIN_Gb_INDEX:
case GC2235_PRE_GAIN_B_INDEX:
#if defined(MT6577)||defined(MT6589)
spin_lock(&gc2235_drv_lock);
#endif
GC2235_sensor.eng.cct[para->ItemIdx].Para = para->ItemValue * BASEGAIN / 1000;
#if defined(MT6577)||defined(MT6589)
spin_unlock(&gc2235_drv_lock);
#endif
GC2235_SetGain(GC2235_sensor.gain); /* update gain */
break;
default:
ASSERT(0);
}
break;
case GC2235_CMMCLK_CURRENT:
switch (para->ItemIdx)
{
case 0:
switch (para->ItemValue)
{
case 2:
temp_para = ISP_DRIVING_2MA;
break;
case 3:
case 4:
temp_para = ISP_DRIVING_4MA;
break;
case 5:
case 6:
temp_para = ISP_DRIVING_6MA;
break;
default:
temp_para = ISP_DRIVING_8MA;
break;
}
//GC2235_set_isp_driving_current(temp_para);
#if defined(MT6577)||defined(MT6589)
spin_lock(&gc2235_drv_lock);
#endif
GC2235_sensor.eng.reg[GC2235_CMMCLK_CURRENT_INDEX].Para = temp_para;
#if defined(MT6577)||defined(MT6589)
spin_unlock(&gc2235_drv_lock);
#endif
break;
default:
ASSERT(0);
}
break;
case GC2235_FRAME_RATE_LIMITATION:
ASSERT(0);
break;
case GC2235_REGISTER_EDITOR:
switch (para->ItemIdx)
{
static kal_uint32 fac_sensor_reg;
case 0:
if (para->ItemValue < 0 || para->ItemValue > 0xFFFF) return KAL_FALSE;
fac_sensor_reg = para->ItemValue;
break;
case 1:
if (para->ItemValue < 0 || para->ItemValue > 0xFF) return KAL_FALSE;
GC2235_write_cmos_sensor(fac_sensor_reg, para->ItemValue);
break;
default:
ASSERT(0);
}
break;
default:
ASSERT(0);
}
return KAL_TRUE;
}
void GC2235_SetMirrorFlip(GC2235_IMAGE_MIRROR Mirror)
{
switch(Mirror)
{
case GC2235_IMAGE_NORMAL://IMAGE_V_MIRROR:
GC2235_write_cmos_sensor(0x17,0x14);
GC2235_write_cmos_sensor(0x92,0x03);
GC2235_write_cmos_sensor(0x94,0x07);
break;
case GC2235_IMAGE_H_MIRROR://IMAGE_NORMAL:
GC2235_write_cmos_sensor(0x17,0x15);
GC2235_write_cmos_sensor(0x92,0x03);
GC2235_write_cmos_sensor(0x94,0x06);
break;
case GC2235_IMAGE_V_MIRROR://IMAGE_HV_MIRROR:
GC2235_write_cmos_sensor(0x17,0x16);
GC2235_write_cmos_sensor(0x92,0x02);
GC2235_write_cmos_sensor(0x94,0x07);
break;
case GC2235_IMAGE_HV_MIRROR://IMAGE_H_MIRROR:
GC2235_write_cmos_sensor(0x17,0x17);
GC2235_write_cmos_sensor(0x92,0x02);
GC2235_write_cmos_sensor(0x94,0x06);
break;
}
}
static void GC2235_Sensor_Init(void)
{
/////////////////////////////////////////////////////
////////////////////// SYS //////////////////////
/////////////////////////////////////////////////////
GC2235_write_cmos_sensor(0xfe, 0x80);
GC2235_write_cmos_sensor(0xfe, 0x80);
GC2235_write_cmos_sensor(0xfe, 0x80);
GC2235_write_cmos_sensor(0xf2, 0x00);
GC2235_write_cmos_sensor(0xf6, 0x00);
GC2235_write_cmos_sensor(0xfc, 0x06);
GC2235_write_cmos_sensor(0xf7, 0x15); //pll enable
GC2235_write_cmos_sensor(0xf8, 0x83); //Pll mode 2
GC2235_write_cmos_sensor(0xf9, 0xfe); //[0] pll enable
GC2235_write_cmos_sensor(0xfa, 0x00); //div
GC2235_write_cmos_sensor(0xfe, 0x00);
/////////////////////////////////////////////////////
//////////////// ANALOG & CISCTL ////////////////
/////////////////////////////////////////////////////
GC2235_write_cmos_sensor(0x03, 0x0a);
GC2235_write_cmos_sensor(0x04, 0xec);
GC2235_write_cmos_sensor(0x05, 0x00);
GC2235_write_cmos_sensor(0x06, 0xd0);
GC2235_write_cmos_sensor(0x07, 0x00);
GC2235_write_cmos_sensor(0x08, 0x1a);
GC2235_write_cmos_sensor(0x0a, 0x02);
GC2235_write_cmos_sensor(0x0c, 0x00);
GC2235_write_cmos_sensor(0x0d, 0x04);
GC2235_write_cmos_sensor(0x0e, 0xd0);
GC2235_write_cmos_sensor(0x0f, 0x06);
GC2235_write_cmos_sensor(0x10, 0x50);
GC2235_write_cmos_sensor(0x17, 0x15);//14 //[0]mirror [1]flip
GC2235_write_cmos_sensor(0x18, 0x1e);
GC2235_write_cmos_sensor(0x19, 0x06);
GC2235_write_cmos_sensor(0x1a, 0x01);
GC2235_write_cmos_sensor(0x1b, 0x48);
GC2235_write_cmos_sensor(0x1e, 0x88);
GC2235_write_cmos_sensor(0x1f, 0x48);
GC2235_write_cmos_sensor(0x20, 0x03);
GC2235_write_cmos_sensor(0x21, 0x6f);
GC2235_write_cmos_sensor(0x22, 0x80);
GC2235_write_cmos_sensor(0x23, 0xc1);
GC2235_write_cmos_sensor(0x24, 0x2f);
GC2235_write_cmos_sensor(0x26, 0x01);
GC2235_write_cmos_sensor(0x27, 0x30);
GC2235_write_cmos_sensor(0x3f, 0x00);
/////////////////////////////////////////////////////
////////////////////// ISP //////////////////////
/////////////////////////////////////////////////////
GC2235_write_cmos_sensor(0x8b, 0xa0);
GC2235_write_cmos_sensor(0x8c, 0x02);
GC2235_write_cmos_sensor(0x90, 0x01);
GC2235_write_cmos_sensor(0x92, 0x02);
GC2235_write_cmos_sensor(0x94, 0x06);
GC2235_write_cmos_sensor(0x95, 0x04);
GC2235_write_cmos_sensor(0x96, 0xb0);
GC2235_write_cmos_sensor(0x97, 0x06);
GC2235_write_cmos_sensor(0x98, 0x40);
/////////////////////////////////////////////////////
////////////////////// BLK //////////////////////
/////////////////////////////////////////////////////
GC2235_write_cmos_sensor(0x40, 0x25);
GC2235_write_cmos_sensor(0x41, 0x04);
GC2235_write_cmos_sensor(0x5e, 0x20);
GC2235_write_cmos_sensor(0x5f, 0x20);
GC2235_write_cmos_sensor(0x60, 0x20);
GC2235_write_cmos_sensor(0x61, 0x20);
GC2235_write_cmos_sensor(0x62, 0x20);
GC2235_write_cmos_sensor(0x63, 0x20);
GC2235_write_cmos_sensor(0x64, 0x20);
GC2235_write_cmos_sensor(0x65, 0x20);
GC2235_write_cmos_sensor(0x66, 0x00);
GC2235_write_cmos_sensor(0x67, 0x00);
GC2235_write_cmos_sensor(0x68, 0x00);
GC2235_write_cmos_sensor(0x69, 0x00);
/////////////////////////////////////////////////////
////////////////////// GAIN /////////////////////
/////////////////////////////////////////////////////
GC2235_write_cmos_sensor(0xb2, 0x00);
GC2235_write_cmos_sensor(0xb3, 0x40);
GC2235_write_cmos_sensor(0xb4, 0x40);
GC2235_write_cmos_sensor(0xb5, 0x40);
/////////////////////////////////////////////////////
//////////////////// DARK SUN ///////////////////
/////////////////////////////////////////////////////
GC2235_write_cmos_sensor(0xb8, 0x0f);
GC2235_write_cmos_sensor(0xb9, 0x23);
GC2235_write_cmos_sensor(0xba, 0xff);
GC2235_write_cmos_sensor(0xbc, 0x00);
GC2235_write_cmos_sensor(0xbd, 0x00);
GC2235_write_cmos_sensor(0xbe, 0xff);
GC2235_write_cmos_sensor(0xbf, 0x09);
/////////////////////////////////////////////////////
////////////////////// OUTPUT /////////////////////
/////////////////////////////////////////////////////
GC2235_write_cmos_sensor(0xfe, 0x03);
GC2235_write_cmos_sensor(0x01, 0x00);
GC2235_write_cmos_sensor(0x02, 0x00);
GC2235_write_cmos_sensor(0x03, 0x00);
GC2235_write_cmos_sensor(0x06, 0x00);
GC2235_write_cmos_sensor(0x10, 0x00);
GC2235_write_cmos_sensor(0x15, 0x00);
GC2235_write_cmos_sensor(0xfe, 0x00);
GC2235_write_cmos_sensor(0xf2, 0x0f);
} /* GC2235_Sensor_Init */
/*****************************************************************************/
/* Windows Mobile Sensor Interface */
/*****************************************************************************/
/*************************************************************************
* FUNCTION
* GC2235Open
*
* DESCRIPTION
* This function initialize the registers of CMOS sensor
*
* PARAMETERS
* None
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
UINT32 GC2235Open(void)
{
kal_uint16 sensor_id=0;
// check if sensor ID correct
sensor_id=((GC2235_read_cmos_sensor(0xf0) << 8) | GC2235_read_cmos_sensor(0xf1));
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235Open, sensor_id:%x \n",sensor_id);
#endif
if (sensor_id != GC2235_SENSOR_ID)
return ERROR_SENSOR_CONNECT_FAIL;
/* initail sequence write in */
GC2235_Sensor_Init();
if(0 == strncmp(VANZO_MAIN_CAM_ROTATION, "180", 3))
GC2235_sensor.Mirror = GC2235_IMAGE_V_MIRROR;
else
GC2235_sensor.Mirror = GC2235_IMAGE_H_MIRROR;
GC2235_SetMirrorFlip(GC2235_sensor.Mirror);
return ERROR_NONE;
} /* GC2235Open */
/*************************************************************************
* FUNCTION
* GC2235GetSensorID
*
* DESCRIPTION
* This function get the sensor ID
*
* PARAMETERS
* *sensorID : return the sensor ID
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
extern bool camera_pdn_reverse;
UINT32 GC2235GetSensorID(UINT32 *sensorID)
{
// check if sensor ID correct
mt_set_gpio_mode(GPIO_CAMERA_CMPDN_PIN,GPIO_CAMERA_CMPDN_PIN_M_GPIO);
mt_set_gpio_dir(GPIO_CAMERA_CMPDN_PIN,GPIO_DIR_OUT);
mt_set_gpio_out(GPIO_CAMERA_CMPDN_PIN,GPIO_OUT_ZERO);
msleep(10);
*sensorID=((GC2235_read_cmos_sensor(0xf0) << 8) | GC2235_read_cmos_sensor(0xf1));
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235GetSensorID:%x \n",*sensorID);
#endif
if (*sensorID != GC2235_SENSOR_ID) {
*sensorID = 0xFFFFFFFF;
return ERROR_SENSOR_CONNECT_FAIL;
}
camera_pdn_reverse = 1;
return ERROR_NONE;
}
/*************************************************************************
* FUNCTION
* GC2235Close
*
* DESCRIPTION
* This function is to turn off sensor module power.
*
* PARAMETERS
* None
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
UINT32 GC2235Close(void)
{
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235Close\n");
#endif
//kdCISModulePowerOn(SensorIdx,currSensorName,0,mode_name);
// DRV_I2CClose(GC2235hDrvI2C);
return ERROR_NONE;
} /* GC2235Close */
/*************************************************************************
* FUNCTION
* GC2235Preview
*
* DESCRIPTION
* This function start the sensor preview.
*
* PARAMETERS
* *image_window : address pointer of pixel numbers in one period of HSYNC
* *sensor_config_data : address pointer of line numbers in one period of VSYNC
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
UINT32 GC2235Preview(MSDK_SENSOR_EXPOSURE_WINDOW_STRUCT *image_window,
MSDK_SENSOR_CONFIG_STRUCT *sensor_config_data)
{
#if defined(MT6577)||defined(MT6589)
spin_lock(&gc2235_drv_lock);
#endif
GC2235_sensor.pv_mode = KAL_TRUE;
//GC2235_set_mirror(sensor_config_data->SensorImageMirror);
switch (sensor_config_data->SensorOperationMode)
{
case MSDK_SENSOR_OPERATION_MODE_VIDEO:
GC2235_sensor.video_mode = KAL_TRUE;
default: /* ISP_PREVIEW_MODE */
GC2235_sensor.video_mode = KAL_FALSE;
}
GC2235_sensor.line_length = GC2235_PV_PERIOD_PIXEL_NUMS;
GC2235_sensor.frame_height = GC2235_PV_PERIOD_LINE_NUMS;
GC2235_sensor.pclk = GC2235_PREVIEW_CLK;
#if defined(MT6577)||defined(MT6589)
spin_unlock(&gc2235_drv_lock);
#endif
//GC2235_Write_Shutter(GC2235_sensor.shutter);
return ERROR_NONE;
} /* GC2235Preview */
/*************************************************************************
* FUNCTION
* GC2235Capture
*
* DESCRIPTION
* This function setup the CMOS sensor in capture MY_OUTPUT mode
*
* PARAMETERS
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
UINT32 GC2235Capture(MSDK_SENSOR_EXPOSURE_WINDOW_STRUCT *image_window,
MSDK_SENSOR_CONFIG_STRUCT *sensor_config_data)
{
kal_uint32 shutter = (kal_uint32)GC2235_sensor.shutter;
#if defined(MT6577)||defined(MT6589)
spin_lock(&gc2235_drv_lock);
#endif
GC2235_sensor.video_mode = KAL_FALSE;
GC2235_sensor.pv_mode = KAL_FALSE;
#if defined(MT6577)||defined(MT6589)
spin_unlock(&gc2235_drv_lock);
#endif
return ERROR_NONE;
} /* GC2235_Capture() */
UINT32 GC2235GetResolution(MSDK_SENSOR_RESOLUTION_INFO_STRUCT *pSensorResolution)
{
pSensorResolution->SensorFullWidth=GC2235_IMAGE_SENSOR_FULL_WIDTH;
pSensorResolution->SensorFullHeight=GC2235_IMAGE_SENSOR_FULL_HEIGHT;
pSensorResolution->SensorPreviewWidth=GC2235_IMAGE_SENSOR_PV_WIDTH;
pSensorResolution->SensorPreviewHeight=GC2235_IMAGE_SENSOR_PV_HEIGHT;
pSensorResolution->SensorVideoWidth = GC2235_IMAGE_SENSOR_VIDEO_WIDTH;
pSensorResolution->SensorVideoHeight = GC2235_IMAGE_SENSOR_VIDEO_HEIGHT;
return ERROR_NONE;
} /* GC2235GetResolution() */
UINT32 GC2235GetInfo(MSDK_SCENARIO_ID_ENUM ScenarioId,
MSDK_SENSOR_INFO_STRUCT *pSensorInfo,
MSDK_SENSOR_CONFIG_STRUCT *pSensorConfigData)
{
pSensorInfo->SensorPreviewResolutionX=GC2235_IMAGE_SENSOR_PV_WIDTH;
pSensorInfo->SensorPreviewResolutionY=GC2235_IMAGE_SENSOR_PV_HEIGHT;
pSensorInfo->SensorFullResolutionX=GC2235_IMAGE_SENSOR_FULL_WIDTH;
pSensorInfo->SensorFullResolutionY=GC2235_IMAGE_SENSOR_FULL_HEIGHT;
pSensorInfo->SensorCameraPreviewFrameRate=30;
pSensorInfo->SensorVideoFrameRate=30;
pSensorInfo->SensorStillCaptureFrameRate=10;
pSensorInfo->SensorWebCamCaptureFrameRate=15;
pSensorInfo->SensorResetActiveHigh=TRUE; //low active
pSensorInfo->SensorResetDelayCount=5;
pSensorInfo->SensorOutputDataFormat=GC2235_COLOR_FORMAT;
pSensorInfo->SensorClockPolarity=SENSOR_CLOCK_POLARITY_LOW;
pSensorInfo->SensorClockFallingPolarity=SENSOR_CLOCK_POLARITY_LOW;
pSensorInfo->SensorHsyncPolarity = SENSOR_CLOCK_POLARITY_LOW;
pSensorInfo->SensorVsyncPolarity = SENSOR_CLOCK_POLARITY_LOW;
pSensorInfo->SensroInterfaceType=SENSOR_INTERFACE_TYPE_PARALLEL;
pSensorInfo->CaptureDelayFrame = 2;
pSensorInfo->PreviewDelayFrame = 1;
pSensorInfo->VideoDelayFrame = 1;
pSensorInfo->SensorMasterClockSwitch = 0;
pSensorInfo->SensorDrivingCurrent = ISP_DRIVING_8MA;
pSensorInfo->AEShutDelayFrame =0; /* The frame of setting shutter default 0 for TG int */
pSensorInfo->AESensorGainDelayFrame = 0; /* The frame of setting sensor gain */
pSensorInfo->AEISPGainDelayFrame = 4;
switch (ScenarioId)
{
case MSDK_SCENARIO_ID_CAMERA_PREVIEW:
pSensorInfo->SensorClockFreq=24;
pSensorInfo->SensorClockDividCount=3;
pSensorInfo->SensorClockRisingCount= 0;
pSensorInfo->SensorClockFallingCount= 2;
pSensorInfo->SensorPixelClockCount= 3;
pSensorInfo->SensorDataLatchCount= 2;
pSensorInfo->SensorGrabStartX = GC2235_PV_X_START;
pSensorInfo->SensorGrabStartY = GC2235_PV_Y_START;
break;
case MSDK_SCENARIO_ID_VIDEO_PREVIEW:
pSensorInfo->SensorClockFreq=24;
pSensorInfo->SensorClockDividCount=3;
pSensorInfo->SensorClockRisingCount= 0;
pSensorInfo->SensorClockFallingCount= 2;
pSensorInfo->SensorPixelClockCount= 3;
pSensorInfo->SensorDataLatchCount= 2;
pSensorInfo->SensorGrabStartX = GC2235_VIDEO_X_START;
pSensorInfo->SensorGrabStartY = GC2235_VIDEO_Y_START;
break;
case MSDK_SCENARIO_ID_CAMERA_CAPTURE_JPEG:
case MSDK_SCENARIO_ID_CAMERA_ZSD:
pSensorInfo->SensorClockFreq=24;
pSensorInfo->SensorClockDividCount= 3;
pSensorInfo->SensorClockRisingCount=0;
pSensorInfo->SensorClockFallingCount=2;
pSensorInfo->SensorPixelClockCount=3;
pSensorInfo->SensorDataLatchCount=2;
pSensorInfo->SensorGrabStartX = GC2235_FULL_X_START;
pSensorInfo->SensorGrabStartY = GC2235_FULL_Y_START;
break;
default:
pSensorInfo->SensorClockFreq=24;
pSensorInfo->SensorClockDividCount=3;
pSensorInfo->SensorClockRisingCount=0;
pSensorInfo->SensorClockFallingCount=2;
pSensorInfo->SensorPixelClockCount=3;
pSensorInfo->SensorDataLatchCount=2;
pSensorInfo->SensorGrabStartX = GC2235_PV_X_START;
pSensorInfo->SensorGrabStartY = GC2235_PV_Y_START;
break;
}
memcpy(pSensorConfigData, &GC2235_sensor.cfg_data, sizeof(MSDK_SENSOR_CONFIG_STRUCT));
return ERROR_NONE;
} /* GC2235GetInfo() */
UINT32 GC2235Control(MSDK_SCENARIO_ID_ENUM ScenarioId, MSDK_SENSOR_EXPOSURE_WINDOW_STRUCT *pImageWindow,
MSDK_SENSOR_CONFIG_STRUCT *pSensorConfigData)
{
#ifdef GC2235_DRIVER_TRACE
SENSORDB("GC2235Control ScenarioId = %d \n",ScenarioId);
#endif
switch (ScenarioId)
{
case MSDK_SCENARIO_ID_CAMERA_PREVIEW:
case MSDK_SCENARIO_ID_VIDEO_PREVIEW:
GC2235Preview(pImageWindow, pSensorConfigData);
break;
case MSDK_SCENARIO_ID_CAMERA_CAPTURE_JPEG:
case MSDK_SCENARIO_ID_CAMERA_ZSD:
GC2235Capture(pImageWindow, pSensorConfigData);
break;
default:
return ERROR_INVALID_SCENARIO_ID;
}
return TRUE;
} /* GC2235Control() */
UINT32 GC2235SetVideoMode(UINT16 u2FrameRate)
{};
UINT32 GC2235FeatureControl(MSDK_SENSOR_FEATURE_ENUM FeatureId,
UINT8 *pFeaturePara,UINT32 *pFeatureParaLen)
{
UINT16 *pFeatureReturnPara16=(UINT16 *) pFeaturePara;
UINT16 *pFeatureData16=(UINT16 *) pFeaturePara;
UINT32 *pFeatureReturnPara32=(UINT32 *) pFeaturePara;
//UINT32 *pFeatureData32=(UINT32 *) pFeaturePara;
//UINT32 GC2235SensorRegNumber;
//UINT32 i;
//PNVRAM_SENSOR_DATA_STRUCT pSensorDefaultData=(PNVRAM_SENSOR_DATA_STRUCT) pFeaturePara;
//MSDK_SENSOR_CONFIG_STRUCT *pSensorConfigData=(MSDK_SENSOR_CONFIG_STRUCT *) pFeaturePara;
MSDK_SENSOR_REG_INFO_STRUCT *pSensorRegData=(MSDK_SENSOR_REG_INFO_STRUCT *) pFeaturePara;
//MSDK_SENSOR_GROUP_INFO_STRUCT *pSensorGroupInfo=(MSDK_SENSOR_GROUP_INFO_STRUCT *) pFeaturePara;
//MSDK_SENSOR_ITEM_INFO_STRUCT *pSensorItemInfo=(MSDK_SENSOR_ITEM_INFO_STRUCT *) pFeaturePara;
//MSDK_SENSOR_ENG_INFO_STRUCT *pSensorEngInfo=(MSDK_SENSOR_ENG_INFO_STRUCT *) pFeaturePara;
switch (FeatureId)
{
case SENSOR_FEATURE_GET_RESOLUTION:
*pFeatureReturnPara16++=GC2235_IMAGE_SENSOR_FULL_WIDTH;
*pFeatureReturnPara16=GC2235_IMAGE_SENSOR_FULL_HEIGHT;
*pFeatureParaLen=4;
break;
case SENSOR_FEATURE_GET_PERIOD: /* 3 */
*pFeatureReturnPara16++=GC2235_sensor.line_length;
*pFeatureReturnPara16=GC2235_sensor.frame_height;
*pFeatureParaLen=4;
break;
case SENSOR_FEATURE_GET_PIXEL_CLOCK_FREQ: /* 3 */
*pFeatureReturnPara32 = GC2235_sensor.pclk;
*pFeatureParaLen=4;
break;
case SENSOR_FEATURE_SET_ESHUTTER: /* 4 */
GC2235_set_shutter(*pFeatureData16);
break;
case SENSOR_FEATURE_SET_NIGHTMODE:
GC2235_night_mode((BOOL) *pFeatureData16);
break;
case SENSOR_FEATURE_SET_GAIN: /* 6 */
GC2235_SetGain((UINT16) *pFeatureData16);
break;
case SENSOR_FEATURE_SET_FLASHLIGHT:
break;
case SENSOR_FEATURE_SET_ISP_MASTER_CLOCK_FREQ:
break;
case SENSOR_FEATURE_SET_REGISTER:
GC2235_write_cmos_sensor(pSensorRegData->RegAddr, pSensorRegData->RegData);
break;
case SENSOR_FEATURE_GET_REGISTER:
pSensorRegData->RegData = GC2235_read_cmos_sensor(pSensorRegData->RegAddr);
break;
case SENSOR_FEATURE_SET_CCT_REGISTER:
memcpy(&GC2235_sensor.eng.cct, pFeaturePara, sizeof(GC2235_sensor.eng.cct));
break;
break;
case SENSOR_FEATURE_GET_CCT_REGISTER: /* 12 */
if (*pFeatureParaLen >= sizeof(GC2235_sensor.eng.cct) + sizeof(kal_uint32))
{
*((kal_uint32 *)pFeaturePara++) = sizeof(GC2235_sensor.eng.cct);
memcpy(pFeaturePara, &GC2235_sensor.eng.cct, sizeof(GC2235_sensor.eng.cct));
}
break;
case SENSOR_FEATURE_SET_ENG_REGISTER:
memcpy(&GC2235_sensor.eng.reg, pFeaturePara, sizeof(GC2235_sensor.eng.reg));
break;
case SENSOR_FEATURE_GET_ENG_REGISTER: /* 14 */
if (*pFeatureParaLen >= sizeof(GC2235_sensor.eng.reg) + sizeof(kal_uint32))
{
*((kal_uint32 *)pFeaturePara++) = sizeof(GC2235_sensor.eng.reg);
memcpy(pFeaturePara, &GC2235_sensor.eng.reg, sizeof(GC2235_sensor.eng.reg));
}
case SENSOR_FEATURE_GET_REGISTER_DEFAULT:
((PNVRAM_SENSOR_DATA_STRUCT)pFeaturePara)->Version = NVRAM_CAMERA_SENSOR_FILE_VERSION;
((PNVRAM_SENSOR_DATA_STRUCT)pFeaturePara)->SensorId = GC2235_SENSOR_ID;
memcpy(((PNVRAM_SENSOR_DATA_STRUCT)pFeaturePara)->SensorEngReg, &GC2235_sensor.eng.reg, sizeof(GC2235_sensor.eng.reg));
memcpy(((PNVRAM_SENSOR_DATA_STRUCT)pFeaturePara)->SensorCCTReg, &GC2235_sensor.eng.cct, sizeof(GC2235_sensor.eng.cct));
*pFeatureParaLen = sizeof(NVRAM_SENSOR_DATA_STRUCT);
break;
case SENSOR_FEATURE_GET_CONFIG_PARA:
memcpy(pFeaturePara, &GC2235_sensor.cfg_data, sizeof(GC2235_sensor.cfg_data));
*pFeatureParaLen = sizeof(GC2235_sensor.cfg_data);
break;
case SENSOR_FEATURE_CAMERA_PARA_TO_SENSOR:
GC2235_camera_para_to_sensor();
break;
case SENSOR_FEATURE_SENSOR_TO_CAMERA_PARA:
GC2235_sensor_to_camera_para();
break;
case SENSOR_FEATURE_GET_GROUP_COUNT:
GC2235_get_sensor_group_count((kal_uint32 *)pFeaturePara);
*pFeatureParaLen = 4;
break;
case SENSOR_FEATURE_GET_GROUP_INFO:
GC2235_get_sensor_group_info((MSDK_SENSOR_GROUP_INFO_STRUCT *)pFeaturePara);
*pFeatureParaLen = sizeof(MSDK_SENSOR_GROUP_INFO_STRUCT);
break;
case SENSOR_FEATURE_GET_ITEM_INFO:
GC2235_get_sensor_item_info((MSDK_SENSOR_ITEM_INFO_STRUCT *)pFeaturePara);
*pFeatureParaLen = sizeof(MSDK_SENSOR_ITEM_INFO_STRUCT);
break;
case SENSOR_FEATURE_SET_ITEM_INFO:
GC2235_set_sensor_item_info((MSDK_SENSOR_ITEM_INFO_STRUCT *)pFeaturePara);
*pFeatureParaLen = sizeof(MSDK_SENSOR_ITEM_INFO_STRUCT);
break;
case SENSOR_FEATURE_GET_ENG_INFO:
memcpy(pFeaturePara, &GC2235_sensor.eng_info, sizeof(GC2235_sensor.eng_info));
*pFeatureParaLen = sizeof(GC2235_sensor.eng_info);
break;
case SENSOR_FEATURE_GET_LENS_DRIVER_ID:
// get the lens driver ID from EEPROM or just return LENS_DRIVER_ID_DO_NOT_CARE
// if EEPROM does not exist in camera module.
*pFeatureReturnPara32=LENS_DRIVER_ID_DO_NOT_CARE;
*pFeatureParaLen=4;
break;
case SENSOR_FEATURE_SET_VIDEO_MODE:
//GC2235SetVideoMode(*pFeatureData16);
break;
case SENSOR_FEATURE_CHECK_SENSOR_ID:
GC2235GetSensorID(pFeatureReturnPara32);
break;
case SENSOR_FEATURE_SET_AUTO_FLICKER_MODE:
break;
default:
break;
}
return ERROR_NONE;
} /* GC2235FeatureControl() */
SENSOR_FUNCTION_STRUCT SensorFuncGC2235=
{
GC2235Open,
GC2235GetInfo,
GC2235GetResolution,
GC2235FeatureControl,
GC2235Control,
GC2235Close
};
UINT32 GC2235_RAW_SensorInit(PSENSOR_FUNCTION_STRUCT *pfFunc)
{
/* To Do : Check Sensor status here */
if (pfFunc!=NULL)
*pfFunc=&SensorFuncGC2235;
return ERROR_NONE;
} /* SensorInit() */
|
mishrakeshav/Competitive-Programming
|
CodeChef/Practice/STFOOD.py
|
from sys import stdin
input = stdin.readline
for t in range(int(input())):
N = int(input())
S = []
P = []
V = []
max_p = 0
for i in range(int(N)):
s,p,v = map(int,input().split())
profit = (p//(s+1))*v
if profit > max_p:
max_p = profit
print(max_p)
|
zababurinsv/waves-node
|
lang/shared/src/main/scala/com/wavesplatform/lang/directives/DirectiveParser.scala
|
<filename>lang/shared/src/main/scala/com/wavesplatform/lang/directives/DirectiveParser.scala
package com.wavesplatform.lang.directives
import com.wavesplatform.lang.ExecutionError
import fastparse._
import fastparse.Parsed.{Failure, Success}
import fastparse.MultiLineWhitespace._
import cats.implicits._
object DirectiveParser {
val start = "{-#"
val end = "#-}"
private def space[_: P]: P[Unit] =
P(CharIn(" ", "\t", "\r", "\n").rep)
private def directiveKeyP[_: P]: P[String] =
P(CharIn("a-zA-Z0-9_"))
.repX(1).!
private def directiveValueP[_:P]: P[String] =
P(CharIn("a-zA-Z0-9/\\., "))
.repX(1).!
private def parser[_:P]: P[Either[ExecutionError, Directive]] =
P(space ~ start ~ directiveKeyP ~ directiveValueP ~ end ~ space)
.map {
case (parsedKey, parsedValue) => {
val valueRaw = parsedValue.replace(" ", "")
for {
key <- DirectiveKey.textMap.get(parsedKey).toRight(s"Illegal directive key $parsedKey")
value <- key match {
case k: PredefinedDirectiveKey => k.valueDic.textMap.get(valueRaw).toRight(s"Illegal directive value $valueRaw for key $parsedKey")
case k: ArbitraryDirectiveKey => Right(k.valueMapper(valueRaw))
}
} yield Directive(key, value)
}
}
def apply(input: String): Either[ExecutionError, List[Directive]] =
input.split("\n")
.filter(_.matches(s"\\s*\\$start.*$end\\s*"))
.map(parse(_, parser(_)))
.foldLeft(Map[DirectiveKey, Directive]().asRight[ExecutionError]) {
case (err: Left[_, _], _) => err
case (_, _: Failure) => Left(s"Directive $input has illegal format")
case (_, Success(Left(err), _)) => Left(err)
case (Right(acc), Success(Right(d), _)) if acc.contains(d.key) => Left(s"Directive key ${d.key.text} is used more than once")
case (Right(acc), Success(Right(d), _)) => Right(acc + (d.key -> d))
}
.map(_.values.toList)
case class ParseResult(keys: Set[DirectiveKey], directives: List[Directive])
}
|
glowroot/glowroot-instrumentation
|
instrumentation-api/src/main/java/org/glowroot/instrumentation/api/config/ConfigService.java
|
<filename>instrumentation-api/src/main/java/org/glowroot/instrumentation/api/config/ConfigService.java
/*
* Copyright 2011-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.instrumentation.api.config;
public interface ConfigService {
/**
* Registers a listener that will receive a callback when the instrumentation's property values
* are changed.
*/
void registerConfigListener(ConfigListener listener);
/**
* Returns the {@code String} instrumentation property value with the specified {@code name}.
* {@code null} is never returned. If there is no {@code String} instrumentation property with
* the specified {@code name} then the empty string {@code ""} is returned.
*
* Properties are scoped per instrumentation. They are defined in the instrumentation's
* META-INF/instrumentation.*.json file, and can be modified (assuming they are not marked as
* hidden) on the configuration page under the instrumentation's configuration section.
*/
StringProperty getStringProperty(String name);
/**
* Returns the {@code boolean} instrumentation property value with the specified {@code name}.
* If there is no {@code boolean} instrumentation property with the specified {@code name} then
* {@code false} is returned.
*
* Properties are scoped per instrumentation. They are defined in the instrumentation's
* META-INF/instrumentation.*.json file, and can be modified (assuming they are not marked as
* hidden) on the configuration page under the instrumentation's configuration section.
*/
BooleanProperty getBooleanProperty(String name);
/**
* Returns the {@code Double} instrumentation property value with the specified {@code name}. If
* there is no {@code Double} instrumentation property with the specified {@code name} then
* {@code null} is returned.
*
* Properties are scoped per instrumentation. They are defined in the instrumentation's
* META-INF/instrumentation.*.json file, and can be modified (assuming they are not marked as
* hidden) on the configuration page under the instrumentation's configuration section.
*/
DoubleProperty getDoubleProperty(String name);
/**
* Returns the {@code List} instrumentation property value with the specified {@code name}.
* {@code null} is never returned. If there is no {@code String} instrumentation property with
* the specified {@code name} then the empty list is returned.
*
* Properties are scoped per instrumentation. They are defined in the instrumentation's
* META-INF/instrumentation.*.json file, and can be modified (assuming they are not marked as
* hidden) on the configuration page under the instrumentation's configuration section.
*/
ListProperty getListProperty(String name);
}
|
govindrgaikwad/java_repo
|
JAVA/equinox-data-access/src/main/java/com/tmg/uifwk/impexp/process/CalendarUIElementProcess.java
|
package com.tmg.uifwk.impexp.process;
import java.sql.Timestamp;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.tmg.equinox.view.formdesign.UIElementChangeTracker;
import com.tmg.uifwk.orm.ui.CalendarUIElement;
import com.tmg.uifwk.orm.ui.UIElementType;
@Component("CalendarUIElementProcess")
public class CalendarUIElementProcess {
private Workbook excelWorkBook;
@Autowired
private GenericUIElementProcess genericUIElementProcess;
public Workbook getExcelWorkBook() {
return excelWorkBook;
}
public void setExcelWorkBook(Workbook excelWorkBook) {
this.excelWorkBook = excelWorkBook;
}
public void exportCalendarUIElementToExcelSheet(
UIElementChangeTracker changedElement,
CalendarUIElement calendarUIElement, int curRow) throws Exception {
Sheet sheet = excelWorkBook.getSheetAt(0);
Row currentRow = sheet.createRow(curRow);
genericUIElementProcess.exportUIElementToExcelSheet(changedElement,
currentRow);
currentRow.createCell(24).setCellValue(
calendarUIElement.getUielementType().getUIElementTypeID());
currentRow.createCell(25).setCellValue(
calendarUIElement.getUielementType().getDisplayText());
if (calendarUIElement.getMinDate() != null) {
currentRow.createCell(35).setCellValue(
calendarUIElement.getMinDate());
}
if (calendarUIElement.getMaxDate() != null) {
currentRow.createCell(36).setCellValue(
calendarUIElement.getMaxDate());
}
if (calendarUIElement.getDefaultDate() != null) {
currentRow.createCell(37).setCellValue(
calendarUIElement.getDefaultDate());
}
}
public void importCalendarUIElementFromExcelSheet(
CalendarUIElement calendarUIElement, int curRow,
UIElementType uiElementType) {
Sheet sheet = excelWorkBook.getSheetAt(0);
Row uiElementRow = sheet.getRow(curRow);
calendarUIElement.setUielementType(uiElementType);
if (uiElementRow.getCell(35) != null) {
calendarUIElement.setMinDate(new Timestamp(uiElementRow.getCell(35)
.getDateCellValue().getTime()));
} else {
calendarUIElement.setMinDate(null);
}
if (uiElementRow.getCell(36) != null) {
calendarUIElement.setMaxDate(new Timestamp(uiElementRow.getCell(36)
.getDateCellValue().getTime()));
} else {
calendarUIElement.setMaxDate(null);
}
if (uiElementRow.getCell(37) != null) {
calendarUIElement.setDefaultDate(new Timestamp(uiElementRow.getCell(37)
.getDateCellValue().getTime()));
} else {
calendarUIElement.setDefaultDate(null);
}
}
}
|
aaoferreira/hackerrank
|
src/main/java/hackerrank/algorithms/strings/Anagram.java
|
<reponame>aaoferreira/hackerrank<filename>src/main/java/hackerrank/algorithms/strings/Anagram.java
/**
*
* Created-By: <NAME>
* Created-Date: 13 Apr 2016
*
*/
package hackerrank.algorithms.strings;
import java.util.Scanner;
/**
*
* @author <NAME>
*
*/
public class Anagram {
// https://www.hackerrank.com/challenges/anagram
private static final short MIN_ASCII_LOWER = 'a';
private static final short MAX_ASCII_LOWER = 'z';
public static void main(String[] args) {
// Gets values from standard in
// Scanner scanner = new Scanner(System.in);
Class<?> clazz = Anagram.class;
Scanner scanner = new Scanner(
clazz.getResourceAsStream(clazz.getSimpleName() + ".txt"));
StringBuilder output = new StringBuilder();
int testCases = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < testCases; i++) {
String line = scanner.nextLine();
int length = line.length();
// Odd lengths can't have anagrams
if (length % 2 == 1) {
output.append("-1\n");
continue;
}
// Gets strings
String left = line.substring(0, length / 2);
String right = line.substring(length / 2);
int[] leftCharCount =
new int[MAX_ASCII_LOWER - MIN_ASCII_LOWER + 1];
for (char character : left.toCharArray()) {
leftCharCount[character - MIN_ASCII_LOWER]++;
}
// Checks how many changes are required to create an anagram
int changesRequired = 0;
for (char character : right.toCharArray()) {
int index = character - MIN_ASCII_LOWER;
int count = leftCharCount[index];
if (count > 0) {
leftCharCount[index]--;
} else {
changesRequired++;
}
}
output.append(changesRequired + "\n");
}
scanner.close();
System.out.println(output.toString());
}
}
|
timwindsor/cordova-blackberry-plugins
|
test/unit/com.blackberry.io.filetransfer/index.js
|
<gh_stars>1-10
/*
* Copyright 2012 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var root = __dirname + "/../../../",
webview = require(root + "lib/webview"),
mockedPluginResult,
index;
describe("io.filetransfer index", function () {
beforeEach(function () {
GLOBAL.JNEXT = {
require: jasmine.createSpy().andReturn(true),
createObject: jasmine.createSpy().andReturn("0"),
registerEvents: jasmine.createSpy(),
invoke: jasmine.createSpy("invoke")
};
GLOBAL.window = {
qnx : {
webplatform : {
getApplication : function () {
return {
getEnv : function () {
return "ROOT";
}
};
}
}
}
};
mockedPluginResult = {
ok: jasmine.createSpy("PluginResult.ok"),
error: jasmine.createSpy("PluginResult.error"),
noResult: jasmine.createSpy("PluginResult.noResult"),
callbackOk: jasmine.createSpy("PluginResult.callbackOk")
};
GLOBAL.PluginResult = jasmine.createSpy("PluginResult").andReturn(mockedPluginResult);
spyOn(webview, "windowGroup").andReturn(42);
index = require(root + "plugin/com.blackberry.io.filetransfer/index");
});
afterEach(function () {
delete GLOBAL.JNEXT;
delete require.cache[require.resolve(root + "plugin/com.blackberry.io.filetransfer/index")];
index = null;
delete GLOBAL.window;
delete GLOBAL.PluginResult;
});
it("makes sure JNEXT was not initialized on require", function () {
expect(JNEXT.require).not.toHaveBeenCalledWith("libfiletransfer");
expect(JNEXT.createObject).not.toHaveBeenCalledWith("libfiletransfer.FileTransfer");
});
describe("filetransfer upload", function () {
it("should call JNEXT.invoke with custom params", function () {
var mocked_args = {
"callbackId": encodeURIComponent(JSON.stringify("123")),
"filePath": encodeURIComponent(JSON.stringify("2")),
"server": encodeURIComponent(JSON.stringify("3")),
"options": encodeURIComponent(JSON.stringify({
"fileKey": "test",
"fileName": "test.gif",
"mimeType": "image/gif",
"params": { "test": "test" },
"chunkedMode": false,
"chunkSize": 512
}))
},
expected_args = {
"filePath": "2",
"server": "3",
"options": {
"fileKey": "test",
"fileName": "test.gif",
"mimeType": "image/gif",
"params": { "test": "test" },
"chunkedMode": false,
"chunkSize": 512,
"windowGroup" : 42
},
"callbackId": "123"
};
index.upload(null, null, mocked_args, null);
expect(JNEXT.invoke).toHaveBeenCalledWith("0", "upload " + JSON.stringify(expected_args));
expect(mockedPluginResult.noResult).toHaveBeenCalled();
expect(mockedPluginResult.error).not.toHaveBeenCalled();
});
it("should call JNEXT.invoke with default params", function () {
var mocked_args = {
"filePath": encodeURIComponent(JSON.stringify("2")),
"server": encodeURIComponent(JSON.stringify("3")),
"callbackId": encodeURIComponent(JSON.stringify("1"))
},
expected_default_args = {
"filePath": "2",
"server": "3",
"options": {
"fileKey": "file",
"fileName": "image.jpg",
"mimeType": "image/jpeg",
"params": {},
"chunkedMode": true,
"chunkSize": 1024,
"windowGroup" : 42
},
"callbackId": "1"
};
index.upload(null, null, mocked_args);
expect(JNEXT.invoke).toHaveBeenCalledWith("0", "upload " + JSON.stringify(expected_default_args));
expect(mockedPluginResult.noResult).toHaveBeenCalled();
expect(mockedPluginResult.error).not.toHaveBeenCalled();
});
it("should call failure callback with null parameters", function () {
var mocked_args = {
"filePath": encodeURIComponent(JSON.stringify("")),
"server": encodeURIComponent(JSON.stringify("")),
"callbackId": encodeURIComponent(JSON.stringify("123"))
};
index.upload(null, null, mocked_args, null);
expect(mockedPluginResult.noResult).not.toHaveBeenCalled();
expect(mockedPluginResult.error).toHaveBeenCalled();
});
it("should fail if chunkSize is not positive", function () {
var mocked_args = {
"filePath": encodeURIComponent(JSON.stringify("2")),
"server": encodeURIComponent(JSON.stringify("3")),
"callbackId": encodeURIComponent(JSON.stringify("123")),
"options": encodeURIComponent(JSON.stringify({
"chunkSize": -1
}))
};
index.upload(null, null, mocked_args, null);
expect(mockedPluginResult.noResult).not.toHaveBeenCalled();
expect(mockedPluginResult.error).toHaveBeenCalled();
});
it("should translate local path", function () {
var params,
mocked_args = {
"filePath": encodeURIComponent(JSON.stringify("local:///persistent/test.txt")),
"callbackId": encodeURIComponent(JSON.stringify("123")),
"server": encodeURIComponent(JSON.stringify("3"))
};
JNEXT.invoke = jasmine.createSpy().andCallFake(function () {
params = JSON.parse(arguments[1].substring(7, arguments[1].length));
});
index.upload(null, null, mocked_args, null);
expect(JNEXT.invoke).toHaveBeenCalled();
expect(params.filePath).toEqual("/ROOT/../app/native/persistent/test.txt");
expect(mockedPluginResult.noResult).toHaveBeenCalled();
});
});
describe("filetransfer download", function () {
it("should call JNEXT.invoke", function () {
var mocked_args = {
"source": encodeURIComponent(JSON.stringify("2")),
"target": encodeURIComponent(JSON.stringify("3")),
"callbackId": encodeURIComponent(JSON.stringify("123"))
},
expected_args = {
"source": "2",
"target": "3",
"callbackId": "123",
"windowGroup": 42
};
index.download(null, null, mocked_args, null);
expect(JNEXT.invoke).toHaveBeenCalledWith("0", "download " + JSON.stringify(expected_args));
expect(mockedPluginResult.noResult).toHaveBeenCalled();
expect(mockedPluginResult.error).not.toHaveBeenCalled();
});
it("should call failure callback with null parameters", function () {
var mocked_args = {
"filePath": encodeURIComponent(JSON.stringify("")),
"server": encodeURIComponent(JSON.stringify("")),
"callbackId": encodeURIComponent(JSON.stringify("123"))
};
index.download(null, null, mocked_args, null);
expect(mockedPluginResult.noResult).not.toHaveBeenCalled();
expect(mockedPluginResult.error).toHaveBeenCalled();
});
it("should translate local path", function () {
var params,
mocked_args = {
"target": encodeURIComponent(JSON.stringify("local:///persistent/test.txt")),
"source": encodeURIComponent(JSON.stringify("3")),
"callbackId": encodeURIComponent(JSON.stringify("123"))
};
JNEXT.invoke = jasmine.createSpy("JNEXT.invoke").andCallFake(function () {
params = JSON.parse(arguments[1].substring(9, arguments[1].length));
});
index.download(null, null, mocked_args, null);
expect(JNEXT.invoke).toHaveBeenCalled();
expect(params.target).toEqual("/ROOT/../app/native/persistent/test.txt");
expect(mockedPluginResult.noResult).toHaveBeenCalled();
});
});
});
|
gu-bin/bosh-agent
|
agent/action/update_settings.go
|
<gh_stars>1-10
package action
import (
"errors"
"encoding/json"
"github.com/cloudfoundry/bosh-agent/platform"
"github.com/cloudfoundry/bosh-agent/platform/cert"
boshsettings "github.com/cloudfoundry/bosh-agent/settings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
"github.com/cloudfoundry/bosh-utils/logger"
"path/filepath"
)
type UpdateSettingsAction struct {
trustedCertManager cert.Manager
logger logger.Logger
settingsService boshsettings.Service
platform platform.Platform
}
func NewUpdateSettings(service boshsettings.Service, platform platform.Platform, trustedCertManager cert.Manager, logger logger.Logger) UpdateSettingsAction {
return UpdateSettingsAction{
trustedCertManager: trustedCertManager,
logger: logger,
settingsService: service,
platform: platform,
}
}
func (a UpdateSettingsAction) IsAsynchronous(_ ProtocolVersion) bool {
return true
}
func (a UpdateSettingsAction) IsPersistent() bool {
return false
}
func (a UpdateSettingsAction) IsLoggable() bool {
return true
}
func (a UpdateSettingsAction) Run(newUpdateSettings boshsettings.UpdateSettings) (string, error) {
err := a.settingsService.LoadSettings()
if err != nil {
return "", err
}
currentSettings := a.settingsService.GetSettings()
for _, diskAssociation := range newUpdateSettings.DiskAssociations {
diskSettings, found := currentSettings.PersistentDiskSettings(diskAssociation.DiskCID)
if !found {
return "", bosherr.Errorf("Persistent disk settings contains no disk with CID: %s", diskAssociation.DiskCID)
}
err := a.platform.AssociateDisk(diskAssociation.Name, diskSettings)
if err != nil {
return "", err
}
}
err = a.trustedCertManager.UpdateCertificates(newUpdateSettings.TrustedCerts)
if err != nil {
return "", err
}
updateSettingsJSON, err := json.Marshal(newUpdateSettings)
if err != nil {
return "", bosherr.WrapError(err, "Marshalling updateSettings json")
}
updateSettingsPath := filepath.Join(a.platform.GetDirProvider().BoshDir(), "update_settings.json")
err = a.platform.GetFs().WriteFile(updateSettingsPath, updateSettingsJSON)
if err != nil {
return "", bosherr.WrapError(err, "writing update settings json")
}
return "updated", nil
}
func (a UpdateSettingsAction) Resume() (interface{}, error) {
return nil, errors.New("not supported")
}
func (a UpdateSettingsAction) Cancel() error {
return errors.New("not supported")
}
|
ssin122/test-h
|
tests/h/celery_test.py
|
<gh_stars>0
# -*- coding: utf-8 -*-
import logging
import mock
import pytest
from h import celery
class TestCelery(object):
@pytest.fixture(autouse=True)
def register_signal(self, request):
return _patch('h.celery.register_signal', request)
@pytest.fixture(autouse=True)
def register_logger_signal(self, request):
return _patch('h.celery.register_logger_signal', request)
def test_bootstrap_worker_bootstraps_application(self):
sender = mock.Mock(spec=['app'])
celery.bootstrap_worker(sender)
sender.app.webapp_bootstrap.assert_called_once_with()
def test_bootstrap_worker_attaches_request_to_app(self):
sender = mock.Mock(spec=['app'])
request = sender.app.webapp_bootstrap.return_value
celery.bootstrap_worker(sender)
assert sender.app.request == request
def test_bootstrap_worker_configures_sentry_reporting(self,
register_signal,
register_logger_signal):
sender = mock.Mock(spec=['app'])
request = sender.app.webapp_bootstrap.return_value
request.sentry = mock.sentinel.sentry
celery.bootstrap_worker(sender)
register_signal.assert_called_once_with(mock.sentinel.sentry)
register_logger_signal.assert_called_once_with(mock.sentinel.sentry,
loglevel=logging.ERROR)
def test_reset_feature_flags_resets_request_feature_flags(self):
sender = mock.Mock(spec=['app'])
celery.reset_feature_flags(sender)
sender.app.request.feature.clear.assert_called_once_with()
def test_nipsa_cache(self, pyramid_config, pyramid_request):
sender = mock.Mock(app=mock.Mock(request=pyramid_request))
nipsa_svc = mock.Mock()
pyramid_config.register_service(nipsa_svc, name='nipsa')
celery.reset_nipsa_cache(sender)
nipsa_svc.clear.assert_called_once_with()
def test_transaction_commit_commits_request_transaction(self):
sender = mock.Mock(spec=['app'])
celery.transaction_commit(sender)
sender.app.request.tm.commit.assert_called_once_with()
def test_transaction_abort_aborts_request_transaction(self):
sender = mock.Mock(spec=['app'])
celery.transaction_abort(sender)
sender.app.request.tm.abort.assert_called_once_with()
def _patch(modulepath, request):
patcher = mock.patch(modulepath, autospec=True)
module = patcher.start()
request.addfinalizer(patcher.stop)
return module
|
m00g3n/kyma
|
components/application-gateway/internal/proxy/cache.go
|
<filename>components/application-gateway/internal/proxy/cache.go
package proxy
import (
"net/http/httputil"
"time"
"github.com/kyma-project/kyma/components/application-gateway/internal/authorization"
gocache "github.com/patrickmn/go-cache"
)
const cleanupInterval = 60
type CacheEntry struct {
Proxy *httputil.ReverseProxy
AuthorizationStrategy authorization.Strategy
}
type Cache interface {
// Get returns entry from the cache
Get(id string) (*CacheEntry, bool)
// Put adds entry to the cache
Put(id string, reverseProxy *httputil.ReverseProxy, authorizationStrategy authorization.Strategy) *CacheEntry
}
type cache struct {
proxyCache *gocache.Cache
}
// NewCache creates new cache with specified TTL
func NewCache(proxyCacheTTL int) Cache {
return &cache{
proxyCache: gocache.New(time.Duration(proxyCacheTTL)*time.Second, cleanupInterval*time.Second),
}
}
func (p *cache) Get(id string) (*CacheEntry, bool) {
proxy, found := p.proxyCache.Get(id)
if !found {
return nil, false
}
return proxy.(*CacheEntry), found
}
func (p *cache) Put(id string, reverseProxy *httputil.ReverseProxy, authorizationStrategy authorization.Strategy) *CacheEntry {
proxy := &CacheEntry{Proxy: reverseProxy, AuthorizationStrategy: authorizationStrategy}
p.proxyCache.Set(id, proxy, gocache.DefaultExpiration)
return proxy
}
|
tsallinen/oskari-frontend
|
bundles/framework/coordinatetool/instance.js
|
<filename>bundles/framework/coordinatetool/instance.js
/**
* @class Oskari.mapframework.bundle.coordinatetool.CoordinateToolBundleInstance
*
* Registers and starts the
* Oskari.mapframework.bundle.coordinatetool.plugin.CoordinatesPlugin plugin for main map.
*/
Oskari.clazz.define('Oskari.mapframework.bundle.coordinatetool.CoordinateToolBundleInstance',
/**
* @method create called automatically on construction
* @static
*/
function () {
this.sandbox = null;
this.started = false;
this._localization = null;
this.coordinateToolService = undefined;
}, {
__name: 'coordinatetool',
/**
* @method getName
* @return {String} the name for the component
*/
getName: function () {
return this.__name;
},
/**
* Needed by sandbox.register()
*/
init: function () {},
/**
* @method setSandbox
* @param {Oskari.Sandbox} sandbox
* Sets the sandbox reference to this component
*/
setSandbox: function (sbx) {
this.sandbox = sbx;
},
/**
* @method getSandbox
* @return {Oskari.Sandbox}
*/
getSandbox: function () {
return this.sandbox;
},
/**
* @method update
* implements BundleInstance protocol update method - does nothing atm
*/
update: function () {
},
/**
* @method getLocalization
* Returns JSON presentation of bundles localization data for
* current language.
* If key-parameter is not given, returns the whole localization
* data.
*
* @param {String} key (optional) if given, returns the value for
* key
* @return {String/Object} returns single localization string or
* JSON object for complete data depending on localization
* structure and if parameter key is given
*/
getLocalization: function (key) {
if (!this._localization) {
this._localization = Oskari.getLocalization(this.getName());
}
if (key) {
return this._localization[key];
}
return this._localization;
},
/**
* @method start
* implements BundleInstance protocol start methdod
*/
start: function () {
var me = this;
if (me.started) {
return;
}
me.started = true;
var conf = me.conf || {},
sandboxName = (conf ? conf.sandbox : null) || 'sandbox',
sandbox = Oskari.getSandbox(sandboxName);
me.setSandbox(sandbox);
this.coordinateToolService = this.createService(sandbox, conf);
var mapModule = sandbox.findRegisteredModuleInstance('MainMapModule');
var locale = Oskari.getMsg.bind(null, 'coordinatetool');
var plugin = Oskari.clazz.create('Oskari.mapframework.bundle.coordinatetool.plugin.CoordinateToolPlugin', this, conf, locale, mapModule, sandbox);
mapModule.registerPlugin(plugin);
mapModule.startPlugin(plugin);
this.plugin = plugin;
sandbox.register(me);
// get the plugin order straight in mobile toolbar even for the tools coming in late
if (Oskari.util.isMobile() && this.plugin.hasUI()) {
mapModule.redrawPluginUIs(true);
}
this._registerForGuidedTour();
},
/**
* @method @public isOpen
* @return {Boolean} is popup open
*/
isOpen: function () {
var me = this;
return (me.plugin) ? me.plugin.isOpen() : false;
},
/**
* Creates the coordinate tool service and registers it to the sandbox.
*
* @method createService
* @param {Oskari.Sandbox} sandbox
* @param {} configuration conf.reverseGeocodingIds is in use
* @return {Oskari.mapframework.bundle.coordinatetool.CoordinateToolService}
*/
createService: function (sandbox, conf) {
var coordinateToolService = Oskari.clazz.create(
'Oskari.mapframework.bundle.coordinatetool.CoordinateToolService',
this, conf || {}
);
sandbox.registerService(coordinateToolService);
return coordinateToolService;
},
/**
* Returns the coordinate tool service.
*
* @method getService
* @return {Oskari.mapframework.bundle.myplacesimport.MyPlacesImportService}
*/
getService: function () {
return this.coordinateToolService;
},
/**
* @public @method showMessage
* Shows user a message with ok button
*
* @param {String} title popup title
* @param {String} message popup message
*
*/
showMessage: function (title, message) {
var dialog = Oskari.clazz.create(
'Oskari.userinterface.component.Popup'
);
dialog.show(title, message);
dialog.fadeout(5000);
},
/**
* @method update
* implements BundleInstance protocol update method - does nothing atm
*/
stop: function () {
this.sandbox = null;
this.started = false;
},
/**
* @static
* @property __guidedTourDelegateTemplate
* Delegate object given to guided tour bundle instance. Handles content & actions of guided tour popup.
* Function "this" context is bound to bundle instance
*/
__guidedTourDelegateTemplate: {
priority: 120,
show: function () {
this.sandbox.postRequestByName('userinterface.UpdateExtensionRequest', [null, 'attach', this.__name]);
},
hide: function () {
this.sandbox.postRequestByName('userinterface.UpdateExtensionRequest', [null, 'close', this.__name]);
},
getTitle: function () {
return this.getLocalization().guidedTour.title;
},
getContent: function () {
var content = jQuery('<div></div>');
content.append(this.getLocalization().guidedTour.message);
return content;
},
getPositionRef: function () {
return jQuery('.coordinatetool');
},
positionAlign: 'left',
getLinks: function () {
var me = this;
var loc = this.getLocalization().guidedTour;
var linkTemplate = jQuery('<a href="#"></a>');
var openLink = linkTemplate.clone();
openLink.append(loc.openLink);
openLink.on('click',
function () {
me.sandbox.postRequestByName('userinterface.UpdateExtensionRequest', [null, 'attach', this.__name]);
openLink.hide();
closeLink.show();
});
var closeLink = linkTemplate.clone();
closeLink.append(loc.closeLink);
closeLink.on('click',
function () {
me.sandbox.postRequestByName('userinterface.UpdateExtensionRequest', [null, 'close', this.__name]);
openLink.show();
closeLink.hide();
});
closeLink.show();
openLink.hide();
return [openLink, closeLink];
}
},
/**
* @method _registerForGuidedTour
* Registers bundle for guided tour help functionality. Waits for guided tour load if not found
*/
_registerForGuidedTour: function () {
var me = this;
function sendRegister () {
var requestBuilder = Oskari.requestBuilder('Guidedtour.AddToGuidedTourRequest');
if (requestBuilder && me.sandbox.hasHandler('Guidedtour.AddToGuidedTourRequest')) {
var delegate = {
bundleName: me.getName()
};
for (var prop in me.__guidedTourDelegateTemplate) {
if (typeof me.__guidedTourDelegateTemplate[prop] === 'function') {
delegate[prop] = me.__guidedTourDelegateTemplate[prop].bind(me); // bind methods to bundle instance
} else {
delegate[prop] = me.__guidedTourDelegateTemplate[prop]; // assign values
}
}
me.sandbox.request(me, requestBuilder(delegate));
}
}
function handler (msg) {
if (msg.id === 'guidedtour') {
sendRegister();
}
}
var tourInstance = me.sandbox.findRegisteredModuleInstance('GuidedTour');
if (tourInstance) {
sendRegister();
} else {
Oskari.on('bundle.start', handler);
}
}
}, {
/**
* @property {String[]} protocol
* @static
*/
protocol: ['Oskari.bundle.BundleInstance', 'Oskari.mapframework.module.Module']
});
|
xiaosean/leetcode_python
|
Q169_Majority-Element.py
|
from collections import Counter
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_counter = Counter(nums)
n = len(nums)
for key, count in nums_counter.most_common():
if count > n/2:
return key
return None
|
FELDSAM-INC/ve-vertice-v1
|
carton/quota.go
|
<gh_stars>1-10
package carton
import (
"encoding/json"
"github.com/virtengine/libgo/api"
"github.com/virtengine/libgo/pairs"
)
type Quota struct {
Id string `json:"id" cql:"id"`
AccountId string `json:"account_id" cql:"account_id"`
Name string `json:"name" cql:"name"`
JsonClaz string `json:"json_claz" cql:"json_claz"`
Allowed pairs.JsonPairs `json:"allowed" cql:"allowed"`
AllocatedTo string `json:"allocated_to" cql:"allocated_to"`
QuotaType string `json:"quota_type" cql:"quota_type"`
Status string `json:"status" cql:"status"`
Inputs pairs.JsonPairs `json:"inputs" cql:"inputs"`
}
type ApiQuota struct {
JsonClaz string `json:"json_claz"`
Results []Quota `json:"results"`
}
func (q *Quota) Update() error {
return q.update(newArgs(q.AccountId, ""))
}
func (q *Quota) update(args api.ApiArgs) error {
cl := api.NewClient(args, "/quotas/update")
_, err := cl.Post(q)
if err != nil {
return err
}
return nil
}
func NewQuota(accountid, id string) (*Quota, error) {
q := new(Quota)
q.AccountId = accountid
q.Id = id
return q.get(newArgs(accountid, ""))
}
func (q *Quota) get(args api.ApiArgs) (*Quota, error) {
cl := api.NewClient(args, "/quotas/"+q.Id)
response, err := cl.Get()
if err != nil {
return nil, err
}
ac := &ApiQuota{}
//log.Debugf("Response %s : (%s)",cmd.Colorfy("[Body]", "green", "", "bold"),string(response))
err = json.Unmarshal(response, ac)
if err != nil {
return nil, err
}
return &ac.Results[0], nil
}
func (q *Quota) ContainerQuota() (bool, error) {
asm, err := NewAssembly(q.AllocatedTo, q.AccountId, "")
if err != nil {
return true, err
}
return !(len(asm.quotaID()) > 0), nil
}
func (q *Quota) AllowedSnaps() string {
return q.Allowed.Match("no_of_units")
}
|
paullewallencom/java-978-1-7821-7198-0
|
_/1980EN_06_Code/ticket-agency-jms/src/main/java/com/packtpub/wflydevelopment/chapter6/entity/SeatPositionConverter.java
|
<reponame>paullewallencom/java-978-1-7821-7198-0
package com.packtpub.wflydevelopment.chapter6.entity;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class SeatPositionConverter implements AttributeConverter<SeatPosition, String> {
@Override
public String convertToDatabaseColumn(SeatPosition attribute) {
return attribute.getDatabaseRepresentation();
}
@Override
public SeatPosition convertToEntityAttribute(String dbData) {
for (SeatPosition seatPosition : SeatPosition.values()) {
if (dbData.equals(seatPosition.getDatabaseRepresentation())) {
return seatPosition;
}
}
throw new IllegalArgumentException("Unknown attribute value " + dbData);
}
}
|
bradbeam/redskyops-controller
|
internal/controller/errors.go
|
/*
Copyright 2020 GramLabs, 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 controller
import (
redskyapi "github.com/redskyops/redskyops-controller/redskyapi/experiments/v1alpha1"
apierrs "k8s.io/apimachinery/pkg/api/errors"
)
// IgnoreNotFound returns the supplied error, unless that error is a "not found" error
func IgnoreNotFound(err error) error {
if apierrs.IsNotFound(err) {
return nil
}
if rserr, ok := err.(*redskyapi.Error); ok {
if rserr.Type == redskyapi.ErrExperimentNotFound || rserr.Type == redskyapi.ErrTrialNotFound {
return nil
}
}
return err
}
// IgnoreAlreadyExists returns the supplied error, unless that error is an "already exists" error
func IgnoreAlreadyExists(err error) error {
if apierrs.IsAlreadyExists(err) {
return nil
}
return err
}
// IgnoreReportError returns the supplied error, unless the error is ignorable when reporting trials
func IgnoreReportError(err error) error {
if IgnoreNotFound(err) == nil {
return nil
}
if rserr, ok := err.(*redskyapi.Error); ok {
if rserr.Type == redskyapi.ErrTrialAlreadyReported {
return nil
}
}
return err
}
|
rahulchaudhary2244/encog-java-core
|
src/main/java/org/encog/mathutil/Convert.java
|
<filename>src/main/java/org/encog/mathutil/Convert.java
/*
* Encog(tm) Core v3.4 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2017 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.mathutil;
/**
* This class is used to convert strings into numeric values. If the string
* holds a non-numeric value, a zero is returned.
*
* @author jheaton
*
*/
public final class Convert {
/**
* Convert a string to a double. Just make the number a zero if the string
* is invalid.
*
* @param str
* The string.
* @return The string converted to numeric.
*/
public static double string2double(final String str) {
double result = 0;
try {
if (str != null) {
result = Double.parseDouble(str);
}
} catch (final NumberFormatException e) {
result = 0;
}
return result;
}
/**
* Convert a string to an int. Just make the number a zero if the string is
* invalid.
*
* @param str
* The string.
* @return The string converted to numeric.
*/
public static int string2int(final String str) {
int result = 0;
try {
if (str != null) {
result = Integer.parseInt(str);
}
} catch (final NumberFormatException e) {
result = 0;
}
return result;
}
/**
* Private constructor.
*/
private Convert() {
}
}
|
furiousOyster/interbit
|
packages/interbit-cli/scripts/deploy.js
|
// © 2018 BTL GROUP LTD - This package is licensed under the MIT license https://opensource.org/licenses/MIT
const path = require('path')
const {
argOptions: { KEY_PAIR },
getArtifactsLocation,
getConnect,
getKeyPair,
getManifest,
getPort,
deploy,
manifestSelectors: { getChains }
} = require('interbit')
const deployWithCliOptions = async () => {
const options = getOptions()
console.log(options.location, options.manifest)
console.log('MANIFEST CHAIN IDs', getChains(options.manifest))
if (!options.keyPair) {
console.warn(
`interbit deploy: You are about to launch a node without ${KEY_PAIR}. The hypervisor will generate a new pair which may not match your ACL or network configuration.`
)
}
deploy(options)
}
const getOptions = () => ({
manifest: getManifest(),
port: getPort(),
keyPair: getKeyPair(),
location: path.relative(process.cwd(), getArtifactsLocation()),
connect: getConnect()
})
deployWithCliOptions()
|
EstherWaweru/30DaysOfCode
|
Day10_Binary Numbers/test/task3.py
|
<gh_stars>1-10
array=[-6,-91,1011,-100,84,-22,0,1,473]
mini=array[0]
for i in range(len(array)):
if array[i]<mini:
if array[i]%11==0:
mini=array[i]
print(mini)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.