repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
rLadia-demo/AttacknidPatch
|
decompiled_src/CFR/org/anddev/andengine/audio/BaseAudioManager.java
|
/*
* Decompiled with CFR 0_79.
*/
package org.anddev.andengine.audio;
import java.util.ArrayList;
import org.anddev.andengine.audio.IAudioEntity;
import org.anddev.andengine.audio.IAudioManager;
public abstract class BaseAudioManager<T extends IAudioEntity>
implements IAudioManager<T> {
protected final ArrayList<T> mAudioEntities = new ArrayList<T>();
protected float mMasterVolume = 1.0f;
@Override
public void add(T T) {
this.mAudioEntities.add(T);
}
@Override
public float getMasterVolume() {
return this.mMasterVolume;
}
@Override
public void releaseAll() {
ArrayList<T> arrayList = this.mAudioEntities;
int n = -1 + arrayList.size();
while (n >= 0) {
IAudioEntity iAudioEntity = (IAudioEntity)arrayList.get(n);
iAudioEntity.stop();
iAudioEntity.release();
--n;
}
return;
}
@Override
public void setMasterVolume(float f) {
this.mMasterVolume = f;
ArrayList<T> arrayList = this.mAudioEntities;
int n = -1 + arrayList.size();
while (n >= 0) {
((IAudioEntity)arrayList.get(n)).onMasterVolumeChanged(f);
--n;
}
return;
}
}
|
white-lab/pyproteome
|
pyproteome/motifs/weblogo.py
|
<filename>pyproteome/motifs/weblogo.py<gh_stars>1-10
import os
import math
import requests
try:
from IPython.display import Image
except ImportError:
Image = None
from . import motif
WEBLOGO_URL = 'http://weblogo.threeplusone.com/create.cgi'
def make_logo(
data,
**kwargs
):
'''
Create a sequence logo figure.
Logos are created based on the frequencies of peptides in a data set.
Parameters
----------
data : :class:`pyproteome.data_sets.DataSet`
'''
nmer_args = motif.get_nmer_args(kwargs)
nmers = motif.generate_n_mers(
data.psms['Sequence'],
**nmer_args
)
nmer_txt = '\n'.join(nmers) + '\n'
first_index = math.ceil(-nmer_args.get('n', 15) / 2)
response = requests.post(
WEBLOGO_URL,
files=(
('sequences_file', ('', nmer_txt, 'application/octet-stream')),
('sequences_url', (None, '')),
('sequences', (None, '')),
('cmd_create', (None, '')),
('logo_title', (None, data.name)),
('format', (None, 'png_print')),
('alphabet', (None, 'alphabet_auto')),
('stack_width', (None, 'large')),
('stacks_per_line', (None, '40')),
('unit_name', (None, 'bits')),
('first_index', (None, str(first_index))),
('logo_start', (None, '')),
('logo_end', (None, '')),
('scale_width', (None, 'true')),
('composition', (None, 'comp_auto')),
('percentCG', (None, '')),
('show_errorbars', (None, 'true')),
# ('show_fineprint', (None, 'true')),
('show_xaxis', (None, 'true')),
('xaxis_label', (None, '')),
('show_yaxis', (None, 'true')),
('yaxis_label', (None, '')),
('yaxis_scale', (None, 'auto')),
('yaxis_tic_interval', (None, '1.0')),
('color_scheme', (None, 'color_auto')),
('symbols0', (None, '')),
('symbols1', (None, '')),
('symbols2', (None, '')),
('symbols3', (None, '')),
('symbols4', (None, '')),
('color0', (None, '')),
('color1', (None, '')),
('color2', (None, '')),
('color3', (None, '')),
('color4', (None, '')),
),
stream=True,
)
response.raise_for_status()
if Image:
return Image(response.content, format='png')
else:
return response.content
|
apache/lenya
|
org.apache.lenya.core.workflow/src/test/java/org/apache/lenya/cms/workflow/WorkflowTest.java
|
<filename>org.apache.lenya.core.workflow/src/test/java/org/apache/lenya/cms/workflow/WorkflowTest.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/* $Id$ */
package org.apache.lenya.cms.workflow;
import org.apache.lenya.ac.Group;
import org.apache.lenya.ac.User;
import org.apache.lenya.cms.AbstractAccessControlTest;
import org.apache.lenya.cms.publication.Document;
import org.apache.lenya.cms.publication.Publication;
import org.apache.lenya.cms.publication.Session;
import org.apache.lenya.workflow.Version;
import org.apache.lenya.workflow.Workflowable;
/**
* To change the template for this generated type comment go to Window>Preferences>Java>Code
* Generation>Code and Comments
*/
public class WorkflowTest extends AbstractAccessControlTest {
private static final String variableName = "is_live";
protected static final String URL = "/authoring/index.html";
protected String getWebappUrl() {
return "/test" + URL;
}
/**
* Tests the workflow.
* @throws Exception when something went wrong.
*/
public void testWorkflow() throws Exception {
User lenya = getAccreditableManager().getUserManager().getUser("lenya");
Group reviewers = getAccreditableManager().getGroupManager().getGroup("reviewer");
reviewers.add(lenya);
Session session = getSession();
Publication publication = session.getPublication("test");
String url = "/" + publication.getId() + URL;
Document document = session.getUriHandler().getDocument(url);
document.lock();
Workflowable workflowable = WorkflowUtil.getWorkflowable(document);
if (workflowable.getVersions().length > 0) {
Version version = workflowable.getLatestVersion();
if (version.getValue(variableName) == true) {
invoke(document, deactivateSituation);
} else if (version.getState().equals("review")) {
invoke(document, rejectSituation);
}
}
for (TestSituation situation : situations) {
invoke(document, situation);
}
document.unlock();
getLogger().info("Test completed.");
}
protected void invoke(Document document, TestSituation situation) throws Exception {
Workflowable instance = new DocumentWorkflowable(document);
assertNotNull(instance);
String event = situation.getEvent();
getLogger().info("Event: " + event);
WorkflowUtil.invoke(document, event);
boolean value = instance.getLatestVersion().getValue(variableName);
getLogger().info("Variable: " + variableName + " = " + value);
getLogger().info("------------------------------------------------------");
assertEquals(value, situation.getValue());
}
protected Session getSession(TestSituation situation) throws Exception {
Session session = login(situation.getUser());
getLogger().info("User: [" + session.getIdentity().getUser() + "]");
return session;
}
private static final TestSituation submitSituation = new TestSituation("lenya", "submit", false);
private static final TestSituation rejectSituation = new TestSituation("alice", "reject", false);
private static final TestSituation deactivateSituation = new TestSituation("alice",
"deactivate", false);
private static final TestSituation publishSituation = new TestSituation("alice", "publish",
true);
private static final TestSituation[] situations = { submitSituation, rejectSituation,
submitSituation, publishSituation, deactivateSituation };
/**
* A test situation.
*/
public static class TestSituation {
private String user;
private String event;
private boolean value;
/**
* Creates a new test situation.
* @param _user The user.
* @param _event The event.
* @param _value The variable value.
*/
public TestSituation(String _user, String _event, boolean _value) {
this.user = _user;
this.event = _event;
this.value = _value;
}
/**
* Returns the event.
* @return An event.
*/
public String getEvent() {
return this.event;
}
/**
* Returns the user.
* @return A string.
*/
public String getUser() {
return this.user;
}
/**
* Returns the value.
* @return A value.
*/
public boolean getValue() {
return this.value;
}
}
}
|
kevin-DL/m3o-go
|
examples/sunnah/hadiths/listTheHadithsInABook.go
|
package example
import (
"fmt"
"os"
"go.m3o.com/sunnah"
)
// Hadiths returns a list of hadiths and their corresponding text for a
// given book within a collection.
func ListTheHadithsInAbook() {
sunnahService := sunnah.NewSunnahService(os.Getenv("M3O_API_TOKEN"))
rsp, err := sunnahService.Hadiths(&sunnah.HadithsRequest{
Book: 1,
Collection: "bukhari",
})
fmt.Println(rsp, err)
}
|
ilin-in/OP
|
hookflash-core/core/hookflash/stack/message/PeerToFinderPeerLocationFindReply.h
|
/*
Copyright (c) 2012, SMB Phone Inc.
All rights reserved.
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.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
#pragma once
#include <hookflash/stack/message/hookflashTypes.h>
#include <hookflash/stack/message/MessageReply.h>
#include <hookflash/stack/message/MessageFactoryStack.h>
namespace hookflash
{
namespace stack
{
namespace message
{
namespace internal { class PeerToFinderPeerLocationFindReply;}
class PeerToFinderPeerLocationFindReply : public MessageReply
{
public:
friend class internal::PeerToFinderPeerLocationFindReply;
enum AttributeTypes
{
AttributeType_Location,
AttributeType_Routes,
};
public:
static PeerToFinderPeerLocationFindReplyPtr convert(MessagePtr message);
static PeerToFinderPeerLocationFindReplyPtr create(PeerToFinderPeerLocationFindRequestPtr request);
virtual zsLib::XML::DocumentPtr encode(IPeerFilesPtr peerFile = IPeerFilesPtr());
virtual Methods method() const {return (Message::Methods)MessageFactoryStack::Method_PeerToFinder_PeerLocationFind;}
virtual IMessageFactoryPtr factory() const {return MessageFactoryStack::singleton();}
bool hasAttribute(AttributeTypes type) const;
const Location &location() const {return mLocation;}
void location(const Location &location) {mLocation = location;}
const RouteList &routes() const {return mRoutes;}
void routes(const RouteList &routes) {mRoutes = routes;}
protected:
PeerToFinderPeerLocationFindReply();
Location mLocation;
RouteList mRoutes;
};
}
}
}
|
Vsevolod1983/RadeonProRenderMaxPlugin
|
FireRender.Max.Plugin/plugin/FireRenderAnalyticalSun.cpp
|
<gh_stars>1-10
/**********************************************************************
Copyright 2020 Advanced Micro Devices, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
********************************************************************/
#include "frWrap.h"
#include "Common.h"
#include "Resource.h"
#include "plugin/FireRenderAnalyticalSun.h"
#include "utils/Utils.h"
#include <math.h>
#include <iparamb2.h>
#include <LINSHAPE.H>
#include <3dsmaxport.h> //for DLGetWindowLongPtr
#include <hsv.h> // just for RGBtoHSV
#include "ParamBlock.h"
#include "plugin/BgManager.h"
//#if MAX_PRODUCT_YEAR_NUMBER >= 2015
//#define FR_USE_IObjectDisplay2 0
//#endif
#define FR_USE_IObjectDisplay2 0
#if FR_USE_IObjectDisplay2
#include <Graphics/Utilities/MeshEdgeRenderItem.h>
#include <Graphics/Utilities/SplineRenderItem.h>
#include <Graphics/CustomRenderItemHandle.h>
#include <Graphics/RenderNodeHandle.h>
#endif
#include <decomp.h>
#include <iparamm2.h>
static void RemoveScaling(Matrix3 &tm) {
AffineParts ap;
decomp_affine(tm, &ap);
tm.IdentityMatrix();
tm.SetRotate(ap.q);
tm.SetTrans(ap.t);
}
#include <memory>
FIRERENDER_NAMESPACE_BEGIN
TCHAR* FIRERENDER_ANALYTICALSUN_CATEGORY = _T("Radeon ProRender");
TCHAR* FIRERENDER_ANALYTICALSUN_OBJECT_NAME = _T("RPRAnalyticalSun");
TCHAR* FIRERENDER_ANALYTICALSUN_INTERNAL_NAME = _T("RPRAnalyticalSun");
TCHAR* FIRERENDER_ANALYTICALSUN_CLASS_NAME = _T("RPRAnalyticalSun");
class FireRenderAnalyticalSunClassDesc : public ClassDesc2
{
public:
int IsPublic() override { return 0; }
HINSTANCE HInstance() override
{
FASSERT(fireRenderHInstance != NULL);
return fireRenderHInstance;
}
//used in MaxScript to create objects of this class
const TCHAR* InternalName() override {
return FIRERENDER_ANALYTICALSUN_INTERNAL_NAME;
}
//used as lable in creation UI and in MaxScript to create objects of this class
const TCHAR* ClassName() override {
return FIRERENDER_ANALYTICALSUN_CLASS_NAME;
}
Class_ID ClassID() override { return FIRERENDER_ANALYTICALSUN_CLASS_ID; }
SClass_ID SuperClassID() override { return LIGHT_CLASS_ID; }
const TCHAR* Category() override {
return FIRERENDER_ANALYTICALSUN_CATEGORY;
}
void* Create(BOOL loading) override ;
};
static FireRenderAnalyticalSunClassDesc desc;
static const int VERSION = 1;
static ParamBlockDesc2 paramBlock(0, _T("AnalyticalSunPbDesc"), 0, &desc, P_AUTO_CONSTRUCT + P_VERSION + P_AUTO_UI,
VERSION, // for P_VERSION
0, //for P_AUTO_CONSTRUCT
//P_AUTO_UI
IDD_FIRERENDER_ANALYTICALSUN, IDS_FR_ENV, 0, 0, NULL,
p_end
);
ClassDesc2* GetFireRenderAnalyticalSunDesc()
{
return &desc;
}
class FireRenderAnalyticalSun : public GenLight
{
class CreateCallBack : public CreateMouseCallBack
{
FireRenderAnalyticalSun *ob;
public:
int proc(ViewExp *vpt, int msg, int point, int flags, IPoint2 m, Matrix3& mat)
{
if (!vpt || !vpt->IsAlive())
{
// why are we here
DbgAssert(!_T("Invalid viewport!"));
return FALSE;
}
Point3 p0;
#ifdef _OSNAP
if (msg == MOUSE_FREEMOVE)
{
#ifdef _3D_CREATE
vpt->SnapPreview(m, m, NULL, SNAP_IN_3D);
#else
vpt->SnapPreview(m, m, NULL, SNAP_IN_PLANE);
#endif
}
#endif
if (msg == MOUSE_POINT || msg == MOUSE_MOVE)
{
// Since we're now allowing the user to set the color of
// the light wire-frames, we need to set the initial light
// color to yellow, instead of the default random object color.
if (point == 0)
{
ULONG handle;
ob->NotifyDependents(FOREVER, (PartID)&handle, REFMSG_GET_NODE_HANDLE);
INode * node;
node = GetCOREInterface()->GetINodeByHandle(handle);
if (node)
{
Point3 color(1, 1, 0); // yellow wire color
node->SetWireColor(RGB(color.x*255.0f, color.y*255.0f, color.z*255.0f));
}
}
#ifdef _3D_CREATE
mat.SetTrans(vpt->SnapPoint(m, m, NULL, SNAP_IN_3D));
#else
mat.SetTrans(vpt->SnapPoint(m, m, NULL, SNAP_IN_PLANE));
#endif
if (point == 1)
{
if (msg == MOUSE_POINT)
return 0;
}
}
else if (msg == MOUSE_ABORT)
return CREATE_ABORT;
return TRUE;
}
void SetObj(FireRenderAnalyticalSun* obj) { ob = obj; }
};
public:
Mesh displayShape;
FireRenderAnalyticalSun()
{
GetFireRenderAnalyticalSunDesc()->MakeAutoParamBlocks(this);
float radius = 15.f;
int nbLong = 8;
int nbLat = 8;
std::vector<Point3> vertices((nbLong + 1) * nbLat + 2);
float _pi = PI;
float _2pi = _pi * 2.f;
Point3 vectorup(0.f, 1.f, 0.f);
vertices[0] = vectorup * radius;
for (int lat = 0; lat < nbLat; lat++)
{
float a1 = _pi * (float)(lat + 1) / (nbLat + 1);
float sin1 = sin(a1);
float cos1 = cos(a1);
for (int lon = 0; lon <= nbLong; lon++)
{
float a2 = _2pi * (float)(lon == nbLong ? 0 : lon) / nbLong;
float sin2 = sin(a2);
float cos2 = cos(a2);
vertices[lon + lat * (nbLong + 1) + 1] = Point3(sin1 * cos2, cos1, sin1 * sin2) * radius;
}
}
vertices[vertices.size() - 1] = vectorup * -radius;
size_t vsize = vertices.size();
displayShape.setNumVerts( int_cast(vsize) );
// triangles
int nbTriangles = nbLong * 2 + (nbLat - 1)*nbLong * 2;//2 caps and one middle
int nbIndexes = nbTriangles * 3;
std::vector<int> triangles(nbIndexes);
//Top Cap
int i = 0;
for (int lon = 0; lon < nbLong; lon++)
{
triangles[i++] = lon + 2;
triangles[i++] = lon + 1;
triangles[i++] = 0;
}
//Middle
for (int lat = 0; lat < nbLat - 1; lat++)
{
for (int lon = 0; lon < nbLong; lon++)
{
int current = lon + lat * (nbLong + 1) + 1;
int next = current + nbLong + 1;
triangles[i++] = current;
triangles[i++] = current + 1;
triangles[i++] = next + 1;
triangles[i++] = current;
triangles[i++] = next + 1;
triangles[i++] = next;
}
}
//Bottom Cap
for (int lon = 0; lon < nbLong; lon++)
{
// TODO: triangles is int32 but vsize is int64, change vsize to 32?
triangles[i++] = int_cast(vsize - 1);
triangles[i++] = int_cast(vsize - (lon + 2) - 1);
triangles[i++] = int_cast(vsize - (lon + 1) - 1);
}
for (int i = 0; i < vertices.size(); i++)
displayShape.setVert(i, vertices[i]);
displayShape.setNumFaces(nbTriangles);
for (int i = 0; i < nbTriangles; i++)
{
Face* f = displayShape.faces + i;
f->v[0] = triangles[i * 3];
f->v[1] = triangles[i * 3 + 1];
f->v[2] = triangles[i * 3 + 2];
f->smGroup = 0;
f->flags = EDGE_ALL;
}
}
~FireRenderAnalyticalSun() {
DebugPrint(_T("FireRenderAnalyticalSun::~FireRenderAnalyticalSun\n"));
DeleteAllRefs();
}
CreateMouseCallBack *BaseObject::GetCreateMouseCallBack(void)
{
static CreateCallBack createCallback;
createCallback.SetObj(this);
return &createCallback;
}
GenLight *NewLight(int type)
{
return new FireRenderAnalyticalSun();
}
// From Object
ObjectState Eval(TimeValue time) {
return ObjectState(this);
}
//makes part of the node name e.g. TheName001, if method returns L"TheName"
void InitNodeName(TSTR& s) { s = FIRERENDER_ANALYTICALSUN_OBJECT_NAME; }
//displayed in Modifier list
const MCHAR *GetObjectName() override { return FIRERENDER_ANALYTICALSUN_OBJECT_NAME; }
Interval ObjectValidity(TimeValue t) override
{
Interval valid;
valid.SetInfinite();
return valid;
}
BOOL UsesWireColor() { return 1; } // 6/18/01 2:51pm --MQM-- now we can set object color
int DoOwnSelectHilite() { return 1; }
void NotifyChanged() { NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); }
// inherited virtual methods for Reference-management
RefResult NotifyRefChanged(NOTIFY_REF_CHANGED_PARAMETERS) override
{
if ((REFMSG_CHANGE==msg) && (hTarget == pblock2))
{
//some params have changed - should redraw all
if(GetCOREInterface()){
GetCOREInterface()->RedrawViews(GetCOREInterface()->GetTime());
}
}
return REF_SUCCEED;
}
IParamBlock2* pblock2 = NULL;
void DeleteThis() override
{
delete this;
}
Class_ID ClassID() override {
return FIRERENDER_ANALYTICALSUN_CLASS_ID;
}
//
void GetClassName(TSTR& s) override {
FIRERENDER_ANALYTICALSUN_CLASS_NAME;
}
IParamBlock2* GetParamBlock(int i) override {
FASSERT(i == 0);
return pblock2;
}
IParamBlock2* GetParamBlockByID(BlockID id) override {
FASSERT(pblock2->ID() == id);
return pblock2;
}
int NumRefs() override {
return 1;
}
void SetReference(int i, RefTargetHandle rtarg) override {
FASSERT(0 == i);
pblock2 = (IParamBlock2*)rtarg;
}
RefTargetHandle GetReference(int i) override {
FASSERT(0 == i);
return (RefTargetHandle)pblock2;
}
INode* GetNodeRef(ReferenceMaker *rm)
{
if (rm->SuperClassID() == BASENODE_CLASS_ID)
return (INode *)rm;
else
return rm->IsRefTarget() ? FindNodeRef((ReferenceTarget *)rm) : NULL;
}
INode* FindNodeRef(ReferenceTarget *rt)
{
DependentIterator di(rt);
ReferenceMaker *rm;
INode *nd = NULL;
while (bool_cast(rm = di.Next()))
{
nd = GetNodeRef(rm);
if (nd) return nd;
}
return NULL;
}
class PLCB : public PostLoadCallback
{
public:
FireRenderAnalyticalSun* p;
PLCB(FireRenderAnalyticalSun* pp) { p = pp; }
void proc(ILoad *iload)
{
BgManagerMax &man = BgManagerMax::TheManager;
INode* node = p->FindNodeRef(p);
man.SetAnalyticalSunNode(node);
delete this;
}
};
IOResult Load(ILoad *iload) override
{
PLCB* plcb = new PLCB(this);
iload->RegisterPostLoadCallback(plcb);
return IO_OK;
}
Matrix3 GetTransformMatrix(TimeValue t, INode* inode, ViewExp* vpt){
Matrix3 tm;
if ( ! vpt->IsAlive() )
{
tm.Zero();
return tm;
}
tm = inode->GetObjectTM(t);
RemoveScaling(tm);
float scaleFactor = vpt->NonScalingObjectSize() * vpt->GetVPWorldWidth(tm.GetTrans()) / 360.0f;
if (scaleFactor!=(float)1.0)
tm.Scale(Point3(scaleFactor,scaleFactor,scaleFactor));
return tm;
}
Color GetViewportMainColor(INode* pNode) {
if (pNode->Dependent())
{
return Color(ColorMan()->GetColor(kViewportShowDependencies));
}
else if (pNode->Selected())
{
return Color(GetSelColor());
}
else if (pNode->IsFrozen())
{
return Color(GetFreezeColor());
}
return Color(1,0,1);
}
Color GetViewportColor(INode* pNode, Color selectedColor) {
if (pNode->Dependent())
{
return Color(ColorMan()->GetColor(kViewportShowDependencies));
}
else if (pNode->Selected())
{
return selectedColor;
}
else if (pNode->IsFrozen())
{
return Color(GetFreezeColor());
}
return selectedColor*0.5f;
}
int Display(TimeValue t, INode* inode, ViewExp *vpt, int flags) override {
if (!vpt || !vpt->IsAlive())
{
// why are we here
DbgAssert(!_T("Invalid viewport!"));
return FALSE;
}
GraphicsWindow *gw = vpt->getGW();
DWORD rlim = gw->getRndLimits();
//wireframe
gw->setRndLimits(GW_WIREFRAME | GW_EDGES_ONLY | GW_TWO_SIDED | GW_ALL_EDGES | (rlim&GW_Z_BUFFER));
gw->setColor(LINE_COLOR, GetViewportColor(inode, Color(0.8f, 0.8f, 0.0f)));
// display sun shape
Matrix3 tm = GetTransformMatrix(t, inode, vpt);
gw->setTransform(tm);
displayShape.render(gw, gw->getMaterial(), NULL, COMP_ALL, 1);
// display line between sun and environment (parent node)
// revert to world coordinate system
Matrix3 identity;
identity.IdentityMatrix();
gw->setTransform(identity);
// draw the line
Matrix3 parentTm = inode->GetParentTM(t);
Point3 v[3];
v[0] = parentTm.GetTrans();
v[1] = tm.GetTrans();
gw->polyline(2, v, NULL, NULL, FALSE, NULL);
gw->setRndLimits(rlim);
return TRUE;
}
void GetWorldBoundBox(TimeValue t, INode* inode, ViewExp* vpt, Box3& box)
{
if (!vpt || !vpt->IsAlive())
{
box.Init();
return;
}
Matrix3 tm;
tm = inode->GetObjectTM(t);
RemoveScaling(tm);
float scaleFactor = vpt->NonScalingObjectSize() * vpt->GetVPWorldWidth(tm.GetTrans()) / 360.0f;
Point3 loc = tm.GetTrans();
box = displayShape.getBoundingBox(&tm);
box.Scale(scaleFactor*0.5);
}
//w're using retained mode, so we don't need to implement this
int HitTest(TimeValue t, INode* inode, int type, int crossing, int flags, IPoint2 *p, ViewExp *vpt) override
{
if ( ! vpt || ! vpt->IsAlive() )
{
// why are we here
DbgAssert(!_T("Invalid viewport!"));
return FALSE;
}
HitRegion hitRegion;
GraphicsWindow *gw = vpt->getGW();
DWORD savedLimits = gw->getRndLimits();
Material *mtl = gw->getMaterial();
MakeHitRegion(hitRegion, type, crossing, 4, p);
gw->setRndLimits((savedLimits | GW_PICK) & ~GW_ILLUM);
gw->setTransform(GetTransformMatrix(t, inode, vpt));
gw->clearHitCode();
BOOL res = displayShape.select(gw, mtl, &hitRegion, flags & HIT_ABORTONHIT);
gw->setRndLimits(savedLimits);
return res;
};
int extDispFlags = 0;
void SetExtendedDisplay(int flags)
{
extDispFlags = flags;
}
void GetLocalBoundBox(TimeValue t, INode* inode, ViewExp* vpt, Box3& box)
{
Interval ivalid = FOREVER;
box = displayShape.getBoundingBox();
Point3 loc = inode->GetObjectTM(t).GetTrans();
float scaleFactor = vpt->NonScalingObjectSize()*vpt->GetVPWorldWidth(loc) / 360.0f;
box.Scale(scaleFactor);
}
TimeValue getEditTime() {
return GetCOREInterface()->GetTime();
}
// LightObject methods
Point3 GetRGBColor(TimeValue t, Interval &valid) override { return Point3(1.0f, 1.0f, 1.0f); }
void SetRGBColor(TimeValue t, Point3 &color) override { /* empty */ }
void SetUseLight(int onOff) override { /* empty */ }
BOOL GetUseLight() override
{
return TRUE;
}
void SetHotspot(TimeValue time, float f) override { /* empty */ }
float GetHotspot(TimeValue t, Interval& valid) override { return -1.0f; }
void SetFallsize(TimeValue time, float f) override { /* empty */ }
float GetFallsize(TimeValue t, Interval& valid) override { return -1.0f; }
void SetAtten(TimeValue time, int which, float f) override { /* empty */ }
float GetAtten(TimeValue t, int which, Interval& valid) override { return 0.0f; }
void SetTDist(TimeValue time, float f) override { /* empty */ }
float GetTDist(TimeValue t, Interval& valid) override { return 0.0f; }
void SetConeDisplay(int s, int notify) override { /* empty */ }
BOOL GetConeDisplay() override { return FALSE; }
void SetIntensity(TimeValue time, float f) override { /* empty */ }
float GetIntensity(TimeValue t, Interval& valid) override { return 1.0f; }
void SetUseAtten(int s) override { /* empty */ }
BOOL GetUseAtten() override { return FALSE; }
void SetAspect(TimeValue t, float f) override { /* empty */ }
float GetAspect(TimeValue t, Interval& valid) override { return -1.0f; }
void SetOvershoot(int a) override { /* empty */ }
int GetOvershoot() override { return 0; }
void SetShadow(int a) override { /* empty */ }
int GetShadow() override { return 0; }
// From Light
RefResult EvalLightState(TimeValue t, Interval& valid, LightState* cs)
{
cs->color = GetRGBColor(t, valid);
cs->on = GetUseLight();
cs->intens = GetIntensity(t, valid);
cs->hotsize = GetHotspot(t, valid);
cs->fallsize = GetFallsize(t, valid);
cs->useNearAtten = FALSE;
cs->useAtten = GetUseAtten();
cs->nearAttenStart = GetAtten(t, ATTEN1_START, valid);
cs->nearAttenEnd = GetAtten(t, ATTEN1_END, valid);
cs->attenStart = GetAtten(t, ATTEN_START, valid);
cs->attenEnd = GetAtten(t, ATTEN_END, valid);
cs->aspect = GetAspect(t, valid);
cs->overshoot = GetOvershoot();
cs->shadow = GetShadow();
cs->shape = CIRCLE_LIGHT;
cs->ambientOnly = GetAmbientOnly();
cs->affectDiffuse = GetAffectDiffuse();
cs->affectSpecular = GetAffectSpecular();
cs->type = OMNI_LGT;
return REF_SUCCEED;
}
ObjLightDesc* CreateLightDesc(INode *inode, BOOL forceShadowBuf) override { return NULL; }
// virtual GenLight *NewLight(int type);
int Type() override { return OMNI_LIGHT; }
virtual void SetHSVColor(TimeValue, Point3 &)
{
}
virtual Point3 GetHSVColor(TimeValue t, Interval &valid)
{
int h, s, v;
Point3 rgbf = GetRGBColor(t, valid);
DWORD rgb = RGB((int)(rgbf[0] * 255.0f), (int)(rgbf[1] * 255.0f), (int)(rgbf[2] * 255.0f));
RGBtoHSV(rgb, &h, &s, &v);
return Point3(h / 255.0f, s / 255.0f, v / 255.0f);
}
void SetAttenDisplay(int) override { /* empty */ }
BOOL GetAttenDisplay() override { return FALSE; }
void Enable(int) override {}
void SetMapBias(TimeValue, float) override { /* empty */ }
float GetMapBias(TimeValue, Interval &) override { return 0; }
void SetMapRange(TimeValue, float) override { /* empty */ }
float GetMapRange(TimeValue, Interval &) override { return 0; }
void SetMapSize(TimeValue, int) override { /* empty */ }
int GetMapSize(TimeValue, Interval &) override { return 0; }
void SetRayBias(TimeValue, float) override { /* empty */ }
float GetRayBias(TimeValue, Interval &) override { return 0; }
int GetUseGlobal() override { return FALSE; }
void SetUseGlobal(int) override { /* empty */ }
int GetShadowType() override { return -1; }
void SetShadowType(int) override { /* empty */ }
int GetAbsMapBias() override { return FALSE; }
void SetAbsMapBias(int) override { /* empty */ }
BOOL IsSpot() override { return FALSE; }
BOOL IsDir() override { return FALSE; }
void SetSpotShape(int) override { /* empty */ }
int GetSpotShape() override { return CIRCLE_LIGHT; }
void SetContrast(TimeValue, float) override { /* empty */ }
float GetContrast(TimeValue, Interval &) override { return 0; }
void SetUseAttenNear(int) override { /* empty */ }
BOOL GetUseAttenNear() override { return FALSE; }
void SetAttenNearDisplay(int) override { /* empty */ }
BOOL GetAttenNearDisplay() override { return FALSE; }
ExclList &GetExclusionList() override { return m_exclList; }
void SetExclusionList(ExclList &) override { /* empty */ }
BOOL SetHotSpotControl(Control *) override { return FALSE; }
BOOL SetFalloffControl(Control *) override { return FALSE; }
BOOL SetColorControl(Control *) override { return FALSE; }
Control *GetHotSpotControl() override { return NULL; }
Control *GetFalloffControl() override { return NULL; }
Control *GetColorControl() override { return NULL; }
void SetAffectDiffuse(BOOL onOff) override { /* empty */ }
BOOL GetAffectDiffuse() override { return TRUE; }
void SetAffectSpecular(BOOL onOff) override { /* empty */ }
BOOL GetAffectSpecular() override { return TRUE; }
void SetAmbientOnly(BOOL onOff) override { /* empty */ }
BOOL GetAmbientOnly() override { return FALSE; }
void SetDecayType(BOOL onOff) override {}
BOOL GetDecayType() override { return 1; }
void SetDecayRadius(TimeValue time, float f) override {}
float GetDecayRadius(TimeValue t, Interval& valid) override { return 40.0f; } //! check different values
protected:
ExclList m_exclList;
};
void* FireRenderAnalyticalSunClassDesc::Create(BOOL loading) {
return new FireRenderAnalyticalSun();
}
FIRERENDER_NAMESPACE_END
|
AlexWayfer/toys
|
toys-core/test/lookup-cases/append/.toys.rb
|
<filename>toys-core/test/lookup-cases/append/.toys.rb
# frozen_string_literal: true
append "namespace-1" do
tool "tool-1-2" do
desc "file tool-1-2 short description"
long_desc "file tool-1-2 long description"
def run
puts "file tool-1-2 execution"
end
end
end
|
Yeeyao/leetcode-go
|
array/31_test.go
|
package array
import (
"reflect"
"testing"
)
func TestPro(t *testing.T) {
t.Run("31. Next Permutation", func(t *testing.T) {
nums := []int{1, 2, 3}
want := []int{1, 3, 2}
nextPermutation(nums)
if !reflect.DeepEqual(nums, want) {
t.Errorf("got: %v, want: %v", nums, want)
}
})
}
func nextPermutation(nums []int) {
numsLen := len(nums)
i, j, k := numsLen-2, numsLen-1, numsLen-1
// 从后面向前找到 nums[i] < nums[j] 第一个元素比后面元素小的位置,同时 j 后面的元素都是降序的
for i >= 0 && nums[i] >= nums[j] {
i--
j--
}
// 如果找到了,从后面找第一个 nums[k] > nums[i] 然后交换,因为 j 后面的元素是降序的,因此这里也是找到最小的大于 i 元素
if i >= 0 {
for nums[i] >= nums[k] {
k--
}
nums[i], nums[k] = nums[k], nums[i]
}
// 最后将 j 后面的降序,满足排列
for i, j := j, numsLen-1; i < j; i, j = i+1, j-1 {
nums[i], nums[j] = nums[j], nums[i]
}
}
/*
[ref](https://leetcode-cn.com/problems/next-permutation/solution/xia-yi-ge-pai-lie-suan-fa-xiang-jie-si-lu-tui-dao-/)
需要注意,这里是将后面的尽量小的大数和前面的小数交换,然后对大数之后的元素升序排列
12534321 12541233
从后面向前找到 第一个 nums[i] > nums[i-1](等号需要继续向前找) 此时 i 到数组结尾都是降序的
然后从 i 向后面找到最小的数字同时需要大于 nums[i-1](因为第一个位置的不一定是后面最小的数字)
这个数字跟 i 的数字交换后,i 后面的排序
1. 从后向前 查找第一个相邻元素对(i,j) 满足 A[i] < A[j] 此时 j 到最后的元素都是降序的
2. 在 j 到最后的元素从后向前找到第一个满足 A[i] < A[k] 的 k 这里 A[k] 就是第一个大于 A[i] 的最小元素
3. A[i] 直接和 A[k] 交换
4. 之后 j 到最后的元素是降序的,直接反转它们
5. 如果 1 中找不到这样的相邻元素,直接 4
*/
func solution(nums []int) {
numsLen := len(nums)
// 这里比较最后两个元素
i, k := numsLen-1, numsLen-1
// 等于号的处理 从后面向前找 第一个位置,该位置比上一个位置的元素大
for i > 0 && nums[i-1] >= nums[i] {
i--
}
// 将前面找到的元素位置到结尾的所有元素位置反转(将原来的后面的降序数组变成升序的)
// 如果是降序的话,i 已经是 0 同时这里将所有元素反转了,可以直接返回
for j := i; j < k; j, k = j+1, k-1 {
nums[j], nums[k] = nums[k], nums[j]
}
// 不是降序排列 需要注意这里关键元素的位置
if i > 0 {
// 从 i 位置开始 即从大于上一个元素的位置开始
k = i
// 注意这里将 i 递减了才是 i 位置的元素原来是小于下一个元素的
// 这里向后找第一个元素大于 i 位置的元素,并交换
i--
for nums[k] <= nums[i] {
k++
}
nums[i], nums[k] = nums[k], nums[i]
}
}
|
kushagra27/Use-IBM-MQ-and-App-Connect-on-Cloud-to-transform-data
|
web-app-a/node_modules/carbon-components-react/es/components/ExpandableSearch/ExpandableSearch.js
|
<filename>web-app-a/node_modules/carbon-components-react/es/components/ExpandableSearch/ExpandableSearch.js
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
* Copyright IBM Corp. 2021
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useState, useRef, useEffect } from 'react';
import classnames from 'classnames';
import { settings } from 'carbon-components';
import Search from '../Search';
var prefix = settings.prefix;
function ExpandableSearch(props) {
var _useState = useState(false),
_useState2 = _slicedToArray(_useState, 2),
expanded = _useState2[0],
setExpanded = _useState2[1];
var searchRef = useRef(null);
function handleFocus() {
if (!expanded) {
setExpanded(true);
}
}
function handleBlur(evt) {
var relatedTargetIsAllowed = evt.relatedTarget && evt.relatedTarget.classList.contains("".concat(prefix, "--search-close"));
if (expanded && !relatedTargetIsAllowed && !searchRef.current.state.hasContent) {
setExpanded(false);
}
}
useEffect(function () {
var _searchRef$current2;
function focusInput() {
var _searchRef$current;
if (!expanded && (_searchRef$current = searchRef.current) !== null && _searchRef$current !== void 0 && _searchRef$current.input) {
searchRef.current.input.focus();
}
}
if ((_searchRef$current2 = searchRef.current) !== null && _searchRef$current2 !== void 0 && _searchRef$current2.magnifier) {
var magnifier = searchRef.current.magnifier;
magnifier.addEventListener('click', focusInput);
return function () {
magnifier.removeEventListener('click', focusInput);
};
}
}, [expanded, searchRef]);
var classes = classnames("".concat(prefix, "--search--expandable"), _defineProperty({}, "".concat(prefix, "--search--expanded"), expanded), props.className);
return /*#__PURE__*/React.createElement(Search, _extends({}, props, {
ref: searchRef,
className: classes,
onFocus: handleFocus,
onBlur: handleBlur
}));
}
ExpandableSearch.propTypes = Search.propTypes;
export default ExpandableSearch;
|
amstee/NeoRestAPI
|
config/firebase.py
|
<filename>config/firebase.py<gh_stars>1-10
import json
with open('config.json') as data_file:
neo_config = json.load(data_file)
PROJECT_ID = neo_config["firebase"]["project_id"]
KEY_FILE = neo_config["firebase"]
BASE_URL = 'https://fcm.googleapis.com'
FCM_ENDPOINT = 'v1/projects/' + PROJECT_ID + '/messages:send'
FCM_URL = BASE_URL + '/' + FCM_ENDPOINT
SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']
|
XuesongDing/fatiando
|
gallery/gridder/cutting.py
|
"""
Cutting a section from spacial data
-----------------------------------
The :func:`fatiando.gridder.cut` function extracts points from spatially
distributed data that are inside a given area. It doesn't matter whether or
not the points are on a regular grid.
"""
from fatiando import gridder
import matplotlib.pyplot as plt
import numpy as np
# Generate some synthetic data
area = (-100, 100, -60, 60)
x, y = gridder.scatter(area, 1000, seed=0)
data = np.sin(0.1*x)*np.cos(0.1*y)
# Select the data that fall inside "section"
section = [-40, 40, -25, 25]
# Tip: you pass more than one data array as input. Use this to cut multiple
# data sources (e.g., gravity + height + topography).
x_sub, y_sub, [data_sub] = gridder.cut(x, y, [data], section)
# Plot the original data besides the cut section
plt.figure(figsize=(8, 6))
plt.subplot(1, 2, 1)
plt.axis('scaled')
plt.title("Whole data")
plt.tricontourf(y, x, data, 30, cmap='RdBu_r')
plt.plot(y, x, 'xk')
x1, x2, y1, y2 = section
plt.plot([y1, y2, y2, y1, y1], [x1, x1, x2, x2, x1], '-k', linewidth=3)
plt.xlim(area[2:])
plt.ylim(area[:2])
plt.subplot(1, 2, 2)
plt.axis('scaled')
plt.title("Subsection")
plt.plot(y_sub, x_sub, 'xk')
plt.tricontourf(y_sub, x_sub, data_sub, 30, cmap='RdBu_r')
plt.xlim(section[2:])
plt.ylim(section[:2])
plt.tight_layout()
plt.show()
|
Shigawire/eui
|
src/components/icon/assets/app_spaces.js
|
<reponame>Shigawire/eui
import React from "react";
const EuiIconAppSpaces = props => <svg width={32} height={32} viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" {...props}><path className="euiIcon__fillSecondary" d="M4 4h6v2H4zM22 4h6v2h-6zM4 22h6v2H4z" /><path d="M0 14h14V0H0v14zM2 2h10v10H2V2zm16-2v14h14V0H18zm12 12H20V2h10v10zM0 32h14V18H0v14zm2-12h10v10H2V20zm16 12h14V18H18v14zm2-12h10v10H20V20z" /><path className="euiIcon__fillSecondary" d="M22 22h6v2h-6z" /></svg>;
export const icon = EuiIconAppSpaces;
|
domlimm/tp
|
src/main/java/seedu/address/logic/commands/FocusCommand.java
|
<filename>src/main/java/seedu/address/logic/commands/FocusCommand.java
package seedu.address.logic.commands;
import static java.util.Objects.requireNonNull;
import java.util.List;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.index.Index;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.Model;
import seedu.address.model.candidate.Candidate;
public class FocusCommand extends Command {
public static final String MESSAGE_FOCUS_CANDIDATE = "Details of candidate shown";
public static final String MESSAGE_USAGE = "focus: Brings up a candidate's information into the middle panel.\n"
+ "Parameters: INDEX\n"
+ "Example: focus 1\n"
+ "Note: The candidate index number must be a valid non zero positive integer.";
public static final String COMMAND_WORD = "focus";
private final Index targetIndex;
/**
* Constructor for creating a Focus Command.
*/
public FocusCommand(Index targetIndex) {
requireNonNull(targetIndex);
this.targetIndex = targetIndex;
}
/**
* Executes the focus command to a particular index.
*
* @throws CommandException when the command is invalid or index is wrong.
*/
public CommandResult execute(Model model) throws CommandException {
requireNonNull(model);
List<Candidate> lastShownList = model.getFilteredCandidateList();
if (lastShownList.isEmpty()) {
throw new CommandException(String.format(Messages.MESSAGE_NO_CANDIDATES_IN_SYSTEM));
}
if (targetIndex.getZeroBased() >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_CANDIDATE_DISPLAYED_INDEX);
}
Candidate candidateToShow = lastShownList.get(targetIndex.getZeroBased());
return new CommandResult(String.format(MESSAGE_FOCUS_CANDIDATE),
false, false, true, targetIndex.getZeroBased(), false, -1);
}
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other == this) {
return true;
} else if (other instanceof FocusCommand) {
if (((FocusCommand) other).targetIndex.equals(this.targetIndex)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public Index getTargetIndex() {
return targetIndex;
}
}
|
vmware/connectors-workspace-one
|
hub-hubspot-deals-connector/test/services/hubspot-services-test.js
|
<filename>hub-hubspot-deals-connector/test/services/hubspot-services-test.js<gh_stars>10-100
/*
* Copyright © 2020 VMware, Inc. All Rights Reserved.
* SPDX-License-Identifier: BSD-2-Clause
*/
'use strict'
const { describe } = require('mocha')
const { expect } = require('chai')
const sinon = require('sinon')
const chai = require('chai')
const nock = require('nock')
const { getUserInfo, getAssignedDeals, getDealStagesMap, performActionOnDeal, getContactNamesOfDeal, getCompanyInfoFromId } = require('../../services/hubspot-services')
const sinonChai = require('sinon-chai')
chai.use(sinonChai)
describe('Service API tests', () => {
describe('getUserInfo', () => {
it('Get userInfo', async () => {
nock('https://api.hubapi.com')
.get(url => url.includes('access-tokens'))
.reply(200, userInfoMockResp)
const response = await getUserInfo({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
})
expect(typeof response).to.equal('object')
expect(response.user).to.equal('<EMAIL>')
})
it('get userInfo in network error', async () => {
nock('https://api.hubapi.com')
.get(url => url.includes('access-tokens'))
.reply(404,{
"status": "error",
"message": "The access token is expired or invalid"
})
try {
await getUserInfo({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
})
sinon.assert.fail('getUserInfo should throw exception. so this path should not be reachable')
} catch (err) {
const error = JSON.parse(err.message)
expect(error.statusCode).to.equal(401)
}
})
})
describe('getAssignedDeals', () => {
it('getAssignedDeals valid flow', async () => {
nock('https://api.hubapi.com')
.get("/deals/v1/deal/paged")
.query(true)
.reply(200, myOpenDeals)
const response = await getAssignedDeals({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
}, '<EMAIL>' )
expect(typeof response).to.equal('object')
expect(response.length).to.equal(1)
expect(response[0].dealId).to.equal(2776312614)
})
it('getAssignedDeals in network error', async () => {
nock('https://api.hubapi.com')
.get("/deals/v1/deal/paged")
.query(true)
.reply(401)
try {
await getAssignedDeals({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
}, '<EMAIL>' )
sinon.assert.fail('getMyOpenCases should throw exception. so this path should not be reachable')
} catch (err) {
const error = JSON.parse(err.message)
expect(error.statusCode).to.equal(401)
}
})
})
describe('getDealStagesMap', () => {
it('getDealStagesMap happy path', async () => {
nock('https://api.hubapi.com')
.get('/crm-pipelines/v1/pipelines/deals')
.reply(200, dealStagesOutput)
const response = await getDealStagesMap({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
})
expect(typeof response).to.equal('object')
})
it('getDealStagesMap in network error', async () => {
nock('https://api.hubapi.com')
.get('/crm-pipelines/v1/pipelines/deals')
.reply(401)
try {
await getDealStagesMap({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
})
sinon.assert.fail('actionsOnCase should throw exception. so this path should not be reachable')
} catch (err) {
const error = JSON.parse(err.message)
expect(error.statusCode).to.equal(401)
}
})
})
describe('getContactNamesOfDeal', () => {
it('getContactNamesOfDeal happy path', async () => {
nock('https://api.hubapi.com')
.get('/contacts/v1/contact/vids/batch')
.query(true)
.reply(200, contactInfo)
const response = await getContactNamesOfDeal({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
},[51,151])
expect(typeof response).to.equal('object')
})
it('getContactNamesOfDeal in network error', async () => {
nock('https://api.hubapi.com')
.get('/contacts/v1/contact/vids/batch')
.query(true)
.reply(401)
try { await getContactNamesOfDeal({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
}, [51,151])
} catch (err) {
const error = JSON.parse(err.message)
expect(error.statusCode).to.equal(401)
}
})
})
describe('getCompanyInfoFromId', () => {
it('getCompanyInfoFromId happy path', async () => {
nock('https://api.hubapi.com')
.get(url => url.includes('/companies/v2/companies/'))
.reply(200, companyInfo)
const response = await getCompanyInfoFromId({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
}, 4294592507)
expect(typeof response).to.equal('string')
})
it('getCompanyInfoFromId in network error handle', async () => {
nock('https://api.hubapi.com')
.get(url => url.includes('/companies/v2/companies/'))
.reply(401)
try {
await getCompanyInfoFromId({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
}, 4294592507)
} catch (err) {
const error = JSON.parse(err.message)
expect(error.statusCode).to.equal(401)
}
})
})
describe('performActionOnDeal', () => {
it('performActionOnDeal happy path', async () => {
nock('https://api.hubapi.com')
.post('/engagements/v1/engagements', {
"associations": {
"ownerIds": [],
"companyIds": [],
"contactIds": [],
"dealIds": [2776312614],
"ticketIds": [],
"engagementsV2UniversalAssociations": {}
},
"engagement": {
"source": "CRM_UI",
"sourceId": '<EMAIL>',
"type": 'NOTE',
"timestamp": 12345,
"ownerId": 50035835
},
"metadata": {
"body": `<p>test comment</p>`
},
"attachments": [],
"scheduledTasks": [],
"inviteeEmails": []
})
.reply(200,statusInfo)
const response = await performActionOnDeal({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
}, 2776312614,50035835,'<EMAIL>','test comment','NOTE',12345)
expect(response).to.equal(200)
})
it('performActionOnDeal in network error handle', async () => {
nock('https://api.hubapi.com')
.post('/engagements/v1/engagements',{
"associations": {
"ownerIds": [],
"companyIds": [],
"contactIds": [],
"dealIds": [2776312614],
"ticketIds": [],
"engagementsV2UniversalAssociations": {}
},
"engagement": {
"source": "CRM_UI",
"sourceId": '<EMAIL>',
"type": 'NOTE',
"timestamp": 12345,
"ownerId": 50035835
},
"metadata": {
"body": `<p>test comment</p>`
},
"attachments": [],
"scheduledTasks": [],
"inviteeEmails": []
})
.reply(401)
try {
await performActionOnDeal({
connectorAuthorization: 'Bearer connectorAuthorizationValue',
apiBaseUrl: 'https://api.hubapi.com',
mfJwt: { email: '<EMAIL>' }
}, 2776312614,50035835,'<EMAIL>','test comment','NOTE',12345)
} catch (err) {
const error = JSON.parse(err.message)
expect(error.statusCode).to.equal(401)
}
})
})
})
const userInfoMockResp = {
"token": "<KEY>",
"user": "<EMAIL>",
"hub_domain": "backflipt.com",
"scopes": [
"contacts",
"oauth",
"tickets"
],
"scope_to_scope_group_pks": [
10,
12,
18,
25,
31,
51,
52,
64,
66,
71,
72,
73,
74,
75,
84,
113,
180,
181,
191,
192,
201,
202,
203,
204,
205
],
"hub_id": 8247786,
"app_id": 226514,
"expires_in": 19565,
"user_id": 11612752,
"token_type": "access"
}
const myOpenDeals = {
"deals": [
{
"portalId": 8247786,
"dealId": 2789520462,
"isDeleted": false,
"associations": {
"associatedVids": [],
"associatedCompanyIds": [],
"associatedDealIds": [],
"associatedTicketIds": []
},
"properties": {
"dealname": {
"value": "7Deal-$0",
"timestamp": 1597300905392,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "dealname",
"value": "7Deal-$0",
"timestamp": 1597300905392,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"amount": {
"value": "0",
"timestamp": 1597300905392,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "amount",
"value": "0",
"timestamp": 1597300905392,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"closedate": {
"value": "1598856093402",
"timestamp": 1597300905392,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "closedate",
"value": "1598856093402",
"timestamp": 1597300905392,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"hubspot_owner_id": {
"value": "50103167",
"timestamp": 1597300905392,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "hubspot_owner_id",
"value": "50103167",
"timestamp": 1597300905392,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"hs_lastmodifieddate": {
"value": "1597300907726",
"timestamp": 1597300907726,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "hs_lastmodifieddate",
"value": "1597300907726",
"timestamp": 1597300907726,
"source": "CALCULATED",
"sourceVid": []
}
]
},
"dealstage": {
"value": "closedlost",
"timestamp": 1597300905392,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "dealstage",
"value": "closedlost",
"timestamp": 1597300905392,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"hs_createdate": {
"value": "1597300905392",
"timestamp": 1597300905392,
"source": "CONTACTS",
"sourceId": "CRM_UI",
"versions": [
{
"name": "hs_createdate",
"value": "1597300905392",
"timestamp": 1597300905392,
"sourceId": "CRM_UI",
"source": "CONTACTS",
"sourceVid": []
}
]
},
"days_to_close": {
"value": "18",
"timestamp": 1597300905392,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "days_to_close",
"value": "18",
"timestamp": 1597300905392,
"source": "CALCULATED",
"sourceVid": []
}
]
},
"dealtype": {
"value": "existingbusiness",
"timestamp": 1597300905392,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "dealtype",
"value": "existingbusiness",
"timestamp": 1597300905392,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
}
},
"imports": [],
"stateChanges": []
},
{
"portalId": 8247786,
"dealId": 2776312614,
"isDeleted": false,
"associations": {
"associatedVids": [],
"associatedCompanyIds": [],
"associatedDealIds": [],
"associatedTicketIds": []
},
"properties": {
"dealname": {
"value": "Workspace one",
"timestamp": 1597036631500,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "dealname",
"value": "Workspace one",
"timestamp": 1597036631500,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"amount": {
"value": "100000",
"timestamp": 1597036631500,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "amount",
"value": "100000",
"timestamp": 1597036631500,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"closedate": {
"value": "1598850937213",
"timestamp": 1597036631500,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "closedate",
"value": "1598850937213",
"timestamp": 1597036631500,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"hubspot_owner_id": {
"value": "50035835",
"timestamp": 1597036631500,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "hubspot_owner_id",
"value": "50035835",
"timestamp": 1597036631500,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"hs_lastmodifieddate": {
"value": "1597070565671",
"timestamp": 1597070565671,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "hs_lastmodifieddate",
"value": "1597070565671",
"timestamp": 1597070565671,
"source": "CALCULATED",
"sourceVid": []
}
]
},
"dealstage": {
"value": "appointmentscheduled",
"timestamp": 1597036631500,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "dealstage",
"value": "appointmentscheduled",
"timestamp": 1597036631500,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
},
"hs_createdate": {
"value": "1597036631500",
"timestamp": 1597036631500,
"source": "CONTACTS",
"sourceId": "CRM_UI",
"versions": [
{
"name": "hs_createdate",
"value": "1597036631500",
"timestamp": 1597036631500,
"sourceId": "CRM_UI",
"source": "CONTACTS",
"sourceVid": []
}
]
},
"days_to_close": {
"value": "21",
"timestamp": 1597036631500,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "days_to_close",
"value": "21",
"timestamp": 1597036631500,
"source": "CALCULATED",
"sourceVid": []
}
]
},
"dealtype": {
"value": "newbusiness",
"timestamp": 1597036631500,
"source": "CRM_UI",
"sourceId": "<EMAIL>",
"versions": [
{
"name": "dealtype",
"value": "newbusiness",
"timestamp": 1597036631500,
"sourceId": "<EMAIL>",
"source": "CRM_UI",
"sourceVid": []
}
]
}
},
"imports": [],
"stateChanges": []
}
],
"hasMore": false,
"offset": 2790918962
}
const statusInfo ={
'status':200
}
const dealStagesOutput = {
"results": [
{
"label": "Sales Pipeline",
"displayOrder": 0,
"active": true,
"stages": [
{
"label": "Appointment Scheduled",
"displayOrder": 0,
"metadata": {
"isClosed": "false",
"probability": "0.2"
},
"stageId": "appointmentscheduled",
"createdAt": 0,
"updatedAt": 1597309656644,
"active": true
},
{
"label": "Pre Qualified To Buy",
"displayOrder": 1,
"metadata": {
"isClosed": "true",
"probability": "1.0"
},
"stageId": "4074848",
"createdAt": 0,
"updatedAt": 1597309656644,
"active": true
},
{
"label": "Closed Won",
"displayOrder": 6,
"metadata": {
"isClosed": "true",
"probability": "1.0"
},
"stageId": "closedwon",
"createdAt": 0,
"updatedAt": 1597309656644,
"active": true
},
{
"label": "Presentation Scheduled",
"displayOrder": 3,
"metadata": {
"isClosed": "false",
"probability": "0.6"
},
"stageId": "presentationscheduled",
"createdAt": 0,
"updatedAt": 1597309656644,
"active": true
},
{
"label": "Closed Lost",
"displayOrder": 7,
"metadata": {
"isClosed": "true",
"probability": "0.0"
},
"stageId": "closedlost",
"createdAt": 0,
"updatedAt": 1597309656644,
"active": true
},
{
"label": "Qualified To Buy",
"displayOrder": 2,
"metadata": {
"isClosed": "false",
"probability": "0.4"
},
"stageId": "qualifiedtobuy",
"createdAt": 0,
"updatedAt": 1597309656644,
"active": true
},
{
"label": "Decision Maker Bought-In",
"displayOrder": 4,
"metadata": {
"isClosed": "false",
"probability": "0.8"
},
"stageId": "decisionmakerboughtin",
"createdAt": 0,
"updatedAt": 1597309656644,
"active": true
},
{
"label": "Contract Sent",
"displayOrder": 5,
"metadata": {
"isClosed": "false",
"probability": "0.9"
},
"stageId": "contractsent",
"createdAt": 0,
"updatedAt": 1597309656644,
"active": true
}
],
"objectType": "DEAL",
"objectTypeId": "0-3",
"pipelineId": "default",
"createdAt": 0,
"updatedAt": 1597309656644,
"default": true
}
]
}
const companyInfo = {
"portalId": 8247786,
"companyId": 4294592507,
"isDeleted": false,
"properties": {
"country": {
"value": "United States",
"timestamp": 1597036440201,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "country",
"value": "United States",
"timestamp": 1597036440201,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"city": {
"value": "Cambridge",
"timestamp": 1597036440201,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "city",
"value": "Cambridge",
"timestamp": 1597036440201,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"num_associated_contacts": {
"value": "2",
"timestamp": 1597036442920,
"source": "CALCULATED",
"sourceId": "RollupProperties",
"versions": [
{
"name": "num_associated_contacts",
"value": "2",
"timestamp": 1597036442920,
"sourceId": "RollupProperties",
"source": "CALCULATED",
"sourceVid": []
}
]
},
"timezone": {
"value": "America/New_York",
"timestamp": 1597036440201,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "timezone",
"value": "America/New_York",
"timestamp": 1597036440201,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"facebook_company_page": {
"value": "https://www.facebook.com/hubspot",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "facebook_company_page",
"value": "https://www.facebook.com/hubspot",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"createdate": {
"value": "1597036439975",
"timestamp": 1597036439975,
"source": "COMPANIES",
"sourceId": "FetchAssociatedCompanyIdStep",
"versions": [
{
"name": "createdate",
"value": "1597036439975",
"timestamp": 1597036439975,
"sourceId": "FetchAssociatedCompanyIdStep",
"source": "COMPANIES",
"sourceVid": []
}
]
},
"description": {
"value": "HubSpot is an American developer and marketer of software products for inbound marketing, sales, and customer service.",
"timestamp": 1597036440201,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "description",
"value": "HubSpot is an American developer and marketer of software products for inbound marketing, sales, and customer service.",
"timestamp": 1597036440201,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"hs_num_blockers": {
"value": "0",
"timestamp": 1597036441226,
"source": "SALES",
"sourceId": "AssociationsPropertyWorker",
"versions": [
{
"name": "hs_num_blockers",
"value": "0",
"timestamp": 1597036441226,
"sourceId": "AssociationsPropertyWorker",
"source": "SALES",
"sourceVid": []
}
]
},
"industry": {
"value": "COMPUTER_SOFTWARE",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "industry",
"value": "COMPUTER_SOFTWARE",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"total_money_raised": {
"value": "100.5M",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "total_money_raised",
"value": "100.5M",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"web_technologies": {
"value": "unbounce;facebook_advertiser;salesforce;app_nexus;cloud_flare;piwik;dstillery;google_analytics;twitter_button;hubspot;vidyard;sentry;google_tag_manager;facebook_connect;crazy_egg;amazon__cloudfront;wistia;optimizely",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "web_technologies",
"value": "unbounce;facebook_advertiser;salesforce;app_nexus;cloud_flare;piwik;dstillery;google_analytics;twitter_button;hubspot;vidyard;sentry;google_tag_manager;facebook_connect;crazy_egg;amazon__cloudfront;wistia;optimizely",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"hs_total_deal_value": {
"value": "1200.0",
"timestamp": 1597049601469,
"source": "SALES",
"sourceId": "AssociationsPropertyWorker",
"versions": [
{
"name": "hs_total_deal_value",
"value": "1200.0",
"timestamp": 1597049601469,
"sourceId": "AssociationsPropertyWorker",
"source": "SALES",
"sourceVid": []
}
]
},
"numberofemployees": {
"value": "5000",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "numberofemployees",
"value": "5000",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"hs_analytics_num_visits": {
"value": "0",
"timestamp": 1597036442756,
"source": "CALCULATED",
"sourceId": "company sync triggered by vid=1",
"versions": [
{
"name": "hs_analytics_num_visits",
"value": "0",
"timestamp": 1597036442756,
"sourceId": "company sync triggered by vid=1",
"source": "CALCULATED",
"sourceVid": []
}
]
},
"linkedin_company_page": {
"value": "https://www.linkedin.com/company/hubspot",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "linkedin_company_page",
"value": "https://www.linkedin.com/company/hubspot",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"first_deal_created_date": {
"value": "1597049547389",
"timestamp": 1597049601588,
"source": "DEALS",
"sourceId": "DealRollupProperties",
"versions": [
{
"name": "first_deal_created_date",
"value": "1597049547389",
"timestamp": 1597049601588,
"sourceId": "DealRollupProperties",
"source": "DEALS",
"sourceVid": []
}
]
},
"hs_analytics_source": {
"value": "OFFLINE",
"timestamp": 1597036442756,
"source": "CALCULATED",
"sourceId": "company sync triggered by vid=1",
"versions": [
{
"name": "hs_analytics_source",
"value": "OFFLINE",
"timestamp": 1597036442756,
"sourceId": "company sync triggered by vid=1",
"source": "CALCULATED",
"sourceVid": []
}
]
},
"num_contacted_notes": {
"value": "3",
"timestamp": 1597052888565,
"source": "ENGAGEMENTS",
"sourceId": "ObjectPropertyUpdater",
"versions": [
{
"name": "num_contacted_notes",
"value": "3",
"timestamp": 1597052888565,
"sourceId": "ObjectPropertyUpdater",
"source": "ENGAGEMENTS",
"sourceVid": []
}
]
},
"annualrevenue": {
"value": "250000000",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "annualrevenue",
"value": "250000000",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"founded_year": {
"value": "2006",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "founded_year",
"value": "2006",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"num_associated_deals": {
"value": "1",
"timestamp": 1597049601588,
"source": "DEALS",
"sourceId": "DealRollupProperties",
"versions": [
{
"name": "num_associated_deals",
"value": "1",
"timestamp": 1597049601588,
"sourceId": "DealRollupProperties",
"source": "DEALS",
"sourceVid": []
}
]
},
"hs_analytics_num_page_views": {
"value": "0",
"timestamp": 1597036442756,
"source": "CALCULATED",
"sourceId": "company sync triggered by vid=1",
"versions": [
{
"name": "hs_analytics_num_page_views",
"value": "0",
"timestamp": 1597036442756,
"sourceId": "company sync triggered by vid=1",
"source": "CALCULATED",
"sourceVid": []
}
]
},
"state": {
"value": "MA",
"timestamp": 1597036440201,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "state",
"value": "MA",
"timestamp": 1597036440201,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"linkedinbio": {
"value": "HubSpot is an American developer and marketer of software products for inbound marketing, sales, and customer service.",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "linkedinbio",
"value": "HubSpot is an American developer and marketer of software products for inbound marketing, sales, and customer service.",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"hs_num_open_deals": {
"value": "1",
"timestamp": 1597049601469,
"source": "SALES",
"sourceId": "AssociationsPropertyWorker",
"versions": [
{
"name": "hs_num_open_deals",
"value": "1",
"timestamp": 1597049601469,
"sourceId": "AssociationsPropertyWorker",
"source": "SALES",
"sourceVid": []
}
]
},
"zip": {
"value": "02141",
"timestamp": 1597036440201,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "zip",
"value": "02141",
"timestamp": 1597036440201,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"notes_last_updated": {
"value": "1597051989917",
"timestamp": 1597052065685,
"source": "ENGAGEMENTS",
"sourceId": "ObjectPropertyUpdater",
"versions": [
{
"name": "notes_last_updated",
"value": "1597051989917",
"timestamp": 1597052065685,
"sourceId": "ObjectPropertyUpdater",
"source": "ENGAGEMENTS",
"sourceVid": []
}
]
},
"website": {
"value": "hubspot.com",
"timestamp": 1597036439975,
"source": "COMPANIES",
"sourceId": "FetchAssociatedCompanyIdStep",
"versions": [
{
"name": "website",
"value": "hubspot.com",
"timestamp": 1597036439975,
"sourceId": "FetchAssociatedCompanyIdStep",
"source": "COMPANIES",
"sourceVid": []
}
]
},
"address": {
"value": "25 First Street",
"timestamp": 1597036440201,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "address",
"value": "25 First Street",
"timestamp": 1597036440201,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"hs_analytics_first_timestamp": {
"value": "1597036439544",
"timestamp": 1597036442756,
"source": "CALCULATED",
"sourceId": "company sync triggered by vid=1",
"versions": [
{
"name": "hs_analytics_first_timestamp",
"value": "1597036439544",
"timestamp": 1597036442756,
"sourceId": "company sync triggered by vid=1",
"source": "CALCULATED",
"sourceVid": []
}
]
},
"first_contact_createdate": {
"value": "1597036439544",
"timestamp": 1597036441158,
"source": "CALCULATED",
"sourceId": "company sync triggered by vid=1",
"versions": [
{
"name": "first_contact_createdate",
"value": "1597036439544",
"timestamp": 1597036441158,
"sourceId": "company sync triggered by vid=1",
"source": "CALCULATED",
"sourceVid": []
}
]
},
"twitterhandle": {
"value": "HubSpot",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "twitterhandle",
"value": "HubSpot",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"hs_target_account_probability": {
"value": "0.6736696362495422",
"timestamp": 1597052067699,
"source": "SALES",
"sourceId": null,
"versions": [
{
"name": "hs_target_account_probability",
"value": "0.6736696362495422",
"timestamp": 1597052067699,
"source": "SALES",
"sourceVid": []
}
]
},
"hs_lastmodifieddate": {
"value": "1597052888859",
"timestamp": 1597052888859,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "hs_lastmodifieddate",
"value": "1597052888859",
"timestamp": 1597052888859,
"source": "CALCULATED",
"sourceVid": []
}
]
},
"hs_num_decision_makers": {
"value": "0",
"timestamp": 1597036441226,
"source": "SALES",
"sourceId": "AssociationsPropertyWorker",
"versions": [
{
"name": "hs_num_decision_makers",
"value": "0",
"timestamp": 1597036441226,
"sourceId": "AssociationsPropertyWorker",
"source": "SALES",
"sourceVid": []
}
]
},
"notes_last_contacted": {
"value": "1597051989917",
"timestamp": 1597052065685,
"source": "ENGAGEMENTS",
"sourceId": "ObjectPropertyUpdater",
"versions": [
{
"name": "notes_last_contacted",
"value": "1597051989917",
"timestamp": 1597052065685,
"sourceId": "ObjectPropertyUpdater",
"source": "ENGAGEMENTS",
"sourceVid": []
}
]
},
"phone": {
"value": "+1 888-482-7768",
"timestamp": 1597036440201,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "phone",
"value": "+1 888-482-7768",
"timestamp": 1597036440201,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"domain": {
"value": "hubspot.com",
"timestamp": 1597036439975,
"source": "COMPANIES",
"sourceId": "FetchAssociatedCompanyIdStep",
"versions": [
{
"name": "domain",
"value": "hubspot.com",
"timestamp": 1597036439975,
"sourceId": "FetchAssociatedCompanyIdStep",
"source": "COMPANIES",
"sourceVid": []
}
]
},
"hs_num_child_companies": {
"value": "0",
"timestamp": 1597036442919,
"source": "CALCULATED",
"sourceId": "RollupProperties",
"versions": [
{
"name": "hs_num_child_companies",
"value": "0",
"timestamp": 1597036442919,
"sourceId": "RollupProperties",
"source": "CALCULATED",
"sourceVid": []
}
]
},
"hs_num_contacts_with_buying_roles": {
"value": "0",
"timestamp": 1597036441226,
"source": "SALES",
"sourceId": "AssociationsPropertyWorker",
"versions": [
{
"name": "hs_num_contacts_with_buying_roles",
"value": "0",
"timestamp": 1597036441226,
"sourceId": "AssociationsPropertyWorker",
"source": "SALES",
"sourceVid": []
}
]
},
"hs_object_id": {
"value": "4294592507",
"timestamp": 1597036439975,
"source": "COMPANIES",
"sourceId": "FetchAssociatedCompanyIdStep",
"versions": [
{
"name": "hs_object_id",
"value": "4294592507",
"timestamp": 1597036439975,
"sourceId": "FetchAssociatedCompanyIdStep",
"source": "COMPANIES",
"sourceVid": []
}
]
},
"is_public": {
"value": "true",
"timestamp": 1597036440202,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "is_public",
"value": "true",
"timestamp": 1597036440202,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"name": {
"value": "<NAME>.",
"timestamp": 1597036440201,
"source": "BIDEN",
"sourceId": "BidenPropertyMappings",
"versions": [
{
"name": "name",
"value": "HubSpot, Inc.",
"timestamp": 1597036440201,
"sourceId": "BidenPropertyMappings",
"source": "BIDEN",
"sourceVid": []
}
]
},
"hs_last_logged_call_date": {
"value": "1597051989917",
"timestamp": 1597052065381,
"source": "SALES",
"sourceId": "AssociationsPropertyWorker",
"versions": [
{
"name": "hs_last_logged_call_date",
"value": "1597051989917",
"timestamp": 1597052065381,
"sourceId": "AssociationsPropertyWorker",
"source": "SALES",
"sourceVid": []
}
]
},
"hs_analytics_source_data_2": {
"value": "sample-contact",
"timestamp": 1597036442756,
"source": "CALCULATED",
"sourceId": "company sync triggered by vid=1",
"versions": [
{
"name": "hs_analytics_source_data_2",
"value": "sample-contact",
"timestamp": 1597036442756,
"sourceId": "company sync triggered by vid=1",
"source": "CALCULATED",
"sourceVid": []
}
]
},
"hs_analytics_source_data_1": {
"value": "API",
"timestamp": 1597036442756,
"source": "CALCULATED",
"sourceId": "company sync triggered by vid=1",
"versions": [
{
"name": "hs_analytics_source_data_1",
"value": "API",
"timestamp": 1597036442756,
"sourceId": "company sync triggered by vid=1",
"source": "CALCULATED",
"sourceVid": []
}
]
},
"lifecyclestage": {
"value": "opportunity",
"timestamp": 1597049601576,
"source": "DEALS",
"sourceId": "deals-lifecycle-sync",
"versions": [
{
"name": "lifecyclestage",
"value": "opportunity",
"timestamp": 1597049601576,
"sourceId": "deals-lifecycle-sync",
"source": "DEALS",
"sourceVid": []
}
]
},
"num_notes": {
"value": "3",
"timestamp": 1597052888565,
"source": "ENGAGEMENTS",
"sourceId": "ObjectPropertyUpdater",
"versions": [
{
"name": "num_notes",
"value": "3",
"timestamp": 1597052888565,
"sourceId": "ObjectPropertyUpdater",
"source": "ENGAGEMENTS",
"sourceVid": []
}
]
}
},
"additionalDomains": [],
"stateChanges": [],
"mergeAudits": []
}
const contactInfo = {
"51": {
"vid": 51,
"canonical-vid": 51,
"merged-vids": [],
"portal-id": 8247786,
"is-contact": true,
"profile-token": "<KEY>",
"profile-url": "https://app.hubspot.com/contacts/8247786/contact/51",
"properties": {
"firstname": {
"value": "Brian"
},
"associatedcompanyid": {
"value": "4294592507"
},
"lastmodifieddate": {
"value": "1597052179122"
},
"lastname": {
"value": "Halligan (Sample Contact)"
}
},
"form-submissions": [],
"identity-profiles": [
{
"vid": 51,
"saved-at-timestamp": 1597036439978,
"deleted-changed-timestamp": 0,
"identities": [
{
"type": "EMAIL",
"value": "<EMAIL>",
"timestamp": 1597036439544,
"is-primary": true
},
{
"type": "LEAD_GUID",
"value": "ca13fbc9-25e1-4837-be8c-3f3273f9c2cf",
"timestamp": 1597036439973
}
]
}
],
"merge-audits": [],
"associated-company": {
"company-id": 4294592507,
"portal-id": 8247786,
"properties": {
"country": {
"value": "United States"
},
"num_associated_contacts": {
"value": "2"
},
"city": {
"value": "Cambridge"
},
"timezone": {
"value": "America/New_York"
},
"facebook_company_page": {
"value": "https://www.facebook.com/hubspot"
},
"description": {
"value": "HubSpot is an American developer and marketer of software products for inbound marketing, sales, and customer service."
},
"createdate": {
"value": "1597036439975"
},
"web_technologies": {
"value": "unbounce;facebook_advertiser;salesforce;app_nexus;cloud_flare;piwik;dstillery;google_analytics;twitter_button;hubspot;vidyard;sentry;google_tag_manager;facebook_connect;crazy_egg;amazon__cloudfront;wistia;optimizely"
},
"total_money_raised": {
"value": "100.5M"
},
"industry": {
"value": "COMPUTER_SOFTWARE"
},
"hs_num_blockers": {
"value": "0"
},
"numberofemployees": {
"value": "5000"
},
"hs_total_deal_value": {
"value": "1200.0"
},
"hs_analytics_num_visits": {
"value": "0"
},
"linkedin_company_page": {
"value": "https://www.linkedin.com/company/hubspot"
},
"num_contacted_notes": {
"value": "3"
},
"hs_analytics_source": {
"value": "OFFLINE"
},
"first_deal_created_date": {
"value": "1597049547389"
},
"annualrevenue": {
"value": "250000000"
},
"founded_year": {
"value": "2006"
},
"num_associated_deals": {
"value": "1"
},
"hs_analytics_num_page_views": {
"value": "0"
},
"state": {
"value": "MA"
},
"linkedinbio": {
"value": "HubSpot is an American developer and marketer of software products for inbound marketing, sales, and customer service."
},
"zip": {
"value": "02141"
},
"hs_num_open_deals": {
"value": "1"
},
"notes_last_updated": {
"value": "1597051989917"
},
"website": {
"value": "hubspot.com"
},
"address": {
"value": "25 First Street"
},
"hs_analytics_first_timestamp": {
"value": "1597036439544"
},
"twitterhandle": {
"value": "HubSpot"
},
"first_contact_createdate": {
"value": "1597036439544"
},
"hs_target_account_probability": {
"value": "0.6736696362495422"
},
"hs_lastmodifieddate": {
"value": "1597052888859"
},
"phone": {
"value": "+1 888-482-7768"
},
"notes_last_contacted": {
"value": "1597051989917"
},
"hs_num_decision_makers": {
"value": "0"
},
"domain": {
"value": "hubspot.com"
},
"name": {
"value": "<NAME>."
},
"is_public": {
"value": "true"
},
"hs_object_id": {
"value": "4294592507"
},
"hs_num_contacts_with_buying_roles": {
"value": "0"
},
"hs_num_child_companies": {
"value": "0"
},
"hs_last_logged_call_date": {
"value": "1597051989917"
},
"hs_analytics_source_data_2": {
"value": "sample-contact"
},
"hs_analytics_source_data_1": {
"value": "API"
},
"lifecyclestage": {
"value": "opportunity"
},
"num_notes": {
"value": "3"
}
}
}
},
"151": {
"vid": 151,
"canonical-vid": 151,
"merged-vids": [],
"portal-id": 8247786,
"is-contact": true,
"profile-token": "<KEY>",
"profile-url": "https://app.hubspot.com/contacts/8247786/contact/151",
"properties": {
"associatedcompanyid": {
"value": "4316875486"
},
"phone": {
"value": "555-444-1122"
},
"email": {
"value": "<EMAIL>"
}
},
"form-submissions": [],
"identity-profiles": [
{
"vid": 151,
"saved-at-timestamp": 1597336347634,
"deleted-changed-timestamp": 0,
"identities": [
{
"type": "EMAIL",
"value": "<EMAIL>",
"timestamp": 1597336347576,
"is-primary": true
},
{
"type": "LEAD_GUID",
"value": "564235aa-48b8-4ab0-8a6d-4e60bb179c16",
"timestamp": 1597336347629
}
]
}
],
"merge-audits": [],
"associated-company": {
"company-id": 4316875486,
"portal-id": 8247786,
"properties": {
"country": {
"value": "United States"
},
"num_associated_contacts": {
"value": "1"
},
"city": {
"value": "Hoffman Estates"
},
"timezone": {
"value": "America/Chicago"
},
"facebook_company_page": {
"value": "https://facebook.com/cdkglobal"
},
"description": {
"value": "CDK Global provides auto dealer software as well as solutions for truck, motorcycle, marine and RV dealers throughout North America and beyond."
},
"createdate": {
"value": "1597336347243"
},
"web_technologies": {
"value": "youtube;new_relic;qualtrics;pardot;nginx;drupal;google_tag_manager;add_to_any;google_analytics;cloud_flare"
},
"industry": {
"value": "COMPUTER_SOFTWARE"
},
"hs_num_blockers": {
"value": "0"
},
"numberofemployees": {
"value": "10000"
},
"hs_total_deal_value": {
"value": "100000.0"
},
"hs_analytics_num_visits": {
"value": "0"
},
"linkedin_company_page": {
"value": "https://www.linkedin.com/company/cdkglobal"
},
"hs_analytics_source": {
"value": "OFFLINE"
},
"first_deal_created_date": {
"value": "1597348961368"
},
"annualrevenue": {
"value": "250000000"
},
"founded_year": {
"value": "1972"
},
"num_associated_deals": {
"value": "1"
},
"hs_analytics_num_page_views": {
"value": "0"
},
"state": {
"value": "IL"
},
"linkedinbio": {
"value": "CDK Global provides auto dealer software as well as solutions for truck, motorcycle, marine and RV dealers throughout North America and beyond."
},
"zip": {
"value": "60169"
},
"hs_num_open_deals": {
"value": "1"
},
"website": {
"value": "cdk.com"
},
"address": {
"value": "1950 Hassell Road"
},
"hs_analytics_first_timestamp": {
"value": "1597336347432"
},
"twitterhandle": {
"value": "CDKGlobal"
},
"first_contact_createdate": {
"value": "1597336347576"
},
"hs_target_account_probability": {
"value": "0.46257445216178894"
},
"hs_lastmodifieddate": {
"value": "1597349050694"
},
"phone": {
"value": "+1 847-397-1700"
},
"hs_num_decision_makers": {
"value": "0"
},
"domain": {
"value": "cdk.com"
},
"name": {
"value": "<NAME>"
},
"is_public": {
"value": "true"
},
"hs_object_id": {
"value": "4316875486"
},
"hs_num_contacts_with_buying_roles": {
"value": "0"
},
"hs_num_child_companies": {
"value": "0"
},
"hs_analytics_source_data_2": {
"value": "CRM_UI"
},
"hs_analytics_source_data_1": {
"value": "CONTACTS"
},
"lifecyclestage": {
"value": "opportunity"
}
}
}
}
}
|
macaurther/DOCUSA
|
Assets/Python/Screens/PlatyBuilder/WBCorporationScreen.py
|
<reponame>macaurther/DOCUSA
from CvPythonExtensions import *
import CvUtil
import ScreenInput
import CvScreenEnums
import WBGameDataScreen
import WBReligionScreen
import WBPlayerScreen
import WBTeamScreen
import WBCityEditScreen
import WBInfoScreen
import CvPlatyBuilderScreen
import WBStoredDataScreen
gc = CyGlobalContext()
from CvPlatyBuilderSettings import *
bHeadquarter = False
lCities = []
class WBCorporationScreen:
def __init__(self):
self.iTable_Y = 80
def interfaceScreen(self, iPlayerX):
screen = CyGInterfaceScreen("WBCorporationScreen", CvScreenEnums.WB_CORPORATION)
global iSelectedPlayer
iSelectedPlayer = iPlayerX
screen.setRenderInterfaceOnly(True)
screen.addPanel("MainBG", u"", u"", True, False, -10, -10, screen.getXResolution() + 20, screen.getYResolution() + 20, PanelStyles.PANEL_STYLE_MAIN )
screen.showScreen(PopupStates.POPUPSTATE_IMMEDIATE, False)
screen.setText("WBCorporationExit", "Background", "<font=4>" + CyTranslator().getText("TXT_KEY_PEDIA_SCREEN_EXIT", ()).upper() + "</font>", CvUtil.FONT_RIGHT_JUSTIFY, screen.getXResolution() - 30, screen.getYResolution() - 42, -0.1, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_CLOSE_SCREEN, -1, -1 )
screen.setLabel("CorporationHeader", "Background", "<font=4b>" + CyTranslator().getText("TXT_KEY_CONCEPT_CORPORATIONS", ()) + "</font>", CvUtil.FONT_CENTER_JUSTIFY, screen.getXResolution()/2, 20, -0.1, FontTypes.GAME_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)
screen.setLabel("HeadquarterHeader", "Background", "<font=3b>" + CyTranslator().getText("TXT_KEY_CORPORATION_HEADQUARTERS", ()) + "</font>", CvUtil.FONT_CENTER_JUSTIFY, screen.getXResolution()/8, self.iTable_Y - 30, -0.1, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)
iWidth = screen.getXResolution()/4 - 40
screen.addDropDownBoxGFC("CurrentPage", 20, screen.getYResolution() - 42, iWidth, WidgetTypes.WIDGET_GENERAL, -1, -1, FontTypes.GAME_FONT)
screen.addPullDownString("CurrentPage", CyTranslator().getText("TXT_KEY_WB_PLAYER_DATA", ()), 0, 0, False)
screen.addPullDownString("CurrentPage", CyTranslator().getText("TXT_KEY_WB_TEAM_DATA", ()), 1, 1, False)
screen.addPullDownString("CurrentPage", CyTranslator().getText("TXT_KEY_PEDIA_CATEGORY_RELIGION", ()), 8, 8, False)
screen.addPullDownString("CurrentPage", CyTranslator().getText("TXT_KEY_CONCEPT_CORPORATIONS", ()), 9, 9, True)
screen.addPullDownString("CurrentPage", CyTranslator().getText("TXT_KEY_PITBOSS_GAME_OPTIONS", ()), 10, 10, False)
screen.addPullDownString("CurrentPage", CyTranslator().getText("TXT_KEY_INFO_SCREEN", ()), 11, 11, False)
screen.addPullDownString("CurrentPage", CyTranslator().getText("TXT_KEY_WB_STOREDDATA", ()), 12, 12, False)
screen.addDropDownBoxGFC("OwnerType", screen.getXResolution()/4, self.iTable_Y - 60, 150, WidgetTypes.WIDGET_GENERAL, -1, -1, FontTypes.GAME_FONT)
screen.addPullDownString("OwnerType", CyTranslator().getText("TXT_KEY_WB_CITY_ALL", ()), 0, 0, 0 == iOwnerType)
screen.addPullDownString("OwnerType", CyTranslator().getText("TXT_KEY_PITBOSS_TEAM", ()), 2, 2, 2 == iOwnerType)
screen.addPullDownString("OwnerType", CyTranslator().getText("TXT_KEY_MAIN_MENU_PLAYER", ()), 1, 1, 1 == iOwnerType)
screen.addDropDownBoxGFC("CurrentPlayer", screen.getXResolution()/4, self.iTable_Y - 30, 150, WidgetTypes.WIDGET_GENERAL, -1, -1, FontTypes.GAME_FONT)
for i in xrange(gc.getMAX_PLAYERS()):
pPlayerX = gc.getPlayer(i)
if pPlayerX.isEverAlive():
sText = pPlayerX.getName()
if not pPlayerX.isAlive():
sText = "*" + sText
if pPlayerX.isTurnActive():
sText = "[" + sText + "]"
screen.addPullDownString("CurrentPlayer", sText, i, i, i == iSelectedPlayer)
sText = "<font=3b>" + CyTranslator().getText("TXT_KEY_CORPORATION_HEADQUARTERS", ()) + "</font>"
sColor = CyTranslator().getText("[COLOR_WARNING_TEXT]", ())
if bHeadquarter:
sColor = CyTranslator().getText("[COLOR_POSITIVE_TEXT]", ())
screen.setText("SetHeadquarter", "Background", sColor + sText + "</color>", CvUtil.FONT_RIGHT_JUSTIFY, screen.getXResolution() - 20, self.iTable_Y - 30, -0.1, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)
self.placeHeadquarter()
self.sortCities()
def sortCities(self):
global lCities
lCities = []
iSelectedTeam = gc.getPlayer(iSelectedPlayer).getTeam()
for iPlayerX in xrange(gc.getMAX_PLAYERS()):
pPlayerX = gc.getPlayer(iPlayerX)
if iOwnerType == 1 and iPlayerX != iSelectedPlayer: continue
if iOwnerType == 2 and pPlayerX.getTeam() != iSelectedTeam: continue
(loopCity, iter) = pPlayerX.firstCity(False)
while(loopCity):
lCities.append([loopCity, iPlayerX])
(loopCity, iter) = pPlayerX.nextCity(iter, False)
self.placeCityTable()
def placeCityTable(self):
screen = CyGInterfaceScreen("WBCorporationScreen", CvScreenEnums.WB_CORPORATION)
iX = screen.getXResolution()/4
iY = self.iTable_Y
iWidth = screen.getXResolution() * 3/4 - 20
iHeight = (screen.getYResolution() - iY - 100) / 24 * 24 + 2
screen.addTableControlGFC("WBAllCorporations", 1 + gc.getNumCorporationInfos(), iX, iY, iWidth, 50, False, True, 24, 24, TableStyles.TABLE_STYLE_STANDARD)
screen.setTableColumnHeader("WBAllCorporations", 0, "", 150)
for i in xrange(2):
screen.appendTableRow("WBAllCorporations")
sText = CyTranslator().getText("TXT_KEY_WB_CITY_ALL", ())
screen.setTableText("WBAllCorporations", 0, 0, "<font=3b>" + sText + " (+)</font>", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_CENTER_JUSTIFY)
screen.setTableText("WBAllCorporations", 0, 1, "<font=3b>" + sText + " (-)</font>", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_CENTER_JUSTIFY)
for i in xrange(gc.getNumCorporationInfos()):
sText = u"%c" %(gc.getCorporationInfo(i).getChar())
screen.setTableColumnHeader("WBAllCorporations", i + 1, "", (iWidth - 150) / gc.getNumCorporationInfos())
screen.setTableText("WBAllCorporations", i + 1, 0, "<font=4>" + sText + "</font>", "", WidgetTypes.WIDGET_PYTHON, 6782, i, CvUtil.FONT_CENTER_JUSTIFY)
screen.setTableText("WBAllCorporations", i + 1, 1, "<font=4>" + sText + "</font>", "", WidgetTypes.WIDGET_PYTHON, 8201, i, CvUtil.FONT_CENTER_JUSTIFY)
screen.addTableControlGFC("WBCityCorporations", 3 + gc.getNumCorporationInfos(), iX, iY + 60, iWidth, iHeight, False, True, 24, 24, TableStyles.TABLE_STYLE_STANDARD)
screen.setTableColumnHeader("WBCityCorporations", 0, "", 24)
screen.setTableColumnHeader("WBCityCorporations", 1, "", 24)
screen.setTableColumnHeader("WBCityCorporations", 2, "", 102)
for i in xrange(gc.getNumCorporationInfos()):
screen.setTableColumnHeader("WBCityCorporations", i + 3, "", (iWidth - 150) / gc.getNumCorporationInfos())
for (loopCity, iPlayerX) in lCities:
pPlayerX = gc.getPlayer(iPlayerX)
iLeader = pPlayerX.getLeaderType()
iCiv = pPlayerX.getCivilizationType()
sColor = u"<color=%d,%d,%d,%d>" %(pPlayerX.getPlayerTextColorR(), pPlayerX.getPlayerTextColorG(), pPlayerX.getPlayerTextColorB(), pPlayerX.getPlayerTextColorA())
iRow = screen.appendTableRow("WBCityCorporations")
screen.setTableText("WBCityCorporations", 0, iRow, "", gc.getCivilizationInfo(iCiv).getButton(), WidgetTypes.WIDGET_PYTHON, 7872, iCiv, CvUtil.FONT_CENTER_JUSTIFY)
screen.setTableText("WBCityCorporations", 1, iRow, "", gc.getLeaderHeadInfo(iLeader).getButton(), WidgetTypes.WIDGET_PYTHON, 7876, iLeader, CvUtil.FONT_CENTER_JUSTIFY)
screen.setTableText("WBCityCorporations", 2, iRow, "<font=3>" + sColor + loopCity.getName() + "</color></font>", "", WidgetTypes.WIDGET_PYTHON, 7200 + iPlayerX, loopCity.getID(), CvUtil.FONT_LEFT_JUSTIFY)
for i in xrange(gc.getNumCorporationInfos()):
sText = " "
if loopCity.isHasCorporation(i):
sText = u"%c" %(gc.getCorporationInfo(i).getChar())
if loopCity.isHeadquartersByType(i):
sText = u"%c" %(gc.getCorporationInfo(i).getHeadquarterChar())
screen.setTableText("WBCityCorporations", i + 3, iRow, "<font=4>" + sText + "</font>", "", WidgetTypes.WIDGET_PYTHON, 8201, i, CvUtil.FONT_CENTER_JUSTIFY)
def placeHeadquarter(self):
screen = CyGInterfaceScreen("WBCorporationScreen", CvScreenEnums.WB_CORPORATION)
iX = 20
iY = self.iTable_Y
iWidth = screen.getXResolution()/4 - 40
iHeight = (screen.getYResolution() - iY - 40) / 24 * 24 + 2
screen.addTableControlGFC("WBHeadquarter", 3, iX, iY, iWidth, iHeight, False, False, 24, 24, TableStyles.TABLE_STYLE_STANDARD)
screen.setTableColumnHeader("WBHeadquarter", 0, "", 24)
screen.setTableColumnHeader("WBHeadquarter", 1, "", 24)
screen.setTableColumnHeader("WBHeadquarter", 2, "", iWidth - 48)
for i in xrange(gc.getNumCorporationInfos()):
iRow = screen.appendTableRow("WBHeadquarter")
screen.setTableText("WBHeadquarter", 0, iRow, "", gc.getCorporationInfo(i).getButton(), WidgetTypes.WIDGET_PYTHON, 8201, i, CvUtil.FONT_LEFT_JUSTIFY)
pHeadquarter = CyGame().getHeadquarters(i)
if not pHeadquarter.isNone():
iPlayerX = pHeadquarter.getOwner()
pPlayerX = gc.getPlayer(iPlayerX)
sColor = u"<color=%d,%d,%d,%d>" %(pPlayerX.getPlayerTextColorR(), pPlayerX.getPlayerTextColorG(), pPlayerX.getPlayerTextColorB(), pPlayerX.getPlayerTextColorA())
iLeader = pPlayerX.getLeaderType()
screen.setTableText("WBHeadquarter", 1, iRow, "", gc.getLeaderHeadInfo(iLeader).getButton(), WidgetTypes.WIDGET_PYTHON, 7876, iPlayerX * 10000 + iLeader, CvUtil.FONT_LEFT_JUSTIFY)
screen.setTableText("WBHeadquarter", 2, iRow, "<font=3>" + sColor + pHeadquarter.getName() + "</color></font>", gc.getCivilizationInfo(pHeadquarter.getCivilizationType()).getButton(), WidgetTypes.WIDGET_PYTHON, 7200 + iPlayerX, pHeadquarter.getID(), CvUtil.FONT_LEFT_JUSTIFY)
def handleInput(self, inputClass):
screen = CyGInterfaceScreen("WBCorporationScreen", CvScreenEnums.WB_CORPORATION)
global iSelectedPlayer
global bHeadquarter
global iOwnerType
if inputClass.getButtonType() == WidgetTypes.WIDGET_PYTHON:
if inputClass.getData1() > 7199 and inputClass.getData1() < 7300:
iCityID = inputClass.getData2()
iPlayerX = inputClass.getData1() - 7200
WBCityEditScreen.WBCityEditScreen(CvPlatyBuilderScreen.CvWorldBuilderScreen()).interfaceScreen(gc.getPlayer(iPlayerX).getCity(iCityID))
elif inputClass.getData1() == 7876 or inputClass.getData1() == 7872:
iPlayerX = inputClass.getData2() /10000
WBPlayerScreen.WBPlayerScreen().interfaceScreen(iPlayerX)
if inputClass.getFunctionName() == "CurrentPage":
iIndex = screen.getPullDownData("CurrentPage", screen.getSelectedPullDownID("CurrentPage"))
if iIndex == 0:
WBPlayerScreen.WBPlayerScreen().interfaceScreen(iSelectedPlayer)
elif iIndex == 1:
WBTeamScreen.WBTeamScreen().interfaceScreen(gc.getPlayer(iSelectedPlayer).getTeam())
elif iIndex == 8:
WBReligionScreen.WBReligionScreen().interfaceScreen(iSelectedPlayer)
elif iIndex == 10:
WBGameDataScreen.WBGameDataScreen(CvPlatyBuilderScreen.CvWorldBuilderScreen()).interfaceScreen()
elif iIndex == 11:
WBInfoScreen.WBInfoScreen().interfaceScreen(iSelectedPlayer)
elif iIndex == 12:
WBStoredDataScreen.WBStoredDataScreen(CvPlatyBuilderScreen.CvWorldBuilderScreen()).interfaceScreen()
elif inputClass.getFunctionName() == "OwnerType":
iOwnerType = screen.getPullDownData("OwnerType", screen.getSelectedPullDownID("OwnerType"))
self.sortCities()
elif inputClass.getFunctionName() == "CurrentPlayer":
iSelectedPlayer = screen.getPullDownData("CurrentPlayer", screen.getSelectedPullDownID("CurrentPlayer"))
self.interfaceScreen(iSelectedPlayer)
elif inputClass.getFunctionName() == "WBCityCorporations":
if inputClass.getData1() == 8201:
pCity = lCities[inputClass.getData()][0]
if bHeadquarter:
self.editHeadquarter(inputClass.getData2(), pCity)
else:
self.editCorporation(inputClass.getData2(), pCity, 2)
self.placeCityTable()
elif inputClass.getFunctionName() == "WBAllCorporations":
if inputClass.getButtonType() == WidgetTypes.WIDGET_PYTHON:
for (loopCity, iPlayerX) in lCities:
self.editCorporation(inputClass.getData2(), loopCity, inputClass.getData1() == 6782)
self.placeCityTable()
elif inputClass.getFunctionName() == "SetHeadquarter":
bHeadquarter = not bHeadquarter
sText = "<font=3b>" + CyTranslator().getText("TXT_KEY_CORPORATION_HEADQUARTERS", ()) + "</font>"
sColor = CyTranslator().getText("[COLOR_WARNING_TEXT]", ())
if bHeadquarter:
sColor = CyTranslator().getText("[COLOR_POSITIVE_TEXT]", ())
screen.modifyString("SetHeadquarter", sColor + sText + "</color>", 0)
return 1
def editHeadquarter(self, item, pCity):
if pCity.isHeadquartersByType(item):
CyGame().clearHeadquarters(item)
else:
CyGame().setHeadquarters(item, pCity, False)
self.placeHeadquarter()
def editCorporation(self, item, pCity, iType):
if iType == 2:
iType = not pCity.isHasCorporation(item)
if not iType and pCity.isHeadquartersByType(item):
CyGame().clearHeadquarters(item)
self.placeHeadquarter()
pCity.setHasCorporation(item, iType, False, False)
def update(self, fDelta):
return 1
|
mhiley/IDV
|
src/ucar/visad/display/XAxisScalarMap.java
|
/*
* Copyright 1997-2015 Unidata Program Center/University Corporation for
* Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
* <EMAIL>.
*
* This library 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.1 of the License, or (at
* your option) any later version.
*
* This library 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; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package ucar.visad.display;
import visad.*;
import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeEvent;
import java.rmi.RemoteException;
import javax.media.j3d.*;
import javax.vecmath.Vector3d;
/**
* Provides support for adapting ScalarMap-s to {@link visad.Display#XAxis}.
*
* <p>Instances of this class have the the JavaBean properties of the
* superclass.
*
* @author <NAME>
* @version $Revision: 1.9 $
*/
public final class XAxisScalarMap extends AxisScalarMap {
/**
* Constructs.
*
* @param realType The type of data to be mapped to the X-axis.
* @param display The adapted, VisAD display for rendering.
* @throws VisADException VisAD failure.
* @throws RemoteException Java RMI failure.
*/
public XAxisScalarMap(RealType realType, DisplayAdapter display)
throws VisADException, RemoteException {
super(realType, Display.XAxis, display);
}
/**
* Translates the axis values.
*
* @param amount The amount to translate the axis.
* @param transform The transformation to be translated.
*/
protected void translate(double amount, AffineTransform transform) {
transform.translate(amount, 0.0);
}
/**
* Returns a new, 3-D, translation vector.
*
* @param amount The amount to translate the axis.
* @return Vector3D with the x translation amount
*/
protected Vector3d new3DTranslationVector(double amount) {
return new Vector3d(amount, 0.0, 0.0);
}
/**
* Scales the axis values.
*
* @param amount The amount to scale the axis by.
* @param transform The transformation to be scaled.
*/
protected void scale(double amount, AffineTransform transform) {
transform.scale(amount, 1.0);
}
/**
* Scales an array of values by a given amount
*
* @param values The array of values to be scaled.
* @param amount The amount to scale the values.
*/
protected void scale(double[] values, double amount) {
values[0] *= amount;
}
}
|
jpacsai/GoogleUdacity
|
ChallengePhase/JavaScript/StudentPractice/18_ArrayMirrorCheck.js
|
/*
Write a function that takes an array as argument, and returns true or false depending on the following
Returns true if the first half of the array is containing the same elements present in the last half,
and false if it does not
If the array contains odd number elements ,the function returns true if the two parts around the
middle element contain the same elements
Elements in the two parts are not necessary to be in the same order
For example
check([1,4,6,8,8,6,1,4]); // true
check(["a","b","d","g","f","b","g","d","a"]) // true
check(["a","b","d","g","f","b","g","f","a"]);// false
check([10,20,30,40,10,20,50]) // false
*/
function check(arr) {
var middle = Math.floor(arr.length/2);
return arr.slice(0,middle).join("") === arr.slice( - middle).sort().join("");
}
|
nowkoai/test
|
ee/lib/ee/gitlab/background_migration/backfill_iteration_cadence_id_for_boards.rb
|
<gh_stars>1-10
# frozen_string_literal: true
module EE
module Gitlab
module BackgroundMigration
# class that will populate issue boards with iteration cadence id for boards scopped to current iteration
module BackfillIterationCadenceIdForBoards
BATCH_SIZE = 100
class MigrationBoard < ApplicationRecord
include EachBatch
self.table_name = 'boards'
end
class MigrationGroup < ActiveRecord::Base
self.inheritance_column = :_type_disabled
self.table_name = 'namespaces'
end
class MigrationProject < ActiveRecord::Base
self.table_name = 'projects'
end
class MigrationCadence < ApplicationRecord
self.table_name = 'iterations_cadences'
end
def perform(board_type, method, start_id, end_id)
if method == "up"
back_fill_group_boards(start_id, end_id) if board_type == 'group'
back_fill_project_boards(start_id, end_id) if board_type == 'project'
else
MigrationBoard.where.not(iteration_cadence_id: nil).where(id: start_id..end_id).each_batch(of: BATCH_SIZE) do |batch|
batch.update_all(iteration_cadence_id: nil)
end
end
end
private
def bulk_update(cadences_sql)
MigrationBoard.connection.exec_query(<<~SQL)
UPDATE boards SET
iteration_id = CASE
WHEN boards_cadences.first_cadence_id IS NULL THEN NULL
ELSE boards.iteration_id
END,
iteration_cadence_id = boards_cadences.first_cadence_id
FROM #{cadences_sql}
WHERE boards.id = boards_cadences.board_id
SQL
end
def back_fill_group_boards(start_id, end_id)
boards_relation(start_id, end_id).where.not(group_id: nil).each_batch(of: BATCH_SIZE) do |batch|
range = batch.pluck(Arel.sql('MIN(id)'), Arel.sql('MAX(id)')).first
sql = <<~SQL
(
SELECT
boards.id AS board_id,
(SELECT id FROM iterations_cadences WHERE group_id = ANY(traversal_ids) ORDER BY iterations_cadences.id LIMIT 1) AS first_cadence_id
FROM boards
INNER JOIN namespaces ON boards.group_id = namespaces.id
WHERE boards.id BETWEEN #{range.first} AND #{range.last} AND boards.group_id IS NOT NULL AND iteration_id = -4
ORDER BY first_cadence_id NULLS FIRST
) AS boards_cadences
SQL
bulk_update(sql)
end
end
def back_fill_project_boards(start_id, end_id)
boards_relation(start_id, end_id).where.not(project_id: nil).each_batch(of: BATCH_SIZE) do |batch|
range = batch.pluck(Arel.sql('MIN(id)'), Arel.sql('MAX(id)')).first
sql = <<~SQL
(
SELECT
boards.id AS board_id,
(SELECT id FROM iterations_cadences WHERE group_id = ANY(traversal_ids) ORDER BY iterations_cadences.id LIMIT 1) AS first_cadence_id
FROM boards
INNER JOIN projects ON boards.project_id = projects.id
INNER JOIN namespaces ON projects.namespace_id = namespaces.id
WHERE boards.id BETWEEN #{range.first} AND #{range.last} AND boards.project_id IS NOT NULL AND iteration_id = -4
ORDER BY first_cadence_id NULLS FIRST
) AS boards_cadences
SQL
bulk_update(sql)
end
end
def build_board_cadence_data(group_board_pairs)
board_cadence_data = []
group_board_pairs.each do |pair|
cadence = MigrationCadence.where(group_id: MigrationGroup.where(id: pair.last).select('unnest(namespaces.traversal_ids) AS ids')).first
board_cadence_data << if cadence.present?
[pair.first, cadence.id, -4]
else
[pair.first, Arel::Nodes::SqlLiteral.new("NULL"), Arel::Nodes::SqlLiteral.new("NULL")]
end
end
board_cadence_data
end
def boards_relation(start_id, end_id)
MigrationBoard.where(iteration_id: -4).where(iteration_cadence_id: nil).where(id: start_id..end_id)
end
end
end
end
end
|
hiteshbedre/gluecodium
|
gluecodium/src/test/resources/smoke/external_types/output/cbridge/src/smoke/cbridge_Enums.cpp
|
//
//
#include "cbridge/include/smoke/cbridge_Enums.h"
#include "cbridge_internal/include/BaseHandleImpl.h"
#include "cbridge_internal/include/TypeInitRepository.h"
#include "cbridge_internal/include/WrapperCache.h"
#include "foo/Bar.h"
#include "smoke/Enums.h"
#include <memory>
#include <new>
void smoke_Enums_release_handle(_baseRef handle) {
delete get_pointer<::std::shared_ptr< ::smoke::Enums >>(handle);
}
_baseRef smoke_Enums_copy_handle(_baseRef handle) {
return handle
? reinterpret_cast<_baseRef>(checked_pointer_copy(*get_pointer<::std::shared_ptr< ::smoke::Enums >>(handle)))
: 0;
}
const void* smoke_Enums_get_swift_object_from_wrapper_cache(_baseRef handle) {
return handle
? ::gluecodium::get_wrapper_cache().get_cached_wrapper(get_pointer<::std::shared_ptr< ::smoke::Enums >>(handle)->get())
: nullptr;
}
void smoke_Enums_cache_swift_object_wrapper(_baseRef handle, const void* swift_pointer) {
if (!handle) return;
::gluecodium::get_wrapper_cache().cache_wrapper(get_pointer<::std::shared_ptr< ::smoke::Enums >>(handle)->get(), swift_pointer);
}
void smoke_Enums_remove_swift_object_from_wrapper_cache(_baseRef handle) {
if (!::gluecodium::WrapperCache::is_alive) return;
::gluecodium::get_wrapper_cache().remove_cached_wrapper(get_pointer<::std::shared_ptr< ::smoke::Enums >>(handle)->get());
}
void smoke_Enums_methodWithExternalEnum(smoke_Enums_ExternalEnum input) {
return ::smoke::Enums::method_with_external_enum(static_cast<::smoke::Enums::External_Enum>(input));
}
|
jsockchain/payman
|
internal/notifier/notifier_test.go
|
package notifier
import (
"testing"
"github.com/goat-systems/go-tezos/v3/rpc"
"github.com/goat-systems/tzpay/v3/internal/test"
"github.com/stretchr/testify/assert"
)
func Test_isEndorsementSuccessful(t *testing.T) {
m := MissedOpportunityNotifier{
baker: "some_baker",
}
ok := m.isEndorsementSuccessful(&rpc.Block{
Operations: [][]rpc.Operations{
{
{
Contents: rpc.Contents{
{
Metadata: &rpc.ContentsHelperMetadata{
Delegate: "some_baker",
},
},
},
},
},
},
})
assert.Equal(t, true, ok)
ok = m.isEndorsementSuccessful(&rpc.Block{
Operations: [][]rpc.Operations{
{
{
Contents: rpc.Contents{
{
Metadata: &rpc.ContentsHelperMetadata{
Delegate: "some_other_baker",
},
},
},
},
},
},
})
assert.Equal(t, false, ok)
}
func Test_isBakeSuccessful(t *testing.T) {
m := MissedOpportunityNotifier{
baker: "some_baker",
}
ok := m.isBakeSuccessful(&rpc.Block{
Metadata: rpc.Metadata{
Baker: "some_baker",
},
})
assert.Equal(t, true, ok)
ok = m.isBakeSuccessful(&rpc.Block{
Metadata: rpc.Metadata{
Baker: "some_other_baker",
},
})
assert.Equal(t, false, ok)
}
func Test_getRights(t *testing.T) {
type input struct {
m MissedOpportunityNotifier
}
type want struct {
err bool
errContains string
erights *rpc.EndorsingRights
brights *rpc.BakingRights
}
cases := []struct {
name string
input input
want want
}{
{
"is successful",
input{
MissedOpportunityNotifier{
rpcClient: &test.RPCMock{},
},
},
want{
false,
"",
&rpc.EndorsingRights{
{
Level: 100,
Delegate: "some_delegate",
},
},
&rpc.BakingRights{
{
Level: 100,
Delegate: "some_delegate",
},
},
},
},
{
"handles failure to get endorsing rights",
input{
MissedOpportunityNotifier{
rpcClient: &test.RPCMock{
EndorsingRightsErr: true,
},
},
},
want{
true,
"failed to get endorsing rights",
&rpc.EndorsingRights{},
&rpc.BakingRights{},
},
},
{
"handles failure to get baking rights",
input{
MissedOpportunityNotifier{
rpcClient: &test.RPCMock{
BakingRightsErr: true,
},
},
},
want{
true,
"failed to get baking rights",
&rpc.EndorsingRights{},
&rpc.BakingRights{},
},
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
brights, erights, err := tt.input.m.getRights(0)
test.CheckErr(t, tt.want.err, tt.want.errContains, err)
assert.Equal(t, tt.want.erights, erights)
assert.Equal(t, tt.want.brights, brights)
})
}
}
func Test_notify(t *testing.T) {
type input struct {
notifier ClientIFace
}
type want struct {
err bool
errContains string
}
cases := []struct {
name string
input input
want want
}{
{
"handles notifier failure",
input{
notifier: &MockClient{
WantSendErr: true,
},
},
want{
true,
"failed to send message",
},
},
{
"is successful",
input{
notifier: &MockClient{},
},
want{
false,
"",
},
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
notifier := MissedOpportunityNotifier{
notifiers: []ClientIFace{
tt.input.notifier,
},
}
err := notifier.notify("bogus message")
test.CheckErr(t, tt.want.err, tt.want.errContains, err)
})
}
}
|
Relluem94s/RelluLib
|
src/main/java/de/relluem94/rellulib/threads/ThreadWorker.java
|
<reponame>Relluem94s/RelluLib
package de.relluem94.rellulib.threads;
import de.relluem94.rellulib.utils.LogUtils;
public class ThreadWorker extends ThreadSleeper implements Runnable {
private final Thread worker;
public ThreadWorker(int... priority) {
worker = new Thread(this);
if (priority.length != 0) {
worker.setPriority(priority[0]);
} else {
worker.setPriority(Thread.NORM_PRIORITY);
}
}
@Override
public void run() {
LogUtils.warning("Please Override this Method!");
}
public void start() {
LogUtils.info("[" + worker.getName() + "] started with priority " + worker.getPriority());
worker.start();
}
public Thread getThread() {
return worker;
}
}
|
jsz0913/rpg_dvs_evo_open
|
dvs_mapping/test/test_depth_vector.cpp
|
#include <aslam/common/entrypoint.h>
#include <gtest/gtest.h>
#include <dvs_depth_from_defocus/depth_vector.hpp>
using namespace depth_from_defocus;
TEST(DepthVectorTest, LinearDepth) {
size_t num_depth_cells = 5;
evo_utils::geometry::Depth min_depth = 1.0;
evo_utils::geometry::Depth max_depth = 5.0;
DepthVector depth_vec(min_depth, max_depth, num_depth_cells);
EXPECT_NEAR(depth_vec.cellIndexToDepth(0), 1.0, 1e-4);
EXPECT_NEAR(depth_vec.cellIndexToDepth(1), 2.0, 1e-4);
EXPECT_NEAR(depth_vec.cellIndexToDepth(2), 3.0, 1e-4);
EXPECT_NEAR(depth_vec.cellIndexToDepth(3), 4.0, 1e-4);
EXPECT_NEAR(depth_vec.cellIndexToDepth(4), 5.0, 1e-4);
}
TEST(DepthVectorTest, ForwardBackward) {
size_t num_tests = 5;
size_t num_depth_cells = 10;
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_real_distribution<double> distr(1.0, 50.0);
// depth
for (size_t n = 0; n < num_tests; ++n) {
evo_utils::geometry::Depth min_depth = distr(generator);
evo_utils::geometry::Depth max_depth = distr(generator);
DepthVector depth_vector(min_depth, max_depth, num_depth_cells);
for (size_t i = 0; i < depth_vector.size(); ++i) {
const evo_utils::geometry::Depth d_i =
depth_vector.cellIndexToDepth(i);
const size_t rec_i = depth_vector.depthToCellIndex(d_i);
EXPECT_EQ(i, rec_i) << "Forward-Backward index mismatch";
}
}
}
|
rexlManu/Open-Cloud
|
Open-Core/src/main/java/de/tammo/cloud/core/setup/requests/ListRequest.java
|
/*
* Copyright (c) 2018. File created by Tammo
*/
package de.tammo.cloud.core.setup.requests;
import de.tammo.cloud.core.logging.Logger;
import jline.console.ConsoleReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.function.Consumer;
public class ListRequest {
public void request(final Logger logger, final String request, final String[] responses, final ConsoleReader reader, final Consumer<String> accept) throws IOException {
logger.info(request + " " + this.getResponseString(responses));
final String line = reader.readLine();
if (this.contains(responses, line)) {
accept.accept(line.toUpperCase());
} else {
this.request(logger, request, responses, reader, accept);
}
}
private String getResponseString(final String[] responses) {
final StringBuilder responseBuilder = new StringBuilder();
for (final String response : responses) {
responseBuilder.append((responseBuilder.length() == 0) ? response : ", " + response);
}
return responseBuilder.toString();
}
private boolean contains(final String[] responses, final String response) {
return Arrays.stream(responses).anyMatch(s -> s.equalsIgnoreCase(response));
}
}
|
maxvankessel/zephyr
|
samples/subsys/mgmt/updatehub/src/main.c
|
/*
* Copyright (c) 2018-2020 O.S.Systems
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <updatehub.h>
#include <net/net_mgmt.h>
#include <net/net_event.h>
#include <net/net_conn_mgr.h>
#include <net/wifi_mgmt.h>
#include <dfu/mcuboot.h>
#if defined(CONFIG_UPDATEHUB_DTLS)
#include <net/tls_credentials.h>
#include "c_certificates.h"
#endif
#include <logging/log.h>
LOG_MODULE_REGISTER(main);
#define EVENT_MASK (NET_EVENT_L4_CONNECTED | \
NET_EVENT_L4_DISCONNECTED)
static struct net_mgmt_event_callback mgmt_cb;
void start_updatehub(void)
{
#if defined(CONFIG_UPDATEHUB_SAMPLE_POLLING)
LOG_INF("Starting UpdateHub polling mode");
updatehub_autohandler();
#endif
#if defined(CONFIG_UPDATEHUB_SAMPLE_MANUAL)
LOG_INF("Starting UpdateHub manual mode");
switch (updatehub_probe()) {
case UPDATEHUB_HAS_UPDATE:
switch (updatehub_update()) {
case UPDATEHUB_OK:
ret = 0;
sys_reboot(SYS_REBOOT_WARM);
break;
default:
LOG_ERR("Error installing update.");
break;
}
case UPDATEHUB_NO_UPDATE:
LOG_INF("No update found");
ret = 0;
break;
default:
LOG_ERR("Invalid response");
break;
}
#endif
}
static void event_handler(struct net_mgmt_event_callback *cb,
uint32_t mgmt_event, struct net_if *iface)
{
if ((mgmt_event & EVENT_MASK) != mgmt_event) {
return;
}
if (mgmt_event == NET_EVENT_L4_CONNECTED) {
LOG_INF("Network connected");
start_updatehub();
return;
}
if (mgmt_event == NET_EVENT_L4_DISCONNECTED) {
LOG_INF("Network disconnected");
return;
}
}
void main(void)
{
int ret;
LOG_INF("UpdateHub sample app started");
#if defined(CONFIG_UPDATEHUB_DTLS)
if (tls_credential_add(CA_CERTIFICATE_TAG,
TLS_CREDENTIAL_SERVER_CERTIFICATE,
server_certificate,
sizeof(server_certificate)) < 0) {
LOG_ERR("Failed to register server certificate");
return;
}
if (tls_credential_add(CA_CERTIFICATE_TAG,
TLS_CREDENTIAL_PRIVATE_KEY,
private_key,
sizeof(private_key)) < 0) {
LOG_ERR("Failed to register private key");
return;
}
#endif
/* The image of application needed be confirmed */
LOG_INF("Confirming the boot image");
ret = boot_write_img_confirmed();
if (ret < 0) {
LOG_ERR("Error to confirm the image");
}
#if defined(CONFIG_WIFI)
struct net_if *iface = net_if_get_default();
static struct wifi_connect_req_params cnx_params = {
.ssid = CONFIG_UPDATEHUB_SAMPLE_WIFI_SSID,
.ssid_length = 0,
.psk = CONFIG_UPDATEHUB_SAMPLE_WIFI_PSK,
.psk_length = 0,
.channel = 0,
.security = WIFI_SECURITY_TYPE_PSK,
};
cnx_params.ssid_length = strlen(CONFIG_UPDATEHUB_SAMPLE_WIFI_SSID);
cnx_params.psk_length = strlen(CONFIG_UPDATEHUB_SAMPLE_WIFI_PSK);
if (net_mgmt(NET_REQUEST_WIFI_CONNECT, iface,
&cnx_params, sizeof(struct wifi_connect_req_params))) {
LOG_ERR("Error connecting to WiFi");
return;
}
#elif defined(CONFIG_MODEM_GSM_PPP)
const struct device *uart_dev =
device_get_binding(CONFIG_MODEM_GSM_UART_NAME);
LOG_INF("APN '%s' UART '%s' device %p", CONFIG_MODEM_GSM_APN,
CONFIG_MODEM_GSM_UART_NAME, uart_dev);
#endif
net_mgmt_init_event_callback(&mgmt_cb, event_handler, EVENT_MASK);
net_mgmt_add_event_callback(&mgmt_cb);
net_conn_mgr_resend_status();
}
|
song91425/WeIdentityService
|
WeIdentityService/Classes/Code/WI/Headers/Utils/WIError.h
|
//
// WIError.h
// WeIdentityService
//
// Created by lssong on 2021/1/27.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface WIError : NSObject
extern const NSInteger ERR_DEFAULT;//默认错误
extern const NSInteger ERR_INTERNAL ; //内部错误,比如hash失败等,非业务流程或者数据错误,一般不会发生
extern const NSInteger ERR_NOT_INIT ; //还未初始化
extern const NSInteger ERR_NO_WALLET ;
extern const NSInteger LOCAL_ERR_CREATE_KEYPAIR ;
extern const NSInteger ERR_GET_PUBLIC_KEY_BY_KEY_ID ;
extern const NSInteger ERR_UNLOCK_PWD ;//密码错误
extern const NSInteger ERR_RESTORE_PWD ; //密码错误
extern const NSInteger ERR_TRANS_PWD ; //密码错误
extern const NSInteger ERR_FILE_EXIST ; //文件已存在
extern const NSInteger ERR_FILE_NOT_EXIST ; //文件不存在
extern const NSInteger ERR_NOT_FOUND ; //不存在
extern const NSInteger ERR_CREATE_MASTERKEY; //创建maserkey为nil
extern NSString * const NETWORK_ERR_MSG_DEFAULT ;
extern NSString * const MSG_UNKNOWN ;
+(NSError *)normalError:(NSString *) msg errcode:(NSInteger) code;
+(NSError *)internalError:(NSString *) msg;
@end
NS_ASSUME_NONNULL_END
|
EnorMOZ/homebrew-cask
|
Casks/the-hit-list.rb
|
<filename>Casks/the-hit-list.rb<gh_stars>0
cask 'the-hit-list' do
version '1.1.19,308'
sha256 'cc244128df45759cb1306448405cbcd0c0b153292cecda4326230881546eab94'
url "https://distrib.karelia.com/downloads/TheHitList-#{version.after_comma}.zip"
appcast 'https://launch.karelia.com/appcast.php?product=9&appname=The+Hit+List',
checkpoint: '727a25533a0a315b6f77e6b1f7f1a3692d5914712ff6eb04727f086460c8e25b'
name 'The Hit List'
homepage 'https://www.karelia.com/products/the-hit-list/mac.html'
license :commercial
app 'The Hit List.app'
end
|
reels-research/iOS-Private-Frameworks
|
Celestial.framework/BWInferenceVideoScalingProvider.h
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/Celestial.framework/Celestial
*/
@interface BWInferenceVideoScalingProvider : NSObject <BWInferenceExecutable, BWInferencePreventable, BWInferenceScalingProvider> {
bool _applyUprightExifOrientation;
bool _applyValidBufferRect;
NSDictionary * _colorSpaceProperties;
bool _computeAndApplyAspectRatioCrop;
float _customFiltersLastUsedHorizontalRatio;
float _customFiltersLastUsedVerticalRatio;
BWInferenceVideoRequirement * _inputRequirement;
float _outputAspectRatio;
NSArray * _outputRequirements;
FigM2MController * _scalerController;
}
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (nonatomic, readonly) <BWInferenceExecutable> *executable;
@property (nonatomic, readonly) <BWInferenceExtractable> *extractable;
@property (readonly) unsigned long long hash;
@property (nonatomic, readonly) bool mustExecuteWhenAllowed;
@property (nonatomic, readonly) <BWInferencePropagatable> *propagatable;
@property (nonatomic, readonly) <BWInferenceSubmittable> *submittable;
@property (readonly) Class superclass;
@property (nonatomic, readonly) int type;
+ (void)initialize;
- (void)_configureCustomFiltersForScalingFromSourceWidth:(unsigned long long)arg1 sourceHeight:(unsigned long long)arg2 destinationWidth:(unsigned long long)arg3 destinationHeight:(unsigned long long)arg4;
- (void)dealloc;
- (id)description;
- (id)executable;
- (int)executeOnSampleBuffer:(struct opaqueCMSampleBuffer { }*)arg1 usingStorage:(id)arg2 withExecutionTime:(struct { long long x1; int x2; unsigned int x3; long long x4; })arg3 completionHandler:(id /* block */)arg4;
- (id)extractable;
- (id)initWithInputRequirement:(id)arg1 outputRequirements:(id)arg2;
- (bool)mustExecuteWhenAllowed;
- (id)newStorage;
- (int)prepareForExecution;
- (id)preventionReasonWithSampleBuffer:(struct opaqueCMSampleBuffer { }*)arg1 executionTime:(struct { long long x1; int x2; unsigned int x3; long long x4; })arg2;
- (id)propagatable;
- (id)submittable;
- (int)type;
@end
|
pedroroque/DigitalBroadcaster
|
src/Broadcaster2006/Scheduler/ScheduleRightView.h
|
<filename>src/Broadcaster2006/Scheduler/ScheduleRightView.h
#if !defined(AFX_SCHEDULERIGHTVIEW_H__92264448_3B30_4452_87F3_0E8E8A6B39CF__INCLUDED_)
#define AFX_SCHEDULERIGHTVIEW_H__92264448_3B30_4452_87F3_0E8E8A6B39CF__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// ScheduleRightView.h : header file
//
#include "..\OnAir\TypeLineUpItem.h"
#include "..\OnAir\OnAirDefines.h"
#include "ScheduleLeftView.h"
/////////////////////////////////////////////////////////////////////////////
// CScheduleRightView view
typedef struct
{
WORD wType;
long lID,
lTemplateID,
lArtistID;
CString strName,
strTemplate,
strIntro,
strLength;
DWORD64 qwStart,
qwLength,
qwOriginalLen;
DWORD dwIntro;
BOOL bLocked;
int iImage,
iRythm;
} typeScheduleItem;
class CScheduleRightView : public CListView
{
protected:
CScheduleRightView(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(CScheduleRightView)
// Attributes
public:
COleDropTarget m_DropTarget;
typeTreeDrag *m_lpDragItem;
CPoint m_OldPoint;
CScheduleLeftView *m_pLeft;
typeLineUpItem *m_lpBlock[100];
int m_nBlocks;
// Operations
public:
void EditVoiceInsert( int Pos,typeScheduleItem *pItem);
void OnPFL();
void OnCut();
void DrawDragItem( char *strName,CPoint point );
BOOL GetDraggedItem( typeScheduleItem *lpItem );
void GetScheduleBlocks();
void RemoveBlocks();
void InsertBlocks();
void OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult);
void OnLockItem();
void SaveSchedule();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CScheduleRightView)
public:
virtual DROPEFFECT OnDragEnter(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point);
virtual void OnDragLeave();
virtual DROPEFFECT OnDragOver(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point);
virtual BOOL OnDrop(COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point);
protected:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint);
//}}AFX_VIRTUAL
// Implementation
protected:
virtual ~CScheduleRightView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CScheduleRightView)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnBegindrag(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnDblclk(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnRdblclk(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnRclick(NMHDR* pNMHDR, LRESULT* pResult);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SCHEDULERIGHTVIEW_H__92264448_3B30_4452_87F3_0E8E8A6B39CF__INCLUDED_)
|
holmes07/pulsar-beat-output
|
vendor/github.com/aws/aws-sdk-go-v2/service/mobile/api_types.go
|
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package mobile
import (
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/internal/awsutil"
"github.com/aws/aws-sdk-go-v2/private/protocol"
)
var _ aws.Config
var _ = awsutil.Prettify
// The details of the bundle.
// Please also see https://docs.aws.amazon.com/goto/WebAPI/mobile-2017-07-01/BundleDetails
type BundleDetails struct {
_ struct{} `type:"structure"`
// Developer desktop or mobile app or website platforms.
AvailablePlatforms []Platform `locationName:"availablePlatforms" type:"list"`
// Unique bundle identifier.
BundleId *string `locationName:"bundleId" type:"string"`
// Description of the download bundle.
Description *string `locationName:"description" type:"string"`
// Icon for the download bundle.
IconUrl *string `locationName:"iconUrl" type:"string"`
// Title of the download bundle.
Title *string `locationName:"title" type:"string"`
// Version of the download bundle.
Version *string `locationName:"version" type:"string"`
}
// String returns the string representation
func (s BundleDetails) String() string {
return awsutil.Prettify(s)
}
// MarshalFields encodes the AWS API shape using the passed in protocol encoder.
func (s BundleDetails) MarshalFields(e protocol.FieldEncoder) error {
if s.AvailablePlatforms != nil {
v := s.AvailablePlatforms
metadata := protocol.Metadata{}
ls0 := e.List(protocol.BodyTarget, "availablePlatforms", metadata)
ls0.Start()
for _, v1 := range v {
ls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})
}
ls0.End()
}
if s.BundleId != nil {
v := *s.BundleId
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "bundleId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.Description != nil {
v := *s.Description
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "description", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.IconUrl != nil {
v := *s.IconUrl
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "iconUrl", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.Title != nil {
v := *s.Title
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "title", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.Version != nil {
v := *s.Version
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "version", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
return nil
}
// Detailed information about an AWS Mobile Hub project.
// Please also see https://docs.aws.amazon.com/goto/WebAPI/mobile-2017-07-01/ProjectDetails
type ProjectDetails struct {
_ struct{} `type:"structure"`
// Website URL for this project in the AWS Mobile Hub console.
ConsoleUrl *string `locationName:"consoleUrl" type:"string"`
// Date the project was created.
CreatedDate *time.Time `locationName:"createdDate" type:"timestamp"`
// Date of the last modification of the project.
LastUpdatedDate *time.Time `locationName:"lastUpdatedDate" type:"timestamp"`
// Name of the project.
Name *string `locationName:"name" type:"string"`
// Unique project identifier.
ProjectId *string `locationName:"projectId" type:"string"`
// Default region to use for AWS resource creation in the AWS Mobile Hub project.
Region *string `locationName:"region" type:"string"`
// List of AWS resources associated with a project.
Resources []Resource `locationName:"resources" type:"list"`
// Synchronization state for a project.
State ProjectState `locationName:"state" type:"string" enum:"true"`
}
// String returns the string representation
func (s ProjectDetails) String() string {
return awsutil.Prettify(s)
}
// MarshalFields encodes the AWS API shape using the passed in protocol encoder.
func (s ProjectDetails) MarshalFields(e protocol.FieldEncoder) error {
if s.ConsoleUrl != nil {
v := *s.ConsoleUrl
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "consoleUrl", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.CreatedDate != nil {
v := *s.CreatedDate
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "createdDate",
protocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)
}
if s.LastUpdatedDate != nil {
v := *s.LastUpdatedDate
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "lastUpdatedDate",
protocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)
}
if s.Name != nil {
v := *s.Name
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.ProjectId != nil {
v := *s.ProjectId
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "projectId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.Region != nil {
v := *s.Region
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "region", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.Resources != nil {
v := s.Resources
metadata := protocol.Metadata{}
ls0 := e.List(protocol.BodyTarget, "resources", metadata)
ls0.Start()
for _, v1 := range v {
ls0.ListAddFields(v1)
}
ls0.End()
}
if len(s.State) > 0 {
v := s.State
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "state", protocol.QuotedValue{ValueMarshaler: v}, metadata)
}
return nil
}
// Summary information about an AWS Mobile Hub project.
// Please also see https://docs.aws.amazon.com/goto/WebAPI/mobile-2017-07-01/ProjectSummary
type ProjectSummary struct {
_ struct{} `type:"structure"`
// Name of the project.
Name *string `locationName:"name" type:"string"`
// Unique project identifier.
ProjectId *string `locationName:"projectId" type:"string"`
}
// String returns the string representation
func (s ProjectSummary) String() string {
return awsutil.Prettify(s)
}
// MarshalFields encodes the AWS API shape using the passed in protocol encoder.
func (s ProjectSummary) MarshalFields(e protocol.FieldEncoder) error {
if s.Name != nil {
v := *s.Name
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.ProjectId != nil {
v := *s.ProjectId
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "projectId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
return nil
}
// Information about an instance of an AWS resource associated with a project.
// Please also see https://docs.aws.amazon.com/goto/WebAPI/mobile-2017-07-01/Resource
type Resource struct {
_ struct{} `type:"structure"`
// AWS resource name which uniquely identifies the resource in AWS systems.
Arn *string `locationName:"arn" type:"string"`
// Key-value attribute pairs.
Attributes map[string]string `locationName:"attributes" type:"map"`
// Identifies which feature in AWS Mobile Hub is associated with this AWS resource.
Feature *string `locationName:"feature" type:"string"`
// Name of the AWS resource (e.g., for an Amazon S3 bucket this is the name
// of the bucket).
Name *string `locationName:"name" type:"string"`
// Simplified name for type of AWS resource (e.g., bucket is an Amazon S3 bucket).
Type *string `locationName:"type" type:"string"`
}
// String returns the string representation
func (s Resource) String() string {
return awsutil.Prettify(s)
}
// MarshalFields encodes the AWS API shape using the passed in protocol encoder.
func (s Resource) MarshalFields(e protocol.FieldEncoder) error {
if s.Arn != nil {
v := *s.Arn
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "arn", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.Attributes != nil {
v := s.Attributes
metadata := protocol.Metadata{}
ms0 := e.Map(protocol.BodyTarget, "attributes", metadata)
ms0.Start()
for k1, v1 := range v {
ms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})
}
ms0.End()
}
if s.Feature != nil {
v := *s.Feature
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "feature", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.Name != nil {
v := *s.Name
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
if s.Type != nil {
v := *s.Type
metadata := protocol.Metadata{}
e.SetValue(protocol.BodyTarget, "type", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)
}
return nil
}
|
rsins/Scratchpad-Java
|
ScratchPad/src/com/hackerrank/fibonaccimodified/MyMainClass.java
|
<gh_stars>0
package com.hackerrank.fibonaccimodified;
import java.math.BigInteger;
import java.util.Scanner;
public class MyMainClass {
/*
A series is defined in the following manner:
Given the nth and (n+1)th terms, the (n+2)th can be computed by the following relation
Tn+2 = (Tn+1)2 + Tn
So, if the first two terms of the series are 0 and 1:
the third term = 12 + 0 = 1
fourth term = 12 + 1 = 2
fifth term = 22 + 1 = 5
... And so on.
Given three integers A, B and N, such that the first two terms of the series (1st and 2nd terms) are A and B respectively, compute the Nth term of the series.
Input Format
You are given three space separated integers A, B and N on one line.
Input Constraints
0 <= A,B <= 2
3 <= N <= 20
Output Format
One integer.
This integer is the Nth term of the given series when the first two terms are A and B respectively.
Note
Some output may even exceed the range of 64 bit integer.
Sample Input
0 1 5
Sample Output
5
Explanation
The first two terms of the series are 0 and 1. The fifth term is 5. How we arrive at the fifth term, is explained step by step in the introductory sections.
*/
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
BigInteger a = BigInteger.valueOf(scn.nextLong());
BigInteger b = BigInteger.valueOf(scn.nextLong());
int bigN = scn.nextInt();
int curn = 1;
while (bigN >= (curn + 2)) {
BigInteger nthplustwo = getSeries(a, b, bigN, curn);
a = b;
b = nthplustwo;
curn++;
}
scn.close();
}
/**
*
* @param nth nth item
* @param nthplusone (n+1)th item
* @param bigN if the (n+2) = N then print to output
* @return (n+2)th item
*/
private static BigInteger getSeries(BigInteger nth, BigInteger nthplusone, int bigN, int curn) {
BigInteger nthplustwo = nthplusone.multiply(nthplusone).add(nth);
if ((curn + 2) == bigN) System.out.println(nthplustwo.toString());
return nthplustwo;
}
}
|
bnagybalint/BoloDemoEngine
|
Src/Audio/AudioManager.cpp
|
<filename>Src/Audio/AudioManager.cpp
#include "AudioManager.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <mmsystem.h>
#include <dsound.h>
#include "AudioTrack.h"
// Define singleton parts
DEFINE_SINGLETON_IMPL(AudioManager);
AudioManager::AudioManager()
#if BDE_GLOBAL_ENABLE_NICE_INIT
: mDsDevice(NULL)
, mDsPrimaryBuffer(NULL)
#endif
{
}
AudioManager::~AudioManager()
{
#if BDE_GLOBAL_ENABLE_NICE_DESTROY
Assert(mDsDevice == NULL);
Assert(mDsPrimaryBuffer == NULL);
#endif
}
void AudioManager::init(HWND windowHandle)
{
DSBUFFERDESC bufferDesc;
WAVEFORMATEX waveFormat;
// Initialize the direct sound interface pointer for the default sound device.
DS_SafeCall(DirectSoundCreate8(NULL, &mDsDevice, NULL));
// Set the cooperative level to priority so the format of the primary sound buffer can be modified.
DS_SafeCall(mDsDevice->SetCooperativeLevel(windowHandle, DSSCL_PRIORITY));
// Setup the primary buffer description.
bufferDesc.dwSize = sizeof(DSBUFFERDESC);
bufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRLVOLUME;
bufferDesc.dwBufferBytes = 0;
bufferDesc.dwReserved = 0;
bufferDesc.lpwfxFormat = NULL;
bufferDesc.guid3DAlgorithm = GUID_NULL;
// Get control of the primary sound buffer on the default sound device.
DS_SafeCall(mDsDevice->CreateSoundBuffer(&bufferDesc, &mDsPrimaryBuffer, NULL));
// Setup the format of the primary sound bufffer.
// In this case it is a .WAV file recorded at 44,100 samples per second in 16-bit stereo (cd audio format).
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nSamplesPerSec = AUDIO_SAMPLE_FREQ;
waveFormat.wBitsPerSample = AUDIO_SAMPLE_BITS;
waveFormat.nChannels = AUDIO_SAMPLE_CHANNELS;
waveFormat.nBlockAlign = AUDIO_SAMPLE_BLOCKALIGN;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
waveFormat.cbSize = 0;
// Set the primary buffer to be the wave format specified.
DS_SafeCall(mDsPrimaryBuffer->SetFormat(&waveFormat));
}
void AudioManager::shutdown()
{
#if BDE_GLOBAL_ENABLE_NICE_DESTROY
Assert(mDsPrimaryBuffer);
mDsPrimaryBuffer->Release(); mDsPrimaryBuffer = NULL;
Assert(mDsDevice);
mDsDevice->Release(); mDsDevice = NULL;
#endif
}
void AudioManager::prepareTrack(AudioTrack* track)
{
if (track->getDsBuffer())
track->releaseBuffer();
track->createBuffer();
}
void AudioManager::playTrack(AudioTrack* track)
{
Assert(track->getDsBuffer());
track->getDsBuffer()->Play(0, 0, DSBPLAY_LOOPING);
}
void AudioManager::stopTrack(AudioTrack* track)
{
Assert(track->getDsBuffer());
track->getDsBuffer()->Stop();
}
|
draker94/vividus
|
vividus-plugin-saucelabs/src/main/java/org/vividus/selenium/sauce/SauceLabsCapabilitiesConfigurer.java
|
<gh_stars>100-1000
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vividus.selenium.sauce;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.vividus.bdd.context.IBddRunContext;
import org.vividus.selenium.tunnel.AbstractTunnellingCapabilitiesConfigurer;
public class SauceLabsCapabilitiesConfigurer extends AbstractTunnellingCapabilitiesConfigurer<SauceConnectOptions>
{
private static final String SAUCE_OPTIONS = "sauce:options";
private String sauceConnectArguments;
private String restUrl;
public SauceLabsCapabilitiesConfigurer(IBddRunContext bddRunContext, SauceConnectManager sauceConnectManager)
{
super(bddRunContext, sauceConnectManager);
}
@Override
public void configure(DesiredCapabilities desiredCapabilities)
{
configureTunnel(desiredCapabilities,
tunnelId -> putNestedCapability(desiredCapabilities, SAUCE_OPTIONS, "tunnelIdentifier", tunnelId));
configureTestName(desiredCapabilities, SAUCE_OPTIONS, "name");
}
@Override
protected SauceConnectOptions createOptions()
{
SauceConnectOptions sauceConnectOptions = new SauceConnectOptions();
sauceConnectOptions.setCustomArguments(sauceConnectArguments);
sauceConnectOptions.setRestUrl(restUrl);
return sauceConnectOptions;
}
public void setRestUrl(String restUrl)
{
this.restUrl = restUrl;
}
public void setSauceConnectArguments(String sauceConnectArguments)
{
this.sauceConnectArguments = sauceConnectArguments;
}
}
|
OpenDeformerDev/OpenDeformer
|
OpenDeformer/core/datastructure.h
|
<gh_stars>1-10
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef ODER_CORE_DATASTRUCTURE_H
#define ODER_CORE_DATASTRUCTURE_H
#include "oder.h"
#include "memory.h"
#include <type_traits>
#include <set>
namespace ODER{
template<class T, class Compare = std::less<T>> class DisjointSets{
private:
template<class T> struct DisjointSet{
T value;
int rank;
DisjointSet *parent;
};
public:
DisjointSets(Compare comp = Compare()) :sets(SetCompare(std::move(comp))){
sentinel = arena.Alloc();
}
void makeSet(T x){
DisjointSet<T> *entry = arena.Alloc();
entry->value = std::move(x); entry->rank = 0; entry->parent = entry;
sets.insert(entry);
}
void Union(T x, T y){ Link(findSet(x), findSet(y));}
bool isInSameSet(T x, T y){ return findSet(x) == findSet(y);}
private:
DisjointSet<T>* findSet(T x) const{
sentinel->value = x;
auto result = sets.find(sentinel);
if (result == sets.end())
return NULL;
return localFind(*result);
}
void Link(DisjointSet<T>* x, DisjointSet<T>* y){
if (x->rank > y->rank)
y->parent = x;
else{
x->parent = y;
if (x->rank == y->rank)
y->rank++;
}
}
DisjointSet<T>* localFind(DisjointSet<T>* x){
if (x != x->parent)
x->parent = localFind(x->parent);
return x->parent;
}
struct SetCompare{
SetCompare(Compare comp) :comparer(std::move(comp)){}
bool operator()(const DisjointSet<T>* left, const DisjointSet<T>* right){
return comparer(left->value, right->value);
}
private:
Compare comparer;
};
DisjointSet<T>* sentinel;
std::set<DisjointSet<T>*, SetCompare> sets;
MemoryArena<DisjointSet<T>> arena;
};
//not thread safe
template<class T> class RecycledList{
private:
template<class T> struct ListNode{
template<class... Args> ListNode(Args&&... vals): data(std::forward<Args>(vals)...){}
ListNode(const ListNode&) = delete;
ListNode& operator=(const ListNode&) = delete;
ListNode(ListNode&&) = default;
ListNode& operator=(ListNode&&) = default;
~ListNode(){ data.~T(); }
ListNode* next;
ListNode* prev;
T data;
};
public:
RecycledList(){
++listCount;
node = pool->Alloc();
node->next = node;
node->prev = node;
}
RecycledList(const RecycledList &) = default;
RecycledList& operator=(const RecycledList &) = default;
RecycledList(RecycledList&& list) noexcept{
node = list.node;
list.node = NULL;
}
RecycledList& operator=(RecycledList&& list) noexcept{
std::swap(node, list.node);
}
template<class T, class Ref, class Ptr> struct ListIterator{
using iterator_category = std::bidirectional_iterator_tag;
using value_type = T;
using difference_type = ptrdiff_t;
using size_type = size_t;
using reference = Ref;
using pointer = Ptr;
ListIterator():node(nullptr){}
ListIterator(ListNode<T>* n) :node(n){}
ListIterator(const ListIterator&) = default;
ListIterator(ListIterator&&) = default;
ListIterator& operator=(const ListIterator&) = default;
ListIterator& operator=(ListIterator&&) = default;
bool operator==(const ListIterator& x) const{ return node == x.node; }
bool operator!=(const ListIterator& x) const{ return node != x.node; }
reference operator*() const{ return node->data; }
pointer operator->() const{ return &(node->data); }
ListIterator& operator++(){
node = node->next;
return *this;
}
ListIterator operator++(int){
ListIterator temp = *this;
++*this;
return temp;
}
ListIterator& operator--(){
node = node->prev;
return *this;
}
ListIterator operator--(int){
ListIterator temp = *this;
--*this;
return temp;
}
~ListIterator() = default;
ListNode<T>* node;
};
using const_type = typename std::add_const<T>::type;
using iterator = ListIterator<T, T&, T*>;
using const_iterator = ListIterator<T, const_type&, const_type*>;
iterator begin(){ return node->next; }
iterator end(){ return node; }
const_iterator cbegin() const{ return node->next; }
const_iterator cend() const{ return node; }
void push_back(T&& val){
emplace_back(std::forward<T>(val));
}
const_iterator insert(const const_iterator& pos, T&& val){
return emplace(pos, std::forward<T>(val));
}
iterator insert(const iterator& pos, T&& val){
return emplace(pos, std::forward<T>(val));
}
template<class Ref, class Ptr, class... Args> ListIterator<T, Ref, Ptr> emplace(const ListIterator<T, Ref, Ptr>& pos, Args&&... val){
ListNode<T>* postNode = pos.node;
ListNode<T>* tmp = pool->Alloc(std::forward<Args>(val)...);
tmp->next = postNode;
tmp->prev = postNode->prev;
postNode->prev->next = tmp;
postNode->prev = tmp;
return tmp;
}
template<class... Args> void emplace_back(Args&&... val){
ListNode<T>* end = node;
ListNode<T>* tmp = pool->Alloc(std::forward<Args>(val)...);
tmp->next = end;
tmp->prev = end->prev;
end->prev->next = tmp;
end->prev = tmp;
}
void clear(){
ListNode<T>* cur = node->next;
while (cur != node){
ListNode<T>* tmp = cur;
cur = cur->next;
pool->Dealloc(tmp);
}
node->next = node;
node->prev = node;
}
template<class Ref, class Ptr> ListIterator<T, Ref, Ptr> erase(const ListIterator<T, Ref, Ptr>& iter){
ListNode<T>* toBeDelete = iter.node;
ListNode<T>* prev = toBeDelete->prev;
ListNode<T>* next = toBeDelete->next;
prev->next = next;
next->prev = prev;
pool->Dealloc(toBeDelete);
return next;
}
~RecycledList(){
if (--listCount == 0)
pool->freeAll();
}
private:
ListNode<T> *node;
static int listCount;
static MemoryPool<ListNode<T>> *pool;
};
template<class T> int RecycledList<T>::listCount = 0;
template<class T> MemoryPool<typename RecycledList<T>::ListNode<T>> *RecycledList<T>::pool = new MemoryPool<typename RecycledList<T>::ListNode<T>>();
}
#endif
|
ThomsonGuoJing/tools
|
tools-excel/src/main/java/cn/gjing/tools/excel/write/listener/ExcelCascadingDropdownBoxListener.java
|
<reponame>ThomsonGuoJing/tools<filename>tools-excel/src/main/java/cn/gjing/tools/excel/write/listener/ExcelCascadingDropdownBoxListener.java
package cn.gjing.tools.excel.write.listener;
import cn.gjing.tools.excel.metadata.listener.ExcelWriteListener;
import cn.gjing.tools.excel.write.valid.ExcelDropdownBox;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.lang.reflect.Field;
/**
* Cascading dropdown box listener,
* When {@link ExcelDropdownBox} is used in the header field of the mapped entity and a valid {@link ExcelDropdownBox#link()} parameter is set
*
* @author Gjing
**/
public interface ExcelCascadingDropdownBoxListener extends ExcelWriteListener {
/**
* Add cascading dropdown box
*
* @param excelDropdownBox ExplicitValid
* @param workbook workbook
* @param sheet The current sheet
* @param firstRow First row
* @param lastRow Last row
* @param colIndex Col index
* @param field Current field
*/
void addCascadingDropdownBox(ExcelDropdownBox excelDropdownBox, Workbook workbook, Sheet sheet, int firstRow, int lastRow, int colIndex,
Field field);
}
|
MarjanaKarzek/android_diet_tracker
|
app/src/main/java/de/karzek/diettracker/presentation/main/MainContract.java
|
<reponame>MarjanaKarzek/android_diet_tracker<gh_stars>0
package de.karzek.diettracker.presentation.main;
import android.support.annotation.IntDef;
import de.karzek.diettracker.presentation.common.BasePresenter;
import de.karzek.diettracker.presentation.common.BaseView;
/**
* Created by MarjanaKarzek on 26.04.2018.
*
* @author <NAME>
* @version 1.0
* @date 26.04.2018
*/
public interface MainContract {
interface View extends BaseView<Presenter> {
void showOnboardingScreen(int onboardingTag);
}
interface Presenter extends BasePresenter<View> {
}
@IntDef({FragmentIndex.FRAGMENT_HOME,
FragmentIndex.FRAGMENT_DIARY,
FragmentIndex.FRAGMENT_COOKBOOK,
FragmentIndex.FRAGMENT_SETTINGS})
@interface FragmentIndex {
int FRAGMENT_HOME = 0;
int FRAGMENT_DIARY = 1;
int FRAGMENT_COOKBOOK = 2;
int FRAGMENT_SETTINGS = 3;
}
}
|
SNTSVV/FAQAS_MASS
|
examples/mlfs/libm/common/s_fpclassify.c
|
<filename>examples/mlfs/libm/common/s_fpclassify.c
/*!
* -------------------------------------------------------------------------------------------------
* \file s_fpclassify.c
* \par ESA Contract Number
* 4000117691/16/NL/FE
* \brief Implementation file for __fpclassifyd.
* \version c07acbf539f8880d8c1255e7f85138b89f33387b
* \date 2018-03-22 17:44:24 +0100
* \par Last Commit
* <NAME>, 2018-03-22 17:44:24 +0100
*
* \par Detailed Description
* __fpclassifyd is the double precision version of fpclassify. It returns a predefined constant
* integer depending on the type of input. There are different constants for zero, subnormal,
* normal, infinite, and NaN.
*
* -------------------------------------------------------------------------------------------------
* \par Changelog
* Date | Name | Change
* -----------|--------------|------------------------------------------------------
* 2017-05-19 | <NAME> | Remove not needed comparison of unsigned integer >= 0
* 2017-06-07 | <NAME> | Add FPU DAZ behaviour #ifdef.
*
* \copyright Modified work Copyright European Space Agency, 2017.
*/
/* Copyright (C) 2002, 2007 by Red Hat, Incorporated. All rights reserved.
*
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*/
#include "fdlibm.h"
int
__fpclassifyd (double x)
{
#ifdef MLFS_FPU_DAZ
x *= __volatile_one;
#endif /* MLFS_FPU_DAZ */
__uint32_t msw, lsw;
EXTRACT_WORDS(msw,lsw,x);
if ((msw == 0x00000000 && lsw == 0x00000000) ||
(msw == 0x80000000U && lsw == 0x00000000))
return FP_ZERO;
else if ((msw >= 0x00100000 && msw <= 0x7fefffff) ||
(msw >= 0x80100000U && msw <= 0xffefffffU))
return FP_NORMAL;
else if ((msw <= 0x000fffff) ||
(msw >= 0x80000000U && msw <= 0x800fffffU))
/* zero is already handled above */
return FP_SUBNORMAL;
else if ((msw == 0x7ff00000 && lsw == 0x00000000) ||
(msw == 0xfff00000U && lsw == 0x00000000))
return FP_INFINITE;
else
return FP_NAN;
}
|
Hrsn2861/pysat-server
|
school/urls/school.py
|
<reponame>Hrsn2861/pysat-server<filename>school/urls/school.py
"""pysat URL Configuration for School.Create
"""
from django.urls import path
from utils.views import view_maker
from utils.params import ParamType
from utils.permission import ActionType
from school.views import school
urlpatterns = [
path('create', view_maker(school.create_school, 'POST', [
ParamType.Username,
ParamType.SchoolName,
ParamType.SchoolDescription
], [
ParamType.SchoolName
], action=ActionType.CreateSchool)),
path('get_list', view_maker(school.get_school_list, 'GET', [
ParamType.Page,
ParamType.SearchText
], action=ActionType.GetSchoolList))
]
|
haugene/losen
|
src/web/primitives/Wizard.js
|
import styled from 'styled-components';
import injectStyles from '../utils/inject-styles';
const Wizard = injectStyles(styled.div`
background-color: white;
background-image: linear-gradient(164deg, rgba(137, 174, 196, 0.34), white, rgba(0, 117, 127, 0.19));
background-repeat: no-repeat;
background-attachment: fixed;
font-family: ${({ styles }) => styles.font.primary};
font-size: 18px;
font-weight: 300;
line-height: 1.6;
strong {
font-weight: 700;
}
* {
box-sizing: border-box;
&:focus {
outline-color: ${({ styles }) => styles.color.bluegreen};
}
}
img {
max-width: 100%;
}
a {
color: ${({ styles }) => styles.color.light};
&:hover {
color: ${({ styles }) => styles.color.dark};
}
}
@media screen and (max-width: 700px) {
font-size: 16px;
}
@media print {
background-image: none;
background-color: white;
}
`);
export default Wizard;
|
pickettd/code-dot-org
|
lib/cdo/sinatra.rb
|
require 'sinatra/base'
class Sinatra::Base
def self.get_or_post(url,&block)
get(url, &block)
post(url, &block)
end
end
|
argonium/jarman
|
src/io/miti/jarman/util/ClassParser.java
|
<reponame>argonium/jarman
package io.miti.jarman.util;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import io.miti.jarman.util.ClassStreamParser2;
/**
* Parse a .class file and return the list of referenced Java classes.
*
* @author mwallace
* @version 1.0
*/
public final class ClassParser
{
/**
* Default constructor.
*/
public ClassParser()
{
super();
}
/**
* Generate the list of referenced class names.
*
* @param path the path to the input file
* @return the list of referenced class names
*/
public List<String> getReferences(final String path)
{
return getReferences(new File(path));
}
/**
* Generate the list of referenced class names.
*
* @param file the input file
* @return the list of referenced class names
*/
public List<String> getReferences(final File file)
{
// Check the input
if (file == null)
{
return null;
}
else if (file.isDirectory())
{
return null;
}
// Verify the name ends with .class.
final String name = file.getAbsolutePath();
if (name == null)
{
return null;
}
else if (!name.endsWith(".class"))
{
return null;
}
// Get the list of referenced classes
List<String> names = new ArrayList<String>(20);
try
{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream stream = new DataInputStream(bis);
new ClassStreamParser2().parseStream(stream, names);
}
catch (IOException e)
{
e.printStackTrace();
}
// Return the referenced class names
return names;
}
/**
* Generate the list of referenced class names.
*
* @param file the jar file
* @param entry the jar file entry
* @return the list of referenced class names
*/
public List<String> getReferences(final JarFile file, final JarEntry entry)
{
// Check the input
if (entry == null)
{
return null;
}
else if (entry.isDirectory())
{
return null;
}
// Verify the name ends with .class.
String name = entry.getName();
if (name == null)
{
return null;
}
else if (!name.endsWith(".class"))
{
return null;
}
List<String> names = new ArrayList<String>(20);
try
{
BufferedInputStream bis = new BufferedInputStream(file.getInputStream(entry));
DataInputStream stream = new DataInputStream(bis);
new ClassStreamParser2().parseStream(stream, names);
}
catch (IOException e)
{
e.printStackTrace();
}
// Return the referenced class names
return names;
}
}
|
rimliya-scarlet/MiraiGo
|
client/highway.go
|
<reponame>rimliya-scarlet/MiraiGo
package client
import (
"crypto/md5"
"errors"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client/pb"
"github.com/golang/protobuf/proto"
"net"
"time"
)
func (c *QQClient) highwayUploadImage(ser string, updKey, img []byte, cmdId int32) error {
conn, err := net.DialTimeout("tcp", ser, time.Second*5)
if err != nil {
return err
}
defer conn.Close()
if err = conn.SetDeadline(time.Now().Add(time.Second * 10)); err != nil {
return err
}
h := md5.Sum(img)
pkt := c.buildImageUploadPacket(img, updKey, cmdId, h)
for _, p := range pkt {
_, err = conn.Write(p)
}
if err != nil {
return err
}
r := binary.NewNetworkReader(conn)
_, err = r.ReadByte()
if err != nil {
return err
}
hl, _ := r.ReadInt32()
_, _ = r.ReadBytes(4)
payload, _ := r.ReadBytes(int(hl))
_ = conn.Close()
rsp := pb.RspDataHighwayHead{}
if err = proto.Unmarshal(payload, &rsp); err != nil {
return err
}
if rsp.ErrorCode != 0 {
return errors.New("upload failed")
}
return nil
}
|
altbswing/TempGame
|
Tetris/src/main/Test.java
|
<reponame>altbswing/TempGame
package main;
public class Test {
String str = new String("binbin");
char[] ch = new char[]{'a','b','c'};
public static void main(String[] args) {
mn(6);
}
public static void mn(int n){
loop:
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print( i * j + " ");
if(i==j){
System.out.println();
continue loop;
}
}
}
}
}
|
digital-codes/blockly
|
blockly_uncompressed.js
|
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Bootstrap code to load Blockly in uncompiled mode.
*/
'use strict';
/**
* Blockly uncompiled-mode startup code. If running in a browser
* loads closure/goog/base.js and tests/deps.js, then (in any case)
* requires Blockly.requires.
*/
(function(globalThis) {
/* eslint-disable no-undef */
var IS_NODE_JS = !!(typeof module !== 'undefined' && module.exports);
if (IS_NODE_JS) {
// Load Blockly.
goog.require('Blockly.requires');
/* eslint-disable no-undef */
module.exports = Blockly;
} else {
var BLOCKLY_DIR = '';
// Find name of current directory.
var scripts = document.getElementsByTagName('script');
var re = /(.+)[\\/]blockly_(?:.*)uncompressed\.js$/;
for (var script, i = 0; (script = scripts[i]); i++) {
var match = re.exec(script.src);
if (match) {
BLOCKLY_DIR = match[1];
break;
}
}
if (!BLOCKLY_DIR) {
alert('Could not detect Blockly\'s directory name.');
}
// Disable loading of closure/goog/deps.js (which doesn't exist).
globalThis.CLOSURE_NO_DEPS = true;
// Load Closure Library base.js (the only part of the libary we use,
// mainly for goog.require / goog.provide / goog.module).
document.write(
'<script src="' + BLOCKLY_DIR + '/closure/goog/base.js"></script>');
// Load dependency graph info from test/deps.js. To update
// deps.js, run `npm run build:deps`.
document.write(
'<script src="' + BLOCKLY_DIR + '/tests/deps.js"></script>');
// Load the rest of Blockly.
document.write('<script>goog.require(\'Blockly\');</script>');
}
})(this);
|
ChrissW-R1/ParRoute
|
src/main/java/me/chrisswr1/parroute/entities/RestrictionRelation.java
|
<gh_stars>0
package me.chrisswr1.parroute.entities;
import org.openstreetmap.osmosis.core.domain.v0_6.Relation;
import org.openstreetmap.osmosis.core.domain.v0_6.RelationMember;
import org.openstreetmap.osmosis.core.domain.v0_6.Tag;
import me.chrisswr1.parroute.DataHandler;
import me.chrisswr1.parroute.util.StringUtils;
/**
* a {@link Relation} from type {@link RelationType#RESTRICTION}
*
* @version 0.0.1
* @author ChrissW-R1
* @since 0.0.1
*/
public class RestrictionRelation
{
/**
* the super {@link Relation}
*
* @since 0.0.1
*/
private final Relation rel;
/**
* constructor, with given super {@link Relation}
*
* @since 0.0.1
*
* @param rel the super {@link Relation}
* @throws IllegalArgumentException if the type of the given
* {@link Relation} is not {@link RelationType#RESTRICTION}
*/
public RestrictionRelation(Relation rel)
throws IllegalArgumentException
{
if (DataHandler.getRelType(rel) != RelationType.RESTRICTION)
{
throw new IllegalArgumentException(rel + " is not from type restriction!");
}
this.rel = rel;
}
/**
* gives the super {@link Relation}
*
* @since 0.0.1
*
* @return the super {@link Relation}
*/
public Relation getRel()
{
return this.rel;
}
/**
* gives the {@link RelationMember} with the "from" role
*
* @since 0.0.1
*
* @return the {@link RelationMember}, which have the role "from"
*/
public RelationMember getFrom()
{
RelationMember res = null;
String fromKey = "from";
for (RelationMember member : this.getRel().getMembers())
{
String role = member.getMemberRole();
if (role.equals(fromKey))
{
return member;
}
if (role.equalsIgnoreCase(fromKey))
{
res = member;
continue;
}
if (res == null && StringUtils.containsIgnoreCase(role, fromKey))
{
res = member;
}
}
return res;
}
/**
* gives the {@link RelationMember} with the "via" role
*
* @since 0.0.1
*
* @return the {@link RelationMember}, which have the role "via"
*/
public RelationMember getVia()
{
RelationMember res = null;
String viaKey = "via";
for (RelationMember member : this.getRel().getMembers())
{
String role = member.getMemberRole();
if (role.equals(viaKey))
{
return member;
}
if (role.equalsIgnoreCase(viaKey))
{
res = member;
continue;
}
if (res == null && StringUtils.containsIgnoreCase(role, viaKey))
{
res = member;
}
}
return res;
}
/**
* gives the {@link RelationMember} with the "to" role
*
* @since 0.0.1
*
* @return the {@link RelationMember}, which have the role "to"
*/
public RelationMember getTo()
{
RelationMember res = null;
String toKey = "to";
for (RelationMember member : this.getRel().getMembers())
{
String role = member.getMemberRole();
if (role.equals(toKey))
{
return member;
}
if (role.equalsIgnoreCase(toKey))
{
res = member;
continue;
}
if (res == null && StringUtils.containsIgnoreCase(role, toKey))
{
res = member;
}
}
return res;
}
/**
* checks if the {@link Relation} is a commandment (restriction{@link Tag}
* starts with "only")
*
* @since 0.0.1
*
* @return <code>true</code> if the super {@link Relation} is a commandment,
* <code>false</code> otherwise
*/
public boolean isCommandment()
{
return DataHandler.getTagValue(this.getRel(), "restriction").toLowerCase().startsWith("only");
}
}
|
madickson/opencommercesearch
|
opencommercesearch-atg-pub/src/test/java/org/opencommercesearch/remote/assetmanager/editor/service/RedirectRuleAssetValidatorTest.java
|
package org.opencommercesearch.remote.assetmanager.editor.service;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.verification.VerificationMode;
import org.opencommercesearch.repository.RuleProperty;
import atg.remote.assetmanager.editor.model.AssetViewUpdate;
import atg.remote.assetmanager.editor.model.PropertyEditorAssetViewUpdate;
import atg.remote.assetmanager.editor.model.PropertyUpdate;
import atg.remote.assetmanager.editor.service.AssetEditorInfo;
import atg.remote.assetmanager.editor.service.AssetService;
import atg.repository.RepositoryItem;
import atg.service.asset.AssetWrapper;
public class RedirectRuleAssetValidatorTest {
RedirectRuleAssetValidator redirectRuleAssetValidator = new RedirectRuleAssetValidator();
@Mock
AssetEditorInfo editorInfo;
@Mock
AssetService assetService;
@Mock
RepositoryItem repoItem;
Collection updates;
@Before
public void setUp() throws Exception {
initMocks(this);
initMocks(this);
updates = new ArrayList();
when(editorInfo.getAssetService()).thenReturn(assetService);
AssetWrapper assetWrapper = mock(AssetWrapper.class);
when(editorInfo.getAssetWrapper()).thenReturn(assetWrapper );
when(assetWrapper.getAsset()).thenReturn(repoItem);
when(repoItem.getPropertyValue(RuleProperty.START_DATE)).thenReturn(new Timestamp(2000));
when(repoItem.getPropertyValue(RuleProperty.END_DATE)).thenReturn(new Timestamp(2500));
redirectRuleAssetValidator.setLoggingInfo(false);
redirectRuleAssetValidator.setLoggingDebug(false);
}
@Test
public void testValidateNewAsset() {
updates.add(mockAssetView("target", DefaultRuleAssetValidator.SEARCH_PAGES));
updates.add(mockAssetView("query", "validQuery"));
redirectRuleAssetValidator.validateNewAsset(editorInfo, updates, null);
verify(assetService, never()).addError(anyString(), anyString());
}
@Test
public void testValidateNewAssetQueryAll() {
updates.add(mockAssetView("target", DefaultRuleAssetValidator.SEARCH_PAGES));
updates.add(mockAssetView("query", "*"));
redirectRuleAssetValidator.validateNewAsset(editorInfo, updates, null);
verify(assetService, atLeastOnce()).addError(eq(RuleProperty.QUERY), anyString());
}
@Test
public void testValidateNewAssetAllPages() {
updates.add(mockAssetView("target", DefaultRuleAssetValidator.ALL_PAGES));
updates.add(mockAssetView("query", "validQuery"));
redirectRuleAssetValidator.validateNewAsset(editorInfo, updates, null);
verify(assetService).addError(eq(RuleProperty.TARGET), anyString());
}
@Test
public void testValidateNewAssetCategoryPages() {
updates.add(mockAssetView("target", DefaultRuleAssetValidator.CATEGORY_PAGES));
updates.add(mockAssetView("query", "validQuery"));
redirectRuleAssetValidator.validateNewAsset(editorInfo, updates, null);
verify(assetService).addError(eq(RuleProperty.TARGET), anyString());
}
@Test
public void testValidateUpdateAssetExistingTarget1() {
//scenario: if the existing target is search page and we update the query to "*" it should fail
when(repoItem.getPropertyValue(RuleProperty.TARGET)).thenReturn(DefaultRuleAssetValidator.SEARCH_PAGES);
updates.add(mockAssetView("query", "*"));
redirectRuleAssetValidator.validateUpdateAsset(editorInfo, updates, null);
verify(assetService, atLeastOnce()).addError(eq(RuleProperty.QUERY), anyString());
}
@Test
public void testValidateUpdateAssetExistingTarget2() {
//scenario: if the existing target is all pages and we update the query to "*" it should fail
when(repoItem.getPropertyValue(RuleProperty.TARGET)).thenReturn(DefaultRuleAssetValidator.CATEGORY_PAGES);
updates.add(mockAssetView("query", "*"));
redirectRuleAssetValidator.validateUpdateAsset(editorInfo, updates, null);
verify(assetService).addError(eq(RuleProperty.QUERY), anyString());
}
@Test
public void testValidateUpdateAssetOtherAttr1() {
//scenario: if we change another attribute not related to target and query was valid it should pass
when(repoItem.getPropertyValue(RuleProperty.TARGET)).thenReturn(DefaultRuleAssetValidator.SEARCH_PAGES);
when(repoItem.getPropertyValue(RuleProperty.QUERY)).thenReturn("validQuery");
updates.add(mockAssetView("date", "03/11/2013"));
redirectRuleAssetValidator.validateUpdateAsset(editorInfo, updates, null);
verify(assetService, never()).addError(anyString(), anyString());
}
@Test
public void testValidateUpdateAssetOtherAttr2() {
//scenario: if we change another attribute not related to target and query was invalid it should fail
when(repoItem.getPropertyValue(RuleProperty.TARGET)).thenReturn(DefaultRuleAssetValidator.SEARCH_PAGES);
when(repoItem.getPropertyValue(RuleProperty.QUERY)).thenReturn("*");
updates.add(mockAssetView("date", "03/11/2013"));
redirectRuleAssetValidator.validateUpdateAsset(editorInfo, updates, null);
verify(assetService).addError(eq(RuleProperty.QUERY), anyString());
}
@Test
public void testValidateUpdateAssetEmptyQuery() {
//scenario: if we change another attribute not related to target and query was empty it should fail
when(repoItem.getPropertyValue(RuleProperty.TARGET)).thenReturn(DefaultRuleAssetValidator.SEARCH_PAGES);
updates.add(mockAssetView("date", "03/11/2013"));
redirectRuleAssetValidator.validateUpdateAsset(editorInfo, updates, null);
verify(assetService).addError(eq(RuleProperty.QUERY), anyString());
}
private AssetViewUpdate mockAssetView(String propName, String propValue){
PropertyEditorAssetViewUpdate assetView = mock(PropertyEditorAssetViewUpdate.class);
Collection<PropertyUpdate> propertyUpdateCollection = new ArrayList<PropertyUpdate>();
PropertyUpdate propertyUpdate = mock(PropertyUpdate.class);
when(propertyUpdate.getPropertyName()).thenReturn(propName);
when(propertyUpdate.getPropertyValue()).thenReturn(propValue);
propertyUpdateCollection.add(propertyUpdate);
when(assetView.getPropertyUpdates()).thenReturn(propertyUpdateCollection);
return assetView;
}
}
|
davygora/splits-io
|
spec/views/runs/unauthorized_spec.rb
|
<reponame>davygora/splits-io
require 'rails_helper'
RSpec.describe 'runs/unauthorized' do
it 'renders the unauthorized template' do
render
expect(view).to render_template('runs/unauthorized')
end
end
|
mharmuth/gui-bundle
|
Resources/scripts/global.js
|
<reponame>mharmuth/gui-bundle
Ext.require('Phlexible.gui.util.Console');
Phlexible.console = new Phlexible.gui.util.Console();
Ext.provide('Phlexible.Handles');
Ext.require('Phlexible.gui.util.Handles');
Phlexible.Handles = new Phlexible.gui.util.Handles();
Ext.provide('Phlexible.Cookie');
Ext.require('Phlexible.gui.util.Cookie');
Phlexible.Cookie = new Phlexible.gui.util.Cookie();
Ext.provide('Phlexible.globalKeyMap');
Phlexible.globalKeyMap = new Ext.KeyMap(document);
Phlexible.globalKeyMap.accessKey = function (key, handler, scope) {
var h = function (keyCode, e) {
if (Ext.isIE) {
// IE6 doesn't allow cancellation of the F5 key,
// so trick it into thinking some other key was pressed (backspace in this case)
e.browserEvent.keyCode = 8;
}
e.preventDefault();
handler.call(scope || this, keyCode, e);
e.stopEvent();
return false;
};
this.on(key, h, scope);
};
Ext.require('Phlexible.globalKeyMap');
Ext.require('Phlexible.gui.Actions');
Phlexible.globalKeyMap.accessKey({key: 'y', alt: true}, function () {
Phlexible.gui.Actions.show();
});
Ext.provide('Phlexible.PluginRegistry');
Ext.require('Phlexible.gui.util.PluginRegistry');
Phlexible.PluginRegistry = new Phlexible.gui.util.PluginRegistry();
Ext.provide('Phlexible.Router');
Ext.require('Phlexible.gui.util.Router');
Phlexible.Router = new Phlexible.gui.util.Router();
Ext.onReady(function () {
Ext.require('Phlexible.gui.util.Frame');
Phlexible.Frame = new Phlexible.gui.util.Frame();
Phlexible.Frame.initFrame();
});
|
private-octopus/diana
|
stats/ziptry.py
|
import gzip
import shutil
import sys
#with gzip.open(sys.argv[1], 'rt') as f_gz:
iline = 0
for line in gzip.open(sys.argv[1], 'rt'):
iline += 1
if iline > 10:
break
print("-->" + line)
|
ikle/janus
|
groups/node.h
|
<reponame>ikle/janus<gh_stars>0
/*
* Janus Groups Node
*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#ifndef JANUS_GROUPS_NODE_H
#define JANUS_GROUPS_NODE_H 1
#include <stdio.h>
#include "address.h"
#include "callout.h"
#include "seq.h"
enum node_type {
NODE_STATIC,
NODE_DOMAIN,
NODE_ZONE,
};
struct node {
struct node *next;
enum node_type type;
struct address_seq seq;
char *name;
time_t ttl;
struct callout callout, *observer;
};
struct node *node_alloc_static (struct callout *observer, FILE *from);
struct node *node_alloc_domain (struct callout *observer, const char *name);
struct node *node_alloc_zone (struct callout *observer, const char *name);
void node_free_schedule (struct node *o);
SEQ_DECLARE (node)
#endif /* JANUS_GROUPS_NODE_H */
|
haekb/nolf1-modernizer
|
NOLF/ClientShellDLL/SFXMgr.h
|
// ----------------------------------------------------------------------- //
//
// MODULE : SFXMgr.h
//
// PURPOSE : Special FX Mgr - Definition
//
// CREATED : 10/24/97
//
// (c) 1997-2000 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#ifndef __SFX_MGR_H__
#define __SFX_MGR_H__
#include "iltclient.h"
#include "SpecialFXList.h"
#include "SFXMsgIds.h"
#define DYN_ARRAY_SIZE (SFX_TOTAL_NUMBER + 1)
#define CAMERA_LIST_SIZE 20
class CCharacterFX;
class CSFXMgr
{
public :
CSFXMgr() {}
~CSFXMgr() {}
LTBOOL Init(ILTClient* pClientDE);
CSpecialFX* FindSpecialFX(uint8 nType, HLOCALOBJ hObj);
CSpecialFXList* GetCameraList() { return &m_cameraSFXList; }
void RemoveSpecialFX(HLOCALOBJ hObj);
void UpdateSpecialFX();
void HandleSFXMsg(HLOCALOBJ hObj, HMESSAGEREAD hMessage);
void RemoveAll();
CSpecialFX* CreateSFX(uint8 nId, SFXCREATESTRUCT *psfxCreateStruct,
HMESSAGEREAD hMessage=LTNULL, HOBJECT hServerObj=LTNULL);
static void DeleteSFX(CSpecialFX *pSFX);
inline CSpecialFXList* GetFXList(uint8 nType)
{
if (nType < 0 || nType >= DYN_ARRAY_SIZE) return LTNULL;
return &m_dynSFXLists[nType];
}
void OnTouchNotify(HOBJECT hMain, CollisionInfo *pInfo, float forceMag);
void OnModelKey(HLOCALOBJ hObj, ArgList *pArgs);
void OnSFXMessage(HMESSAGEREAD hMessage);
CCharacterFX* GetCharacterFX(HOBJECT hObject);
private :
void AddDynamicSpecialFX(CSpecialFX* pSFX, uint8 nId);
void UpdateDynamicSpecialFX();
void RemoveDynamicSpecialFX(HOBJECT hObj);
void RemoveAllDynamicSpecialFX();
int GetDynArrayIndex(uint8 nFXId);
unsigned int GetDynArrayMaxNum(uint8 nArrayIndex);
CSpecialFXList m_dynSFXLists[DYN_ARRAY_SIZE]; // Lists of dynamic special fx
CSpecialFXList m_cameraSFXList; // List of camera special fx
};
#endif // __SFX_MGR_H__
|
victory460/myOMZ
|
node_modules/ionic-angular/components/menu/menu-controller.js
|
<gh_stars>1-10
export var MenuController = (function () {
function MenuController() {
this._menus = [];
}
MenuController.prototype.open = function (menuId) {
var menu = this.get(menuId);
if (menu) {
var openedMenu = this.getOpen();
if (openedMenu && menu !== openedMenu) {
openedMenu.setOpen(false, false);
}
return menu.open();
}
return Promise.resolve(false);
};
MenuController.prototype.close = function (menuId) {
var menu;
if (menuId) {
menu = this.get(menuId);
}
else {
menu = this.getOpen();
}
if (menu) {
return menu.close();
}
return Promise.resolve(false);
};
MenuController.prototype.toggle = function (menuId) {
var menu = this.get(menuId);
if (menu) {
var openedMenu = this.getOpen();
if (openedMenu && menu !== openedMenu) {
openedMenu.setOpen(false, false);
}
return menu.toggle();
}
return Promise.resolve(false);
};
MenuController.prototype.enable = function (shouldEnable, menuId) {
var menu = this.get(menuId);
if (menu) {
return menu.enable(shouldEnable);
}
};
MenuController.prototype.swipeEnable = function (shouldEnable, menuId) {
var menu = this.get(menuId);
if (menu) {
return menu.swipeEnable(shouldEnable);
}
};
MenuController.prototype.isOpen = function (menuId) {
var menu = this.get(menuId);
return menu && menu.isOpen || false;
};
MenuController.prototype.isEnabled = function (menuId) {
var menu = this.get(menuId);
return menu && menu.enabled || false;
};
MenuController.prototype.get = function (menuId) {
var menu;
if (menuId === 'left' || menuId === 'right') {
menu = this._menus.find(function (m) { return m.side === menuId && m.enabled; });
if (menu)
return menu;
return this._menus.find(function (m) { return m.side === menuId; }) || null;
}
else if (menuId) {
return this._menus.find(function (m) { return m.id === menuId; }) || null;
}
menu = this._menus.find(function (m) { return m.enabled; });
if (menu) {
return menu;
}
return (this._menus.length ? this._menus[0] : null);
};
MenuController.prototype.getOpen = function () {
return this._menus.find(function (m) { return m.isOpen; });
};
MenuController.prototype.getMenus = function () {
return this._menus;
};
MenuController.prototype.register = function (menu) {
this._menus.push(menu);
};
MenuController.prototype.unregister = function (menu) {
var index = this._menus.indexOf(menu);
if (index > -1) {
this._menus.splice(index, 1);
}
};
MenuController.registerType = function (name, cls) {
menuTypes[name] = cls;
};
MenuController.create = function (type, menuCmp, platform) {
return new menuTypes[type](menuCmp, platform);
};
return MenuController;
}());
var menuTypes = {};
|
teadur/registry
|
db/migrate/20150217133937_add_index_for_contact_code.rb
|
<reponame>teadur/registry
class AddIndexForContactCode < ActiveRecord::Migration
def change
add_index :contacts, :code
end
end
|
EzioL/leetcode
|
src/main/java/_1013_CanThreePartsEqualSum.java
|
<filename>src/main/java/_1013_CanThreePartsEqualSum.java
/**
* Here be dragons !
*
* @author: Ezio
* created on 2020/3/11
*/
public class _1013_CanThreePartsEqualSum {
static class Solution {
public boolean canThreePartsEqualSum(int[] A) {
if (A.length < 3) {
return false;
}
int sum = 0;
for (int value : A) {
sum += value;
}
if (sum % 3 > 0) {
return false;
}
int c = 0;
int f = 0;
for (int value : A) {
c += value;
if (c == sum / 3) {
f++;
c = 0;
}
}
return f >= 3;
}
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.canThreePartsEqualSum(new int[]{10, -10, 10, -10, 10, -10, 10, -10}));
}
}
|
wangyuyunmu/Recommended-system-practice
|
chapter2-Algorithms-user behavior based/LFM/Dataset.py
|
<reponame>wangyuyunmu/Recommended-system-practice
import random
import time
# 定义装饰器,监控运行时间
def timmer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
stop_time = time.time()
print('Func %s, run time: %s' % (func.__name__, stop_time - start_time))
return res
return wrapper
# shju 处理相关 load data/split data
class Dataset():
def __init__(self, fp):
# fp: data file path
self.data = self.loadData(fp)
@timmer
def loadData(self, fp):
data = []
for l in open(fp):
data.append(tuple(map(int, l.strip().split('::')[:2])))
return data
@timmer
def splitData(self, M, k, seed=1):
'''
:params: data, 加载的所有(user, item)数据条目
:params: M, 划分的数目,最后需要取M折的平均
:params: k, 本次是第几次划分,k~[0, M)
:params: seed, random的种子数,对于不同的k应设置成一样的
:return: train, test
'''
train, test = [], []
random.seed(seed)
for user, item in self.data:
if random.randint(0, M - 1) == k:
test.append((user, item))
else:
train.append((user, item))
# 处理成字典的形式,user->set(items)
def convert_dict(data):
data_dict = {}
for user, item in data:
if user not in data_dict:
data_dict[user] = set()
data_dict[user].add(item)
data_dict = {k: list(data_dict[k]) for k in data_dict}
return data_dict
return convert_dict(train), convert_dict(test)
|
rekcurd/rekcurd-python
|
rekcurd/_project.py
|
<gh_stars>10-100
__project__ = 'rekcurd'
|
haomingzhi/Model
|
UniversalFramework/UniversalFramework/Common/CommonUtil/BSLocation.h
|
<reponame>haomingzhi/Model<filename>UniversalFramework/UniversalFramework/Common/CommonUtil/BSLocation.h
//
// BSLocation.h
// JiXie
// 定位:1.工程增加MapKit.framework,2.CoreLocation.framework 3.在plist中增加两个设置:NSLocationWhenInUseUsageDescription(YES),NSLocationAlwaysUsageDescription(YES)
// Created by ORANLLC_IOS1 on 15/6/18.
// Copyright (c) 2015年 ORANLLC_IOS1. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@interface BSLocation : NSObject
@property(nonatomic) NSInteger onece;
@property(nonatomic) CLLocationCoordinate2D coordinate;
-(BOOL)getLocation: (id) observer callback:(SEL) callback;
-(NSString *) getLocationDescript:(NSString *)latitude longitude:(NSString *)longitude;
@end
|
ahmar20/WAVE300
|
driver/wireless/driver/shared/mtlk_card_types.h
|
<gh_stars>10-100
/* $Id: mtlk_card_types.h 10358 2011-01-15 09:59:33Z dmytrof $ */
#ifndef __HW_MTLK_CARD_TYPES_H__
#define __HW_MTLK_CARD_TYPES_H__
typedef enum
{
MTLK_CARD_UNKNOWN = 0x8888, /* Just magics to avoid */
MTLK_CARD_FIRST = 0xABCD, /* accidental coincidences */
#ifdef MTCFG_LINDRV_HW_PCIE
MTLK_CARD_PCIE,
#endif
#ifdef MTCFG_LINDRV_HW_PCIG3
MTLK_CARD_PCIG3,
#endif
#ifdef MTCFG_LINDRV_HW_AHBG35
MTLK_CARD_AHBG35,
#endif
MTLK_CARD_LAST
} mtlk_card_type_t;
#endif /* __HW_MTLK_CARD_TYPES_H__ */
|
ponyatov/metaL
|
docs/search/namespaces_4.js
|
var searchData=
[
['fl',['fl',['../namespacefl.html',1,'']]]
];
|
Kilanov/java-a-to-z
|
chapter_005/src/main/java/ru/skilanov/io/map/HashMapContainer.java
|
package ru.skilanov.io.map;
/**
* Conteiner interface for the HashMap.
*
* @param <K> Object
* @param <V> Object
*/
public interface HashMapContainer<K, V> extends Iterable {
/**
* Insert method.
*
* @param key Object
* @param value Object
* @return boolean
*/
boolean insert(K key, V value);
/**
* Get method.
*
* @param key Object
* @return Object
*/
V get(K key);
/**
* Delete method.
*
* @param key Object
* @return boolean
*/
boolean delete(K key);
}
|
kunpengcompute/devkit-intellij-plugin
|
ui/src/main/java/com/huawei/kunpeng/intellij/ui/action/PasswordFieldAction.java
|
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. 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.huawei.kunpeng.intellij.ui.action;
import com.huawei.kunpeng.intellij.common.constant.IDEConstant;
import com.huawei.kunpeng.intellij.common.util.BaseIntellijIcons;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
/**
* PasswordFieldAction
*
* @since 2020-04-06
*/
public class PasswordFieldAction {
private boolean viewIcon = false;
private boolean viewStartIcon = false;
private boolean viewConformIcon = false;
private boolean isCopy;
/**
* 密码显示明文
*
* @param eyePwdLab 图片
* @param jPasswordField 输入框
*/
public void registerMouseListener(JLabel eyePwdLab, JPasswordField jPasswordField) {
jPasswordField.setEchoChar('*');
eyePwdLab.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (viewIcon) {
jPasswordField.setEchoChar('*');
eyePwdLab.setIcon(BaseIntellijIcons.load(IDEConstant.EYE_HIDE));
viewIcon = false;
} else {
jPasswordField.setEchoChar('\0');
eyePwdLab.setIcon(BaseIntellijIcons.load(IDEConstant.EYE_VIEW));
viewIcon = true;
}
}
});
}
/**
* 新增密码显示明文
*
* @param eyePwdLab 图片
* @param jPasswordField 输入框
*/
public void registerMouseListenerOne(JLabel eyePwdLab, JPasswordField jPasswordField) {
jPasswordField.setEchoChar('*');
eyePwdLab.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (viewStartIcon) {
jPasswordField.setEchoChar('*');
eyePwdLab.setIcon(BaseIntellijIcons.load(IDEConstant.EYE_HIDE));
viewStartIcon = false;
} else {
jPasswordField.setEchoChar('\0');
eyePwdLab.setIcon(BaseIntellijIcons.load(IDEConstant.EYE_VIEW));
viewStartIcon = true;
}
}
});
}
/**
* 确认密码显示明文
*
* @param eyePwdLab 图片
* @param jPasswordField 输入框
*/
public void registerMouseListenerTwo(JLabel eyePwdLab, JPasswordField jPasswordField) {
jPasswordField.setEchoChar('*');
eyePwdLab.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (viewConformIcon) {
jPasswordField.setEchoChar('*');
eyePwdLab.setIcon(BaseIntellijIcons.load(IDEConstant.EYE_HIDE));
viewConformIcon = false;
} else {
jPasswordField.setEchoChar('\0');
eyePwdLab.setIcon(BaseIntellijIcons.load(IDEConstant.EYE_VIEW));
viewConformIcon = true;
}
}
});
}
/**
* 密码长度限制
*
* @param passwordField 事件
*/
public void pwdDocument(JPasswordField passwordField) {
passwordField.setDocument(new PlainDocument() {
@Override
public void insertString(int offs, String textNew, AttributeSet attributeSet) throws BadLocationException {
char[] text = passwordField.getPassword();
if (text.length + textNew.length() > 32) {
Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(offs, textNew, attributeSet);
}
});
}
/**
* 键盘复制限制
*
* @param keyEvent 事件
*/
public void keyEvent(KeyEvent keyEvent) {
if (("C").equals(KeyEvent.getKeyText(keyEvent.getKeyCode())) || ("X")
.equals(KeyEvent.getKeyText(keyEvent.getKeyCode()))) {
isCopy = true;
return;
}
if (!isCopy) {
return;
}
if (("Ctrl").equals(KeyEvent.getKeyText(keyEvent.getKeyCode()))) {
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection("");
clip.setContents(tText, null);
}
}
}
|
mrojaczy/Labs
|
2 term/BAP/3 Lab/mylist.cpp
|
#include "mylist.h"
MyList::MyList()
{
}
void MyList::add(Info *info)
{
info->next = first;
first = info;
}
void MyList::remove(Info input)
{
first = remove(first, input);
}
Info *MyList::remove(Info *info, Info input)
{
if (info == nullptr) {
return nullptr;
}
if (info->isEqual(input)) {
return remove(info->next, input);
}
else {
info->next = remove(info->next, input);
return info;
}
}
QString MyList::find(Info input)
{
QString s;
Info *info = first;
while(info != nullptr) {
if (info->isEqual(input)) {
s = "Name: " + info->name + "\nSurname: " + info->surname + "\nCity: " + info->city + "\nStreet: " + info->street + "\nHouse: " + info->house
+ "\nMarks:\nMath: " + QString::number(info->markMath) + "\tPhysics: " + QString::number(info->markPhys) + "\tLang: " + QString::number(info->markLang)
+ "\nAverage mark: " + QString::number(info->averageMark) + "\n----------\n" + s;
}
info = info->next;
}
return s;
}
QString MyList::output()
{
QString s;
Info *info = first;
while(info != nullptr){
s = "Name: " + info->name + "\nSurname: " + info->surname + "\nCity: " + info->city + "\nStreet: " + info->street + "\nHouse: " + info->house
+ "\nMarks:\nMath: " + QString::number(info->markMath) + "\tPhysics: " + QString::number(info->markPhys) + "\tLang: " + QString::number(info->markLang)
+ "\nAverage mark: " + QString::number(info->averageMark) + "\n----------\n" + s;
info = info->next;
}
return s;
}
|
jgowdyelastic/kibana
|
src/ui/public/utils/__tests__/diff_time_picker_vals.js
|
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import moment from 'moment';
import ngMock from 'ng_mock';
import expect from 'expect.js';
import { UtilsDiffTimePickerValsProvider } from '../diff_time_picker_vals';
describe('Diff Time Picker Values', function () {
let diffTimePickerValues;
beforeEach(ngMock.module('kibana'));
beforeEach(ngMock.inject(function (Private) {
diffTimePickerValues = Private(UtilsDiffTimePickerValsProvider);
}));
it('accepts two undefined values', function () {
const diff = diffTimePickerValues(undefined, undefined);
expect(diff).to.be(false);
});
describe('dateMath ranges', function () {
it('knows a match', function () {
const diff = diffTimePickerValues(
{
to: 'now',
from: 'now-7d'
},
{
to: 'now',
from: 'now-7d'
}
);
expect(diff).to.be(false);
});
it('knows a difference', function () {
const diff = diffTimePickerValues(
{
to: 'now',
from: 'now-7d'
},
{
to: 'now',
from: 'now-1h'
}
);
expect(diff).to.be(true);
});
});
describe('a dateMath range, and a moment range', function () {
it('is always different', function () {
const diff = diffTimePickerValues(
{
to: moment(),
from: moment()
},
{
to: 'now',
from: 'now-1h'
}
);
expect(diff).to.be(true);
});
});
describe('moment ranges', function () {
it('uses the time value of moments for comparison', function () {
const to = moment();
const from = moment().add(1, 'day');
const diff = diffTimePickerValues(
{
to: to.clone(),
from: from.clone()
},
{
to: to.clone(),
from: from.clone()
}
);
expect(diff).to.be(false);
});
it('fails if any to or from is different', function () {
const to = moment();
const from = moment().add(1, 'day');
const from2 = moment().add(2, 'day');
const diff = diffTimePickerValues(
{
to: to.clone(),
from: from.clone()
},
{
to: to.clone(),
from: from2.clone()
}
);
expect(diff).to.be(true);
});
});
it('does not fall apart with unusual values', function () {
const diff = diffTimePickerValues({}, {});
expect(diff).to.be(false);
});
});
|
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
|
src/StockIT-v1-release_source_from_JADX/sources/com/google/android/gms/auth/account/zzg.java
|
<filename>src/StockIT-v1-release_source_from_JADX/sources/com/google/android/gms/auth/account/zzg.java
package com.google.android.gms.auth.account;
import android.accounts.Account;
import com.google.android.gms.auth.account.WorkAccountApi;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.internal.PendingResultUtil;
final class zzg implements PendingResultUtil.ResultConverter<WorkAccountApi.AddAccountResult, Account> {
zzg(WorkAccountClient workAccountClient) {
}
public final /* synthetic */ Object convert(Result result) {
return ((WorkAccountApi.AddAccountResult) result).getAccount();
}
}
|
estep12/RELOCO
|
node_modules/walk-back/test/test.js
|
<gh_stars>10-100
const TestRunner = require('test-runner')
const walkBack = require('../')
const a = require('assert')
const runner = new TestRunner()
runner.test('basic', function (t) {
const filename = walkBack(__dirname + '/fixture/subdir', 'file.txt')
a.ok(filename.search('walk-back/test/fixture/subdir/file.txt') > 0)
})
runner.test('basic2', function (t) {
const filename = walkBack(__dirname + '/fixture', 'file.txt')
a.ok(filename.search('walk-back/test/fixture/file.txt') > 0)
})
runner.test('not found', function (t) {
const filename = walkBack(__dirname + '/fixture', 'adskjfhladfn')
a.strictEqual(filename, null)
})
runner.test('relative path', function (t) {
const filename = walkBack('.', 'test/fixture/subdir/file.txt')
a.ok(filename && filename.search('walk-back/test/fixture/subdir/file.txt') > 0)
})
runner.test('relative path 2', function (t) {
const filename = walkBack('./test/fixture/subdir', 'file.txt')
a.ok(filename && filename.search('walk-back/test/fixture/subdir/file.txt') > 0)
})
runner.test('startPath doesn\'t exist', function (t) {
a.throws(function () {
walkBack('slfnavnkln', 'file.txt')
})
})
|
danielleconnolly/diirt
|
pvmanager/datasource-test/src/main/java/org/diirt/datasource/test/CountDownWriteFunction.java
|
<filename>pvmanager/datasource-test/src/main/java/org/diirt/datasource/test/CountDownWriteFunction.java
/**
* Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.datasource.test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.diirt.datasource.ExceptionHandler;
import org.diirt.util.time.TimeDuration;
/**
* Read listener to wait that a certain number of notifications.
*
* @author carcassi
*/
public class CountDownWriteFunction extends ExceptionHandler {
private volatile CountDownLatch latch;
private volatile Exception exception;
public CountDownWriteFunction(int count) {
latch = new CountDownLatch(count);
}
@Override
public void handleException(Exception esception) {
this.exception = esception;
latch.countDown();
}
/**
* Changes the count back to count.
*
* @param count new value for count
*/
public void resetCount(int count) {
latch = new CountDownLatch(count);
}
/**
* Current count.
*
* @return current count
*/
public int getCount() {
return (int) latch.getCount();
}
/**
* Waits that the listener count goes to zero.
*
* @param duration time to wait
* @return false if count didn't go to zero
* @throws InterruptedException if interrupted
*/
public boolean await(TimeDuration duration)
throws InterruptedException {
return latch.await(duration.toNanosLong(), TimeUnit.NANOSECONDS);
}
public Exception getException() {
return exception;
}
}
|
jchiatt/spectrum
|
src/helpers/signed-out-fallback.js
|
<reponame>jchiatt/spectrum<gh_stars>0
// @flow
// Render a component depending on a users authentication status
import React from 'react';
import { connect } from 'react-redux';
import AuthViewHandler from 'src/views/authViewHandler';
// This is the component that determines at render time what to do
const Switch = props => {
const { Component, FallbackComponent, currentUser, ...rest } = props;
return (
<AuthViewHandler>
{authed => {
if (!authed) {
return <FallbackComponent {...rest} />;
} else {
return <Component {...rest} />;
}
}}
</AuthViewHandler>
);
};
// Connect that component to the Redux state
const ConnectedSwitch = connect(
(state: *): * => ({
currentUser: state.users.currentUser,
})
)(Switch);
const signedOutFallback = (
Component: React$ComponentType<*>,
FallbackComponent: React$ComponentType<*>
) => {
return (props: *) => (
<ConnectedSwitch
{...props}
FallbackComponent={FallbackComponent}
Component={Component}
/>
);
};
export default signedOutFallback;
|
f4deb/cen-electronic
|
common/timer/delayTimer.h
|
<filename>common/timer/delayTimer.h
#ifndef DELAY_TIMER_H
#define DELAY_TIMER_H
#include <stdlib.h>
#include <stdbool.h>
#include "cenTimer.h"
Timer* timerDelayMark(void);
void timerDelayWaitMark(Timer* delayTimer, unsigned long delayMilliSeconds);
bool timerDelayTimeout(Timer* delayTimer, unsigned long delayMilliSeconds);
/**
* WARNING : This method MUST NOT be used inside a method raised by an interruption itself.
* If we would like to do something frequently, use State Machine, and only use this method
* inside the main method.
* Do a delay of milli Seconds based on a system delay timer which tends
* to be more precise than the cenDelay.h which raises some problem when some
* interruptions are raised because it longers and leads to an anormal delay
* @param delayMilliSeconds how much milliSeconds we wait
*/
void timerDelayMilliSeconds(unsigned long delayMilliSeconds);
/**
* Initialize a system delay timer used to be more precise than the
* cenDelay.h which raises some problem when some interruptions are raised
* because it longers and leads to an anormal delay.
* @return true if the delay is initialized properly, false else
*/
bool initSystemDelayTimer(void);
#endif
|
MBrassey/xscreensaver_BlueMatrix
|
hacks/glx/swim.c
|
<reponame>MBrassey/xscreensaver_BlueMatrix
/* atlantis --- Shows moving 3D sea animals */
#if 0
static const char sccsid[] = "@(#)swim.c 1.3 98/06/18 xlockmore";
#endif
/* Copyright (c) <NAME>, 1998. */
/*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation.
*
* This file is provided AS IS with no warranties of any kind. The author
* shall have no liability with respect to the infringement of copyrights,
* trade secrets or any patents by this file or any part thereof. In no
* event will the author be liable for any lost revenue or profits or
* other special, indirect and consequential damages.
*
* The original code for this mode was written by <NAME>
* as a demo for openGL programming.
*
* Porting it to xlock was possible by comparing the original Mesa's morph3d
* demo with it's ported version to xlock, so thanks for <NAME>
* (look at morph3d.c) for his indirect help.
*
* Thanks goes also to <NAME> for making it possible and inexpensive
* to use OpenGL at home.
*
* My e-mail address is <EMAIL>
*
* <NAME> (May-13-1998)
*
*/
/**
* (c) Copyright 1993, 1994, Silicon Graphics, Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(TM) is a trademark of Silicon Graphics, Inc.
*/
#ifdef STANDALONE
# include <math.h>
# include "xlockmoreI.h" /* from the xscreensaver distribution */
#else /* !STANDALONE */
# include "xlock.h" /* from the xlockmore distribution */
#endif /* !STANDALONE */
#ifdef USE_GL
#include "atlantis.h"
void
FishTransform(fishRec * fish)
{
glTranslatef(fish->y, fish->z, -fish->x);
glRotatef(-fish->psi, 0.0, 1.0, 0.0);
glRotatef(fish->theta, 1.0, 0.0, 0.0);
glRotatef(-fish->phi, 0.0, 0.0, 1.0);
}
void
WhalePilot(fishRec * fish, float whalespeed, Bool whaledir)
{
fish->phi = -20.0;
fish->theta = 0.0;
fish->psi += ((whaledir) ? -0.5 : 0.5);
fish->x += whalespeed * fish->v * cos(fish->psi / RAD) * cos(fish->theta / RAD);
fish->y += whalespeed * fish->v * sin(fish->psi / RAD) * cos(fish->theta / RAD);
fish->z += whalespeed * fish->v * sin(fish->theta / RAD);
}
void
SharkPilot(fishRec * fish, float sharkspeed)
{
float X, Y, Z, tpsi, ttheta, thetal;
fish->xt = 60000.0;
fish->yt = 0.0;
fish->zt = 0.0;
X = fish->xt - fish->x;
Y = fish->yt - fish->y;
Z = fish->zt - fish->z;
thetal = fish->theta;
ttheta = RAD * atan(Z / (sqrt(X * X + Y * Y)));
if (ttheta > fish->theta + 0.25) {
fish->theta += 0.5;
} else if (ttheta < fish->theta - 0.25) {
fish->theta -= 0.5;
}
if (fish->theta > 90.0) {
fish->theta = 90.0;
}
if (fish->theta < -90.0) {
fish->theta = -90.0;
}
fish->dtheta = fish->theta - thetal;
tpsi = RAD * atan2(Y, X);
fish->attack = 0;
if (fabs(tpsi - fish->psi) < 10.0) {
fish->attack = 1;
} else if (fabs(tpsi - fish->psi) < 45.0) {
if (fish->psi > tpsi) {
fish->psi -= 0.5;
if (fish->psi < -180.0) {
fish->psi += 360.0;
}
} else if (fish->psi < tpsi) {
fish->psi += 0.5;
if (fish->psi > 180.0) {
fish->psi -= 360.0;
}
}
} else {
if (NRAND(100) > 98) {
fish->sign = (fish->sign < 0 ? 1 : -1);
}
fish->psi += (fish->sign ? 1 : -1);
if (fish->psi > 180.0) {
fish->psi -= 360.0;
}
if (fish->psi < -180.0) {
fish->psi += 360.0;
}
}
if (fish->attack) {
if (fish->v < 1.1) {
fish->spurt = 1;
}
if (fish->spurt) {
fish->v += 0.2;
}
if (fish->v > 5.0) {
fish->spurt = 0;
}
if ((fish->v > 1.0) && (!fish->spurt)) {
fish->v -= 0.2;
}
} else {
if (!(NRAND(400)) && (!fish->spurt)) {
fish->spurt = 1;
}
if (fish->spurt) {
fish->v += 0.05;
}
if (fish->v > 3.0) {
fish->spurt = 0;
}
if ((fish->v > 1.0) && (!fish->spurt)) {
fish->v -= 0.05;
}
}
fish->x += sharkspeed * fish->v * cos(fish->psi / RAD) * cos(fish->theta / RAD);
fish->y += sharkspeed * fish->v * sin(fish->psi / RAD) * cos(fish->theta / RAD);
fish->z += sharkspeed * fish->v * sin(fish->theta / RAD);
}
void
SharkMiss(atlantisstruct * ap, int i)
{
int j;
float avoid, thetal;
float X, Y, Z, R;
for (j = 0; j < ap->num_sharks; j++) {
if (j != i) {
X = ap->sharks[j].x - ap->sharks[i].x;
Y = ap->sharks[j].y - ap->sharks[i].y;
Z = ap->sharks[j].z - ap->sharks[i].z;
R = sqrt(X * X + Y * Y + Z * Z);
avoid = 1.0;
thetal = ap->sharks[i].theta;
if (R < ap->sharksize) {
if (Z > 0.0) {
ap->sharks[i].theta -= avoid;
} else {
ap->sharks[i].theta += avoid;
}
}
ap->sharks[i].dtheta += (ap->sharks[i].theta - thetal);
}
}
}
#endif
|
zhengkaixing/kxmall
|
kxmall-data/src/main/java/com/kxmall/market/data/dto/InviteDTO.java
|
package com.kxmall.market.data.dto;
import com.kxmall.market.data.annotation.DtoDescription;
import com.kxmall.market.data.domain.SuperDO;
import com.kxmall.market.data.domain.UserDO;
import lombok.Data;
/**
* 邀请列表
*
* @author kaixin
*/
@Data
public class InviteDTO extends SuperDO {
@DtoDescription(description = "邀请人id")
private Long inviteId;
@DtoDescription(description = "被邀请人id")
private Long beinviteId;
@DtoDescription(description = "被邀请人ip地址")
private String beinviteIp;
@DtoDescription(description = "表示被邀请人是否正常0不正常1正常")
private Integer status;
@DtoDescription(description = "用户对象")
private UserDO userDO;
}
|
georgegillams/georgegillams.co.uk
|
src/containers/Work/SideProjects/Container.js
|
<filename>src/containers/Work/SideProjects/Container.js
import React from 'react';
import { cssModules } from '@george-gillams/components/helpers/cssModules';
import { Button } from '@george-gillams/components/Button';
import { Paragraph } from '@george-gillams/components/Paragraph';
import { Subsection } from '@george-gillams/components/Subsection';
import { Image } from '@george-gillams/components/Image';
import TextLink from 'components/common/TextLink';
import PageTitle from 'components/common/PageTitle';
import STYLES from './work-side-projects.scss';
import VPNWarningLight from './VPNWarning_light.png';
import VPNWarningDark from './VPNWarning_dark.png';
import SraLevelLight from './SraLevel_light.png';
import SraLevelDark from './SraLevel_dark.png';
const getClassName = cssModules(STYLES);
const WorkSideProjects = () => (
<PageTitle link={{ to: '/work', text: 'Work' }} name="Side projects">
<Subsection name="Backpack transpiled">
<Paragraph>
At Skyscanner, we publish{' '}
<TextLink href="https://backpack.github.io/" hrefExternal>
Backpack
</TextLink>{' '}
web libraries untranspiled, as several different packages.
<br />
<br />
backpack-transpiled is a single package, containing all the web components available in Backpack. Thanks to
modern code-splitting and tree-shaking techniques, it's possible to import a single component from this
package without negatively affecting bundle size.
<br />
<br />
Because backpack-transpiled is completely transpiled, there's no need to use{' '}
<TextLink hrefExternal href="https://www.npmjs.com/package/backpack-react-scripts">
backpack-react-scripts
</TextLink>
, or modify webpack config. It will work out of the box with a fresh create react app.
<br />
<Button
className={getClassName('work-side-projects__component')}
hrefExternal
href="https://github.com/georgegillams/backpack-transpiled/">
backpack-transpiled →
</Button>
</Paragraph>
</Subsection>
<Subsection name="VPN Video Checker">
<Paragraph>
While we're in lockdown, many of us are relying on video calls and VPNs to do our work. But video calls can
place a lot of strain on VPNs and streaming via a VPN often results in a flaky video call experience.
<br />
To remind members of my team to disconnect from the VPN when joining a video call, I created a small utility
that checks and notifies you whenever you're simultaneously on a call whilst connected to a VPN. It's
available to{' '}
<TextLink hrefExternal href="https://apps.apple.com/us/app/vpn-video-checker/id1509398961?ls=1">
download for free from the macOS App Store
</TextLink>
.
</Paragraph>
<Image
className={getClassName('work-side-projects__image')}
imgProps={{
alt: 'VPN Zoom warning notification',
}}
aspectX={462}
aspectY={122}
lightSrc={VPNWarningLight}
darkSrc={VPNWarningDark}
/>
</Subsection>
<Subsection name="Screen Reader Adventures">
<Paragraph>
Using VoiceOver on macOS is not trivial. The keyboard commands are not intuitive, so I created an online game
that gradually introduces new commands and VO concepts.
</Paragraph>
<Image
className={getClassName('work-side-projects__image')}
imgProps={{
alt: 'Screen Reader Adventures level',
}}
aspectX={1041}
aspectY={999}
lightSrc={SraLevelLight}
darkSrc={SraLevelDark}
/>
<Button
className={getClassName('work-side-projects__component')}
hrefExternal
href="https://www.screen-reader-adventures.com/">
Screen Reader Adventures →
</Button>
</Subsection>
<Subsection name="Browser scripts">
<Paragraph>
I automate pretty much everything I can, often in the form of browser-scripts. I have built several small
utilities that help me on a day to day basis, and they can be run in any browser via an extension such as{' '}
<TextLink hrefExternal href="https://www.tampermonkey.net/">
Tamper Monkey
</TextLink>
.
</Paragraph>
<br />
<Button
className={getClassName('work-side-projects__component')}
hrefExternal
href="https://github.com/georgegillams/browser-scripts/#browser-scripts">
Browser scripts →
</Button>
</Subsection>
{/* <Subsection name="Redux definitions">
<Paragraph>
After a while using Redux, I became frustrated with the
overly-verbose and repetitive nature of its components. I,
therefore, wrote some helpers to reduce the repetitiveness, and
eventually, they grew into a complete library for generating redux
components from a single source of truth. Because of the organic
way in which I built this from the ground up, the library is
completely interoperable with hand-coded redux components, meaning
that it can be adopted gradually in an existing codebase using
redux.
</Paragraph>
<br />
<Button
className={getClassName('pages__component--upper-margin')}
hrefExternal
href="https://github.com/georgegillams/redux-definitions/"
>
Check out redux-definitions on GitHub →
</Button>
</Subsection> */}
<Subsection name="Party Parrot">
<Paragraph>
As a developer and advocate for open source, having a contribution to the{' '}
<TextLink hrefExternal href="https://cultofthepartyparrot.com/">
official Party Parrot repo{' '}
</TextLink>{' '}
is a proud achievement.
</Paragraph>
<Image
aspectX={60}
aspectY={60}
style={{ width: '4rem' }}
lightSrc="https://cultofthepartyparrot.com/parrots/hd/opensourceparrot.gif"
darkSrc="https://cultofthepartyparrot.com/parrots/hd/opensourceparrot.gif"
imgProps={{ alt: 'Open-source party parrot' }}
/>
</Subsection>
</PageTitle>
);
export default WorkSideProjects;
|
blockspacer/chromium_base_conan
|
extensions/third_party/abseil-cpp/absl/random/uniform_int_distribution.h
|
<filename>extensions/third_party/abseil-cpp/absl/random/uniform_int_distribution.h<gh_stars>1-10
#pragma once
#include "absl/random/uniform_int_distribution.h"
|
billyfish/lib-gen
|
src/idl_writer.c
|
<reponame>billyfish/lib-gen<filename>src/idl_writer.c<gh_stars>0
#include <ctype.h>
#include <string.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/utility.h>
#include <exec/types.h>
#include "idl_writer.h"
#include "parameter.h"
#include "function_definition.h"
#include "debugging_utils.h"
#include "utils.h"
static BOOL WriteIDL (struct Writer *writer_p, struct List *function_definitions_p, CONST_STRPTR library_s, CONST_STRPTR prefix_s, const int32 version, const enum InterfaceFlag flag, BPTR out_p);
static CONST_STRPTR GetIDLWriterFileSuffix (struct Writer *writer_p);
static BOOL WriteIDLHeader (BPTR out_p, CONST CONST_STRPTR library_s, CONST CONST_STRPTR prefix_s, const int32 version, const enum InterfaceFlag flag, struct List *function_definitions_list_p);
static BOOL WriteIDLFunctionDefinition (BPTR out_p, const struct FunctionDefinition * const fd_p);
static BOOL WriteIDLParameter (BPTR out_p, const struct Parameter * const param_p);
static BOOL WriteIDLDefaultFunctions (BPTR out_p);
static BOOL WriteIDLFooter (BPTR out_p);
static BOOL WriteIDLFunctionDefinitionsList (BPTR out_p, struct List * const function_definitions_list_p);
static CONST_STRPTR GetIDLWriterFileSuffix (struct Writer *writer_p)
{
ENTER ();
LEAVE ();
return ".xml";
}
Writer *AllocateIDLWriter (void)
{
ENTER ();
IDLWriter *idl_p = (IDLWriter *) IExec->AllocVecTags (sizeof (IDLWriter), TAG_DONE);
if (idl_p)
{
idl_p -> iw_base_writer.wr_write_function_definitions_list_fn = WriteIDL;
idl_p -> iw_base_writer.wr_get_file_suffix_fn = GetIDLWriterFileSuffix;
}
LEAVE ();
return ((Writer *) idl_p);
}
void FreeIDLWriter (Writer *writer_p)
{
ENTER ();
IDLWriter *idl_p = (IDLWriter *) writer_p;
IExec->FreeVec (idl_p);
LEAVE ();
}
static BOOL WriteIDL (struct Writer *writer_p, struct List *function_definitions_p, CONST_STRPTR library_s, CONST_STRPTR prefix_s, const int32 version, const enum InterfaceFlag flag, BPTR out_p)
{
ENTER ();
BOOL success_flag = FALSE;
DB (KPRINTF ("%s %ld - Entering WriteIDL", __FILE__, __LINE__));
if (WriteIDLHeader (out_p, library_s, prefix_s, version, flag, function_definitions_p))
{
if (WriteIDLDefaultFunctions (out_p))
{
if (WriteIDLFunctionDefinitionsList (out_p, function_definitions_p))
{
if (WriteIDLFooter (out_p))
{
success_flag = TRUE;
}
else
{
DB (KPRINTF ("%s %ld - Failed to write idl footer", __FILE__, __LINE__));
}
}
else
{
DB (KPRINTF ("%s %ld - Failed to write idl header definitions\n", __FILE__, __LINE__));
}
}
else
{
DB (KPRINTF ("%s %ld - Failed to write idl default_functions\n", __FILE__, __LINE__));
}
} /* if (WriteIDLHeader (name_s, basename_s, struct_name_s, prefix_s)) */
else
{
DB (KPRINTF ("%s %ld - Failed to write idl header\n", __FILE__, __LINE__));
}
DB (KPRINTF ("%s %ld - Exiting WriteIDL %ld", __FILE__, __LINE__, success_flag));
LEAVE ();
return success_flag;
}
static BOOL WriteIDLHeader (BPTR out_p, CONST CONST_STRPTR library_s, CONST CONST_STRPTR prefix_s, const int32 version, const enum InterfaceFlag flag, struct List *function_definitions_p)
{
ENTER ();
BOOL success_flag = FALSE;
if (IDOS->FPrintf (out_p, "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n") >= 0)
{
if (IDOS->FPrintf (out_p, "<!DOCTYPE library SYSTEM \"library.dtd\">\n") >= 0)
{
if (library_s)
{
STRPTR capitalized_library_s = GetCapitalizedString (library_s);
if (capitalized_library_s)
{
if (IDOS->FPrintf (out_p, "<library name=\"%s\" basename=\"%sBase\" openname=\"%s.library\">\n", library_s, capitalized_library_s, library_s) >= 0)
{
CONST_STRPTR flags_s = NULL;
switch (flag)
{
case IF_PRIVATE:
flags_s = "private";
break;
case IF_PROTECTED:
flags_s = "protected";
break;
case IF_PUBLIC:
default:
flags_s = "none";
break;
}
if (WriteFunctionDefinitionListIncludes (out_p, function_definitions_p, "\t<include>", "</include>\n"))
{
if (IDOS->FPrintf (out_p, "\n\t<interface name=\"main\" version=\"%lu.0\" flags=\"%s\" prefix=\"%s\" struct=\"%sIFace\" asmprefix=\"I%s\" global=\"I%s\">\n",
version, flags_s, prefix_s, capitalized_library_s, capitalized_library_s, capitalized_library_s) >= 0)
{
success_flag = TRUE;
}
}
}
} /* if (capitalized_library_s) */
} /* if (library_s) */
}
}
LEAVE ();
return success_flag;
}
static BOOL WriteIDLFunctionDefinitionsList (BPTR out_p, struct List * const function_definitions_list_p)
{
ENTER ();
BOOL success_flag = TRUE;
struct FunctionDefinitionNode *node_p = (struct FunctionDefinitionNode *) IExec->GetHead (function_definitions_list_p);
while ((node_p != NULL) && success_flag)
{
if (WriteIDLFunctionDefinition (out_p, node_p -> fdn_function_def_p))
{
node_p = (struct FunctionDefinitionNode *) IExec->GetSucc ((struct Node *) node_p);
}
else
{
success_flag = FALSE;
}
}
LEAVE ();
return success_flag;
}
static BOOL WriteIDLFunctionDefinition (BPTR out_p, const struct FunctionDefinition * const fd_p)
{
ENTER ();
BOOL success_flag = FALSE;
if (IDOS->FPrintf (out_p, "\n\t\t<!-- %s:%ld -->\n", fd_p -> fd_header_filename_s, fd_p -> fd_line_number) >= 0)
{
if (IDOS->FPrintf (out_p, "\t\t<method name=\"%s\" result=\"%s\">\n", fd_p -> fd_definition_p -> pa_name_s, fd_p -> fd_definition_p -> pa_type_s) >= 0)
{
if (fd_p -> fd_args_p)
{
struct ParameterNode *node_p = (struct ParameterNode *) IExec->GetHead (fd_p -> fd_args_p);
success_flag = TRUE;
while (node_p && success_flag)
{
if (WriteIDLParameter (out_p, node_p -> pn_param_p))
{
node_p = (struct ParameterNode *) IExec->GetSucc ((struct Node *) node_p);
}
else
{
success_flag = FALSE;
}
}
if (success_flag)
{
success_flag = (IDOS->FPrintf (out_p, "\t\t</method>\n") >= 0);
}
}
} /* if (IDOS->FPrintf (out_p, "\t\t<method name=\"%s\" result=\"%s\">\n", fd_p -> fd_definition_p -> pa_name_s, fd_p -> fd_definition_p -> pa_type_s) >= 0) */
} /* if (IDOS->FPrintf (out_p, "\n\t\t<!-- %s:%ld -->\n", fd_p -> fd_filename_s, fd_p -> fd_line_number) >= 0) */
LEAVE ();
return success_flag;
}
static BOOL WriteIDLParameter (BPTR out_p, const struct Parameter * const param_p)
{
ENTER ();
BOOL success_flag = TRUE;
if (!IsVoidParameter (param_p))
{
success_flag = (IDOS->FPrintf (out_p, "\t\t\t<arg name=\"%s\" type=\"%s\" />\n", param_p -> pa_name_s, param_p -> pa_type_s) >= 0);
}
LEAVE ();
return success_flag;
}
static BOOL WriteIDLDefaultFunctions (BPTR out_p)
{
BOOL success_flag = FALSE;
ENTER ();
if (IDOS->FPrintf (out_p, "\t\t<method name=\"Obtain\" result=\"uint32\"></method>\n") >= 0)
{
if (IDOS->FPrintf (out_p, "\t\t<method name=\"Release\" result=\"uint32\"></method>\n") >= 0)
{
if (IDOS->FPrintf (out_p, "\t\t<method name=\"Expunge\" result=\"void\" status=\"unimplemented\"></method>\n") >= 0)
{
if (IDOS->FPrintf (out_p, "\t\t<method name=\"Clone\" result=\"struct Interface *\" status=\"unimplemented\"></method>\n") >= 0)
{
success_flag = TRUE;
}
}
}
}
LEAVE ();
return success_flag;
}
static BOOL WriteIDLFooter (BPTR out_p)
{
ENTER ();
LEAVE ();
return (IDOS->FPrintf (out_p, "\t</interface>\n</library>\n") >= 0);
}
|
mhazankin/vic
|
vendor/github.com/hashicorp/consul/api/lock_test.go
|
<filename>vendor/github.com/hashicorp/consul/api/lock_test.go
package api
import (
"log"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"sync"
"testing"
"time"
)
func TestLock_LockUnlock(t *testing.T) {
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
lock, err := c.LockKey("test/lock")
if err != nil {
t.Fatalf("err: %v", err)
}
// Initial unlock should fail
err = lock.Unlock()
if err != ErrLockNotHeld {
t.Fatalf("err: %v", err)
}
// Should work
leaderCh, err := lock.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if leaderCh == nil {
t.Fatalf("not leader")
}
// Double lock should fail
_, err = lock.Lock(nil)
if err != ErrLockHeld {
t.Fatalf("err: %v", err)
}
// Should be leader
select {
case <-leaderCh:
t.Fatalf("should be leader")
default:
}
// Initial unlock should work
err = lock.Unlock()
if err != nil {
t.Fatalf("err: %v", err)
}
// Double unlock should fail
err = lock.Unlock()
if err != ErrLockNotHeld {
t.Fatalf("err: %v", err)
}
// Should lose leadership
select {
case <-leaderCh:
case <-time.After(time.Second):
t.Fatalf("should not be leader")
}
}
func TestLock_ForceInvalidate(t *testing.T) {
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
lock, err := c.LockKey("test/lock")
if err != nil {
t.Fatalf("err: %v", err)
}
// Should work
leaderCh, err := lock.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if leaderCh == nil {
t.Fatalf("not leader")
}
defer lock.Unlock()
go func() {
// Nuke the session, simulator an operator invalidation
// or a health check failure
session := c.Session()
session.Destroy(lock.lockSession, nil)
}()
// Should loose leadership
select {
case <-leaderCh:
case <-time.After(time.Second):
t.Fatalf("should not be leader")
}
}
func TestLock_DeleteKey(t *testing.T) {
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
// This uncovered some issues around special-case handling of low index
// numbers where it would work with a low number but fail for higher
// ones, so we loop this a bit to sweep the index up out of that
// territory.
for i := 0; i < 10; i++ {
func() {
lock, err := c.LockKey("test/lock")
if err != nil {
t.Fatalf("err: %v", err)
}
// Should work
leaderCh, err := lock.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if leaderCh == nil {
t.Fatalf("not leader")
}
defer lock.Unlock()
go func() {
// Nuke the key, simulate an operator intervention
kv := c.KV()
kv.Delete("test/lock", nil)
}()
// Should loose leadership
select {
case <-leaderCh:
case <-time.After(time.Second):
t.Fatalf("should not be leader")
}
}()
}
}
func TestLock_Contend(t *testing.T) {
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
wg := &sync.WaitGroup{}
acquired := make([]bool, 3)
for idx := range acquired {
wg.Add(1)
go func(idx int) {
defer wg.Done()
lock, err := c.LockKey("test/lock")
if err != nil {
t.Fatalf("err: %v", err)
}
// Should work eventually, will contend
leaderCh, err := lock.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if leaderCh == nil {
t.Fatalf("not leader")
}
defer lock.Unlock()
log.Printf("Contender %d acquired", idx)
// Set acquired and then leave
acquired[idx] = true
}(idx)
}
// Wait for termination
doneCh := make(chan struct{})
go func() {
wg.Wait()
close(doneCh)
}()
// Wait for everybody to get a turn
select {
case <-doneCh:
case <-time.After(3 * DefaultLockRetryTime):
t.Fatalf("timeout")
}
for idx, did := range acquired {
if !did {
t.Fatalf("contender %d never acquired", idx)
}
}
}
func TestLock_Destroy(t *testing.T) {
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
lock, err := c.LockKey("test/lock")
if err != nil {
t.Fatalf("err: %v", err)
}
// Should work
leaderCh, err := lock.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if leaderCh == nil {
t.Fatalf("not leader")
}
// Destroy should fail
if err := lock.Destroy(); err != ErrLockHeld {
t.Fatalf("err: %v", err)
}
// Should be able to release
err = lock.Unlock()
if err != nil {
t.Fatalf("err: %v", err)
}
// Acquire with a different lock
l2, err := c.LockKey("test/lock")
if err != nil {
t.Fatalf("err: %v", err)
}
// Should work
leaderCh, err = l2.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if leaderCh == nil {
t.Fatalf("not leader")
}
// Destroy should still fail
if err := lock.Destroy(); err != ErrLockInUse {
t.Fatalf("err: %v", err)
}
// Should release
err = l2.Unlock()
if err != nil {
t.Fatalf("err: %v", err)
}
// Destroy should work
err = lock.Destroy()
if err != nil {
t.Fatalf("err: %v", err)
}
// Double destroy should work
err = l2.Destroy()
if err != nil {
t.Fatalf("err: %v", err)
}
}
func TestLock_Conflict(t *testing.T) {
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
sema, err := c.SemaphorePrefix("test/lock/", 2)
if err != nil {
t.Fatalf("err: %v", err)
}
// Should work
lockCh, err := sema.Acquire(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if lockCh == nil {
t.Fatalf("not hold")
}
defer sema.Release()
lock, err := c.LockKey("test/lock/.lock")
if err != nil {
t.Fatalf("err: %v", err)
}
// Should conflict with semaphore
_, err = lock.Lock(nil)
if err != ErrLockConflict {
t.Fatalf("err: %v", err)
}
// Should conflict with semaphore
err = lock.Destroy()
if err != ErrLockConflict {
t.Fatalf("err: %v", err)
}
}
func TestLock_ReclaimLock(t *testing.T) {
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
session, _, err := c.Session().Create(&SessionEntry{}, nil)
if err != nil {
t.Fatalf("err: %v", err)
}
lock, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session})
if err != nil {
t.Fatalf("err: %v", err)
}
// Should work
leaderCh, err := lock.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if leaderCh == nil {
t.Fatalf("not leader")
}
defer lock.Unlock()
l2, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session})
if err != nil {
t.Fatalf("err: %v", err)
}
reclaimed := make(chan (<-chan struct{}), 1)
go func() {
l2Ch, err := l2.Lock(nil)
if err != nil {
t.Fatalf("not locked: %v", err)
}
reclaimed <- l2Ch
}()
// Should reclaim the lock
var leader2Ch <-chan struct{}
select {
case leader2Ch = <-reclaimed:
case <-time.After(time.Second):
t.Fatalf("should have locked")
}
// unlock should work
err = l2.Unlock()
if err != nil {
t.Fatalf("err: %v", err)
}
//Both locks should see the unlock
select {
case <-leader2Ch:
case <-time.After(time.Second):
t.Fatalf("should not be leader")
}
select {
case <-leaderCh:
case <-time.After(time.Second):
t.Fatalf("should not be leader")
}
}
func TestLock_MonitorRetry(t *testing.T) {
t.Parallel()
raw, s := makeClient(t)
defer s.Stop()
// Set up a server that always responds with 500 errors.
failer := func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(500)
}
outage := httptest.NewServer(http.HandlerFunc(failer))
defer outage.Close()
// Set up a reverse proxy that will send some requests to the
// 500 server and pass everything else through to the real Consul
// server.
var mutex sync.Mutex
errors := 0
director := func(req *http.Request) {
mutex.Lock()
defer mutex.Unlock()
req.URL.Scheme = "http"
if errors > 0 && req.Method == "GET" && strings.Contains(req.URL.Path, "/v1/kv/test/lock") {
req.URL.Host = outage.URL[7:] // Strip off "http://".
errors--
} else {
req.URL.Host = raw.config.Address
}
}
proxy := httptest.NewServer(&httputil.ReverseProxy{Director: director})
defer proxy.Close()
// Make another client that points at the proxy instead of the real
// Consul server.
config := raw.config
config.Address = proxy.URL[7:] // Strip off "http://".
c, err := NewClient(&config)
if err != nil {
t.Fatalf("err: %v", err)
}
// Set up a lock with retries enabled.
opts := &LockOptions{
Key: "test/lock",
SessionTTL: "60s",
MonitorRetries: 3,
}
lock, err := c.LockOpts(opts)
if err != nil {
t.Fatalf("err: %v", err)
}
// Make sure the default got set.
if lock.opts.MonitorRetryTime != DefaultMonitorRetryTime {
t.Fatalf("bad: %d", lock.opts.MonitorRetryTime)
}
// Now set a custom time for the test.
opts.MonitorRetryTime = 250 * time.Millisecond
lock, err = c.LockOpts(opts)
if err != nil {
t.Fatalf("err: %v", err)
}
if lock.opts.MonitorRetryTime != 250*time.Millisecond {
t.Fatalf("bad: %d", lock.opts.MonitorRetryTime)
}
// Should get the lock.
leaderCh, err := lock.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if leaderCh == nil {
t.Fatalf("not leader")
}
// Poke the key using the raw client to force the monitor to wake up
// and check the lock again. This time we will return errors for some
// of the responses.
mutex.Lock()
errors = 2
mutex.Unlock()
pair, _, err := raw.KV().Get("test/lock", &QueryOptions{})
if err != nil {
t.Fatalf("err: %v", err)
}
if _, err := raw.KV().Put(pair, &WriteOptions{}); err != nil {
t.Fatalf("err: %v", err)
}
time.Sleep(5 * opts.MonitorRetryTime)
// Should still be the leader.
select {
case <-leaderCh:
t.Fatalf("should be leader")
default:
}
// Now return an overwhelming number of errors.
mutex.Lock()
errors = 10
mutex.Unlock()
if _, err := raw.KV().Put(pair, &WriteOptions{}); err != nil {
t.Fatalf("err: %v", err)
}
time.Sleep(5 * opts.MonitorRetryTime)
// Should lose leadership.
select {
case <-leaderCh:
case <-time.After(time.Second):
t.Fatalf("should not be leader")
}
}
func TestLock_OneShot(t *testing.T) {
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
// Set up a lock as a one-shot.
opts := &LockOptions{
Key: "test/lock",
LockTryOnce: true,
}
lock, err := c.LockOpts(opts)
if err != nil {
t.Fatalf("err: %v", err)
}
// Make sure the default got set.
if lock.opts.LockWaitTime != DefaultLockWaitTime {
t.Fatalf("bad: %d", lock.opts.LockWaitTime)
}
// Now set a custom time for the test.
opts.LockWaitTime = 250 * time.Millisecond
lock, err = c.LockOpts(opts)
if err != nil {
t.Fatalf("err: %v", err)
}
if lock.opts.LockWaitTime != 250*time.Millisecond {
t.Fatalf("bad: %d", lock.opts.LockWaitTime)
}
// Should get the lock.
ch, err := lock.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if ch == nil {
t.Fatalf("not leader")
}
// Now try with another session.
contender, err := c.LockOpts(opts)
if err != nil {
t.Fatalf("err: %v", err)
}
start := time.Now()
ch, err = contender.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if ch != nil {
t.Fatalf("should not be leader")
}
diff := time.Now().Sub(start)
if diff < contender.opts.LockWaitTime || diff > 2*contender.opts.LockWaitTime {
t.Fatalf("time out of bounds: %9.6f", diff.Seconds())
}
// Unlock and then make sure the contender can get it.
if err := lock.Unlock(); err != nil {
t.Fatalf("err: %v", err)
}
ch, err = contender.Lock(nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if ch == nil {
t.Fatalf("should be leader")
}
}
|
snkmr/shirasagi
|
app/jobs/gws/history_archive_job.rb
|
class Gws::HistoryArchiveJob < Gws::ApplicationJob
include Job::Gws::TaskFilter
include SS::HistoryArchiveBase
self.task_name = 'gws:history_archive'
class << self
def select_histories_to_archive(site, now = Time.zone.now)
save_term = site.effective_log_save_days.days
Gws::History.site(site).lt(created: threshold_day(now, save_term))
end
def histories_to_archive?(site, now = Time.zone.now)
select_histories_to_archive(site, now).present?
end
end
private
def select_histories
@histories = self.class.select_histories_to_archive(site)
end
def put_histories
@csv_generator = Gws::HistoryCsv.new(cur_site: site)
all_ids = @histories.order_by(created: 1).pluck(:id)
all_ids.each_slice(100) do |ids|
Gws::History.in(id: ids).order_by(created: 1).to_a.each do |history|
file = to_archive_file(history)
append_file(file, history)
end
end
@last_open_file_handle.close if @last_open_file_handle
@last_open_file = nil
@last_open_file_handle = nil
end
def create_empty_archive_file(name, filename, &block)
Gws::HistoryArchiveFile.create_empty!(cur_site: site, name: name, filename: filename, content_type: 'application/zip', &block)
end
end
|
wuzhuobin/QvtkProject
|
Src/Data/QvtkNeuralTube.cpp
|
// me
#include "QvtkNeuralTube.h"
//vtk
#include <vtkTubeFilter.h>
#include <vtkLineSource.h>
#include <vtkPolyData.h>
#include <vtkPassArrays.h>
#include <vtkTransform.h>
// qt
#include <QDomElement>
namespace Q {
namespace vtk {
Q_VTK_DATA_CPP(NeuralTube);
NeuralTube::NeuralTube()
:m_intermediatePoint{ 0,0,0 }
{
this->m_lineSource = vtkLineSource::New();
this->m_lineSource->SetResolution(1);
this->m_tubeFilter = vtkTubeFilter::New();
this->m_tubeFilter->SetInputConnection(this->m_lineSource->GetOutputPort());
this->m_tubeFilter->SetCapping(true);
this->m_tubeFilter->SetRadius(0);
this->m_passArrays = vtkPassArrays::New();
this->m_passArrays->SetInputConnection(this->m_tubeFilter->GetOutputPort());
this->m_passArrays->SetRemoveArrays(false);
this->m_passArrays->SetUseFieldTypes(true);
this->m_passArrays->AddFieldType(vtkDataObject::FIELD);
this->m_passArrays->AddFieldType(vtkDataObject::POINT);
this->m_passArrays->AddFieldType(vtkDataObject::CELL);
}
NeuralTube::~NeuralTube()
{
this->m_lineSource->Delete();
this->m_tubeFilter->Delete();
this->m_passArrays->Delete();
}
void NeuralTube::readXML(const QDomElement & xml, QString directoryPath)
{
PolyData::readXML(xml, directoryPath);
this->setTubeRadius(xml.attribute(K.TubeRadius).toDouble());
this->setTubeLength(xml.attribute(K.TubeLength).toDouble());
NeuralTube::readArray<double>(K.IntermediatePoint, xml, this->m_intermediatePoint, 3);
NeuralTube::readArray<double>(K.EndPoint, xml, this->m_lineSource->GetPoint2(), 3);
}
void NeuralTube::writeXML(QDomElement & xml, QString directoryPath) const
{
PolyData::writeXML(xml, directoryPath);
xml.setAttribute(K.TubeRadius, this->getTubeRadius());
xml.setAttribute(K.TubeLength, this->getTubeLength());
NeuralTube::writeArray<double>(K.IntermediatePoint, xml, this->getIntermediatePoint(), 3);
NeuralTube::writeArray<double>(K.EndPoint, xml, this->getEndPoint(), 3);
}
bool NeuralTube::readData(QString rootDirectory)
{
if (rootDirectory.isEmpty()) {
return PolyData::readData(rootDirectory);
}
else {
double vector[3];
vtkMath::Subtract(const_cast<const NeuralTube*>(this)->getIntermediatePoint(), const_cast<const NeuralTube*>(this)->getEndPoint(), vector);
vtkMath::Normalize(vector);
double vector_IE[3] = { -vector[0], -vector[1], -vector[2] };
double rotation[3];
double z_axis_down[3] = { 0, 0, -1 };
vtkMath::Cross(z_axis_down, vector_IE, rotation);
vtkMath::Normalize(rotation);
double angleInRadius = vtkMath::AngleBetweenVectors(z_axis_down, vector_IE);
vtkMath::MultiplyScalar(vector, this->getTubeLength());
vtkMath::Add(const_cast<const NeuralTube*>(this)->getEndPoint(), vector, vector);
this->m_lineSource->SetPoint1(vector);
vtkSmartPointer<vtkTransform> transform =
vtkSmartPointer<vtkTransform>::New();
transform->Identity();
transform->PostMultiply();
transform->RotateWXYZ(vtkMath::DegreesFromRadians(angleInRadius), rotation);
transform->Translate(vector);
transform->GetMatrix(this->getAdditionalMatrix());
this->m_lineSource->Update();
int sides = this->getTubeRadius() / 1 + 10;
this->m_tubeFilter->SetNumberOfSides(sides);
this->m_tubeFilter->Update();
this->m_passArrays->Update();
this->getPolyData()->ShallowCopy(this->m_passArrays->GetOutput());
return true;
}
}
double NeuralTube::getTubeRadius() const
{
return this->m_tubeFilter->GetRadius();
}
const double * NeuralTube::getEndPoint() const
{
return this->m_lineSource->GetPoint2();
}
QVariantList NeuralTube::getEndPoint()
{
return QVariantList{const_cast<const NeuralTube*>(this)->getEndPoint()[0], const_cast<const NeuralTube*>(this)->getEndPoint()[1], const_cast<const NeuralTube*>(this)->getEndPoint()[2]};
}
void NeuralTube::setTubeLength(double length)
{
this->m_tubeLength = length;
this->readData("...");
emit this->tubeLengthChanged(length);
}
void NeuralTube::setTubeRadius(double radius)
{
this->m_tubeFilter->SetRadius(radius);
this->readData("...");
emit this->tubeRadiusChanged(radius);
}
void NeuralTube::setIntermediatePoint(double x, double y, double z)
{
this->m_intermediatePoint[0] = x;
this->m_intermediatePoint[1] = y;
this->m_intermediatePoint[2] = z;
this->readData("...");
emit this->intermediatePointChanged(this->getIntermediatePoint());
emit this->intermediatePointChanged(this->m_intermediatePoint);
}
void NeuralTube::setEndPoint(double x, double y, double z)
{
this->m_lineSource->SetPoint2(x, y, z);
this->readData("...");
emit this->endPointChanged(this->getEndPoint());
emit this->endPointChanged(const_cast<const NeuralTube*>(this)->getEndPoint());
}
}
}
|
robbykraft/SVG
|
tests/core.coordinates.test.js
|
const SVG = require("../svg");
test("coordinates, two points", () => {
SVG.core.coordinates(1, 2, 3, 4)
.forEach((n, i) => expect(n).toBe([1,2,3,4][i]));
SVG.core.coordinates([1, 2], [3, 4])
.forEach((n, i) => expect(n).toBe([1,2,3,4][i]));
SVG.core.coordinates([1, 2, 3], [4, 5, 6])
.forEach((n, i) => expect(n).toBe([1,2,4,5][i]));
SVG.core.coordinates([1], [2])
.forEach((n, i) => expect(n).toBe([1, undefined, 2, undefined][i]));
});
test("coordinates, not two points", () => {
expect(SVG.core.coordinates().length).toBe(0);
expect(SVG.core.coordinates([]).length).toBe(0);
expect(SVG.core.coordinates([[]]).length).toBe(0);
expect(SVG.core.coordinates([], []).length).toBe(0);
SVG.core.coordinates([1,2], [3,4], [5,6])
.forEach((n, i) => expect(n).toBe([1, 2, 3, 4, 5, 6][i]));
})
|
MarginC/kame
|
freebsd5/sys/boot/ofw/common/main.c
|
<filename>freebsd5/sys/boot/ofw/common/main.c<gh_stars>10-100
/*-
* Copyright (c) 2000 <NAME> <<EMAIL>>
* Copyright (c) 2000 <NAME> <<EMAIL>>
* All rights reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHOR 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.
*
* $FreeBSD: src/sys/boot/ofw/common/main.c,v 1.3 2002/11/10 19:17:35 jake Exp $
*/
#include <stand.h>
#include "openfirm.h"
#include "libofw.h"
#include "bootstrap.h"
struct arch_switch archsw; /* MI/MD interface boundary */
extern char end[];
extern char bootprog_name[];
extern char bootprog_rev[];
extern char bootprog_date[];
extern char bootprog_maker[];
phandle_t chosen;
#define HEAP_SIZE 0x40000
void
init_heap(void)
{
void *base;
if ((base = ofw_alloc_heap(HEAP_SIZE)) == (void *)0xffffffff) {
printf("Heap memory claim failed!\n");
OF_enter();
}
setheap(base, base + (HEAP_SIZE / sizeof(base)));
}
uint32_t
memsize(void)
{
ihandle_t meminstance;
phandle_t memory;
struct ofw_reg reg;
OF_getprop(chosen, "memory", &meminstance, sizeof(meminstance));
memory = OF_instance_to_package(meminstance);
OF_getprop(memory, "reg", ®, sizeof(reg));
return (reg.size);
}
int
main(int (*openfirm)(void *))
{
int i;
char bootpath[64];
char *ch;
/*
* Initalise the OpenFirmware routines by giving them the entry point.
*/
OF_init(openfirm);
chosen = OF_finddevice("/chosen");
/*
* Set up console.
*/
cons_probe();
/*
* Initialise the heap as early as possible. Once this is done,
* alloc() is usable. The stack is buried inside us, so this is
* safe.
*/
init_heap();
/*
* Initialise the block cache
*/
bcache_init(32, 512); /* 16k XXX tune this */
/*
* March through the device switch probing for things.
*/
for (i = 0; devsw[i] != NULL; i++)
if (devsw[i]->dv_init != NULL)
(devsw[i]->dv_init)();
printf("\n");
printf("%s, Revision %s\n", bootprog_name, bootprog_rev);
printf("(%s, %s)\n", bootprog_maker, bootprog_date);
printf("Memory: %dKB\n", memsize() / 1024);
OF_getprop(chosen, "bootpath", bootpath, 64);
ch = index(bootpath, ':');
*ch = '\0';
printf("Booted from: %s\n", bootpath);
printf("\n");
env_setenv("currdev", EV_VOLATILE, bootpath,
ofw_setcurrdev, env_nounset);
env_setenv("loaddev", EV_VOLATILE, bootpath, env_noset,
env_nounset);
setenv("LINES", "24", 1); /* optional */
archsw.arch_getdev = ofw_getdev;
archsw.arch_copyin = ofw_copyin;
archsw.arch_copyout = ofw_copyout;
archsw.arch_readin = ofw_readin;
archsw.arch_autoload = ofw_autoload;
interact(); /* doesn't return */
OF_exit();
return 0;
}
COMMAND_SET(halt, "halt", "halt the system", command_halt);
static int
command_halt(int argc, char *argv[])
{
OF_exit();
return (CMD_OK);
}
COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
int
command_memmap(int argc, char **argv)
{
ofw_memmap();
return (CMD_OK);
}
|
antoniobertilpaiva/cert
|
ejb-in-ear/ejb/src/main/java/com/criticalsoftware/certitools/entities/sm/EmergencyUser.java
|
<gh_stars>0
package com.criticalsoftware.certitools.entities.sm;
import com.criticalsoftware.certitools.entities.Contract;
import javax.persistence.*;
/**
* Emergency User Entity
*
* @author miseabra
* @version $Revision$
*/
@SuppressWarnings("UnusedDeclaration")
@Entity
@Table(name = "sm_emergencyuser")
public class EmergencyUser {
@Id
@SequenceGenerator(name = "EMERGENCY_USER_ID_GENERATOR", sequenceName = "sm_emergencyuser_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EMERGENCY_USER_ID_GENERATOR")
private Long id;
private String name;
private String email;
@ManyToOne(fetch = FetchType.LAZY)
private Contract contract;
private Boolean deleted = false;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}
|
ctm/executor
|
src/config/front-ends/nextstep/HFS_XFer/helper.c
|
<filename>src/config/front-ends/nextstep/HFS_XFer/helper.c
#if defined(OUTDATEDCODE)
/*
* TODO: better support for read-only floppies
*/
#include "rsys/common.h"
#include "OSUtil.h"
#include "FileMgr.h"
#include "myhfs.h"
#include <string.h>
#include "SegmentLdr.h"
#include "xbar.h"
#include "ToolboxEvent.h"
#if defined(UNIX)
#include <sys/file.h>
#include <nextdev/disk.h>
#include <nextdev/fd_extern.h>
#include "fs.h"
#include <assert.h>
#define BIGBLOCK (20L * 1024)
#define NBIGBLOCKS 144 /* enough for an ED disk */
static char buf[NBIGBLOCKS * BIGBLOCK];
static char readmap[NBIGBLOCKS];
static char writemap[NBIGBLOCKS];
LONGINT floppyfd = -1; /* should be static */
PUBLIC OSErr updatefloppy( void )
{
OSErr err;
INTEGER i;
LONGINT offset;
err = noErr;
for (i = 0; i < NBIGBLOCKS; ++i) {
if (writemap[i]) {
offset = i * BIGBLOCK;
if (lseek(floppyfd, offset, L_SET) < 0 ||
write(floppyfd, buf+offset, BIGBLOCK) != BIGBLOCK)
err = ioErr;
}
}
return err;
}
PUBLIC OSErr ejectfloppy( void )
{
OSErr err;
err = noErr;
if (floppyfd != -1 && ioctl(floppyfd, DKIOCEJECT, (char *) 0) < 0) {
fprintf(stderr, "couldn't eject disk\n");
err = ioErr;
} else {
close(floppyfd);
floppyfd = -1;
}
return err;
}
PRIVATE void OurClose( void )
{
ParamBlockRec pb;
pb.ioParam.ioVRefNum = 5;
pb.ioParam.ioNamePtr = 0;
myPBUnmountVol((volumeParam *) &pb);
updatefloppy();
ejectfloppy();
}
PUBLIC void openfloppy( const char *dname )
{
ParamBlockRec pb;
extern long pipefd[2];
struct fd_ioreq req;
LONGINT dir;
HVCB *vcbp;
BOOLEAN writelocked;
char savec;
OSErr myPBMountVol(volumeParam *pb);
extern void (*ROMlib_slimyclosehack)(void);
bzero(readmap, (size_t) sizeof(readmap));
bzero(writemap, (size_t) sizeof(writemap));
if ((floppyfd = open(dname, O_RDWR|O_EXCL)) < 0) {
if (pipefd[1] != -1)
write(pipefd[1], dname, strlen(dname)+1);
fprintf(stderr, "can't open %s\n", dname);
} else {
if (pipefd[1] != -1)
write(pipefd[1], dname, strlen(dname)+1);
pb.ioParam.ioVRefNum = 5;
myPBMountVol((volumeParam *) &pb);
writelocked = FALSE;
if (dname[6] == 'f') { /* counting on /dev/rfd?b */
bzero(&req, sizeof(req));
req.command = FDCMD_GET_STATUS;
req.drive_stat.write_prot = 0;
if (ioctl(floppyfd, FDIOCREQ, &req) < 0)
printf("IOCREQ failed %d\n", errno);
if (req.drive_stat.write_prot)
writelocked = TRUE;
} else {
/*
* NOTE: the bullshit below is because our DIT floppy pretends it can
* write
*/
if (lseek(floppyfd, 0, L_SET) < 0)
fprintf(stderr, "lseek errno %d\n", errno);
if (read(floppyfd, buf, 1024) != 1024)
fprintf(stderr, "read errno %d\n", errno);
if (lseek(floppyfd, 0, L_SET) < 0)
fprintf(stderr, "lseek errno %d\n", errno);
savec = buf[1023];
buf[1023] ^= 0xFF;
if (write(floppyfd, buf, 1024) != 1024)
writelocked = TRUE;
if (lseek(floppyfd, 0, L_SET) < 0)
fprintf(stderr, "lseek errno %d\n", errno);
if (read(floppyfd, buf, 1024) != 1024)
fprintf(stderr, "read errno %d\n", errno);
if (buf[1023] == savec)
writelocked = TRUE;
else {
if (lseek(floppyfd, 0, L_SET) < 0)
fprintf(stderr, "lseek errno %d\n", errno);
buf[1023] = savec;
if (write(floppyfd, buf, 1024) != 1024)
writelocked = TRUE;
}
}
if (writelocked) {
vcbp = findvcb(pb.ioParam.ioVRefNum, (StringPtr) 0, &dir);
if (vcbp)
vcbp->vcbAtrb |= VHARDLOCKBIT;
}
}
ROMlib_slimyclosehack = OurClose;
}
BOOLEAN xGetNextEvent( INTEGER em, EventRecord *evtp )
{
BOOLEAN retval;
struct sockaddr sockname;
long addrlen;
char device[DEVNAMELEN];
long ns, nread;
extern long sock;
retval = FALSE;
if ((em & diskMask) && floppyfd == -1) {
addrlen = sizeof(sockname);
if ((ns = accept(sock, &sockname, (int *) &addrlen)) >= 0) {
fcntl(ns, F_SETFL, 0); /* turn off FNDELAY */
nread = read(ns, device, sizeof(device));
openfloppy(device);
evtp->what = diskEvt;
retval = TRUE;
} else
assert(errno == EWOULDBLOCK);
}
return retval ? TRUE : GetNextEvent(em, evtp);
}
BOOLEAN xWaitNextEvent( INTEGER em, EventRecord *evtp, LONGINT sleep,
RgnHandle mousergn )
{
BOOLEAN retval;
struct sockaddr sockname;
long addrlen;
char device[DEVNAMELEN];
long ns, nread;
extern long sock;
retval = FALSE;
if ((em & diskMask) && floppyfd == -1) {
addrlen = sizeof(sockname);
if ((ns = accept(sock, &sockname, (int *) &addrlen)) >= 0) {
fcntl(ns, F_SETFL, 0); /* turn off FNDELAY */
nread = read(ns, device, sizeof(device));
openfloppy(device);
evtp->what = diskEvt;
retval = TRUE;
} else
assert(errno == EWOULDBLOCK);
}
return retval ? TRUE : WaitNextEvent(em, evtp, sleep, mousergn);
}
#endif
PUBLIC void OurExit( void )
{
#if defined(UNIX)
OurClose();
#endif
ExitToShell();
}
PUBLIC OSErr TransPhysBlk(HVCB *vcbp, long physblock, short nphysblocks,
Ptr bufp, accesstype rw, long *actp)
{
#if !defined(UNIX)
ioParam pb;
#else
LONGINT firstbigblock, lastbigblock, offset, ntocopy;
INTEGER i;
#endif
OSErr err;
#if 1 && !defined(UNIX)
if (rw != reading && strncmp((char *) vcbp->vcbVN, "\pMyVol",
vcbp->vcbVN[0]+1) != 0) {
errormessage((StringPtr) "\pAck! not Myvol.", CAUTION);
printf("Dangerous chemicals, Timmy! (we should stick to MyVol)\n");
exit(1);
}
#endif
#if !defined(UNIX)
pb.ioVRefNum = vcbp->vcbDrvNum;
pb.ioRefNum = vcbp->vcbDRefNum;
pb.ioBuffer = bufp;
pb.ioReqCount = PHYSBSIZE * nphysblocks;
pb.ioPosMode = fsFromStart;
pb.ioPosOffset = physblock;
err = rw == reading ? PBRead ((ParmBlkPtr) &pb, FALSE) :
PBWrite((ParmBlkPtr) &pb, FALSE);
if (actp)
*actp = pb.ioActCount;
#else
firstbigblock = physblock / BIGBLOCK;
lastbigblock = (physblock + PHYSBSIZE * nphysblocks - 1) / BIGBLOCK;
err = noErr;
if (firstbigblock >= 0 || lastbigblock < NBIGBLOCKS) {
for (i = firstbigblock; i <= lastbigblock; ++i) {
if (!readmap[i]) {
offset = i * BIGBLOCK;
if (lseek(floppyfd, offset, L_SET) < 0 ||
read(floppyfd, buf+offset, BIGBLOCK) != BIGBLOCK) {
err = ioErr;
break;
}
readmap[i] = 1;
}
if (rw == writing)
writemap[i] = 1;
}
} else
err = paramErr;
ntocopy = nphysblocks * PHYSBSIZE;
if (rw == reading)
memcpy(bufp, buf+physblock, ntocopy);
else
memcpy(buf+physblock, bufp, ntocopy);
if (actp)
*actp = ntocopy;
#endif
#if 1
if (err != noErr)
DebugStr((StringPtr)"\perr in transphysblock");
#endif
return err;
}
PUBLIC char *indexn(char *str, char tofind, INTEGER length)
{
while (--length >= 0)
if (*str++ == tofind)
return str - 1;
return 0;
}
#if !defined(str255assign)
PUBLIC void str255assign(StringPtr dstp, StringPtr srcp)
{
memcpy(dstp, srcp, (size_t) srcp[0]+1);
}
#endif /* !defined(str255assign) */
/*
* indexqueue returns a pointer to the n'th entry on a queue.
* indexqueue is one based; not zero based.
*/
PUBLIC void *indexqueue(QHdr *qp, short index)
{
QElemPtr p;
#if !defined (UNIX)
for (p = qp->qHead; --index > 0; p = p->qLink)
;
#else
for (p = qp->qHead; --index > 0; p = p->vcbQElem.qLink)
;
#endif
return p;
}
PUBLIC OSErr writefcbp(filecontrolblock *fcbp)
{
Byte flags;
OSErr retval;
flags = fcbp->fcbMdRByt;
if (!(flags & WRITEBIT))
retval = wrPermErr;
else if (flags & FLOCKEDBIT)
retval = fLckdErr;
else
retval = noErr;
return retval;
}
PUBLIC OSErr writevcbp(HVCB *vcbp)
{
INTEGER vflags;
OSErr retval;
vflags = vcbp->vcbAtrb;
if (vflags & VSOFTLOCKBIT)
retval = vLckdErr;
else if (vflags & VHARDLOCKBIT)
retval = wPrErr;
else
retval = noErr;
return retval;
}
#endif
|
AngularJS-Angular2-Angular4/angular2-project
|
wsdl/AddressService/com/qwest/xmlschema/TelephoneConnectionT.java
|
package com.qwest.xmlschema;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for TelephoneConnectionT complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TelephoneConnectionT">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ADSR" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="AddressConnection" type="{http://www.qwest.com/XMLSchema}AddressConnectionT" minOccurs="0"/>
* <element name="CTID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="ClassOfService" type="{http://www.qwest.com/XMLSchema}TelephoneConnectionTClassOfService" minOccurs="0"/>
* <element name="ConnectionStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="CustomerName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="ExtAdministeredInd" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="NonPublishedInd" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="PlugType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TelephoneNumber" type="{http://www.qwest.com/XMLSchema}BaseTNType" minOccurs="0"/>
* <element name="USOC" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TelephoneConnectionT", propOrder = {
"adsr",
"addressConnection",
"ctid",
"classOfService",
"connectionStatus",
"customerName",
"extAdministeredInd",
"nonPublishedInd",
"plugType",
"telephoneNumber",
"usoc"
})
public class TelephoneConnectionT {
@XmlElementRef(name = "ADSR", namespace = "http://www.qwest.com/XMLSchema", type = JAXBElement.class, required = false)
protected JAXBElement<String> adsr;
@XmlElementRef(name = "AddressConnection", namespace = "http://www.qwest.com/XMLSchema", type = JAXBElement.class, required = false)
protected JAXBElement<AddressConnectionT> addressConnection;
@XmlElementRef(name = "CTID", namespace = "http://www.qwest.com/XMLSchema", type = JAXBElement.class, required = false)
protected JAXBElement<String> ctid;
@XmlElement(name = "ClassOfService")
@XmlSchemaType(name = "string")
protected TelephoneConnectionTClassOfService classOfService;
@XmlElementRef(name = "ConnectionStatus", namespace = "http://www.qwest.com/XMLSchema", type = JAXBElement.class, required = false)
protected JAXBElement<String> connectionStatus;
@XmlElementRef(name = "CustomerName", namespace = "http://www.qwest.com/XMLSchema", type = JAXBElement.class, required = false)
protected JAXBElement<String> customerName;
@XmlElement(name = "ExtAdministeredInd")
protected Boolean extAdministeredInd;
@XmlElement(name = "NonPublishedInd")
protected Boolean nonPublishedInd;
@XmlElementRef(name = "PlugType", namespace = "http://www.qwest.com/XMLSchema", type = JAXBElement.class, required = false)
protected JAXBElement<String> plugType;
@XmlElementRef(name = "TelephoneNumber", namespace = "http://www.qwest.com/XMLSchema", type = JAXBElement.class, required = false)
protected JAXBElement<BaseTNType> telephoneNumber;
@XmlElementRef(name = "USOC", namespace = "http://www.qwest.com/XMLSchema", type = JAXBElement.class, required = false)
protected JAXBElement<String> usoc;
/**
* Gets the value of the adsr property.
*
* @return
* possible object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getADSR() {
return adsr;
}
/**
* Sets the value of the adsr property.
*
* @param value
* allowed object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setADSR(JAXBElement<String> value) {
this.adsr = value;
}
/**
* Gets the value of the addressConnection property.
*
* @return
* possible object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link AddressConnectionT }{@code >}
*
*/
public JAXBElement<AddressConnectionT> getAddressConnection() {
return addressConnection;
}
/**
* Sets the value of the addressConnection property.
*
* @param value
* allowed object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link AddressConnectionT }{@code >}
*
*/
public void setAddressConnection(JAXBElement<AddressConnectionT> value) {
this.addressConnection = value;
}
/**
* Gets the value of the ctid property.
*
* @return
* possible object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getCTID() {
return ctid;
}
/**
* Sets the value of the ctid property.
*
* @param value
* allowed object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setCTID(JAXBElement<String> value) {
this.ctid = value;
}
/**
* Gets the value of the classOfService property.
*
* @return
* possible object is
* {@link TelephoneConnectionTClassOfService }
*
*/
public TelephoneConnectionTClassOfService getClassOfService() {
return classOfService;
}
/**
* Sets the value of the classOfService property.
*
* @param value
* allowed object is
* {@link TelephoneConnectionTClassOfService }
*
*/
public void setClassOfService(TelephoneConnectionTClassOfService value) {
this.classOfService = value;
}
/**
* Gets the value of the connectionStatus property.
*
* @return
* possible object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getConnectionStatus() {
return connectionStatus;
}
/**
* Sets the value of the connectionStatus property.
*
* @param value
* allowed object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setConnectionStatus(JAXBElement<String> value) {
this.connectionStatus = value;
}
/**
* Gets the value of the customerName property.
*
* @return
* possible object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getCustomerName() {
return customerName;
}
/**
* Sets the value of the customerName property.
*
* @param value
* allowed object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setCustomerName(JAXBElement<String> value) {
this.customerName = value;
}
/**
* Gets the value of the extAdministeredInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isExtAdministeredInd() {
return extAdministeredInd;
}
/**
* Sets the value of the extAdministeredInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setExtAdministeredInd(Boolean value) {
this.extAdministeredInd = value;
}
/**
* Gets the value of the nonPublishedInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isNonPublishedInd() {
return nonPublishedInd;
}
/**
* Sets the value of the nonPublishedInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setNonPublishedInd(Boolean value) {
this.nonPublishedInd = value;
}
/**
* Gets the value of the plugType property.
*
* @return
* possible object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getPlugType() {
return plugType;
}
/**
* Sets the value of the plugType property.
*
* @param value
* allowed object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setPlugType(JAXBElement<String> value) {
this.plugType = value;
}
/**
* Gets the value of the telephoneNumber property.
*
* @return
* possible object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link BaseTNType }{@code >}
*
*/
public JAXBElement<BaseTNType> getTelephoneNumber() {
return telephoneNumber;
}
/**
* Sets the value of the telephoneNumber property.
*
* @param value
* allowed object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link BaseTNType }{@code >}
*
*/
public void setTelephoneNumber(JAXBElement<BaseTNType> value) {
this.telephoneNumber = value;
}
/**
* Gets the value of the usoc property.
*
* @return
* possible object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getUSOC() {
return usoc;
}
/**
* Sets the value of the usoc property.
*
* @param value
* allowed object is
* {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setUSOC(JAXBElement<String> value) {
this.usoc = value;
}
}
|
teamdigitale/pagopa-ios-example
|
PagoPaSDK.framework/Headers/WALPpaWalletType.h
|
<reponame>teamdigitale/pagopa-ios-example<filename>PagoPaSDK.framework/Headers/WALPpaWalletType.h<gh_stars>1-10
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from ppa_wallet_type.djinni
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, WALPpaWalletType)
{
WALPpaWalletTypeCreditCard,
WALPpaWalletTypeBankAccount,
WALPpaWalletTypeExternalPs,
WALPpaWalletTypeUnknown,
};
|
lperson/dcaf_case_management
|
db/migrate/20210403213315_create_users.rb
|
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :name, null: false
t.string :line
t.integer :role, null: false, default: 0
t.boolean :disabled_by_fund, default: false
# Scratch field - temporary BSON ID from Mongo so we can link things back
t.string :mongo_id
t.timestamps
end
end
end
|
plojyon/resolwe-bio
|
resolwe_bio/processes/alignment/star_index.py
|
"""Generate STAR genome index."""
import shutil
from pathlib import Path
from plumbum import TEE
from resolwe.process import (
Cmd,
DataField,
DirField,
FileField,
GroupField,
IntegerField,
Process,
StringField,
)
class StarIndex(Process):
"""Generate STAR genome index.
Generate genome indices files from the supplied reference genome
sequence and GTF files.
"""
slug = "alignment-star-index"
name = "STAR genome index"
process_type = "data:index:star"
version = "3.0.0"
category = "Genome index"
requirements = {
"expression-engine": "jinja",
"executor": {
"docker": {"image": "public.ecr.aws/s4q6j6e8/resolwebio/rnaseq:5.9.0"}
},
"resources": {
"cores": 1,
"memory": 32768,
},
}
data_name = "{{ ref_seq.fasta.file|basename|default('?') }}"
class Input:
"""Input fields to process StarIndex."""
ref_seq = DataField(
"seq:nucleotide", label="Reference sequence (nucleotide FASTA)"
)
annotation = DataField(
"annotation",
label="Annotation file (GTF/GFF3)",
required=False,
description="Insert known annotations into genome indices at the indexing stage.",
)
source = StringField(
label="Gene ID Database Source",
disabled="annotation",
required=False,
allow_custom_choice=True,
choices=[
("ENSEMBL", "ENSEMBL"),
("NCBI", "NCBI"),
("UCSC", "UCSC"),
],
)
class AnnotationOptions:
"""Annotation file options."""
feature_exon = StringField(
label="Feature type [--sjdbGTFfeatureExon]",
default="exon",
description="Feature type in GTF file to be used as exons for building "
"transcripts.",
)
sjdb_overhang = IntegerField(
label="Junction length [--sjdbOverhang]",
default=100,
description="This parameter specifies the length of the genomic sequence around "
"the annotated junction to be used in constructing the splice junction database. "
"Ideally, this length should be equal to the ReadLength-1, where ReadLength is "
"the length of the reads. For instance, for Illumina 2x100b paired-end reads, the "
"ideal value is 100-1=99. In case of reads of varying length, the ideal value is "
"max(ReadLength)-1. In most cases, the default value of 100 will work as well as "
"the ideal value.",
)
class AdvancedOptions:
"""Advanced options."""
genome_sa_string_len = IntegerField(
label="Small genome adjustment [--genomeSAindexNbases]",
required=False,
description="For small genomes, the parameter --genomeSAindexNbases needs to be "
"scaled down, with a typical value of min(14, log2(GenomeLength)/2 - 1). For "
"example, for 1 megaBase genome, this is equal to 9, for 100 kiloBase genome, "
"this is equal to 7.",
)
genome_chr_bin_size = IntegerField(
label="Bin size for genome storage [--genomeChrBinNbits]",
required=False,
description="If you are using a genome with a large (>5,000) number of references "
"(chrosomes/scaffolds), you may need to reduce the --genomeChrBinNbits to reduce "
"RAM consumption. The following scaling is recommended: --genomeChrBinNbits = "
"min(18, log2(GenomeLength / NumberOfReferences)). For example, for 3 gigaBase "
"genome with 100,000 chromosomes/scaffolds, this is equal to 15.",
)
genome_sa_sparsity = IntegerField(
label="Suffix array sparsity [--genomeSAsparseD]",
required=False,
description="Suffix array sparsity, i.e. distance between indices: use bigger "
"numbers to decrease needed RAM at the cost of mapping speed reduction (integer > "
"0, default = 1).",
)
annotation_options = GroupField(
AnnotationOptions, label="Annotation file options", hidden="!annotation"
)
advanced = GroupField(AdvancedOptions, label="Advanced options")
class Output:
"""Output fields to process StarIndex."""
index = DirField(label="Indexed genome")
fastagz = FileField(label="FASTA file (compressed)")
fasta = FileField(label="FASTA file")
fai = FileField(label="FASTA file index")
source = StringField(label="Gene ID source")
species = StringField(label="Species")
build = StringField(label="Build")
def run(self, inputs, outputs):
"""Run analysis."""
if not inputs.source and not inputs.annotation:
self.error(
"Gene ID database Source information must be provided when annotation GTF is not "
"selected."
)
fasta = Path(inputs.ref_seq.output.fasta.path).name
shutil.copy(inputs.ref_seq.output.fasta.path, fasta)
outputs.fasta = fasta
fastagz = Path(inputs.ref_seq.output.fastagz.path).name
shutil.copy(inputs.ref_seq.output.fastagz.path, fastagz)
outputs.fastagz = fastagz
fai = Path(inputs.ref_seq.output.fai.path).name
shutil.copy(inputs.ref_seq.output.fai.path, fai)
outputs.fai = fai
self.progress(0.1)
index_dir = Path("star_index")
index_dir.mkdir()
index_params = [
"--runThreadN",
self.requirements.resources.cores,
"--runMode",
"genomeGenerate",
"--genomeDir",
str(index_dir),
"--genomeFastaFiles",
str(Path(inputs.ref_seq.output.fasta.path).name),
]
if inputs.annotation:
index_params.extend(
[
"--sjdbGTFfile",
inputs.annotation.output.annot.path,
"--sjdbOverhang",
inputs.annotation_options.sjdb_overhang,
"--sjdbGTFfeatureExon",
inputs.annotation_options.feature_exon,
]
)
if inputs.annotation.type.startswith("data:annotation:gff3:"):
index_params.extend(["--sjdbGTFtagExonParentTranscript Parent"])
if inputs.advanced.genome_sa_string_len:
index_params.extend(
["--genomeSAindexNbases", inputs.advanced.genome_sa_string_len]
)
if inputs.advanced.genome_chr_bin_size:
index_params.extend(
["--genomeChrBinNbits", inputs.advanced.genome_chr_bin_size]
)
if inputs.advanced.genome_sa_sparsity:
index_params.extend(
["--genomeSAsparseD", inputs.advanced.genome_sa_sparsity]
)
return_code, _, _ = Cmd["STAR"][index_params] & TEE(retcode=None)
if return_code:
self.error("Genome index build failed.")
self.progress(0.8)
outputs.index = str(index_dir)
if inputs.annotation:
outputs.source = inputs.annotation.output.source
outputs.species = inputs.annotation.output.species
outputs.build = inputs.annotation.output.build
else:
outputs.source = inputs.source
outputs.species = inputs.ref_seq.output.species
outputs.build = inputs.ref_seq.output.build
|
filmote/Karateka_Pokitto
|
src/images/fighters/Fullbody10.h
|
// Automatically generated file, do not edit.
#pragma once
const uint8_t Fullbody10[] = {
24, 40,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0x44,0x44,0x4e,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xe4,0x44,0x44,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xe4,0x44,0xff,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xe4,0x4f,0xf0,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xe4,0x4f,0xff,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xe4,0x4f,0xff,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x7f,0xfe,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0x77,0x7e,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x77,0x77,0x7e,0xee,
0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0x77,0x77,0x7f,0xfe,
0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0x77,0x77,0x7f,0xee,
0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x77,0x77,0x7e,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x77,0x77,0x77,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x77,0x77,0x77,0x7e,0xee,
0xee,0xee,0xee,0xee,0xee,0x00,0x00,0x77,0xee,0x77,0xff,0xee,
0xee,0xee,0xee,0xee,0xe7,0x77,0x00,0x00,0xee,0xee,0xff,0xfe,
0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0x0e,0xee,0xee,0xef,0xee,
0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0x7e,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0x7e,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0x77,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x77,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x77,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0x7e,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x7e,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x7e,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xe7,0x77,0x77,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x77,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0x77,0x77,0x7e,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0x77,0xff,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xef,0xff,0xfe,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xff,0xff,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee
};
|
sunnychanwork/deltaforce
|
ledgers/src/main/java/org/namstorm/deltaforce/ledgers/DeltaLedgerEntry.java
|
<reponame>sunnychanwork/deltaforce
package org.namstorm.deltaforce.ledgers;
/**
* Created by maxnamstorm on 16/8/2016.
* It's an entry, bound to a openEntry
*/
public interface DeltaLedgerEntry {
}
|
MManicaM/ogs
|
ProcessLib/SurfaceFlux/SurfaceFluxLocalAssembler.h
|
<gh_stars>0
/**
* \copyright
* Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#pragma once
#include "NumLib/Fem/ShapeMatrixPolicy.h"
#include "NumLib/DOF/DOFTableUtil.h"
#include "ParameterLib/Parameter.h"
#include "ProcessLib/Process.h"
#include "ProcessLib/Utils/InitShapeMatrices.h"
#include "MeshLib/Elements/MapBulkElementPoint.h"
#include "MeshLib/Elements/FaceRule.h"
#include "MeshLib/Elements/Elements.h"
namespace ProcessLib
{
class SurfaceFluxLocalAssemblerInterface
{
public:
virtual ~SurfaceFluxLocalAssemblerInterface() = default;
virtual void integrate(std::size_t const element_id,
GlobalVector const& x,
MeshLib::PropertyVector<double>& specific_flux,
double const t,
MeshLib::Mesh const& bulk_mesh,
std::function<Eigen::Vector3d(
std::size_t const, MathLib::Point3d const&,
double const, GlobalVector const&)>) = 0;
};
template <typename ShapeFunction, typename IntegrationMethod,
unsigned GlobalDim>
class SurfaceFluxLocalAssembler final
: public SurfaceFluxLocalAssemblerInterface
{
protected:
using ShapeMatricesType = ShapeMatrixPolicyType<ShapeFunction, GlobalDim>;
using NodalMatrixType = typename ShapeMatricesType::NodalMatrixType;
using NodalVectorType = typename ShapeMatricesType::NodalVectorType;
public:
/// Precomputes the shape matrices for a given surface element.
/// @param surface_element The surface element used for precomputing the
/// shape matrices used later on for the integration.
/// @param is_axially_symmetric corrects integration measure for cylinder
/// coordinates.
/// @param bulk_element_ids The id of the corresponding element in the bulk
/// mesh.
/// @param bulk_face_ids The id of the corresponding face in the bulk
/// element.
/// @param integration_order the order of the integration
SurfaceFluxLocalAssembler(
MeshLib::Element const& surface_element,
std::size_t /*const local_matrix_size*/,
bool const is_axially_symmetric,
unsigned const integration_order,
MeshLib::PropertyVector<std::size_t> const& bulk_element_ids,
MeshLib::PropertyVector<std::size_t> const& bulk_face_ids)
: _surface_element(surface_element),
_integration_method(integration_order),
_bulk_element_id(bulk_element_ids[surface_element.getID()]),
_bulk_face_id(bulk_face_ids[surface_element.getID()])
{
auto const fe = NumLib::createIsoparametricFiniteElement<
ShapeFunction, ShapeMatricesType>(_surface_element);
std::size_t const n_integration_points =
_integration_method.getNumberOfPoints();
std::vector<
typename ShapeMatricesType::ShapeMatrices,
Eigen::aligned_allocator<typename ShapeMatricesType::ShapeMatrices>>
shape_matrices;
shape_matrices.reserve(n_integration_points);
_detJ_times_integralMeasure.reserve(n_integration_points);
for (std::size_t ip = 0; ip < n_integration_points; ++ip)
{
shape_matrices.emplace_back(ShapeFunction::DIM, GlobalDim,
ShapeFunction::NPOINTS);
fe.template computeShapeFunctions<NumLib::ShapeMatrixType::N_J>(
_integration_method.getWeightedPoint(ip).getCoords(),
shape_matrices[ip], GlobalDim, is_axially_symmetric);
_detJ_times_integralMeasure.push_back(
shape_matrices[ip].detJ * shape_matrices[ip].integralMeasure);
}
}
/// Integration for the element with the id \c element_id.
/// @param element_id id of the element
/// @param x The global vector containing the values for numerical
/// integration.
/// @param specific_flux PropertyVector the integration result will be
/// stored into, where specific_flux has the same number of entries like
/// mesh elements exists.
/// @param t The integration is performed at the time t.
/// @param bulk_mesh Stores a reference to the bulk mesh that is needed to
/// fetch the information for the integration over the surface mesh.
/// @param getFlux function that calculates the flux in the integration
/// points of the face elements of the bulk element that belongs to the
/// surface.
void integrate(std::size_t const element_id,
GlobalVector const& x,
MeshLib::PropertyVector<double>& specific_flux,
double const t,
MeshLib::Mesh const& bulk_mesh,
std::function<Eigen::Vector3d(
std::size_t const, MathLib::Point3d const&, double const,
GlobalVector const&)>
getFlux) override
{
auto surface_element_normal =
MeshLib::FaceRule::getSurfaceNormal(&_surface_element);
surface_element_normal.normalize();
// At the moment (2016-09-28) the surface normal is not oriented
// according to the right hand rule
// for correct results it is necessary to multiply the normal with -1
surface_element_normal *= -1;
double element_area = 0.0;
std::size_t const n_integration_points =
_integration_method.getNumberOfPoints();
// specific_flux[id_of_element] +=
// int_{\Gamma_e} \alpha \cdot flux \cdot normal \d \Gamma /
// element_area
for (std::size_t ip(0); ip < n_integration_points; ip++)
{
auto const& wp = _integration_method.getWeightedPoint(ip);
auto const bulk_element_point = MeshLib::getBulkElementPoint(
bulk_mesh, _bulk_element_id, _bulk_face_id, wp);
auto const bulk_flux =
getFlux(_bulk_element_id, bulk_element_point, t, x);
for (int component_id(0);
component_id < specific_flux.getNumberOfComponents();
++component_id)
{
// TODO find solution for 2d case
double const bulk_grad_times_normal(
Eigen::Map<Eigen::RowVectorXd const>(bulk_flux.data(),
bulk_flux.size())
.dot(Eigen::Map<Eigen::RowVectorXd const>(
surface_element_normal.getCoords(), 3)));
specific_flux.getComponent(element_id, component_id) +=
bulk_grad_times_normal * _detJ_times_integralMeasure[ip] *
wp.getWeight();
}
element_area += _detJ_times_integralMeasure[ip] * wp.getWeight();
}
for (int component_id(0);
component_id < specific_flux.getNumberOfComponents();
++component_id)
{
specific_flux.getComponent(element_id, component_id) /=
element_area;
}
}
private:
MeshLib::Element const& _surface_element;
std::vector<double> _detJ_times_integralMeasure;
IntegrationMethod const _integration_method;
std::size_t _bulk_element_id;
std::size_t _bulk_face_id;
};
} // namespace ProcessLib
|
Gear61/GO-Database
|
app/src/main/java/com/randomappsinc/pokemonlocations_pokemongo/Adapters/NavDrawerAdapter.java
|
package com.randomappsinc.pokemonlocations_pokemongo.Adapters;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.randomappsinc.pokemonlocations_pokemongo.R;
import butterknife.Bind;
import butterknife.BindColor;
import butterknife.ButterKnife;
/**
* Created by alexanderchiou on 9/25/16.
*/
public class NavDrawerAdapter extends BaseAdapter {
public static final int ME_INDEX = 0;
public static final int DIVIDER_INDEX = 3;
public static final int TOOLS_INDEX = 4;
private Context context;
private String[] itemNames;
private String[] itemIcons;
public NavDrawerAdapter(Context context) {
this.context = context;
this.itemNames = context.getResources().getStringArray(R.array.nav_drawer_options);
this.itemIcons = context.getResources().getStringArray(R.array.nav_drawer_icons);
}
@Override
public int getCount() {
return itemNames.length;
}
@Override
public String getItem(int position) {
return itemNames[position];
}
@Override
public long getItemId(int position) {
return position;
}
public class DrawerItemViewHolder {
@Bind(R.id.nav_item_parent) View parent;
@Bind(R.id.divider) View divider;
@Bind(R.id.header) TextView header;
@Bind(R.id.nav_item) View navItem;
@Bind(R.id.drawer_icon) TextView itemIcon;
@Bind(R.id.drawer_option) TextView itemName;
@BindColor(R.color.white) int white;
public DrawerItemViewHolder(View view) {
ButterKnife.bind(this, view);
}
public void loadItem(int position) {
if (position == DIVIDER_INDEX) {
header.setVisibility(View.GONE);
navItem.setVisibility(View.GONE);
divider.setVisibility(View.VISIBLE);
parent.setBackgroundColor(white);
} else if (position == ME_INDEX || position == TOOLS_INDEX) {
header.setText(getItem(position));
divider.setVisibility(View.GONE);
navItem.setVisibility(View.GONE);
header.setVisibility(View.VISIBLE);
parent.setBackgroundColor(white);
} else {
itemIcon.setText(itemIcons[position]);
itemName.setText(getItem(position));
divider.setVisibility(View.GONE);
header.setVisibility(View.GONE);
navItem.setVisibility(View.VISIBLE);
int[] attrs = new int[] { android.R.attr.selectableItemBackground };
TypedArray typedArray = context.obtainStyledAttributes(attrs);
Drawable drawableFromTheme = typedArray.getDrawable(0);
typedArray.recycle();
parent.setBackground(drawableFromTheme);
}
}
}
public View getView(int position, View view, ViewGroup parent) {
DrawerItemViewHolder holder;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.nav_drawer_cell, parent, false);
holder = new DrawerItemViewHolder(view);
view.setTag(holder);
} else {
holder = (DrawerItemViewHolder) view.getTag();
}
holder.loadItem(position);
return view;
}
}
|
drnic/pivotal-tracker-tmbundle
|
Support/vendor/rails/railties/lib/generators/rails/controller/controller_generator.rb
|
<reponame>drnic/pivotal-tracker-tmbundle<gh_stars>1-10
module Rails
module Generators
class ControllerGenerator < NamedBase
argument :actions, :type => :array, :default => [], :banner => "action action"
check_class_collision :suffix => "Controller"
def create_controller_files
template 'controller.rb', File.join('app/controllers', class_path, "#{file_name}_controller.rb")
end
hook_for :template_engine, :test_framework, :helper
end
end
end
|
agoodfriendalwayspayshisdebts/agoodfriendalwayspayshisdebts-webapp
|
src/js/participant/resource/participants_resource.js
|
<reponame>agoodfriendalwayspayshisdebts/agoodfriendalwayspayshisdebts-webapp
"use strict";
/* @ngInject */
function ParticipantsResource(restService) {
return {
add: add,
update: update
};
function add(eventId, participant) {
return restService.post("/api/events/" + eventId + "/participants", participant);
}
function update(eventId, participant) {
return restService.put("/api/events/" + eventId + "/participants/" + participant.id, participant);
}
}
module.exports = ParticipantsResource;
|
Merkll/Quick-Credit
|
server/test/helpers/auth.spec.js
|
/* eslint-disable no-unused-expressions */
import { expect } from 'chai';
import * as Auth from '../../src/helpers/auth';
describe('AuthHelper', () => {
context('TokenGeneration', () => {
it('should return auth token', () => {
const token = Auth.generateToken({ id: 2, name: 'john' });
expect(token).to.not.be.undefined;
});
});
context('TokenVerification', () => {
it('should return auth token', () => {
const token = Auth.generateToken({ id: 2, name: 'john' });
const { id } = Auth.verifyToken(token);
expect(id).to.be.eql(2);
});
});
context('Pssword hash', () => {
it('should return hased password', () => {
const hash = Auth.hashPassword('<PASSWORD>');
expect(hash).to.not.be.undefined;
});
});
context('hashCompare', () => {
it('should return true', () => {
const hash = Auth.hashPassword('<PASSWORD>');
const compare = Auth.validateHash('testPassword', hash);
expect(compare).to.be.true;
});
});
});
|
autocore-ai/scenario_simulator_v2
|
openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/global_action.hpp
|
<filename>openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/global_action.hpp
// Copyright 2015-2020 <NAME>, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSCENARIO_INTERPRETER__SYNTAX__GLOBAL_ACTION_HPP_
#define OPENSCENARIO_INTERPRETER__SYNTAX__GLOBAL_ACTION_HPP_
#include <openscenario_interpreter/syntax/entity_action.hpp>
#include <openscenario_interpreter/syntax/infrastructure_action.hpp>
#include <openscenario_interpreter/syntax/parameter_action.hpp>
#include <utility>
namespace openscenario_interpreter
{
inline namespace syntax
{
/* ---- GlobalAction -----------------------------------------------------------
*
* <xsd:complexType name="GlobalAction">
* <xsd:choice>
* <xsd:element name="EnvironmentAction" type="EnvironmentAction"/>
* <xsd:element name="EntityAction" type="EntityAction"/>
* <xsd:element name="ParameterAction" type="ParameterAction"/>
* <xsd:element name="InfrastructureAction" type="InfrastructureAction"/>
* <xsd:element name="TrafficAction" type="TrafficAction"/>
* </xsd:choice>
* </xsd:complexType>
*
* -------------------------------------------------------------------------- */
struct GlobalAction : public Element
{
template <typename Node, typename... Ts>
explicit GlobalAction(const Node & node, Ts &&... xs)
// clang-format off
: Element(
choice(node,
std::make_pair( "EnvironmentAction", [&](auto && node) { throw UNSUPPORTED_ELEMENT_SPECIFIED(node.name()); return unspecified; }),
std::make_pair( "EntityAction", [&](auto && node) { return make< EntityAction>(std::forward<decltype(node)>(node), std::forward<decltype(xs)>(xs)...); }),
std::make_pair( "ParameterAction", [&](auto && node) { return make< ParameterAction>(std::forward<decltype(node)>(node), std::forward<decltype(xs)>(xs)...); }),
std::make_pair("InfrastructureAction", [&](auto && node) { return make<InfrastructureAction>(std::forward<decltype(node)>(node), std::forward<decltype(xs)>(xs)...); }),
std::make_pair( "TrafficAction", [&](auto && node) { throw UNSUPPORTED_ELEMENT_SPECIFIED(node.name()); return unspecified; })))
// clang-format on
{
}
bool endsImmediately() const
{
#define BOILERPLATE(TYPE) \
if (is<TYPE>()) { \
return as<TYPE>().endsImmediately(); \
}
BOILERPLATE(EntityAction)
BOILERPLATE(ParameterAction)
BOILERPLATE(InfrastructureAction)
throw UNSUPPORTED_ELEMENT_SPECIFIED(type().name());
#undef BOILERPLATE
}
};
} // namespace syntax
} // namespace openscenario_interpreter
#endif // OPENSCENARIO_INTERPRETER__SYNTAX__GLOBAL_ACTION_HPP_
|
phanisai4u/PdfBox-Android
|
library/src/main/java/com/tom_roush/pdfbox/pdmodel/font/FontMapper.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tom_roush.pdfbox.pdmodel.font;
import com.tom_roush.fontbox.FontBoxFont;
import com.tom_roush.fontbox.ttf.TrueTypeFont;
/**
* Font mapper, locates non-embedded fonts. If you implement this then you're responsible for
* caching the fonts. SoftReference<FontBoxFont> is recommended.
*
* @author <NAME>
*/
public interface FontMapper
{
/**
* Finds a TrueType font with the given PostScript name, or a suitable substitute, or null.
*
* @param fontDescriptor FontDescriptor
*/
FontMapping<TrueTypeFont> getTrueTypeFont(String baseFont, PDFontDescriptor fontDescriptor);
/**
* Finds a font with the given PostScript name, or a suitable substitute, or null. This allows
* any font to be substituted with a PFB, TTF or OTF.
*
* @param fontDescriptor the FontDescriptor of the font to find
*/
FontMapping<FontBoxFont> getFontBoxFont(String baseFont, PDFontDescriptor fontDescriptor);
/**
* Finds a CFF CID-Keyed font with the given PostScript name, or a suitable substitute, or null.
* This method can also map CJK fonts via their CIDSystemInfo (ROS).
*
* @param fontDescriptor FontDescriptor
* @param cidSystemInfo the CID system info, e.g. "Adobe-Japan1", if any.
*/
CIDFontMapping getCIDFont(String baseFont, PDFontDescriptor fontDescriptor,
PDCIDSystemInfo cidSystemInfo);
}
|
Transkribus/TranskribusDU
|
TranskribusDU/tasks/case_BAR/DU_BAR_sgm.py
|
# -*- coding: utf-8 -*-
"""
DU task for BAR - see https://read02.uibk.ac.at/wiki/index.php/Document_Understanding_BAR
Copyright Xerox(C) 2017 <NAME>
Developed for the EU project READ. The READ project has received funding
from the European Union's Horizon 2020 research and innovation programme
under grant agreement No 674943.
"""
import sys, os
try: #to ease the use without proper Python installation
import TranskribusDU_version
except ImportError:
sys.path.append( os.path.dirname(os.path.dirname( os.path.abspath(sys.argv[0]) )) )
import TranskribusDU_version
from common.trace import traceln
from crf.Graph_MultiPageXml import Graph_MultiContinousPageXml
from crf.NodeType_PageXml import NodeType_PageXml_type_woText
from DU_CRF_Task import DU_CRF_Task
from crf.FeatureDefinition_PageXml_std_noText import FeatureDefinition_T_PageXml_StandardOnes_noText
from crf.FeatureDefinition_PageXml_std_noText import FeatureDefinition_PageXml_StandardOnes_noText
from DU_BAR import main
class DU_BAR_sgm(DU_CRF_Task):
"""
We will do a typed CRF model for a DU task
, with the below labels
"""
sLabeledXmlFilenamePattern = "*.du_mpxml"
# ===============================================================================================================
#DEFINING THE CLASS OF GRAPH WE USE
DU_GRAPH = Graph_MultiContinousPageXml
#lLabels2 = ['heigh', 'ho', 'other']
#lLabels2 = ['heigh', 'ho']
lLabels2 = ['B', 'I', 'E'] #we never see any S... , 'S']
# Some TextRegion have no segmentation label at all, and were labelled'other' by the converter
lIgnoredLabels2 = None
# """
# if you play with a toy collection, which does not have all expected classes, you can reduce those.
# """
#
# lActuallySeen = None
# if lActuallySeen:
# print "REDUCING THE CLASSES TO THOSE SEEN IN TRAINING"
# lIgnoredLabels = [lLabels[i] for i in range(len(lLabels)) if i not in lActuallySeen]
# lLabels = [lLabels[i] for i in lActuallySeen ]
# print len(lLabels) , lLabels
# print len(lIgnoredLabels) , lIgnoredLabels
# nbClass = len(lLabels) + 1 #because the ignored labels will become OTHER
nt2 = NodeType_PageXml_type_woText("sgm" #some short prefix because labels below are prefixed with it
, lLabels2
, lIgnoredLabels2
, False #no label means OTHER
, BBoxDeltaFun=lambda v: max(v * 0.066, min(5, v/3)) #we reduce overlap in this way
)
nt2.setLabelAttribute("DU_sgm")
nt2.setXpathExpr( (".//pc:TextRegion" #how to find the nodes
, "./pc:TextEquiv") #how to get their text
)
DU_GRAPH.addNodeType(nt2)
#=== CONFIGURATION ====================================================================
def __init__(self, sModelName, sModelDir, sComment=None, C=None, tol=None, njobs=None, max_iter=None, inference_cache=None):
DU_CRF_Task.__init__(self
, sModelName, sModelDir
, self.DU_GRAPH
, dLearnerConfig = {
'C' : .1 if C is None else C
, 'njobs' : 8 if njobs is None else njobs
, 'inference_cache' : 50 if inference_cache is None else inference_cache
#, 'tol' : .1
, 'tol' : .05 if tol is None else tol
, 'save_every' : 50 #save every 50 iterations,for warm start
, 'max_iter' : 1000 if max_iter is None else max_iter
}
, sComment=sComment
, cFeatureDefinition=FeatureDefinition_PageXml_StandardOnes_noText
# , cFeatureDefinition=FeatureDefinition_T_PageXml_StandardOnes_noText
# , dFeatureConfig = {
# #config for the extractor of nodes of each type
# "text": None,
# "sprtr": None,
# #config for the extractor of edges of each type
# "text_text": None,
# "text_sprtr": None,
# "sprtr_text": None,
# "sprtr_sprtr": None
# }
)
traceln("- classes: ", self.DU_GRAPH.getLabelNameList())
self.bsln_mdl = self.addBaseline_LogisticRegression() #use a LR model trained by GridSearch as baseline
#=== END OF CONFIGURATION =============================================================
def predict(self, lsColDir,sDocId):
"""
Return the list of produced files
"""
# self.sXmlFilenamePattern = "*.a_mpxml"
return DU_CRF_Task.predict(self, lsColDir,sDocId)
if __name__ == "__main__":
main(DU_BAR_sgm)
|
utilForever/Wings
|
Libraries/gtkmm/lib/x64/atkmm/include/atkmmconfig.h
|
/* atk/atkmmconfig.h. Generated from atkmmconfig.h.in by configure. */
/* atkmm library configuration header */
#ifndef ATKMMCONFIG_H_INCLUDED
#define ATKMMCONFIG_H_INCLUDED
//#define ATKMM_DISABLE_DEPRECATED 1
#include <glibmmconfig.h>
/* Major version number of atkmm. */
#define ATKMM_MAJOR_VERSION 2
/* Minor version number of atkmm. */
#define ATKMM_MINOR_VERSION 24
/* Micro version number of atkmm. */
#define ATKMM_MICRO_VERSION 2
/* Define when building atkmm as a static library. */
/* #undef ATKMM_STATIC_LIB */
/* Enable DLL-specific stuff only when not building a static library */
#if !defined(ATKMM_STATIC_LIB) defined(__MINGW32__) && !defined(__CYGWIN__)
# define ATKMM_DLL 1
#endif
/* Do not dllexport as it is handled by gendef on MSVC */
#if defined(ATKMM_DLL) && !defined(ATKMM_BUILD)
# define ATKMM_API __declspec(dllimport)
#else
# define ATKMM_API
#endif
#endif /* !ATKMMCONFIG_H_INCLUDED */
|
atagomes/MoGrid
|
src/martin/mogrid/p2pdl/protocol/P2PDPCoordinationConnection.java
|
package martin.mogrid.p2pdl.protocol;
/**
* @author luciana
*
* Created on 22/06/2005
*/
public abstract class P2PDPCoordinationConnection implements P2PDPSenderConnection,
P2PDPReceiverConnection {
}
|
npocmaka/Windows-Server-2003
|
admin/extens/acldiag/resource.h
|
<reponame>npocmaka/Windows-Server-2003
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by acldiag.rc
//
#define IDS_BAD_CL_SYNTAX 1
#define IDS_BAD_CL_SYNTAX_NO_CLOSE_QUOTE 2
#define IDS_SECURITY_DIAGNOSIS_FOR 3
#define IDS_DESCRIPTION 4
#define IDS_INVALID_OBJECT 5
#define IDS_OWNER 6
#define IDS_CONFIG_NO_INHERIT 7
#define IDS_ALLOW 8
#define IDS_DENY 9
#define IDS_PERMISSIONS_EFFECTIVE 10
#define IDS_CREATE_ALL_SUBOBJECTS 11
#define IDS_CREATE_CLASS_OBJECTS 12
#define IDS_DELETE_ALL_SUBOBJECTS 13
#define IDS_DELETE_CLASS_OBJECTS 14
#define IDS_READ_ALL_PROPERTIES 15
#define IDS_READ_PROPERTY_PROPERTY 16
#define IDS_WRITE_ALL_PROPERTIES 17
#define IDS_WRITE_PROPERTY_PROPERTY 18
#define IDS_LIST_CONTENTS 19
#define IDS_LIST_OBJECT 20
#define IDS_DELETE_TREE 21
#define IDS_ALL_CONTROL_ACCESSES 22
#define IDS_CONTROL_ACCESS_DISPLAY_NAME 23
#define IDS_DELETE_THIS_OBJECT 24
#define IDS_READ_PERMISSIONS 25
#define IDS_TAKE_CHANGE_OWNERSHIP 26
#define IDS_MODIFY_PERMISSIONS 27
#define IDS_MODIFY_MEMBERSHIP 28
#define IDS_INHERITED_PERMISSION 29
#define IDS_DELEGWIZ_READ_PROPERTY 30
#define IDS_DELEGWIZ_WRITE_PROPERTY 31
#define IDS_DELEGWIZ_CREATE_CLASS 32
#define IDS_DELEGWIZ_DELETE_CLASS 33
#define IDS_PERMISSIONS_INHERITED_BY_SUBOBJECTS 34
#define IDS_INHERIT_TO_ALL_SUBOBJECTS 35
#define IDS_INHERIT_TO_X_OBJECTS_ONLY 36
#define IDS_AUDITING_EFFECTIVE_ON_THIS_OBJECT 37
#define IDS_SCHEMA_DEFAULTS_DIAGNOSIS 38
#define IDS_SCHEMA_DEFAULTS 39
#define IDS_OBTAINED 40
#define IDS_ABSENT 41
#define IDS_PRESENT 42
#define IDS_PARTIAL 43
#define IDS_AT_CREATION 44
#define IDS_BY_INHERITANCE 45
#define IDS_SUCCESS 46
#define IDS_FAILURE 47
#define IDS_SUCCESS_AND_FAILURE 48
#define IDS_AUDITING_INHERITED_TO_SUBOBJECTS 49
#define IDS_COULD_NOT_VALIDATE_USER_CREDENTIALS 50
#define IDS_USER_MUST_BE_ADMINISTRATOR 51
#define IDS_UNKNOWN_PARENT 52
#define IDS_HELP_MAIN 53
#define IDS_ADS_BAD_PATHNAME 54
#define IDS_INVALID_OPTION 55
#define IDS_HELP_SCHEMA 56
#define IDS_HELP_CHKDELEG 57
#define IDS_HELP_GETEFFECTIVE 58
#define IDS_HELP_CDO 59
#define IDS_UNABLE_TO_READ_SECURITY_DESCRIPTOR 60
#define IDS_DELEGWIZ_FINISH_TEMPLATE 61
#define IDS_DELEGWIZ_FINISH_PRINCIPALS 62
#define IDS_DELEGWIZ_ERR_OBJ_PEC_PERM 63
#define IDS_DELEGWIZ_FULL_CONTROL 64
#define IDS_DELEGWIZ_FINISH_PERMISSIONS 65
#define IDS_DELEGWIZ_RW_PROPERTYSET 66
#define IDS_DELEGWIZ_ACTRL_FULL 67
#define IDS_DELEGWIZ_ACTRL_READ 68
#define IDS_DELEGWIZ_ACTRL_WRITE 69
#define IDS_DELEGWIZ_ACTRL_DS_CREATE_CHILD 70
#define IDS_DELEGWIZ_ACTRL_DS_DELETE_CHILD 71
#define IDS_DELEGATION_TEMPLATE_DIAGNOSIS 72
#define IDS_DELTEMPL_STATUS 73
#define IDS_OK 74
#define IDS_NOT_PRESENT 75
#define IDS_MISCONFIGURED 76
#define IDS_APPLIES_ON_THIS_OBJECT 77
#define IDS_INHERITED_FROM_PARENT 78
#define IDS_YES 79
#define IDS_NO 80
#define IDS_DELEGATION_TITLE 81
#define IDS_FIX_DELEGATION_QUERY 82
#define IDS_DELEGWIZ_ERR_SET_SEC_INFO 83
#define IDS_DELEGWIZ_ERR_GET_SEC_INFO 84
#define IDS_EFFECTIVE_RIGHTS_DIAGNOSIS 85
#define IDS_OWNER_CDO 86
#define IDS_PERMISSIONS_PROTECTED 87
#define IDS_PERMISSIONS_NOT_PROTECTED 88
#define IDS_AUDITING_PROTECTED 89
#define IDS_AUDITING_NOT_PROTECTED 90
#define IDS_ALLOW_CDO 91
#define IDS_DENY_CDO 92
#define IDS_THIS_OBJECT 93
#define IDS_ALL_SUBOBJECTS 94
#define IDS_SUCCESS_CDO 95
#define IDS_FAILURE_CDO 96
#define IDS_SUCCESS_AND_FAILURE_CDO 97
#define IDS_INHERITED_PERMISSION_CDO 98
#define IDS_CLASS_OBJECT 99
#define IDS_SCHEMA_DEFAULTS_CDO 100
#define IDS_OBTAINED_CDO 101
#define IDS_DELEGATION_TITLE_CDO 102
#define IDS_DELTEMPL_STATUS_CDO 103
#define IDS_APPLIES_ON_THIS_OBJECT_CDO 104
#define IDS_APPLIES 105
#define IDS_DOES_NOT_APPLY 106
#define IDS_INHERITED_FROM_PARENT_CDO 107
#define IDS_EXPLICIT 108
#define IDS_INHERITED 109
#define IDS_DELEGATION_NOT_FOUND_CDO 110
#define IDS_HELP_LOG 111
#define IDS_CAN 112
#define IDS_CAN_CDO 113
#define IDS_HELP_SKIP_DESCRIPTION 114
#define IDS_CREATE_ALL_SUBOBJECTS_ER 115
#define IDS_DELETE_ALL_SUBOBJECTS_ER 116
#define IDS_READ_ALL_PROPERTIES_ER 117
#define IDS_WRITE_ALL_PROPERTIES_ER 118
#define IDS_ALL_CONTROL_ACCESSES_ER 119
#define IDS_LIST_CONTENTS_ER 123
#define IDS_LIST_OBJECT_ER 124
#define IDS_READ_PERMISSIONS_ER 125
#define IDS_MODIFY_PERMISSIONS_ER 126
#define IDS_TAKE_CHANGE_OWNERSHIP_ER 127
#define IDS_MODIFY_MEMBERSHIP_ER 128
#define IDS_DELETE_THIS_OBJECT_ER 129
#define IDS_CLASS 130
#define IDS_PROPERTY 131
#define IDS_CONTROL 132
#define IDS_CANNOT_EF 133
#define IDS_CANNOT_CDO 134
#define IDS_NO_SECDESC_RETURNED 135
#define IDS_NO_SECDESC_RETURNED_WITH_CODE 136
#define IDS_EFFRIGHT_FROM_GROUP 137
#define IDS_EFFRIGHT_FROM_GROUP_CDO 138
#define IDS_CAN_CREATE_FOLLOWING_CHILD_OBJECTS 139
#define IDS_CAN_DELETE_FOLLOWING_CHILD_OBJECTS 140
#define IDS_CAN_READ_FOLLOWING_PROPERTIES 141
#define IDS_CAN_WRITE_FOLLOWING_PROPERTIES 142
#define IDS_CAN_DO_FOLLOWING_CONTROL_OPERATIONS 143
#define IDS_CREATE_CLASS_OBJECTS_ER 144
#define IDS_DELETE_CLASS_OBJECTS_ER 145
#define IDS_READ_PROPERTY_PROPERTY_ER 146
#define IDS_WRITE_PROPERTY_PROPERTY_ER 147
#define IDS_CAN_ER 148
#define IDS_FAILED_TO_LOAD_TEMPLATES 149
#define IDS_DELEGWIZ_ACTRL_DS_READ_PROP 150
#define IDS_DELEGWIZ_ACTRL_DS_WRITE_PROP 151
#define IDS_GENERATED_INHERITED_PERMISSION 152
#define IDS_GENERATED_INHERITED_PERMISSION_CDO 153
#define IDS_HELP_FIXDELEG 154
#define IDS_HELP_EXAMPLE 155
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
|
Crabo-7498/qmk-keyboard-firmware
|
lib/chibios-contrib/os/hal/ports/HT32/LLD/SPIv1/hal_spi_lld.h
|
/*
Copyright (C) 2020 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @file hal_spi_lld.h
* @brief HT32 SPI subsystem low level driver header.
*
* @addtogroup SPI
* @{
*/
#ifndef HAL_SPI_LLD_H
#define HAL_SPI_LLD_H
#if HAL_USE_SPI || defined(__DOXYGEN__)
/*===========================================================================*/
/* Driver constants. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver pre-compile time settings. */
/*===========================================================================*/
/**
* @name HT32 configuration options
* @{
*/
/**
* @brief SPI0 driver enable switch.
* @details If set to @p TRUE the support for SPI0 is included.
* @note The default is @p FALSE.
*/
#if !defined(HT32_SPI_USE_SPI0) || defined(__DOXYGEN__)
#define HT32_SPI_USE_SPI0 FALSE
#endif
#if !defined(HT32_SPI_USE_SPI1) || defined(__DOXYGEN__)
#define HT32_SPI_USE_SPI1 FALSE
#endif
/** @} */
/*===========================================================================*/
/* Derived constants and error checks. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver data structures and types. */
/*===========================================================================*/
/**
* @brief Low Level fields of the SPI driver structure.
*/
#define spi_lld_driver_fields \
SPI_TypeDef *SPI; \
uint8_t *rxptr; \
const uint8_t *txptr; \
size_t rxcnt; \
size_t txcnt; \
/**
* @brief Low Level fields of the SPI configuration structure.
*/
#define spi_lld_config_fields \
uint32_t cr0; \
uint32_t cr1; \
uint32_t cpr; \
uint32_t fcr;
/*===========================================================================*/
/* Driver macros. */
/*===========================================================================*/
/*===========================================================================*/
/* External declarations. */
/*===========================================================================*/
#if (HT32_SPI_USE_SPI0 == TRUE) && !defined(__DOXYGEN__)
extern SPIDriver SPID0;
#endif
#if (HT32_SPI_USE_SPI1 == TRUE) && !defined(__DOXYGEN__)
extern SPIDriver SPID1;
#endif
#ifdef __cplusplus
extern "C" {
#endif
void spi_lld_init(void);
void spi_lld_start(SPIDriver *spip);
void spi_lld_stop(SPIDriver *spip);
void spi_lld_select(SPIDriver *spip);
void spi_lld_unselect(SPIDriver *spip);
void spi_lld_ignore(SPIDriver *spip, size_t n);
void spi_lld_exchange(SPIDriver *spip, size_t n,
const void *txbuf, void *rxbuf);
void spi_lld_send(SPIDriver *spip, size_t n, const void *txbuf);
void spi_lld_receive(SPIDriver *spip, size_t n, void *rxbuf);
uint16_t spi_lld_polled_exchange(SPIDriver *spip, uint16_t frame);
#ifdef __cplusplus
}
#endif
#endif /* HAL_USE_SPI == TRUE */
#endif /* HAL_SPI_LLD_H */
/** @} */
|
smagill/opensphere-desktop
|
open-sphere-base/mantle/src/main/java/io/opensphere/mantle/data/cache/impl/DiskCacheReferenceFactory.java
|
<reponame>smagill/opensphere-desktop
package io.opensphere.mantle.data.cache.impl;
/**
* A factory for creating DiskCacheReference objects based on the size of the
* reference so that the DiskCacheReference objects are the minimum necessary
* size to store the cache reference.
*/
@SuppressWarnings("PMD.AvoidUsingShortType")
public final class DiskCacheReferenceFactory
{
/**
* Creates a new DiskCacheReference object.
*
* @param insertNum the insert num
* @param pos the pos
* @param size the size
* @param originIdSize the origin id size
* @param mgsOffset the mgs offset
* @return the disk cache reference
*/
public static CacheReference createDiskCacheReference(short insertNum, int pos, int size, byte originIdSize, int mgsOffset)
{
CacheReference ref = null;
if (size < Short.MAX_VALUE && pos < Integer.MAX_VALUE)
{
ref = new ShortDiskCacheReference(insertNum, pos, (short)size, originIdSize, (short)mgsOffset);
}
else
{
ref = new IntDiskCacheReference(insertNum, pos, size, originIdSize, mgsOffset);
}
return ref;
}
/**
* Instantiates a new disk cache reference factory.
*/
private DiskCacheReferenceFactory()
{
// Don't allow instantiation.
}
}
|
LightningOnOmnilayer/OmniWalletMobile-Server
|
wallet_service/src/main/java/com/lx/server/service/impl/FpConfigBaseParameterServiceImpl.java
|
<gh_stars>1-10
package com.lx.server.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lx.server.dao.MyBatisBaseDao;
import com.lx.server.service.impl.MybatisBaseServiceImpl;
import com.lx.server.dao.FpConfigBaseParameterDao;
import com.lx.server.service.FpConfigBaseParameterService;
/**
* 【平台基本配置参数】 服务类 实现类
*
* @author AutoCode <EMAIL>
* @date 2019-06-14 10:53:53
*
*/
@Service(value = "fpConfigBaseParameterService")
public class FpConfigBaseParameterServiceImpl extends MybatisBaseServiceImpl implements FpConfigBaseParameterService {
@Autowired
private FpConfigBaseParameterDao fpConfigBaseParameterDao;
@Override
public MyBatisBaseDao getDao() {
return fpConfigBaseParameterDao;
}
}
|
huanqing/jstorm
|
jstorm-client/src/main/java/backtype/storm/spout/Scheme.java
|
package backtype.storm.spout;
import backtype.storm.tuple.Fields;
import java.io.Serializable;
import java.util.List;
public interface Scheme extends Serializable {
public List<Object> deserialize(byte[] ser);
public Fields getOutputFields();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.